ArrcttacsrjksX commited on
Commit
7f24197
·
verified ·
1 Parent(s): 6c34591

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -0
app.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModelForCausalLM, TextStreamer
3
+ import torch
4
+
5
+ # Load model và tokenizer (chọn model mày muốn ở đây)
6
+ model_id = "Qwen/Qwen3-0.6B-Chat"
7
+
8
+ tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
9
+ model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", torch_dtype=torch.bfloat16, trust_remote_code=True)
10
+ streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
11
+
12
+ # Hàm xử lý chat
13
+ def chat_with_model(history, user_input):
14
+ # Lịch sử chat dưới dạng [(user, bot), ...]
15
+ messages = []
16
+ for user_msg, bot_msg in history:
17
+ messages.append({"role": "user", "content": user_msg})
18
+ messages.append({"role": "assistant", "content": bot_msg})
19
+ messages.append({"role": "user", "content": user_input})
20
+
21
+ # Tokenize và sinh
22
+ input_ids = tokenizer.apply_chat_template(messages, return_tensors="pt").to(model.device)
23
+ output = model.generate(input_ids, max_new_tokens=1024, streamer=streamer, do_sample=True, temperature=0.7)
24
+ decoded_output = tokenizer.decode(output[0][input_ids.shape[1]:], skip_special_tokens=True)
25
+
26
+ # Trả về output và update history
27
+ return decoded_output, history + [(user_input, decoded_output)]
28
+
29
+ # Gradio UI
30
+ with gr.Blocks(title="Chat với Qwen3") as demo:
31
+ gr.Markdown("# Chat với AI - Qwen3 Model")
32
+
33
+ chatbot = gr.Chatbot(height=400)
34
+ user_input = gr.Textbox(placeholder="Nhập tin nhắn...", label="Mày nói gì?")
35
+ clear = gr.Button("Xoá sạch")
36
+
37
+ state = gr.State([])
38
+
39
+ def respond(message, history):
40
+ response, updated_history = chat_with_model(history, message)
41
+ return updated_history, updated_history
42
+
43
+ user_input.submit(respond, [user_input, state], [chatbot, state])
44
+ clear.click(lambda: ([], []), None, [chatbot, state])
45
+
46
+ # Chạy app
47
+ demo.launch()