ShAnSantosh
commited on
Commit
•
35e86b1
1
Parent(s):
ba439ed
Update app.py
Browse files
app.py
CHANGED
@@ -1,7 +1,31 @@
|
|
1 |
import gradio as gr
|
|
|
|
|
|
|
2 |
|
3 |
-
|
4 |
-
return "Hello " + name + "!"
|
5 |
|
6 |
-
|
7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
+
import torch
|
3 |
+
import transformers
|
4 |
+
from transformers import BertTokenizer, BertForMaskedLM
|
5 |
|
6 |
+
device = torch.device('cpu')
|
|
|
7 |
|
8 |
+
NUM_CLASSES=5
|
9 |
+
|
10 |
+
model=BertForMaskedLM.from_pretrained("./")
|
11 |
+
tokenizer=BertTokenizer.from_pretrained("./")
|
12 |
+
|
13 |
+
|
14 |
+
def predict(text=None) -> dict:
|
15 |
+
model.eval()
|
16 |
+
inputs = tokenizer(text, return_tensors="pt")
|
17 |
+
input_ids = inputs["input_ids"].to(device)
|
18 |
+
attention_mask = inputs["attention_mask"].to(device)
|
19 |
+
model.to(device)
|
20 |
+
token_logits = model(input_ids, attention_mask=attention_mask).logits
|
21 |
+
mask_token_index = torch.where(inputs_ex["input_ids"] == tokenizer.mask_token_id)[1]
|
22 |
+
mask_token_logits = token_logits[0, mask_token_index, :]
|
23 |
+
top_5_tokens = torch.topk(mask_token_logits, NUM_CLASSES, dim=1).indices[0].tolist()
|
24 |
+
score = torch.nn.functional.softmax(mask_token_logits)[0]
|
25 |
+
top_5_score = torch.topk(score, NUM_CLASSES).values.tolist()
|
26 |
+
return {tokenizer.decode([tok]): float(score) for tok, score in zip(top_5_tokens, top_5_score)}
|
27 |
+
|
28 |
+
gr.Interface(fn=predict,
|
29 |
+
inputs=gr.inputs.Textbox(lines=2, placeholder="Your Text… "),
|
30 |
+
title="Mask Language Modeling - Demo",
|
31 |
+
outputs=gr.outputs.Label(num_top_classes=NUM_CLASSES)).launch()
|