Methni commited on
Commit
5ff6559
·
verified ·
1 Parent(s): 79c330c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +518 -296
app.py CHANGED
@@ -9,7 +9,7 @@ from sklearn.metrics import accuracy_score, precision_recall_fscore_support, con
9
  from sklearn.feature_extraction.text import TfidfVectorizer
10
  from sklearn.metrics.pairwise import cosine_similarity
11
  from setfit import SetFitModel
12
- from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoModelForMaskedLM
13
  import io
14
  import tempfile
15
  import os
@@ -17,25 +17,46 @@ from PIL import Image
17
  import gradio as gr
18
  from huggingface_hub import hf_hub_download
19
 
20
- #CONFIG
21
- HF_USERNAME = "Methni"
22
- SETFIT_REPO = f"{HF_USERNAME}/STEMO-SetFit"
23
- FINETUNED_REPO = f"{HF_USERNAME}/STEMO-XLMRoberta-Finetuned"
24
- DATASET_REPO = f"{HF_USERNAME}/STEMO-Dataset"
25
 
26
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
27
  print(f"Using device: {device}")
28
 
29
- # PREPROCESSING
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  def clean_text_setfit(text):
31
  if not isinstance(text, str): return ""
32
  text = re.sub(r'http\S+', '', text)
 
33
  text = re.sub(r'\s+', ' ', text).strip()
34
  text = emoji.demojize(text)
35
  return text
36
 
37
- clean_text_finetuned = clean_text_setfit
38
-
39
  def clean_text_fewshot(text):
40
  if not isinstance(text, str): return ""
41
  text = re.sub(r'http\S+', '', text)
@@ -45,9 +66,11 @@ def clean_text_fewshot(text):
45
  return text
46
 
47
  def detect_language_stats(text):
48
- sinhala = len(re.findall(r'[\u0D80-\u0DFF]', text))
49
- tamil = len(re.findall(r'[\u0B80-\u0BFF]', text))
50
- english = len(re.findall(r'[a-zA-Z]', text))
 
 
51
  total = sinhala + tamil + english
52
  if total == 0:
53
  return {'sinhala': 0, 'tamil': 0, 'english': 0, 'is_code_mixed': False}
@@ -58,14 +81,14 @@ def detect_language_stats(text):
58
  'is_code_mixed': sinhala > 0 and tamil > 0
59
  }
60
 
61
- # FEW-SHOT COMPONENTS
62
  class SmartExampleSelector:
63
  def __init__(self, support_df):
64
- self.support_df = support_df.reset_index(drop=True)
65
- self.vectorizer = TfidfVectorizer(analyzer='char', ngram_range=(3, 5), min_df=2)
66
- cleaned = [clean_text_fewshot(t) for t in self.support_df['text']]
67
  self.support_vecs = self.vectorizer.fit_transform(cleaned)
68
- print(f"✓ Selector ready with {len(self.support_df)} examples")
69
 
70
  def get_k_similar(self, query_text, k=3):
71
  query_vec = self.vectorizer.transform([query_text])
@@ -75,27 +98,25 @@ class SmartExampleSelector:
75
 
76
  class FewShotClassifier:
77
  def __init__(self):
78
- print("Loading few-shot model (xlm-roberta-base)...")
79
  self.tokenizer = AutoTokenizer.from_pretrained("xlm-roberta-base")
80
- self.model = AutoModelForMaskedLM.from_pretrained("xlm-roberta-base").to(device)
81
  self.model.eval()
82
- self.label_map = {
83
  'Happy': 'happy', 'Anger': 'mad', 'Sadness': 'sad',
84
  'Fear': 'fear', 'Surprise': 'shock', 'Disgust': 'gross'
85
  }
86
- self.logit_bias = {
87
- 'Anger': 0.25, 'Disgust': 2.2, 'Fear': 3.0,
88
- 'Sadness': 1.6, 'Happy': 0.2, 'Surprise': -1.4
89
- }
90
- self.labels = list(self.label_map.keys())
91
  self.verbalizer_ids = [
92
  self.tokenizer.encode(self.label_map[l], add_special_tokens=False)[0]
93
  for l in self.labels
94
  ]
95
- print("✓ Few-shot model ready")
96
 
97
  def get_logits(self, prompt):
98
- inputs = self.tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512).to(device)
 
99
  mask_idx = (inputs.input_ids == self.tokenizer.mask_token_id)[0].nonzero(as_tuple=True)[0]
100
  if len(mask_idx) == 0:
101
  return torch.zeros(len(self.verbalizer_ids))
@@ -109,11 +130,11 @@ class FewShotClassifier:
109
  for _, row in examples.iterrows():
110
  prompt += f"Tweet: {row['text']} \nEmotion: {self.label_map[row['label']]}\n\n"
111
  prompt += f"Tweet: {text} \nEmotion: {self.tokenizer.mask_token}"
112
- raw = self.get_logits(prompt)
113
- null_p = f"Tweet: [N/A] \nEmotion: {self.tokenizer.mask_token}"
114
- bias = self.get_logits(null_p)
115
- scores = [(raw[i] - bias[i]) + self.logit_bias[l] for i, l in enumerate(self.labels)]
116
- probs = torch.softmax(torch.tensor(scores), dim=0).cpu().numpy()
117
  return self.labels[int(np.argmax(scores))], probs
118
 
119
  # MODEL MANAGER
@@ -123,15 +144,13 @@ class ModelManager:
123
  self.setfit_model = None
124
  self.fewshot_classifier = None
125
  self.fewshot_selector = None
126
- self.finetuned_model = None
127
- self.finetuned_tokenizer = None
128
 
129
  def load_all_models(self):
130
  print("=" * 60)
131
- print("LOADING ALL MODELS")
132
  print("=" * 60)
133
 
134
- # 1. SetFit
135
  try:
136
  print("\n1. Loading SetFit...")
137
  self.setfit_model = SetFitModel.from_pretrained(SETFIT_REPO)
@@ -140,27 +159,15 @@ class ModelManager:
140
  except Exception as e:
141
  print(f" ✗ {e}")
142
 
143
- # 2. Fine-tuned XLM-R
144
  try:
145
- print("\n2. Loading Fine-Tuned XLM-RoBERTa...")
146
- self.finetuned_model = AutoModelForSequenceClassification.from_pretrained(
147
- FINETUNED_REPO
148
- ).to(device)
149
- self.finetuned_model.eval()
150
- self.finetuned_tokenizer = AutoTokenizer.from_pretrained("xlm-roberta-base")
151
- print(" ✓ Fine-tuned loaded")
152
- except Exception as e:
153
- print(f" ✗ {e}")
154
-
155
- # 3. Few-shot
156
- try:
157
- print("\n3. Loading Few-Shot components...")
158
- train_path = hf_hub_download(
159
  repo_id=DATASET_REPO,
160
- filename="STEMO_Train.xlsx",
161
  repo_type="dataset"
162
  )
163
- train_df = pd.read_excel(train_path)
164
  self.fewshot_selector = SmartExampleSelector(train_df)
165
  self.fewshot_classifier = FewShotClassifier()
166
  print(" ✓ Few-shot loaded")
@@ -168,322 +175,537 @@ class ModelManager:
168
  print(f" ✗ {e}")
169
 
170
  print("\n" + "=" * 60)
171
- print("READY")
172
  print("=" * 60)
173
 
174
- # prediction methods
175
  def predict_setfit(self, text):
176
- if self.setfit_model is None: return {'error': 'SetFit not loaded'}
 
177
  processed = clean_text_setfit(text)
178
- lang = detect_language_stats(processed)
179
  try:
180
  predictions = self.setfit_model.predict([processed])
181
  probs = self.setfit_model.predict_proba([processed])[0]
182
  prediction = predictions[0]
183
  confidence = float(probs.max())
184
- emotion = (self.label_names[prediction]
185
- if isinstance(prediction, (int, np.integer)) else prediction)
186
  result = {
187
- 'model': 'SetFit', 'emotion': emotion, 'confidence': confidence,
 
188
  'all_scores': {self.label_names[i]: float(probs[i]) for i in range(len(probs))},
189
  'lang': lang,
190
  }
