Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +105 -253
src/streamlit_app.py
CHANGED
|
@@ -1,18 +1,24 @@
|
|
| 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>
|
|
@@ -26,7 +32,6 @@ st.markdown(
|
|
| 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;
|
|
@@ -60,34 +65,17 @@ st.markdown(
|
|
| 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("HR.ai", 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 web app predicts thirty-six (36) labels: "Email", "Phone_number", "Street_address", "City", "Country", "Date_of_birth", "Marital_status", "Person", "Full_time", "Part_time", "Contract", "Terminated", "Retired", "Job_title", "Date", "Organization", "Role", "Performance_score", "Leave_of_absence", "Retirement_plan", "Bonus", "Stock_options", "Health_insurance", "Pay_rate", "Annual_salary", "Tax", "Deductions", "Interview_type", "Applicant", "Referral", "Job_board", "Recruiter", "Offer_letter", "Agreement", "Certification", "Skill"
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
**
|
| 73 |
-
|
| 74 |
-
**Usage Limits:** You can request results unlimited times for one (1) month.
|
| 75 |
-
|
| 76 |
-
**Supported Languages:** English
|
| 77 |
-
|
| 78 |
-
**Technical issues:** If your connection times out, please refresh the page or reopen the app's URL.
|
| 79 |
-
|
| 80 |
-
For any errors or inquiries, please contact us at info@nlpblogs.com""")
|
| 81 |
|
| 82 |
with st.sidebar:
|
| 83 |
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.")
|
| 84 |
code = '''
|
| 85 |
-
<iframe
|
| 86 |
-
src="https://aiecosystem-hr-ai.hf.space"
|
| 87 |
-
frameborder="0"
|
| 88 |
-
width="850"
|
| 89 |
-
height="450"
|
| 90 |
-
></iframe>
|
| 91 |
'''
|
| 92 |
st.code(code, language="html")
|
| 93 |
st.text("")
|
|
@@ -101,23 +89,18 @@ COMET_API_KEY = os.environ.get("COMET_API_KEY")
|
|
| 101 |
COMET_WORKSPACE = os.environ.get("COMET_WORKSPACE")
|
| 102 |
COMET_PROJECT_NAME = os.environ.get("COMET_PROJECT_NAME")
|
| 103 |
comet_initialized = bool(COMET_API_KEY and COMET_WORKSPACE and COMET_PROJECT_NAME)
|
| 104 |
-
|
| 105 |
if not comet_initialized:
|
| 106 |
st.warning("Comet ML not initialized. Check environment variables.")
|
| 107 |
|
| 108 |
# --- Label Definitions ---
|
| 109 |
-
|
| 110 |
-
labels = ["Role_Date", "Job_Title_Date", "Email", "Phone_number", "Street_address", "City", "Country", "Date_of_birth", "Marital_status", "Person", "Full_time", "Part_time", "Contract", "Terminated", "Retired", "Job_title", "Date", "Organization", "Role", "Performance_score", "Leave_of_absence", "Retirement_plan", "Bonus", "Stock_options", "Health_insurance", "Pay_rate", "Annual_salary", "Tax", "Deductions", "Interview_type", "Applicant", "Referral", "Job_board", "Recruiter", "Offer_letter", "Agreement", "Certification", "Skill"]
|
| 111 |
-
|
| 112 |
-
|
| 113 |
|
| 114 |
# Create a mapping dictionary for labels to categories
|
| 115 |
-
|
| 116 |
category_mapping = {
|
| 117 |
"Contact Information": ["Email", "Phone_number", "Street_address", "City", "Country"],
|
| 118 |
"Personal Details": ["Date_of_birth", "Marital_status", "Person"],
|
| 119 |
"Employment Status": ["Full_time", "Part_time", "Contract", "Terminated", "Retired"],
|
| 120 |
-
"Employment Information" : ["Job_title", "Date", "Organization", "Role"
|
| 121 |
"Performance": ["Performance_score"],
|
| 122 |
"Attendance": ["Leave_of_absence"],
|
| 123 |
"Benefits": ["Retirement_plan", "Bonus", "Stock_options", "Health_insurance"],
|
|
@@ -125,16 +108,9 @@ category_mapping = {
|
|
| 125 |
"Deductions": ["Tax", "Deductions"],
|
| 126 |
"Recruitment & Sourcing": ["Interview_type", "Applicant", "Referral", "Job_board", "Recruiter"],
|
| 127 |
"Legal & Compliance": ["Offer_letter", "Agreement"],
|
| 128 |
-
"Professional_Development": [
|
| 129 |
}
|
| 130 |
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
# --- Model Loading ---
|
| 139 |
@st.cache_resource
|
| 140 |
def load_ner_model():
|
|
@@ -144,21 +120,17 @@ def load_ner_model():
|
|
| 144 |
except Exception as e:
|
| 145 |
st.error(f"Failed to load NER model. Please check your internet connection or model availability: {e}")
|
| 146 |
st.stop()
|
| 147 |
-
model = load_ner_model()
|
| 148 |
|
| 149 |
-
|
| 150 |
reverse_category_mapping = {label: category for category, label_list in category_mapping.items() for label in label_list}
|
| 151 |
|
| 152 |
# --- Text Input and Clear Button ---
|
| 153 |
text = st.text_area("Type or paste your text below, and then press Ctrl + Enter", height=250, key='my_text_area')
|
| 154 |
-
|
| 155 |
def clear_text():
|
| 156 |
"""Clears the text area."""
|
| 157 |
st.session_state['my_text_area'] = ""
|
| 158 |
-
|
| 159 |
st.button("Clear text", on_click=clear_text)
|
| 160 |
|
| 161 |
-
|
| 162 |
# --- Results Section ---
|
| 163 |
if st.button("Results"):
|
| 164 |
start_time = time.time()
|
|
@@ -166,229 +138,109 @@ if st.button("Results"):
|
|
| 166 |
st.warning("Please enter some text to extract entities.")
|
| 167 |
else:
|
| 168 |
with st.spinner("Extracting entities...", show_time=True):
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
if not df.empty:
|
| 173 |
-
df['category'] = df['label'].map(reverse_category_mapping)
|
| 174 |
-
if comet_initialized:
|
| 175 |
-
experiment = Experiment(
|
| 176 |
-
api_key=COMET_API_KEY,
|
| 177 |
-
workspace=COMET_WORKSPACE,
|
| 178 |
-
project_name=COMET_PROJECT_NAME,
|
| 179 |
-
)
|
| 180 |
-
experiment.log_parameter("input_text", text)
|
| 181 |
-
experiment.log_table("predicted_entities", df)
|
| 182 |
-
|
| 183 |
-
st.subheader("Grouped Entities by Category", divider = "green")
|
| 184 |
-
|
| 185 |
-
# Create tabs for each category
|
| 186 |
-
category_names = sorted(list(category_mapping.keys()))
|
| 187 |
-
category_tabs = st.tabs(category_names)
|
| 188 |
-
|
| 189 |
-
for i, category_name in enumerate(category_names):
|
| 190 |
-
with category_tabs[i]:
|
| 191 |
-
df_category_filtered = df[df['category'] == category_name]
|
| 192 |
-
if not df_category_filtered.empty:
|
| 193 |
-
st.dataframe(df_category_filtered.drop(columns=['category']), use_container_width=True)
|
| 194 |
-
else:
|
| 195 |
-
st.info(f"No entities found for the '{category_name}' category.")
|
| 196 |
-
|
| 197 |
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
except Exception as e:
|
| 220 |
-
st.error(f"Error loading the GLiNER model: {e}")
|
| 221 |
-
st.stop()
|
| 222 |
-
|
| 223 |
-
model = load_gliner_model()
|
| 224 |
-
st.subheader("Question-Answering", divider = "violet")
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
question_input = st.text_input("Ask wh-questions. **Wh-questions begin with what, when, where, who, whom, which, whose, why and how. We use them to ask for specific information.**")
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
if st.button("Add Question"):
|
| 231 |
-
if question_input:
|
| 232 |
-
if question_input not in st.session_state.user_labels:
|
| 233 |
-
st.session_state.user_labels.append(question_input)
|
| 234 |
-
st.success(f"Added question: {question_input}")
|
| 235 |
-
else:
|
| 236 |
-
st.warning("This question has already been added.")
|
| 237 |
-
else:
|
| 238 |
-
st.warning("Please enter a question.")
|
| 239 |
-
st.markdown("---")
|
| 240 |
-
|
| 241 |
-
st.subheader("Record of Questions", divider = "violet")
|
| 242 |
-
|
| 243 |
-
if st.session_state.user_labels:
|
| 244 |
-
|
| 245 |
-
for i, label in enumerate(st.session_state.user_labels):
|
| 246 |
-
col_list, col_delete = st.columns([0.9, 0.1])
|
| 247 |
-
with col_list:
|
| 248 |
-
st.write(f"- {label}", key=f"label_{i}")
|
| 249 |
-
with col_delete:
|
| 250 |
-
# Create a unique key for each button using the index
|
| 251 |
-
if st.button("Delete", key=f"delete_{i}"):
|
| 252 |
-
# Remove the label at the specific index
|
| 253 |
-
st.session_state.user_labels.pop(i)
|
| 254 |
-
# Rerun to update the UI
|
| 255 |
-
st.rerun()
|
| 256 |
-
else:
|
| 257 |
-
st.info("No questions defined yet. Use the input above to add one.")
|
| 258 |
-
|
| 259 |
-
def get_stable_color(label):
|
| 260 |
-
"""Generates a consistent hexadecimal color from a given string."""
|
| 261 |
-
hash_object = hashlib.sha1(label.encode('utf-8'))
|
| 262 |
-
hex_dig = hash_object.hexdigest()
|
| 263 |
-
return '#' + hex_dig[:6]
|
| 264 |
-
|
| 265 |
-
st.divider()
|
| 266 |
-
|
| 267 |
-
# --- Main Processing Logic ---
|
| 268 |
-
if st.button("Extract Answers"):
|
| 269 |
-
if not user_text.strip():
|
| 270 |
-
st.warning("Please enter some text to analyze.")
|
| 271 |
-
elif not st.session_state.user_labels:
|
| 272 |
-
st.warning("Please define at least one question.")
|
| 273 |
-
else:
|
| 274 |
-
if comet_initialized:
|
| 275 |
-
experiment = Experiment(
|
| 276 |
-
api_key=COMET_API_KEY,
|
| 277 |
-
workspace=COMET_WORKSPACE,
|
| 278 |
-
project_name=COMET_PROJECT_NAME
|
| 279 |
-
)
|
| 280 |
-
experiment.log_parameter("input_text_length", len(user_text))
|
| 281 |
-
experiment.log_parameter("defined_labels", st.session_state.user_labels)
|
| 282 |
-
|
| 283 |
-
start_time = time.time()
|
| 284 |
-
with st.spinner("Analyzing text...", show_time=True):
|
| 285 |
-
try:
|
| 286 |
-
entities = model.predict_entities(user_text, st.session_state.user_labels)
|
| 287 |
-
end_time = time.time()
|
| 288 |
-
elapsed_time = end_time - start_time
|
| 289 |
-
st.info(f"Processing took **{elapsed_time:.2f} seconds**.")
|
| 290 |
-
|
| 291 |
-
if entities:
|
| 292 |
-
df1 = pd.DataFrame(entities)
|
| 293 |
-
df2 = df1[['label', 'text', 'score']]
|
| 294 |
-
df = df2.rename(columns={'label': 'question', 'text': 'answer'})
|
| 295 |
|
| 296 |
-
|
| 297 |
-
st.
|
| 298 |
-
|
|
|
|
|
|
|
| 299 |
|
| 300 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 301 |
|
| 302 |
-
csv_data = df.to_csv(index=False).encode('utf-8')
|
| 303 |
with stylable_container(
|
| 304 |
-
key="
|
| 305 |
-
css_styles="""button { background-color:
|
| 306 |
):
|
| 307 |
st.download_button(
|
| 308 |
-
label="Download CSV",
|
| 309 |
data=csv_data,
|
| 310 |
file_name="nlpblogs_results.csv",
|
| 311 |
mime="text/csv",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 312 |
)
|
| 313 |
-
|
| 314 |
-
if comet_initialized:
|
| 315 |
-
experiment.log_metric("processing_time_seconds", elapsed_time)
|
| 316 |
-
experiment.log_table("predicted_entities", df)
|
| 317 |
-
experiment.log_figure(figure=fig_treemap, figure_name="entity_treemap")
|
| 318 |
|
| 319 |
-
experiment.end()
|
| 320 |
-
else:
|
| 321 |
-
st.info("No answers were found in the text with the defined questions.")
|
| 322 |
if comet_initialized:
|
|
|
|
| 323 |
experiment.end()
|
|
|
|
|
|
|
| 324 |
except Exception as e:
|
| 325 |
st.error(f"An error occurred during processing: {e}")
|
| 326 |
-
st.write(f"Error details: {e}")
|
| 327 |
if comet_initialized:
|
| 328 |
experiment.log_text(f"Error: {e}")
|
| 329 |
experiment.end()
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
# Download Section
|
| 352 |
-
st.divider()
|
| 353 |
-
|
| 354 |
-
dfa = pd.DataFrame(
|
| 355 |
-
data={
|
| 356 |
-
'Column Name': ['text', 'label', 'score', 'start', 'end'],
|
| 357 |
-
'Description': [
|
| 358 |
-
'entity extracted from your text data',
|
| 359 |
-
'label (tag) assigned to a given extracted entity',
|
| 360 |
-
'accuracy score; how accurately a tag has been assigned to a given entity',
|
| 361 |
-
'index of the start of the corresponding entity',
|
| 362 |
-
'index of the end of the corresponding entity',
|
| 363 |
-
|
| 364 |
-
]
|
| 365 |
-
}
|
| 366 |
-
)
|
| 367 |
-
buf = io.BytesIO()
|
| 368 |
-
with zipfile.ZipFile(buf, "w") as myzip:
|
| 369 |
-
myzip.writestr("Summary of the results.csv", df.to_csv(index=False))
|
| 370 |
-
myzip.writestr("Glossary of tags.csv", dfa.to_csv(index=False))
|
| 371 |
-
|
| 372 |
-
with stylable_container(
|
| 373 |
-
key="download_button",
|
| 374 |
-
css_styles="""button { background-color: red; border: 1px solid black; padding: 5px; color: white; }""",
|
| 375 |
-
):
|
| 376 |
-
st.download_button(
|
| 377 |
-
label="Download results and glossary (zip)",
|
| 378 |
-
data=buf.getvalue(),
|
| 379 |
-
file_name="nlpblogs_results.zip",
|
| 380 |
-
mime="application/zip",
|
| 381 |
-
)
|
| 382 |
-
|
| 383 |
-
if comet_initialized:
|
| 384 |
-
experiment.log_figure(figure=fig_treemap, figure_name="entity_treemap_categories")
|
| 385 |
-
experiment.end()
|
| 386 |
-
else: # If df is empty
|
| 387 |
-
st.warning("No entities were found in the provided text.")
|
| 388 |
-
|
| 389 |
-
end_time = time.time()
|
| 390 |
-
elapsed_time = end_time - start_time
|
| 391 |
-
st.text("")
|
| 392 |
-
st.text("")
|
| 393 |
-
st.info(f"Results processed in **{elapsed_time:.2f} seconds**.")
|
| 394 |
-
|
|
|
|
| 1 |
import os
|
|
|
|
| 2 |
import time
|
| 3 |
+
import hashlib
|
| 4 |
import streamlit as st
|
| 5 |
import pandas as pd
|
| 6 |
import io
|
| 7 |
import plotly.express as px
|
| 8 |
import zipfile
|
|
|
|
|
|
|
| 9 |
from streamlit_extras.stylable_container import stylable_container
|
| 10 |
from typing import Optional
|
| 11 |
from gliner import GLiNER
|
| 12 |
from comet_ml import Experiment
|
| 13 |
|
| 14 |
+
# Set HF_HOME environment variable
|
| 15 |
+
os.environ['HF_HOME'] = '/tmp'
|
| 16 |
+
|
| 17 |
+
# --- Page Configuration and UI Elements ---
|
| 18 |
+
st.set_page_config(layout="wide", page_title="Named Entity Recognition App")
|
| 19 |
+
st.subheader("HR.ai", divider="green")
|
| 20 |
+
st.link_button("by nlpblogs", "https://nlpblogs.com", type="tertiary")
|
| 21 |
+
|
| 22 |
st.markdown(
|
| 23 |
"""
|
| 24 |
<style>
|
|
|
|
| 32 |
background-color: #B2F2B2; /* A pale green for the sidebar */
|
| 33 |
secondary-background-color: #B2F2B2;
|
| 34 |
}
|
|
|
|
| 35 |
/* Expander background color */
|
| 36 |
.streamlit-expanderContent {
|
| 37 |
background-color: #F5FFFA;
|
|
|
|
| 65 |
unsafe_allow_html=True
|
| 66 |
)
|
| 67 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
expander = st.expander("**Important notes**")
|
| 69 |
+
expander.write("""**Named Entities:** This HR.ai web app predicts thirty-six (36) labels: "Email", "Phone_number", "Street_address", "City", "Country", "Date_of_birth", "Marital_status", "Person", "Full_time", "Part_time", "Contract", "Terminated", "Retired", "Job_title", "Date", "Organization", "Role", "Performance_score", "Leave_of_absence", "Retirement_plan", "Bonus", "Stock_options", "Health_insurance", "Pay_rate", "Annual_salary", "Tax", "Deductions", "Interview_type", "Applicant", "Referral", "Job_board", "Recruiter", "Offer_letter", "Agreement", "Certification", "Skill"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. For any errors or inquiries, please contact us at info@nlpblogs.com""")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
with st.sidebar:
|
| 76 |
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.")
|
| 77 |
code = '''
|
| 78 |
+
<iframe src="https://aiecosystem-hr-ai.hf.space" frameborder="0" width="850" height="450"></iframe>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
'''
|
| 80 |
st.code(code, language="html")
|
| 81 |
st.text("")
|
|
|
|
| 89 |
COMET_WORKSPACE = os.environ.get("COMET_WORKSPACE")
|
| 90 |
COMET_PROJECT_NAME = os.environ.get("COMET_PROJECT_NAME")
|
| 91 |
comet_initialized = bool(COMET_API_KEY and COMET_WORKSPACE and COMET_PROJECT_NAME)
|
|
|
|
| 92 |
if not comet_initialized:
|
| 93 |
st.warning("Comet ML not initialized. Check environment variables.")
|
| 94 |
|
| 95 |
# --- Label Definitions ---
|
| 96 |
+
labels = ["Email", "Phone_number", "Street_address", "City", "Country", "Date_of_birth", "Marital_status", "Person", "Full_time", "Part_time", "Contract", "Terminated", "Retired", "Job_title", "Date", "Organization", "Role", "Performance_score", "Leave_of_absence", "Retirement_plan", "Bonus", "Stock_options", "Health_insurance", "Pay_rate", "Annual_salary", "Tax", "Deductions", "Interview_type", "Applicant", "Referral", "Job_board", "Recruiter", "Offer_letter", "Agreement", "Certification", "Skill"]
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
# Create a mapping dictionary for labels to categories
|
|
|
|
| 99 |
category_mapping = {
|
| 100 |
"Contact Information": ["Email", "Phone_number", "Street_address", "City", "Country"],
|
| 101 |
"Personal Details": ["Date_of_birth", "Marital_status", "Person"],
|
| 102 |
"Employment Status": ["Full_time", "Part_time", "Contract", "Terminated", "Retired"],
|
| 103 |
+
"Employment Information" : ["Job_title", "Date", "Organization", "Role"],
|
| 104 |
"Performance": ["Performance_score"],
|
| 105 |
"Attendance": ["Leave_of_absence"],
|
| 106 |
"Benefits": ["Retirement_plan", "Bonus", "Stock_options", "Health_insurance"],
|
|
|
|
| 108 |
"Deductions": ["Tax", "Deductions"],
|
| 109 |
"Recruitment & Sourcing": ["Interview_type", "Applicant", "Referral", "Job_board", "Recruiter"],
|
| 110 |
"Legal & Compliance": ["Offer_letter", "Agreement"],
|
| 111 |
+
"Professional_Development": ["Certification", "Skill"]
|
| 112 |
}
|
| 113 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
# --- Model Loading ---
|
| 115 |
@st.cache_resource
|
| 116 |
def load_ner_model():
|
|
|
|
| 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 |
|
| 124 |
+
model = load_ner_model()
|
| 125 |
reverse_category_mapping = {label: category for category, label_list in category_mapping.items() for label in label_list}
|
| 126 |
|
| 127 |
# --- Text Input and Clear Button ---
|
| 128 |
text = st.text_area("Type or paste your text below, and then press Ctrl + Enter", height=250, key='my_text_area')
|
|
|
|
| 129 |
def clear_text():
|
| 130 |
"""Clears the text area."""
|
| 131 |
st.session_state['my_text_area'] = ""
|
|
|
|
| 132 |
st.button("Clear text", on_click=clear_text)
|
| 133 |
|
|
|
|
| 134 |
# --- Results Section ---
|
| 135 |
if st.button("Results"):
|
| 136 |
start_time = time.time()
|
|
|
|
| 138 |
st.warning("Please enter some text to extract entities.")
|
| 139 |
else:
|
| 140 |
with st.spinner("Extracting entities...", show_time=True):
|
| 141 |
+
try:
|
| 142 |
+
entities = model.predict_entities(text, labels)
|
| 143 |
+
df = pd.DataFrame(entities)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
|
| 145 |
+
if not df.empty:
|
| 146 |
+
df['category'] = df['label'].map(reverse_category_mapping)
|
| 147 |
+
|
| 148 |
+
if comet_initialized:
|
| 149 |
+
experiment = Experiment(
|
| 150 |
+
api_key=COMET_API_KEY,
|
| 151 |
+
workspace=COMET_WORKSPACE,
|
| 152 |
+
project_name=COMET_PROJECT_NAME,
|
| 153 |
+
)
|
| 154 |
+
experiment.log_parameter("input_text", text)
|
| 155 |
+
experiment.log_table("predicted_entities", df)
|
| 156 |
+
|
| 157 |
+
st.subheader("Grouped Entities by Category", divider="green")
|
| 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]
|
| 164 |
+
if not df_category_filtered.empty:
|
| 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']
|
| 172 |
+
- **score**: ['accuracy score; how accurately a tag has been assigned to a given entity']
|
| 173 |
+
- **label**: ['label (tag) assigned to a given extracted entity']
|
| 174 |
+
- **start**: ['index of the start of the corresponding entity']
|
| 175 |
+
- **end**: ['index of the end of the corresponding entity']
|
| 176 |
+
''')
|
| 177 |
+
|
| 178 |
+
st.divider()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
|
| 180 |
+
# Tree map
|
| 181 |
+
st.subheader("Tree map", divider="green")
|
| 182 |
+
fig_treemap = px.treemap(df, path=[px.Constant("all"), 'category', 'label', 'text'], values='score', color='category')
|
| 183 |
+
fig_treemap.update_layout(margin=dict(t=50, l=25, r=25, b=25), paper_bgcolor='#F5FFFA', plot_bgcolor='#F5FFFA')
|
| 184 |
+
st.plotly_chart(fig_treemap)
|
| 185 |
|
| 186 |
+
# Download Section
|
| 187 |
+
st.divider()
|
| 188 |
+
|
| 189 |
+
df_results = df[['label', 'text', 'score']]
|
| 190 |
+
csv_data = df_results.to_csv(index=False).encode('utf-8')
|
| 191 |
|
|
|
|
| 192 |
with stylable_container(
|
| 193 |
+
key="download_csv_button",
|
| 194 |
+
css_styles="""button { background-color: #D4F4D4; border: 1px solid black; padding: 5px; color: black; }""",
|
| 195 |
):
|
| 196 |
st.download_button(
|
| 197 |
+
label="Download results (CSV)",
|
| 198 |
data=csv_data,
|
| 199 |
file_name="nlpblogs_results.csv",
|
| 200 |
mime="text/csv",
|
| 201 |
+
key="download_csv"
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
dfa = pd.DataFrame(
|
| 205 |
+
data={
|
| 206 |
+
'Column Name': ['text', 'label', 'score', 'start', 'end'],
|
| 207 |
+
'Description': [
|
| 208 |
+
'entity extracted from your text data',
|
| 209 |
+
'label (tag) assigned to a given extracted entity',
|
| 210 |
+
'accuracy score; how accurately a tag has been assigned to a given entity',
|
| 211 |
+
'index of the start of the corresponding entity',
|
| 212 |
+
'index of the end of the corresponding entity',
|
| 213 |
+
]
|
| 214 |
+
}
|
| 215 |
+
)
|
| 216 |
+
buf = io.BytesIO()
|
| 217 |
+
with zipfile.ZipFile(buf, "w") as myzip:
|
| 218 |
+
myzip.writestr("Summary of the results.csv", df_results.to_csv(index=False))
|
| 219 |
+
myzip.writestr("Glossary of tags.csv", dfa.to_csv(index=False))
|
| 220 |
+
|
| 221 |
+
with stylable_container(
|
| 222 |
+
key="download_zip_button",
|
| 223 |
+
css_styles="""button { background-color: #D4F4D4; border: 1px solid black; padding: 5px; color: black; }""",
|
| 224 |
+
):
|
| 225 |
+
st.download_button(
|
| 226 |
+
label="Download results and glossary (zip)",
|
| 227 |
+
data=buf.getvalue(),
|
| 228 |
+
file_name="nlpblogs_results.zip",
|
| 229 |
+
mime="application/zip",
|
| 230 |
+
key="download_zip"
|
| 231 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
|
|
|
|
|
|
|
|
|
|
| 233 |
if comet_initialized:
|
| 234 |
+
experiment.log_figure(figure=fig_treemap, figure_name="entity_treemap_categories")
|
| 235 |
experiment.end()
|
| 236 |
+
else:
|
| 237 |
+
st.warning("No entities were found in the provided text.")
|
| 238 |
except Exception as e:
|
| 239 |
st.error(f"An error occurred during processing: {e}")
|
|
|
|
| 240 |
if comet_initialized:
|
| 241 |
experiment.log_text(f"Error: {e}")
|
| 242 |
experiment.end()
|
| 243 |
+
|
| 244 |
+
end_time = time.time()
|
| 245 |
+
elapsed_time = end_time - start_time
|
| 246 |
+
st.info(f"Results processed in **{elapsed_time:.2f} seconds**.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|