AIEcosystem commited on
Commit
6ff1fb4
·
verified ·
1 Parent(s): e90d33d

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +30 -43
src/streamlit_app.py CHANGED
@@ -7,17 +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
-
18
-
19
-
20
-
21
  # --- Page Configuration and UI Elements ---
22
  st.set_page_config(layout="wide", page_title="Named Entity Recognition App")
23
  st.subheader("DataHarvest", divider="violet")
@@ -27,15 +23,13 @@ st.markdown(':rainbow[**Supported Languages: English**]')
27
  expander = st.expander("**Important notes**")
28
  expander.write("""**Named Entities:** This DataHarvest web app predicts nine (9) labels: "person", "country", "city", "organization", "date", "time", "money", "percent", "position"
29
 
30
- 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.
31
-
32
- **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.
33
 
34
- **Usage Limits:** You can request results unlimited times for one (1) month.
35
 
36
- **Technical issues:** If your connection times out, please refresh the page or reopen the app's URL.
37
 
38
- For any errors or inquiries, please contact us at info@nlpblogs.com""")
39
 
40
  with st.sidebar:
41
  st.write("Use the following code to embed the DataHarvest web app on your website. Feel free to adjust the width and height values to fit your page.")
@@ -46,7 +40,7 @@ with st.sidebar:
46
  width="850"
47
  height="450"
48
  ></iframe>
49
-
50
  '''
51
  st.code(code, language="html")
52
  st.text("")
@@ -60,7 +54,6 @@ COMET_API_KEY = os.environ.get("COMET_API_KEY")
60
  COMET_WORKSPACE = os.environ.get("COMET_WORKSPACE")
61
  COMET_PROJECT_NAME = os.environ.get("COMET_PROJECT_NAME")
62
  comet_initialized = bool(COMET_API_KEY and COMET_WORKSPACE and COMET_PROJECT_NAME)
63
-
64
  if not comet_initialized:
65
  st.warning("Comet ML not initialized. Check environment variables.")
66
 
@@ -68,7 +61,6 @@ if not comet_initialized:
68
  labels = ["person", "country", "city", "organization", "date", "time", "money", "percent", "position"]
69
 
70
  # Corrected mapping dictionary
71
-
72
  # Create a mapping dictionary for labels to categories
73
  category_mapping = {
74
  "People": ["person", "organization", "position"],
@@ -77,9 +69,6 @@ category_mapping = {
77
  "Numbers": ["money", "percent"]
78
  }
79
 
80
-
81
-
82
-
83
  # --- Model Loading ---
84
  @st.cache_resource
85
  def load_ner_model():
@@ -89,6 +78,7 @@ def load_ner_model():
89
  except Exception as e:
90
  st.error(f"Failed to load NER model. Please check your internet connection or model availability: {e}")
91
  st.stop()
 
92
  model = load_ner_model()
93
 
94
  # Flatten the mapping to a single dictionary
@@ -101,8 +91,12 @@ def clear_text():
101
  """Clears the text area."""
102
  st.session_state['my_text_area'] = ""
103
 
104
- st.button("Clear text", on_click=clear_text)
 
 
 
105
 
 
106
 
107
  # --- Results Section ---
108
  if st.button("Results"):
@@ -110,10 +104,12 @@ if st.button("Results"):
110
  if not text.strip():
111
  st.warning("Please enter some text to extract entities.")
112
  else:
 
 
113
  with st.spinner("Extracting entities...", show_time=True):
114
- entities = model.predict_entities(text, labels)
 
115
  df = pd.DataFrame(entities)
116
-
117
  if not df.empty:
118
  df['category'] = df['label'].map(reverse_category_mapping)
119
  if comet_initialized:
@@ -124,13 +120,13 @@ if st.button("Results"):
124
  )
125
  experiment.log_parameter("input_text", text)
126
  experiment.log_table("predicted_entities", df)
127
-
128
  st.subheader("Grouped Entities by Category", divider = "violet")
129
-
130
  # Create tabs for each category
131
  category_names = sorted(list(category_mapping.keys()))
132
  category_tabs = st.tabs(category_names)
133
-
134
  for i, category_name in enumerate(category_names):
135
  with category_tabs[i]:
136
  df_category_filtered = df[df['category'] == category_name]
@@ -139,8 +135,6 @@ if st.button("Results"):
139
  else:
140
  st.info(f"No entities found for the '{category_name}' category.")
141
 
142
-
143
-
144
  with st.expander("See Glossary of tags"):
145
  st.write('''
146
  - **text**: ['entity extracted from your text data']
@@ -150,38 +144,33 @@ if st.button("Results"):
150
  - **end**: ['index of the end of the corresponding entity']
