File size: 1,256 Bytes
ba4df19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f523ea6
 
ba4df19
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# AUTOGENERATED! DO NOT EDIT! File to edit: ../app.ipynb.

# %% auto 0
__all__ = ['tokenizer', 'device', 'model', 'CLASS_LABELS', 'sentence', 'label', 'examples', 'intf', 'classify_sentiment']

# %% ../app.ipynb 2
import gradio as gr 
import torch
from layer import Model

# %% ../app.ipynb 3
from transformers import BertTokenizerFast

tokenizer = BertTokenizerFast.from_pretrained('bert-base-cased')

# %% ../app.ipynb 4
device = "cuda" if torch.cuda.is_available() else "cpu"

model = torch.load('./model.pt', map_location=torch.device('cpu')).to(device)
model.eval()

# %% ../app.ipynb 5
CLASS_LABELS  = ['Negative', 'Positive']

# %% ../app.ipynb 6
def classify_sentiment(sentence):
    tokens = tokenizer(sentence)
    pred = model(torch.tensor([tokens['input_ids']]).to(device), [len(tokens)]).item()
    return dict(zip(CLASS_LABELS, [1 - pred, pred]))
    

# %% ../app.ipynb 7
sentence = gr.inputs.Textbox()
label = gr.outputs.Label(label='sentiment')
examples = ["best movie I've ever seen", 'Worst movie ever.']

intf = gr.Interface(fn=classify_sentiment, 
                    inputs=sentence, 
                    outputs=label, 
                    title='Sentiment analysis',
                    examples=examples)
intf.launch(inline=False)