AIEcosystem commited on
Commit
a3bc5c8
·
verified ·
1 Parent(s): 7a8a10e

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +41 -33
src/streamlit_app.py CHANGED
@@ -1,4 +1,5 @@
1
  import os
 
2
  import time
3
  import streamlit as st
4
  import pandas as pd
@@ -25,7 +26,8 @@ st.markdown(
25
  background-color: #B2F2B2; /* A pale green for the sidebar */
26
  secondary-background-color: #B2F2B2;
27
  }
28
- /* Expander background color */
 
29
  .streamlit-expanderContent {
30
  background-color: #F5FFFA;
31
  }
@@ -63,17 +65,23 @@ st.set_page_config(layout="wide", page_title="Named Entity Recognition App")
63
  st.subheader("HR.ai", divider="orange")
64
  st.link_button("by nlpblogs", "https://nlpblogs.com", type="tertiary")
65
  expander = st.expander("**Important notes**")
66
- expander.write("""**Named Entities:** This HR.ai predicts sixty (60) labels:"Email", "Phone_number", "Street_address", "City", "State", "Zip_code", "Country", "Date_of_birth", "Gender", "Marital_status", "Person", "Full_time", "Part_time", "Contract", "Temporary", "Terminated", "Active", "Retired", "Job_title", "Employment_type", "Year", "Date", "Company", "Organization", "Role", "Position","Performance_review", "Performance_rating", "Performance_score", "Sick_days", "Vacation_days", "Leave_of_absence", "Holidays", "Pension", "Retirement_plan", "Bonus", "Stock_options", "Health_insurance", "Retire_date", "Pay_rate", "Hourly_wage", "Annual_salary", "Overtime_pay", "Tax", "Social_security", "Deductions", "Job_posting", "Job_description", "Interview_type", "Applicant", "Candidate", "Referral", "Job_board", "Recruiter","Contract", "Offer_letter", "Agreement", "Training_course", "Certification", "Skill"
67
- 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.
68
- **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.
69
- **Usage Limits:** You can request results unlimited times for one (1) month.
70
- **Supported Languages:** English, German, French, Italian, Spanish, Portuguese
71
- **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 [email protected]""")
 
72
 
73
  with st.sidebar:
74
  st.write("Use the following code to embed the HR.ai web app on your website. Feel free to adjust the width and height values to fit your page.")
75
  code = '''
76
- <iframe src="https://aiecosystem-hr-ai.hf.space" frameborder="0" width="850" height="450" ></iframe>
 
 
 
 
 
77
  '''
78
  st.code(code, language="html")
79
  st.text("")
@@ -87,6 +95,7 @@ COMET_API_KEY = os.environ.get("COMET_API_KEY")
87
  COMET_WORKSPACE = os.environ.get("COMET_WORKSPACE")
88
  COMET_PROJECT_NAME = os.environ.get("COMET_PROJECT_NAME")
89
  comet_initialized = bool(COMET_API_KEY and COMET_WORKSPACE and COMET_PROJECT_NAME)
 
90
  if not comet_initialized:
91
  st.warning("Comet ML not initialized. Check environment variables.")
92
 
@@ -132,6 +141,7 @@ def clear_text():
132
 
133
  st.button("Clear text", on_click=clear_text)
134
 
 
135
  # --- Results Section ---
136
  if st.button("Results"):
137
  start_time = time.time()
@@ -141,6 +151,7 @@ if st.button("Results"):
141
  with st.spinner("Extracting entities...", show_time=True):
142
  entities = model.predict_entities(text, labels)
143
  df = pd.DataFrame(entities)
 
144
  if not df.empty:
145
  df['category'] = df['label'].map(reverse_category_mapping)
146
  if comet_initialized:
@@ -151,13 +162,13 @@ if st.button("Results"):
151
  )
152
  experiment.log_parameter("input_text", text)
153
  experiment.log_table("predicted_entities", df)
154
-
155
  st.subheader("Extracted Entities", divider = "orange")
156
-
157
  # Create tabs for each category
158
  category_names = sorted(list(category_mapping.keys()))