151
  ''')
152
  st.divider()
153
-
154
  # Tree map
155
  st.subheader("Tree map", divider = "violet")
156
  fig_treemap = px.treemap(df, path=[px.Constant("all"), 'category', 'label', 'text'], values='score', color='category')
157
  fig_treemap.update_layout(margin=dict(t=50, l=25, r=25, b=25))
158
  st.plotly_chart(fig_treemap)
159
-
160
  # Pie and Bar charts
161
  grouped_counts = df['category'].value_counts().reset_index()
162
  grouped_counts.columns = ['category', 'count']
163
  col1, col2 = st.columns(2)
164
-
165
  with col1:
166
  st.subheader("Pie chart", divider = "violet")
167
  fig_pie = px.pie(grouped_counts, values='count', names='category', hover_data=['count'], labels={'count': 'count'}, title='Percentage of predicted categories')
168
  fig_pie.update_traces(textposition='inside', textinfo='percent+label')
169
  fig_pie.update_layout(
170
-
171
- )
172
  st.plotly_chart(fig_pie)
173
-
174
-
175
-
176
 
177
  with col2:
178
  st.subheader("Bar chart", divider = "violet")
179
  fig_bar = px.bar(grouped_counts, x="count", y="category", color="category", text_auto=True, title='Occurrences of predicted categories')
180
  fig_bar.update_layout( # Changed from fig_pie to fig_bar
181
-
182
- )
183
  st.plotly_chart(fig_bar)
184
-
185
  # Most Frequent Entities
186
  st.subheader("Most Frequent Entities", divider="violet")
187
  word_counts = df['text'].value_counts().reset_index()
@@ -195,10 +184,10 @@ if st.button("Results"):
195
  st.plotly_chart(fig_repeating_bar)
196
  else:
197
  st.warning("No entities were found that occur more than once.")
198
-
199
  # Download Section
200
  st.divider()
201
-
202
  dfa = pd.DataFrame(
203
  data={
204
  'Column Name': ['text', 'label', 'score', 'start', 'end'],
@@ -208,7 +197,6 @@ if st.button("Results"):
208
  'accuracy score; how accurately a tag has been assigned to a given entity',
209
  'index of the start of the corresponding entity',
210
  'index of the end of the corresponding entity',
211
-
212
  ]
213
  }
214
  )
@@ -216,7 +204,7 @@ if st.button("Results"):
216
  with zipfile.ZipFile(buf, "w") as myzip:
217
  myzip.writestr("Summary of the results.csv", df.to_csv(index=False))
218
  myzip.writestr("Glossary of tags.csv", dfa.to_csv(index=False))
219
-
220
  with stylable_container(
221
  key="download_button",
222
  css_styles="""button { background-color: red; border: 1px solid black; padding: 5px; color: white; }""",
@@ -227,14 +215,13 @@ if st.button("Results"):
227
  file_name="nlpblogs_results.zip",
228
  mime="application/zip",
229
  )
230
-
231
  if comet_initialized:
232
  experiment.log_figure(figure=fig_treemap, figure_name="entity_treemap_categories")
233
  experiment.end()
234
  else: # If df is empty
235
  st.warning("No entities were found in the provided text.")
236
-
237
- end_time = time.time()
238
  elapsed_time = end_time - start_time
239
  st.text("")
240
  st.text("")
 
7
  import plotly.express as px
8
  import zipfile
9
  import json
10
+ import string
11
  from cryptography.fernet import Fernet
12
  from streamlit_extras.stylable_container import stylable_container
13
  from typing import Optional
14
  from gliner import GLiNER
15
  from comet_ml import Experiment
16
 
 
 
 
 
 
17
  # --- Page Configuration and UI Elements ---
18
  st.set_page_config(layout="wide", page_title="Named Entity Recognition App")
19
  st.subheader("DataHarvest", divider="violet")
 
23
  expander = st.expander("**Important notes**")
24
  expander.write("""**Named Entities:** This DataHarvest web app predicts nine (9) labels: "person", "country", "city", "organization", "date", "time", "money", "percent", "position"
25
 
26
+ 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.
 
 
27
 
28
+ **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.
29
 
30
+ **Usage Limits:** You can request results unlimited times for one (1) month.
31
 
32
+ **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""")
33
 
34
  with st.sidebar:
35
  st.write("Use the following code to embed the DataHarvest web app on your website. Feel free to adjust the width and height values to fit your page.")
 
40
  width="850"
41
  height="450"
42
  ></iframe>
43
+
44
  '''
45
  st.code(code, language="html")
46
  st.text("")
 
54
  COMET_WORKSPACE = os.environ.get("COMET_WORKSPACE")
55
  COMET_PROJECT_NAME = os.environ.get("COMET_PROJECT_NAME")
56
  comet_initialized = bool(COMET_API_KEY and COMET_WORKSPACE and COMET_PROJECT_NAME)
 
57
  if not comet_initialized:
58
  st.warning("Comet ML not initialized. Check environment variables.")
59
 
 
61
  labels = ["person", "country", "city", "organization", "date", "time", "money", "percent", "position"]
62
 
63
  # Corrected mapping dictionary
 
64
  # Create a mapping dictionary for labels to categories
65
  category_mapping = {
66
  "People": ["person", "organization", "position"],
 
69
  "Numbers": ["money", "percent"]
70
  }
71
 
 
 
 
72
  # --- Model Loading ---
73
  @st.cache_resource
74
  def load_ner_model():
 
