Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +106 -38
src/streamlit_app.py
CHANGED
|
@@ -1,40 +1,108 @@
|
|
| 1 |
-
import altair as alt
|
| 2 |
-
import numpy as np
|
| 3 |
-
import pandas as pd
|
| 4 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
+
import pickle
|
| 3 |
+
from collections import Counter
|
| 4 |
+
import re
|
| 5 |
+
from typing import Counter as TCounter, Tuple, List, Any
|
| 6 |
|
| 7 |
+
# --- 1. CONFIGURATION ---
|
| 8 |
+
|
| 9 |
+
# The n-gram range used during model training (e.g., (1, 4) for unigrams up to 4-grams)
|
| 10 |
+
N_GRAM_RANGE = (1, 4)
|
| 11 |
+
# Filenames saved in the previous step
|
| 12 |
+
MODEL_FILE = 'src/emotion.pkl'
|
| 13 |
+
VECTORIZER_FILE = 'src/vectorizer.pkl'
|
| 14 |
+
|
| 15 |
+
# --- 2. LOAD ARTIFACTS ---
|
| 16 |
+
|
| 17 |
+
@st.cache_resource
|
| 18 |
+
def load_artifacts():
|
| 19 |
+
"""Loads the saved classifier model and DictVectorizer."""
|
| 20 |
+
try:
|
| 21 |
+
# Load the Model
|
| 22 |
+
with open(MODEL_FILE, 'rb') as model_file:
|
| 23 |
+
loaded_model = pickle.load(model_file)
|
| 24 |
+
|
| 25 |
+
# Load the Vectorizer
|
| 26 |
+
with open(VECTORIZER_FILE, 'rb') as vec_file:
|
| 27 |
+
loaded_vectorizer = pickle.load(vec_file)
|
| 28 |
+
|
| 29 |
+
return loaded_model, loaded_vectorizer
|
| 30 |
+
except FileNotFoundError:
|
| 31 |
+
st.error(f"Error: Required files ({MODEL_FILE} or {VECTORIZER_FILE}) not found. Please ensure they are in the correct directory.")
|
| 32 |
+
return None, None
|
| 33 |
+
|
| 34 |
+
# --- 3. FEATURE EXTRACTION FUNCTION (CRITICAL!) ---
|
| 35 |
+
|
| 36 |
+
# This function MUST be identical to the one used during model training.
|
| 37 |
+
def create_feature(text: str, nrange: Tuple[int, int]) -> TCounter[str]:
|
| 38 |
+
"""Extracts n-gram and punctuation features from a text string."""
|
| 39 |
+
text_features: List[str] = []
|
| 40 |
+
lower_text = text.lower()
|
| 41 |
+
|
| 42 |
+
# Word N-Grams
|
| 43 |
+
text_alphanum = re.sub(r'[^a-z0-9#]', ' ', lower_text)
|
| 44 |
+
token = text_alphanum.split()
|
| 45 |
+
|
| 46 |
+
for n in range(nrange[0], nrange[1] + 1):
|
| 47 |
+
if n > 0 and n <= len(token):
|
| 48 |
+
ngrams = [' '.join(token[i-n:i]) for i in range(n, len(token) + 1)]
|
| 49 |
+
text_features.extend(ngrams)
|
| 50 |
+
|
| 51 |
+
# Punctuation Features
|
| 52 |
+
text_punc = re.sub(r'[a-z0-9]', ' ', lower_text)
|
| 53 |
+
text_features.extend(text_punc.split())
|
| 54 |
+
|
| 55 |
+
return Counter(text_features)
|
| 56 |
+
|
| 57 |
+
# --- 4. PREDICTION LOGIC ---
|
| 58 |
+
|
| 59 |
+
def predict_emotion(text: str, model: Any, vectorizer: Any) -> str:
|
| 60 |
+
"""Processes text and returns the predicted emotion label."""
|
| 61 |
+
if not text:
|
| 62 |
+
return "Please enter text for analysis."
|
| 63 |
+
|
| 64 |
+
# 1. Convert Text to Features (Counter object)
|
| 65 |
+
feature_counter = create_feature(text, N_GRAM_RANGE)
|
| 66 |
+
|
| 67 |
+
# 2. Vectorization (DictVectorizer expects a list of dictionaries/Counters)
|
| 68 |
+
# The saved vectorizer is used to ensure the features are ordered correctly.
|
| 69 |
+
X_processed = vectorizer.transform([feature_counter])
|
| 70 |
+
|
| 71 |
+
# 3. Make Prediction
|
| 72 |
+
prediction = model.predict(X_processed)
|
| 73 |
+
|
| 74 |
+
return prediction[0]
|
| 75 |
+
|
| 76 |
+
# --- 5. STREAMLIT UI ---
|
| 77 |
+
|
| 78 |
+
# Load the model artifacts
|
| 79 |
+
model, vectorizer = load_artifacts()
|
| 80 |
+
|
| 81 |
+
if model and vectorizer:
|
| 82 |
+
st.title("π£οΈ Text Emotion Detection App")
|
| 83 |
+
st.markdown("Enter a sentence or text below to see the predicted emotion.")
|
| 84 |
+
|
| 85 |
+
# User input area
|
| 86 |
+
user_input = st.text_area("Enter your text here:", "")
|
| 87 |
+
|
| 88 |
+
if st.button("Predict Emotion"):
|
| 89 |
+
if user_input:
|
| 90 |
+
# Perform prediction
|
| 91 |
+
result = predict_emotion(user_input, model, vectorizer)
|
| 92 |
+
|
| 93 |
+
# --- Result Display (Using visual cues) ---
|
| 94 |
+
st.subheader("Analysis Result")
|
| 95 |
+
|
| 96 |
+
# Simple color-coding based on common emotions
|
| 97 |
+
if result == 'joy':
|
| 98 |
+
st.success(f"Predicted Emotion: **{result.upper()}** π")
|
| 99 |
+
elif result in ['sadness', 'fear']:
|
| 100 |
+
st.warning(f"Predicted Emotion: **{result.upper()}** π")
|
| 101 |
+
elif result == 'anger':
|
| 102 |
+
st.error(f"Predicted Emotion: **{result.upper()}** π‘")
|
| 103 |
+
elif result == 'disgust':
|
| 104 |
+
st.markdown(f"Predicted Emotion: **{result.upper()}** π€’", unsafe_allow_html=True)
|
| 105 |
+
else:
|
| 106 |
+
st.info(f"Predicted Emotion: **{result.upper()}**")
|
| 107 |
+
else:
|
| 108 |
+
st.warning("Please enter some text to predict.")
|