191
- if confidence < 0.5: result['warning'] = 'Low confidence'
192
- return result
193
- except Exception as e:
194
- return {'error': str(e)}
195
-
196
- def predict_finetuned(self, text):
197
- if self.finetuned_model is None: return {'error': 'Fine-tuned not loaded'}
198
- processed = clean_text_finetuned(text)
199
- lang = detect_language_stats(processed)
200
- try:
201
- inputs = self.finetuned_tokenizer(
202
- processed, return_tensors="pt", truncation=True, max_length=128, padding=True
203
- ).to(device)
204
- with torch.no_grad():
205
- probs = torch.softmax(self.finetuned_model(**inputs).logits, dim=1)[0].cpu().numpy()
206
- idx = int(probs.argmax())
207
- emotion = (self.finetuned_model.config.id2label[idx]
208
- if hasattr(self.finetuned_model.config, 'id2label')
209
- else self.label_names[idx])
210
- result = {
211
- 'model': 'Fine-Tuned', 'emotion': emotion, 'confidence': float(probs[idx]),
212
- 'all_scores': {self.label_names[i]: float(probs[i]) for i in range(len(probs))},
213
- 'lang': lang,
214
- }
215
- if result['confidence'] < 0.5: result['warning'] = 'Low confidence'
216
  return result
217
  except Exception as e:
218
  return {'error': str(e)}
219
 
220
  def predict_fewshot(self, text):
221
- if self.fewshot_classifier is None: return {'error': 'Few-shot not loaded'}
 
222
  processed = clean_text_fewshot(text)
223
- lang = detect_language_stats(processed)
224
  try:
225
- examples = self.fewshot_selector.get_k_similar(processed, k=3)
226
- emotion, probs = self.fewshot_classifier.predict(processed, examples)
 
227
  result = {
228
- 'model': 'Few-Shot', 'emotion': emotion, 'confidence': float(probs.max()),
229
  'all_scores': {self.label_names[i]: float(probs[i]) for i in range(len(probs))},
230
  'lang': lang,
231
  }
232
- if result['confidence'] < 0.5: result['warning'] = 'Low confidence'
233
  return result
234
  except Exception as e:
235
  return {'error': str(e)}
236
 
237
  def predict_all(self, text):
238
  results = {}
239
- if self.setfit_model: results['SetFit'] = self.predict_setfit(text)
240
- if self.fewshot_classifier: results['Few-Shot'] = self.predict_fewshot(text)
241
- if self.finetuned_model: results['Fine-Tuned'] = self.predict_finetuned(text)
242
  return results
243
 
244
- # INITIALIZE ONCE AT STARTUP
 
 
 
 
 
245
  model_manager = ModelManager()
246
  model_manager.load_all_models()
247
 
248
- # UI HELPER FUNCTIONS
249
- def build_result_text(result):
250
- lang = result.get('lang', {})
251
- output = (
252
- f"### Prediction\n"
253
- f"**Model:** {result['model']} \n"
254
- f"**Emotion:** {result['emotion']} \n"
255
- f"**Confidence:** {result['confidence']:.2%}\n"
256
- )
257
- if result.get('warning'): output += f"\n{result['warning']}\n"
258
- output += (
259
- f"\n### Language\n"
260
- f"- Sinhala: {lang.get('sinhala',0):.1%} \n"
261
- f"- Tamil: {lang.get('tamil',0):.1%} \n"
262
- f"- English: {lang.get('english',0):.1%} \n"
263
- f"- Code-Mixed: {'Yes' if lang.get('is_code_mixed') else 'No'}\n"
264
- )
265
- return output
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
266
 
267
- def build_score_plot(all_scores):
268
- emotions = list(all_scores.keys())
269
- scores = list(all_scores.values())
270
- colors = ['#FFD700','#FF4444','#4169E1','#9370DB','#FF8C00','#228B22']
271
- fig, ax = plt.subplots(figsize=(9, 4))
272
- bars = ax.barh(emotions, scores, color=colors, alpha=0.8, edgecolor='black')
273
- ax.set_xlabel('Confidence', fontweight='bold')
274
- ax.set_title('Emotion Scores', fontweight='bold')
275
- ax.set_xlim([0, 1])
276
- for bar in bars:
277
- w = bar.get_width()
278
- ax.text(w, bar.get_y() + bar.get_height()/2,
279
- f'{w:.2%}', ha='left', va='center', fontweight='bold', fontsize=9)
280
- ax.grid(axis='x', alpha=0.3)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
281
  plt.tight_layout()
282
- buf = io.BytesIO(); plt.savefig(buf, format='png', dpi=100, bbox_inches='tight')
 
283
  buf.seek(0); img = Image.open(buf); plt.close()
284
  return img
285
 
286
- def save_df_to_temp_xlsx(df, filename="results.xlsx"):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
287
  path = os.path.join(tempfile.gettempdir(), filename)
288
  df.to_excel(path, index=False)
289
  return path
290
 
291
- # GRADIO CALLBACKS
292
- def gradio_predict_single(text, model_choice, show_details):
293
- if not text.strip(): return "Please enter a tweet!", None, None
294
- model_map = {
295
- 'SetFit': 'setfit',
296
- 'Few-Shot (Prompt-Based)': 'fewshot',
297
- 'Fine-Tuned XLM-RoBERTa': 'finetuned',
298
- }
299
- result = (model_manager.predict_setfit(text) if model_map[model_choice]=='setfit' else
300
- model_manager.predict_fewshot(text) if model_map[model_choice]=='fewshot' else
301
- model_manager.predict_finetuned(text))
302
- if 'error' in result: return f" {result['error']}", None, None
303
- scores_df = pd.DataFrame([
304
- {'Emotion': e, 'Confidence': f"{s:.2%}"}
305
- for e, s in sorted(result['all_scores'].items(), key=lambda x: -x[1])
306
- ])
307
- img = build_score_plot(result['all_scores']) if show_details else None
308
- return build_result_text(result), scores_df, img
309
-
310
- def gradio_compare_models(text):
311
- if not text.strip(): return "Please enter a tweet!", None, None
 
 
 
312
  results = model_manager.predict_all(text)
313
- output, comp = "# Model Comparison\n\n", []
314
- emotion_colors = {'Happy':'#FFD700','Anger':'#FF4444','Sadness':'#4169E1',
315
- 'Fear':'#9370DB','Surprise':'#FF8C00','Disgust':'#228B22'}
316
- for mname, result in results.items():
317
- if 'error' in result:
318
- output += f"## {mname}\n{result['error']}\n\n"; continue
319
- output += f"## {mname}\n- **Emotion:** {result['emotion']}\n- **Confidence:** {result['confidence']:.2%}\n\n"
320
- comp.append({'Model': mname, 'Emotion': result['emotion'],
321
- 'Confidence': f"{result['confidence']:.2%}", 'Score': result['confidence']})
322
- if not comp: return output, None, None
323
- comp_df = pd.DataFrame(comp)
324
- fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5))
325
- ax1.bar(comp_df['Model'], comp_df['Score'], color=['#1f77b4','#ff7f0e','#2ca02c'][:len(comp_df)], alpha=0.8, edgecolor='black')
326
- ax1.set_ylim([0,1]); ax1.axhline(0.5, color='red', linestyle='--')
327
- ax1.set_title('Confidence Comparison', fontweight='bold'); ax1.grid(axis='y', alpha=0.3)
328
- bar_colors = [emotion_colors.get(e,'gray') for e in comp_df['Emotion']]
329
- ax2.bar(comp_df['Model'], [1]*len(comp_df), color=bar_colors, alpha=0.7, edgecolor='black')
330
- ax2.set_yticks([]); ax2.set_title('Predicted Emotions', fontweight='bold')
331
- for i, (m, e) in enumerate(zip(comp_df['Model'], comp_df['Emotion'])):
332
- ax2.text(i, 0.5, e, ha='center', va='center', fontsize=11, fontweight='bold',
333
- color='white' if e != 'Happy' else 'black')
334
- plt.tight_layout()
335
- buf = io.BytesIO(); plt.savefig(buf, format='png', dpi=100, bbox_inches='tight')
336
- buf.seek(0); img = Image.open(buf); plt.close()
337
- return output, comp_df[['Model','Emotion','Confidence']], img
338
-
339
- def gradio_batch_process(file, model_choice, text_col):
340
- if file is None: return "Please upload a file!", None, None
341
- model_map = {'All Models':'all','SetFit':'setfit','Few-Shot':'fewshot','Fine-Tuned':'finetuned'}
342
- model = model_map.get(model_choice, 'setfit')
 
 
343
  try:
