Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import torch
|
3 |
+
import transformers
|
4 |
+
|
5 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
6 |
+
|
7 |
+
|
8 |
+
|
9 |
+
class Model(torch.nn.Module):
|
10 |
+
def __init__(self):
|
11 |
+
super().__init__()
|
12 |
+
self.MODEL_NAME = "distilbert-base-uncased-finetuned-sst-2-english"
|
13 |
+
self.bert = transformers.AutoModelForSequenceClassification.from_pretrained(self.MODEL_NAME)
|
14 |
+
self.tokenizer = transformers.AutoTokenizer.from_pretrained(self.MODEL_NAME)
|
15 |
+
|
16 |
+
def forward(self, input_text):
|
17 |
+
encoding = self.tokenizer.encode_plus(
|
18 |
+
input_text,
|
19 |
+
add_special_tokens = True,
|
20 |
+
pad_to_max_length = True,
|
21 |
+
return_token_type_ids = False,
|
22 |
+
return_attention_mask = True,
|
23 |
+
return_tensors = 'pt'
|
24 |
+
)
|
25 |
+
|
26 |
+
input_ids = encoding['input_ids'].to(device)
|
27 |
+
attention_mask = encoding['attention_mask'].to(device)
|
28 |
+
|
29 |
+
output = self.bert(
|
30 |
+
input_ids = input_ids,
|
31 |
+
attention_mask = attention_mask)
|
32 |
+
|
33 |
+
return output
|
34 |
+
|
35 |
+
|
36 |
+
def predict(input_text):
|
37 |
+
model = Model()
|
38 |
+
model.load_state_dict(torch.load("ayse/distilbert-english-finetuned", map_location=device), strict=False)
|
39 |
+
model.eval()
|
40 |
+
outputs = model(input_text)
|
41 |
+
logits = outputs.logits
|
42 |
+
prediction = torch.argmax(logits, dim=-1)
|
43 |
+
if prediction.item() == 0:
|
44 |
+
return "NEGATIVE"
|
45 |
+
if prediction.item() == 1:
|
46 |
+
return "POSITIVE"
|
47 |
+
|
48 |
+
|
49 |
+
iface = gr.Interface(predict,
|
50 |
+
inputs="text",
|
51 |
+
outputs="text",
|
52 |
+
title="Bert Base Sentiment Analysis",
|
53 |
+
description="This is a bert based sentiment classifier that is trained with tinder application reviews (EN).",
|
54 |
+
allow_flagging="never")
|
55 |
+
iface.launch(inbrowser=True)
|