entropy25 commited on
Commit
f9ab3c4
·
verified ·
1 Parent(s): 1defa7e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -17
app.py CHANGED
@@ -9,22 +9,19 @@ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
9
  print(f"Using device: {device}")
10
 
11
  # Load model and tokenizer from Hugging Face Model Hub
12
- tokenizer = BertTokenizer.from_pretrained("entropy25/sentimentanalysis") # Replace with your model path
13
- model = BertForSequenceClassification.from_pretrained("entropy25/sentimentanalysis") # Replace with your model path
14
  model.to(device)
15
 
16
  # Define sentiment analysis function
17
  def analyze_sentiment(text):
18
  inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=512).to(device)
19
-
20
  with torch.no_grad():
21
  outputs = model(**inputs)
22
  logits = outputs.logits
23
  prediction = torch.argmax(logits, dim=-1).item()
24
- confidence = torch.nn.functional.softmax(logits, dim=-1).max().item() # Get maximum confidence score
25
-
26
- sentiment = "Positive" if prediction == 1 else "Negative"
27
-
28
  # Return sentiment and confidence score
29
  return f"Sentiment: {sentiment} (Confidence: {confidence:.2f})"
30
 
@@ -33,16 +30,18 @@ def plot_sentiment_distribution():
33
  sentiments = ["Positive", "Negative"]
34
  # Randomly generate some distribution data for demonstration
35
  scores = np.random.rand(2)
 
36
  plt.bar(sentiments, scores, color=['green', 'red'])
37
  plt.title("Sentiment Distribution")
38
  plt.ylabel("Confidence")
39
- plt.show()
 
40
 
41
  # Gradio interface setup
42
  with gr.Blocks() as demo:
43
  gr.Markdown("# 🎬 AI Movie Sentiment Analyzer")
44
  gr.Markdown("This tool uses a BERT model to analyze movie reviews. Enter a review to analyze its sentiment!")
45
-
46
  with gr.Row():
47
  with gr.Column(scale=3):
48
  input_text = gr.Textbox(
@@ -51,14 +50,16 @@ with gr.Blocks() as demo:
51
  lines=4
52
  )
53
  submit_button = gr.Button("Analyze Sentiment")
 
54
  with gr.Column(scale=2):
55
  sentiment_output = gr.Textbox(label="Prediction")
56
- sentiment_plot = gr.Button("Visualize Sentiment Distribution")
57
-
 
58
  # Trigger sentiment analysis when button is clicked
59
  submit_button.click(fn=analyze_sentiment, inputs=input_text, outputs=sentiment_output)
60
- sentiment_plot.click(fn=plot_sentiment_distribution)
61
-
62
  # Add some more complex example inputs for user convenience
63
  examples = [
64
  ["The cinematography was absolutely stunning, but the pacing felt slow at times."],
@@ -72,10 +73,18 @@ with gr.Blocks() as demo:
72
  ["A great film for fans of the genre, but it may not appeal to everyone. It's definitely a niche film."],
73
  ["The ending left me speechless, and the entire movie had a fantastic build-up."]
74
  ]
75
-
76
- # Launch the interface with examples passed as argument here
77
- demo.launch(share=True, examples=examples)
78
-
 
 
 
 
 
 
 
 
79
 
80
 
81
 
 
9
  print(f"Using device: {device}")
10
 
11
  # Load model and tokenizer from Hugging Face Model Hub
12
+ tokenizer = BertTokenizer.from_pretrained("entropy25/sentimentanalysis") # Replace with your model path
13
+ model = BertForSequenceClassification.from_pretrained("entropy25/sentimentanalysis") # Replace with your model path
14
  model.to(device)
15
 
16
  # Define sentiment analysis function
17
  def analyze_sentiment(text):
18
  inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=512).to(device)
 
19
  with torch.no_grad():
20
  outputs = model(**inputs)
21
  logits = outputs.logits
22
  prediction = torch.argmax(logits, dim=-1).item()
23
+ confidence = torch.nn.functional.softmax(logits, dim=-1).max().item() # Get maximum confidence score
24
+ sentiment = "Positive" if prediction == 1 else "Negative"
 
 
25
  # Return sentiment and confidence score
26
  return f"Sentiment: {sentiment} (Confidence: {confidence:.2f})"
27
 
 
30
  sentiments = ["Positive", "Negative"]
31
  # Randomly generate some distribution data for demonstration
32
  scores = np.random.rand(2)
33
+ plt.figure(figsize=(8, 6))
34
  plt.bar(sentiments, scores, color=['green', 'red'])
35
  plt.title("Sentiment Distribution")
36
  plt.ylabel("Confidence")
37
+ plt.tight_layout()
38
+ return plt
39
 
40
  # Gradio interface setup
41
  with gr.Blocks() as demo:
42
  gr.Markdown("# 🎬 AI Movie Sentiment Analyzer")
43
  gr.Markdown("This tool uses a BERT model to analyze movie reviews. Enter a review to analyze its sentiment!")
44
+
45
  with gr.Row():
46
  with gr.Column(scale=3):
47
  input_text = gr.Textbox(
 
50
  lines=4
51
  )
52
  submit_button = gr.Button("Analyze Sentiment")
53
+
54
  with gr.Column(scale=2):
55
  sentiment_output = gr.Textbox(label="Prediction")
56
+ sentiment_plot_btn = gr.Button("Visualize Sentiment Distribution")
57
+ plot_output = gr.Plot()
58
+
59
  # Trigger sentiment analysis when button is clicked
60
  submit_button.click(fn=analyze_sentiment, inputs=input_text, outputs=sentiment_output)
61
+ sentiment_plot_btn.click(fn=plot_sentiment_distribution, outputs=plot_output)
62
+
63
  # Add some more complex example inputs for user convenience
64
  examples = [
65
  ["The cinematography was absolutely stunning, but the pacing felt slow at times."],
 
73
  ["A great film for fans of the genre, but it may not appeal to everyone. It's definitely a niche film."],
74
  ["The ending left me speechless, and the entire movie had a fantastic build-up."]
75
  ]
76
+
77
+ # 正确的方式:使用 gr.Examples 组件
78
+ gr.Examples(
79
+ examples=examples,
80
+ inputs=input_text,
81
+ outputs=sentiment_output,
82
+ fn=analyze_sentiment,
83
+ cache_examples=True
84
+ )
85
+
86
+ # Launch the interface - 移除 examples 参数
87
+ demo.launch(share=True)
88
 
89
 
90