Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +221 -119
src/streamlit_app.py
CHANGED
|
@@ -1,27 +1,18 @@
|
|
| 1 |
import os
|
| 2 |
os.environ['HF_HOME'] = '/tmp'
|
| 3 |
-
|
| 4 |
-
|
| 5 |
import time
|
| 6 |
-
import hashlib
|
| 7 |
import streamlit as st
|
| 8 |
import pandas as pd
|
| 9 |
import io
|
| 10 |
import plotly.express as px
|
| 11 |
import zipfile
|
|
|
|
|
|
|
| 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 |
-
# Set HF_HOME environment variable
|
| 18 |
-
os.environ['HF_HOME'] = '/tmp'
|
| 19 |
-
|
| 20 |
-
# --- Page Configuration and UI Elements ---
|
| 21 |
-
st.set_page_config(layout="wide", page_title="Named Entity Recognition App")
|
| 22 |
-
st.subheader("HR.ai", divider="green")
|
| 23 |
-
st.link_button("by nlpblogs", "https://nlpblogs.com", type="tertiary")
|
| 24 |
-
|
| 25 |
st.markdown(
|
| 26 |
"""
|
| 27 |
<style>
|
|
@@ -35,6 +26,7 @@ st.markdown(
|
|
| 35 |
background-color: #B2F2B2; /* A pale green for the sidebar */
|
| 36 |
secondary-background-color: #B2F2B2;
|
| 37 |
}
|
|
|
|
| 38 |
/* Expander background color */
|
| 39 |
.streamlit-expanderContent {
|
| 40 |
background-color: #F5FFFA;
|
|
@@ -68,37 +60,53 @@ st.markdown(
|
|
| 68 |
unsafe_allow_html=True
|
| 69 |
)
|
| 70 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
expander = st.expander("**Important notes**")
|
| 72 |
-
expander.write("""**Named Entities:** This HR.ai
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
|
|
|
|
|
|
| 77 |
|
| 78 |
with st.sidebar:
|
| 79 |
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.")
|
| 80 |
code = '''
|
| 81 |
-
<iframe
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
'''
|
| 83 |
st.code(code, language="html")
|
| 84 |
st.text("")
|
| 85 |
st.text("")
|
| 86 |
st.divider()
|
| 87 |
st.subheader("🚀 Ready to build your own AI Web App?", divider="green")
|
| 88 |
-
st.link_button("AI Web App Builder", "https://nlpblogs.com/custom-web-app-development/", type="primary")
|
| 89 |
|
| 90 |
# --- Comet ML Setup ---
|
| 91 |
COMET_API_KEY = os.environ.get("COMET_API_KEY")
|
| 92 |
COMET_WORKSPACE = os.environ.get("COMET_WORKSPACE")
|
| 93 |
COMET_PROJECT_NAME = os.environ.get("COMET_PROJECT_NAME")
|
| 94 |
comet_initialized = bool(COMET_API_KEY and COMET_WORKSPACE and COMET_PROJECT_NAME)
|
|
|
|
| 95 |
if not comet_initialized:
|
| 96 |
st.warning("Comet ML not initialized. Check environment variables.")
|
| 97 |
|
| 98 |
# --- Label Definitions ---
|
|
|
|
| 99 |
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"]
|
| 100 |
|
|
|
|
|
|
|
| 101 |
# Create a mapping dictionary for labels to categories
|
|
|
|
| 102 |
category_mapping = {
|
| 103 |
"Contact Information": ["Email", "Phone_number", "Street_address", "City", "Country"],
|
| 104 |
"Personal Details": ["Date_of_birth", "Marital_status", "Person"],
|
|
@@ -111,9 +119,16 @@ category_mapping = {
|
|
| 111 |
"Deductions": ["Tax", "Deductions"],
|
| 112 |
"Recruitment & Sourcing": ["Interview_type", "Applicant", "Referral", "Job_board", "Recruiter"],
|
| 113 |
"Legal & Compliance": ["Offer_letter", "Agreement"],
|
| 114 |
-
"Professional_Development": ["Certification", "Skill"]
|
| 115 |
}
|
| 116 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
# --- Model Loading ---
|
| 118 |
@st.cache_resource
|
| 119 |
def load_ner_model():
|
|
@@ -123,17 +138,21 @@ def load_ner_model():
|
|
| 123 |
except Exception as e:
|
| 124 |
st.error(f"Failed to load NER model. Please check your internet connection or model availability: {e}")
|
| 125 |
st.stop()
|
| 126 |
-
|
| 127 |
model = load_ner_model()
|
|
|
|
|
|
|
| 128 |
reverse_category_mapping = {label: category for category, label_list in category_mapping.items() for label in label_list}
|
| 129 |
|
| 130 |
# --- Text Input and Clear Button ---
|
| 131 |
text = st.text_area("Type or paste your text below, and then press Ctrl + Enter", height=250, key='my_text_area')
|
|
|
|
| 132 |
def clear_text():
|
| 133 |
"""Clears the text area."""
|
| 134 |
st.session_state['my_text_area'] = ""
|
|
|
|
| 135 |
st.button("Clear text", on_click=clear_text)
|
| 136 |
|
|
|
|
| 137 |
# --- Results Section ---
|
| 138 |
if st.button("Results"):
|
| 139 |
start_time = time.time()
|
|
@@ -141,109 +160,192 @@ if st.button("Results"):
|
|
| 141 |
st.warning("Please enter some text to extract entities.")
|
| 142 |
else:
|
| 143 |
with st.spinner("Extracting entities...", show_time=True):
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
|
|
|
|
|
|
|
|
|
| 171 |
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
|
| 192 |
-
|
| 193 |
-
|
|
|
|
|
|
|
| 194 |
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
'
|
| 210 |
-
'
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
)
|
| 219 |
-
|
| 220 |
-
with zipfile.ZipFile(buf, "w") as myzip:
|
| 221 |
-
myzip.writestr("Summary of the results.csv", df_results.to_csv(index=False))
|
| 222 |
-
myzip.writestr("Glossary of tags.csv", dfa.to_csv(index=False))
|
| 223 |
-
|
| 224 |
-
with stylable_container(
|
| 225 |
-
key="download_zip_button",
|
| 226 |
-
css_styles="""button { background-color: #D4F4D4; border: 1px solid black; padding: 5px; color: black; }""",
|
| 227 |
-
):
|
| 228 |
-
st.download_button(
|
| 229 |
-
label="Download results and glossary (zip)",
|
| 230 |
-
data=buf.getvalue(),
|
| 231 |
-
file_name="nlpblogs_results.zip",
|
| 232 |
-
mime="application/zip",
|
| 233 |
-
key="download_zip"
|
| 234 |
-
)
|
| 235 |
-
|
| 236 |
-
if comet_initialized:
|
| 237 |
-
experiment.log_figure(figure=fig_treemap, figure_name="entity_treemap_categories")
|
| 238 |
-
experiment.end()
|
| 239 |
-
else:
|
| 240 |
-
st.warning("No entities were found in the provided text.")
|
| 241 |
-
except Exception as e:
|
| 242 |
-
st.error(f"An error occurred during processing: {e}")
|
| 243 |
if comet_initialized:
|
| 244 |
-
experiment.
|
| 245 |
experiment.end()
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
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 |
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 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 |
+
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 info@nlpblogs.com""")
|
| 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 AI Web App?", divider="green")
|
| 91 |
+
st.link_button("AI Web App Builder", " https://nlpblogs.com/custom-web-app-development/", 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 |
+
|
| 104 |
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"]
|
| 105 |
|
| 106 |
+
|
| 107 |
+
|
| 108 |
# Create a mapping dictionary for labels to categories
|
| 109 |
+
|
| 110 |
category_mapping = {
|
| 111 |
"Contact Information": ["Email", "Phone_number", "Street_address", "City", "Country"],
|
| 112 |
"Personal Details": ["Date_of_birth", "Marital_status", "Person"],
|
|
|
|
| 119 |
"Deductions": ["Tax", "Deductions"],
|
| 120 |
"Recruitment & Sourcing": ["Interview_type", "Applicant", "Referral", "Job_board", "Recruiter"],
|
| 121 |
"Legal & Compliance": ["Offer_letter", "Agreement"],
|
| 122 |
+
"Professional_Development": [ "Certification", "Skill"]
|
| 123 |
}
|
| 124 |
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
|
| 132 |
# --- Model Loading ---
|
| 133 |
@st.cache_resource
|
| 134 |
def load_ner_model():
|
|
|
|
| 138 |
except Exception as e:
|
| 139 |
st.error(f"Failed to load NER model. Please check your internet connection or model availability: {e}")
|
| 140 |
st.stop()
|
|
|
|
| 141 |
model = load_ner_model()
|
| 142 |
+
|
| 143 |
+
# Flatten the mapping to a single dictionary
|
| 144 |
reverse_category_mapping = {label: category for category, label_list in category_mapping.items() for label in label_list}
|
| 145 |
|
| 146 |
# --- Text Input and Clear Button ---
|
| 147 |
text = st.text_area("Type or paste your text below, and then press Ctrl + Enter", height=250, key='my_text_area')
|
| 148 |
+
|
| 149 |
def clear_text():
|
| 150 |
"""Clears the text area."""
|
| 151 |
st.session_state['my_text_area'] = ""
|
| 152 |
+
|
| 153 |
st.button("Clear text", on_click=clear_text)
|
| 154 |
|
| 155 |
+
|
| 156 |
# --- Results Section ---
|
| 157 |
if st.button("Results"):
|
| 158 |
start_time = time.time()
|
|
|
|
| 160 |
st.warning("Please enter some text to extract entities.")
|
| 161 |
else:
|
| 162 |
with st.spinner("Extracting entities...", show_time=True):
|
| 163 |
+
entities = model.predict_entities(text, labels)
|
| 164 |
+
df = pd.DataFrame(entities)
|
| 165 |
+
|
| 166 |
+
if not df.empty:
|
| 167 |
+
df['category'] = df['label'].map(reverse_category_mapping)
|
| 168 |
+
if comet_initialized:
|
| 169 |
+
experiment = Experiment(
|
| 170 |
+
api_key=COMET_API_KEY,
|
| 171 |
+
workspace=COMET_WORKSPACE,
|
| 172 |
+
project_name=COMET_PROJECT_NAME,
|
| 173 |
+
)
|
| 174 |
+
experiment.log_parameter("input_text", text)
|
| 175 |
+
experiment.log_table("predicted_entities", df)
|
| 176 |
|
| 177 |
+
st.subheader("Grouped Entities by Category", divider = "green")
|
| 178 |
+
|
| 179 |
+
# Create tabs for each category
|
| 180 |
+
category_names = sorted(list(category_mapping.keys()))
|
| 181 |
+
category_tabs = st.tabs(category_names)
|
| 182 |
+
|
| 183 |
+
for i, category_name in enumerate(category_names):
|
| 184 |
+
with category_tabs[i]:
|
| 185 |
+
df_category_filtered = df[df['category'] == category_name]
|
| 186 |
+
if not df_category_filtered.empty:
|
| 187 |
+
st.dataframe(df_category_filtered.drop(columns=['category']), use_container_width=True)
|
| 188 |
+
else:
|
| 189 |
+
st.info(f"No entities found for the '{category_name}' category.")
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
with st.expander("See Glossary of tags"):
|
| 194 |
+
st.write('''
|
| 195 |
+
- **text**: ['entity extracted from your text data']
|
| 196 |
+
- **score**: ['accuracy score; how accurately a tag has been assigned to a given entity']
|
| 197 |
+
- **label**: ['label (tag) assigned to a given extracted entity']
|
| 198 |
+
- **category**: ['the high-level category for the label']
|
| 199 |
+
- **start**: ['index of the start of the corresponding entity']
|
| 200 |
+
- **end**: ['index of the end of the corresponding entity']
|
| 201 |
+
''')
|
| 202 |
+
st.divider()
|
| 203 |
|
| 204 |
+
# Tree map
|
| 205 |
+
st.subheader("Tree map", divider = "green")
|
| 206 |
+
fig_treemap = px.treemap(df, path=[px.Constant("all"), 'category', 'label', 'text'], values='score', color='category')
|
| 207 |
+
fig_treemap.update_layout(margin=dict(t=50, l=25, r=25, b=25), paper_bgcolor='#F5FFFA', plot_bgcolor='#F5FFFA')
|
| 208 |
+
st.plotly_chart(fig_treemap)
|
| 209 |
+
|
| 210 |
+
# --- Model Loading and Caching ---
|
| 211 |
+
@st.cache_resource
|
| 212 |
+
def load_gliner_model():
|
| 213 |
+
"""
|
| 214 |
+
Initializes and caches the GLiNER model.
|
| 215 |
+
This ensures the model is only loaded once, improving performance.
|
| 216 |
+
"""
|
| 217 |
+
try:
|
| 218 |
+
return GLiNER.from_pretrained("knowledgator/gliner-multitask-v1.0", device="cpu")
|
| 219 |
+
except Exception as e:
|
| 220 |
+
st.error(f"Error loading the GLiNER model: {e}")
|
| 221 |
+
st.stop()
|
| 222 |
+
|
| 223 |
+
# Load the model
|
| 224 |
+
model = load_gliner_model()
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
st.subheader("Question-Answering", divider = "violet")
|
| 229 |
+
|
| 230 |
+
# Replaced two columns with a single text input
|
| 231 |
+
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.**")
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
if st.button("Add Question"):
|
| 235 |
+
if question_input:
|
| 236 |
+
if question_input not in st.session_state.user_labels:
|
| 237 |
+
st.session_state.user_labels.append(question_input)
|
| 238 |
+
st.success(f"Added question: {question_input}")
|
| 239 |
+
else:
|
| 240 |
+
st.warning("This question has already been added.")
|
| 241 |
+
else:
|
| 242 |
+
st.warning("Please enter a question.")
|
| 243 |
+
st.markdown("---")
|
| 244 |
+
|
| 245 |
+
st.subheader("Record of Questions", divider = "violet")
|
| 246 |
+
|
| 247 |
+
if st.session_state.user_labels:
|
| 248 |
+
# Use enumerate to create a unique key for each item
|
| 249 |
+
for i, label in enumerate(st.session_state.user_labels):
|
| 250 |
+
col_list, col_delete = st.columns([0.9, 0.1])
|
| 251 |
+
with col_list:
|
| 252 |
+
st.write(f"- {label}", key=f"label_{i}")
|
| 253 |
+
with col_delete:
|
| 254 |
+
# Create a unique key for each button using the index
|
| 255 |
+
if st.button("Delete", key=f"delete_{i}"):
|
| 256 |
+
# Remove the label at the specific index
|
| 257 |
+
st.session_state.user_labels.pop(i)
|
| 258 |
+
# Rerun to update the UI
|
| 259 |
+
st.rerun()
|
| 260 |
+
else:
|
| 261 |
+
st.info("No questions defined yet. Use the input above to add one.")
|
| 262 |
+
|
| 263 |
+
def get_stable_color(label):
|
| 264 |
+
"""Generates a consistent hexadecimal color from a given string."""
|
| 265 |
+
hash_object = hashlib.sha1(label.encode('utf-8'))
|
| 266 |
+
hex_dig = hash_object.hexdigest()
|
| 267 |
+
return '#' + hex_dig[:6]
|
| 268 |
+
|
| 269 |
+
st.divider()
|
| 270 |
+
|
| 271 |
+
# --- Main Processing Logic ---
|
| 272 |
+
if st.button("Extract Answers"):
|
| 273 |
+
if not text.strip():
|
| 274 |
+
st.warning("Please enter some text to analyze.")
|
| 275 |
+
elif not st.session_state.user_labels:
|
| 276 |
+
st.warning("Please define at least one question.")
|
| 277 |
+
else:
|
| 278 |
+
if comet_initialized:
|
| 279 |
+
experiment = Experiment(
|
| 280 |
+
api_key=COMET_API_KEY,
|
| 281 |
+
workspace=COMET_WORKSPACE,
|
| 282 |
+
project_name=COMET_PROJECT_NAME
|
| 283 |
+
)
|
| 284 |
+
experiment.log_parameter("input_text_length", len(user_text))
|
| 285 |
+
experiment.log_parameter("defined_labels", st.session_state.user_labels)
|
| 286 |
+
|
| 287 |
+
start_time = time.time()
|
| 288 |
+
with st.spinner("Analyzing text...", show_time=True):
|
| 289 |
+
try:
|
| 290 |
+
entities = model.predict_entities(text, st.session_state.user_labels)
|
| 291 |
+
end_time = time.time()
|
| 292 |
+
elapsed_time = end_time - start_time
|
| 293 |
+
st.info(f"Processing took **{elapsed_time:.2f} seconds**.")
|
| 294 |
+
|
| 295 |
+
if entities:
|
| 296 |
+
df1 = pd.DataFrame(entities)
|
| 297 |
+
df2 = df1[['label', 'text', 'score']]
|
| 298 |
+
df = df2.rename(columns={'label': 'question', 'text': 'answer'})
|
| 299 |
|
| 300 |
+
st.subheader("Extracted Answers", divider = "violet")
|
| 301 |
+
st.dataframe(df, use_container_width=True)
|
| 302 |
+
|
| 303 |
+
|
| 304 |
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
st.divider()
|
| 311 |
+
|
| 312 |
+
dfa = pd.DataFrame(
|
| 313 |
+
data={
|
| 314 |
+
'Column Name': ['text', 'label', 'score', 'start', 'end', 'category'],
|
| 315 |
+
'Description': [
|
| 316 |
+
'entity extracted from your text data',
|
| 317 |
+
'label (tag) assigned to a given extracted entity',
|
| 318 |
+
'accuracy score; how accurately a tag has been assigned to a given entity',
|
| 319 |
+
'index of the start of the corresponding entity',
|
| 320 |
+
'index of the end of the corresponding entity',
|
| 321 |
+
'the broader category the entity belongs to',
|
| 322 |
+
]
|
| 323 |
+
}
|
| 324 |
+
)
|
| 325 |
+
buf = io.BytesIO()
|
| 326 |
+
with zipfile.ZipFile(buf, "w") as myzip:
|
| 327 |
+
myzip.writestr("Summary of the results.csv", df.to_csv(index=False))
|
| 328 |
+
myzip.writestr("Glossary of tags.csv", dfa.to_csv(index=False))
|
| 329 |
+
|
| 330 |
+
with stylable_container(
|
| 331 |
+
key="download_button",
|
| 332 |
+
css_styles="""button { background-color: red; border: 1px solid black; padding: 5px; color: white; }""",
|
| 333 |
+
):
|
| 334 |
+
st.download_button(
|
| 335 |
+
label="Download results and glossary (zip)",
|
| 336 |
+
data=buf.getvalue(),
|
| 337 |
+
file_name="nlpblogs_results.zip",
|
| 338 |
+
mime="application/zip",
|
| 339 |
)
|
| 340 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 341 |
if comet_initialized:
|
| 342 |
+
experiment.log_figure(figure=fig_treemap, figure_name="entity_treemap_categories")
|
| 343 |
experiment.end()
|
| 344 |
+
else: # If df is empty
|
| 345 |
+
st.warning("No entities were found in the provided text.")
|
| 346 |
+
|
| 347 |
+
end_time = time.time()
|
| 348 |
+
elapsed_time = end_time - start_time
|
| 349 |
+
st.text("")
|
| 350 |
+
st.text("")
|
| 351 |
+
st.info(f"Results processed in **{elapsed_time:.2f} seconds**.")
|