AIEcosystem commited on
Commit
0cb886c
·
verified ·
1 Parent(s): 1e3a413

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +332 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,334 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ os.environ['HF_HOME'] = '/tmp'
3
+ import time
4
  import streamlit as st
5
+ import pandas as pd
6
+ import io
7
+ import plotly.express as px
8
+ import zipfile
9
+ import json
10
+ from cryptography.fernet import Fernet
11
+ from streamlit_extras.stylable_container import stylable_container
12
+ from typing import Optional
13
+ from gliner import GLiNER
14
+ from comet_ml import Experiment
15
+
16
+
17
+ st.markdown(
18
+ """
19
+ <style>
20
+ /* Overall app container */
21
+ .stApp {
22
+ background-color: #F5F5F5; /* A very light grey */
23
+ color: #333333; /* Dark grey for text for good contrast */
24
+ }
25
+ /* Sidebar background */
26
+ .css-1d36184, .css-1d36184, .st-ck {
27
+ background-color: #D3D3D3; /* Light grey for the sidebar */
28
+ }
29
+ /* Expander header and content background */
30
+ .streamlit-expanderHeader, .streamlit-expanderContent {
31
+ background-color: #F5F5F5;
32
+ }
33
+ /* Text Area background and text color */
34
+ .stTextArea textarea {
35
+ background-color: #E6E6E6; /* Slightly darker grey for input fields */
36
+ color: #000000;
37
+ border: 1px solid #B0B0B0; /* Add a subtle border */
38
+ }
39
+ /* Button styling */
40
+ .stButton > button {
41
+ background-color: #B0B0B0; /* A medium grey for the button */
42
+ color: #FFFFFF; /* White text for contrast */
43
+ border: none;
44
+ padding: 10px 20px;
45
+ border-radius: 5px;
46
+ }
47
+ .stButton > button:hover {
48
+ background-color: #8C8C8C; /* Darker grey on hover */
49
+ }
50
+ /* Alert boxes */
51
+ .stAlert {
52
+ color: #000000;
53
+ border-left: 5px solid #8C8C8C; /* A dark grey border for a clean look */
54
+ }
55
+ .stAlert.st-warning {
56
+ background-color: #C0C0C0; /* Silver grey for warning */
57
+ }
58
+ .stAlert.st-success {
59
+ background-color: #C0C0C0; /* Silver grey for success */
60
+ }
61
+ </style>
62
+ """,
63
+ unsafe_allow_html=True
64
+ )
65
+
66
+
67
+
68
+
69
+
70
+ # --- Page Configuration and UI Elements ---
71
+ st.set_page_config(layout="wide", page_title="Named Entity Recognition App")
72
+ st.subheader("MediExtract", divider="gray")
73
+ st.link_button("by nlpblogs", "https://nlpblogs.com", type="tertiary")
74
+
75
+ expander = st.expander("**Important notes**")
76
+ expander.write("""**Named Entities:** This MediExtract web app predicts sixteen (16) labels: "Disease", "Symptom", "Medication", "Dosage", "Frequency", "Procedure", "Diagnostic_test", "Lab_value", "Gene", "Protein", "Anatomy", "Cell_type", "Chemical", "Person", "Organization", "Date"
77
+
78
+ Results are presented in easy-to-read tables, visualized in an interactive tree map, pie chart and bar chart, and are available for download along with a Glossary of tags.
79
+
80
+ **How to Use:** Type or paste your text into the text area below, then press Ctrl + Enter. Click the 'Results' button to extract and tag entities in your text data.
81
+
82
+ **Usage Limits:** You can request results unlimited times for one (1) month.
83
+
84
+ **Supported Languages:** English
85
+
86
+ **Technical issues:** If your connection times out, please refresh the page or reopen the app's URL.
87
+
88
+ For any errors or inquiries, please contact us at info@nlpblogs.com""")
89
+
90
+ with st.sidebar:
91
+ st.write("Use the following code to embed the EntityFinance web app on your website. Feel free to adjust the width and height values to fit your page.")
92
+ code = '''
93
+ <iframe
94
+ src="https://aiecosystem-entityfinance.hf.space"
95
+ frameborder="0"
96
+ width="850"
97
+ height="450"
98
+ ></iframe>
99
+ '''
100
+ st.code(code, language="html")
101
+ st.text("")
102
+ st.text("")
103
+ st.divider()
104
+ st.subheader("🚀 Ready to build your own AI Web App?", divider="gray")
105
+ st.link_button("AI Web App Builder", " https://nlpblogs.com/custom-web-app-development/", type="primary")
106
+
107
+ # --- Comet ML Setup ---
108
+ COMET_API_KEY = os.environ.get("COMET_API_KEY")
109
+ COMET_WORKSPACE = os.environ.get("COMET_WORKSPACE")
110
+ COMET_PROJECT_NAME = os.environ.get("COMET_PROJECT_NAME")
111
+ comet_initialized = bool(COMET_API_KEY and COMET_WORKSPACE and COMET_PROJECT_NAME)
112
+
113
+ if not comet_initialized:
114
+ st.warning("Comet ML not initialized. Check environment variables.")
115
+
116
+ # --- Label Definitions ---
117
+ labels = [
118
+ "Disease",
119
+ "Symptom",
120
+ "Medication",
121
+ "Dosage",
122
+ "Frequency",
123
+ "Procedure",
124
+ "Diagnostic_test",
125
+ "Lab_value",
126
+ "Gene",
127
+ "Protein",
128
+ "Anatomy",
129
+ "Cell_type",
130
+ "Chemical",
131
+ "Person",
132
+ "Organization",
133
+ "Date"
134
+ ]
135
+
136
+ # Corrected mapping dictionary
137
+
138
+ # Create a mapping dictionary for labels to categories
139
+ category_mapping = {
140
+ "Clinical & Procedural": [
141
+ "Disease",
142
+ "Symptom",
143
+ "Procedure"
144
+ ],
145
+ "Medication & Treatment": [
146
+ "Medication",
147
+ "Dosage",
148
+ "Frequency"
149
+ ],
150
+ "Measurements & Results": [
151
+ "Diagnostic_test",
152
+ "Lab_value"
153
+ ],
154
+ "Biological & Anatomical": [
155
+ "Gene",
156
+ "Protein",
157
+ "Anatomy",
158
+ "Cell_type",
159
+ "Chemical"
160
+ ],
161
+ "People & Groups": [
162
+ "Person",
163
+ "Organization"
164
+ ],
165
+ "Temporal": [
166
+ "Date"
167
+ ]
168
+ }
169
+
170
+
171
+
172
+
173
+ # --- Model Loading ---
174
+ @st.cache_resource
175
+ def load_ner_model():
176
+ """Loads the GLiNER model and caches it."""
177
+ try:
178
+ return GLiNER.from_pretrained("Ihor/gliner-biomed-large-v1.0", nested_ner=True, num_gen_sequences=2, gen_constraints= labels)
179
+ except Exception as e:
180
+ st.error(f"Failed to load NER model. Please check your internet connection or model availability: {e}")
181
+ st.stop()
182
+ model = load_ner_model()
183
+
184
+ # Flatten the mapping to a single dictionary
185
+ reverse_category_mapping = {label: category for category, label_list in category_mapping.items() for label in label_list}
186
+
187
+ # --- Text Input and Clear Button ---
188
+ text = st.text_area("Type or paste your text below, and then press Ctrl + Enter", height=250, key='my_text_area')
189
+
190
+ def clear_text():
191
+ """Clears the text area."""
192
+ st.session_state['my_text_area'] = ""
193
+
194
+ st.button("Clear text", on_click=clear_text)
195
+
196
+
197
+ # --- Results Section ---
198
+ if st.button("Results"):
199
+ start_time = time.time()
200
+ if not text.strip():
201
+ st.warning("Please enter some text to extract entities.")
202
+ else:
203
+ with st.spinner("Extracting entities...", show_time=True):
204
+ entities = model.predict_entities(text, labels)
205
+ df = pd.DataFrame(entities)
206
+
207
+ if not df.empty:
208
+ df['category'] = df['label'].map(reverse_category_mapping)
209
+ if comet_initialized:
210
+ experiment = Experiment(
211
+ api_key=COMET_API_KEY,
212
+ workspace=COMET_WORKSPACE,
213
+ project_name=COMET_PROJECT_NAME,
214
+ )
215
+ experiment.log_parameter("input_text", text)
216
+ experiment.log_table("predicted_entities", df)
217
+
218
+ st.subheader("Grouped Entities by Category", divider = "gray")
219
+
220
+ # Create tabs for each category
221
+ category_names = sorted(list(category_mapping.keys()))
222
+ category_tabs = st.tabs(category_names)
223
+
224
+ for i, category_name in enumerate(category_names):
225
+ with category_tabs[i]:
226
+ df_category_filtered = df[df['category'] == category_name]
227
+ if not df_category_filtered.empty:
228
+ st.dataframe(df_category_filtered.drop(columns=['category']), use_container_width=True)
229
+ else:
230
+ st.info(f"No entities found for the '{category_name}' category.")
231
+
232
+
233
+
234
+ with st.expander("See Glossary of tags"):
235
+ st.write('''
236
+ - **text**: ['entity extracted from your text data']
237
+ - **score**: ['accuracy score; how accurately a tag has been assigned to a given entity']
238
+ - **label**: ['label (tag) assigned to a given extracted entity']
239
+ - **start**: ['index of the start of the corresponding entity']
240
+ - **end**: ['index of the end of the corresponding entity']
241
+ ''')
242
+ st.divider()
243
+
244
+ # Tree map
245
+ st.subheader("Tree map", divider = "gray")
246
+ fig_treemap = px.treemap(df, path=[px.Constant("all"), 'category', 'label', 'text'], values='score', color='category')
247
+ fig_treemap.update_layout(margin=dict(t=50, l=25, r=25, b=25), paper_bgcolor='#E8F5E9', plot_bgcolor='#E8F5E9')
248
+ st.plotly_chart(fig_treemap)
249
+
250
+ # Pie and Bar charts
251
+ grouped_counts = df['category'].value_counts().reset_index()
252
+ grouped_counts.columns = ['category', 'count']
253
+ col1, col2 = st.columns(2)
254
+
255
+ with col1:
256
+ st.subheader("Pie chart", divider = "gray")
257
+ fig_pie = px.pie(grouped_counts, values='count', names='category', hover_data=['count'], labels={'count': 'count'}, title='Percentage of predicted categories')
258
+ fig_pie.update_traces(textposition='inside', textinfo='percent+label')
259
+ fig_pie.update_layout(
260
+ paper_bgcolor='#E8F5E9',
261
+ plot_bgcolor='#E8F5E9'
262
+ )
263
+ st.plotly_chart(fig_pie)
264
+
265
+
266
+
267
 