344
  df = pd.read_excel(file.name) if file.name.endswith('.xlsx') else pd.read_csv(file.name)
345
  if text_col not in df.columns:
346
- return f"Column '{text_col}' not found. Available: {', '.join(df.columns)}", None, None
347
- results = []
 
348
  for _, row in df.iterrows():
349
- text = row[text_col]
350
- preds = (model_manager.predict_all(text) if model=='all' else
351
- {'SetFit': model_manager.predict_setfit(text)} if model=='setfit' else
352
- {'Few-Shot': model_manager.predict_fewshot(text)} if model=='fewshot' else
353
- {'Fine-Tuned': model_manager.predict_finetuned(text)})
354
- result_row = row.to_dict()
355
- for mn, pred in preds.items():
356
- if 'error' not in pred:
357
- result_row[f'{mn}_Predicted_Emotion'] = pred['emotion']
358
- result_row[f'{mn}_Confidence'] = f"{pred['confidence']:.2%}"
359
- results.append(result_row)
360
- results_df = pd.DataFrame(results)
361
- path = save_df_to_temp_xlsx(results_df, "STEMO_Batch_Predictions.xlsx")
362
- status = f"### Done!\n- **Processed:** {len(df)} tweets\n- **Model:** {model_choice}"
363
- return status, results_df.head(10), gr.update(value=path, visible=True)
 
 
 
 
 
 
 
 
 
364
  except Exception as e:
365
- return f"Error: {e}", None, None
366
-
367
- def gradio_evaluate(file, model_choice, text_col, label_col):
368
- if file is None: return "Please upload a test file!", None, None, None
369
- model_map = {'SetFit':'setfit','Few-Shot':'fewshot','Fine-Tuned':'finetuned'}
370
- model = model_map.get(model_choice, 'setfit')
 
 
 
371
  try:
372
  df = pd.read_excel(file.name) if file.name.endswith('.xlsx') else pd.read_csv(file.name)
373
  if text_col not in df.columns or label_col not in df.columns:
374
- return f"Columns not found. Available: {', '.join(df.columns)}", None, None, None
375
- y_true, y_pred, confidences = [], [], []
 
376
  for _, row in df.iterrows():
377
- result = (model_manager.predict_setfit(row[text_col]) if model=='setfit' else
378
- model_manager.predict_fewshot(row[text_col]) if model=='fewshot' else
379
- model_manager.predict_finetuned(row[text_col]))
380
  if 'error' not in result:
381
- y_true.append(row[label_col]); y_pred.append(result['emotion'])
382
- confidences.append(result['confidence'])
 
383
  acc = accuracy_score(y_true, y_pred)
384
- prec, rec, f1, _ = precision_recall_fscore_support(y_true, y_pred, average='weighted', zero_division=0)
385
- output = (f"## Results — {model_choice}\n\n"
386
- f"- **Accuracy:** {acc:.2%}\n- **Precision:** {prec:.2%}\n"
387
- f"- **Recall:** {rec:.2%}\n- **F1:** {f1:.2%}\n\n"
 
 
 
 
 
 
388
  f"```\n{classification_report(y_true, y_pred, zero_division=0)}\n```")
389
  metrics_df = pd.DataFrame([
390
- {'Metric':'Accuracy','Score':f"{acc:.2%}"},{'Metric':'Precision','Score':f"{prec:.2%}"},
391
- {'Metric':'Recall','Score':f"{rec:.2%}"},{'Metric':'F1','Score':f"{f1:.2%}"},
 
 
 
392
  ])
393
- cm = confusion_matrix(y_true, y_pred, labels=model_manager.label_names)
394
- fig, ax = plt.subplots(figsize=(9, 7))
 
395
  sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',
396
- xticklabels=model_manager.label_names, yticklabels=model_manager.label_names)
397
- ax.set_title(f'{model_choice} — Confusion Matrix', fontweight='bold')
398
- ax.set_ylabel('True'); ax.set_xlabel('Predicted')
 
 
 
 
 
 
399
  plt.tight_layout()
400
- buf = io.BytesIO(); plt.savefig(buf, format='png', dpi=100, bbox_inches='tight')
 
401
  buf.seek(0); img = Image.open(buf); plt.close()
402
- results_df = df[[text_col, label_col]].copy()
403
- results_df['Predicted'] = y_pred
404
- results_df['Correct'] = results_df[label_col] == results_df['Predicted']
405
- path = os.path.join(tempfile.gettempdir(), f"STEMO_{model_choice}_Eval.xlsx")
 
 
 
406
  with pd.ExcelWriter(path, engine='openpyxl') as writer:
407
- results_df.to_excel(writer, sheet_name='Predictions', index=False)
408
- metrics_df.to_excel(writer, sheet_name='Metrics', index=False)
409
- return output, metrics_df, img, gr.update(value=path, visible=True)
 
410
  except Exception as e:
411
- return f"Error: {e}", None, None, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
412
 
413
- #GRADIO UI
414
- with gr.Blocks(theme=gr.themes.Soft(), title="STEMO") as demo:
415
  gr.HTML("""
416
- <div style='text-align:center;background:linear-gradient(135deg,#667eea,#764ba2);
417
- padding:30px;border-radius:15px;margin-bottom:20px;'>
418
- <h1 style='color:white;margin:0;font-size:2.5em;'>STEMO</h1>
419
- <p style='color:white;margin:10px 0 0;font-size:1.2em;'>
420
- Sinhala-Tamil Emotion Classification</p>
421
- <p style='color:rgba(255,255,255,.8);margin:5px 0 0;'>
422
- SetFit · Few-Shot XLM-RoBERTa · Fine-Tuned XLM-RoBERTa</p>
423
- </div>""")
 
 
 
424
 
425
  with gr.Tabs():
426
- with gr.Tab("Single Tweet"):
427
- gr.Markdown("### Predict emotion for a single tweet")
 
 
 
428
  with gr.Row():
 
 
 
 
429
  with gr.Column(scale=2):
430
- single_text = gr.Textbox(label="Tweet", lines=3, placeholder="Enter a Sinhala/Tamil tweet...")
431
- single_model = gr.Dropdown(
432
- choices=['SetFit','Few-Shot (Prompt-Based)','Fine-Tuned XLM-RoBERTa'],
433
- value='SetFit', label="Model")
434
- single_details = gr.Checkbox(label="Show chart", value=True)
435
- single_btn = gr.Button("Predict", variant="primary")
436
- single_output = gr.Markdown()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
437
  with gr.Row():
438
- single_table = gr.Dataframe(label="Scores")
439
- single_plot = gr.Image(label="Chart")
440
- single_btn.click(gradio_predict_single,
441
- [single_text, single_model, single_details],
442
- [single_output, single_table, single_plot])
443
- gr.Examples(
444
- examples=[["මං ගොඩක් සතුටුයි අද 😊","SetFit",True],
445
- ["வெகு சந்தோஷமா இருக்கு today! 🎉","SetFit",True],
446
- ["I'm really කනගාටුයි about this","Few-Shot (Prompt-Based)",True]],
447
- inputs=[single_text, single_model, single_details])
448
-
449
- with gr.Tab("Compare Models"):
450
- compare_text = gr.Textbox(label="Tweet", lines=3)
451
- compare_btn = gr.Button("Compare All Models", variant="primary")
452
- compare_out = gr.Markdown()
453
  with gr.Row():
