Winnie-Kay commited on
Commit
7861bfe
·
1 Parent(s): 988aaf8

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -0
app.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoModelForSequenceClassification
2
+ from transformers import TFAutoModelForSequenceClassification
3
+ from transformers import AutoTokenizer, AutoConfig
4
+ from scipy.special import softmax
5
+ import gradio as gr
6
+
7
+ # Requirements
8
+ model_path = f"Winnie-Kay/Finetuned_BertModel_SentimentAnalysis"
9
+ tokenizer = AutoTokenizer.from_pretrained('bert-base-cased')
10
+ config = AutoConfig.from_pretrained(model_path)
11
+ model = AutoModelForSequenceClassification.from_pretrained(model_path)
12
+
13
+ # Preprocess text (username and link placeholders)
14
+ def preprocess(text):
15
+ new_text = []
16
+ for t in text.split(" "):
17
+ t = '@user' if t.startswith('@') and len(t) > 1 else t
18
+ t = 'http' if t.startswith('http') else t
19
+ new_text.append(t)
20
+ return " ".join(new_text)
21
+
22
+
23
+ def sentiment_analysis(text):
24
+ text = preprocess(text)
25
+
26
+ # PyTorch-based models
27
+ encoded_input = tokenizer(text, return_tensors='pt')
28
+ output = model(**encoded_input)
29
+ scores_ = output[0][0].detach().numpy()
30
+ scores_ = softmax(scores_)
31
+
32
+ # Format output dict of scores
33
+ labels = ['Negative', 'Neutral', 'Positive']
34
+ scores = {l:float(s) for (l,s) in zip(labels, scores_) }
35
+
36
+ return scores
37
+
38
+ demo = gr.Interface(
39
+ fn=sentiment_analysis,
40
+ inputs=gr.Textbox(placeholder="Write your tweet here..."),
41
+ outputs="label",
42
+ interpretation="default",
43
+ examples=[["This is wonderful!"]])
44
+
45
+ demo.launch()