Spaces:
Sleeping
Sleeping
jschwaller
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -6,10 +6,7 @@ import scipy as sp
|
|
6 |
import torch
|
7 |
import transformers
|
8 |
from transformers import pipeline
|
9 |
-
from transformers import
|
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
|
@@ -22,30 +19,15 @@ device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
|
22 |
tokenizer = AutoTokenizer.from_pretrained("jschwaller/ADRv2024")
|
23 |
model = AutoModelForSequenceClassification.from_pretrained("jschwaller/ADRv2024")
|
24 |
|
25 |
-
#
|
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')
|
@@ -54,31 +36,21 @@ def adr_predict(x):
|
|
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 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
|
|
78 |
|
79 |
htext = ""
|
80 |
prev_end = 0
|
81 |
-
|
82 |
for entity in res:
|
83 |
start = entity['start']
|
84 |
end = entity['end']
|
@@ -87,55 +59,50 @@ def adr_predict(x):
|
|
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 = "
|
104 |
|
105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
-
|
115 |
-
|
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 |
-
|
122 |
-
# sym = gr.Label(label = "Contains Symptoms")
|
123 |
-
|
124 |
submit_btn.click(
|
125 |
main,
|
126 |
[prob1],
|
127 |
-
[label
|
128 |
-
|
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 |
-
|
139 |
-
|
140 |
-
|
141 |
-
demo.launch()
|
|
|
6 |
import torch
|
7 |
import transformers
|
8 |
from transformers import pipeline
|
9 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoModelForTokenClassification
|
|
|
|
|
|
|
10 |
|
11 |
import matplotlib.pyplot as plt
|
12 |
import sys
|
|
|
19 |
tokenizer = AutoTokenizer.from_pretrained("jschwaller/ADRv2024")
|
20 |
model = AutoModelForSequenceClassification.from_pretrained("jschwaller/ADRv2024")
|
21 |
|
22 |
+
# Build a pipeline object for predictions
|
23 |
pred = transformers.pipeline("text-classification", model=model,
|
24 |
tokenizer=tokenizer, return_all_scores=True)
|
25 |
|
26 |
explainer = shap.Explainer(pred)
|
27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
ner_tokenizer = AutoTokenizer.from_pretrained("d4data/biomedical-ner-all")
|
29 |
ner_model = AutoModelForTokenClassification.from_pretrained("d4data/biomedical-ner-all")
|
30 |
+
ner_pipe = pipeline("ner", model=ner_model, tokenizer=ner_tokenizer, aggregation_strategy="simple")
|
|
|
|
|
31 |
|
32 |
def adr_predict(x):
|
33 |
encoded_input = tokenizer(x, return_tensors='pt')
|
|
|
36 |
scores = torch.nn.functional.softmax(scores)
|
37 |
|
38 |
shap_values = explainer([str(x).lower()])
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
local_plot = shap.plots.text(shap_values[0], display=False)
|
40 |
|
|
|
|
|
|
|
41 |
res = ner_pipe(x)
|
|
|
42 |
entity_colors = {
|
43 |
+
'Severity': 'red',
|
44 |
+
'Sign_symptom': 'green',
|
45 |
+
'Medication': 'lightblue',
|
46 |
+
'Age': 'yellow',
|
47 |
+
'Sex': 'yellow',
|
48 |
+
'Diagnostic_procedure': 'gray',
|
49 |
+
'Biological_structure': 'silver'
|
50 |
+
}
|
51 |
|
52 |
htext = ""
|
53 |
prev_end = 0
|
|
|
54 |
for entity in res:
|
55 |
start = entity['start']
|
56 |
end = entity['end']
|
|
|
59 |
|
60 |
htext += f"{x[prev_end:start]}<mark style='background-color:{color};'>{word}</mark>"
|
61 |
prev_end = end
|
|
|
62 |
htext += x[prev_end:]
|
63 |
|
64 |
+
return {"Severe Reaction": float(scores.numpy()[1]), "Non-severe Reaction": float(scores.numpy()[0])}, local_plot, htext
|
|
|
|
|
65 |
|
66 |
def main(prob1):
|
67 |
text = str(prob1).lower()
|
68 |
obj = adr_predict(text)
|
69 |
+
return obj[0], obj[1], obj[2]
|
70 |
|
71 |
title = "Welcome to **ADR Detector** 🪐"
|
72 |
+
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 medications. Please do NOT use for medical diagnosis."
|
73 |
|
74 |
+
css = """
|
75 |
+
body { font-family: 'Roboto', sans-serif; background-color: #fafafa; color: #333; }
|
76 |
+
h1, h2, h3, h4, h5, h6 { color: #ff6347; }
|
77 |
+
.textbox { width: 100%; border-radius: 10px; border: 1px solid #ccc; }
|
78 |
+
.button { background-color: #ff6347; color: white; border: none; border-radius: 10px; padding: 10px 20px; cursor: pointer; }
|
79 |
+
"""
|
80 |
+
|
81 |
+
with gr.Blocks(css=css) as demo:
|
82 |
gr.Markdown(f"## {title}")
|
83 |
gr.Markdown(description1)
|
84 |
+
gr.Markdown("---")
|
85 |
+
prob1 = gr.Textbox(label="Enter Your Text Here:", lines=2, placeholder="Type it here...")
|
86 |
submit_btn = gr.Button("Analyze")
|
87 |
|
88 |
with gr.Row():
|
89 |
+
with gr.Column(visible=True):
|
90 |
+
label = gr.Label(label="Predicted Label")
|
91 |
+
with gr.Column(visible=True):
|
92 |
+
local_plot = gr.HTML(label='Shap:')
|
|
|
|
|
|
|
93 |
htext = gr.HTML(label="NER")
|
94 |
+
|
|
|
|
|
95 |
submit_btn.click(
|
96 |
main,
|
97 |
[prob1],
|
98 |
+
[label, local_plot, htext],
|
99 |
+
api_name="adr"
|
|
|
|
|
100 |
)
|
101 |
|
102 |
with gr.Row():
|
103 |
gr.Markdown("### Click on any of the examples below to see how it works:")
|
104 |
gr.Examples([["A 35 year-old male had severe headache after taking Aspirin. The lab results were normal."],
|
105 |
["A 35 year-old female had minor pain in upper abdomen after taking Acetaminophen."]],
|
106 |
+
[prob1], [label, local_plot, htext], main, cache_examples=True)
|
107 |
+
|
108 |
+
demo.launch()
|
|
|
|