wy-wu commited on
Commit
a03ce67
·
verified ·
1 Parent(s): 516130a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +13 -68
app.py CHANGED
@@ -1,76 +1,21 @@
1
- import os
2
  import gradio as gr
3
- import torch
4
- from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
5
 
6
- # 🔹 CPU 省時小技巧:限制多執行緒
7
- os.environ["OMP_NUM_THREADS"] = "1"
8
- os.environ["MKL_NUM_THREADS"] = "1"
9
 
10
- # 🔹 使用 TinyLlama 模型(更快)
11
- MODEL_ID = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
12
-
13
- def load_pipe(model_id=MODEL_ID):
14
- tokenizer = AutoTokenizer.from_pretrained(model_id, use_fast=True)
15
- model = AutoModelForCausalLM.from_pretrained(
16
- model_id,
17
- torch_dtype=torch.float32, # CPU 環境建議 float32
18
- low_cpu_mem_usage=True
19
- )
20
- return pipeline(
21
- "text-generation",
22
- model=model,
23
- tokenizer=tokenizer,
24
- device=-1 # -1 = CPU
25
- )
26
-
27
- pipe = load_pipe()
28
-
29
- SYSTEM_PROMPT = "You are a helpful assistant. Please answer concisely in Traditional Chinese."
30
- MAX_TURNS = 3 # 最多保留最近 3 回合,避免輸入過長拖慢
31
-
32
- def chat(history, user_msg):
33
- # 🔹 縮短歷史,避免輸入過大拖慢
34
- history = history[-2*MAX_TURNS:]
35
-
36
- prompt = ""
37
- for role, text in history:
38
- prompt += f"{role}: {text}\n"
39
- prompt = f"{prompt}system: {SYSTEM_PROMPT}\nuser: {user_msg}\nassistant:"
40
-
41
- out = pipe(
42
- prompt,
43
- max_new_tokens=128, # 🔹 限制輸出長度,加快生成
44
  do_sample=True,
45
  temperature=0.7,
46
- top_p=0.9,
47
- top_k=50,
48
- repetition_penalty=1.1, # 🔹 減少重複
49
- eos_token_id=pipe.tokenizer.eos_token_id,
50
- num_return_sequences=1
51
- )[0]["generated_text"]
52
-
53
- reply = out.split("assistant:")[-1].strip()
54
- history.append(("user", user_msg))
55
- history.append(("assistant", reply))
56
- return history, ""
57
-
58
- with gr.Blocks() as demo:
59
- gr.Markdown("## Chatbot 範例 - TinyLlama-1.1B-Chat (CPU)")
60
- chatbox = gr.Chatbot(height=350)
61
- msg = gr.Textbox(label="輸入訊息")
62
- clear = gr.Button("清空對話")
63
-
64
- state = gr.State([])
65
-
66
- def init():
67
- return []
68
-
69
- msg.submit(chat, [state, msg], [state, msg]).then(
70
- lambda h: ([(h[i], h[i+1]) for i in range(0, len(h), 2)], ""),
71
- inputs=state,
72
- outputs=[chatbox, msg]
73
  )
74
- clear.click(init, outputs=state).then(lambda: [], outputs=chatbox)
 
 
 
75
 
76
  demo.launch()
 
 
1
  import gradio as gr
2
+ from transformers import pipeline
 
3
 
4
+ # 使用 TinyLlama-1.1B-Chat 模型
5
+ generator = pipeline("text-generation", model="TinyLlama/TinyLlama-1.1B-Chat-v1.0")
 
6
 
7
+ def chat(message, history):
8
+ # 生成回覆
9
+ result = generator(
10
+ message,
11
+ max_new_tokens=128, # 建議用 max_new_tokens(取代 max_length)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  do_sample=True,
13
  temperature=0.7,
14
+ top_p=0.9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  )
16
+ reply = result[0]["generated_text"]
17
+ return reply
18
+
19
+ demo = gr.ChatInterface(fn=chat, title="AI 聊天機器人 (TinyLlama-1.1B-Chat)")
20
 
21
  demo.launch()