explorewithai commited on
Commit
0307fac
·
verified ·
1 Parent(s): e70d663

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -33
app.py CHANGED
@@ -1,42 +1,58 @@
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
 
@@ -46,15 +62,13 @@ iface = gr.Interface(
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()
 
1
  import gradio as gr
2
  from transformers import AutoTokenizer, AutoModelForSequenceClassification
3
+ import torch
4
+ import numpy as np # Import numpy
5
 
6
+
7
+ # Check for GPU availability and set device
8
+ device = "cuda" if torch.cuda.is_available() else "cpu"
9
+ print(f"Using device: {device}")
10
+
11
+ # Load the model and tokenizer
12
+ model_name = "explorewithai/PersianSwear-Detector" # Corrected model name
13
+ loaded_model = AutoModelForSequenceClassification.from_pretrained(model_name).to(device) # Move model to device
14
  loaded_tokenizer = AutoTokenizer.from_pretrained(model_name)
15
+
16
 
17
 
18
  def predict_sentiment(text):
19
+ """Predicts the sentiment (Bad Word, Good Word, Neutral Word) of a given text."""
20
+ inputs = loaded_tokenizer(text, return_tensors="pt", padding=True, truncation=True).to(device) # Move inputs to GPU
21
+ with torch.no_grad(): # Ensure no gradients are calculated
22
+ outputs = loaded_model(**inputs)
23
+ logits = outputs.logits
24
+ probabilities = torch.nn.functional.softmax(logits, dim=-1) # Get probabilities
25
+ prediction = torch.argmax(logits, dim=-1).item()
26
+
27
+ # Map numeric labels to meaningful strings and get probabilities
28
+ if prediction == 4:
29
+ sentiment = "Bad Word"
30
+ elif prediction == 0:
31
+ sentiment = "Good Word"
32
+ elif prediction == 3:
33
+ sentiment = "Neutral Word"
34
  else:
35
+ sentiment = "Unknown" # Should not happen, but good practice
36
+
37
+ # Create a dictionary for the probabilities
38
+ prob_dict = {}
39
+ if "Bad Word" in ["Bad Word", "Good Word", "Neutral Word"]:
40
+ prob_dict["Bad Word"] = float(probabilities[0][4]) if 4 < probabilities.shape[1] else 0.0
41
+ if "Good Word" in ["Bad Word", "Good Word", "Neutral Word"]:
42
+ prob_dict["Good Word"] = float(probabilities[0][0]) if 0 < probabilities.shape[1] else 0.0
43
+ if "Neutral Word" in ["Bad Word", "Good Word", "Neutral Word"]:
44
+ prob_dict["Neutral Word"] = float(probabilities[0][3]) if 3 < probabilities.shape[1] else 0.0
45
+
46
+ return prob_dict, sentiment
47
 
 
 
 
 
 
 
48
 
49
  # Create example sentences
50
  examples = [
51
+ ["چه کت و شلوار زیبایی"], # Good word example
52
+ ["این فیلم خیلی زیبا بود"], # Good word example
53
+ ["میز"], # Neutral word example
54
+ ["کثافت"], # Bad word example
55
+ ["هوا خوب است."] #neutral
56
  ]
57
 
58
 
 
62
  inputs=gr.Textbox(label="Enter Persian Text", lines=5, placeholder="Type your text here..."),
63
  outputs=[
64
  gr.Label(label="Sentiment Probabilities"),
65
+ gr.Textbox(label="Predicted Sentiment") # Output component for the sentiment string
 
66
  ],
67
+ title="Persian Swear Word Detection",
68
+ description="Enter a Persian sentence and get its sentiment (Good Word, Bad Word, or Neutral Word).",
69
  examples=examples,
70
+ live=False # Set to True for automatic updates as you type
71
  )
72
 
 
73
  if __name__ == "__main__":
74
  iface.launch()