454
- compare_table = gr.Dataframe(label="Predictions")
455
- compare_plot = gr.Image(label="Chart")
456
- compare_btn.click(gradio_compare_models,
457
- [compare_text], [compare_out, compare_table, compare_plot])
458
-
459
- with gr.Tab("Batch Processing"):
460
- batch_file = gr.File(label="Upload .xlsx or .csv", file_types=['.xlsx','.csv'])
461
- batch_text_col = gr.Textbox(label="Text Column", value="text")
462
- batch_model = gr.Dropdown(
463
- choices=['All Models','SetFit','Few-Shot','Fine-Tuned'], value='SetFit', label="Model")
464
- batch_btn = gr.Button("Process Batch", variant="primary")
465
- batch_output = gr.Markdown()
466
- batch_table = gr.Dataframe(label="Preview (first 10 rows)")
467
- batch_download = gr.File(label="⬇ Download Results", visible=True)
468
- batch_btn.click(gradio_batch_process,
469
- [batch_file, batch_model, batch_text_col],
470
- [batch_output, batch_table, batch_download])
471
-
472
- with gr.Tab("Model Evaluation"):
473
- eval_file = gr.File(label="Upload test .xlsx or .csv", file_types=['.xlsx','.csv'])
474
  with gr.Row():
475
- eval_text_col = gr.Textbox(label="Text Column", value="text")
476
- eval_label_col = gr.Textbox(label="Label Column", value="label")
477
- eval_model = gr.Dropdown(
478
- choices=['SetFit','Few-Shot','Fine-Tuned'], value='SetFit', label="Model")
479
- eval_btn = gr.Button("Evaluate", variant="primary")
480
- eval_output = gr.Markdown()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
481
  with gr.Row():
482
- eval_table = gr.Dataframe(label="Metrics")
483
- eval_plot = gr.Image(label="Confusion Matrix")
484
- eval_download = gr.File(label="⬇ Download Results", visible=True)
485
- eval_btn.click(gradio_evaluate,
486
- [eval_file, eval_model, eval_text_col, eval_label_col],
487
- [eval_output, eval_table, eval_plot, eval_download])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
488
 
489
  demo.launch()
 
9
  from sklearn.feature_extraction.text import TfidfVectorizer
10
  from sklearn.metrics.pairwise import cosine_similarity
11
  from setfit import SetFitModel
12
+ from transformers import AutoTokenizer, AutoModelForMaskedLM
13
  import io
14
  import tempfile
15
  import os
 
17
  import gradio as gr
18
  from huggingface_hub import hf_hub_download
19
 
20
+
21
+ HF_USERNAME = "Methni"
22
+ SETFIT_REPO = f"{HF_USERNAME}/STEMO-SetFit"
23
+ DATASET_REPO = f"{HF_USERNAME}/STEMO-Dataset"
 
24
 
25
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
26
  print(f"Using device: {device}")
27
 
28
+
29
+ EMOTION_INFO = {
30
+ 'Happy': {'emoji': '😊', 'color': '#FFD700', 'description': 'Joy, excitement, positivity'},
31
+ 'Anger': {'emoji': '😠', 'color': '#FF4444', 'description': 'Frustration, rage, irritation'},
32
+ 'Sadness': {'emoji': '😢', 'color': '#4169E1', 'description': 'Grief, disappointment, sorrow'},
33
+ 'Fear': {'emoji': '😨', 'color': '#9370DB', 'description': 'Worry, anxiety, dread'},
34
+ 'Surprise': {'emoji': '😲', 'color': '#FF8C00', 'description': 'Shock, astonishment, disbelief'},
35
+ 'Disgust': {'emoji': '🤢', 'color': '#228B22', 'description': 'Revulsion, distaste, contempt'},
36
+ }
37
+
38
+ MODEL_INFO = {
39
+ 'SetFit (Recommended)': {
40
+ 'key': 'setfit',
41
+ 'accuracy': '80.65%',
42
+ 'description': 'Best overall accuracy. Recommended for most users.',
43
+ },
44
+ 'Prompt-Based': {
45
+ 'key': 'fewshot',
46
+ 'accuracy': '58.71%',
47
+ 'description': 'Works without any training. More robust to very noisy text.',
48
+ },
49
+ }
50
+
51
+ # PREPROCESSING
52
  def clean_text_setfit(text):
53
  if not isinstance(text, str): return ""
54
  text = re.sub(r'http\S+', '', text)
55
+ text = re.sub(r'@\w+', '', text)
56
  text = re.sub(r'\s+', ' ', text).strip()
57
  text = emoji.demojize(text)
58
  return text
59
 
 
 
60
  def clean_text_fewshot(text):
61
  if not isinstance(text, str): return ""
62
  text = re.sub(r'http\S+', '', text)
 
66
  return text
67
 
68
  def detect_language_stats(text):
69
+ text_no_emoji = re.sub(r':[a-z_]+:', '', text)
70
+ text_no_emoji = re.sub(r'\b[a-z]+_[a-z_]+\b', '', text_no_emoji)
71
+ sinhala = len(re.findall(r'[\u0D80-\u0DFF]', text_no_emoji))
72
+ tamil = len(re.findall(r'[\u0B80-\u0BFF]', text_no_emoji))
73
+ english = len(re.findall(r'[a-zA-Z]', text_no_emoji))
74
  total = sinhala + tamil + english
75
  if total == 0:
76
  return {'sinhala': 0, 'tamil': 0, 'english': 0, 'is_code_mixed': False}
 
81
  'is_code_mixed': sinhala > 0 and tamil > 0
82
  }
83
 
84
+ # FEW-SHOT COMPONENTS
85
  class SmartExampleSelector:
86
  def __init__(self, support_df):
87
+ self.support_df = support_df.reset_index(drop=True)
88
+ self.vectorizer = TfidfVectorizer(analyzer='char', ngram_range=(3, 5), min_df=2)
89
+ cleaned = [clean_text_fewshot(t) for t in self.support_df['text']]
90
  self.support_vecs = self.vectorizer.fit_transform(cleaned)
91
+ print(f" Selector ready with {len(self.support_df)} examples")
92
 
93
  def get_k_similar(self, query_text, k=3):
94
  query_vec = self.vectorizer.transform([query_text])
 
98
 
99
  class FewShotClassifier:
100
  def __init__(self):
101
+ print("Loading few-shot model...")
102
  self.tokenizer = AutoTokenizer.from_pretrained("xlm-roberta-base")
103
+ self.model = AutoModelForMaskedLM.from_pretrained("xlm-roberta-base").to(device)
104
  self.model.eval()
105
+ self.label_map = {
106
  'Happy': 'happy', 'Anger': 'mad', 'Sadness': 'sad',
107
  'Fear': 'fear', 'Surprise': 'shock', 'Disgust': 'gross'
108
  }
109
+ self.logit_bias = {l: 0.0 for l in self.label_map}
110
+ self.labels = list(self.label_map.keys())
 
 
 
111
  self.verbalizer_ids = [
112
  self.tokenizer.encode(self.label_map[l], add_special_tokens=False)[0]
113
  for l in self.labels
114
  ]
115
+ print("Few-shot model loaded")
116
 
117
  def get_logits(self, prompt):
118
+ inputs = self.tokenizer(prompt, return_tensors="pt",
119
+ truncation=True, max_length=512).to(device)
120
  mask_idx = (inputs.input_ids == self.tokenizer.mask_token_id)[0].nonzero(as_tuple=True)[0]
121
  if len(mask_idx) == 0:
122
  return torch.zeros(len(self.verbalizer_ids))
 
130
  for _, row in examples.iterrows():
131
  prompt += f"Tweet: {row['text']} \nEmotion: {self.label_map[row['label']]}\n\n"
132
  prompt += f"Tweet: {text} \nEmotion: {self.tokenizer.mask_token}"
133
+ raw = self.get_logits(prompt)
134
+ null_prompt = f"Tweet: [N/A] \nEmotion: {self.tokenizer.mask_token}"
135
+ bias = self.get_logits(null_prompt)
136
+ scores = [(raw[i] - bias[i]) + self.logit_bias[l] for i, l in enumerate(self.labels)]
137
+ probs = torch.softmax(torch.tensor(scores), dim=0).cpu().numpy()
138
  return self.labels[int(np.argmax(scores))], probs
139
 
