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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import requests
|
2 |
+
import streamlit as st
|
3 |
+
from bs4 import BeautifulSoup
|
4 |
+
import pandas as pd
|
5 |
+
from transformers import pipeline
|
6 |
+
import plotly.express as px
|
7 |
+
import time
|
8 |
+
import io
|
9 |
+
import os
|
10 |
+
from comet_ml import Experiment
|
11 |
+
import zipfile
|
12 |
+
import re
|
13 |
+
from streamlit_extras.stylable_container import stylable_container
|
14 |
+
|
15 |
+
|
16 |
+
st.set_page_config(layout="wide", page_title="Named Entity Recognition App")
|
17 |
+
|
18 |
+
|
19 |
+
|
20 |
+
|
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 |
+
|
30 |
+
|
31 |
+
st.subheader("9-Personal Data Named Entity Recognition Web App", divider="rainbow")
|
32 |
+
st.link_button("by nlpblogs", "https://nlpblogs.com", type="tertiary")
|
33 |
+
|
34 |
+
expander = st.expander("**Important notes on the 9-Personal Data Named Entity Recognition Web App**")
|
35 |
+
expander.write('''
|
36 |
+
|
37 |
+
**Named Entities:**
|
38 |
+
This 9-Personal Data Named Entity Recognition Web App predicts nine (9) categories:
|
39 |
+
|
40 |
+
1. **Account-related information**: Account name, account number, and transaction amounts
|
41 |
+
|
42 |
+
2. **Banking details**: BIC, IBAN, and Bitcoin or Ethereum addresses
|
43 |
+
|
44 |
+
3. **Personal information**: Full name, first name, middle name, last name, gender, and date of birth
|
45 |
+
|
46 |
+
4. **Contact information**: Email, phone number, and street address (including building number, city, county, state, and zip code)
|
47 |
+
|
48 |
+
5. **Job-related data**: Job title, job area, job descriptor, and job type
|
49 |
+
|
50 |
+
6. **Financial data**: Credit card number, issuer, CVV, and currency information (code, name, and symbol)
|
51 |
+
|
52 |
+
7. **Digital identifiers**: IP addresses (IPv4 and IPv6), MAC addresses, and user agents
|
53 |
+
|
54 |
+
8. **Online presence**: URL, usernames, and passwords
|
55 |
+
|
56 |
+
9. **Other sensitive data**: SSN, vehicle VIN and VRM, phone IMEI, and nearby GPS coordinates
|
57 |
+
|
58 |
+
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.
|
59 |
+
|
60 |
+
**How to Use:**
|
61 |
+
Upload your .pdf or .docx file. Then, click the 'Results' button to extract and tag entities in your text data.
|
62 |
+
|
63 |
+
**Usage Limits:**
|
64 |
+
You can request results up to 10 times.
|
65 |
+
|
66 |
+
**Customization:**
|
67 |
+
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.
|
68 |
+
|
69 |
+
**Technical issues:**
|
70 |
+
If your connection times out, please refresh the page or reopen the app's URL.
|
71 |
+
|
72 |
+
For any errors or inquiries, please contact us at info@nlpblogs.com
|
73 |
+
|
74 |
+
''')
|
75 |
+
|
76 |
+
|
77 |
+
|
78 |
+
|
79 |
+
with st.sidebar:
|
80 |
+
container = st.container(border=True)
|
81 |
+
container.write("**Named Entity Recognition (NER)** is the task of extracting and tagging entities in text data. Entities can be persons, organizations, locations, countries, products, events etc.")
|
82 |
+
st.subheader("Related NLP Web Apps", divider="rainbow")
|
83 |
+
st.link_button("8-Named Entity Recognition Web App", "https://nlpblogs.com/shop/named-entity-recognition-ner/8-named-entity-recognition-web-app/", type="primary")
|
84 |
+
|
85 |
+
|
86 |
+
if 'source_type_attempts' not in st.session_state:
|
87 |
+
st.session_state['source_type_attempts'] = 0
|
88 |
+
max_attempts = 10
|
89 |
+
|
90 |
+
def clear_url_input():
|
91 |
+
|
92 |
+
st.session_state.url = ""
|
93 |
+
|
94 |
+
def clear_text_input():
|
95 |
+
|
96 |
+
st.session_state.my_text_area = ""
|
97 |
+
|
98 |
+
url = st.text_input("Enter URL from the internet, and then press Enter:", key="url")
|
99 |
+
st.button("Clear URL", on_click=clear_url_input)
|
100 |
+
|
101 |
+
text = st.text_area("Type or paste your text below, and then press Ctrl + Enter", key='my_text_area')
|
102 |
+
st.button("Clear Text", on_click=clear_text_input)
|
103 |
+
|
104 |
+
|
105 |
+
source_type = None
|
106 |
+
input_content = None
|
107 |
+
text_to_process = None
|
108 |
+
|
109 |
+
if url:
|
110 |
+
source_type = 'url'
|
111 |
+
input_content = url
|
112 |
+
elif text:
|
113 |
+
source_type = 'text'
|
114 |
+
input_content = text
|
115 |
+
|
116 |
+
if source_type:
|
117 |
+
|
118 |
+
st.subheader("Results", divider = "rainbow")
|
119 |
+
|
120 |
+
|
121 |
+
if st.session_state['source_type_attempts'] >= max_attempts:
|
122 |
+
st.error(f"You have requested results {max_attempts} times. You have reached your daily request limit.")
|
123 |
+
st.stop()
|
124 |
+
|
125 |
+
st.session_state['source_type_attempts'] += 1
|
126 |
+
|
127 |
+
|
128 |
+
@st.cache_resource
|
129 |
+
def load_ner_model():
|
130 |
+
|
131 |
+
return pipeline("token-classification", model="h2oai/deberta_finetuned_pii", aggregation_strategy="first")
|
132 |
+
|
133 |
+
model = load_ner_model()
|
134 |
+
experiment = None
|
135 |
+
|
136 |
+
try:
|
137 |
+
if source_type == 'url':
|
138 |
+
if not url.startswith(("http://", "https://")):
|
139 |
+
st.error("Please enter a valid URL starting with 'http://' or 'https://'.")
|
140 |
+
else:
|
141 |
+
with st.spinner(f"Fetching and parsing content from **{url}**...", show_time=True):
|
142 |
+
f = requests.get(url, timeout=10)
|
143 |
+
f.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
|
144 |
+
soup = BeautifulSoup(f.text, 'html.parser')
|
145 |
+
text_to_process = soup.get_text(separator=' ', strip=True)
|
146 |
+
st.divider()
|
147 |
+
st.write("**Input text content**")
|
148 |
+
st.write(text_to_process[:500] + "..." if len(text_to_process) > 500 else text_to_process)
|
149 |
+
|
150 |
+
|
151 |
+
|
152 |
+
elif source_type == 'text':
|
153 |
+
text_to_process = text
|
154 |
+
st.divider()
|
155 |
+
st.write("**Input text content**")
|
156 |
+
|
157 |
+
st.write(text_to_process[:500] + "..." if len(text_to_process) > 500 else text_to_process)
|
158 |
+
|
159 |
+
if text_to_process and len(text_to_process.strip()) > 0:
|
160 |
+
with st.spinner("Analyzing text...", show_time=True):
|
161 |
+
entities = model(text_to_process)
|
162 |
+
data = []
|
163 |
+
for entity in entities:
|
164 |
+
data.append({
|
165 |
+
'word': entity['word'],
|
166 |
+
'entity_group': entity['entity_group'],
|
167 |
+
'score': entity['score'],
|
168 |
+
'start': entity['start'], # Include start and end for download
|
169 |
+
'end': entity['end']
|
170 |
+
})
|
171 |
+
df = pd.DataFrame(data)
|
172 |
+
|
173 |
+
|
174 |
+
pattern = r'[^\w\s]'
|
175 |
+
df['word'] = df['word'].replace(pattern, '', regex=True)
|
176 |
+
|
177 |
+
df = df.replace('', 'Unknown')
|
178 |
+
st.dataframe(df)
|
179 |
+
|
180 |
+
|
181 |
+
if comet_initialized:
|
182 |
+
experiment = Experiment(
|
183 |
+
api_key=COMET_API_KEY,
|
184 |
+
workspace=COMET_WORKSPACE,
|
185 |
+
project_name=COMET_PROJECT_NAME,
|
186 |
+
)
|
187 |
+
experiment.log_parameter("input_source_type", source_type)
|
188 |
+
experiment.log_parameter("input_content_length", len(input_content))
|
189 |
+
experiment.log_table("predicted_entities", df)
|
190 |
+
|
191 |
+
with st.expander("See Glossary of tags"):
|
192 |
+
st.write('''
|
193 |
+
'**word**': ['entity extracted from your text data']
|
194 |
+
|
195 |
+
'**score**': ['accuracy score; how accurately a tag has been assigned to a given entity']
|
196 |
+
|
197 |
+
'**entity_group**': ['label (tag) assigned to a given extracted entity']
|
198 |
+
|
199 |
+
'**start**': ['index of the start of the corresponding entity']
|
200 |
+
|
201 |
+
'**end**': ['index of the end of the corresponding entity']
|
202 |
+
''')
|
203 |
+
|
204 |
+
|
205 |
+
if not df.empty:
|
206 |
+
|
207 |
+
st.markdown("---")
|
208 |
+
st.subheader("Treemap", divider="rainbow")
|
209 |
+
fig = px.treemap(df, path=[px.Constant("all"), 'entity_group', 'word'],
|
210 |
+
values='score', color='entity_group',
|
211 |
+
)
|
212 |
+
fig.update_layout(margin=dict(t=50, l=25, r=25, b=25))
|
213 |
+
st.plotly_chart(fig, use_container_width=True)
|
214 |
+
if comet_initialized and experiment:
|
215 |
+
experiment.log_figure(figure=fig, figure_name="entity_treemap")
|
216 |
+
|
217 |
+
|
218 |
+
|
219 |
+
value_counts = df['entity_group'].value_counts().reset_index()
|
220 |
+
value_counts.columns = ['entity_group', 'count']
|
221 |
+
|
222 |
+
col1, col2 = st.columns(2)
|
223 |
+
with col1:
|
224 |
+
st.subheader("Pie Chart", divider="rainbow")
|
225 |
+
fig1 = px.pie(value_counts, values='count', names='entity_group',
|
226 |
+
hover_data=['count'], labels={'count': 'count'},
|
227 |
+
title='Percentage of Predicted Labels')
|
228 |
+
fig1.update_traces(textposition='inside', textinfo='percent+label')
|
229 |
+
st.plotly_chart(fig1, use_container_width=True)
|
230 |
+
if comet_initialized and experiment: # Check if experiment is initialized
|
231 |
+
experiment.log_figure(figure=fig1, figure_name="label_pie_chart")
|
232 |
+
|
233 |
+
with col2:
|
234 |
+
st.subheader("Bar Chart", divider="rainbow")
|
235 |
+
fig2 = px.bar(value_counts, x="count", y="entity_group", color="entity_group",
|
236 |
+
text_auto=True, title='Occurrences of Predicted Labels')
|
237 |
+
st.plotly_chart(fig2, use_container_width=True)
|
238 |
+
if comet_initialized and experiment: # Check if experiment is initialized
|
239 |
+
experiment.log_figure(figure=fig2, figure_name="label_bar_chart")
|
240 |
+
else:
|
241 |
+
st.warning("No entities were extracted from the provided text.")
|
242 |
+
|
243 |
+
|
244 |
+
|
245 |
+
dfa = pd.DataFrame(
|
246 |
+
data={
|
247 |
+
'word': ['entity extracted from your text data'],
|
248 |
+
'score': ['accuracy score; how accurately a tag has been assigned to a given entity'],
|
249 |
+
'entity_group': ['label (tag) assigned to a given extracted entity'],
|
250 |
+
'start': ['index of the start of the corresponding entity'],
|
251 |
+
'end': ['index of the end of the corresponding entity'],
|
252 |
+
}
|
253 |
+
)
|
254 |
+
buf = io.BytesIO()
|
255 |
+
with zipfile.ZipFile(buf, "w") as myzip:
|
256 |
+
if not df.empty:
|
257 |
+
myzip.writestr("Summary_of_results.csv", df.to_csv(index=False))
|
258 |
+
myzip.writestr("Glossary_of_tags.csv", dfa.to_csv(index=False))
|
259 |
+
|
260 |
+
with stylable_container(
|
261 |
+
key="download_button",
|
262 |
+
css_styles="""button { background-color: yellow; border: 1px solid black; padding: 5px; color: black; }""",
|
263 |
+
):
|
264 |
+
st.download_button(
|
265 |
+
label="Download zip file",
|
266 |
+
data=buf.getvalue(),
|
267 |
+
file_name="nlpblogs_ner_results.zip",
|
268 |
+
mime="application/zip",)
|
269 |
+
|
270 |
+
|
271 |
+
if comet_initialized and experiment: # Ensure experiment exists before ending
|
272 |
+
experiment.end()
|
273 |
+
else:
|
274 |
+
st.warning("No meaningful text found to process. Please enter a URL or text.")
|
275 |
+
|
276 |
+
except requests.exceptions.RequestException as e:
|
277 |
+
st.error(f"Error fetching the URL: {e}. Please check the URL and your internet connection.")
|
278 |
+
|
279 |
+
st.write(f"Number of times you requested results: **{st.session_state['source_type_attempts']}/{max_attempts}**")
|