| import os |
|
|
| import gradio as gr |
| import torch |
| from transformers import AutoTokenizer |
|
|
| from modeling_bert import BertForSequenceClassification |
|
|
|
|
| |
| BASE_DIR = os.path.dirname(os.path.abspath(__file__)) |
|
|
| |
| MODEL_DIR = os.path.join(BASE_DIR, "experiments") |
|
|
| |
| DEVICE = "cuda" if torch.cuda.is_available() else "cpu" |
|
|
| |
| ID2LABEL = { |
| 0: "not_disaster", |
| 1: "disaster", |
| } |
|
|
| |
| tokenizer = AutoTokenizer.from_pretrained(MODEL_DIR) |
|
|
| |
| model = BertForSequenceClassification.from_pretrained(MODEL_DIR) |
| model.to(DEVICE) |
| model.eval() |
|
|
|
|
| def inference(input_text): |
| |
| input_text = (input_text or "").strip() |
| if not input_text: |
| return "Please input a sentence." |
|
|
| |
| |
| inputs = tokenizer( |
| input_text, |
| max_length=128, |
| truncation=True, |
| padding="max_length", |
| return_tensors="pt", |
| ) |
|
|
| |
| inputs = {k: v.to(DEVICE) for k, v in inputs.items()} |
|
|
| |
| with torch.no_grad(): |
| logits = model(**inputs).logits |
|
|
| |
| predicted_class_id = logits.argmax(dim=-1).item() |
| output = ID2LABEL[predicted_class_id] |
| return output |
|
|
|
|
| |
| with gr.Blocks(css=""" |
| .message.svelte-w6rprc.svelte-w6rprc.svelte-w6rprc {font-size: 20px; margin-top: 20px} |
| #component-2 > div.wrap.svelte-w6rprc {height: 600px;} |
| """) as demo: |
| gr.Markdown("# Disaster Tweet Classifier") |
| gr.Markdown("Input a sentence or tweet, and the model will predict whether it describes a real disaster.") |
|
|
| |
| with gr.Row(): |
| with gr.Column(): |
| |
| input_text = gr.Textbox( |
| placeholder="Insert your text here...", |
| label="Input Text", |
| lines=4, |
| ) |
|
|
| |
| answer = gr.Textbox(label="Prediction") |
|
|
| |
| generate_bt = gr.Button("Generate") |
|
|
| |
| generate_bt.click( |
| fn=inference, |
| inputs=[input_text], |
| outputs=[answer], |
| show_progress=True, |
| ) |
|
|
| |
| gr.Examples( |
| examples=[ |
| ["Forest fire near La Ronge Sask. Canada"], |
| ["I love fruits and summer weather."], |
| ["There is an emergency evacuation happening now in the building across the street."], |
| ], |
| inputs=input_text, |
| outputs=answer, |
| fn=inference, |
| cache_examples=False, |
| ) |
|
|
| |
| demo.launch() |
|
|