78
  except Exception as e:
79
  st.error(f"Failed to load NER model. Please check your internet connection or model availability: {e}")
80
  st.stop()
81
+
82
  model = load_ner_model()
83
 
84
  # Flatten the mapping to a single dictionary
 
91
  """Clears the text area."""
92
  st.session_state['my_text_area'] = ""
93
 
94
+ def remove_punctuation(text):
95
+ """Removes punctuation from a string."""
96
+ translator = str.maketrans('', '', string.punctuation)
97
+ return text.translate(translator)
98
 
99
+ st.button("Clear text", on_click=clear_text)
100
 
101
  # --- Results Section ---
102
  if st.button("Results"):
 
104
  if not text.strip():
105
  st.warning("Please enter some text to extract entities.")
106
  else:
107
+ # Call the new function to remove punctuation from the input text
108
+ cleaned_text = remove_punctuation(text)
109
  with st.spinner("Extracting entities...", show_time=True):
110
+ # Use the cleaned text for prediction
111
+ entities = model.predict_entities(cleaned_text, labels)
112
  df = pd.DataFrame(entities)
 
113
  if not df.empty:
114
  df['category'] = df['label'].map(reverse_category_mapping)
115
  if comet_initialized:
 
120
  )
121
  experiment.log_parameter("input_text", text)
122
  experiment.log_table("predicted_entities", df)
123
+
124
  st.subheader("Grouped Entities by Category", divider = "violet")
125
+
126
  # Create tabs for each category
127
  category_names = sorted(list(category_mapping.keys()))
128
  category_tabs = st.tabs(category_names)
129
+
130
  for i, category_name in enumerate(category_names):
131
  with category_tabs[i]:
132
  df_category_filtered = df[df['category'] == category_name]
 
135
  else:
136
  st.info(f"No entities found for the '{category_name}' category.")
137
 
 
 
138
  with st.expander("See Glossary of tags"):
139
  st.write('''
140
  - **text**: ['entity extracted from your text data']
 
144
  - **end**: ['index of the end of the corresponding entity']
145
  ''')
146
  st.divider()
147
+
148
  # Tree map
149
  st.subheader("Tree map", divider = "violet")
150
  fig_treemap = px.treemap(df, path=[px.Constant("all"), 'category', 'label', 'text'], values='score', color='category')
151
  fig_treemap.update_layout(margin=dict(t=50, l=25, r=25, b=25))
152
  st.plotly_chart(fig_treemap)
153
+
154
  # Pie and Bar charts
155
  grouped_counts = df['category'].value_counts().reset_index()
156
  grouped_counts.columns = ['category', 'count']
157
  col1, col2 = st.columns(2)
158
+
159
  with col1:
160
  st.subheader("Pie chart", divider = "violet")
161
  fig_pie = px.pie(grouped_counts, values='count', names='category', hover_data=['count'], labels={'count': 'count'}, title='Percentage of predicted categories')
162
  fig_pie.update_traces(textposition='inside', textinfo='percent+label')
163
  fig_pie.update_layout(
164
+ )
 
165
  st.plotly_chart(fig_pie)
 
 
 
166
 
167
  with col2:
168
  st.subheader("Bar chart", divider = "violet")
169
  fig_bar = px.bar(grouped_counts, x="count", y="category", color="category", text_auto=True, title='Occurrences of predicted categories')
170
  fig_bar.update_layout( # Changed from fig_pie to fig_bar
171
+ )
 
172
  st.plotly_chart(fig_bar)
173
+
174
  # Most Frequent Entities
175
  st.subheader("Most Frequent Entities", divider="violet")
176
  word_counts = df['text'].value_counts().reset_index()
 
184
  st.plotly_chart(fig_repeating_bar)
185
  else:
186
  st.warning("No entities were found that occur more than once.")
187
+
188
  # Download Section
189
  st.divider()
190
+
191
  dfa = pd.DataFrame(
192
  data={
193
  'Column Name': ['text', 'label', 'score', 'start', 'end'],
 
197
  'accuracy score; how accurately a tag has been assigned to a given entity',
198
  'index of the start of the corresponding entity',
199
  'index of the end of the corresponding entity',
 
200
  ]
201
  }
202
  )
 
204
  with zipfile.ZipFile(buf, "w") as myzip:
205
  myzip.writestr("Summary of the results.csv", df.to_csv(index=False))
206
  myzip.writestr("Glossary of tags.csv", dfa.to_csv(index=False))
207
+
208
  with stylable_container(
209
  key="download_button",
210
  css_styles="""button { background-color: red; border: 1px solid black; padding: 5px; color: white; }""",
 
215
  file_name="nlpblogs_results.zip",
216
  mime="application/zip",
217
  )
218
+
219
  if comet_initialized:
220
  experiment.log_figure(figure=fig_treemap, figure_name="entity_treemap_categories")
221
  experiment.end()
222
  else: # If df is empty
223
  st.warning("No entities were found in the provided text.")
224
+ end_time = time.time()
 
225
  elapsed_time = end_time - start_time
226
  st.text("")
227
  st.text("")