Spaces:
Running
Running
created app
Browse files
app.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 6 |
+
|
| 7 |
+
tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
|
| 8 |
+
model = AutoModelForSequenceClassification.from_pretrained("Rahmat82/DistilBERT-finetuned-on-emotion")
|
| 9 |
+
model.to(device)
|
| 10 |
+
|
| 11 |
+
def predict(query: str) -> dict:
|
| 12 |
+
inputs = tokenizer(query, return_tensors='pt')
|
| 13 |
+
inputs.to(device)
|
| 14 |
+
outputs = model(**inputs)
|
| 15 |
+
outputs = torch.sigmoid(outputs.logits)
|
| 16 |
+
outputs = outputs.detach().cpu().numpy()
|
| 17 |
+
label2ids = {
|
| 18 |
+
"sadness": 0,
|
| 19 |
+
"love": 2,
|
| 20 |
+
"anger": 3,
|
| 21 |
+
"fear": 4,
|
| 22 |
+
"surprise": 5,
|
| 23 |
+
"joy": 6
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
for i, k in enumerate(label2ids.keys()):
|
| 27 |
+
label2ids[k] = outputs[0][i]
|
| 28 |
+
label2ids = {k: float(v) for k, v in sorted(label2ids.items(), key=lambda item: item[1], reverse=True)}
|
| 29 |
+
return label2ids
|
| 30 |
+
|
| 31 |
+
demo = gr.Interface(
|
| 32 |
+
fn=predict,
|
| 33 |
+
inputs=gr.components.Textbox(label='Input query'),
|
| 34 |
+
outputs=gr.components.Label(label='Predictions', num_top_classes=6),
|
| 35 |
+
allow_flagging='never'
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
demo.launch(share=True)
|