babelmachine / interfaces /illframes.py
poltextlab's picture
fix typo
40ba46f verified
raw
history blame
2.47 kB
import gradio as gr
import os
import torch
import numpy as np
import pandas as pd
from transformers import AutoModelForSequenceClassification
from transformers import AutoTokenizer
from huggingface_hub import HfApi
from label_dicts import ILLFRAMES_MIGRATION_LABEL_NAMES, ILLFRAMES_COVID_LABEL_NAMES
HF_TOKEN = os.environ["hf_read"]
languages = [
"English"
]
domains = {
"Covid": "covid",
"Migration": "migration"
}
def check_huggingface_path(checkpoint_path: str):
try:
hf_api = HfApi(token=HF_TOKEN)
hf_api.model_info(checkpoint_path, token=HF_TOKEN)
return True
except:
return False
def build_huggingface_path(domain: str):
return f"poltextlab/xlm-roberta-large-english-ILLFRAMES-{domain}"
def predict(text, model_id, tokenizer_id, label_names):
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)
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()
NUMS_DICT = {i: key for i, key in enumerate(sorted(label_names.keys()))}
output_pred = {f"[{NUMS_DICT[i]}] {label_names[NUMS_DICT[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_illframes(text, domain):
domain = domains[domain]
model_id = build_huggingface_path(domain)
tokenizer_id = "xlm-roberta-large"
if domain == "migration":
label_names = ILLFRAMES_MIGRATION_LABEL_NAMES
else:
label_names = ILLFRAMES_COVID_LABEL_NAMES
return predict(text, model_id, tokenizer_id, label_names)
demo = gr.Interface(
fn=predict_illframes,
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()])