AIEcosystem commited on
Commit
6510d04
·
verified ·
1 Parent(s): f1761cd

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +331 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,333 @@
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("RetailTag", 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 RetailTag web app predicts eighteen (18) labels:
76
+ "Product_Name", "Product_Type", "Brand", "Model_Number", "SKU", "Product_Attribute", "Service_Type", "Order_Number", "Monetary_Value", "Payment_Method", "Discount", "Shipping_Method", "Quantity", "Organization", "Location", "Person", "Date", "Time"
77
+
78
+ 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.
79
+
80
+ **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.
81
+
82
+ **Usage Limits:** You can request results unlimited times for one (1) month.
83
+
84
+ **Supported Languages:** English
85
+
86
+ **Technical issues:** If your connection times out, please refresh the page or reopen the app's URL.
87
+
88
+ For any errors or inquiries, please contact us at info@nlpblogs.com""")
89
+
90
+ with st.sidebar:
91
+ st.write("Use the following code to embed the RetailTag web app on your website. Feel free to adjust the width and height values to fit your page.")
92
+ code = '''
93
+ <iframe
94
+ src="https://aiecosystem-chainsense.hf.space"
95
+ frameborder="0"
96
+ width="850"
97
+ height="450"
98
+ ></iframe>
99
+
100
+ '''
101
+ st.code(code, language="html")
102
+ st.text("")
103
+ st.text("")
104
+ st.divider()
105
+ st.subheader("🚀 Ready to build your own AI Web App?", divider="violet")
106
+ st.link_button("AI Web App Builder", " https://nlpblogs.com/custom-web-app-development/", type="primary")
107
+
108
+ # --- Comet ML Setup ---
109
+ COMET_API_KEY = os.environ.get("COMET_API_KEY")
110
+ COMET_WORKSPACE = os.environ.get("COMET_WORKSPACE")
111
+ COMET_PROJECT_NAME = os.environ.get("COMET_PROJECT_NAME")
112
+ comet_initialized = bool(COMET_API_KEY and COMET_WORKSPACE and COMET_PROJECT_NAME)
113
+
114
+ if not comet_initialized:
115
+ st.warning("Comet ML not initialized. Check environment variables.")
116
+
117
+ # --- Label Definitions ---
118
+ [
119
+ "Product_Name",
120
+ "Product_Type",
121
+ "Brand",
122
+ "Model_Number",
123
+ "SKU",
124
+ "Product_Attribute",
125
+ "Service_Type",
126
+ "Order_Number",
127
+ "Monetary_Value",
128
+ "Payment_Method",
129
+ "Discount",
130
+ "Shipping_Method",
131
+ "Quantity",
132
+ "Organization",
133
+ "Location",
134
+ "Person",
135
+ "Date",
136
+ "Time"
137
+ ]
138
+
139
+
140
+ # Corrected mapping dictionary
141
+
142
+ # Create a mapping dictionary for labels to categories
143
+ category_mapping = {
144
+ "Product & Service Entities": [
145
+ "Product_Name",
146
+ "Product_Type",
147
+ "Brand",
148
+ "Model_Number",
149
+ "SKU",
150
+ "Product_Attribute",
151
+ "Service_Type"
152
+ ],
153
+ "Transaction & Order Entities": [
154
+ "Order_Number",
155
+ "Monetary_Value",
156
+ "Payment_Method",
157
+ "Discount",
158
+ "Shipping_Method",
159
+ "Quantity"
160
+ ],
161
+ "General Entities": [
162
+ "Organization",
163
+ "Location",
164
+ "Person",
165
+ "Date",
166
+ "Time"
167
+ ]
168
+ }
169
+
170
+
171
+
172
+ # --- Model Loading ---
173
+ @st.cache_resource
174
+ def load_ner_model():
175
+ """Loads the GLiNER model and caches it."""
176
+ try:
177
+ return GLiNER.from_pretrained("gliner-community/gliner_large-v2.5", nested_ner=True, num_gen_sequences=2, gen_constraints= labels)
178
+ except Exception as e:
179
+ st.error(f"Failed to load NER model. Please check your internet connection or model availability: {e}")
180
+ st.stop()
181
+ model = load_ner_model()
182
+
183
+ # Flatten the mapping to a single dictionary
184
+ reverse_category_mapping = {label: category for category, label_list in category_mapping.items() for label in label_list}
185
+
186
+ # --- Text Input and Clear Button ---
187
+ text = st.text_area("Type or paste your text below, and then press Ctrl + Enter", height=250, key='my_text_area')
188
+
189
+ def clear_text():
190
+ """Clears the text area."""
191
+ st.session_state['my_text_area'] = ""
192
+
193
+ st.button("Clear text", on_click=clear_text)
194
+
195
+
196
+ # --- Results Section ---
197
+ if st.button("Results"):
198
+ start_time = time.time()
199
+ if not text.strip():
200
+ st.warning("Please enter some text to extract entities.")
201
+ else:
202
+ with st.spinner("Extracting entities...", show_time=True):
203
+ entities = model.predict_entities(text, labels)
204
+ df = pd.DataFrame(entities)
205
+
206
+ if not df.empty:
207
+ df['category'] = df['label'].map(reverse_category_mapping)
208
+ if comet_initialized:
209
+ experiment = Experiment(
210
+ api_key=COMET_API_KEY,
211
+ workspace=COMET_WORKSPACE,
212
+ project_name=COMET_PROJECT_NAME,
213
+ )
214
+ experiment.log_parameter("input_text", text)
215
+ experiment.log_table("predicted_entities", df)
216
+
217
+ st.subheader("Grouped Entities by Category", divider = "violet")
218
+
219
+ # Create tabs for each category
220
+ category_names = sorted(list(category_mapping.keys()))
221
+ category_tabs = st.tabs(category_names)
222
+
223
+ for i, category_name in enumerate(category_names):
224
+ with category_tabs[i]:
225
+ df_category_filtered = df[df['category'] == category_name]
226
+ if not df_category_filtered.empty:
227
+ st.dataframe(df_category_filtered.drop(columns=['category']), use_container_width=True)
228
+ else:
229
+ st.info(f"No entities found for the '{category_name}' category.")
230
+
231
+
232
+
233
+ with st.expander("See Glossary of tags"):
234
+ st.write('''
235
+ - **text**: ['entity extracted from your text data']
236
+ - **score**: ['accuracy score; how accurately a tag has been assigned to a given entity']
237
+ - **label**: ['label (tag) assigned to a given extracted entity']
238
+ - **start**: ['index of the start of the corresponding entity']
239
+ - **end**: ['index of the end of the corresponding entity']
240
+ ''')
241
+ st.divider()
242
+
243
+ # Tree map
244
+ st.subheader("Tree map", divider = "violet")
245
+ fig_treemap = px.treemap(df, path=[px.Constant("all"), 'category', 'label', 'text'], values='score', color='category')
246
+ fig_treemap.update_layout(margin=dict(t=50, l=25, r=25, b=25), paper_bgcolor='#E8F5E9', plot_bgcolor='#E8F5E9')
247
+ st.plotly_chart(fig_treemap)
248
+
249
+ # Pie and Bar charts
250
+ grouped_counts = df['category'].value_counts().reset_index()
251
+ grouped_counts.columns = ['category', 'count']
252
+ col1, col2 = st.columns(2)
253
+
254
+ with col1:
255
+ st.subheader("Pie chart", divider = "violet")
256
+ fig_pie = px.pie(grouped_counts, values='count', names='category', hover_data=['count'], labels={'count': 'count'}, title='Percentage of predicted categories')
257
+ fig_pie.update_traces(textposition='inside', textinfo='percent+label')
258
+ fig_pie.update_layout(
259
+ paper_bgcolor='#E8F5E9',
260
+ plot_bgcolor='#E8F5E9'
261
+ )
262
+ st.plotly_chart(fig_pie)
263
+
264
+
265
+
266
 
267
+ with col2:
268
+ st.subheader("Bar chart", divider = "violet")
269
+ fig_bar = px.bar(grouped_counts, x="count", y="category", color="category", text_auto=True, title='Occurrences of predicted categories')
270
+ fig_bar.update_layout( # Changed from fig_pie to fig_bar
271
+ paper_bgcolor='#E8F5E9',
272
+ plot_bgcolor='#E8F5E9'
273
+ )
274
+ st.plotly_chart(fig_bar)
275
+
276
+ # Most Frequent Entities
277
+ st.subheader("Most Frequent Entities", divider="violet")
278
+ word_counts = df['text'].value_counts().reset_index()
279
+ word_counts.columns = ['Entity', 'Count']
280
+ repeating_entities = word_counts[word_counts['Count'] > 1]
281
+ if not repeating_entities.empty:
282
+ st.dataframe(repeating_entities, use_container_width=True)
283
+ fig_repeating_bar = px.bar(repeating_entities, x='Entity', y='Count', color='Entity')
284
+ fig_repeating_bar.update_layout(xaxis={'categoryorder': 'total descending'},
285
+ paper_bgcolor='#E8F5E9',
286
+ plot_bgcolor='#E8F5E9')
287
+ st.plotly_chart(fig_repeating_bar)
288
+ else:
289
+ st.warning("No entities were found that occur more than once.")
290
+
291
+ # Download Section
292
+ st.divider()
293
+
294
+ dfa = pd.DataFrame(
295
+ data={
296
+ 'Column Name': ['text', 'label', 'score', 'start', 'end'],
297
+ 'Description': [
298
+ 'entity extracted from your text data',
299
+ 'label (tag) assigned to a given extracted entity',
300
+ 'accuracy score; how accurately a tag has been assigned to a given entity',
301
+ 'index of the start of the corresponding entity',
302
+ 'index of the end of the corresponding entity',
303
+
304
+ ]
305
+ }
306
+ )
307
+ buf = io.BytesIO()
308
+ with zipfile.ZipFile(buf, "w") as myzip:
309
+ myzip.writestr("Summary of the results.csv", df.to_csv(index=False))
310
+ myzip.writestr("Glossary of tags.csv", dfa.to_csv(index=False))
311
+
312
+ with stylable_container(
313
+ key="download_button",
314
+ css_styles="""button { background-color: red; border: 1px solid black; padding: 5px; color: white; }""",
315
+ ):
316
+ st.download_button(
317
+ label="Download results and glossary (zip)",
318
+ data=buf.getvalue(),
319
+ file_name="nlpblogs_results.zip",
320
+ mime="application/zip",
321
+ )
322
+
323
+ if comet_initialized:
324
+ experiment.log_figure(figure=fig_treemap, figure_name="entity_treemap_categories")
325
+ experiment.end()
326
+ else: # If df is empty
327
+ st.warning("No entities were found in the provided text.")
328
+
329
+ end_time = time.time()
330
+ elapsed_time = end_time - start_time
331
+ st.text("")
332
+ st.text("")
333
+ st.info(f"Results processed in **{elapsed_time:.2f} seconds**.")