AIEcosystem commited on
Commit
6a6aa81
·
verified ·
1 Parent(s): 79c885d

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +51 -66
src/streamlit_app.py CHANGED
@@ -7,13 +7,13 @@ 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>
@@ -22,36 +22,36 @@ st.markdown(
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 */
@@ -61,10 +61,6 @@ st.markdown(
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")
@@ -72,44 +68,41 @@ 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
- 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.
78
- **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.
79
- **Usage Limits:** You can request results unlimited times for one (1) month.
80
- **Supported Languages:** English
81
- **Technical issues:** If your connection times out, please refresh the page or reopen the app's URL.
82
- For any errors or inquiries, please contact us at info@nlpblogs.com""")
 
 
83
 
84
  with st.sidebar:
85
  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.")
86
  code = '''
87
- <iframe
88
- src="https://aiecosystem-retailtag.hf.space"
89
- frameborder="0"
90
- width="850"
91
- height="450"
92
- ></iframe>
93
-
94
  '''
95
  st.code(code, language="html")
96
  st.text("")
97
  st.text("")
98
  st.divider()
99
  st.subheader("🚀 Ready to build your own AI Web App?", divider="violet")
100
- st.link_button("AI Web App Builder", " https://nlpblogs.com/custom-web-app-development/", type="primary")
101
 
102
  # --- Comet ML Setup ---
103
  COMET_API_KEY = os.environ.get("COMET_API_KEY")
104
  COMET_WORKSPACE = os.environ.get("COMET_WORKSPACE")
105
  COMET_PROJECT_NAME = os.environ.get("COMET_PROJECT_NAME")
106
  comet_initialized = bool(COMET_API_KEY and COMET_WORKSPACE and COMET_PROJECT_NAME)
107
-
108
  if not comet_initialized:
109
  st.warning("Comet ML not initialized. Check environment variables.")
110
 
111
  # --- Label Definitions ---
112
- [
 
113
  "Product_Name",
114
  "Product_Type",
115
  "Brand",
@@ -130,9 +123,6 @@ if not comet_initialized:
130
  "Time"
131
  ]
132
 
133
-
134
- # Corrected mapping dictionary
135
-
136
  # Create a mapping dictionary for labels to categories
137
  category_mapping = {
138
  "Product & Service Entities": [
@@ -161,17 +151,17 @@ category_mapping = {
161
  ]
162
  }
163
 
164
-
165
-
166
  # --- Model Loading ---
167
  @st.cache_resource
168
  def load_ner_model():
169
  """Loads the GLiNER model and caches it."""
170
  try:
171
- return GLiNER.from_pretrained("knowledgator/gliner-multitask-large-v0.5", nested_ner=True, num_gen_sequences=2, gen_constraints= labels)
 
172
  except Exception as e:
173
  st.error(f"Failed to load NER model. Please check your internet connection or model availability: {e}")
174
  st.stop()
 
175
  model = load_ner_model()
176
 
177
  # Flatten the mapping to a single dictionary
@@ -183,10 +173,8 @@ text = st.text_area("Type or paste your text below, and then press Ctrl + Enter"
183
  def clear_text():
184
  """Clears the text area."""
185
  st.session_state['my_text_area'] = ""
186
-
187
  st.button("Clear text", on_click=clear_text)
188
 
189
-
190
  # --- Results Section ---
191
  if st.button("Results"):
192
  start_time = time.time()
@@ -196,9 +184,10 @@ if st.button("Results"):
196
  with st.spinner("Extracting entities...", show_time=True):
197
  entities = model.predict_entities(text, labels)
198
  df = pd.DataFrame(entities)
199
-
200
  if not df.empty:
201
  df['category'] = df['label'].map(reverse_category_mapping)
 
202
  if comet_initialized:
203
  experiment = Experiment(
204
  api_key=COMET_API_KEY,
@@ -208,7 +197,7 @@ if st.button("Results"):
208
  experiment.log_parameter("input_text", text)
209
  experiment.log_table("predicted_entities", df)
210
 
211
- st.subheader("Grouped Entities by Category", divider = "violet")
212
 
213
  # Create tabs for each category
214
  category_names = sorted(list(category_mapping.keys()))
@@ -222,8 +211,6 @@ if st.button("Results"):
222
  else:
223
  st.info(f"No entities found for the '{category_name}' category.")
224
 
225
-
226
-
227
  with st.expander("See Glossary of tags"):
228
  st.write('''
229
  - **text**: ['entity extracted from your text data']
@@ -233,20 +220,20 @@ if st.button("Results"):
233
  - **end**: ['index of the end of the corresponding entity']
234
  ''')
235
  st.divider()
236
-
237
  # Tree map
238
- st.subheader("Tree map", divider = "violet")
239
  fig_treemap = px.treemap(df, path=[px.Constant("all"), 'category', 'label', 'text'], values='score', color='category')
240
  fig_treemap.update_layout(margin=dict(t=50, l=25, r=25, b=25), paper_bgcolor='#E8F5E9', plot_bgcolor='#E8F5E9')
241
  st.plotly_chart(fig_treemap)
242
-
243
  # Pie and Bar charts
244
  grouped_counts = df['category'].value_counts().reset_index()
245
  grouped_counts.columns = ['category', 'count']
246
  col1, col2 = st.columns(2)
247
-
248
  with col1:
249
- st.subheader("Pie chart", divider = "violet")
250
  fig_pie = px.pie(grouped_counts, values='count', names='category', hover_data=['count'], labels={'count': 'count'}, title='Percentage of predicted categories')
251
  fig_pie.update_traces(textposition='inside', textinfo='percent+label')
252
  fig_pie.update_layout(
@@ -254,19 +241,16 @@ if st.button("Results"):
254
  plot_bgcolor='#E8F5E9'
255
  )
256
  st.plotly_chart(fig_pie)
257
-
258
-
259
-
260
 
261
  with col2:
262
- st.subheader("Bar chart", divider = "violet")
263
  fig_bar = px.bar(grouped_counts, x="count", y="category", color="category", text_auto=True, title='Occurrences of predicted categories')
264
- fig_bar.update_layout( # Changed from fig_pie to fig_bar
265
  paper_bgcolor='#E8F5E9',
266
  plot_bgcolor='#E8F5E9'
267
  )
268
  st.plotly_chart(fig_bar)
269
-
270
  # Most Frequent Entities
271
  st.subheader("Most Frequent Entities", divider="violet")
272
  word_counts = df['text'].value_counts().reset_index()
@@ -275,16 +259,18 @@ if st.button("Results"):
275
  if not repeating_entities.empty:
276
  st.dataframe(repeating_entities, use_container_width=True)
277
  fig_repeating_bar = px.bar(repeating_entities, x='Entity', y='Count', color='Entity')
278
- fig_repeating_bar.update_layout(xaxis={'categoryorder': 'total descending'},
 
279
  paper_bgcolor='#E8F5E9',
280
- plot_bgcolor='#E8F5E9')
 
281
  st.plotly_chart(fig_repeating_bar)
282
  else:
283
  st.warning("No entities were found that occur more than once.")
284
-
285
  # Download Section
286
  st.divider()
287
-
288
  dfa = pd.DataFrame(
289
  data={
290
  'Column Name': ['text', 'label', 'score', 'start', 'end'],
@@ -294,7 +280,6 @@ if st.button("Results"):
294
  'accuracy score; how accurately a tag has been assigned to a given entity',
295
  'index of the start of the corresponding entity',
296
  'index of the end of the corresponding entity',
297
-
298
  ]
299
  }
300
  )
@@ -302,10 +287,10 @@ if st.button("Results"):
302
  with zipfile.ZipFile(buf, "w") as myzip:
303
  myzip.writestr("Summary of the results.csv", df.to_csv(index=False))
304
  myzip.writestr("Glossary of tags.csv", dfa.to_csv(index=False))
305
-
306
  with stylable_container(
307
  key="download_button",
308
- css_styles="""button { background-color: red; border: 1px solid black; padding: 5px; color: white; }""",
309
  ):
310
  st.download_button(
311
  label="Download results and glossary (zip)",
@@ -313,15 +298,15 @@ if st.button("Results"):
313
  file_name="nlpblogs_results.zip",
314
  mime="application/zip",
315
  )
316
-
317
  if comet_initialized:
318
  experiment.log_figure(figure=fig_treemap, figure_name="entity_treemap_categories")
319
  experiment.end()
320
  else: # If df is empty
321
  st.warning("No entities were found in the provided text.")
322
-
323
- end_time = time.time()
324
- elapsed_time = end_time - start_time
325
- st.text("")
326
- st.text("")
327
- st.info(f"Results processed in **{elapsed_time:.2f} seconds**.")
 
7
  import plotly.express as px
8
  import zipfile
9
  import json
10
+ from cryptography.fernet import Fernet # This import is not used
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
+ # --- CSS Styling for the App ---
17
  st.markdown(
18
  """
19
  <style>
 
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 */
 
61
  """,
62
  unsafe_allow_html=True
63
  )
 
 
 
 
64
 
65
  # --- Page Configuration and UI Elements ---
66
  st.set_page_config(layout="wide", page_title="Named Entity Recognition App")
 
68
  st.link_button("by nlpblogs", "https://nlpblogs.com", type="tertiary")
69
 
70
  expander = st.expander("**Important notes**")
71
+ expander.write("""
72
+ **Named Entities:** This RetailTag web app predicts eighteen (18) labels:
73
  "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"
74
+ 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.
75
+
76
+ **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.
77
+
78
+ **Usage Limits:** You can request results unlimited times for one (1) month.
79
+
80
+ **Supported Languages:** English
81
+ **Technical issues:** If your connection times out, please refresh the page or reopen the app's URL. 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 RetailTag web app on your website. Feel free to adjust the width and height values to fit your page.")
85
  code = '''
86
+ <iframe src="https://aiecosystem-chainsense.hf.space" frameborder="0" width="850" height="450"></iframe>
 
 
 
 
 
 
87
  '''
88
  st.code(code, language="html")
89
  st.text("")
90
  st.text("")
91
  st.divider()
92
  st.subheader("🚀 Ready to build your own AI Web App?", divider="violet")
93
+ st.link_button("AI Web App Builder", "https://nlpblogs.com/custom-web-app-development/", type="primary")
94
 
95
  # --- Comet ML Setup ---
96
  COMET_API_KEY = os.environ.get("COMET_API_KEY")
97
  COMET_WORKSPACE = os.environ.get("COMET_WORKSPACE")
98
  COMET_PROJECT_NAME = os.environ.get("COMET_PROJECT_NAME")
99
  comet_initialized = bool(COMET_API_KEY and COMET_WORKSPACE and COMET_PROJECT_NAME)
 
100
  if not comet_initialized:
101
  st.warning("Comet ML not initialized. Check environment variables.")
102
 
103
  # --- Label Definitions ---
104
+ # The list of labels is assigned to a variable for use in the model loading function
105
+ labels = [
106
  "Product_Name",
107
  "Product_Type",
108
  "Brand",
 
123
  "Time"
124
  ]
125
 
 
 
 
126
  # Create a mapping dictionary for labels to categories
127
  category_mapping = {
128
  "Product & Service Entities": [
 
151
  ]
152
  }
153
 
 
 
154
  # --- Model Loading ---
155
  @st.cache_resource
156
  def load_ner_model():
157
  """Loads the GLiNER model and caches it."""
158
  try:
159
+ # The 'labels' variable is now correctly passed to the function
160
+ return GLiNER.from_pretrained("knowledgator/gliner-multitask-large-v0.5", nested_ner=True, num_gen_sequences=2, gen_constraints=labels)
161
  except Exception as e:
162
  st.error(f"Failed to load NER model. Please check your internet connection or model availability: {e}")
163
  st.stop()
164
+
165
  model = load_ner_model()
166
 
167
  # Flatten the mapping to a single dictionary
 
173
  def clear_text():
174
  """Clears the text area."""
175
  st.session_state['my_text_area'] = ""
 
176
  st.button("Clear text", on_click=clear_text)
177
 
 
178
  # --- Results Section ---
179
  if st.button("Results"):
180
  start_time = time.time()
 
184
  with st.spinner("Extracting entities...", show_time=True):
185
  entities = model.predict_entities(text, labels)
186
  df = pd.DataFrame(entities)
187
+
188
  if not df.empty:
189
  df['category'] = df['label'].map(reverse_category_mapping)
190
+
191
  if comet_initialized:
192
  experiment = Experiment(
193
  api_key=COMET_API_KEY,
 
197
  experiment.log_parameter("input_text", text)
198
  experiment.log_table("predicted_entities", df)
199
 
200
+ st.subheader("Grouped Entities by Category", divider="violet")
201
 
202
  # Create tabs for each category
203
  category_names = sorted(list(category_mapping.keys()))
 
211
  else:
212
  st.info(f"No entities found for the '{category_name}' category.")
213
 
 
 
214
  with st.expander("See Glossary of tags"):
215
  st.write('''
216
  - **text**: ['entity extracted from your text data']
 
220
  - **end**: ['index of the end of the corresponding entity']
221
  ''')
222
  st.divider()
223
+
224
  # Tree map
225
+ st.subheader("Tree map", divider="violet")
226
  fig_treemap = px.treemap(df, path=[px.Constant("all"), 'category', 'label', 'text'], values='score', color='category')
227
  fig_treemap.update_layout(margin=dict(t=50, l=25, r=25, b=25), paper_bgcolor='#E8F5E9', plot_bgcolor='#E8F5E9')
228
  st.plotly_chart(fig_treemap)
229
+
230
  # Pie and Bar charts
231
  grouped_counts = df['category'].value_counts().reset_index()
232
  grouped_counts.columns = ['category', 'count']
233
  col1, col2 = st.columns(2)
234
+
235
  with col1:
236
+ st.subheader("Pie chart", divider="violet")
237
  fig_pie = px.pie(grouped_counts, values='count', names='category', hover_data=['count'], labels={'count': 'count'}, title='Percentage of predicted categories')
238
  fig_pie.update_traces(textposition='inside', textinfo='percent+label')
239
  fig_pie.update_layout(
 
241
  plot_bgcolor='#E8F5E9'
242
  )
243
  st.plotly_chart(fig_pie)
 
 
 
244
 
245
  with col2:
246
+ st.subheader("Bar chart", divider="violet")
247
  fig_bar = px.bar(grouped_counts, x="count", y="category", color="category", text_auto=True, title='Occurrences of predicted categories')
248
+ fig_bar.update_layout(
249
  paper_bgcolor='#E8F5E9',
250
  plot_bgcolor='#E8F5E9'
251
  )
252
  st.plotly_chart(fig_bar)
253
+
254
  # Most Frequent Entities
255
  st.subheader("Most Frequent Entities", divider="violet")
256
  word_counts = df['text'].value_counts().reset_index()
 
259
  if not repeating_entities.empty:
260
  st.dataframe(repeating_entities, use_container_width=True)
261
  fig_repeating_bar = px.bar(repeating_entities, x='Entity', y='Count', color='Entity')
262
+ fig_repeating_bar.update_layout(
263
+ xaxis={'categoryorder': 'total descending'},
264
  paper_bgcolor='#E8F5E9',
265
+ plot_bgcolor='#E8F5E9'
266
+ )
267
  st.plotly_chart(fig_repeating_bar)
268
  else:
269
  st.warning("No entities were found that occur more than once.")
270
+
271
  # Download Section
272
  st.divider()
273
+
274
  dfa = pd.DataFrame(
275
  data={
276
  'Column Name': ['text', 'label', 'score', 'start', 'end'],
 
280
  'accuracy score; how accurately a tag has been assigned to a given entity',
281
  'index of the start of the corresponding entity',
282
  'index of the end of the corresponding entity',
 
283
  ]
284
  }
285
  )
 
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: #81C784; border: 1px solid black; padding: 5px; color: #1B5E20; }""",
294
  ):
295
  st.download_button(
296
  label="Download results and glossary (zip)",
 
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**.")