AIEcosystem commited on
Commit
81b0b13
·
verified ·
1 Parent(s): 8a3c92a

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +271 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,273 @@
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
+ st.markdown(
17
+ """
18
+ <style>
19
+ /* Main app background and text color */
20
+ .stApp {
21
+ background-color: #F5FFFA; /* Mint cream, a very light green */
22
+ color: #000000; /* Black for the text */
23
+ }
24
+ /* Sidebar background color */
25
+ .css-1d36184 {
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
+ }
34
+ /* Expander header background color */
35
+ .streamlit-expanderHeader {
36
+ background-color: #F5FFFA;
37
+ }
38
+ /* Text Area background and text color */
39
+ .stTextArea textarea {
40
+ background-color: #D4F4D4; /* A light, soft green */
41
+ color: #000000; /* Black for text */
42
+ }
43
+ /* Button background and text color */
44
+ .stButton > button {
45
+ background-color: #D4F4D4;
46
+ color: #000000;
47
+ }
48
+ /* Warning box background and text color */
49
+ .stAlert.st-warning {
50
+ background-color: #C8F0C8; /* A light green for the warning box */
51
+ color: #000000;
52
+ }
53
+ /* Success box background and text color */
54
+ .stAlert.st-success {
55
+ background-color: #C8F0C8; /* A light green for the success box */
56
+ color: #000000;
57
+ }
58
+ </style>
59
+ """,
60
+ unsafe_allow_html=True
61
+ )
62
+
63
+ # --- Page Configuration and UI Elements ---
64
+ st.set_page_config(layout="wide", page_title="Named Entity Recognition App")
65
+ st.subheader("StoryCraft", divider="green")
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 fifty-nine (59) 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", "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
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("")
88
+ st.text("")
89
+ st.divider()
90
+ st.subheader("🚀 Ready to build your own NER Web App?", divider="green")
91
+ st.link_button("NER Builder", "https://nlpblogs.com", type="primary")
92
+
93
+ # --- Comet ML Setup ---
94
+ COMET_API_KEY = os.environ.get("COMET_API_KEY")
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
+
102
+ # --- Label Definitions ---
103
+ labels = ["Person","Organization","Location","Date","Time","Quantity","Product","Event","Title","Job Title","Artwork","Media","URL","Website","Hashtag","Email_address","IP_address","File_path"]
104
+
105
+ # Corrected mapping dictionary
106
+
107
+ # Create a mapping dictionary for labels to categories
108
+ category_mapping = {
109
+ "Core Foundational Entities": ["Person", "Organization", "Location", "Date", "Time", "Quantity"],
110
+ "Content Enrichment Entities": ["Product", "Event", "Title", "Job Title", "Artwork", "Media"],
111
+ "Digital & Technical Entities": ["URL", "Website", "Hashtag", "Email_address", "IP_address", "File_path"],
112
+ }
113
+
114
+ # --- Model Loading ---
115
+ @st.cache_resource
116
+ def load_ner_model():
117
+ """Loads the GLiNER model and caches it."""
118
+ try:
119
+ return GLiNER.from_pretrained("gliner-community/gliner_large-v2.5", nested_ner=True, num_gen_sequences=2, gen_constraints= labels)
120
+ except Exception as e:
121
+ st.error(f"Failed to load NER model. Please check your internet connection or model availability: {e}")
122
+ st.stop()
123
+ model = load_ner_model()
124
+
125
+ # Flatten the mapping to a single dictionary
126
+ reverse_category_mapping = {label: category for category, label_list in category_mapping.items() for label in label_list}
127
+
128
+ # --- Text Input and Clear Button ---
129
+ text = st.text_area("Type or paste your text below, and then press Ctrl + Enter", height=250, key='my_text_area')
130
+
131
+ def clear_text():
132
+ """Clears the text area."""
133
+ st.session_state['my_text_area'] = ""
134
+
135
+ st.button("Clear text", on_click=clear_text)
136
+
137
+
138
+ # --- Results Section ---
139
+ if st.button("Results"):
140
+ start_time = time.time()
141
+ if not text.strip():
142
+ st.warning("Please enter some text to extract entities.")
143
+ else:
144
+ with st.spinner("Extracting entities...", show_time=True):
145
+ entities = model.predict_entities(text, labels)
146
+ df = pd.DataFrame(entities)
147
+
148
+ if not df.empty:
149
+ df['category'] = df['label'].map(reverse_category_mapping)
150
+ if comet_initialized:
151
+ experiment = Experiment(
152
+ api_key=COMET_API_KEY,
153
+ workspace=COMET_WORKSPACE,
154
+ project_name=COMET_PROJECT_NAME,
155
+ )
156
+ experiment.log_parameter("input_text", text)
157
+ experiment.log_table("predicted_entities", df)
158
+
159
+ st.subheader("Grouped Entities by Category", divider = "green")
160
+
161
+ # Create tabs for each category
162
+ category_names = sorted(list(category_mapping.keys()))
163
+ category_tabs = st.tabs(category_names)
164
+
165
+ for i, category_name in enumerate(category_names):
166
+ with category_tabs[i]:
167
+ df_category_filtered = df[df['category'] == category_name]
168
+ if not df_category_filtered.empty:
169
+ st.dataframe(df_category_filtered.drop(columns=['category']), use_container_width=True)
170
+ else:
171
+ st.info(f"No entities found for the '{category_name}' category.")
172
+
173
+
174
 
