StressDetection / src /streamlit_app.py
EnYa32's picture
Update src/streamlit_app.py
eb70157 verified
Raw History Blame Contribute Delete
3.13 kB
# src/streamlit_app.py
import os
import joblib
import streamlit as st
# ===================== FIX: Download NLTK corpora for TextBlob =====================
@st.cache_resource
def ensure_nltk_corpora():
import nltk
nltk_dir = "/tmp/nltk_data"
os.makedirs(nltk_dir, exist_ok=True)
# Tell NLTK to use this writable folder in HF Spaces
os.environ["NLTK_DATA"] = nltk_dir
if nltk_dir not in nltk.data.path:
nltk.data.path.append(nltk_dir)
# TextBlob/NLTK resources needed for tokenization + lemmatization
nltk.download("punkt", download_dir=nltk_dir, quiet=True)
nltk.download("punkt_tab", download_dir=nltk_dir, quiet=True) # important on many HF setups
nltk.download("wordnet", download_dir=nltk_dir, quiet=True)
nltk.download("omw-1.4", download_dir=nltk_dir, quiet=True)
ensure_nltk_corpora()
# ================================================================================
# ---- Custom analyzer MUST exist to load your saved pipeline ----
from textblob import TextBlob
from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS
stops = ENGLISH_STOP_WORDS
def ekkok(text):
words = TextBlob(str(text)).words
return [
w.lemmatize(pos="v").lower()
for w in words
if w.lower() not in stops and w.isalpha()
]
# ---------------------------------------------------------------
st.set_page_config(page_title="Stress Detection (TF-IDF)", page_icon="🧠", layout="centered")
@st.cache_resource
def load_pipeline():
# If your pickle is in repo root, change to: "tfidf_lr_pipeline.pkl"
return joblib.load("src/tfidf_lr_pipeline.pkl")
pipeline = load_pipeline()
st.title("🧠 Stress Detection from Text")
st.write("This app uses a **TF-IDF + Logistic Regression** pipeline to predict **Stress (1)** or **No Stress (0)**.")
default_example = "I feel stressed and overwhelmed with my daily tasks."
text = st.text_area(
"Enter text (e.g., a social media post):",
height=180,
placeholder="Type or paste text here..."
)
col1, col2 = st.columns(2)
with col1:
predict_btn = st.button("Predict", use_container_width=True)
with col2:
example_btn = st.button("Use example", use_container_width=True)
if example_btn:
text = default_example
st.session_state["last_text"] = text
if "last_text" in st.session_state and not text.strip():
text = st.session_state["last_text"]
st.markdown("---")
if predict_btn:
if not text.strip():
st.warning("Please enter some text.")
else:
pred = int(pipeline.predict([text])[0])
st.subheader("Result")
if pred == 1:
st.error("Prediction: **Stress (1)**")
else:
st.success("Prediction: **No Stress (0)**")
if hasattr(pipeline, "predict_proba"):
proba = pipeline.predict_proba([text])[0] # [P(0), P(1)]
st.write(f"Confidence (No Stress): **{proba[0]*100:.2f}%**")
st.write(f"Confidence (Stress): **{proba[1]*100:.2f}%**")
st.progress(float(proba[1]))
st.caption("Saved model: tfidf_lr_pipeline.pkl (TF-IDF + Logistic Regression)")