Spaces:
Running
Running
Update interfaces/ontolisst.py
Browse files- interfaces/ontolisst.py +62 -0
interfaces/ontolisst.py
CHANGED
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
|
3 |
+
import os
|
4 |
+
import torch
|
5 |
+
import numpy as np
|
6 |
+
from transformers import AutoModelForSequenceClassification
|
7 |
+
from transformers import AutoTokenizer
|
8 |
+
from huggingface_hub import HfApi
|
9 |
+
|
10 |
+
HF_TOKEN = os.environ["hf_read"]
|
11 |
+
|
12 |
+
languages = [
|
13 |
+
"English"
|
14 |
+
]
|
15 |
+
domains = {
|
16 |
+
"parliamentary speech": "parlspeech",
|
17 |
+
}
|
18 |
+
|
19 |
+
from label_dicts import ONTOLISST_LABEL_NAMES
|
20 |
+
|
21 |
+
|
22 |
+
def build_huggingface_path(language: str):
|
23 |
+
return "poltextlab/xlm-roberta-large_ontolisst_v1"
|
24 |
+
|
25 |
+
def predict(text, model_id, tokenizer_id):
|
26 |
+
device = torch.device("cpu")
|
27 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_id, low_cpu_mem_usage=True, device_map="auto", offload_folder="offload", token=HF_TOKEN)
|
28 |
+
tokenizer = AutoTokenizer.from_pretrained(tokenizer_id)
|
29 |
+
model.to(device)
|
30 |
+
|
31 |
+
inputs = tokenizer(text,
|
32 |
+
max_length=256,
|
33 |
+
truncation=True,
|
34 |
+
padding="do_not_pad",
|
35 |
+
return_tensors="pt").to(device)
|
36 |
+
model.eval()
|
37 |
+
|
38 |
+
with torch.no_grad():
|
39 |
+
logits = model(**inputs).logits
|
40 |
+
|
41 |
+
probs = torch.nn.functional.softmax(logits, dim=1).cpu().numpy().flatten()
|
42 |
+
predicted_class_id = probs.argmax()
|
43 |
+
predicted_class_id = {4: 2, 5: 1}.get(predicted_class_id, 0)
|
44 |
+
|
45 |
+
|
46 |
+
output_pred = ONTOLISST_LABEL_NAMES.get(predicted_class_id, predicted_class_id)
|
47 |
+
|
48 |
+
|
49 |
+
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>'
|
50 |
+
return output_pred, output_info
|
51 |
+
|
52 |
+
def predict_cap(text, language, domain):
|
53 |
+
model_id = build_huggingface_path(language)
|
54 |
+
tokenizer_id = "xlm-roberta-large"
|
55 |
+
return predict(text, model_id, tokenizer_id)
|
56 |
+
|
57 |
+
demo = gr.Interface(
|
58 |
+
fn=predict_cap,
|
59 |
+
inputs=[gr.Textbox(lines=6, label="Input"),
|
60 |
+
gr.Dropdown(languages, label="Language"),
|
61 |
+
gr.Dropdown(domains.keys(), label="Domain")],
|
62 |
+
outputs=[gr.Label(num_top_classes=3, label="Output"), gr.Markdown()])
|