Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +139 -173
src/streamlit_app.py
CHANGED
|
@@ -1,5 +1,4 @@
|
|
| 1 |
import os
|
| 2 |
-
os.environ['HF_HOME'] = '/tmp'
|
| 3 |
import time
|
| 4 |
import streamlit as st
|
| 5 |
import pandas as pd
|
|
@@ -26,7 +25,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;
|
|
@@ -66,22 +64,16 @@ 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("")
|
|
@@ -91,6 +83,7 @@ with st.sidebar:
|
|
| 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")
|
|
@@ -100,13 +93,9 @@ 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"],
|
|
@@ -122,13 +111,6 @@ category_mapping = {
|
|
| 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,6 +120,7 @@ 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
|
|
@@ -152,7 +135,6 @@ def clear_text():
|
|
| 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()
|
|
@@ -162,7 +144,6 @@ if st.button("Results"):
|
|
| 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:
|
|
@@ -173,13 +154,12 @@ if st.button("Results"):
|
|
| 173 |
)
|
| 174 |
experiment.log_parameter("input_text", text)
|
| 175 |
experiment.log_table("predicted_entities", df)
|
| 176 |
-
|
| 177 |
-
st.subheader("Grouped Entities by Category", divider
|
| 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]
|
|
@@ -188,8 +168,6 @@ if st.button("Results"):
|
|
| 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']
|
|
@@ -200,152 +178,140 @@ if st.button("Results"):
|
|
| 200 |
- **end**: ['index of the end of the corresponding entity']
|
| 201 |
''')
|
| 202 |
st.divider()
|
| 203 |
-
|
| 204 |
# Tree map
|
| 205 |
-
st.subheader("Tree map", divider
|
| 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.
|
| 229 |
|
| 230 |
-
#
|
| 231 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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**.")
|
|
|
|
| 1 |
import os
|
|
|
|
| 2 |
import time
|
| 3 |
import streamlit as st
|
| 4 |
import pandas as pd
|
|
|
|
| 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;
|
|
|
|
| 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 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"
|
| 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
|
| 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 info@nlpblogs.com""")
|
|
|
|
| 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("")
|
|
|
|
| 83 |
st.link_button("AI Web App Builder", " https://nlpblogs.com/custom-web-app-development/", type="primary")
|
| 84 |
|
| 85 |
# --- Comet ML Setup ---
|
| 86 |
+
os.environ['HF_HOME'] = '/tmp'
|
| 87 |
COMET_API_KEY = os.environ.get("COMET_API_KEY")
|
| 88 |
COMET_WORKSPACE = os.environ.get("COMET_WORKSPACE")
|
| 89 |
COMET_PROJECT_NAME = os.environ.get("COMET_PROJECT_NAME")
|
|
|
|
| 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"],
|
|
|
|
| 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 |
|
| 126 |
# Flatten the mapping to a single dictionary
|
|
|
|
| 135 |
|
| 136 |
st.button("Clear text", on_click=clear_text)
|
| 137 |
|
|
|
|
| 138 |
# --- Results Section ---
|
| 139 |
if st.button("Results"):
|
| 140 |
start_time = time.time()
|
|
|
|
| 144 |
with st.spinner("Extracting entities...", show_time=True):
|
| 145 |
entities = model.predict_entities(text, labels)
|
| 146 |
df = pd.DataFrame(entities)
|
|
|
|
| 147 |
if not df.empty:
|
| 148 |
df['category'] = df['label'].map(reverse_category_mapping)
|
| 149 |
if comet_initialized:
|
|
|
|
| 154 |
)
|
| 155 |
experiment.log_parameter("input_text", text)
|
| 156 |
experiment.log_table("predicted_entities", df)
|
| 157 |
+
|
| 158 |
+
st.subheader("Grouped Entities by Category", divider="green")
|
|
|
|
| 159 |
# Create tabs for each category
|
| 160 |
category_names = sorted(list(category_mapping.keys()))
|
| 161 |
category_tabs = st.tabs(category_names)
|
| 162 |
+
|
| 163 |
for i, category_name in enumerate(category_names):
|
| 164 |
with category_tabs[i]:
|
| 165 |
df_category_filtered = df[df['category'] == category_name]
|
|
|
|
| 168 |
else:
|
| 169 |
st.info(f"No entities found for the '{category_name}' category.")
|
| 170 |
|
|
|
|
|
|
|
| 171 |
with st.expander("See Glossary of tags"):
|
| 172 |
st.write('''
|
| 173 |
- **text**: ['entity extracted from your text data']
|
|
|
|
| 178 |
- **end**: ['index of the end of the corresponding entity']
|
| 179 |
''')
|
| 180 |
st.divider()
|
| 181 |
+
|
| 182 |
# Tree map
|
| 183 |
+
st.subheader("Tree map", divider="green")
|
| 184 |
fig_treemap = px.treemap(df, path=[px.Constant("all"), 'category', 'label', 'text'], values='score', color='category')
|
| 185 |
fig_treemap.update_layout(margin=dict(t=50, l=25, r=25, b=25), paper_bgcolor='#F5FFFA', plot_bgcolor='#F5FFFA')
|
| 186 |
st.plotly_chart(fig_treemap)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
|
| 188 |
+
# --- Model Loading and Caching ---
|
| 189 |
+
@st.cache_resource
|
| 190 |
+
def load_gliner_model():
|
| 191 |
+
"""
|
| 192 |
+
Initializes and caches the GLiNER model.
|
| 193 |
+
This ensures the model is only loaded once, improving performance.
|
| 194 |
+
"""
|
| 195 |
+
try:
|
| 196 |
+
return GLiNER.from_pretrained("knowledgator/gliner-multitask-v1.0", device="cpu")
|
| 197 |
+
except Exception as e:
|
| 198 |
+
st.error(f"Error loading the GLiNER model: {e}")
|
| 199 |
+
st.stop()
|
| 200 |
+
|
| 201 |
+
# Load the model
|
| 202 |
+
model = load_gliner_model()
|
| 203 |
+
st.subheader("Question-Answering", divider="violet")
|
| 204 |
+
# Replaced two columns with a single text input
|
| 205 |
+
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.**")
|
| 206 |
+
|
| 207 |
+
if 'user_labels' not in st.session_state:
|
| 208 |
+
st.session_state.user_labels = []
|
| 209 |
+
|
| 210 |
+
if st.button("Add Question"):
|
| 211 |
+
if question_input:
|
| 212 |
+
if question_input not in st.session_state.user_labels:
|
| 213 |
+
st.session_state.user_labels.append(question_input)
|
| 214 |
+
st.success(f"Added question: {question_input}")
|
| 215 |
+
else:
|
| 216 |
+
st.warning("This question has already been added.")
|
| 217 |
+
else:
|
| 218 |
+
st.warning("Please enter a question.")
|
| 219 |
+
st.markdown("---")
|
| 220 |
+
st.subheader("Record of Questions", divider="violet")
|
| 221 |
+
|
| 222 |
+
if st.session_state.user_labels:
|
| 223 |
+
# Use enumerate to create a unique key for each item
|
| 224 |
+
for i, label in enumerate(st.session_state.user_labels):
|
| 225 |
+
col_list, col_delete = st.columns([0.9, 0.1])
|
| 226 |
+
with col_list:
|
| 227 |
+
st.write(f"- {label}", key=f"label_{i}")
|
| 228 |
+
with col_delete:
|
| 229 |
+
# Create a unique key for each button using the index
|
| 230 |
+
if st.button("Delete", key=f"delete_{i}"):
|
| 231 |
+
# Remove the label at the specific index
|
| 232 |
+
st.session_state.user_labels.pop(i)
|
| 233 |
+
# Rerun to update the UI
|
| 234 |
+
st.rerun()
|
| 235 |
+
else:
|
| 236 |
+
st.info("No questions defined yet. Use the input above to add one.")
|
| 237 |
|
| 238 |
+
st.divider()
|
| 239 |
|
| 240 |
+
# --- Main Processing Logic ---
|
| 241 |
+
if st.button("Extract Answers"):
|
| 242 |
+
if not text.strip():
|
| 243 |
+
st.warning("Please enter some text to analyze.")
|
| 244 |
+
elif not st.session_state.user_labels:
|
| 245 |
+
st.warning("Please define at least one question.")
|
| 246 |
+
else:
|
| 247 |
+
if comet_initialized:
|
| 248 |
+
experiment = Experiment(
|
| 249 |
+
api_key=COMET_API_KEY,
|
| 250 |
+
workspace=COMET_WORKSPACE,
|
| 251 |
+
project_name=COMET_PROJECT_NAME
|
| 252 |
+
)
|
| 253 |
+
experiment.log_parameter("input_text_length", len(text))
|
| 254 |
+
experiment.log_parameter("defined_labels", st.session_state.user_labels)
|
| 255 |
+
start_time = time.time()
|
| 256 |
+
with st.spinner("Analyzing text...", show_time=True):
|
| 257 |
+
try:
|
| 258 |
+
entities = model.predict_entities(text, st.session_state.user_labels)
|
| 259 |
+
end_time = time.time()
|
| 260 |
+
elapsed_time = end_time - start_time
|
| 261 |
+
st.info(f"Processing took **{elapsed_time:.2f} seconds**.")
|
| 262 |
+
|
| 263 |
+
if entities:
|
| 264 |
+
df1 = pd.DataFrame(entities)
|
| 265 |
+
df2 = df1[['label', 'text', 'score']]
|
| 266 |
+
df = df2.rename(columns={'label': 'question', 'text': 'answer'})
|
| 267 |
+
|
| 268 |
+
st.subheader("Extracted Answers", divider="violet")
|
| 269 |
+
st.dataframe(df, use_container_width=True)
|
| 270 |
+
st.divider()
|
| 271 |
+
|
| 272 |
+
dfa = pd.DataFrame(
|
| 273 |
+
data={
|
| 274 |
+
'Column Name': ['text', 'label', 'score', 'start', 'end', 'category'],
|
| 275 |
+
'Description': [
|
| 276 |
+
'entity extracted from your text data',
|
| 277 |
+
'label (tag) assigned to a given extracted entity',
|
| 278 |
+
'accuracy score; how accurately a tag has been assigned to a given entity',
|
| 279 |
+
'index of the start of the corresponding entity',
|
| 280 |
+
'index of the end of the corresponding entity',
|
| 281 |
+
'the broader category the entity belongs to',
|
| 282 |
+
]
|
| 283 |
+
}
|
| 284 |
+
)
|
| 285 |
+
buf = io.BytesIO()
|
| 286 |
+
with zipfile.ZipFile(buf, "w") as myzip:
|
| 287 |
+
myzip.writestr("Summary of the results.csv", df.to_csv(index=False))
|
| 288 |
+
myzip.writestr("Glossary of tags.csv", dfa.to_csv(index=False))
|
| 289 |
+
|
| 290 |
+
with stylable_container(
|
| 291 |
+
key="download_button",
|
| 292 |
+
css_styles="""button { background-color: red; border: 1px solid black; padding: 5px; color: white; }""",
|
| 293 |
+
):
|
| 294 |
+
st.download_button(
|
| 295 |
+
label="Download results and glossary (zip)",
|
| 296 |
+
data=buf.getvalue(),
|
| 297 |
+
file_name="nlpblogs_results.zip",
|
| 298 |
+
mime="application/zip",
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
if comet_initialized:
|
| 302 |
+
experiment.log_figure(figure=fig_treemap, figure_name="entity_treemap_categories")
|
| 303 |
+
experiment.end()
|
| 304 |
+
else: # If df is empty
|
| 305 |
+
st.warning("No entities were found in the provided text.")
|
| 306 |
+
except Exception as e:
|
| 307 |
+
st.error(f"An error occurred during entity extraction: {e}")
|
| 308 |
+
|
| 309 |
+
else: # If df is empty from the first extraction
|
| 310 |
+
st.warning("No entities were found in the provided text.")
|
| 311 |
|
| 312 |
+
end_time = time.time()
|
| 313 |
+
elapsed_time = end_time - start_time
|
| 314 |
+
st.text("")
|
| 315 |
+
st.text("")
|
| 316 |
+
st.info(f"Results processed in **{elapsed_time:.2f} seconds**.")
|
| 317 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|