handex commited on
Commit
e51a2fd
Β·
verified Β·
1 Parent(s): 20b99de

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. 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
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
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.")