Spaces:
Running
Running
import gradio as gr | |
import os | |
import torch | |
import numpy as np | |
from transformers import AutoModelForSequenceClassification | |
from transformers import AutoTokenizer | |
from huggingface_hub import HfApi | |
from label_dicts import MANIFESTO_LABEL_NAMES | |
HF_TOKEN = os.environ["hf_read"] | |
languages = [ | |
"Czech", "English", "French", "German", "Hungarian", "Polish", "Slovakian" | |
] | |
domains = { | |
"parliamentary speech": "parlspeech", | |
} | |
SENTIMENT_LABEL_NAMES = {0: "Negative", 1: "No sentiment or Neutral sentiment", 2: "Positive"} | |
def build_huggingface_path(language: str): | |
if language == "Czech" or language == "Slovakian": | |
return "visegradmedia-emotion/Emotion_RoBERTa_pooled_V4" | |
return "poltextlab/xlm-roberta-large-pooled-MORES" | |
def predict(text, model_id, tokenizer_id): | |
device = torch.device("cpu") | |
model = AutoModelForSequenceClassification.from_pretrained(model_id, low_cpu_mem_usage=True, device_map="auto", offload_folder="offload", token=HF_TOKEN) | |
tokenizer = AutoTokenizer.from_pretrained(tokenizer_id) | |
model.to(device) | |
inputs = tokenizer(text, | |
max_length=256, | |
truncation=True, | |
padding="do_not_pad", | |
return_tensors="pt").to(device) | |
model.eval() | |
with torch.no_grad(): | |
logits = model(**inputs).logits | |
probs = torch.nn.functional.softmax(logits, dim=1).cpu().numpy().flatten() | |
predicted_class_id = probs.argmax() | |
predicted_class_id = {4: 2, 5: 1}.get(predicted_class_id, 0) | |
output_pred = SENTIMENT_LABEL_NAMES.get(predicted_class_id, predicted_class_id) | |
output_info = f'<p style="text-align: center; display: block">Prediction was made using the <a href="https://huggingface.co/{model_id}">{model_id}</a> model.</p>' | |
return output_pred, output_info | |
def predict_cap(text, language, domain): | |
model_id = build_huggingface_path(language) | |
tokenizer_id = "xlm-roberta-large" | |
return predict(text, model_id, tokenizer_id) | |
demo = gr.Interface( | |
fn=predict_cap, | |
inputs=[gr.Textbox(lines=6, label="Input"), | |
gr.Dropdown(languages, label="Language"), | |
gr.Dropdown(domains.keys(), label="Domain")], | |
outputs=[gr.Label(num_top_classes=3, label="Output"), gr.Markdown()]) |