enigmaize commited on
Commit
c7cadf9
·
verified ·
1 Parent(s): 1509c4d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +16 -44
app.py CHANGED
@@ -5,48 +5,29 @@ import json
5
  import pickle
6
  import re
7
 
8
- # Create a simple fallback prediction function
9
- def predict_emotion_fallback(text, top_k=5):
10
- """Fallback prediction function for testing"""
11
- # Return some sample predictions for demonstration
12
- sample_predictions = [
13
- ("Wonder", 42.88),
14
- ("Relief", 6.86),
15
- ("Intrigue", 6.62),
16
- ("Joy", 5.31),
17
- ("Curiosity", 4.97)
18
- ]
19
- return sample_predictions[:top_k]
20
-
21
- # Load saved components with comprehensive error handling
22
  def load_model_components():
23
- """Load all saved model components with error handling"""
24
  try:
25
- # Try to import tensorflow components
26
  from tensorflow.keras.models import load_model
27
  from tensorflow.keras.preprocessing.text import Tokenizer
28
  from tensorflow.keras.preprocessing.sequence import pad_sequences
29
 
30
- # Load model
31
  model = load_model('best_emotion_model.h5')
32
 
33
- # Load tokenizer
34
  with open('tokenizer.pickle', 'rb') as handle:
35
  tokenizer = pickle.load(handle)
36
 
37
- # Load label encoder
38
  with open('label_encoder.pickle', 'rb') as handle:
39
  label_encoder = pickle.load(handle)
40
 
41
- # Load config
42
  with open('model_config.json', 'r') as f:
43
  config = json.load(f)
44
 
45
  return model, tokenizer, label_encoder, config
46
 
47
  except Exception as e:
48
- print(f"Model loading error: {str(e)}")
49
- return None, None, None, None
50
 
51
  # Text cleaning function
52
  def clean_text(text, labels_to_remove=[]):
@@ -74,17 +55,11 @@ def clean_text(text, labels_to_remove=[]):
74
 
75
  return text
76
 
77
- # Prediction function with fallback
78
  def predict_emotion(text, top_k=5):
79
  """Predict emotion from text with top-k confidence scores"""
80
- # Get model components
81
- model, tokenizer, label_encoder, config = load_model_components()
82
-
83
- # If model failed to load, use fallback
84
- if model is None or tokenizer is None or label_encoder is None:
85
- return predict_emotion_fallback(text, top_k)
86
-
87
  try:
 
88
  MAX_LEN = config['MAX_LEN']
89
 
90
  # Clean text
@@ -113,8 +88,7 @@ def predict_emotion(text, top_k=5):
113
  return results
114
 
115
  except Exception as e:
116
- print(f"Prediction error: {str(e)}")
117
- return predict_emotion_fallback(text, top_k)
118
 
119
  # Gradio interface
120
  def emotion_classifier(text, top_k):
@@ -128,20 +102,18 @@ def emotion_classifier(text, top_k):
128
  if not predictions or len(predictions) == 0:
129
  return "❌ No predictions generated. Please try different text."
130
 
131
- # Format results as HTML table for better display
132
- result_html = f"<h3>Emotion Predictions for:</h3><p>{text}</p>"
133
- result_html += "<table border='1' cellpadding='5' cellspacing='0' style='border-collapse: collapse;'>"
134
- result_html += "<tr><th>Emotion</th><th>Confidence (%)</th></tr>"
135
 
136
  for emotion, confidence in predictions:
137
  if confidence > 0:
138
- result_html += f"<tr><td>{emotion}</td><td>{confidence:.2f}%</td></tr>"
139
  else:
140
- result_html += f"<tr><td>{emotion}</td><td>Not available</td></tr>"
141
-
142
- result_html += "</table>"
143
 
144
- return result_html
145
 
146
  except Exception as e:
147
  return f"❌ Error during analysis: {str(e)}"
@@ -160,7 +132,7 @@ with gr.Blocks(title="Emotion Classification App", theme=gr.themes.Soft()) as de
160
  label="Enter Text for Emotion Analysis",
161
  placeholder="Type your text here (e.g., 'I feel so happy about my achievements!')",
162
  lines=5,
163
- value="I heard that rumor about my colleague, and honestly, I feel a rush of competitive schadenfreude."
164
  )
165
 
166
  top_k_slider = gr.Slider(
@@ -188,9 +160,9 @@ with gr.Blocks(title="Emotion Classification App", theme=gr.themes.Soft()) as de
188
  )
189
 
190
  with gr.Column():
191
- output = gr.HTML(
192
  label="Emotion Predictions",
193
- value="<p>Enter text and click 'Analyze Emotions' to see predictions.</p>"
194
  )
195
 
196
  submit_btn.click(
 
5
  import pickle
6
  import re
7
 
8
+ # Load saved components
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  def load_model_components():
10
+ """Load all saved model components"""
11
  try:
 
12
  from tensorflow.keras.models import load_model
13
  from tensorflow.keras.preprocessing.text import Tokenizer
14
  from tensorflow.keras.preprocessing.sequence import pad_sequences
15
 
 
16
  model = load_model('best_emotion_model.h5')
17
 
 
18
  with open('tokenizer.pickle', 'rb') as handle:
19
  tokenizer = pickle.load(handle)
20
 
 
21
  with open('label_encoder.pickle', 'rb') as handle:
22
  label_encoder = pickle.load(handle)
23
 
 
24
  with open('model_config.json', 'r') as f:
25
  config = json.load(f)
26
 
27
  return model, tokenizer, label_encoder, config
28
 
29
  except Exception as e:
30
+ raise ImportError(f"Error loading model components: {str(e)}")
 
31
 
32
  # Text cleaning function
33
  def clean_text(text, labels_to_remove=[]):
 
55
 
56
  return text
57
 
58
+ # Prediction function
59
  def predict_emotion(text, top_k=5):
60
  """Predict emotion from text with top-k confidence scores"""
 
 
 
 
 
 
 
61
  try:
62
+ model, tokenizer, label_encoder, config = load_model_components()
63
  MAX_LEN = config['MAX_LEN']
64
 
65
  # Clean text
 
88
  return results
89
 
90
  except Exception as e:
91
+ return [("Error", 0.0)]
 
92
 
93
  # Gradio interface
94
  def emotion_classifier(text, top_k):
 
102
  if not predictions or len(predictions) == 0:
103
  return "❌ No predictions generated. Please try different text."
104
 
105
+ # Format results
106
+ result_text = f"**Emotion Predictions for:** {text}\n\n"
107
+ result_text += "| Emotion | Confidence (%) |\n"
108
+ result_text += "|---------|----------------|\n"
109
 
110
  for emotion, confidence in predictions:
111
  if confidence > 0:
112
+ result_text += f"| {emotion} | {confidence:.2f} |\n"
113
  else:
114
+ result_text += f"| {emotion} | Not available |\n"
 
 
115
 
116
+ return result_text
117
 
118
  except Exception as e:
119
  return f"❌ Error during analysis: {str(e)}"
 
132
  label="Enter Text for Emotion Analysis",
133
  placeholder="Type your text here (e.g., 'I feel so happy about my achievements!')",
134
  lines=5,
135
+ value="I made the mistake, but I'm determined to fix it immediately and ensure it never happens again"
136
  )
137
 
138
  top_k_slider = gr.Slider(
 
160
  )
161
 
162
  with gr.Column():
163
+ output = gr.Markdown(
164
  label="Emotion Predictions",
165
+ value="Enter text and click 'Analyze Emotions' to see predictions."
166
  )
167
 
168
  submit_btn.click(