159
  category_tabs = st.tabs(category_names)
160
-
161
  for i, category_name in enumerate(category_names):
162
  with category_tabs[i]:
163
  df_category_filtered = df[df['category'] == category_name]
@@ -165,7 +176,9 @@ if st.button("Results"):
165
  st.dataframe(df_category_filtered.drop(columns=['category']), use_container_width=True)
166
  else:
167
  st.info(f"No entities found for the '{category_name}' category.")
168
-
 
 
169
  with st.expander("See Glossary of tags"):
170
  st.write('''
171
  - **text**: ['entity extracted from your text data']
@@ -176,22 +189,18 @@ if st.button("Results"):
176
  - **end**: ['index of the end of the corresponding entity']
177
  ''')
178
  st.divider()
179
-
180
  # Tree map
181
  st.subheader("Tree map", divider = "orange")
182
  fig_treemap = px.treemap(df, path=[px.Constant("all"), 'category', 'label', 'text'], values='score', color='category')
183
- fig_treemap.update_layout(
184
- margin=dict(t=50, l=25, r=25, b=25),
185
- paper_bgcolor='#F5FFFA',
186
- plot_bgcolor='#F5FFFA'
187
- )
188
  st.plotly_chart(fig_treemap)
189
-
190
  # Pie and Bar charts
191
  grouped_counts = df['category'].value_counts().reset_index()
192
  grouped_counts.columns = ['category', 'count']
193
  col1, col2 = st.columns(2)
194
-
195
  with col1:
196
  st.subheader("Pie chart", divider = "orange")
197
  fig_pie = px.pie(grouped_counts, values='count', names='category', hover_data=['count'], labels={'count': 'count'}, title='Percentage of predicted categories')
@@ -201,16 +210,16 @@ if st.button("Results"):
201
  plot_bgcolor='#F5FFFA'
202
  )
203
  st.plotly_chart(fig_pie)
204
-
205
  with col2:
206
  st.subheader("Bar chart", divider = "orange")
207
  fig_bar = px.bar(grouped_counts, x="count", y="category", color="category", text_auto=True, title='Occurrences of predicted categories')
208
- fig_bar.update_layout(
209
  paper_bgcolor='#F5FFFA',
210
  plot_bgcolor='#F5FFFA'
211
  )
212
  st.plotly_chart(fig_bar)
213
-
214
  # Most Frequent Entities
215
  st.subheader("Most Frequent Entities", divider="orange")
216
  word_counts = df['text'].value_counts().reset_index()
@@ -219,18 +228,16 @@ if st.button("Results"):
219
  if not repeating_entities.empty:
220
  st.dataframe(repeating_entities, use_container_width=True)
221
  fig_repeating_bar = px.bar(repeating_entities, x='Entity', y='Count', color='Entity')
222
- fig_repeating_bar.update_layout(
223
- xaxis={'categoryorder': 'total descending'},
224
  paper_bgcolor='#F5FFFA',
225
- plot_bgcolor='#F5FFFA'
226
- )
227
  st.plotly_chart(fig_repeating_bar)
228
  else:
229
  st.warning("No entities were found that occur more than once.")
230
-
231
  # Download Section
232
  st.divider()
