explorewithai commited on
Commit
1b442a6
·
verified ·
1 Parent(s): 794dee8

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -0
app.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
3
+ import torch # Import torch
4
+
5
+ # Load the model and tokenizer (same as your original code)
6
+ model_name = "frameai/PersianSentiment"
7
+ loaded_tokenizer = AutoTokenizer.from_pretrained(model_name)
8
+ loaded_model = AutoModelForSequenceClassification.from_pretrained(model_name)
9
+
10
+
11
+ def predict_sentiment(text):
12
+ """Predicts the sentiment of a given text."""
13
+ inputs = loaded_tokenizer(text, return_tensors="pt", padding=True, truncation=True) # Add padding and truncation
14
+ outputs = loaded_model(**inputs)
15
+ # Use softmax to get probabilities and argmax to get the predicted class
16
+ probabilities = torch.nn.functional.softmax(outputs.logits, dim=-1)
17
+ predictions = torch.argmax(probabilities, dim=-1).item()
18
+
19
+ if predictions == 0:
20
+ sentiment = "Negative"
21
+ elif predictions == 1:
22
+ sentiment = "Positive"
23
+ else:
24
+ sentiment = "Neutral"
25
+
26
+ # Return probabilities as well for a more informative output
27
+ return {
28
+ "Negative": float(probabilities[0][0]),
29
+ "Positive": float(probabilities[0][1]),
30
+ "Neutral": float(probabilities[0][2]),
31
+ }, sentiment
32
+
33
+ # Create example sentences
34
+ examples = [
35
+ ["این فیلم عالی بود!"], # Positive example
36
+ ["من این غذا را دوست نداشتم."], # Negative example
37
+ ["هوا خوب است."], # Neutral (could be slightly positive, depends on context)
38
+ ["کتاب جالبی بود اما کمی خسته کننده هم بود."] , # Mixed/Neutral
39
+ ["اصلا راضی نبودم."] #negative
40
+ ]
41
+
42
+
43
+ # Create the Gradio interface
44
+ iface = gr.Interface(
45
+ fn=predict_sentiment,
46
+ inputs=gr.Textbox(label="Enter Persian Text", lines=5, placeholder="Type your text here..."),
47
+ outputs=[
48
+ gr.Label(label="Sentiment Probabilities"),
49
+ gr.Textbox(label="Predicted Sentiment") # Add output component for the sentiment string
50
+
51
+ ],
52
+ title="Persian Sentiment Analysis",
53
+ description="Enter a Persian sentence and get its sentiment (Positive, Negative, or Neutral).",
54
+ examples=examples,
55
+ live=False # set to True for automatic updates as you type
56
+ )
57
+
58
+
59
+ if __name__ == "__main__":
60
+ iface.launch()