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