File size: 13,527 Bytes
0cb886c
 
 
2bdcf2d
0cb886c
 
 
 
 
 
 
 
 
 
d7497b2
0cb886c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7497b2
 
 
0cb886c
 
 
 
 
 
 
d7497b2
0cb886c
d7497b2
0cb886c
d7497b2
0cb886c
d7497b2
0cb886c
 
 
 
 
 
ae0756a
0cb886c
607f86d
 
 
 
 
0cb886c
607f86d
0cb886c
 
 
 
 
 
5363948
d7497b2
0cb886c
 
 
 
 
 
 
d7497b2
0cb886c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7497b2
 
0cb886c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7497b2
 
 
0cb886c
d7497b2
 
0cb886c
 
d7497b2
0cb886c
 
 
d7497b2
0cb886c
 
 
d7497b2
 
 
 
 
 
 
 
 
 
 
 
0cb886c
8a77caa
 
 
 
d7497b2
0cb886c
d7497b2
0cb886c
d7497b2
 
 
 
 
0cb886c
d7497b2
0cb886c
 
 
 
d7497b2
8a77caa
 
d7497b2
0cb886c
d7497b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cb886c
d7497b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
import os
os.environ['HF_HOME'] = '/tmp'
import time
import streamlit as st
import pandas as pd
import io
import plotly.express as px
import zipfile
import json
from cryptography.fernet import Fernet
from streamlit_extras.stylable_container import stylable_container
from typing import Optional
from gliner import GLiNER
from comet_ml import Experiment

st.markdown(
    """
    <style>
    /* Overall app container */
    .stApp {
        background-color: #F5F5F5; /* A very light grey */
        color: #333333; /* Dark grey for text for good contrast */
    }
    /* Sidebar background */
    .css-1d36184, .css-1d36184, .st-ck {
        background-color: #D3D3D3; /* Light grey for the sidebar */
    }
    /* Expander header and content background */
    .streamlit-expanderHeader, .streamlit-expanderContent {
        background-color: #F5F5F5;
    }
    /* Text Area background and text color */
    .stTextArea textarea {
        background-color: #E6E6E6; /* Slightly darker grey for input fields */
        color: #000000;
        border: 1px solid #B0B0B0; /* Add a subtle border */
    }
    /* Button styling */
    .stButton > button {
        background-color: #B0B0B0; /* A medium grey for the button */
        color: #FFFFFF; /* White text for contrast */
        border: none;
        padding: 10px 20px;
        border-radius: 5px;
    }
    .stButton > button:hover {
        background-color: #8C8C8C; /* Darker grey on hover */
    }
    /* Alert boxes */
    .stAlert {
        color: #000000;
        border-left: 5px solid #8C8C8C; /* A dark grey border for a clean look */
    }
    .stAlert.st-warning {
        background-color: #C0C0C0; /* Silver grey for warning */
    }
    .stAlert.st-success {
        background-color: #C0C0C0; /* Silver grey for success */
    }
    </style>
    """,
    unsafe_allow_html=True
)

# --- Page Configuration and UI Elements ---
st.set_page_config(layout="wide", page_title="Named Entity Recognition App")
st.subheader("MediExtract", divider="gray")
st.link_button("by nlpblogs", "https://nlpblogs.com", type="tertiary")
expander = st.expander("**Important notes**")
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"

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.

**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.

**Usage Limits:** You can request results unlimited times for one (1) month.

**Supported Languages:** English

**Technical issues:** If your connection times out, please refresh the page or reopen the app's URL. 

