AIEcosystem commited on
Commit
4d27e51
·
verified ·
1 Parent(s): ad0e013

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +327 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,329 @@
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: #F5FFFA; /* Mint cream, a very light green */
23
+ color: #000000; /* Black for the text */
24
+ }
25
+ /* Sidebar background color */
26
+ .css-1d36184 {
27
+ background-color: #B2F2B2; /* A pale green for the sidebar */
28
+ secondary-background-color: #B2F2B2;
29
+ }
30
+
31
+ /* Expander background color */
32
+ .streamlit-expanderContent {
33
+ background-color: #F5FFFA;
34
+ }
35
+ /* Expander header background color */
36
+ .streamlit-expanderHeader {
37
+ background-color: #F5FFFA;
38
+ }
39
+ /* Text Area background and text color */
40
+ .stTextArea textarea {
41
+ background-color: #D4F4D4; /* A light, soft green */
42
+ color: #000000; /* Black for text */
43
+ }
44
+ /* Button background and text color */
45
+ .stButton > button {
46
+ background-color: #D4F4D4;
47
+ color: #000000;
48
+ }
49
+ /* Warning box background and text color */
50
+ .stAlert.st-warning {
51
+ background-color: #C8F0C8; /* A light green for the warning box */
52
+ color: #000000;
53
+ }
54
+ /* Success box background and text color */
55
+ .stAlert.st-success {
56
+ background-color: #C8F0C8; /* A light green for the success box */
57
+ color: #000000;
58
+ }
59
+ </style>
60
+ """,
61
+ unsafe_allow_html=True
62
+ )
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
+
72
+ st.subheader("HR.ai", divider="orange")
73
+ st.link_button("by nlpblogs", "https://nlpblogs.com", type="tertiary")
74
+
75
+ expander = st.expander("**Important notes on the Human Resources**")
76
+ expander.write("""
77
+ **Named Entities:** This HR.ai predicts twenty-four (24) labels:
78
+ "Email_address", "Phone_number", "Street_address", "City", "State", "Zip_code",
79
+ "Date_of_birth", "Gender", "Marital_status", "Full_name",
80
+ "Full_time", "Part_time", "Contract", "Temporary", "Terminated", "Active", "Retired",
81
+ "Job_title", "Employment_type", "Start_date", "End_date", "Company", "Organization", "Role", "Position",
82
+ "Performance_review", "Performance_rating", "Performance_score",
83
+ "Sick_days", "Vacation_days", "Leave_of_absence", "Holidays",
84
+ "Pension", "Retirement_plan", "Bonus", "Stock_options", "Health_insurance","Retire_date",
85
+ "Pay_rate", "Hourly_wage", "Annual_salary", "Overtime_pay",
86
+ "Tax", "Social_security", "Deductions",
87
+ "Job_posting", "Job_description", "Interview_type", "Applicant", "Candidate", "Referral", "Job_board", "Recruiter",
88
+ "Contract", "Offer_letter", "Agreement",
89
+ "Training_course", "Certification", "Skill"]
90
+
91
+ 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.
92
+
93
+ **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.
94
+
95
+ **Usage Limits:** You can request results unlimited times for one (1) week.
96
+
97
+ **Supported Languages:** English
98
+
99
+ **Technical issues:** If your connection times out, please refresh the page or reopen the app's URL.
100
+
101
+ For any errors or inquiries, please contact us at [email protected]
102
+ """)
103
+
104
+ with st.sidebar:
105
+
106
+
107
+ st.write("Use the following code to embed the ProductTag web app on your website. Feel free to adjust the width and height values to fit your page.")
108
+ code = '''
109
+ <iframe
110
+ src="https://aiecosystem-producttag.hf.space"
111
+ frameborder="0"
112
+ width="850"
113
+ height="450"
114
+ ></iframe>
115
+ '''
116
+ st.code(code, language="html")
117
+
118
+ st.text("")
119
+ st.text("")
120
+ st.divider()
121
+
122
+
123
+
124
+ st.subheader("Ready to build your own NER Web App?", divider="orange")
125
+ st.link_button("NER Builder", "https://nlpblogs.com", type="primary")
126
+
127
+
128
+
129
+ # --- Comet ML Setup ---
130
+ COMET_API_KEY = os.environ.get("COMET_API_KEY")
131
+ COMET_WORKSPACE = os.environ.get("COMET_WORKSPACE")
132
+ COMET_PROJECT_NAME = os.environ.get("COMET_PROJECT_NAME")
133
+
134
+ comet_initialized = bool(COMET_API_KEY and COMET_WORKSPACE and COMET_PROJECT_NAME)
135
+ if not comet_initialized:
136
+ st.warning("Comet ML not initialized. Check environment variables.")
137
+
138
+ # --- Label Definitions ---
139
+ labels = [
140
+ "Email_Address", "Phone_Number", "Street_Address", "City", "State", "Zip_code",
141
+ "Date_of_Birth", "Gender", "Marital_Status", "Full_Name",
142
+ "Full_Time", "Part_Time", "Contract", "Temporary", "Terminated", "Active", "Retired",
143
+ "Job_Title", "Employment_Type", "Start_Date", "End_Date", "Company_Name", "Organization_Name", "Role", "Position",
144
+ "Performance_Review", "Performance_Rating", "Performance_Score",
145
+ "Sick_Days", "Vacation_Days", "Leave_of_Absence", "Holidays",
146
+ "Pension", "Retirement_Plan", "Bonus", "Stock_Options", "Health_Insurance","Retire date",
147
+ "Pay_Rate", "Hourly_Wage", "Annual_Salary", "Overtime_Pay",
148
+ "Tax", "Social_Security", "Deductions",
149
+ "Job_Posting", "Job_Description", "Interview_Type", "Applicant", "Candidate", "Referral", "Job_board", "Recruiter",
150
+ "Contract", "Offer_letter", "Agreement",
151
+ "Training_Course", "Certification", "Skill"]
152
+
153
+
154
+
155
+
156
+ # Create a mapping dictionary for labels to categories
157
+ category_mapping = {
158
+
159
+
160
+ "Contact Information": ["Email_Address", "Phone_Number", "Street_Address", "City", "State", "Zip_code"],
161
+ "Personal Details": ["Date of birth", "Gender", "Marital_Status", "Full_Name"],
162
+ "Employment Status": ["Full_Time", "Part_Time", "Contract", "Temporary", "Terminated", "Active", "Retired"],
163
+ "Employment Information" : ["Job_Title", "Employment_Type", "Start_Date", "End_Date", "Company_Name", "Organization_Name", "Role", "Position"],
164
+
165
+ "Performance": ["Performance_Review", "Performance_Rating", "Performance_Score"],
166
+ "Attendance": ["Sick_Days", "Vacation_Days", "Leave_of_Absence", "Holidays"],
167
+ "Benefits": ["Pension", "Retirement_Plan", "Bonus", "Stock_Options", "Health_Insurance", "Retire date"],
168
+ "Compensation": ["Pay_Rate", "Hourly_Wage", "Annual_Salary", "Overtime_Pay"],
169
+ "Deductions": ["Tax", "Social_Security", "Deductions"],
170
+ "Recruitment & Sourcing": ["Job_Posting", "Job_Description", "Interview_Type", "Applicant", "Candidate", "Referral", "Job_board", "Recruiter"],
171
+ "Legal & Compliance": ["Contract", "Offer_letter", "Agreement"],
172
+ "Professional_Development": ["Training_Course", "Certification", "Skill"]
173
+ }
174
+
175
+
176
+ # --- Model Loading ---
177
+ @st.cache_resource
178
+ def load_ner_model():
179
+ """Loads the GLiNER model and caches it."""
180
+ try:
181
+ return GLiNER.from_pretrained("gliner-community/gliner_xxl-v2.5", nested_ner=True, num_gen_sequences=2, gen_constraints= labels)
182
+
183
+ except Exception as e:
184
+ st.error(f"Failed to load NER model. Please check your internet connection or model availability: {e}")
185
+ st.stop()
186
+
187
+ model = load_ner_model()
188
+
189
+
190
+
191
+ # Flatten the mapping to a single dictionary
192
+ reverse_category_mapping = {label: category for category, label_list in category_mapping.items() for label in label_list}
193
+
194
+ # --- Text Input and Clear Button ---
195
+ text = st.text_area("Type or paste your text below, and then press Ctrl + Enter", height=250, key='my_text_area')
196
+
197
+ def clear_text():
198
+ """Clears the text area."""
199
+ st.session_state['my_text_area'] = ""
200
+
201
+ st.button("Clear text", on_click=clear_text)
202
+ st.divider()
203
+
204
+ # --- Results Section ---
205
+ if st.button("Results"):
206
+ start_time = time.time()
207
+ if not text.strip():
208
+ st.warning("Please enter some text to extract entities.")
209
+ else:
210
+ with st.spinner("Extracting entities...", show_time=True):
211
+ entities = model.predict_entities(text, labels)
212
+ df = pd.DataFrame(entities)
213
+
214
+ if not df.empty:
215
+ df['category'] = df['label'].map(reverse_category_mapping)
216
+
217
+ if comet_initialized:
218
+ experiment = Experiment(
219
+ api_key=COMET_API_KEY,
220
+ workspace=COMET_WORKSPACE,
221
+ project_name=COMET_PROJECT_NAME,
222
+ )
223
+ experiment.log_parameter("input_text", text)
224
+ experiment.log_table("predicted_entities", df)
225
+
226
+ st.subheader("Extracted Entities", divider = "orange")
227
+ st.dataframe(df.style.set_properties(**{"border": "2px solid gray", "color": "blue", "font-size": "16px"}))
228
+
229
+ with st.expander("See Glossary of tags"):
230
+ st.write('''
231
+ - **text**: ['entity extracted from your text data']
232
+ - **score**: ['accuracy score; how accurately a tag has been assigned to a given entity']
233
+ - **label**: ['label (tag) assigned to a given extracted entity']
234
+ - **category**: ['the high-level category for the label']
235
+ - **start**: ['index of the start of the corresponding entity']
236
+ - **end**: ['index of the end of the corresponding entity']
237
+ ''')
238
+
239
+ st.divider()
240
+
241
+
242
+ # Tree map
243
+ st.subheader("Tree map", divider = "orange")
244
+ fig_treemap = px.treemap(df, path=[px.Constant("all"), 'category', 'label', 'text'], values='score', color='category')
245
+ fig_treemap.update_layout(margin=dict(t=50, l=25, r=25, b=25))
246
+ st.plotly_chart(fig_treemap)
247
+
248
+ # Pie and Bar charts
249
+ grouped_counts = df['category'].value_counts().reset_index()
250
+ grouped_counts.columns = ['category', 'count']
251
+
252
+ col1, col2 = st.columns(2)
253
+ with col1:
254
+ st.subheader("Pie chart", divider = "orange")
255
+ fig_pie = px.pie(grouped_counts, values='count', names='category',
256
+ hover_data=['count'], labels={'count': 'count'}, title='Percentage of predicted categories')
257
+ fig_pie.update_traces(textposition='inside', textinfo='percent+label')
258
+ st.plotly_chart(fig_pie)
259
+
260
+ with col2:
261
+ st.subheader("Bar chart", divider = "orange")
262
+ fig_bar = px.bar(grouped_counts, x="count", y="category", color="category", text_auto=True,
263
+ title='Occurrences of predicted categories')
264
+ st.plotly_chart(fig_bar)
265
+
266
+ # Most Frequent Entities
267
+ st.subheader("Most Frequent Entities", divider="orange")
268
+ word_counts = df['text'].value_counts().reset_index()
269
+ word_counts.columns = ['Entity', 'Count']
270
+ repeating_entities = word_counts[word_counts['Count'] > 1]
271
+ if not repeating_entities.empty:
272
+ st.dataframe(repeating_entities, use_container_width=True)
273
+ fig_repeating_bar = px.bar(repeating_entities, x='Entity', y='Count', color='Entity')
274
+ fig_repeating_bar.update_layout(xaxis={'categoryorder': 'total descending'})
275
+ st.plotly_chart(fig_repeating_bar)
276
+ else:
277
+ st.warning("No entities were found that occur more than once.")
278
+
279
+
280
+
281
+
282
+
283
+
284
+ # Download Section
285
+ st.divider()
286
+
287
+ dfa = pd.DataFrame(
288
+ data={
289
+ 'Column Name': ['text', 'label', 'score', 'start', 'end', 'category'],
290
+ 'Description': [
291
+ 'entity extracted from your text data',
292
+ 'label (tag) assigned to a given extracted entity',
293
+ 'accuracy score; how accurately a tag has been assigned to a given entity',
294
+ 'index of the start of the corresponding entity',
295
+ 'index of the end of the corresponding entity',
296
+ 'the broader category the entity belongs to',
297
+ ]
298
+ }
299
+ )
300
+
301
+ buf = io.BytesIO()
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)",
312
+ data=buf.getvalue(),
313
+ file_name="markettag_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
+
321
+ else: # If df is empty
322
+ st.warning("No entities were found in the provided text.")
323
+
324
+ end_time = time.time()
325
+ elapsed_time = end_time - start_time
326
 
327
+ st.text("")
328
+ st.text("")
329
+ st.info(f"Results processed in **{elapsed_time:.2f} seconds**.")