Dhruv-DG commited on
Commit
4741a5e
·
verified ·
1 Parent(s): 2f958f3

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -0
app.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
3
+ import torch
4
+ import numpy as np
5
+
6
+ # ✅ Paths to your hosted models on Hugging Face Hub
7
+ MODEL_PATHS = [
8
+ "Basavians/youtube-comment-sentiment-1",
9
+ "Basavians/youtube-comment-sentiment-2",
10
+ "Basavians/youtube-comment-sentiment-3"
11
+ ]
12
+
13
+ # Load models and tokenizers (once at startup)
14
+ models = []
15
+ tokenizers = []
16
+ for path in MODEL_PATHS:
17
+ tokenizer = AutoTokenizer.from_pretrained(path)
18
+ model = AutoModelForSequenceClassification.from_pretrained(path)
19
+ model.eval()
20
+ tokenizers.append(tokenizer)
21
+ models.append(model)
22
+
23
+ # Class labels (update if different)
24
+ LABELS = ["negative", "neutral", "positive"]
25
+
26
+ def predict_sentiment(text):
27
+ if not text.strip():
28
+ return "Please enter some text", None
29
+
30
+ probs = []
31
+ for model, tokenizer in zip(models, tokenizers):
32
+ inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True)
33
+ with torch.no_grad():
34
+ outputs = model(**inputs)
35
+ logits = outputs.logits
36
+ prob = torch.nn.functional.softmax(logits, dim=-1)
37
+ probs.append(prob.numpy())
38
+
39
+ # 🎯 Ensemble by averaging probabilities
40
+ avg_prob = np.mean(probs, axis=0)
41
+ pred_class = int(np.argmax(avg_prob, axis=1)[0])
42
+ pred_label = LABELS[pred_class]
43
+ confidence = float(avg_prob[0][pred_class])
44
+
45
+ return pred_label, {label: float(avg_prob[0][i]) for i, label in enumerate(LABELS)}
46
+
47
+ # Gradio UI
48
+ demo = gr.Interface(
49
+ fn=predict_sentiment,
50
+ inputs=gr.Textbox(lines=4, placeholder="Paste a YouTube comment here..."),
51
+ outputs=[
52
+ gr.Label(num_top_classes=1, label="Predicted Sentiment"),
53
+ gr.Label(label="Confidence Scores"),
54
+ ],
55
+ title="YouTube Comment Sentiment Classifier (Ensemble)",
56
+ description="Enter a comment to see sentiment prediction based on an ensemble of 3 models."
57
+ )
58
+
59
+ demo.launch()