AIEcosystem commited on
Commit
dcc6d3b
·
verified ·
1 Parent(s): 2b93269

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: #E8F5E9; /* A very light green */
23
+ color: #1B5E20; /* Dark green for the text */
24
+ }
25
+
26
+ /* Sidebar background color */
27
+ .css-1d36184 {
28
+ background-color: #A5D6A7; /* A medium light green */
29
+ secondary-background-color: #A5D6A7;
30
+ }
31
+
32
+ /* Expander background color and header */
33
+ .streamlit-expanderContent, .streamlit-expanderHeader {
34
+ background-color: #E8F5E9;
35
+ }
36
+
37
+ /* Text Area background and text color */
38
+ .stTextArea textarea {
39
+ background-color: #81C784; /* A slightly darker medium green */
40
+ color: #1B5E20; /* Dark green for text */
41
+ }
42
+
43
+ /* Button background and text color */
44
+ .stButton > button {
45
+ background-color: #81C784;
46
+ color: #1B5E20;
47
+ }
48
+
49
+ /* Warning box background and text color */
50
+ .stAlert.st-warning {
51
+ background-color: #66BB6A; /* A medium-dark green for the warning box */
52
+ color: #1B5E20;
53
+ }
54
+
55
+ /* Success box background and text color */
56
+ .stAlert.st-success {
57
+ background-color: #66BB6A; /* A medium-dark green for the success box */
58
+ color: #1B5E20;
59
+ }
60
+ </style>
61
+ """,
62
+ unsafe_allow_html=True
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("PiiGuard", divider="violet")
72
+ st.link_button("by nlpblogs", "https://nlpblogs.com", type="tertiary")
73
+
74
+ expander = st.expander("**Important notes**")
75
+ expander.write("""**Named Entities:** This PiiGuard web app predicts eight (8) labels:"Location", "Organization", "Product_or_Good", "Date", "Quantity", "Transportation_Mode", "Person", "Document_or_Form_ID"
76
+
77
+ 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.
78
+
79
+ **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.
80
+
81
+ **Usage Limits:** You can request results unlimited times for one (1) month.
82
+
83
+ **Supported Languages:** English
84
+
85
+ **Technical issues:** If your connection times out, please refresh the page or reopen the app's URL.
86
+
87
+ For any errors or inquiries, please contact us at info@nlpblogs.com""")
88
+
89
+ with st.sidebar:
90
+ st.write("Use the following code to embed the PiiGuard web app on your website. Feel free to adjust the width and height values to fit your page.")
91
+ code = '''
92
+ <iframe
93
+ src="https://aiecosystem-chainsense.hf.space"
94
+ frameborder="0"
95
+ width="850"
96
+ height="450"
97
+ ></iframe>
98
+
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="violet")
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
+
119
+ "person",
120
+ "organization",
121
+ "social_media_handle",
122
+ "username",
123
+ "insurance_company", "phone_number",
124
+ "email",
125
+ "email_address",
126
+ "mobile_phone_number",
127
+ "landline_phone_number",
128
+ "fax_number", "credit_card_number",
129
+ "credit_card_expiration_date",
130
+ "credit_card_brand",
131
+ "cvv",
132
+ "cvc",
133
+ "bank_account_number",
134
+ "iban",
135
+ "transaction_number",
136
+ "cpf",
137
+ "cnpj", "passport_number",
138
+ "passport_expiration_date",
139
+ "driver's_license_number",
140
+ "tax_identification_number",
141
+ "identity_card_number",
142
+ "national_id_number",
143
+ "identity_document_number",
144
+ "birth_certificate_number",
145
+ "social_security_number",
146
+ "health_insurance_id_number",
147
+ "health_insurance_number",
148
+ "national_health_insurance_number",
149
+ "student_id_number",
150
+ "registration_number",
151
+ "insurance_number",
152
+ "serial_number",
153
+ "visa_number",
154
+ "reservation_number",
155
+ "train_ticket_number", "medication",
156
+ "medical_condition",
157
+ "blood_type",
158
+ "date_of_birth", "address",
159
+ "ip_address",
160
+ "postal_code", "flight_number",
161
+ "license_plate_number",
162
+ "vehicle_registration_number", "digital_signature"
163
+ ]
164
+
165
+
166
+ # Corrected mapping dictionary
167
+ category_mapping =
168
+ {
169
+ "People_and_Groups": [
170
+ "person",
171
+ "organization",
172
+ "social_media_handle",
173
+ "username",
174
+ "insurance_company"
175
+ ],
176
+ "Contact_Information": [
177
+ "phone_number",
178
+ "email",
179
+ "email_address",
180
+ "mobile_phone_number",
181
+ "landline_phone_number",
182
+ "fax_number"
183
+ ],
184
+ "Financial_and_Transactions": [
185
+ "credit_card_number",
186
+ "credit_card_expiration_date",
187
+ "credit_card_brand",
188
+ "cvv",
189
+ "cvc",
190
+ "bank_account_number",
191
+ "iban",
192
+ "transaction_number",
193
+ "cpf",
194
+ "cnpj"
195
+ ],
196
+ "Identification_and_Documents": [
197
+ "passport_number",
198
+ "passport_expiration_date",
199
+ "driver's_license_number",
200
+ "tax_identification_number",
201
+ "identity_card_number",
202
+ "national_id_number",
203
+ "identity_document_number",
204
+ "birth_certificate_number",
205
+ "social_security_number",
206
+ "health_insurance_id_number",
207
+ "health_insurance_number",
208
+ "national_health_insurance_number",
209
+ "student_id_number",
210
+ "registration_number",
211
+ "insurance_number",
212
+ "serial_number",
213
+ "visa_number",
214
+ "reservation_number",
215
+ "train_ticket_number"
216
+ ],
217
+ "Health_and_Personal": [
218
+ "medication",
219
+ "medical_condition",
220
+ "blood_type",
221
+ "date_of_birth"
222
+ ],
223
+ "Locations_and_Addresses": [
224
+ "address",
225
+ "ip_address",
226
+ "postal_code"
227
+ ],
228
+ "Transportation_and_Logistics": [
229
+ "flight_number",
230
+ "license_plate_number",
231
+ "vehicle_registration_number"
232
+ ],
233
+ "Digital_and_Security": [
234
+ "digital_signature"
235
+ ]
236
+ }
237
+
238
+
239
+
240
+
241
+ # --- Model Loading ---
242
+ @st.cache_resource
243
+ def load_ner_model():
244
+ """Loads the GLiNER model and caches it."""
245
+ try:
246
+ return GLiNER.from_pretrained("E3-JSI/gliner-multi-pii-domains-v1", nested_ner=True, num_gen_sequences=2, gen_constraints= labels)
247
+ except Exception as e:
248
+ st.error(f"Failed to load NER model. Please check your internet connection or model availability: {e}")
249
+ st.stop()
250
+ model = load_ner_model()
251
+
252
+ # Flatten the mapping to a single dictionary
253
+ reverse_category_mapping = {label: category for category, label_list in category_mapping.items() for label in label_list}
254
+
255
+ # --- Text Input and Clear Button ---
256
+ text = st.text_area("Type or paste your text below, and then press Ctrl + Enter", height=250, key='my_text_area')
257
+
258
+ def clear_text():
259
+ """Clears the text area."""
260
+ st.session_state['my_text_area'] = ""
261
+
262
+ st.button("Clear text", on_click=clear_text)
263
+
264
+
265
+ # --- Results Section ---
266
+ if st.button("Results"):
267
+ start_time = time.time()
268
+ if not text.strip():
269
+ st.warning("Please enter some text to extract entities.")
270
+ else:
271
+ with st.spinner("Extracting entities...", show_time=True):
272
+ entities = model.predict_entities(text, labels)
273
+ df = pd.DataFrame(entities)
274
+
275
+ if not df.empty:
276
+ df['category'] = df['label'].map(reverse_category_mapping)
277
+ if comet_initialized:
278
+ experiment = Experiment(
279
+ api_key=COMET_API_KEY,
280
+ workspace=COMET_WORKSPACE,
281
+ project_name=COMET_PROJECT_NAME,
282
+ )
283
+ experiment.log_parameter("input_text", text)
284
+ experiment.log_table("predicted_entities", df)
285
+
286
+ st.subheader("Grouped Entities by Category", divider = "violet")
287
+
288
+ # Create tabs for each category
289
+ category_names = sorted(list(category_mapping.keys()))
290
+ category_tabs = st.tabs(category_names)
291
+
292
+ for i, category_name in enumerate(category_names):
293
+ with category_tabs[i]:
294
+ df_category_filtered = df[df['category'] == category_name]
295
+ if not df_category_filtered.empty:
296
+ st.dataframe(df_category_filtered.drop(columns=['category']), use_container_width=True)
297
+ else:
298
+ st.info(f"No entities found for the '{category_name}' category.")
299
+
300
+
301
+
302
+ with st.expander("See Glossary of tags"):
303
+ st.write('''
304
+ - **text**: ['entity extracted from your text data']
305
+ - **score**: ['accuracy score; how accurately a tag has been assigned to a given entity']
306
+ - **label**: ['label (tag) assigned to a given extracted entity']
307
+ - **start**: ['index of the start of the corresponding entity']
308
+ - **end**: ['index of the end of the corresponding entity']
309
+ ''')
310
+ st.divider()
311
+
312
+ # Tree map
313
+ st.subheader("Tree map", divider = "violet")
314
+ fig_treemap = px.treemap(df, path=[px.Constant("all"), 'category', 'label', 'text'], values='score', color='category')
315
+ fig_treemap.update_layout(margin=dict(t=50, l=25, r=25, b=25), paper_bgcolor='#E8F5E9', plot_bgcolor='#E8F5E9')
316
+ st.plotly_chart(fig_treemap)
317
+
318
+ # Pie and Bar charts
319
+ grouped_counts = df['category'].value_counts().reset_index()
320
+ grouped_counts.columns = ['category', 'count']
321
+ col1, col2 = st.columns(2)
322
+
323
+ with col1:
324
+ st.subheader("Pie chart", divider = "violet")
325
+ fig_pie = px.pie(grouped_counts, values='count', names='category', hover_data=['count'], labels={'count': 'count'}, title='Percentage of predicted categories')
326
+ fig_pie.update_traces(textposition='inside', textinfo='percent+label')
327
+ fig_pie.update_layout(
328
+ paper_bgcolor='#E8F5E9',
329
+ plot_bgcolor='#E8F5E9'
330
+ )
331
+ st.plotly_chart(fig_pie)
332
+
333
+
334
+
335
 
336
+ with col2:
337
+ st.subheader("Bar chart", divider = "violet")
338
+ fig_bar = px.bar(grouped_counts, x="count", y="category", color="category", text_auto=True, title='Occurrences of predicted categories')
339
+ fig_bar.update_layout( # Changed from fig_pie to fig_bar
340
+ paper_bgcolor='#E8F5E9',
341
+ plot_bgcolor='#E8F5E9'
342
+ )
343
+ st.plotly_chart(fig_bar)
344
+
345
+ # Most Frequent Entities
346
+ st.subheader("Most Frequent Entities", divider="violet")
347
+ word_counts = df['text'].value_counts().reset_index()
348
+ word_counts.columns = ['Entity', 'Count']
349
+ repeating_entities = word_counts[word_counts['Count'] > 1]
350
+ if not repeating_entities.empty:
351
+ st.dataframe(repeating_entities, use_container_width=True)
352
+ fig_repeating_bar = px.bar(repeating_entities, x='Entity', y='Count', color='Entity')
353
+ fig_repeating_bar.update_layout(xaxis={'categoryorder': 'total descending'},
354
+ paper_bgcolor='#E8F5E9',
355
+ plot_bgcolor='#E8F5E9')
356
+ st.plotly_chart(fig_repeating_bar)
357
+ else:
358
+ st.warning("No entities were found that occur more than once.")
359
+
360
+ # Download Section
361
+ st.divider()
362
+
363
+ dfa = pd.DataFrame(
364
+ data={
365
+ 'Column Name': ['text', 'label', 'score', 'start', 'end'],
366
+ 'Description': [
367
+ 'entity extracted from your text data',
368
+ 'label (tag) assigned to a given extracted entity',
369
+ 'accuracy score; how accurately a tag has been assigned to a given entity',
370
+ 'index of the start of the corresponding entity',
371
+ 'index of the end of the corresponding entity',
372
+
373
+ ]
374
+ }
375
+ )
376
+ buf = io.BytesIO()
377
+ with zipfile.ZipFile(buf, "w") as myzip:
378
+ myzip.writestr("Summary of the results.csv", df.to_csv(index=False))
379
+ myzip.writestr("Glossary of tags.csv", dfa.to_csv(index=False))
380
+
381
+ with stylable_container(
382
+ key="download_button",
383
+ css_styles="""button { background-color: red; border: 1px solid black; padding: 5px; color: white; }""",
384
+ ):
385
+ st.download_button(
386
+ label="Download results and glossary (zip)",
387
+ data=buf.getvalue(),
388
+ file_name="nlpblogs_results.zip",
389
+ mime="application/zip",
390
+ )
391
+
392
+ if comet_initialized:
393
+ experiment.log_figure(figure=fig_treemap, figure_name="entity_treemap_categories")
394
+ experiment.end()
395
+ else: # If df is empty
396
+ st.warning("No entities were found in the provided text.")
397
+
398
+ end_time = time.time()
399
+ elapsed_time = end_time - start_time
400
+ st.text("")
401
+ st.text("")
402
+ st.info(f"Results processed in **{elapsed_time:.2f} seconds**.")