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