For any errors or inquiries, please contact us at info@nlpblogs.com""")

with st.sidebar:
    st.write("Use the following code to embed the MediExtract web app on your website. Feel free to adjust the width and height values to fit your page.")
    code = '''
    <iframe
	src="https://aiecosystem-mediextract.hf.space"
	frameborder="0"
	width="850"
	height="450"
    ></iframe>

    '''
    st.code(code, language="html")
    st.text("")
    st.text("")
    st.divider()
    st.subheader("πŸš€ Ready to build your own AI Web App?", divider="gray")
    st.link_button("AI Web App Builder", "https://nlpblogs.com/build-your-named-entity-recognition-app/", type="primary")

# --- Comet ML Setup ---
COMET_API_KEY = os.environ.get("COMET_API_KEY")
COMET_WORKSPACE = os.environ.get("COMET_WORKSPACE")
COMET_PROJECT_NAME = os.environ.get("COMET_PROJECT_NAME")
comet_initialized = bool(COMET_API_KEY and COMET_WORKSPACE and COMET_PROJECT_NAME)
if not comet_initialized:
    st.warning("Comet ML not initialized. Check environment variables.")

# --- Label Definitions ---
labels = [
    "Disease",
    "Symptom",
    "Medication",
    "Dosage",
    "Frequency",
    "Procedure",
    "Diagnostic_test",
    "Lab_value",
    "Gene",
    "Protein",
    "Anatomy",
    "Cell_type",
    "Chemical",
    "Person",
    "Organization",
    "Date"
]
# Create a mapping dictionary for labels to categories
category_mapping = {
    "Clinical & Procedural": [
        "Disease",
        "Symptom",
        "Procedure"
    ],
    "Medication & Treatment": [
        "Medication",
        "Dosage",
        "Frequency"
    ],
    "Measurements & Results": [
        "Diagnostic_test",
        "Lab_value"
    ],
    "Biological & Anatomical": [
        "Gene",
        "Protein",
        "Anatomy",
        "Cell_type",
        "Chemical"
    ],
    "People & Groups": [
        "Person",
        "Organization"
    ],
    "Temporal": [
        "Date"
    ]
}

# --- Model Loading ---
@st.cache_resource
def load_ner_model():
    """Loads the GLiNER model and caches it."""
    try:
        return GLiNER.from_pretrained("Ihor/gliner-biomed-bi-large-v1.0", nested_ner=True, num_gen_sequences=2, gen_constraints=labels)
    except Exception as e:
        st.error(f"Failed to load NER model. Please check your internet connection or model availability: {e}")
        st.stop()

model = load_ner_model()
# Flatten the mapping to a single dictionary
reverse_category_mapping = {label: category for category, label_list in category_mapping.items() for label in label_list}

# --- Session State Initialization ---
# This is the key fix. We use session state to control what is displayed.
if 'show_results' not in st.session_state:
    st.session_state.show_results = False
if 'last_text' not in st.session_state:
    st.session_state.last_text = ""
if 'results_df' not in st.session_state:
    st.session_state.results_df = pd.DataFrame()
if 'elapsed_time' not in st.session_state:
    st.session_state.elapsed_time = 0.0

# --- Text Input and Clear Button ---
word_limit = 200
text = st.text_area(f"Type or paste your text below (max {word_limit} words), and then press Ctrl + Enter", height=250, key='my_text_area')
word_count = len(text.split())
st.markdown(f"**Word count:** {word_count}/{word_limit}")

def clear_text():
    """Clears the text area and hides results."""
    st.session_state['my_text_area'] = ""
    st.session_state.show_results = False
    st.session_state.last_text = ""
    st.session_state.results_df = pd.DataFrame()
    st.session_state.elapsed_time = 0.0

st.button("Clear text", on_click=clear_text)

# --- Results Section ---
if st.button("Results"):
    if not text.strip():
        st.warning("Please enter some text to extract entities.")
        st.session_state.show_results = False
    elif word_count > word_limit:
        st.warning(f"Your text exceeds the {word_limit} word limit. Please shorten it to continue.")
        st.session_state.show_results = False
    else:
        # Check if the text is different from the last time
        if text != st.session_state.last_text:
            st.session_state.show_results = True
            st.session_state.last_text = text
            start_time = time.time()
            with st.spinner("Extracting entities...", show_time=True):
                entities = model.predict_entities(text, labels)
                df = pd.DataFrame(entities)
                st.session_state.results_df = df
                if not df.empty:
                    df['category'] = df['label'].map(reverse_category_mapping)
                    if comet_initialized:
                        experiment = Experiment(
                            api_key=COMET_API_KEY,
                            workspace=COMET_WORKSPACE,
                            project_name=COMET_PROJECT_NAME,
                        )
                        experiment.log_parameter("input_text", text)
                        experiment.log_table("predicted_entities", df)
                        experiment.end()
            end_time = time.time()
            st.session_state.elapsed_time = end_time - start_time
        else:
            # If the text is the same, just show the cached results without re-running
            st.session_state.show_results = True

# Display results if the state variable is True
if st.session_state.show_results:
    df = st.session_state.results_df
    if not df.empty:
        df['category'] = df['label'].map(reverse_category_mapping)
        st.subheader("Grouped Entities by Category", divider="gray")

        # Create tabs for each category
        category_names = sorted(list(category_mapping.keys()))
        category_tabs = st.tabs(category_names)

        for i, category_name in enumerate(category_names):
            with category_tabs[i]:
                df_category_filtered = df[df['category'] == category_name]
                if not df_category_filtered.empty:
                    st.dataframe(df_category_filtered.drop(columns=['category']), use_container_width=True)
                else:
                    st.info(f"No entities found for the '{category_name}' category.")
        
        with st.expander("See Glossary of tags"):
            st.write('''
            - **text**: ['entity extracted from your text data']
            - **score**: ['accuracy score; how accurately a tag has been assigned to a given entity']
            - **label**: ['label (tag) assigned to a given extracted entity']
            - **start**: ['index of the start of the corresponding entity']
            - **end**: ['index of the end of the corresponding entity']
            ''')
        st.divider()
        
        # Tree map
        st.subheader("Tree map", divider="gray")
        fig_treemap = px.treemap(df, path=[px.Constant("all"), 'category', 'label', 'text'], values='score', color='category')
        fig_treemap.update_layout(margin=dict(t=50, l=25, r=25, b=25), paper_bgcolor='#F5F5F5', plot_bgcolor='#F5F5F5')
        st.plotly_chart(fig_treemap)
        
        # Pie and Bar charts
        grouped_counts = df['category'].value_counts().reset_index()
        grouped_counts.columns = ['category', 'count']
        col1, col2 = st.columns(2)
        
        with col1:
            st.subheader("Pie chart", divider="gray")
            fig_pie = px.pie(grouped_counts, values='count', names='category', hover_data=['count'], labels={'count': 'count'}, title='Percentage of predicted categories')
            fig_pie.update_traces(textposition='inside', textinfo='percent+label')
            fig_pie.update_layout(
                paper_bgcolor='#F5F5F5',
                plot_bgcolor='#F5F5F5'
            )
            st.plotly_chart(fig_pie)
            
        with col2:
            st.subheader("Bar chart", divider="gray")
            fig_bar = px.bar(grouped_counts, x="count", y="category", color="category", text_auto=True, title='Occurrences of predicted categories')
            fig_bar.update_layout(
                paper_bgcolor='#F5F5F5',
                plot_bgcolor='#F5F5F5'
            )
            st.plotly_chart(fig_bar)
            
        # Most Frequent Entities
        st.subheader("Most Frequent Entities", divider="gray")
        word_counts = df['text'].value_counts().reset_index()
        word_counts.columns = ['Entity', 'Count']
        repeating_entities = word_counts[word_counts['Count'] > 1]
        
        if not repeating_entities.empty:
            st.dataframe(repeating_entities, use_container_width=True)
            fig_repeating_bar = px.bar(repeating_entities, x='Entity', y='Count', color='Entity')
            fig_repeating_bar.update_layout(xaxis={'categoryorder': 'total descending'},
                                            paper_bgcolor='#F5F5F5',
                                            plot_bgcolor='#F5F5F5')
            st.plotly_chart(fig_repeating_bar)
        else:
            st.warning("No entities were found that occur more than once.")
        
        # Download Section
        st.divider()
        dfa = pd.DataFrame(
            data={
                'Column Name': ['text', 'label', 'score', 'start', 'end'],
                'Description': [
                    'entity extracted from your text data',
                    'label (tag) assigned to a given extracted entity',
                    'accuracy score; how accurately a tag has been assigned to a given entity',
                    'index of the start of the corresponding entity',
                    'index of the end of the corresponding entity',
                ]
            }
        )
        buf = io.BytesIO()
        with zipfile.ZipFile(buf, "w") as myzip:
            myzip.writestr("Summary of the results.csv", df.to_csv(index=False))
            myzip.writestr("Glossary of tags.csv", dfa.to_csv(index=False))
        
        with stylable_container(
            key="download_button",
            css_styles="""button { background-color: #8C8C8C; border: 1px solid black; padding: 5px; color: white; }""",
        ):
            st.download_button(
                label="Download results and glossary (zip)",
                data=buf.getvalue(),
                file_name="nlpblogs_results.zip",
                mime="application/zip",
            )
        
        st.text("")
        st.text("")
        st.info(f"Results processed in **{st.session_state.elapsed_time:.2f} seconds**.")
    
    else:  # If df is empty after the button click
        st.warning("No entities were found in the provided text.")