AIEcosystem commited on
Commit
081b8a3
·
verified ·
1 Parent(s): a1ea95f

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +322 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,324 @@
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
+ /* Main app background and text color */
21
+ .stApp {
22
+ background-color: #FFF8F0; /* A very light, creamy orange */
23
+ color: #000000; /* Black for text */
24
+ }
25
+ /* Sidebar background color */
26
+ .css-1d36184 {
27
+ background-color: #FFC080; /* A soft orange for the sidebar */
28
+ secondary-background-color: #FFC080;
29
+ }
30
+ /* Expander background color */
31
+ .streamlit-expanderContent {
32
+ background-color: #FFF8F0;
33
+ }
34
+ /* Expander header background color */
35
+ .streamlit-expanderHeader {
36
+ background-color: #FFF8F0;
37
+ }
38
+ /* Text Area background and text color */
39
+ .stTextArea textarea {
40
+ background-color: #FFDDAA; /* A light, soft orange */
41
+ color: #000000; /* Black for text */
42
+ }
43
+ /* Button background and text color */
44
+ .stButton > button {
45
+ background-color: #FFDDAA;
46
+ color: #000000;
47
+ }
48
+ /* Warning box background and text color */
49
+ .stAlert.st-warning {
50
+ background-color: #FFBB88; /* A slightly darker orange for warnings */
51
+ color: #000000;
52
+ }
53
+ /* Success box background and text color */
54
+ .stAlert.st-success {
55
+ background-color: #FFBB88; /* A slightly darker orange for success boxes */
56
+ color: #000000;
57
+ }
58
+ </style>
59
+ """,
60
+ unsafe_allow_html=True
61
+ )
62
+
63
+
64
+
65
+
66
+
67
+
68
+
69
+ # --- Page Configuration and UI Elements ---
70
+ st.set_page_config(layout="wide", page_title="Named Entity Recognition App")
71
+ st.subheader("Uncover", divider="orange")
72
+ st.link_button("by nlpblogs", "https://nlpblogs.com", type="tertiary")
73
+ expander = st.expander("**Important notes**")
74
+ expander.write("""**Named Entities:** This Business Core predicts twenty-six (26) labels: "Person", "Contact", "Company", "Department", "Vendor", "Client", "Office", "Warehouse", "Address", "City", "State", "Country", "Date", "Time", "Time Period", "Revenue", "Cost", "Budget", "Invoice Number", "Product", "Service", "Task", "Project", "Status", "Asset", "Transaction"
75
+ 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.
76
+ **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.
77
+ **Usage Limits:** You can request results unlimited times for one (1) month.
78
+ **Supported Languages:** English
79
+ **Technical issues:** If your connection times out, please refresh the page or reopen the app's URL.
80
+ For any errors or inquiries, please contact us at [email protected]""")
81
+
82
+ with st.sidebar:
83
+ st.write("Use the following code to embed the Business Core web app on your website. Feel free to adjust the width and height values to fit your page.")
84
+ code = '''
85
+ <iframe
86
+ src="https://aiecosystem-business-core.hf.space"
87
+ frameborder="0"
88
+ width="850"
89
+ height="450"
90
+ ></iframe>
91
+ '''
92
+ st.code(code, language="html")
93
+ st.text("")
94
+ st.text("")
95
+ st.divider()
96
+ st.subheader("🚀 Ready to build your own NER Web App?", divider="orange")
97
+ st.link_button("NER Builder", "https://nlpblogs.com", type="primary")
98
+
99
+ # --- Comet ML Setup ---
100
+ COMET_API_KEY = os.environ.get("COMET_API_KEY")
101
+ COMET_WORKSPACE = os.environ.get("COMET_WORKSPACE")
102
+ COMET_PROJECT_NAME = os.environ.get("COMET_PROJECT_NAME")
103
+ comet_initialized = bool(COMET_API_KEY and COMET_WORKSPACE and COMET_PROJECT_NAME)
104
+
105
+ if not comet_initialized:
106
+ st.warning("Comet ML not initialized. Check environment variables.")
107
+
108
+ # --- Label Definitions ---
109
+
110
+ labels = [
111
+ "Names",
112
+ "Aliases",
113
+ "Identifiers",
114
+ "Roles",
115
+ "Government_agencies",
116
+ "Businesses",
117
+ "Criminal_groups",
118
+ "Financial_institutions",
119
+ "Addresses",
120
+ "Geographic_coordinates",
121
+ "Landmarks",
122
+ "Jurisdictions",
123
+ "Dates",
124
+ "Timestamps",
125
+ "Time_ranges",
126
+ "Weapons",
127
+ "Vehicles",
128
+ "Financial_information",
129
+ "Evidence",
130
+ "Relationships",
131
+ "Demographics",
132
+ "Biometrics",
133
+ "Psychological_states",
134
+ "Software_types",
135
+ "Hardware_components",
136
+
137
+ "Equipment",
138
+
139
+ "Events",
140
+
141
+ "Activities"
142
+
143
+
144
+
145
+ ]
146
+
147
+
148
+ # Create a mapping dictionary for labels to categories
149
+
150
+ category_mapping = {
151
+
152
+
153
+ "People & Identities": ["Names", "Aliases", "Identifiers", "Roles", "Demographics", "Biometrics", "Psychological_states", "Relationships"],
154
+ "Organizations & Groups": ["Government_agencies", "Businesses", "Criminal_groups", "Financial_institutions"],
155
+ "Locations & Jurisdictions": ["Addresses", "Geographic_coordinates", "Landmarks", "Jurisdictions"],
156
+ "Times & Events" : ["Dates", "Timestamps", "Time_ranges", "Events", "Activities"],
157
+
158
+ "Objects & Information": ["Weapons", "Vehicles", "Equipment", "Financial_information", "Evidence", "Software_types", "Hardware_components"],
159
+
160
+ }
161
+
162
+
163
+
164
+
165
+ # --- Model Loading ---
166
+ @st.cache_resource
167
+ def load_ner_model():
168
+ """Loads the GLiNER model and caches it."""
169
+ try:
170
+ return GLiNER.from_pretrained("knowledgator/gliner-multitask-large-v0.5", nested_ner=True, num_gen_sequences=2, gen_constraints= labels)
171
+ except Exception as e:
172
+ st.error(f"Failed to load NER model. Please check your internet connection or model availability: {e}")
173
+ st.stop()
174
+ model = load_ner_model()
175
+
176
+ # Flatten the mapping to a single dictionary
177
+ reverse_category_mapping = {label: category for category, label_list in category_mapping.items() for label in label_list}
178
+
179
+ # --- Text Input and Clear Button ---
180
+ text = st.text_area("Type or paste your text below, and then press Ctrl + Enter", height=250, key='my_text_area')
181
+
182
+ def clear_text():
183
+ """Clears the text area."""
184
+ st.session_state['my_text_area'] = ""
185
+
186
+ st.button("Clear text", on_click=clear_text)
187
+
188
+
189
+ # --- Results Section ---
190
+ if st.button("Results"):
191
+ start_time = time.time()
192
+ if not text.strip():
193
+ st.warning("Please enter some text to extract entities.")
194
+ else:
195
+ with st.spinner("Extracting entities...", show_time=True):
196
+ entities = model.predict_entities(text, labels)
197
+ df = pd.DataFrame(entities)
198
+
199
+ if not df.empty:
200
+ df['category'] = df['label'].map(reverse_category_mapping)
201
+ if comet_initialized:
202
+ experiment = Experiment(
203
+ api_key=COMET_API_KEY,
204
+ workspace=COMET_WORKSPACE,
205
+ project_name=COMET_PROJECT_NAME,
206
+ )
207
+ experiment.log_parameter("input_text", text)
208
+ experiment.log_table("predicted_entities", df)
209
+
210
+ st.subheader("Grouped Entities by Category", divider = "orange")
211
+
212
+ # Create tabs for each category
213
+ category_names = sorted(list(category_mapping.keys()))
214
+ category_tabs = st.tabs(category_names)
215
+
216
+ for i, category_name in enumerate(category_names):
217
+ with category_tabs[i]:
218
+ df_category_filtered = df[df['category'] == category_name]
219
+ if not df_category_filtered.empty:
220
+ st.dataframe(df_category_filtered.drop(columns=['category']), use_container_width=True)
221
+ else:
222
+ st.info(f"No entities found for the '{category_name}' category.")
223
+
224
+
225
 
226
+ with st.expander("See Glossary of tags"):
227
+ st.write('''
228
+ - **text**: ['entity extracted from your text data']
229
+ - **score**: ['accuracy score; how accurately a tag has been assigned to a given entity']
230
+ - **label**: ['label (tag) assigned to a given extracted entity']
231
+ - **category**: ['the high-level category for the label']
232
+ - **start**: ['index of the start of the corresponding entity']
233
+ - **end**: ['index of the end of the corresponding entity']
234
+ ''')
235
+ st.divider()
236
+
237
+ # Tree map
238
+ st.subheader("Tree map", divider = "orange")
239
+ fig_treemap = px.treemap(df, path=[px.Constant("all"), 'category', 'label', 'text'], values='score', color='category')
240
+ fig_treemap.update_layout(margin=dict(t=50, l=25, r=25, b=25), paper_bgcolor='#FFF8F0', plot_bgcolor='#FFF8F0')
241
+ st.plotly_chart(fig_treemap)
242
+
243
+ # Pie and Bar charts
244
+ grouped_counts = df['category'].value_counts().reset_index()
245
+ grouped_counts.columns = ['category', 'count']
246
+ col1, col2 = st.columns(2)
247
+
248
+ with col1:
249
+ st.subheader("Pie chart", divider = "orange")
250
+ fig_pie = px.pie(grouped_counts, values='count', names='category', hover_data=['count'], labels={'count': 'count'}, title='Percentage of predicted categories')
251
+ fig_pie.update_traces(textposition='inside', textinfo='percent+label')
252
+ fig_pie.update_layout(
253
+ paper_bgcolor='#FFF8F0',
254
+ plot_bgcolor='#FFF8F0'
255
+ )
256
+ st.plotly_chart(fig_pie)
257
+
258
+ with col2:
259
+ st.subheader("Bar chart", divider = "orange")
260
+ fig_bar = px.bar(grouped_counts, x="count", y="category", color="category", text_auto=True, title='Occurrences of predicted categories')
261
+ fig_bar.update_layout(
262
+ paper_bgcolor='#FFF8F0',
263
+ plot_bgcolor='#FFF8F0'
264
+ )
265
+ st.plotly_chart(fig_bar)
266
+
267
+ # Most Frequent Entities
268
+ st.subheader("Most Frequent Entities", divider="orange")
269
+ word_counts = df['text'].value_counts().reset_index()
270
+ word_counts.columns = ['Entity', 'Count']
271
+ repeating_entities = word_counts[word_counts['Count'] > 1]
272
+ if not repeating_entities.empty:
273
+ st.dataframe(repeating_entities, use_container_width=True)
274
+ fig_repeating_bar = px.bar(repeating_entities, x='Entity', y='Count', color='Entity')
275
+ fig_repeating_bar.update_layout(xaxis={'categoryorder': 'total descending'},
276
+ paper_bgcolor='#FFF8F0',
277
+ plot_bgcolor='#FFF8F0')
278
+ st.plotly_chart(fig_repeating_bar)
279
+ else:
280
+ st.warning("No entities were found that occur more than once.")
281
+
282
+ # Download Section
283
+ st.divider()
284
+
285
+ dfa = pd.DataFrame(
286
+ data={
287
+ 'Column Name': ['text', 'label', 'score', 'start', 'end', 'category'],
288
+ 'Description': [
289
+ 'entity extracted from your text data',
290
+ 'label (tag) assigned to a given extracted entity',
291
+ 'accuracy score; how accurately a tag has been assigned to a given entity',
292
+ 'index of the start of the corresponding entity',
293
+ 'index of the end of the corresponding entity',
294
+ 'the broader category the entity belongs to',
295
+ ]
296
+ }
297
+ )
298
+ buf = io.BytesIO()
299
+ with zipfile.ZipFile(buf, "w") as myzip:
300
+ myzip.writestr("Summary of the results.csv", df.to_csv(index=False))
301
+ myzip.writestr("Glossary of tags.csv", dfa.to_csv(index=False))
302
+
303
+ with stylable_container(
304
+ key="download_button",
305
+ css_styles="""button { background-color: red; border: 1px solid black; padding: 5px; color: white; }""",
306
+ ):
307
+ st.download_button(
308
+ label="Download results and glossary (zip)",
309
+ data=buf.getvalue(),
310
+ file_name="nlpblogs_results.zip",
311
+ mime="application/zip",
312
+ )
313
+
314
+ if comet_initialized:
315
+ experiment.log_figure(figure=fig_treemap, figure_name="entity_treemap_categories")
316
+ experiment.end()
317
+ else: # If df is empty
318
+ st.warning("No entities were found in the provided text.")
319
+
320
+ end_time = time.time()
321
+ elapsed_time = end_time - start_time
322
+ st.text("")
323
+ st.text("")
324
+ st.info(f"Results processed in **{elapsed_time:.2f} seconds**.")