268
+ with col2:
269
+ st.subheader("Bar chart", divider = "gray")
270
+ fig_bar = px.bar(grouped_counts, x="count", y="category", color="category", text_auto=True, title='Occurrences of predicted categories')
271
+ fig_bar.update_layout( # Changed from fig_pie to fig_bar
272
+ paper_bgcolor='#E8F5E9',
273
+ plot_bgcolor='#E8F5E9'
274
+ )
275
+ st.plotly_chart(fig_bar)
276
+
277
+ # Most Frequent Entities
278
+ st.subheader("Most Frequent Entities", divider="gray")
279
+ word_counts = df['text'].value_counts().reset_index()
280
+ word_counts.columns = ['Entity', 'Count']
281
+ repeating_entities = word_counts[word_counts['Count'] > 1]
282
+ if not repeating_entities.empty:
283
+ st.dataframe(repeating_entities, use_container_width=True)
284
+ fig_repeating_bar = px.bar(repeating_entities, x='Entity', y='Count', color='Entity')
285
+ fig_repeating_bar.update_layout(xaxis={'categoryorder': 'total descending'},
286
+ paper_bgcolor='#E8F5E9',
287
+ plot_bgcolor='#E8F5E9')
288
+ st.plotly_chart(fig_repeating_bar)
289
+ else:
290
+ st.warning("No entities were found that occur more than once.")
291
+
292
+ # Download Section
293
+ st.divider()
294
+
295
+ dfa = pd.DataFrame(
296
+ data={
297
+ 'Column Name': ['text', 'label', 'score', 'start', 'end'],
298
+ 'Description': [
299
+ 'entity extracted from your text data',
300
+ 'label (tag) assigned to a given extracted entity',
301
+ 'accuracy score; how accurately a tag has been assigned to a given entity',
302
+ 'index of the start of the corresponding entity',
303
+ 'index of the end of the corresponding entity',
304
+
305
+ ]
306
+ }
307
+ )
308
+ buf = io.BytesIO()
309
+ with zipfile.ZipFile(buf, "w") as myzip:
310
+ myzip.writestr("Summary of the results.csv", df.to_csv(index=False))
311
+ myzip.writestr("Glossary of tags.csv", dfa.to_csv(index=False))
312
+
313
+ with stylable_container(
314
+ key="download_button",
315
+ css_styles="""button { background-color: red; border: 1px solid black; padding: 5px; color: white; }""",
316
+ ):
317
+ st.download_button(
318
+ label="Download results and glossary (zip)",
319
+ data=buf.getvalue(),
320
+ file_name="nlpblogs_results.zip",
321
+ mime="application/zip",
322
+ )
323
+
324
+ if comet_initialized:
325
+ experiment.log_figure(figure=fig_treemap, figure_name="entity_treemap_categories")
326
+ experiment.end()
327
+ else: # If df is empty
328
+ st.warning("No entities were found in the provided text.")
329
+
330
+ end_time = time.time()
331
+ elapsed_time = end_time - start_time
332
+ st.text("")
333
+ st.text("")
334
+ st.info(f"Results processed in **{elapsed_time:.2f} seconds**.")