Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from huggingface_hub import hf_hub_download
|
3 |
+
import torch
|
4 |
+
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
|
5 |
+
|
6 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
7 |
+
tokenizer = AutoTokenizer.from_pretrained("VietAI/vit5-base")
|
8 |
+
model = AutoModelForSeq2SeqLM.from_pretrained("VietAI/vit5-base")
|
9 |
+
model_file = hf_hub_download(repo_id="tuongvxx1/medBot", filename="medicalBot_ver4.pth")
|
10 |
+
model.load_state_dict(torch.load(model_file, map_location=torch.device('cpu')))
|
11 |
+
model.to(device)
|
12 |
+
|
13 |
+
def generate_answer(question, model, tokenizer, device):
|
14 |
+
model.eval()
|
15 |
+
input_text = "hỏi: " + question
|
16 |
+
inputs = tokenizer(input_text, return_tensors="pt", max_length=512, truncation=True, padding="max_length")
|
17 |
+
input_ids = inputs.input_ids.to(device)
|
18 |
+
attention_mask = inputs.attention_mask.to(device)
|
19 |
+
|
20 |
+
with torch.no_grad():
|
21 |
+
outputs = model.generate(input_ids=input_ids, attention_mask=attention_mask, max_length=128, num_beams=4, early_stopping=True)
|
22 |
+
answer = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
23 |
+
return answer
|
24 |
+
|
25 |
+
def run(ques):
|
26 |
+
return generate_answer(ques, model, tokenizer, device)
|
27 |
+
|
28 |
+
demo = gr.Interface(fn=run, inputs=gr.Textbox(label="Nhập câu hỏi"), outputs=gr.Textbox(label="Câu trả lời"))
|
29 |
+
demo.launch()
|