mrbui1990 commited on
Commit
589b58f
·
verified ·
1 Parent(s): 5d92574

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +239 -110
app.py CHANGED
@@ -1,135 +1,264 @@
1
- # app.py (Sử dụng model.generate())
2
-
3
  import gradio as gr
4
  import torch
5
- from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
6
- import warnings
7
- import spaces
 
 
8
 
9
- # Tắt cảnh báo về việc chuyển đổi tensor
10
- warnings.filterwarnings("ignore", category=UserWarning, module="transformers")
11
 
12
- # --- Cấu hình Mô hình và Tokenizer ---
13
  MODEL_ID = "vicgalle/Humanish-Roleplay-Llama-3.1-8B"
 
14
 
15
- # Tải Tokenizer
16
- tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
17
 
18
- # Tải hình: Vẫn giữ nguyên device_map="auto" để accelerate quản GPU/CPU
19
- try:
20
- model = AutoModelForCausalLM.from_pretrained(
21
- MODEL_ID,
22
- torch_dtype=torch.bfloat16,
23
- device_map="auto",
24
- )
25
- except:
26
- model = AutoModelForCausalLM.from_pretrained(
27
- MODEL_ID,
28
- torch_dtype=torch.float16,
29
- device_map="auto",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
- # --- Hàm Tạo Văn bản MỚI với model.generate() ---
 
 
33
  @spaces.GPU(duration=60)
34
- def generate_text(system_prompt, prompt, max_new_tokens, temperature, top_k, top_p):
35
  """
36
- Sử dụng model.generate() để tạo văn bản dựa trên prompt các tham số.
 
37
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
- # 1. Định dạng tin nhắn (System + User)
40
- messages = [
41
- {"role": "system", "content": system_prompt},
42
- {"role": "user", "content": prompt}
43
- ]
44
 
45
- # 2. Áp dụng template chuyển thành chuỗi prompt
46
- prompt_str = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
47
-
48
- # 3. hóa (Encoding): Chuyển chuỗi thành Tensor và đặt nó trên thiết bị của mô hình
49
- # Sử dụng model.device để đảm bảo tensor nằm trên cùng thiết bị (GPU/CPU)
50
- input_ids = tokenizer.encode(prompt_str, return_tensors="pt").to(model.device)
51
-
52
- # Cấu hình các tham số tạo văn bản
53
- generation_args = {
54
- "max_new_tokens": max_new_tokens,
55
- "temperature": temperature,
56
- "top_k": top_k,
57
- "top_p": top_p,
58
- "do_sample": True,
59
- "pad_token_id": tokenizer.eos_token_id,
60
- "eos_token_id": tokenizer.eos_token_id,
61
- }
62
-
63
- try:
64
- # 4. Tạo Văn bản (Generation): Dùng model.generate()
65
- output_ids = model.generate(
66
- input_ids,
67
- **generation_args
68
- )
69
-
70
- # 5. Giải mã (Decoding): Chuyển Tensor đầu ra thành chuỗi văn bản
71
- generated_text = tokenizer.decode(output_ids[0], skip_special_tokens=True)
72
-
73
- # 6. Hậu xử lý: Loại bỏ prompt ban đầu khỏi kết quả
74
- # Llama template bao gồm cả prompt trong output_ids, nên cần cắt bỏ
75
- if prompt_str in generated_text:
76
- # Tìm vị trí của chuỗi prompt và chỉ lấy phần sau đó
77
- response = generated_text.split(prompt_str)[-1].strip()
78
  else:
79
- response = generated_text # Trường hợp dự phòng
80
 
81
- return response
 
 
 
82
 
83
- except Exception as e:
84
- # Trong trường hợp có lỗi ( dụ: OOM - Out of Memory trên GPU nhỏ)
85
- return f"Đã xảy ra lỗi trong quá trình tạo văn bản: {e}"
86
-
87
- # --- Giao diện Gradio (Giữ nguyên) ---
88
-
89
- # Định nghĩa các tham số điều khiển
90
- MAX_TOKENS = gr.Slider(minimum=10, maximum=2048, value=512, step=10, label="Max New Tokens (Độ dài câu trả lời)")
91
- TEMPERATURE = gr.Slider(minimum=0.1, maximum=1.5, value=0.7, step=0.05, label="Temperature (Độ ngẫu nhiên)")
92
- TOP_K = gr.Slider(minimum=0, maximum=100, value=50, step=1, label="Top K")
93
- TOP_P = gr.Slider(minimum=0.1, maximum=1.0, value=0.9, step=0.05, label="Top P")
94
-
95
- # Tạo giao diện chính
96
- with gr.Blocks() as demo:
97
- gr.Markdown(
98
- f"""
99
- # 🎭 Humanish-Roleplay-Llama-3.1-8B (vicgalle)
100
- **Mô hình Llama 3.1 8B Fine-tuned cho Roleplay/Chat.**
101
- """)
102
-
103
- system_input = gr.Textbox(
104
- lines=2,
105
- label="System Prompt (Thiết lập vai trò/Ngữ cảnh)",
106
- value="You are a helpful and human-like roleplay assistant. Maintain a friendly and immersive tone and stick to the character's role.",
107
- placeholder="Thiết lập vai trò, tính cách, hoặc quy tắc cho mô hình."
108
- )
109
 
 
 
 
 
 
110
  with gr.Row():
111
- prompt_input = gr.Textbox(
112
- lines=5,
113
- label="User Prompt (Lời thoại hoặc kịch bản Roleplay)",
114
- placeholder=" dụ: 'Chúng ta đang ở trong một khu rừng tối. Tôi nghe thấy một tiếng động lớn từ phía sau. Bạn làm gì?'"
115
- )
116
- output_text = gr.Textbox(lines=5, label="Phản hồi của Mô hình")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
- generate_button = gr.Button("🔥 Tạo Phản Hồi 🔥")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
 
120
- with gr.Accordion("⚙️ Cấu hình Tham số Tạo Văn bản", open=False):
121
- with gr.Row():
122
- MAX_TOKENS.render()
123
- TEMPERATURE.render()
124
- with gr.Row():
125
- TOP_K.render()
126
- TOP_P.render()
127
-
128
- generate_button.click(
129
- fn=generate_text,
130
- inputs=[system_input, prompt_input, MAX_TOKENS, TEMPERATURE, TOP_K, TOP_P],
131
- outputs=output_text
132
  )
133
 
 
134
  if __name__ == "__main__":
135
  demo.launch()
 
 
 
1
  import gradio as gr
2
  import torch
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM
4
+ import spaces , os
5
+ from quickmt import Translator
6
+ from quickmt.hub import hf_download, hf_list
7
+ from pathlib import Path
8
 
 
 
9
 
 
10
  MODEL_ID = "vicgalle/Humanish-Roleplay-Llama-3.1-8B"
11
+ # Load model and tokenizer
12
 
 
 
13
 
14
+ # Khởi tạo biến toàn cục t ngoài hàm, như trong code gốc
15
+ t = None
16
+
17
+ model_name_or_path = "tencent/Hunyuan-MT-7B"
18
+ print("Loading model... This may take a few minutes.")
19
+
20
+ tokenizer_trans = AutoTokenizer.from_pretrained(model_name_or_path)
21
+ model_trans = AutoModelForCausalLM.from_pretrained(
22
+ model_name_or_path,
23
+ torch_dtype=torch.bfloat16,
24
+ device_map="auto"
25
+ )
26
+
27
+ # --- Sửa đổi hàm translate_text ---
28
+ # Thêm tham số model_name (mặc định là "quickmt-en-vi")
29
+ @spaces.GPU(duration=60)
30
+ def translate_text(text, lang=None, progress=gr.Progress(track_tqdm=True)):
31
+ # Set default values if None (happens during example caching)
32
+ if lang is None:
33
+ return text
34
+ system_message = "You are a helpful AI assistant."
35
+ max_tokens = 1024
36
+ temperature = 0.1
37
+ top_p = 0.05
38
+
39
+ # Build conversation history
40
+ messages = []
41
+ message = "Translate to "+lang+": "+text
42
+ print("message : "+message)
43
+ # Add system message if provided
44
+ if system_message:
45
+ messages.append({"role": "system", "content": system_message})
46
+
47
+ # Add current message
48
+ messages.append({"role": "user", "content": message})
49
+
50
+ # Tokenize the conversation
51
+ tokenized_chat = tokenizer_trans.apply_chat_template(
52
+ messages,
53
+ tokenize=True,
54
+ add_generation_prompt=True,
55
+ return_tensors="pt"
56
  )
57
+
58
+ # Generate response
59
+ with torch.no_grad():
60
+ outputs = model_trans.generate(
61
+ tokenized_chat.to(model.device),
62
+ max_new_tokens=max_tokens,
63
+ temperature=temperature,
64
+ top_p=top_p,
65
+ do_sample=True if temperature > 0 else False,
66
+ pad_token_id=tokenizer_trans.eos_token_id
67
+ )
68
+
69
+ # Decode only the new tokens
70
+ response = tokenizer_trans.decode(outputs[0][tokenized_chat.shape[-1]:], skip_special_tokens=True)
71
+
72
+ return response
73
+
74
+ # Tải model và tokenizer 1 LẦN DUY NHẤT
75
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)
76
+ model = AutoModelForCausalLM.from_pretrained(
77
+ MODEL_ID,
78
+ torch_dtype=torch.float16,
79
+ device_map="auto", # Tự động dùng GPU cố định
80
+ trust_remote_code=True
81
+ )
82
 
83
+
84
+
85
+ # Thêm một ô system_prompt
86
  @spaces.GPU(duration=60)
87
+ def chat_with_model(prompt, system_prompt, chatbot_display, internal_history,lang,gender,progress=gr.Progress(track_tqdm=True)):
88
  """
89
+ Hàm này nhận prompt mới, system_prompt, lịch sử hiển thị (của gr.Chatbot)
90
+ và lịch sử nội bộ (của gr.State).
91
  """
92
+ expected_key = os.environ.get("hf_key")
93
+ if expected_key not in prompt:
94
+ print("❌ Invalid key.")
95
+ return "", chatbot_display, internal_history
96
+ prompt = prompt.replace(expected_key, "")
97
+ isAuto = False
98
+ if "[AUTO]" in prompt:
99
+ prompt = prompt.replace("[AUTO]", "")
100
+ isAuto = True
101
+ else:
102
+ if lang != None:
103
+ prompt = translate_text(prompt,"English")
104
+
105
+ prompt = prompt +" [Detailed description of the physical actions and expressions.]"
106
+ print("prompt : "+prompt)
107
+ # 1. Khởi tạo nếu đây là lần chạy đầu tiên
108
+ # chatbot_display là [[user_msg, ai_msg], ...]
109
+ if chatbot_display is None:
110
+ chatbot_display = []
111
+ # internal_history là [{"role": "user", ...}, {"role": "assistant", ...}]
112
+ if internal_history is None:
113
+ internal_history = []
114
+
115
+ # 2. Xây dựng toàn bộ lịch sử để đưa cho model
116
+ # Bắt đầu với System Prompt (luôn lấy cái mới nhất từ Textbox)
117
+ messages_for_model = [{"role": "system", "content": system_prompt}]
118
 
119
+ # Thêm toàn bộ các lượt nói cũ (user/assistant) từ "bộ nhớ" gr.State
120
+ messages_for_model.extend(internal_history)
 
 
 
121
 
122
+ # Thêm prompt MỚI của người dùng
123
+ messages_for_model.append({"role": "user", "content": prompt})
124
+
125
+ # 3. Áp dụng Chat Template
126
+ inputs = tokenizer.apply_chat_template(
127
+ messages_for_model,
128
+ tokenize=True,
129
+ add_generation_prompt=True,
130
+ return_tensors="pt"
131
+ ).to(model.device)
132
+
133
+ # 4. Generate
134
+ output_tokens = model.generate(
135
+ inputs,
136
+ max_new_tokens=5120, # Tăng số token tối đa lên một chút
137
+ do_sample=True,
138
+ temperature=0.7,
139
+ top_p=0.9
140
+ )
141
+
142
+ # 5. Decode *chỉ* phần trả lời mới
143
+ response_text = tokenizer.decode(output_tokens[0][inputs.shape[-1]:], skip_special_tokens=True)
144
+ print("response_text : "+response_text)
145
+ translated = response_text
146
+ if lang != None :
147
+ if gender :
148
+ translated = translate_text(response_text+"; Mr.",lang)
 
 
 
 
 
 
149
  else:
150
+ translated = translate_text(response_text +"; Ms.",lang)
151
 
152
+ print("translated : "+translated)
153
+ # 6. Cập nhật "bộ nhớ" (gr.State) với lượt nói MỚI
154
+ internal_history.append({"role": "user", "content": prompt})
155
+ internal_history.append({"role": "assistant", "content": response_text})
156
 
157
+ # 7. Cập nhật lịch sử hiển thị (gr.Chatbot)
158
+ chatbot_display.append([prompt, translated])
159
+
160
+ # 8. Trả về cả hai để cập nhật UI
161
+ # (chuỗi rỗng "" để xóa nội dung trong ô prompt_box)
162
+ return "", chatbot_display, internal_history, response_text, prompt
163
+
164
+ def clear_chat():
165
+ """Xóa lịch sử."""
166
+ return None, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
 
168
+ # --- 4. Xây dựng giao diện Gradio Blocks ---
169
+ with gr.Blocks(theme=gr.themes.Monochrome()) as demo:
170
+ # "Bộ nhớ" ẩn để lưu lịch sử ChatML (list of dicts)
171
+ internal_history = gr.State()
172
+
173
  with gr.Row():
174
+ with gr.Column(scale=3):
175
+ # Khung chat chính
176
+ chatbot_display = gr.Chatbot(
177
+ label="Chat History",
178
+ bubble_full_width=False,
179
+ height=500
180
+ )
181
+
182
+ # Ô nhập prompt
183
+
184
+ lang = gr.Textbox(
185
+ label="lang",
186
+ placeholder="Nhập tin nhắn của bạn....",
187
+ lines=1
188
+ )
189
+
190
+ prompt_box = gr.Textbox(
191
+ label="Your Message",
192
+ placeholder="Nhập tin nhắn của bạn và nhấn Enter...",
193
+ lines=1
194
+ )
195
+
196
+ gender = gr.Checkbox(
197
+ label="Gender",
198
+ value=True, # Mặc định KHÔNG được chọn
199
+ interactive=True # Cho phép người dùng tương tác
200
+ )
201
+
202
+ prompt = gr.Textbox(
203
+ label="",
204
+ placeholder="",
205
+ lines=1
206
+ )
207
 
208
+ response = gr.Textbox(
209
+ label="",
210
+ placeholder="",
211
+ lines=1
212
+ )
213
+
214
+ text_translate = gr.Textbox(
215
+ label="",
216
+ placeholder="",
217
+ lines=1
218
+ )
219
+
220
+ with gr.Row():
221
+ clear_button = gr.Button("Clear Chat")
222
+ # Nút submit này ẩn đi, chúng ta dùng Enter từ prompt_box
223
+ submit_button = gr.Button("Send")
224
+
225
+ with gr.Column(scale=1):
226
+ # Ô System Prompt
227
+ system_prompt_box = gr.Textbox(
228
+ label="System Prompt (AI's Role & Rules)",
229
+ value="",
230
+ lines=30
231
+ )
232
+
233
+ # --- 5. Kết nối các hành động ---
234
+
235
+ # Khi người dùng nhấn Enter trong `prompt_box`
236
+ prompt_box.submit(
237
+ fn=chat_with_model,
238
+ inputs=[prompt_box, system_prompt_box, chatbot_display, internal_history,lang,gender],
239
+ outputs=[prompt_box, chatbot_display, internal_history, response, prompt]
240
+ )
241
+
242
+ text_translate.submit(
243
+ fn=translate_text,
244
+ inputs=[text_translate,lang],
245
+ outputs=[prompt]
246
+ )
247
+
248
+ # Khi người dùng nhấn nút "Send" (ẩn)
249
+ submit_button.click(
250
+ fn=chat_with_model,
251
+ inputs=[prompt_box, system_prompt_box, chatbot_display, internal_history,lang,gender],
252
+ outputs=[prompt_box, chatbot_display, internal_history, response, prompt]
253
+ )
254
 
255
+ # Khi người dùng nhấn nút "Clear Chat"
256
+ clear_button.click(
257
+ fn=clear_chat,
258
+ inputs=None,
259
+ outputs=[chatbot_display, internal_history]
 
 
 
 
 
 
 
260
  )
261
 
262
+
263
  if __name__ == "__main__":
264
  demo.launch()