Maria Tsilimos commited on
Commit
a3633fc
·
unverified ·
1 Parent(s): 56a1f71

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +448 -0
app.py ADDED
@@ -0,0 +1,448 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import streamlit as st
3
+ import pandas as pd
4
+ import io
5
+ import plotly.express as px
6
+ import zipfile
7
+ import os
8
+ import re
9
+ import numpy as np
10
+
11
+ from cryptography.fernet import Fernet
12
+ from gliner import GLiNER
13
+ from PyPDF2 import PdfReader
14
+ import docx
15
+ from comet_ml import Experiment
16
+ from streamlit_extras.stylable_container import stylable_container
17
+
18
+ st.set_page_config(layout="wide", page_title="Named Entity Recognition App")
19
+
20
+ # --- Configuration ---
21
+ COMET_API_KEY = os.environ.get("COMET_API_KEY")
22
+ COMET_WORKSPACE = os.environ.get("COMET_WORKSPACE")
23
+ COMET_PROJECT_NAME = os.environ.get("COMET_PROJECT_NAME")
24
+
25
+ comet_initialized = False
26
+ if COMET_API_KEY and COMET_WORKSPACE and COMET_PROJECT_NAME:
27
+ comet_initialized = True
28
+
29
+ # --- Initialize session state ---
30
+ if 'file_upload_attempts' not in st.session_state:
31
+ st.session_state['file_upload_attempts'] = 0
32
+
33
+ if 'encrypted_extracted_text' not in st.session_state:
34
+ st.session_state['encrypted_extracted_text'] = None
35
+
36
+ max_attempts = 10
37
+
38
+
39
+ GLINER_LABELS_CATEGORIZED = {
40
+ "Personal Identifiers": [
41
+ "Person",
42
+ "Date of birth",
43
+ "Blood type",
44
+ "Digital signature",
45
+ "Social media handle",
46
+ "Username",
47
+ "Birth certificate number",
48
+ ],
49
+ "Contact Details": [
50
+ "Address",
51
+ "Phone number",
52
+ "Mobile phone number",
53
+ "Landline phone number",
54
+ "Email",
55
+ "Fax number",
56
+ "Postal code",
57
+ ],
58
+ "Financial & Payment": [
59
+ "Credit card number",
60
+ "Credit card expiration date",
61
+ "CVV",
62
+ "CVC",
63
+ "Bank account number",
64
+ "IBAN",
65
+ "Transaction number",
66
+ "Credit card brand",
67
+ ],
68
+ "Government & Official IDs": [
69
+ "Passport number",
70
+
71
+ "Social security number",
72
+
73
+ "CPF",
74
+ "Driver license number",
75
+ "Tax identification number",
76
+ "Identity card number",
77
+ "National ID number",
78
+ "Identity document number",
79
+ "Visa number",
80
+ "License plate number",
81
+ "CNPJ",
82
+ "Registration number",
83
+ "Student ID number",
84
+ "Passport expiration date",
85
+ ],
86
+ "Medical & Health": [
87
+ "Medication",
88
+ "Medical condition",
89
+ "Health insurance ID number",
90
+ "Health insurance number",
91
+ "National health insurance number",
92
+ ],
93
+ "Travel & Transport": [
94
+ "Flight number",
95
+ "Reservation number",
96
+ "Train ticket number",
97
+ "Vehicle registration number",
98
+ ],
99
+ "General Business & Other": [
100
+ "Organization",
101
+ "Insurance company",
102
+ "IP address",
103
+ "Serial number",
104
+ "Insurance number",
105
+ ]
106
+ }
107
+
108
+ # Flatten the categorized labels into a single list for GLiNER model input
109
+ GLINER_LABELS_FLAT = [label for category_labels in GLINER_LABELS_CATEGORIZED.values() for label in category_labels]
110
+
111
+ # Create a mapping from each specific label to its category for DataFrame processing
112
+ LABEL_TO_CATEGORY_MAP = {label: category for category, labels in GLINER_LABELS_CATEGORIZED.items() for label in labels}
113
+
114
+ @st.cache_resource
115
+ def load_ner_model():
116
+ """
117
+ Loads the pre-trained GLiNER NER model (urchade/gliner_multi_pii-v1) and
118
+ caches it.
119
+ This model is suitable for a wide range of custom entity types.
120
+ """
121
+ try:
122
+ return GLiNER.from_pretrained("urchade/gliner_multi_pii-v1")
123
+ except Exception as e:
124
+ st.error(f"Failed to load NER model. Please check your internet connection or model availability: {e}")
125
+ st.stop()
126
+
127
+ @st.cache_resource
128
+ def load_encryption_key():
129
+ """
130
+ Loads the Fernet encryption key from environment variables.
131
+ This key is crucial for encrypting/decrypting sensitive data.
132
+ It's cached as a resource to be loaded only once.
133
+ """
134
+ try:
135
+ # Get the key string from environment variables
136
+ key_str = os.environ.get("FERNET_KEY")
137
+ if not key_str:
138
+ raise ValueError("FERNET_KEY environment variable not set. Cannot perform encryption/decryption.")
139
+
140
+ # Fernet key must be bytes, so encode the string
141
+ key_bytes = key_str.encode('utf-8')
142
+ return Fernet(key_bytes)
143
+ except ValueError as ve:
144
+ st.error(f"Configuration Error: {ve}. Please ensure the 'FERNET_KEY' environment variable is set securely in your deployment environment (e.g., Hugging Face Spaces secrets, Render environment variables) or in a local .env file for development.")
145
+ st.stop() # Stop the app if the key is not found, as security is compromised
146
+ except Exception as e:
147
+ st.error(f"An unexpected error occurred while loading encryption key: {e}. Please check your key format and environment settings.")
148
+ st.stop()
149
+
150
+ # Initialize the Fernet cipher instance globally (cached)
151
+ fernet = load_encryption_key()
152
+
153
+ def encrypt_text(text_content: str) -> bytes:
154
+ """
155
+ Encrypts a string using the loaded Fernet cipher.
156
+ The input string is first encoded to UTF-8 bytes.
157
+ """
158
+ return fernet.encrypt(text_content.encode('utf-8'))
159
+
160
+ def decrypt_text(encrypted_bytes: bytes) -> str | None:
161
+ """
162
+ Decrypts bytes using the loaded Fernet cipher.
163
+ Returns the decrypted string, or None if decryption fails (e.g., tampering).
164
+ """
165
+ try:
166
+ return fernet.decrypt(encrypted_bytes).decode('utf-8')
167
+ except Exception as e:
168
+ st.error(f"Decryption failed. This might indicate data tampering or an incorrect encryption key. Error: {e}")
169
+ return None
170
+
171
+ # --- UI Elements ---
172
+ st.subheader("Multilingual PDF & DOCX Entity Finder", divider="orange") # Updated title
173
+ st.link_button("by nlpblogs", "https://nlpblogs.com", type="tertiary")
174
+
175
+
176
+
177
+
178
+ expander = st.expander("**Important notes on the Multilingual PDF & DOCX Entity Finder**")
179
+ expander.write(f'''
180
+ **Named Entities:** This Multilingual PDF & DOCX Entity Finder predicts a wide range of custom labels, including: "Person", "Organization", "Phone number", "Address", "Passport number", "Email", "Credit card number", "Social security number", "Health insurance ID number", "Date of birth", "Mobile phone number", "Bank account number", "Medication", "CPF", "Driver license number", "Tax identification number", "Medical condition", "Identity card number", "National ID number", "IP address", "IBAN", "Credit card expiration date", "Username", "Health insurance number", "Registration number", "Student ID number", "Insurance number", "Flight number", "Landline phone number", "Blood type", "CVV", "Reservation number", "Digital signature", "Social media handle", "License plate number", "CNPJ", "Postal code", "Serial number", "Vehicle registration number", "Credit card brand", "Fax number", "Visa number", "Insurance company", "Identity document number", "Transaction number", "National health insurance number", "CVC", "Birth certificate number", "Train ticket number", "Passport expiration date"
181
+
182
+ Results are presented in an easy-to-read table, visualized in an interactive tree map, pie chart, and bar chart, and are available for download along with a Glossary of tags.
183
+
184
+ **Supported languages:** English, French, German, Spanish, Portuguese, Italian
185
+
186
+ **How to Use:** Upload your PDF or DOCX file. Then, click the 'Results' button to extract and tag entities in your text data.
187
+
188
+ **Usage Limits:** You can request results up to 10 times.
189
+
190
+ **Language settings:** Please check and adjust the language settings in your computer, so the French, German, Spanish, Portuguese and Italian characters are handled properly in your downloaded file.
191
+
192
+ **Customization:** To change the app's background color to white or black, click the three-dot menu on the right-hand side of your app, go to Settings and then Choose app theme, colors and fonts.
193
+
194
+ **Technical issues:** If your connection times out, please refresh the page or reopen the app's URL.
195
+
196
+ For any errors or inquiries, please contact us at [email protected]
197
+ ''')
198
+
199
+
200
+
201
+
202
+ with st.sidebar:
203
+ container = st.container(border=True)
204
+ container.write("**Named Entity Recognition (NER)** is the task of "
205
+ "extracting and tagging entities in text data. Entities can be persons, "
206
+ "organizations, locations, countries, products, events etc.")
207
+ st.subheader("Related NER Web Apps", divider="orange")
208
+ st.link_button("Scandinavian JSON Entity Finder",
209
+ "https://nlpblogs.com/shop/named-entity-recognition-ner/scandinavian-json-entity-finder/",
210
+ type="primary")
211
+
212
+ # --- File Upload (PDF/DOCX) ---
213
+ uploaded_file = st.file_uploader("Upload your file. Accepted file formats include: .pdf, .docx", type=['pdf', 'docx'])
214
+
215
+ # Initialize text for the current run outside the if uploaded_file block
216
+ current_run_text = None
217
+
218
+ if uploaded_file is not None:
219
+ file_extension = uploaded_file.name.split('.')[-1].lower()
220
+ if file_extension == 'pdf':
221
+ try:
222
+ pdf_reader = PdfReader(uploaded_file)
223
+ text_content = ""
224
+ for page in pdf_reader.pages:
225
+ text_content += page.extract_text()
226
+ current_run_text = text_content
227
+ st.success("PDF file uploaded successfully. File content encrypted and secured. Due to security protocols, the file content is hidden.")
228
+ except Exception as e:
229
+ st.error(f"An error occurred while reading PDF: {e}")
230
+ current_run_text = None
231
+ elif file_extension == 'docx':
232
+ try:
233
+ doc = docx.Document(uploaded_file)
234
+ text_content = "\n".join([para.text for para in doc.paragraphs])
235
+ current_run_text = text_content
236
+ st.success("DOCX file uploaded successfully. File content encrypted and secured. Due to security protocols, the file content is hidden.")
237
+ except Exception as e:
238
+ st.error(f"An error occurred while reading DOCX: {e}")
239
+ current_run_text = None
240
+ else:
241
+ st.warning("Unsupported file type. Please upload a .pdf or .docx file.")
242
+ current_run_text = None
243
+
244
+ if current_run_text and current_run_text.strip():
245
+ # --- ENCRYPT THE EXTRACTED TEXT BEFORE STORING IN SESSION STATE ---
246
+ encrypted_text_bytes = encrypt_text(current_run_text)
247
+ st.session_state['encrypted_extracted_text'] = encrypted_text_bytes
248
+
249
+ st.divider()
250
+ else:
251
+ st.session_state['encrypted_extracted_text'] = None
252
+ st.error("Could not extract meaningful text from the uploaded file.")
253
+
254
+ # --- Results Button and Processing Logic ---
255
+ if st.button("Results"):
256
+ start_time_overall = time.time() # Start time for overall processing
257
+ if not comet_initialized:
258
+ st.warning("Comet ML not initialized. Check environment variables if you wish to log data.")
259
+
260
+ if st.session_state['file_upload_attempts'] >= max_attempts:
261
+ st.error(f"You have requested results {max_attempts} times. You have reached your daily request limit.")
262
+ st.stop()
263
+
264
+ # --- DECRYPT THE TEXT BEFORE PASSING TO NER MODEL ---
265
+ text_for_ner = None
266
+ if st.session_state['encrypted_extracted_text'] is not None:
267
+ text_for_ner = decrypt_text(st.session_state['encrypted_extracted_text'])
268
+
269
+ if text_for_ner is None or not text_for_ner.strip():
270
+ st.warning("No extractable text content available for analysis. Please upload a valid PDF or DOCX file.")
271
+ st.stop()
272
+
273
+ st.session_state['file_upload_attempts'] += 1
274
+
275
+ with st.spinner("Analyzing text...", show_time=True):
276
+ model = load_ner_model()
277
+
278
+ # Measure NER model processing time
279
+ start_time_ner = time.time()
280
+ # Use GLiNER's predict_entities method with the defined flat list of labels
281
+ text_entities = model.predict_entities(text_for_ner, GLINER_LABELS_FLAT)
282
+ end_time_ner = time.time()
283
+ ner_processing_time = end_time_ner - start_time_ner
284
+
285
+ df = pd.DataFrame(text_entities)
286
+
287
+ # Rename 'label' to 'entity_group' and 'text' to 'word' for consistency
288
+ if 'label' in df.columns:
289
+ df.rename(columns={'label': 'entity_group', 'text': 'word'}, inplace=True)
290
+ else:
291
+ st.error("Unexpected GLiNER output structure. Please check the model's output format.")
292
+ st.stop()
293
+
294
+ # Replace empty strings with 'Unknown' and drop rows with NaN after cleaning
295
+ df = df.replace('', 'Unknown').dropna()
296
+
297
+ if df.empty:
298
+ st.warning("No entities were extracted from the uploaded text.")
299
+ st.stop()
300
+
301
+ # --- Add 'category' column to the DataFrame based on the grouped labels ---
302
+ df['category'] = df['entity_group'].map(LABEL_TO_CATEGORY_MAP)
303
+ # Handle cases where an entity_group might not have a category (shouldn't happen if maps are complete)
304
+ df['category'] = df['category'].fillna('Uncategorized')
305
+
306
+ if comet_initialized:
307
+ experiment = Experiment(
308
+ api_key=COMET_API_KEY,
309
+ workspace=COMET_WORKSPACE,
310
+ project_name=COMET_PROJECT_NAME,
311
+ )
312
+ experiment.log_parameter("input_text_length", len(text_for_ner))
313
+ experiment.log_table("predicted_entities", df)
314
+ experiment.log_metric("ner_processing_time_seconds", ner_processing_time)
315
+
316
+
317
+ # --- Display Results ---
318
+ st.subheader("Extracted Entities", divider="rainbow")
319
+ properties = {"border": "2px solid gray", "color": "blue", "font-size": "16px"}
320
+ df_styled = df.style.set_properties(**properties)
321
+ st.dataframe(df_styled, use_container_width=True)
322
+
323
+ with st.expander("See Glossary of tags"):
324
+ st.write("""
325
+ '**word**': ['entity extracted from your text data']
326
+
327
+ '**score**': ['accuracy score; how accurately a tag has been assigned to
328
+ a given entity']
329
+
330
+ '**entity_group**': ['label (tag) assigned to a given extracted entity']
331
+
332
+ '**start**': ['index of the start of the corresponding entity']
333
+
334
+ '**end**': ['index of the end of the corresponding entity']
335
+ '**category**': ['the broader category this entity belongs to']
336
+ """)
337
+
338
+
339
+ st.subheader("Grouped Entities by Category", divider = "orange")
340
+
341
+ # Create tabs for each category
342
+ category_names = list(GLINER_LABELS_CATEGORIZED.keys())
343
+ category_tabs = st.tabs(category_names)
344
+
345
+ for i, category_name in enumerate(category_names):
346
+ with category_tabs[i]:
347
+
348
+
349
+ # Filter the main DataFrame for the current category
350
+ df_category_filtered = df[df['category'] == category_name]
351
+
352
+ if not df_category_filtered.empty:
353
+ # Sort entities within the category by their specific type for better display
354
+ for entity_type in GLINER_LABELS_CATEGORIZED[category_name]:
355
+ df_entity_type_filtered = df_category_filtered[df_category_filtered['entity_group'] == entity_type]
356
+ if not df_entity_type_filtered.empty:
357
+ st.markdown(f"***{entity_type}***")
358
+ st.dataframe(df_entity_type_filtered.drop(columns=['category']), use_container_width=True)
359
+ else:
360
+ st.info(f"No '{entity_type}' entities found for this category.")
361
+ else:
362
+ st.info(f"No entities found for the '{category_name}' category.")
363
+
364
+ st.divider()
365
+
366
+ # --- Visualizations ---
367
+ st.subheader("Tree map", divider="orange")
368
+ # Update treemap path to include category
369
+ fig_treemap = px.treemap(df, path=[px.Constant("all"), 'category', 'entity_group', 'word'],
370
+ values='score', color='category') # Color by category for better visual distinction
371
+ fig_treemap.update_layout(margin=dict(t=50, l=25, r=25, b=25))
372
+ st.plotly_chart(fig_treemap)
373
+ if comet_initialized:
374
+ experiment.log_figure(figure=fig_treemap, figure_name="entity_treemap")
375
+
376
+ value_counts1 = df['entity_group'].value_counts()
377
+ final_df_counts = value_counts1.reset_index().rename(columns={"index": "entity_group", "count": "count"})
378
+
379
+ col1, col2 = st.columns(2)
380
+ with col1:
381
+ st.subheader("Pie Chart (by Entity Type)", divider="orange")
382
+ fig_pie = px.pie(final_df_counts, values='count', names='entity_group',
383
+ hover_data=['count'], labels={'count': 'count'}, title='Percentage of Predicted Labels (Entity Types)')
384
+ fig_pie.update_traces(textposition='inside', textinfo='percent+label')
385
+ st.plotly_chart(fig_pie)
386
+ if comet_initialized:
387
+ experiment.log_figure(figure=fig_pie, figure_name="label_pie_chart")
388
+
389
+ with col2:
390
+ st.subheader("Bar Chart (by Entity Type)", divider="orange")
391
+ fig_bar = px.bar(final_df_counts, x="count", y="entity_group", color="entity_group", text_auto=True,
392
+ title='Occurrences of Predicted Labels (Entity Types)', orientation='h')
393
+ fig_bar.update_layout(yaxis={'categoryorder':'total ascending'}) # Order bars
394
+ st.plotly_chart(fig_bar)
395
+ if comet_initialized:
396
+ experiment.log_figure(figure=fig_bar, figure_name="label_bar_chart")
397
+
398
+ # Add a chart for categories
399
+ st.subheader("Entity Counts by Category", divider="orange")
400
+ category_counts = df['category'].value_counts().reset_index().rename(columns={"index": "category", "count": "count"})
401
+ fig_cat_bar = px.bar(category_counts, x="count", y="category", color="category", text_auto=True,
402
+ title='Occurrences of Entities by Category', orientation='h')
403
+ fig_cat_bar.update_layout(yaxis={'categoryorder':'total ascending'})
404
+ st.plotly_chart(fig_cat_bar)
405
+
406
+
407
+ # --- Downloadable Content ---
408
+ dfa = pd.DataFrame(
409
+ data={
410
+ 'Column Name': ['word', 'entity_group', 'score', 'start', 'end', 'category'],
411
+ 'Description': [
412
+ 'entity extracted from your text data',
413
+ 'label (tag) assigned to a given extracted entity',
414
+ 'accuracy score; how accurately a tag has been assigned to a given entity',
415
+ 'index of the start of the corresponding entity',
416
+ 'index of the end of the corresponding entity',
417
+ 'the broader category this entity belongs to',
418
+ ]
419
+ }
420
+ )
421
+
422
+ buf = io.BytesIO()
423
+ with zipfile.ZipFile(buf, "w") as myzip:
424
+ myzip.writestr("Summary of the results.csv", df.to_csv(index=False))
425
+ myzip.writestr("Glossary of tags.csv", dfa.to_csv(index=False))
426
+
427
+ with stylable_container(
428
+ key="download_button",
429
+ css_styles="""button { background-color: yellow; border: 1px solid black; padding: 5px; color: black; }""",
430
+ ):
431
+ st.download_button(
432
+ label="Download zip file",
433
+ data=buf.getvalue(),
434
+ file_name="nlpblogs_ner_results.zip",
435
+ mime="application/zip",
436
+ )
437
+ if comet_initialized:
438
+ experiment.log_asset(buf.getvalue(), file_name="downloadable_results.zip")
439
+
440
+ st.divider()
441
+ if comet_initialized:
442
+ experiment.end()
443
+
444
+ end_time_overall = time.time() # End time for overall processing
445
+ elapsed_time_overall = end_time_overall - start_time_overall
446
+ st.info(f"Results processed in **{elapsed_time_overall:.2f} seconds**.")
447
+
448
+ st.write(f"Number of times you requested results: **{st.session_state['file_upload_attempts']}/{max_attempts}**")