File size: 3,125 Bytes
eb70157
 
65ec8db
5b918a8
65ec8db
 
eb70157
65ec8db
 
 
 
 
 
5b918a8
eb70157
65ec8db
5b918a8
 
65ec8db
eb70157
5b918a8
eb70157
5b918a8
 
65ec8db
 
eb70157
5b918a8
eb70157
5b918a8
 
fb660d2
 
 
 
 
 
 
 
 
 
eb70157
7f80422
604c8fd
 
 
 
eb70157
604c8fd
 
 
 
 
eb70157
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb660d2
eb70157
fb660d2
eb70157
604c8fd
 
 
 
 
 
 
 
 
 
 
eb70157
 
fb660d2
 
 
604c8fd
eb70157
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# 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)")