233
-
234
  dfa = pd.DataFrame(
235
  data={
236
  'Column Name': ['text', 'label', 'score', 'start', 'end', 'category'],
@@ -248,7 +255,7 @@ if st.button("Results"):
248
  with zipfile.ZipFile(buf, "w") as myzip:
249
  myzip.writestr("Summary of the results.csv", df.to_csv(index=False))
250
  myzip.writestr("Glossary of tags.csv", dfa.to_csv(index=False))
251
-
252
  with stylable_container(
253
  key="download_button",
254
  css_styles="""button { background-color: red; border: 1px solid black; padding: 5px; color: white; }""",
@@ -259,14 +266,15 @@ if st.button("Results"):
259
  file_name="nlpblogs_results.zip",
260
  mime="application/zip",
261
  )
262
-
263
  if comet_initialized:
264
  experiment.log_figure(figure=fig_treemap, figure_name="entity_treemap_categories")
265
  experiment.end()
266
  else: # If df is empty
267
  st.warning("No entities were found in the provided text.")
268
- end_time = time.time()
 
269
  elapsed_time = end_time - start_time
270
  st.text("")
271
  st.text("")
272
- st.info(f"Results processed in **{elapsed_time:.2f} seconds**.")
 
1
  import os
2
+ os.environ['HF_HOME'] = '/tmp'
3
  import time
4
  import streamlit as st
5
  import pandas as pd
 
26
  background-color: #B2F2B2; /* A pale green for the sidebar */
27
  secondary-background-color: #B2F2B2;
28
  }
29
+
30
+ /* Expander background color */
31
  .streamlit-expanderContent {
32
  background-color: #F5FFFA;
33
  }
 
65
  st.subheader("HR.ai", divider="orange")
66
  st.link_button("by nlpblogs", "https://nlpblogs.com", type="tertiary")
67
  expander = st.expander("**Important notes**")
68
+ expander.write("""**Named Entities:** This HR.ai predicts sixty (60) labels:"Email", "Phone_number", "Street_address", "City", "State", "Zip_code", "Country", "Date_of_birth", "Gender", "Marital_status", "Person", "Full_time", "Part_time", "Contract", "Temporary", "Terminated", "Active", "Retired", "Job_title", "Employment_type", "Year", "Date", "Company", "Organization", "Role", "Position","Performance_review", "Performance_rating", "Performance_score", "Sick_days", "Vacation_days", "Leave_of_absence", "Holidays", "Pension", "Retirement_plan", "Bonus", "Stock_options", "Health_insurance", "Retire_date", "Pay_rate", "Hourly_wage", "Annual_salary", "Overtime_pay", "Tax", "Social_security", "Deductions", "Job_posting", "Job_description", "Interview_type", "Applicant", "Candidate", "Referral", "Job_board", "Recruiter","Contract", "Offer_letter", "Agreement", "Training_course", "Certification", "Skill"
69
+ 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.
70
+ **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.
71
+ **Usage Limits:** You can request results unlimited times for one (1) month.
72
+ **Supported Languages:** English, German, French, Italian, Spanish, Portuguese
73
+ **Technical issues:** If your connection times out, please refresh the page or reopen the app's URL.
74
+ For any errors or inquiries, please contact us at [email protected]""")
75
 
76
  with st.sidebar:
77
  st.write("Use the following code to embed the HR.ai web app on your website. Feel free to adjust the width and height values to fit your page.")
78
  code = '''
79
+ <iframe
80
+ src="https://aiecosystem-hr-ai.hf.space"
81
+ frameborder="0"
82
+ width="850"
83
+ height="450"
84
+ ></iframe>
85
  '''
86
  st.code(code, language="html")
87
  st.text("")
 
95
  COMET_WORKSPACE = os.environ.get("COMET_WORKSPACE")
96
  COMET_PROJECT_NAME = os.environ.get("COMET_PROJECT_NAME")
97
  comet_initialized = bool(COMET_API_KEY and COMET_WORKSPACE and COMET_PROJECT_NAME)
98
+
99
  if not comet_initialized:
100
  st.warning("Comet ML not initialized. Check environment variables.")
101
 
 
141
 
142
  st.button("Clear text", on_click=clear_text)
143
 
144
+
145
  # --- Results Section ---
146
  if st.button("Results"):
147
  start_time = time.time()
 
151
  with st.spinner("Extracting entities...", show_time=True):
152
  entities = model.predict_entities(text, labels)
153
  df = pd.DataFrame(entities)
154
+
155
  if not df.empty:
156
  df['category'] = df['label'].map(reverse_category_mapping)
157
  if comet_initialized:
 
162
  )
163
  experiment.log_parameter("input_text", text)
164
  experiment.log_table("predicted_entities", df)
165
+
166
  st.subheader("Extracted Entities", divider = "orange")
167
+
168
  # Create tabs for each category
169
  category_names = sorted(list(category_mapping.keys()))
