sitayeb commited on
Commit
e665ead
·
verified ·
1 Parent(s): 92f0f1d

Create Add file → Create new file

Browse files
Files changed (1) hide show
  1. Add file → Create new file +55 -0
Add file → Create new file ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import plotly.express as px
4
+ import torch
5
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
6
+
7
+ MODEL_NAME = "cardiffnlp/twitter-xlm-roberta-base-sentiment"
8
+
9
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
10
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
11
+ model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME).to(device)
12
+ model.eval()
13
+
14
+ def predict_sentiment(text):
15
+ inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=128)
16
+ inputs = {k: v.to(device) for k, v in inputs.items()}
17
+
18
+ with torch.no_grad():
19
+ outputs = model(**inputs)
20
+ probs = torch.softmax(outputs.logits, dim=-1)[0].cpu().numpy()
21
+
22
+ pred = np.argmax(probs)
23
+ label = "✅ Positive" if pred == 1 else "❌ Negative"
24
+ confidence = f"{probs[pred]:.1%}"
25
+
26
+ fig = px.bar(x=["Negative", "Positive"], y=probs, title=f"Sentiment: {label}")
27
+ fig.update_yaxes(range=[0, 1])
28
+
29
+ return label, confidence, fig
30
+
31
+ def chat_response(message, history):
32
+ if not message.strip():
33
+ return "", history
34
+
35
+ label, conf, plot = predict_sentiment(message)
36
+ bot_message = f"**Sentiment:** {label}\n**Confidence:** {conf}"
37
+
38
+ history.append({"role": "user", "content": message})
39
+ history.append({"role": "assistant", "content": bot_message})
40
+
41
+ return "", history, plot
42
+
43
+ with gr.Blocks(title="Sentiment Chatbot") as demo:
44
+ gr.Markdown("# 🗣️ Sentiment Chatbot (EN/AR)")
45
+
46
+ with gr.Row():
47
+ with gr.Column(scale=3):
48
+ chatbot = gr.Chatbot(type="messages", height=500)
49
+ msg_input = gr.Textbox(placeholder="اكتب بالعربية أو الإنجليزية...")
50
+ with gr.Column(scale=1):
51
+ sentiment_plot = gr.Plot(label="📊 Confidence")
52
+
53
+ msg_input.submit(chat_response, [msg_input, chatbot], [msg_input, chatbot, sentiment_plot])
54
+
55
+ demo.launch()