Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch
|
| 4 |
+
from huggingface_hub import hf_hub_download
|
| 5 |
+
from safetensors.torch import load_file as load_safetensors
|
| 6 |
+
from transformers import AutoTokenizer
|
| 7 |
+
from openvino.runtime import Core
|
| 8 |
+
import gradio as gr
|
| 9 |
+
|
| 10 |
+
# 1) Model repo on HF Hub
|
| 11 |
+
HF_MODEL = "Kaiyeee/goemotions-multilabel"
|
| 12 |
+
|
| 13 |
+
# 2) Load tokenizer once
|
| 14 |
+
tokenizer = AutoTokenizer.from_pretrained("roberta-base")
|
| 15 |
+
|
| 16 |
+
# 3) Load and compile ONNX with OpenVINO on first request
|
| 17 |
+
core = Core()
|
| 18 |
+
# download and cache the .onnx from the model repo
|
| 19 |
+
onnx_path = hf_hub_download(repo_id=HF_MODEL, filename="goemotions_multilabel.onnx")
|
| 20 |
+
ov_model = core.read_model(model=onnx_path)
|
| 21 |
+
compiled = core.compile_model(model=ov_model, device_name="CPU")
|
| 22 |
+
|
| 23 |
+
# 4) Emotion labels
|
| 24 |
+
emotion_labels = [
|
| 25 |
+
"admiration","amusement","anger","annoyance","approval","caring","confusion",
|
| 26 |
+
"curiosity","desire","disappointment","disapproval","disgust","embarrassment",
|
| 27 |
+
"excitement","fear","gratitude","grief","joy","love","nervousness","optimism",
|
| 28 |
+
"pride","realization","relief","remorse","sadness","surprise","neutral"
|
| 29 |
+
]
|
| 30 |
+
|
| 31 |
+
def predict(texts, threshold=0.3):
|
| 32 |
+
# tokenize to numpy
|
| 33 |
+
toks = tokenizer(texts, padding="max_length", truncation=True, max_length=128, return_tensors="np")
|
| 34 |
+
outs = compiled([toks["input_ids"], toks["attention_mask"]])
|
| 35 |
+
logits = outs[compiled.output(0)]
|
| 36 |
+
probs = 1 / (1 + np.exp(-logits))
|
| 37 |
+
preds = (probs > threshold).astype(int)
|
| 38 |
+
|
| 39 |
+
# map back
|
| 40 |
+
results = []
|
| 41 |
+
for i, ps in enumerate(preds):
|
| 42 |
+
fired = [emotion_labels[j] for j, flag in enumerate(ps) if flag]
|
| 43 |
+
results.append(", ".join(fired) or "none")
|
| 44 |
+
return results
|
| 45 |
+
|
| 46 |
+
# 5) Gradio UI
|
| 47 |
+
with gr.Blocks() as demo:
|
| 48 |
+
gr.Markdown("# 👀 GoEmotions Multi-Label Demo")
|
| 49 |
+
inp = gr.Textbox(label="Enter text", lines=3, placeholder="How are you feeling today?")
|
| 50 |
+
thr = gr.Slider(0.1, 0.9, 0.3, label="Threshold")
|
| 51 |
+
out = gr.Textbox(label="Predicted emotions")
|
| 52 |
+
btn = gr.Button("Analyze")
|
| 53 |
+
btn.click(fn=predict, inputs=[inp, thr], outputs=out)
|
| 54 |
+
|
| 55 |
+
demo.launch()
|