File size: 1,942 Bytes
b1c2932
 
 
 
 
 
 
 
 
 
 
 
 
 
d0aeec8
b1c2932
624dc37
 
 
b1c2932
 
 
 
 
 
eaa511e
b1c2932
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
624dc37
b1c2932
 
 
 
 
 
 
624dc37
 
b1c2932
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
44
45
46
47
48
49
50
51
52
53
54
55
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 = [
    "English", "French", "German", "Hungarian", "Polish"
]
domains = {
    "parliamentary speech": "parlspeech",
}

def build_huggingface_path(language: str):
    return "poltextlab/xlm-roberta-large-pooled-emotions"

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=512,
                       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()
    output_pred = {model.config.id2label[i]: probs[i] for i in np.argsort(probs)[::-1]}
    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=5, label="Output"), gr.Markdown()])