Spaces:
Running
Running
File size: 2,754 Bytes
3afc718 da5015b 3afc718 da5015b 3afc718 da5015b 3afc718 da5015b 3afc718 da5015b 3afc718 da5015b 3afc718 da5015b 3afc718 da5015b 3afc718 da5015b 3afc718 28668a9 3afc718 28668a9 3afc718 |
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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
# # 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()
|