Spaces:
Sleeping
Sleeping
| # # app.py | |
| # import gradio as gr # type: ignore | |
| # import torch # type: ignore | |
| # from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer | |
| # # 1️⃣ Cấu hình và load model + tokenizer | |
| # model_path = "vinai/PhoGPT-4B-Chat" | |
| # config = AutoConfig.from_pretrained(model_path, trust_remote_code=True) | |
| # config.init_device = "cpu" | |
| # model = AutoModelForCausalLM.from_pretrained("vinai/PhoGPT-4B-Chat", trust_remote_code=True) | |
| # model.eval() | |
| # tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True) | |
| # def respond(message, history: list[tuple[str, str]], system_message, max_tokens, temperature, top_p): | |
| # # 2.1 — Gom system message và history vào messages list | |
| # messages = [{"role": "system", "content": system_message}] | |
| # for u, b in history: | |
| # if u: | |
| # messages.append({"role": "user", "content": u}) | |
| # if b: | |
| # messages.append({"role": "assistant", "content": b}) | |
| # messages.append({"role": "user", "content": message}) | |
| # # 2.2 — Tạo prompt chuẩn | |
| # input_prompt = tokenizer.apply_chat_template( | |
| # messages, | |
| # tokenize=False, | |
| # add_generation_prompt=True | |
| # ) | |
| # # 2.3 — Tokenize và đưa lên device | |
| # # inputs = tokenizer(input_prompt, return_tensors="pt") | |
| # input_ids = tokenizer(input_prompt, return_tensors="pt") | |
| # # inputs = {k: v.to(model.device) for k, v in inputs.items()} | |
| # # 2.4 — Sinh text | |
| # outputs = model.generate( | |
| # inputs=input_ids["input_ids"], | |
| # max_new_tokens=max_tokens, | |
| # temperature=temperature, | |
| # top_p=top_p, | |
| # do_sample=True, | |
| # eos_token_id=tokenizer.eos_token_id, | |
| # pad_token_id=tokenizer.pad_token_id, | |
| # ) | |
| # # print('!!!! OUTPUTS 1: ',outputs) | |
| # # 2.5 — Decode và tách phần assistant trả lời | |
| # response = tokenizer.batch_decode(outputs, skip_special_tokens=True)[0] | |
| # print('!! OUTPUTS 2: ',response) | |
| # response = response.split("### Trả lời:")[1] | |
| # print('!!!! OUTPUTS 3: ',response) | |
| # return response | |
| # # 2.6 — Cập nhật history và trả về | |
| # # history.append((message, response)) | |
| # # return history | |
| # # 3️⃣ Giao diện Gradio | |
| # demo = gr.ChatInterface( | |
| # respond, #câu phản hồi | |
| # additional_inputs=[ | |
| # gr.Textbox("Bạn là một chatbot tiếng Việt thân thiện.", label="System message"), | |
| # gr.Slider(1, 2048, value=512, step=1, label="Max new tokens"), | |
| # gr.Slider(0.1, 4.0, value=0.7, step=0.1, label="Temperature"), | |
| # gr.Slider(0.1, 1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"), | |
| # ], | |
| # ) | |
| # if __name__ == "__main__": | |
| # demo.launch() | |