140
  # MODEL MANAGER
 
144
  self.setfit_model = None
145
  self.fewshot_classifier = None
146
  self.fewshot_selector = None
 
 
147
 
148
  def load_all_models(self):
149
  print("=" * 60)
150
+ print("LOADING MODELS FROM HUGGING FACE")
151
  print("=" * 60)
152
 
153
+ # 1. SetFit
154
  try:
155
  print("\n1. Loading SetFit...")
156
  self.setfit_model = SetFitModel.from_pretrained(SETFIT_REPO)
 
159
  except Exception as e:
160
  print(f" ✗ {e}")
161
 
162
+ # 2. Few-shot
163
  try:
164
+ print("\n2. Loading Few-Shot components...")
165
+ train_path = hf_hub_download(
 
 
 
 
 
 
 
 
 
 
 
 
166
  repo_id=DATASET_REPO,
167
+ filename="STEMO_Train_Balanced.xlsx",
168
  repo_type="dataset"
169
  )
170
+ train_df = pd.read_excel(train_path)
171
  self.fewshot_selector = SmartExampleSelector(train_df)
172
  self.fewshot_classifier = FewShotClassifier()
173
  print(" ✓ Few-shot loaded")
 
175
  print(f" ✗ {e}")
176
 
177
  print("\n" + "=" * 60)
178
+ print("ALL MODELS LOADED — STEMO READY")
179
  print("=" * 60)
180
 
 
181
  def predict_setfit(self, text):
182
+ if self.setfit_model is None:
183
+ return {'error': 'SetFit model not loaded'}
184
  processed = clean_text_setfit(text)
185
+ lang = detect_language_stats(processed)
186
  try:
187
  predictions = self.setfit_model.predict([processed])
188
  probs = self.setfit_model.predict_proba([processed])[0]
189
  prediction = predictions[0]
190
  confidence = float(probs.max())
191
+ emotion = (self.label_names[prediction]
192
+ if isinstance(prediction, (int, np.integer)) else prediction)
193
  result = {
194
+ 'model': 'SetFit (Recommended)', 'emotion': emotion,
195
+ 'confidence': confidence,
196
  'all_scores': {self.label_names[i]: float(probs[i]) for i in range(len(probs))},
197
  'lang': lang,
198
  }
199
+ if confidence < 0.5: result['warning'] = True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
  return result
201
  except Exception as e:
202
  return {'error': str(e)}
203
 
204
  def predict_fewshot(self, text):
205
+ if self.fewshot_classifier is None:
206
+ return {'error': 'Few-shot model not loaded'}
207
  processed = clean_text_fewshot(text)
208
+ lang = detect_language_stats(processed)
209
  try:
210
+ examples = self.fewshot_selector.get_k_similar(processed, k=3)
211
+ emotion, probs = self.fewshot_classifier.predict(processed, examples)
212
+ confidence = float(probs.max())
213
  result = {
214
+ 'model': 'Prompt-Based', 'emotion': emotion, 'confidence': confidence,
215
  'all_scores': {self.label_names[i]: float(probs[i]) for i in range(len(probs))},
216
  'lang': lang,
217
  }
218
+ if confidence < 0.5: result['warning'] = True
219
  return result
220
  except Exception as e:
221
  return {'error': str(e)}
222
 
223
  def predict_all(self, text):
224
  results = {}
225
+ if self.setfit_model: results['SetFit (Recommended)'] = self.predict_setfit(text)
226
+ if self.fewshot_classifier: results['Prompt-Based'] = self.predict_fewshot(text)
 
227
  return results
228
 
229
+ def predict_by_key(self, text, key):
230
+ if key == 'setfit': return self.predict_setfit(text)
231
+ if key == 'fewshot': return self.predict_fewshot(text)
232
+ return {'error': 'Unknown model'}
233
+
234
+ #INITIALIZE
235
  model_manager = ModelManager()
236
  model_manager.load_all_models()
237
 
238
+ # VISUALIZATION HELPERS
239
+ def build_confidence_chart(all_scores):
240
+ emotions = list(EMOTION_INFO.keys())
241
+ scores = [all_scores.get(e, 0) for e in emotions]
242
+ colors = [EMOTION_INFO[e]['color'] for e in emotions]
243
+ emojis = [EMOTION_INFO[e]['emoji'] for e in emotions]
244
+ labels = [f"{emojis[i]} {emotions[i]}" for i in range(len(emotions))]
245
+
246
+ fig, ax = plt.subplots(figsize=(10, 5))
247
+ fig.patch.set_facecolor('#FAFAFA')
248
+ ax.set_facecolor('#FAFAFA')
249
+ bars = ax.barh(labels, scores, color=colors, alpha=0.85,
250
+ edgecolor='white', linewidth=1.5, height=0.6)
251
+ max_idx = scores.index(max(scores))
252
+ bars[max_idx].set_edgecolor('#333333')
253
+ bars[max_idx].set_linewidth(2.5)
254
+ ax.set_xlabel('Confidence (higher = more certain)', fontsize=11)
255
+ ax.set_title('How confident is the model about each emotion?',
256
+ fontsize=13, fontweight='bold', pad=15)
257
+ ax.set_xlim([0, 1.15])
258
+ ax.xaxis.set_major_formatter(plt.FuncFormatter(lambda x, _: f'{x:.0%}'))
259
+ ax.tick_params(axis='y', labelsize=11)
260
+ ax.tick_params(axis='x', labelsize=10)
261
+ for i, (bar, score) in enumerate(zip(bars, scores)):
262
+ ax.text(score + 0.02, bar.get_y() + bar.get_height() / 2,
263
+ f'{score:.0%}', va='center', ha='left', fontsize=10,
264
+ fontweight='bold' if i == max_idx else 'normal', color='#222222')
265
+ ax.grid(axis='x', linestyle='--', alpha=0.4)
266
+ ax.spines['top'].set_visible(False)
267
+ ax.spines['right'].set_visible(False)
268
+ plt.tight_layout()
269
+ buf = io.BytesIO()
270
+ plt.savefig(buf, format='png', dpi=120, bbox_inches='tight')
271
+ buf.seek(0); img = Image.open(buf); plt.close()
272
+ return img
273
 
274
+ def build_comparison_chart(results):
275
+ model_names, confidences, emotions = [], [], []
276
+ for name, r in results.items():
277
+ if 'error' not in r:
278
+ model_names.append(name)
279
+ confidences.append(r['confidence'])
280
+ emotions.append(r['emotion'])
281
+ if not model_names: return None
282
+
283
+ fig, ax = plt.subplots(figsize=(10, 5))
284
+ fig.patch.set_facecolor('#FAFAFA')
285
+ ax.set_facecolor('#FAFAFA')
286
+ bar_colors = [EMOTION_INFO.get(e, {}).get('color', '#888888') for e in emotions]
287
+ bars = ax.bar(model_names, confidences, color=bar_colors, alpha=0.85,
288
+ edgecolor='white', linewidth=2, width=0.5)
289
+ ax.axhline(y=0.5, color='#CC0000', linestyle='--', linewidth=1.5,
290
+ label='Low-confidence threshold (50%)')
291
+ ax.set_ylabel('Confidence Score', fontsize=11)
292
+ ax.set_title('Which model is most confident — and what did each predict?',
293
+ fontsize=13, fontweight='bold', pad=15)
294
+ ax.set_ylim([0, 1.25])
295
+ ax.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, _: f'{x:.0%}'))
296
+ ax.tick_params(axis='x', labelsize=10)
297
+ ax.tick_params(axis='y', labelsize=10)
298
+ ax.legend(fontsize=9)
299
+ for bar, conf, emo in zip(bars, confidences, emotions):
300
+ info = EMOTION_INFO.get(emo, {})
301
+ em = info.get('emoji', '')
302
+ ax.text(bar.get_x() + bar.get_width() / 2, conf + 0.03,
303
+ f'{em} {emo}\n{conf:.0%}',
304
+ ha='center', va='bottom', fontsize=10, fontweight='bold')
305
+ ax.spines['top'].set_visible(False)
306
+ ax.spines['right'].set_visible(False)
307
+ ax.grid(axis='y', linestyle='--', alpha=0.4)
308
  plt.tight_layout()
