Vadim Borisov commited on
Commit
a5c3607
·
verified ·
1 Parent(s): aaf5c73

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -49
app.py CHANGED
@@ -1,16 +1,21 @@
1
  import gradio as gr
2
  from transformers import AutoTokenizer, AutoModelForSequenceClassification
3
  import torch
4
- import random
5
 
6
  # Load model and tokenizer
7
  model_name = "tabularisai/robust-sentiment-analysis"
8
  tokenizer = AutoTokenizer.from_pretrained(model_name)
9
  model = AutoModelForSequenceClassification.from_pretrained(model_name)
10
 
 
 
 
 
11
  # Function to predict sentiment
12
  def predict_sentiment(text):
13
  inputs = tokenizer(text.lower(), return_tensors="pt", truncation=True, padding=True, max_length=512)
 
 
14
  with torch.no_grad():
15
  outputs = model(**inputs)
16
 
@@ -18,54 +23,31 @@ def predict_sentiment(text):
18
  predicted_class = torch.argmax(probabilities, dim=-1).item()
19
 
20
  sentiment_map = {0: "Very Negative", 1: "Negative", 2: "Neutral", 3: "Positive", 4: "Very Positive"}
21
- return sentiment_map[predicted_class], {k: float(v) for k, v in zip(sentiment_map.values(), probabilities[0])}
22
-
23
- # Function to generate random example
24
- def random_example():
25
- examples = [
26
- "I absolutely loved this movie! The acting was superb and the plot was engaging.",
27
- "The service at this restaurant was terrible. I'll never go back.",
28
- "The product works as expected. Nothing special, but it gets the job done.",
29
- "I'm somewhat disappointed with my purchase. It's not as good as I hoped.",
30
- "This book changed my life! I couldn't put it down and learned so much."
31
- ]
32
- return random.choice(examples)
33
 
34
  # Gradio interface
35
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
36
- gr.Markdown(
37
- """
38
- # 🎭 Sentiment Analysis Wizard
39
- Discover the emotional tone behind any text with our advanced AI model!
40
- """
41
- )
42
-
43
- with gr.Row():
44
- with gr.Column(scale=2):
45
- text_input = gr.Textbox(label="Enter your text here", placeholder="Type or paste your text...")
46
- random_btn = gr.Button("Get Random Example")
47
-
48
- with gr.Column(scale=1):
49
- sentiment_output = gr.Textbox(label="Overall Sentiment")
50
- confidence_output = gr.Label(label="Confidence Scores")
51
-
52
- analyze_btn = gr.Button("Analyze Sentiment", variant="primary")
53
-
54
- gr.Markdown(
55
- """
56
- ### How it works
57
- This app uses a state-of-the-art language model to analyze the sentiment of your text.
58
- It classifies the input into one of five categories: Very Negative, Negative, Neutral, Positive, or Very Positive.
59
-
60
- Try it out with your own text or click "Get Random Example" for inspiration!
61
- """
62
- )
63
-
64
- def analyze(text):
65
- sentiment, confidences = predict_sentiment(text)
66
- return sentiment, confidences
67
-
68
- analyze_btn.click(analyze, inputs=text_input, outputs=[sentiment_output, confidence_output])
69
- random_btn.click(random_example, outputs=text_input)
70
 
71
- demo.launch()
 
 
1
  import gradio as gr
2
  from transformers import AutoTokenizer, AutoModelForSequenceClassification
3
  import torch
 
4
 
5
  # Load model and tokenizer
6
  model_name = "tabularisai/robust-sentiment-analysis"
7
  tokenizer = AutoTokenizer.from_pretrained(model_name)
8
  model = AutoModelForSequenceClassification.from_pretrained(model_name)
9
 
10
+ # Move model to GPU if available
11
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
12
+ model = model.to(device)
13
+
14
  # Function to predict sentiment
15
  def predict_sentiment(text):
16
  inputs = tokenizer(text.lower(), return_tensors="pt", truncation=True, padding=True, max_length=512)
17
+ inputs = {k: v.to(device) for k, v in inputs.items()}
18
+
19
  with torch.no_grad():
20
  outputs = model(**inputs)
21
 
 
23
  predicted_class = torch.argmax(probabilities, dim=-1).item()
24
 
25
  sentiment_map = {0: "Very Negative", 1: "Negative", 2: "Neutral", 3: "Positive", 4: "Very Positive"}
26
+ confidence = probabilities[0][predicted_class].item()
27
+
28
+ return sentiment_map[predicted_class], f"{confidence:.2%}"
 
 
 
 
 
 
 
 
 
29
 
30
  # Gradio interface
31
+ def gradio_sentiment_analysis(text):
32
+ sentiment, confidence = predict_sentiment(text)
33
+ return f"Sentiment: {sentiment}\nConfidence: {confidence}"
34
+
35
+ # Create Gradio interface
36
+ iface = gr.Interface(
37
+ fn=gradio_sentiment_analysis,
38
+ inputs=gr.Textbox(lines=5, label="Enter text for sentiment analysis"),
39
+ outputs=gr.Textbox(label="Result"),
40
+ title="Sentiment Analysis",
41
+ description="Analyze the sentiment of your text using a 5-class sentiment model.",
42
+ theme="huggingface",
43
+ examples=[
44
+ ["I absolutely loved this movie! The acting was superb and the plot was engaging."],
45
+ ["The service at this restaurant was terrible. I'll never go back."],
46
+ ["The product works as expected. Nothing special, but it gets the job done."],
47
+ ["I'm somewhat disappointed with my purchase. It's not as good as I hoped."],
48
+ ["This book changed my life! I couldn't put it down and learned so much."]
49
+ ]
50
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
+ # Launch the app
53
+ iface.launch()