katsuchi commited on
Commit
7d08fa9
·
verified ·
1 Parent(s): 33a5d30

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +47 -0
  2. requirements.txt +5 -0
app.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from peft import PeftModel
4
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
5
+ import numpy as np
6
+
7
+ base_model = AutoModelForSequenceClassification.from_pretrained("bert-base-uncased")
8
+ model = PeftModel.from_pretrained(base_model, "katsuchi/bert-base-uncased-twitter-sentiment-analysis")
9
+
10
+ tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
11
+
12
+ def get_sentiment(input_sentence):
13
+ inputs = tokenizer(input_sentence, return_tensors="pt", padding=True, truncation=True, max_length=512)
14
+
15
+ inputs = {k: v.to(model.device) for k, v in inputs.items()}
16
+
17
+ with torch.no_grad():
18
+ outputs = model(**inputs)
19
+ logits = outputs.logits
20
+
21
+ probabilities = torch.nn.functional.softmax(logits, dim=-1).squeeze().cpu().numpy()
22
+
23
+ labels = ["Negative", "Positive"]
24
+
25
+ result = {labels[i]: round(prob, 3) for i, prob in enumerate(probabilities)}
26
+
27
+ return result
28
+
29
+ # Example sentences
30
+ examples = [
31
+ ["I love this product!"],
32
+ ["This is the worst experience ever."],
33
+ ["The movie was okay, not great but not bad."],
34
+ ["Absolutely terrible, do not buy!"],
35
+ ["I feel amazing today!"]
36
+ ]
37
+
38
+ iface = gr.Interface(
39
+ fn=get_sentiment,
40
+ inputs=gr.Textbox(label="Enter a sentence for sentiment analysis"),
41
+ outputs=gr.JSON(label="Sentiment Probabilities"),
42
+ title="Sentiment Analysis with Bert",
43
+ description="Enter a sentence, and this model will predict the sentiment (positive/negative) along with the probabilities.",
44
+ examples=examples
45
+ )
46
+
47
+ iface.launch()
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gradio
2
+ torch
3
+ transformers
4
+ peft
5
+ numpy