Spaces:
Runtime error
Runtime error
PenguinMan
commited on
Commit
·
0725a09
1
Parent(s):
fdd1d01
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import transformers
|
3 |
+
import torch
|
4 |
+
from transformers import BertModel, BertTokenizer, AdamW, get_linear_schedule_with_warmup
|
5 |
+
|
6 |
+
class_names = ['left', 'neutral', 'right']
|
7 |
+
PRE_TRAINED_MODEL_NAME = 'bert-base-uncased'
|
8 |
+
tokenizer = BertTokenizer.from_pretrained(PRE_TRAINED_MODEL_NAME)
|
9 |
+
MAX_LEN = 256
|
10 |
+
bert_model = BertModel.from_pretrained(PRE_TRAINED_MODEL_NAME)
|
11 |
+
|
12 |
+
class SentimentClassifier(nn.Module):
|
13 |
+
def __init__(self, n_classes):
|
14 |
+
super(SentimentClassifier, self).__init__()
|
15 |
+
self.bert = BertModel.from_pretrained(PRE_TRAINED_MODEL_NAME)
|
16 |
+
self.drop = nn.Dropout(p=0.4)
|
17 |
+
self.out = nn.Linear(self.bert.config.hidden_size, n_classes)
|
18 |
+
def forward(self, input_ids, attention_mask):
|
19 |
+
_, pooled_output = self.bert(
|
20 |
+
input_ids=input_ids,
|
21 |
+
attention_mask=attention_mask,
|
22 |
+
return_dict=False
|
23 |
+
|
24 |
+
)
|
25 |
+
output = self.drop(pooled_output)
|
26 |
+
return self.out(output)
|
27 |
+
|
28 |
+
model = SentimentClassifier(len(class_names))
|
29 |
+
|
30 |
+
def result_final(new_article):
|
31 |
+
|
32 |
+
encoded_review = tokenizer.encode_plus(
|
33 |
+
review_text,
|
34 |
+
max_length=MAX_LEN,
|
35 |
+
add_special_tokens=True,
|
36 |
+
return_token_type_ids=False,
|
37 |
+
padding="max_length",
|
38 |
+
truncation=True,
|
39 |
+
return_attention_mask=True,
|
40 |
+
return_tensors='pt',
|
41 |
+
)
|
42 |
+
|
43 |
+
input_ids = encoded_review['input_ids'].to(device)
|
44 |
+
attention_mask = encoded_review['attention_mask'].to(device)
|
45 |
+
output = model2(input_ids, attention_mask)
|
46 |
+
_, prediction = torch.max(output, dim=1)
|
47 |
+
|
48 |
+
return class_names[prediction]
|
49 |
+
|
50 |
+
|
51 |
+
iface = gr.Interface(fn = result_final, inputs = "text", outputs = ["text"], title = "News Bias Classifer")
|
52 |
+
iface.launch()
|
53 |
+
|