309
+ buf = io.BytesIO()
310
+ plt.savefig(buf, format='png', dpi=120, bbox_inches='tight')
311
  buf.seek(0); img = Image.open(buf); plt.close()
312
  return img
313
 
314
+ def build_result_card(result):
315
+ if 'error' in result:
316
+ return f" **Something went wrong:** {result['error']}\n\nPlease check your input and try again."
317
+ emotion = result['emotion']
318
+ info = EMOTION_INFO.get(emotion, {})
319
+ em = info.get('emoji', '❓')
320
+ conf = result['confidence']
321
+ lang = result.get('lang', {})
322
+ if conf >= 0.75: conf_label = "🟢 High confidence"
323
+ elif conf >= 0.50: conf_label = "🟡 Moderate confidence"
324
+ else: conf_label = "🔴 Low confidence — the model is uncertain about this tweet"
325
+ lang_parts = []
326
+ if lang.get('sinhala', 0) > 0.05: lang_parts.append(f"Sinhala ({lang['sinhala']:.0%})")
327
+ if lang.get('tamil', 0) > 0.05: lang_parts.append(f"Tamil ({lang['tamil']:.0%})")
328
+ if lang.get('english', 0) > 0.05: lang_parts.append(f"English ({lang['english']:.0%})")
329
+ lang_str = " + ".join(lang_parts) if lang_parts else "Not detected"
330
+ mixed_str = "Yes — this is a code-mixed tweet" if lang.get('is_code_mixed') else "No"
331
+ output = f"""## {em} The detected emotion is **{emotion}**
332
+
333
+ > *{info.get('description', '')}*
334
+
335
+ | | |
336
+ |---|---|
337
+ | **Confidence** | {conf:.0%} — {conf_label} |
338
+ | **Languages detected** | {lang_str} |
339
+ | **Code-mixed?** | {mixed_str} |
340
+
341
+ ---
342
+ """
343
+ if result.get('warning'):
344
+ output += (
345
+ "\n> **Note:** The model is less than 50% confident about this result. "
346
+ "This can happen with very short tweets, unusual spelling, or mixed scripts. "
347
+ "Try rewording or using a different model.\n\n"
348
+ )
349
+ return output
350
+
351
+ def save_to_xlsx(df, filename="results.xlsx"):
352
  path = os.path.join(tempfile.gettempdir(), filename)
353
  df.to_excel(path, index=False)
354
  return path
355
 
356
+ # ── GRADIO TAB FUNCTIONS ──────────────────────────────────────
357
+ def tab_single(text, model_display_name):
358
+ if not text.strip():
359
+ return ("**Please type or paste a tweet above and click Analyse.**\n\n"
360
+ "You can mix Sinhala, Tamil, and English — emojis are welcome too! 😊",
361
+ None, None)
362
+ key = MODEL_INFO[model_display_name]['key']
363
+ result = model_manager.predict_by_key(text, key)
364
+ card = build_result_card(result)
365
+ chart = build_confidence_chart(result['all_scores']) if 'error' not in result else None
366
+ if 'error' not in result:
367
+ rows = sorted(result['all_scores'].items(), key=lambda x: -x[1])
368
+ table = pd.DataFrame([{
369
+ 'Emotion': f"{EMOTION_INFO[e]['emoji']} {e}",
370
+ 'Confidence': f"{s:.0%}",
371
+ 'What it means': EMOTION_INFO[e]['description']
372
+ } for e, s in rows])
373
+ else:
374
+ table = None
375
+ return card, table, chart
376
+
377
+ def tab_compare(text):
378
+ if not text.strip():
379
+ return ("**Please type or paste a tweet above and click Compare.**", None, None)
380
  results = model_manager.predict_all(text)
381
+ chart = build_comparison_chart(results)
382
+ output = "## Model Comparison Results\n\n"
383
+ output += ("Each STEMO model was run on your tweet independently. "
384
+ "The table below shows what each model predicted and how confident it was.\n\n")
385
+ rows = []
386
+ for name, r in results.items():
387
+ if 'error' not in r:
388
+ em = EMOTION_INFO.get(r['emotion'], {}).get('emoji', '')
389
+ conf = r['confidence']
390
+ note = ("🟢 High confidence" if conf >= 0.75 else
391
+ "🟡 Moderate confidence" if conf >= 0.50 else "🔴 Low confidence")
392
+ rows.append({'Model': name,
393
+ 'Predicted Emotion': f"{em} {r['emotion']}",
394
+ 'Confidence': f"{conf:.0%}",
395
+ 'Confidence Level': note})
396
+ table = pd.DataFrame(rows) if rows else None
397
+ if rows:
398
+ emotions_predicted = [r['emotion'] for r in results.values() if 'error' not in r]
399
+ if len(set(emotions_predicted)) == 1:
400
+ output += f" **All models agree: the emotion is {emotions_predicted[0]}.**\n\n"
401
+ else:
402
+ output += ("**The models disagree on this tweet.** "
403
+ "This often happens when the tweet is ambiguous or very short. "
404
+ "The **SetFit (Recommended)** result is usually the most reliable.\n\n")
405
+ return output, table, chart
406
+
407
+ def tab_batch(file, model_display_name, text_col):
408
+ if file is None:
409
+ return ("**Please upload a file to get started.**\n\n"
410
+ "Your file should be a spreadsheet (.xlsx) or CSV. "
411
+ "The default tweet column name is **text**.", None, None)
412
+ key = MODEL_INFO[model_display_name]['key']
413
  try:
414
  df = pd.read_excel(file.name) if file.name.endswith('.xlsx') else pd.read_csv(file.name)
415
  if text_col not in df.columns:
416
+ return (f"**Column '{text_col}' was not found.**\n\n"
417
+ f"Available columns: **{', '.join(df.columns)}**", None, None)
418
+ results_list = []
419
  for _, row in df.iterrows():
420
+ result = model_manager.predict_by_key(str(row[text_col]), key)
421
+ entry = row.to_dict()
422
+ if 'error' not in result:
423
+ em = EMOTION_INFO.get(result['emotion'], {}).get('emoji', '')
424
+ entry['Predicted Emotion'] = f"{em} {result['emotion']}"
425
+ entry['Confidence'] = f"{result['confidence']:.0%}"
426
+ entry['Confidence Level'] = ('High' if result['confidence'] >= 0.75 else
427
+ 'Moderate' if result['confidence'] >= 0.50 else
428
+ 'Low — review manually')
429
+ else:
430
+ entry['Predicted Emotion'] = 'Error'
431
+ entry['Confidence'] = 'N/A'
432
+ entry['Confidence Level'] = 'Error'
433
+ results_list.append(entry)
434
+ results_df = pd.DataFrame(results_list)
435
+ path = save_to_xlsx(results_df, "STEMO_Batch_Results.xlsx")
436
+ top_emotion = results_df['Predicted Emotion'].value_counts().index[0]
437
+ status = (f"## Analysis Complete!\n\n"
438
+ f"| | |\n|---|---|\n"
439
+ f"| **Tweets analysed** | {len(results_df)} |\n"
440
+ f"| **Model used** | {model_display_name} |\n"
441
+ f"| **Most common emotion** | {top_emotion} |\n\n"
442
+ f"Click **Download Results** to save the full analysis.")
443
+ return status, results_df.head(10), path
444
  except Exception as e:
445
+ return f"**Error:** {str(e)}", None, None
446
+
447
+ def tab_evaluate(file, model_display_name, text_col, label_col):
448
+ if file is None:
449
+ return ("**Please upload a labelled test file.**\n\n"
450
+ "Your file needs a **text** column and a **label** column.\n\n"
451
+ "Valid labels: Happy, Anger, Sadness, Fear, Surprise, Disgust",
452
+ None, None, None)
453
+ key = MODEL_INFO[model_display_name]['key']
454
  try:
455
  df = pd.read_excel(file.name) if file.name.endswith('.xlsx') else pd.read_csv(file.name)
456
  if text_col not in df.columns or label_col not in df.columns:
