AbstractQbit commited on
Commit
41d22ed
·
1 Parent(s): 666c725
Files changed (1) hide show
  1. app.py +50 -0
app.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
2
+ import torch
3
+ import gradio as gr
4
+ import pickle
5
+
6
+ torch.autograd.set_grad_enabled(False)
7
+
8
+ sklearn_model = pickle.load(open('classic_pipeline.pickle', 'rb'))
9
+
10
+ model_name = "AbstractQbit/electra_large_imdb_htsplice"
11
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
12
+ model = AutoModelForSequenceClassification.from_pretrained(model_name)
13
+
14
+
15
+ def tokenize_with_splicing(text):
16
+ tokens = tokenizer(text, truncation=False)
17
+ if len(tokens['input_ids']) > 512:
18
+ tokens['input_ids'] = tokens['input_ids'][:129] + \
19
+ [102] + tokens['input_ids'][-382:]
20
+ tokens['token_type_ids'] = [0]*512
21
+ tokens['attention_mask'] = [1]*512
22
+ return tokens
23
+
24
+ def make_stars(prob):
25
+ stars = round(1 + prob*9)
26
+ return '★'*stars + '☆'*(10-stars)
27
+
28
+ def run_models(review):
29
+ prob_sklearn = float(sklearn_model.predict_proba([review])[0][1])
30
+ label_sklearn = 'positive' if prob_sklearn > 0.5 else 'negative'
31
+ res = f"TF-IDF SVC thinks the review is {label_sklearn} ({100*prob_sklearn:.2f}% positive).\n{make_stars(prob_sklearn):s}\n\n"
32
+
33
+ input = tokenize_with_splicing(review).convert_to_tensors('pt', True)
34
+ output = torch.nn.functional.softmax(model(**input).logits, dim=1)
35
+ prob_electra = float(output[0][1])
36
+ label_electra = 'positive' if prob_electra > 0.5 else 'negative'
37
+ res += f"ELECTRA thinks the review is {label_electra} ({100*prob_electra:.2f}% positive).\n{make_stars(prob_electra):s}"
38
+
39
+ return res
40
+
41
+
42
+ demo = gr.Interface(
43
+ fn=run_models,
44
+ inputs="text",
45
+ outputs="text",
46
+ title="Movie review classification",
47
+ allow_flagging='never'
48
+ )
49
+
50
+ demo.launch()