AIEcosystem commited on
Commit
6a76f7c
·
verified ·
1 Parent(s): 636a8b1

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +400 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,402 @@
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: white;
23
+ color: black;
24
+ }
25
+ /* Sidebar background color */
26
+ .css-1d36184 {
27
+ background-color: #ADD8E6;
28
+ secondary-background-color: #ADD8E6;
29
+ }
30
+
31
+ /* Expander background color */
32
+ .streamlit-expanderContent {
33
+ background-color: white;
34
+ }
35
+ /* Expander header background color */
36
+ .streamlit-expanderHeader {
37
+ background-color: white;
38
+ }
39
+ /* Text Area background and text color */
40
+ .stTextArea textarea {
41
+ background-color: lavender;
42
+ color: black;
43
+ }
44
+ /* Button background and text color */
45
+ .stButton > button {
46
+ background-color: lavender;
47
+ color: black;
48
+ }
49
+ /* Warning box background and text color */
50
+ .stAlert.st-warning {
51
+ background-color: #lavender;
52
+ color: black;
53
+ }
54
+ /* Success box background and text color */
55
+ .stAlert.st-success {
56
+ background-color: #lavender;
57
+ color: black;
58
+ }
59
+ </style>
60
+ """,
61
+ unsafe_allow_html=True
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
+
72
+ st.subheader("Public Service", divider="gray")
73
+ st.link_button("by nlpblogs", "https://nlpblogs.com", type="tertiary")
74
+
75
+ expander = st.expander("**Important notes on the ProductTag**")
76
+ expander.write("""
77
+ **Named Entities:** This ProductTag predicts twenty-four (24) labels: "Product", "Service", "Organization", "Company", "Currency", "City", "Country", "Region", "Market", "Store", "Shop", "Customer_segment", "Demographics", "Target_market", "Market_segment", "Fiscal_period", "Timeframe", "Date", "Campaign", "Advertisement", "Event", "Media_platform", "Media_channel", "Social_media_platform"
78
+
79
+ 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.
80
+
81
+ **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.
82
+
83
+ **Usage Limits:** You can request results unlimited times for one (1) week.
84
+
85
+ **Supported Languages:** English
86
+
87
+ **Technical issues:** If your connection times out, please refresh the page or reopen the app's URL.
88
+
89
+ For any errors or inquiries, please contact us at [email protected]
90
+ """)
91
+
92
+ with st.sidebar:
93
+ st.subheader("Build your own NER Web App in a minute without writing a single line of code.", divider="gray")
94
+ st.link_button("NER File Builder", "https://nlpblogs.com/shop/named-entity-recognition-ner/ner-file-builder/", type="primary")
95
+
96
+ st.text("")
97
+ st.text("")
98
+
99
+ st.write("Use the following code to embed the ProductTag web app on your website. Feel free to adjust the width and height values to fit your page.")
100
+ code = '''
101
+ <iframe
102
+ src="https://aiecosystem-producttag1.hf.space"
103
+ frameborder="0"
104
+ width="850"
105
+ height="450"
106
+ ></iframe>
107
+ '''
108
+ st.code(code, language="html")
109
+
110
+ # --- Comet ML Setup ---
111
+ COMET_API_KEY = os.environ.get("COMET_API_KEY")
112
+ COMET_WORKSPACE = os.environ.get("COMET_WORKSPACE")
113
+ COMET_PROJECT_NAME = os.environ.get("COMET_PROJECT_NAME")
114
+
115
+ comet_initialized = bool(COMET_API_KEY and COMET_WORKSPACE and COMET_PROJECT_NAME)
116
+ if not comet_initialized:
117
+ st.warning("Comet ML not initialized. Check environment variables.")
118
+
119
+
120
+
121
+
122
+ # --- Label Definitions ---
123
+ labels = [
124
+ "Person",
125
+ "Date of birth",
126
+ "Blood type",
127
+ "Digital signature",
128
+ "Social media handle",
129
+ "Username",
130
+ "Birth certificate number",
131
+ "Address",
132
+ "Phone number",
133
+ "Mobile phone number",
134
+ "Landline phone number",
135
+ "Email",
136
+ "Fax number",
137
+ "Postal code",
138
+ "Credit card number",
139
+ "Credit card expiration date",
140
+ "CVV",
141
+ "CVC",
142
+ "Bank account number",
143
+ "IBAN",
144
+ "Transaction number",
145
+ "Credit card brand",
146
+ "Passport number",
147
+ "Social security number",
148
+ "CPF",
149
+ "Driver license number",
150
+ "Tax identification number",
151
+ "Identity card number",
152
+ "National ID number",
153
+ "Identity document number",
154
+ "Visa number",
155
+ "License plate number",
156
+ "CNPJ",
157
+ "Registration number",
158
+ "Student ID number",
159
+ "Passport expiration date",
160
+ "Medication",
161
+ "Medical condition",
162
+ "Health insurance ID number",
163
+ "Health insurance number",
164
+ "National health insurance number",
165
+ "Flight number",
166
+ "Reservation number",
167
+ "Train ticket number",
168
+ "Vehicle registration number",
169
+ "Organization",
170
+ "Insurance company",
171
+ "IP address",
172
+ "Serial number",
173
+ "Insurance number",
174
+
175
+ ]
176
+
177
+ category_mapping = {
178
+ "Personal Identifiers": [
179
+ "Person",
180
+ "Date of birth",
181
+ "Blood type",
182
+ "Digital signature",
183
+ "Social media handle",
184
+ "Username",
185
+ "Birth certificate number",
186
+ ],
187
+ "Contact Details": [
188
+ "Address",
189
+ "Phone number",
190
+ "Mobile phone number",
191
+ "Landline phone number",
192
+ "Email",
193
+ "Fax number",
194
+ "Postal code",
195
+ ],
196
+ "Financial & Payment": [
197
+ "Credit card number",
198
+ "Credit card expiration date",
199
+ "CVV",
200
+ "CVC",
201
+ "Bank account number",
202
+ "IBAN",
203
+ "Transaction number",
204
+ "Credit card brand",
205
+ ],
206
+ "Government & Official IDs": [
207
+ "Passport number",
208
+ "Social security number",
209
+ "CPF",
210
+ "Driver license number",
211
+ "Tax identification number",
212
+ "Identity card number",
213
+ "National ID number",
214
+ "Identity document number",
215
+ "Visa number",
216
+ "License plate number",
217
+ "CNPJ",
218
+ "Registration number",
219
+ "Student ID number",
220
+ "Passport expiration date",
221
+ ],
222
+ "Medical & Health": [
223
+ "Medication",
224
+ "Medical condition",
225
+ "Health insurance ID number",
226
+ "Health insurance number",
227
+ "National health insurance number",
228
+ ],
229
+ "Travel & Transport": [
230
+ "Flight number",
231
+ "Reservation number",
232
+ "Train ticket number",
233
+ "Vehicle registration number",
234
+ ],
235
+ "General Business & Other": [
236
+ "Organization",
237
+ "Insurance company",
238
+ "IP address",
239
+ "Serial number",
240
+ "Insurance number",
241
+ ]
242
+ }
243
+
244
+
245
+
246
+
247
+
248
+
249
+ # --- Model Loading ---
250
+ @st.cache_resource
251
+ def load_ner_model():
252
+ """Loads the GLiNER model and caches it."""
253
+ try:
254
+ return GLiNER.from_pretrained("urchade/gliner_multi_pii-v1", nested_ner=True, num_gen_sequences=2, gen_constraints= labels, threshold = 0.70)
255
+ except Exception as e:
256
+ st.error(f"Failed to load NER model. Please check your internet connection or model availability: {e}")
257
+ st.stop()
258
+
259
+ model = load_ner_model()
260
+
261
+
262
+ # Flatten the mapping to a single dictionary
263
+ reverse_category_mapping = {label: category for category, label_list in category_mapping.items() for label in label_list}
264
+
265
+ # --- Text Input and Clear Button ---
266
+ text = st.text_area("Type or paste your text below, and then press Ctrl + Enter", height=250, key='my_text_area')
267
+
268
+ def clear_text():
269
+ """Clears the text area."""
270
+ st.session_state['my_text_area'] = ""
271
+
272
+ st.button("Clear text", on_click=clear_text)
273
+ st.divider()
274
+
275
+ # --- Results Section ---
276
+ if st.button("Results"):
277
+ start_time = time.time()
278
+ if not text.strip():
279
+ st.warning("Please enter some text to extract entities.")
280
+ else:
281
+ with st.spinner("Extracting entities...", show_time=True):
282
+ entities = model.predict_entities(text, labels)
283
+ df = pd.DataFrame(entities)
284
+
285
+ if not df.empty:
286
+ df['category'] = df['label'].map(reverse_category_mapping)
287
+
288
+ if comet_initialized:
289
+ experiment = Experiment(
290
+ api_key=COMET_API_KEY,
291
+ workspace=COMET_WORKSPACE,
292
+ project_name=COMET_PROJECT_NAME,
293
+ )
294
+ experiment.log_parameter("input_text", text)
295
+ experiment.log_table("predicted_entities", df)
296
+
297
+ st.subheader("Extracted Entities", divider = "gray")
298
+ st.dataframe(df.style.set_properties(**{"border": "2px solid gray", "color": "blue", "font-size": "16px"}))
299
+
300
+ with st.expander("See Glossary of tags"):
301
+ st.write('''
302
+ - **text**: ['entity extracted from your text data']
303
+ - **score**: ['accuracy score; how accurately a tag has been assigned to a given entity']
304
+ - **label**: ['label (tag) assigned to a given extracted entity']
305
+ - **category**: ['the high-level category for the label']
306
+ - **start**: ['index of the start of the corresponding entity']
307
+ - **end**: ['index of the end of the corresponding entity']
308
+ ''')
309
+
310
+ st.divider()
311
+
312
+
313
+ # Tree map
314
+ st.subheader("Tree map", divider = "gray")
315
+ fig_treemap = px.treemap(df, path=[px.Constant("all"), 'category', 'label', 'text'], values='score', color='category')
316
+ fig_treemap.update_layout(margin=dict(t=50, l=25, r=25, b=25))
317
+
318
+
319
+ st.plotly_chart(fig_treemap)
320
+
321
+ # Pie and Bar charts
322
+ grouped_counts = df['category'].value_counts().reset_index()
323
+ grouped_counts.columns = ['category', 'count']
324
+
325
+ col1, col2 = st.columns(2)
326
+ with col1:
327
+ st.subheader("Pie chart", divider = "gray")
328
+ fig_pie = px.pie(grouped_counts, values='count', names='category',
329
+ hover_data=['count'], labels={'count': 'count'}, title='Percentage of predicted categories')
330
+ fig_pie.update_traces(textposition='inside', textinfo='percent+label')
331
+ st.plotly_chart(fig_pie)
332
+
333
+ with col2:
334
+ st.subheader("Bar chart", divider = "gray")
335
+ fig_bar = px.bar(grouped_counts, x="count", y="category", color="category", text_auto=True,
336
+ title='Occurrences of predicted categories')
337
+ st.plotly_chart(fig_bar)
338
+
339
+ # Most Frequent Entities
340
+ st.subheader("Most Frequent Entities", divider="gray")
341
+ word_counts = df['text'].value_counts().reset_index()
342
+ word_counts.columns = ['Entity', 'Count']
343
+ repeating_entities = word_counts[word_counts['Count'] > 1]
344
+ if not repeating_entities.empty:
345
+ st.dataframe(repeating_entities, use_container_width=True)
346
+ fig_repeating_bar = px.bar(repeating_entities, x='Entity', y='Count', color='Entity')
347
+ fig_repeating_bar.update_layout(xaxis={'categoryorder': 'total descending'})
348
+ st.plotly_chart(fig_repeating_bar)
349
+ else:
350
+ st.warning("No entities were found that occur more than once.")
351
+
352
+
353
+
354
+
355
+
356
+
357
+ # Download Section
358
+ st.divider()
359
+
360
+ dfa = pd.DataFrame(
361
+ data={
362
+ 'Column Name': ['text', 'label', 'score', 'start', 'end', 'category'],
363
+ 'Description': [
364
+ 'entity extracted from your text data',
365
+ 'label (tag) assigned to a given extracted entity',
366
+ 'accuracy score; how accurately a tag has been assigned to a given entity',
367
+ 'index of the start of the corresponding entity',
368
+ 'index of the end of the corresponding entity',
369
+ 'the broader category the entity belongs to',
370
+ ]
371
+ }
372
+ )
373
+
374
+ buf = io.BytesIO()
375
+ with zipfile.ZipFile(buf, "w") as myzip:
376
+ myzip.writestr("Summary of the results.csv", df.to_csv(index=False))
377
+ myzip.writestr("Glossary of tags.csv", dfa.to_csv(index=False))
378
+
379
+ with stylable_container(
380
+ key="download_button",
381
+ css_styles="""button { background-color: red; border: 1px solid black; padding: 5px; color: white; }""",
382
+ ):
383
+ st.download_button(
384
+ label="Download results and glossary (zip)",
385
+ data=buf.getvalue(),
386
+ file_name="markettag_results.zip",
387
+ mime="application/zip",
388
+ )
389
+
390
+ if comet_initialized:
391
+ experiment.log_figure(figure=fig_treemap, figure_name="entity_treemap_categories")
392
+ experiment.end()
393
+
394
+ else: # If df is empty
395
+ st.warning("No entities were found in the provided text.")
396
+
397
+ end_time = time.time()
398
+ elapsed_time = end_time - start_time
399
 
400
+ st.text("")
401
+ st.text("")
402
+ st.info(f"Results processed in **{elapsed_time:.2f} seconds**.")