170
  category_tabs = st.tabs(category_names)
171
+
172
  for i, category_name in enumerate(category_names):
173
  with category_tabs[i]:
174
  df_category_filtered = df[df['category'] == category_name]
 
176
  st.dataframe(df_category_filtered.drop(columns=['category']), use_container_width=True)
177
  else:
178
  st.info(f"No entities found for the '{category_name}' category.")
179
+
180
+
181
+
182
  with st.expander("See Glossary of tags"):
183
  st.write('''
184
  - **text**: ['entity extracted from your text data']
 
189
  - **end**: ['index of the end of the corresponding entity']
190
  ''')
191
  st.divider()
192
+
193
  # Tree map
194
  st.subheader("Tree map", divider = "orange")
195
  fig_treemap = px.treemap(df, path=[px.Constant("all"), 'category', 'label', 'text'], values='score', color='category')
196
+ fig_treemap.update_layout(margin=dict(t=50, l=25, r=25, b=25), paper_bgcolor='#F5FFFA', plot_bgcolor='#F5FFFA')
 
 
 
 
197
  st.plotly_chart(fig_treemap)
198
+
199
  # Pie and Bar charts
200
  grouped_counts = df['category'].value_counts().reset_index()
201
  grouped_counts.columns = ['category', 'count']
202
  col1, col2 = st.columns(2)
203
+
204
  with col1:
205
  st.subheader("Pie chart", divider = "orange")
206
  fig_pie = px.pie(grouped_counts, values='count', names='category', hover_data=['count'], labels={'count': 'count'}, title='Percentage of predicted categories')
 
210
  plot_bgcolor='#F5FFFA'
211
  )
212
  st.plotly_chart(fig_pie)
213
+
214
  with col2:
215
  st.subheader("Bar chart", divider = "orange")
216
  fig_bar = px.bar(grouped_counts, x="count", y="category", color="category", text_auto=True, title='Occurrences of predicted categories')
217
+ fig_pie.update_layout(
218
  paper_bgcolor='#F5FFFA',
219
  plot_bgcolor='#F5FFFA'
220
  )
221
  st.plotly_chart(fig_bar)
222
+
223
  # Most Frequent Entities
224
  st.subheader("Most Frequent Entities", divider="orange")
225
  word_counts = df['text'].value_counts().reset_index()
 
228
  if not repeating_entities.empty:
229
  st.dataframe(repeating_entities, use_container_width=True)
230
  fig_repeating_bar = px.bar(repeating_entities, x='Entity', y='Count', color='Entity')
231
+ fig_repeating_bar.update_layout(xaxis={'categoryorder': 'total descending'},
 
232
  paper_bgcolor='#F5FFFA',
233
+ plot_bgcolor='#F5FFFA')
 
234
  st.plotly_chart(fig_repeating_bar)
235
  else:
236
  st.warning("No entities were found that occur more than once.")
237
+
238
  # Download Section
239
  st.divider()
240
+
241
  dfa = pd.DataFrame(
242
  data={
243
  'Column Name': ['text', 'label', 'score', 'start', 'end', 'category'],
 
255
  with zipfile.ZipFile(buf, "w") as myzip:
256
  myzip.writestr("Summary of the results.csv", df.to_csv(index=False))
257
  myzip.writestr("Glossary of tags.csv", dfa.to_csv(index=False))
258
+
259
  with stylable_container(
260
  key="download_button",
261
  css_styles="""button { background-color: red; border: 1px solid black; padding: 5px; color: white; }""",
 
266
  file_name="nlpblogs_results.zip",
267
  mime="application/zip",
268
  )
269
+
270
  if comet_initialized:
271
  experiment.log_figure(figure=fig_treemap, figure_name="entity_treemap_categories")
272
  experiment.end()
273
  else: # If df is empty
274
  st.warning("No entities were found in the provided text.")
275
+
276
+ end_time = time.time()
277
  elapsed_time = end_time - start_time
278
  st.text("")
279
  st.text("")
280
+ st.info(f"Results processed in **{elapsed_time:.2f} seconds**.")