457
+ return (f" **Column not found.** Available: {', '.join(df.columns)}",
458
+ None, None, None)
459
+ y_true, y_pred, confs = [], [], []
460
  for _, row in df.iterrows():
461
+ result = model_manager.predict_by_key(str(row[text_col]), key)
 
 
462
  if 'error' not in result:
463
+ y_true.append(row[label_col])
464
+ y_pred.append(result['emotion'])
465
+ confs.append(result['confidence'])
466
  acc = accuracy_score(y_true, y_pred)
467
+ prec, rec, f1, _ = precision_recall_fscore_support(
468
+ y_true, y_pred, average='macro', zero_division=0)
469
+ output = (f"## Evaluation Results — {model_display_name}\n\n"
470
+ f"| Metric | Score | What it means |\n|---|---|---|\n"
471
+ f"| **Accuracy** | {acc:.1%} | Out of every 100 tweets, the model got this many right |\n"
472
+ f"| **Precision** | {prec:.1%} | When the model predicts an emotion, how often it is correct |\n"
473
+ f"| **Recall** | {rec:.1%} | How well the model finds all tweets with each emotion |\n"
474
+ f"| **F1 Score** | {f1:.1%} | Overall balance between precision and recall |\n"
475
+ f"| **Avg Confidence** | {np.mean(confs):.1%} | Average certainty of predictions |\n\n"
476
+ f"---\n**Detailed breakdown by emotion:**\n"
477
  f"```\n{classification_report(y_true, y_pred, zero_division=0)}\n```")
478
  metrics_df = pd.DataFrame([
479
+ {'Metric': 'Accuracy', 'Score': f"{acc:.1%}"},
480
+ {'Metric': 'Precision', 'Score': f"{prec:.1%}"},
481
+ {'Metric': 'Recall', 'Score': f"{rec:.1%}"},
482
+ {'Metric': 'F1 Score', 'Score': f"{f1:.1%}"},
483
+ {'Metric': 'Avg Confidence', 'Score': f"{np.mean(confs):.1%}"},
484
  ])
485
+ cm = confusion_matrix(y_true, y_pred, labels=model_manager.label_names)
486
+ fig, ax = plt.subplots(figsize=(10, 8))
487
+ fig.patch.set_facecolor('#FAFAFA')
488
  sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',
489
+ xticklabels=[f"{EMOTION_INFO[l]['emoji']} {l}" for l in model_manager.label_names],
490
+ yticklabels=[f"{EMOTION_INFO[l]['emoji']} {l}" for l in model_manager.label_names],
491
+ cbar_kws={'label': 'Number of tweets'}, linewidths=0.5)
492
+ ax.set_title(f'{model_display_name} — Confusion Matrix\n'
493
+ 'Diagonal = correct predictions | Off-diagonal = mistakes',
494
+ fontsize=13, fontweight='bold', pad=15)
495
+ ax.set_ylabel('Actual Emotion', fontsize=11)
496
+ ax.set_xlabel('Predicted Emotion', fontsize=11)
497
+ plt.xticks(rotation=30, ha='right'); plt.yticks(rotation=0)
498
  plt.tight_layout()
499
+ buf = io.BytesIO()
500
+ plt.savefig(buf, format='png', dpi=120, bbox_inches='tight')
501
  buf.seek(0); img = Image.open(buf); plt.close()
502
+ results_df = df[[text_col, label_col]].copy()
503
+ results_df['Predicted'] = y_pred
504
+ results_df['Correct?'] = results_df[label_col] == results_df['Predicted']
505
+ results_df['Confidence'] = [f"{c:.0%}" for c in confs]
506
+ per_class = classification_report(y_true, y_pred, output_dict=True, zero_division=0)
507
+ per_class_df = pd.DataFrame(per_class).T.reset_index().rename(columns={'index': 'Class'})
508
+ path = os.path.join(tempfile.gettempdir(), "STEMO_Evaluation_Results.xlsx")
509
  with pd.ExcelWriter(path, engine='openpyxl') as writer:
510
+ results_df.to_excel(writer, sheet_name='Predictions', index=False)
511
+ metrics_df.to_excel(writer, sheet_name='Overall Metrics', index=False)
512
+ per_class_df.to_excel(writer, sheet_name='Per Emotion F1', index=False)
513
+ return output, metrics_df, img, path
514
  except Exception as e:
515
+ return f"**Error:** {str(e)}", None, None, None
516
+
517
+ #GRADIO UI
518
+ MODEL_CHOICES = list(MODEL_INFO.keys())
519
+
520
+ with gr.Blocks(theme=gr.themes.Soft(), title="STEMO — Emotion Classifier") as demo:
521
+
522
+ gr.HTML("""
523
+ <div style="text-align:center; background:linear-gradient(135deg,#4f46e5,#7c3aed);
524
+ padding:36px 20px; border-radius:16px; margin-bottom:24px;">
525
+ <h1 style="color:white; margin:0; font-size:2.4em; font-weight:700; letter-spacing:-0.5px;">
526
+ STEMO
527
+ </h1>
528
+ <p style="color:rgba(255,255,255,0.95); margin:10px 0 4px; font-size:1.25em; font-weight:500;">
529
+ Sinhala-Tamil Emotion Classifier
530
+ </p>
531
+ <p style="color:rgba(255,255,255,0.75); margin:0; font-size:1em;">
532
+ Type any tweet in Sinhala, Tamil, English, or a mix and discover its emotion instantly.
533
+ </p>
534
+ </div>
535
+ """)
536
 
 
 
537
  gr.HTML("""
538
+ <div style="background:#f0fdf4; border:1px solid #bbf7d0; border-radius:12px;
539
+ padding:16px 20px; margin-bottom:20px;">
540
+ <p style="margin:0; font-size:0.97em; color:#166534;">
541
+ <strong>How STEMO works:</strong>
542
+ STEMO reads your tweet including Sinhala (සිංහල), Tamil (தமிழ்), emojis, and English
543
+ and classifies it into one of six emotions:
544
+ <strong>Happy &nbsp;|&nbsp; Anger &nbsp;|&nbsp; Sadness &nbsp;|&nbsp;
545
+ Fear &nbsp;|&nbsp; Surprise &nbsp;|&nbsp; Disgust</strong>.
546
+ </p>
547
+ </div>
548
+ """)
549
 
550
  with gr.Tabs():
551
+
552
+ # ── TAB 1 ─────────────────────────────────────────────
553
+ with gr.Tab("Analyse a Tweet"):
554
+ gr.Markdown("### Step 1 — Type or paste your tweet below\n"
555
+ "You can write in Sinhala, Tamil, English, or mix freely. Emojis help! 😊")
556
  with gr.Row():
557
+ with gr.Column(scale=3):
558
+ t1_text = gr.Textbox(label="Your tweet", lines=3,
559
+ placeholder="e.g. මං ගොඩක් සතුටුයි today! 🎉",
560
+ max_lines=6)
561
  with gr.Column(scale=2):
