WyattMiller commited on
Commit
43bf7d9
1 Parent(s): 91a3664

Upload 2 files

Browse files
Files changed (2) hide show
  1. app (1).py +141 -0
  2. requirements (2) (1).txt +10 -0
app (1).py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import gradio as gr
3
+ import shap
4
+ import numpy as np
5
+ import scipy as sp
6
+ import torch
7
+ import transformers
8
+ from transformers import pipeline
9
+ from transformers import RobertaTokenizer, RobertaModel
10
+ from transformers import AutoModelForSequenceClassification
11
+ from transformers import TFAutoModelForSequenceClassification
12
+ from transformers import AutoTokenizer, AutoModelForTokenClassification
13
+
14
+ import matplotlib.pyplot as plt
15
+ import sys
16
+ import csv
17
+
18
+ csv.field_size_limit(sys.maxsize)
19
+
20
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
21
+
22
+ tokenizer = AutoTokenizer.from_pretrained("WyattMiller/Mod4Team5")
23
+ model = AutoModelForSequenceClassification.from_pretrained("WyattMiller/Mod4Team5").to(device)
24
+
25
+ # build a pipeline object to do predictions
26
+ pred = transformers.pipeline("text-classification", model=model,
27
+ tokenizer=tokenizer, return_all_scores=True)
28
+
29
+ explainer = shap.Explainer(pred)
30
+
31
+ ##
32
+ # classifier = transformers.pipeline("text-classification", model = "cross-encoder/qnli-electra-base")
33
+
34
+ # def med_score(x):
35
+ # label = x['label']
36
+ # score_1 = x['score']
37
+ # return round(score_1,3)
38
+
39
+ # def sym_score(x):
40
+ # label2sym= x['label']
41
+ # score_1sym = x['score']
42
+ # return round(score_1sym,3)
43
+
44
+ ner_tokenizer = AutoTokenizer.from_pretrained("d4data/biomedical-ner-all")
45
+ ner_model = AutoModelForTokenClassification.from_pretrained("d4data/biomedical-ner-all")
46
+
47
+ ner_pipe = pipeline("ner", model=ner_model, tokenizer=ner_tokenizer, aggregation_strategy="simple") # pass device=0 if using gpu
48
+ #
49
+
50
+ def adr_predict(x):
51
+ encoded_input = tokenizer(x, return_tensors='pt')
52
+ output = model(**encoded_input)
53
+ scores = output[0][0].detach()
54
+ scores = torch.nn.functional.softmax(scores)
55
+
56
+ shap_values = explainer([str(x).lower()])
57
+ # # Find the index of the class you want as the default reference (e.g., 'label_1')
58
+ # label_1_index = np.where(np.array(explainer.output_names) == 'label_1')[0][0]
59
+
60
+ # # Plot the SHAP values for a specific instance in your dataset (e.g., instance 0)
61
+ # shap.plots.text(shap_values[label_1_index][0])
62
+
63
+ local_plot = shap.plots.text(shap_values[0], display=False)
64
+
65
+ # med = med_score(classifier(x+str(", There is a medication."))[0])
66
+ # sym = sym_score(classifier(x+str(", There is a symptom."))[0])
67
+
68
+ res = ner_pipe(x)
69
+
70
+ entity_colors = {
71
+ 'Severity': 'red',
72
+ 'Sign_symptom': 'green',
73
+ 'Medication': 'lightblue',
74
+ 'Age': 'yellow',
75
+ 'Sex':'yellow',
76
+ 'Diagnostic_procedure':'gray',
77
+ 'Biological_structure':'silver'}
78
+
79
+ htext = ""
80
+ prev_end = 0
81
+
82
+ for entity in res:
83
+ start = entity['start']
84
+ end = entity['end']
85
+ word = entity['word'].replace("##", "")
86
+ color = entity_colors[entity['entity_group']]
87
+
88
+ htext += f"{x[prev_end:start]}<mark style='background-color:{color};'>{word}</mark>"
89
+ prev_end = end
90
+
91
+ htext += x[prev_end:]
92
+
93
+ return {"Severe Reaction": float(scores.numpy()[1]), "Non-severe Reaction": float(scores.numpy()[0])}, local_plot,htext
94
+ # ,{"Contains Medication": float(med), "No Medications": float(1-med)} , {"Contains Symptoms": float(sym), "No Symptoms": float(1-sym)}
95
+
96
+
97
+ def main(prob1):
98
+ text = str(prob1).lower()
99
+ obj = adr_predict(text)
100
+ return obj[0],obj[1],obj[2]
101
+
102
+ title = "Welcome to **ADR Detector** 🪐"
103
+ description1 = """This app takes text (up to a few sentences) and predicts to what extent the text describes severe (or non-severe) adverse reaction to medicaitons. Please do NOT use for medical diagnosis."""
104
+
105
+ with gr.Blocks(title=title) as demo:
106
+ gr.Markdown(f"## {title}")
107
+ gr.Markdown(description1)
108
+ gr.Markdown("""---""")
109
+ prob1 = gr.Textbox(label="Enter Your Text Here:",lines=2, placeholder="Type it here ...")
110
+ submit_btn = gr.Button("Analyze")
111
+
112
+ with gr.Row():
113
+
114
+ with gr.Column(visible=True) as output_col:
115
+ label = gr.Label(label = "Predicted Label")
116
+
117
+
118
+ with gr.Column(visible=True) as output_col:
119
+ local_plot = gr.HTML(label = 'Shap:')
120
+ htext = gr.HTML(label="NER")
121
+ # med = gr.Label(label = "Contains Medication")
122
+ # sym = gr.Label(label = "Contains Symptoms")
123
+
124
+ submit_btn.click(
125
+ main,
126
+ [prob1],
127
+ [label
128
+ ,local_plot, htext
129
+ # , med, sym
130
+ ], api_name="adr"
131
+ )
132
+
133
+ with gr.Row():
134
+ gr.Markdown("### Click on any of the examples below to see how it works:")
135
+ gr.Examples([["A 35 year-old male had severe headache after taking Aspirin. The lab results were normal."],
136
+ ["A 35 year-old female had minor pain in upper abdomen after taking Acetaminophen."]],
137
+ [prob1], [label,local_plot, htext
138
+ # , med, sym
139
+ ], main, cache_examples=True)
140
+
141
+ demo.launch()
requirements (2) (1).txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ transformers==4.35.0
2
+ gradio==3.44.1
3
+ Pillow
4
+ matplotlib
5
+ spacy_streamlit
6
+ streamlit
7
+ torch==1.12.1
8
+ shap==0.41.0
9
+ numpy==1.22.0
10
+ scipy