175
+ with st.expander("See Glossary of tags"):
176
+ st.write('''
177
+ - **text**: ['entity extracted from your text data']
178
+ - **score**: ['accuracy score; how accurately a tag has been assigned to a given entity']
179
+ - **label**: ['label (tag) assigned to a given extracted entity']
180
+ - **category**: ['the high-level category for the label']
181
+ - **start**: ['index of the start of the corresponding entity']
182
+ - **end**: ['index of the end of the corresponding entity']
183
+ ''')
184
+ st.divider()
185
+
186
+ # Tree map
187
+ st.subheader("Tree map", divider = "green")
188
+ fig_treemap = px.treemap(df, path=[px.Constant("all"), 'category', 'label', 'text'], values='score', color='category')
189
+ fig_treemap.update_layout(margin=dict(t=50, l=25, r=25, b=25), paper_bgcolor='#F5FFFA', plot_bgcolor='#F5FFFA')
190
+ st.plotly_chart(fig_treemap)
191
+
192
+ # Pie and Bar charts
193
+ grouped_counts = df['category'].value_counts().reset_index()
194
+ grouped_counts.columns = ['category', 'count']
195
+ col1, col2 = st.columns(2)
196
+
197
+ with col1:
198
+ st.subheader("Pie chart", divider = "green")
199
+ fig_pie = px.pie(grouped_counts, values='count', names='category', hover_data=['count'], labels={'count': 'count'}, title='Percentage of predicted categories')
200
+ fig_pie.update_traces(textposition='inside', textinfo='percent+label')
201
+ fig_pie.update_layout(
202
+ paper_bgcolor='#F5FFFA',
203
+ plot_bgcolor='#F5FFFA'
204
+ )
205
+ st.plotly_chart(fig_pie)
206
+
207
+ with col2:
208
+ st.subheader("Bar chart", divider = "green")
209
+ fig_bar = px.bar(grouped_counts, x="count", y="category", color="category", text_auto=True, title='Occurrences of predicted categories')
210
+ fig_pie.update_layout(
211
+ paper_bgcolor='#F5FFFA',
212
+ plot_bgcolor='#F5FFFA'
213
+ )
214
+ st.plotly_chart(fig_bar)
215
+
216
+ # Most Frequent Entities
217
+ st.subheader("Most Frequent Entities", divider="green")
218
+ word_counts = df['text'].value_counts().reset_index()
219
+ word_counts.columns = ['Entity', 'Count']
220
+ repeating_entities = word_counts[word_counts['Count'] > 1]
221
+ if not repeating_entities.empty:
222
+ st.dataframe(repeating_entities, use_container_width=True)
223
+ fig_repeating_bar = px.bar(repeating_entities, x='Entity', y='Count', color='Entity')
224
+ fig_repeating_bar.update_layout(xaxis={'categoryorder': 'total descending'},
225
+ paper_bgcolor='#F5FFFA',
226
+ plot_bgcolor='#F5FFFA')
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'],
237
+ 'Description': [
238
+ 'entity extracted from your text data',
239
+ 'label (tag) assigned to a given extracted entity',
240
+ 'accuracy score; how accurately a tag has been assigned to a given entity',
241
+ 'index of the start of the corresponding entity',
242
+ 'index of the end of the corresponding entity',
243
+ 'the broader category the entity belongs to',
244
+ ]
245
+ }
246
+ )
247
+ buf = io.BytesIO()
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; }""",
255
+ ):
256
+ st.download_button(
257
+ label="Download results and glossary (zip)",
258
+ data=buf.getvalue(),
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
+
269
+ end_time = time.time()
270
+ elapsed_time = end_time - start_time
271
+ st.text("")
272
+ st.text("")
273
+ st.info(f"Results processed in **{elapsed_time:.2f} seconds**.")