Spaces:
Runtime error
Runtime error
File size: 3,111 Bytes
038c0c5 6c7e4fb 038c0c5 16cc0a9 376a330 16cc0a9 6c7e4fb 16cc0a9 6c7e4fb 16cc0a9 6c7e4fb 16cc0a9 6c7e4fb 16cc0a9 6c7e4fb 16cc0a9 6c7e4fb 16cc0a9 6c7e4fb 16cc0a9 6c7e4fb 16cc0a9 6c7e4fb 16cc0a9 6c7e4fb 16cc0a9 6c7e4fb 16cc0a9 6c7e4fb 16cc0a9 6c7e4fb 16cc0a9 6c7e4fb 16cc0a9 6c7e4fb 16cc0a9 6c7e4fb 16cc0a9 6c7e4fb 16cc0a9 | 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 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 | import streamlit as st
import pickle
import re
import nltk
from nltk.corpus import stopwords
from nltk.stem import SnowballStemmer
from typing import Any
# --- Configuration ---
MODEL_FILE = "src/stress_detectipn.pkl"
VECTORIZER_FILE = "src/vectorizer.pkl"
# Make sure stopwords are available on HF Spaces
try:
nltk.data.find("corpora/stopwords")
except LookupError:
nltk.download("stopwords")
# Preprocessing tools
stemmer = SnowballStemmer("english")
stop_words_set = set(stopwords.words("english"))
# --- 1. Load Model + Vectorizer ---
@st.cache_resource
def load_artifacts():
"""Load trained model and vectorizer."""
try:
with open(MODEL_FILE, "rb") as model_file:
model = pickle.load(model_file)
with open(VECTORIZER_FILE, "rb") as vec_file:
vectorizer = pickle.load(vec_file)
return model, vectorizer
except FileNotFoundError:
st.error(
f"Error: Required files ({MODEL_FILE} or {VECTORIZER_FILE}) were not found. "
"Please upload them to the Space."
)
return None, None
# --- 2. Preprocessing Pipeline ---
def preprocess_text(text: str) -> str:
"""Clean and prepare text exactly as in training."""
text = str(text).lower()
# Remove brackets, URLs, HTML
text = re.sub(r"\[.*?\]", "", text)
text = re.sub(r"https?://\S+|www\.\S+", "", text)
text = re.sub(r"<.*?>", "", text)
# Remove punctuation and special characters
text = re.sub(r"[^\w\s]", "", text)
text = re.sub(r"[^a-zA-Z0-9]", " ", text)
# Remove numbers, extra spaces
text = re.sub(r"\w*\d\w*", "", text)
text = re.sub(r"\s+", " ", text).strip()
# Token list
tokens = text.split()
# Remove stopwords
tokens = [w for w in tokens if w not in stop_words_set]
# Stemming
tokens = [stemmer.stem(w) for w in tokens]
return " ".join(tokens)
# --- 3. Prediction Logic ---
def predict_stress(text: str, model: Any, vectorizer: Any) -> str:
"""Return model prediction as label ('Stress' / 'No Stress')."""
if not text:
return "Please enter text."
cleaned = preprocess_text(text)
X = vectorizer.transform([cleaned])
# Your model already returns the final string label
prediction = model.predict(X)[0]
return prediction
# --- 4. Streamlit UI ---
model, vectorizer = load_artifacts()
if model and vectorizer:
st.title("🧠 Stress Detection System")
st.write("Enter any text and the model will classify it as **Stress** or **No Stress**.")
user_input = st.text_area("Enter your text here:", "")
if st.button("Analyze"):
if not user_input.strip():
st.warning("Please enter some text.")
else:
result = predict_stress(user_input, model, vectorizer)
st.subheader("Result")
if result == "Stress":
st.error(f"Prediction: **{result}** 😥")
elif result == "No Stress":
st.success(f"Prediction: **{result}** 😊")
else:
st.info(f"Prediction: **{result}**")
|