Spaces:
Build error
Build error
| import gradio as gr | |
| from huggingface_hub import hf_hub_download | |
| import torch | |
| from transformers import AutoTokenizer, AutoModelForSeq2SeqLM | |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| tokenizer = AutoTokenizer.from_pretrained("vinai/bartpho-syllable") | |
| model = AutoModelForSeq2SeqLM.from_pretrained("vinai/bartpho-syllable") | |
| model_file = hf_hub_download(repo_id="acediaaa/VietTour_0", filename="viettour_model_bartpho.pth") | |
| state_dict = torch.load(model_file, map_location=torch.device('cpu')) | |
| model.load_state_dict(state_dict) | |
| model.to(device) | |
| def generate_answer(question, model, tokenizer, device): | |
| model.eval() | |
| input_text = "hỏi: " + question | |
| # Tokenize câu hỏi | |
| inputs = tokenizer(input_text, return_tensors="pt", max_length=512, truncation=True, padding="max_length") | |
| input_ids = inputs.input_ids.to(device) | |
| attention_mask = inputs.attention_mask.to(device) | |
| with torch.no_grad(): | |
| # Sinh câu trả lời từ mô hình | |
| outputs = model.generate( | |
| input_ids=input_ids, | |
| attention_mask=attention_mask, | |
| max_length=512, # Độ dài tối đa của câu trả lời | |
| num_beams=5, # Beam search với 5 beam | |
| repetition_penalty=1.2, # Phạt lặp từ (giá trị > 1.0 để tránh lặp lại) | |
| no_repeat_ngram_size=3, # Tránh lặp lại các cụm từ dài 3 từ | |
| early_stopping=True # Dừng sớm nếu sinh văn bản đủ tốt | |
| ) | |
| # Giải mã câu trả lời từ token thành chuỗi văn bản | |
| answer = tokenizer.decode(outputs[0], skip_special_tokens=True) | |
| return answer | |
| def run(ques): | |
| return generate_answer(ques, model, tokenizer, device) | |
| demo = gr.Interface(fn=run, inputs=gr.Textbox(label="Nhập câu hỏi"), outputs=gr.Textbox(label="Câu trả lời")) | |
| demo.launch() |