File size: 1,918 Bytes
cb33df2
7679301
42e5097
7679301
de85801
 
a6074ba
 
7679301
 
 
de85801
 
7679301
de85801
 
7679301
 
de85801
7679301
 
de85801
 
7679301
de85801
7679301
 
de85801
7679301
 
 
 
de85801
 
7679301
de85801
 
 
7679301
 
de85801
7679301
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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()