vdmbrsv commited on
Commit
e766350
Β·
verified Β·
1 Parent(s): 1c5142c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -23
app.py CHANGED
@@ -1,16 +1,16 @@
1
  import gradio as gr
 
2
  import torch
3
  from transformers import AutoTokenizer, AutoModelForSequenceClassification
4
 
5
- # Initialize device - force CPU usage
6
- device = "cpu"
7
  print(f"Using device: {device}")
8
 
9
  # Load model and tokenizer
10
  model_name = "tabularisai/robust-sentiment-analysis"
11
  tokenizer = AutoTokenizer.from_pretrained(model_name)
12
- model = AutoModelForSequenceClassification.from_pretrained(model_name) # Remove .to(device)
13
- model.eval() # Set model to evaluation mode
14
 
15
  # Define sentiment mapping
16
  SENTIMENT_MAP = {
@@ -21,21 +21,22 @@ SENTIMENT_MAP = {
21
  4: "Very Positive"
22
  }
23
 
 
24
  def analyze_sentiment(text, show_probabilities=False):
25
  """
26
- Analyzes the sentiment of the input text with preprocessing.
27
  """
28
  try:
29
  # Preprocess text - convert to lowercase
30
  text = text.lower()
31
 
32
  # Tokenize and prepare input
33
- inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=512)
34
 
35
  with torch.no_grad():
36
  outputs = model(**inputs)
37
 
38
- probabilities = torch.nn.functional.softmax(outputs.logits, dim=-1).numpy()[0]
39
  predicted_class = probabilities.argmax()
40
  predicted_sentiment = SENTIMENT_MAP[predicted_class]
41
  confidence = probabilities[predicted_class]
@@ -49,8 +50,8 @@ def analyze_sentiment(text, show_probabilities=False):
49
  "Very Positive": "🀩"
50
  }
51
 
52
- result = f"## {sentiment_emojis[predicted_sentiment]} Overall Sentiment: {predicted_sentiment}\n"
53
- result += f"### Confidence: {confidence:.2%}\n\n"
54
 
55
  if show_probabilities:
56
  result += "### Detailed Analysis:\n"
@@ -62,15 +63,12 @@ def analyze_sentiment(text, show_probabilities=False):
62
  except Exception as e:
63
  return f"An error occurred during sentiment analysis: {str(e)}"
64
 
65
- # Create Gradio interface using Blocks
66
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
 
67
  gr.Markdown(
68
  """
69
- # 🎭 Sentiment Analysis Wizard
70
-
71
- <div style='text-align: center; padding: 1rem; background: rgba(255, 255, 255, 0.5); border-radius: 1rem; margin: 1rem 0;'>
72
- Discover the emotional tone behind any text with our advanced AI model! Let our wizard analyze your text and reveal its true sentiment.
73
- </div>
74
  """
75
  )
76
 
@@ -78,13 +76,12 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
78
  with gr.Column(scale=2):
79
  input_text = gr.Textbox(
80
  lines=10,
81
- placeholder="Enter your text here to uncover its emotional essence...",
82
- label="✍️ Input Text",
83
- show_label=True
84
  )
85
  with gr.Row():
86
  show_probs = gr.Checkbox(
87
- label="🎯 Show detailed probabilities",
88
  value=False
89
  )
90
  analyze_button = gr.Button("✨ Analyze Sentiment", variant="primary")
@@ -92,7 +89,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
92
  with gr.Column(scale=1):
93
  output = gr.Markdown(label="Result")
94
 
95
- with gr.Accordion("πŸ“š Example Texts", open=False):
96
  examples = [
97
  ["I absolutely loved this movie! The acting was superb and the plot was engaging.", True],
98
  ["The service at this restaurant was terrible. I'll never go back.", False],
@@ -114,9 +111,8 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
114
 
115
  gr.Markdown(
116
  """
117
- <div style='text-align: center; padding: 1rem; margin-top: 2rem; font-size: 0.9em; color: #666;'>
118
- Developed with ❀️ using Gradio and Transformers by Hugging Face
119
- </div>
120
  """
121
  )
122
 
 
1
  import gradio as gr
2
+ import spaces
3
  import torch
4
  from transformers import AutoTokenizer, AutoModelForSequenceClassification
5
 
6
+ # Initialize device
7
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
8
  print(f"Using device: {device}")
9
 
10
  # Load model and tokenizer
11
  model_name = "tabularisai/robust-sentiment-analysis"
12
  tokenizer = AutoTokenizer.from_pretrained(model_name)
13
+ model = AutoModelForSequenceClassification.from_pretrained(model_name).to(device)
 
14
 
15
  # Define sentiment mapping
16
  SENTIMENT_MAP = {
 
21
  4: "Very Positive"
22
  }
23
 
24
+ @spaces.GPU
25
  def analyze_sentiment(text, show_probabilities=False):
26
  """
27
+ Analyzes the sentiment of the input text.
28
  """
29
  try:
30
  # Preprocess text - convert to lowercase
31
  text = text.lower()
32
 
33
  # Tokenize and prepare input
34
+ inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=512).to(device)
35
 
36
  with torch.no_grad():
37
  outputs = model(**inputs)
38
 
39
+ probabilities = torch.nn.functional.softmax(outputs.logits, dim=-1).cpu().numpy()[0]
40
  predicted_class = probabilities.argmax()
41
  predicted_sentiment = SENTIMENT_MAP[predicted_class]
42
  confidence = probabilities[predicted_class]
 
50
  "Very Positive": "🀩"
51
  }
52
 
53
+ result = f"**{sentiment_emojis[predicted_sentiment]} Overall Sentiment: {predicted_sentiment}**\n"
54
+ result += f"Confidence: {confidence:.2%}\n\n"
55
 
56
  if show_probabilities:
57
  result += "### Detailed Analysis:\n"
 
63
  except Exception as e:
64
  return f"An error occurred during sentiment analysis: {str(e)}"
65
 
66
+ # Create Gradio interface using Blocks for better layout control
67
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
68
+ gr.Markdown("# 🎭 Sentiment Analysis Wizard")
69
  gr.Markdown(
70
  """
71
+ Discover the emotional tone behind any text with our advanced AI model! This app uses a state-of-the-art language model to analyze the sentiment of your text, classifying it into one of five categories: **Very Negative**, **Negative**, **Neutral**, **Positive**, or **Very Positive**.
 
 
 
 
72
  """
73
  )
74
 
 
76
  with gr.Column(scale=2):
77
  input_text = gr.Textbox(
78
  lines=10,
79
+ placeholder="Enter text for sentiment analysis...",
80
+ label="✍️ Input Text"
 
81
  )
82
  with gr.Row():
83
  show_probs = gr.Checkbox(
84
+ label="🎯 Show probabilities for each class",
85
  value=False
86
  )
87
  analyze_button = gr.Button("✨ Analyze Sentiment", variant="primary")
 
89
  with gr.Column(scale=1):
90
  output = gr.Markdown(label="Result")
91
 
92
+ with gr.Accordion("πŸ“š Examples", open=False):
93
  examples = [
94
  ["I absolutely loved this movie! The acting was superb and the plot was engaging.", True],
95
  ["The service at this restaurant was terrible. I'll never go back.", False],
 
111
 
112
  gr.Markdown(
113
  """
114
+ ---
115
+ **Developed with ❀️ using Gradio and Transformers by Hugging Face**
 
116
  """
117
  )
118