562
+ gr.HTML("""
563
+ <div style="background:#fefce8; border:1px solid #fde047;
564
+ border-radius:10px; padding:12px 14px;">
565
+ <p style="margin:0 0 8px; font-weight:600; font-size:0.95em; color:#713f12;">
566
+ Try one of these example tweets:
567
+ </p>
568
+ <p style="margin:0; font-size:0.88em; color:#92400e; line-height:1.8;">
569
+ <em>මං ගොඩක් සතුටුයි අද 😊</em><br>
570
+ <em>I'm really කනගාටුයි about this</em><br>
571
+ <em>மிகவும் கோபமா இருக்கு today!</em><br>
572
+ <em>OMG இது என்னன்னே தெரியல!! 😲</em>
573
+ </p>
574
+ </div>""")
575
+
576
+ gr.Markdown("### Step 2 — Choose a model\n"
577
+ "Not sure which to pick? **Use SetFit — it is the most accurate.**")
578
+ with gr.Row():
579
+ t1_model = gr.Radio(choices=MODEL_CHOICES, value=MODEL_CHOICES[0],
580
+ label="Which model should analyse your tweet?")
581
+
582
+ gr.HTML("""
583
+ <div style="display:flex; gap:12px; flex-wrap:wrap; margin-bottom:16px;">
584
+ <div style="flex:1; min-width:180px; background:#eff6ff; border:1px solid #bfdbfe;
585
+ border-radius:10px; padding:12px;">
586
+ <p style="margin:0; font-weight:700; color:#1e40af;">⭐ SetFit (Recommended)</p>
587
+ <p style="margin:4px 0 0; font-size:0.85em; color:#1e3a8a;">
588
+ Accuracy: <strong>80.65%</strong><br>Best for everyday use.
589
+ </p>
590
+ </div>
591
+ <div style="flex:1; min-width:180px; background:#f0fdf4; border:1px solid #bbf7d0;
592
+ border-radius:10px; padding:12px;">
593
+ <p style="margin:0; font-weight:700; color:#166534;">Prompt-Based</p>
594
+ <p style="margin:4px 0 0; font-size:0.85em; color:#14532d;">
595
+ Accuracy: <strong>58.71%</strong><br>No training needed. Handles noisy text well.
596
+ </p>
597
+ </div>
598
+ </div>""")
599
+
600
+ t1_btn = gr.Button("Analyse Emotion", variant="primary", size="lg")
601
+ gr.Markdown("### Results")
602
+ t1_result = gr.Markdown(value="_Your results will appear here after you click Analyse._")
603
  with gr.Row():
604
+ t1_table = gr.Dataframe(label="Full breakdown — all six emotions and their confidence scores", wrap=True)
605
+ t1_chart = gr.Image(label="Confidence chart — how sure is the model about each emotion?", height=320)
606
+ t1_btn.click(fn=tab_single, inputs=[t1_text, t1_model],
607
+ outputs=[t1_result, t1_table, t1_chart])
608
+
609
+ # ── TAB 2 ─────────────────────────────────────────────
610
+ with gr.Tab("Compare All Models"):
611
+ gr.Markdown("### See what each model thinks about the same tweet\n"
612
+ "Runs your tweet through both models at once for a side-by-side comparison.")
613
+ t2_text = gr.Textbox(label="Your tweet", lines=3,
614
+ placeholder="Type any Sinhala-Tamil tweet here...")
615
+ t2_btn = gr.Button("Compare All Models", variant="primary", size="lg")
616
+ t2_result = gr.Markdown(value="_Results will appear here after you click Compare._")
 
 
617
  with gr.Row():
618
+ t2_table = gr.Dataframe(label="Side-by-side comparison", wrap=True)
619
+ t2_chart = gr.Image(label="Visual comparison — colour shows the predicted emotion", height=320)
620
+ t2_btn.click(fn=tab_compare, inputs=[t2_text],
621
+ outputs=[t2_result, t2_table, t2_chart])
622
+
623
+ # TAB 3
624
+ with gr.Tab("Analyse Many Tweets"):
625
+ gr.Markdown("### Analyse a whole spreadsheet of tweets at once\n"
626
+ "Upload a file and STEMO will classify each tweet automatically.")
627
+ gr.HTML("""
628
+ <div style="background:#eff6ff; border:1px solid #bfdbfe; border-radius:10px;
629
+ padding:14px 16px; margin-bottom:16px;">
630
+ <p style="margin:0; font-size:0.9em; color:#1e40af;">
631
+ <strong>📋 How to prepare your file:</strong><br>
632
+ • <strong>.xlsx (Excel)</strong> or <strong>.csv</strong> format<br>
633
+ • Must have a column containing the tweets (default name: <strong>text</strong>)<br>
634
+ • Other columns are kept in the results
635
+ </p>
636
+ </div>""")
 
637
  with gr.Row():
638
+ with gr.Column():
639
+ t3_file = gr.File(label="Upload your file (.xlsx or .csv)",
640
+ file_types=['.xlsx', '.csv'])
641
+ t3_text_col = gr.Textbox(label="Tweet column name", value="text",
642
+ info="Column in your file that contains the tweets")
643
+ t3_model = gr.Dropdown(choices=MODEL_CHOICES, value=MODEL_CHOICES[0],
644
+ label="Which model to use?",
645
+ info="SetFit is recommended for best accuracy")
646
+ t3_btn = gr.Button("Start Analysis", variant="primary", size="lg")
647
+ t3_result = gr.Markdown(value="_Upload a file and click Start Analysis to begin._")
648
+ t3_table = gr.Dataframe(label="Preview — first 10 rows of results", wrap=True)
649
+ t3_download = gr.File(label="Download Full Results (.xlsx)", visible=False)
650
+
651
+ def run_batch(file, model_choice, text_col):
652
+ status, preview, path = tab_batch(file, model_choice, text_col)
653
+ return status, preview, gr.update(value=path, visible=path is not None)
654
+
655
+ t3_btn.click(fn=run_batch, inputs=[t3_file, t3_model, t3_text_col],
656
+ outputs=[t3_result, t3_table, t3_download])
657
+
658
+ # ── TAB 4 ─────────────────────────────────────────────
659
+ with gr.Tab("Evaluate Model Performance"):
660
+ gr.Markdown("### For researchers — test how well the model performs on your labelled data\n"
661
+ "Upload a file with tweets and correct emotion labels for a full performance report.")
662
+ gr.HTML("""
663
+ <div style="background:#fdf4ff; border:1px solid #e9d5ff; border-radius:10px;
664
+ padding:14px 16px; margin-bottom:16px;">
665
+ <p style="margin:0; font-size:0.9em; color:#6b21a8;">
666
+ <strong>Your file needs two columns:</strong><br>
667
+ • <strong>text</strong> — the tweet<br>
668
+ • <strong>label</strong> — the correct emotion
669
+ (Happy, Anger, Sadness, Fear, Surprise, Disgust)
670
+ </p>
671
+ </div>""")
672
  with gr.Row():
673
+ with gr.Column():
674
+ t4_file = gr.File(label="Upload labelled test file (.xlsx or .csv)",
675
+ file_types=['.xlsx', '.csv'])
676
+ with gr.Row():
677
+ t4_text_col = gr.Textbox(label="Tweet column name", value="text")
678
+ t4_label_col = gr.Textbox(label="Label column name", value="label")
679
+ t4_model = gr.Dropdown(choices=MODEL_CHOICES, value=MODEL_CHOICES[0],
680
+ label="Which model to evaluate?")
681
+ t4_btn = gr.Button("Run Evaluation", variant="primary", size="lg")
682
+ t4_result = gr.Markdown(value="_Upload a labelled file and click Run Evaluation._")
683
+ with gr.Row():
684
+ t4_table = gr.Dataframe(label="Performance metrics", wrap=True)
685
+ t4_chart = gr.Image(label="Confusion matrix", height=400)
686
+ t4_download = gr.File(
687
+ label="Download Full Report (.xlsx) — includes predictions and per-emotion F1",
688
+ visible=False)
689
+
690
+ def run_eval(file, model_choice, text_col, label_col):
691
+ report, metrics, img, path = tab_evaluate(file, model_choice, text_col, label_col)
692
+ return report, metrics, img, gr.update(value=path, visible=path is not None)
693
+
694
+ t4_btn.click(fn=run_eval,
695
+ inputs=[t4_file, t4_model, t4_text_col, t4_label_col],
696
+ outputs=[t4_result, t4_table, t4_chart, t4_download])
697
+
698
+ gr.HTML("""
699
+ <div style="text-align:center; margin-top:32px; padding:20px;
700
+ background:#f8fafc; border-radius:12px; border:1px solid #e2e8f0;">
701
+ <p style="margin:0; color:#475569; font-size:0.95em;">
702
+ <strong>STEMO</strong> — Sinhala-Tamil Emotion Model
703
+ </p>
704
+ <p style="margin:6px 0 0; color:#94a3b8; font-size:0.85em;">
705
+ SetFit (80.65%) &nbsp;|&nbsp; Prompt-Based XLM-RoBERTa (58.71%)<br>
706
+ Trained on 1,013 code-mixed Sinhala-Tamil tweets from the ACTSEA corpus.
707
+ </p>
708
+ </div>
709
+ """)
710
 
711
  demo.launch()