danhtran2mind commited on
Commit
4330b89
·
verified ·
1 Parent(s): f714e11

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +704 -0
app.py ADDED
@@ -0,0 +1,704 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import re
3
+ import time
4
+ import torch
5
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
6
+ from peft import PeftModel
7
+ from threading import Thread
8
+ import gradio as gr
9
+ import gc
10
+
11
+ # Configure logging
12
+ logging.basicConfig(level=logging.INFO)
13
+ logger = logging.getLogger(__name__)
14
+
15
+ # LoRA configurations
16
+ lora_configs = {
17
+ "Gemma-3-1B-Instruct-Vi-Medical-LoRA": {
18
+ "base_model": "unsloth/gemma-3-1b-it",
19
+ "lora_adapter": "danhtran2mind/Gemma-3-1B-Instruct-Vi-Medical-LoRA"
20
+ },
21
+ "Gemma-3-1B-GRPO-Vi-Medical-LoRA": {
22
+ "base_model": "unsloth/gemma-3-1b-it",
23
+ "lora_adapter": "danhtran2mind/Gemma-3-1B-GRPO-Vi-Medical-LoRA"
24
+ },
25
+ "Llama-3.2-3B-Instruct-Vi-Medical-LoRA": {
26
+ "base_model": "unsloth/Llama-3.2-3B-Instruct",
27
+ "lora_adapter": "danhtran2mind/Llama-3.2-3B-Instruct-Vi-Medical-LoRA"
28
+ },
29
+ "Llama-3.2-1B-Instruct-Vi-Medical-LoRA": {
30
+ "base_model": "unsloth/Llama-3.2-1B-Instruct",
31
+ "lora_adapter": "danhtran2mind/Llama-3.2-1B-Instruct-Vi-Medical-LoRA"
32
+ },
33
+ "Llama-3.2-3B-Reasoning-Vi-Medical-LoRA": {
34
+ "base_model": "unsloth/Llama-3.2-3B-Instruct",
35
+ "lora_adapter": "danhtran2mind/Llama-3.2-3B-Reasoning-Vi-Medical-LoRA"
36
+ },
37
+ "Qwen-3-0.6B-Instruct-Vi-Medical-LoRA": {
38
+ "base_model": "Qwen/Qwen3-0.6B",
39
+ "lora_adapter": "danhtran2mind/Qwen-3-0.6B-Instruct-Vi-Medical-LoRA"
40
+ },
41
+ "Qwen-3-0.6B-Reasoning-Vi-Medical-LoRA": {
42
+ "base_model": "Qwen/Qwen3-0.6B",
43
+ "lora_adapter": "danhtran2mind/Qwen-3-0.6B-Reasoning-Vi-Medical-LoRA"
44
+ }
45
+ }
46
+
47
+ # Model settings
48
+ MAX_INPUT_TOKEN_LENGTH = 4096
49
+ DEFAULT_MAX_NEW_TOKENS = 512
50
+ MAX_MAX_NEW_TOKENS = 2048
51
+
52
+ # Global model and tokenizer
53
+ model = None
54
+ tokenizer = None
55
+ current_model_id = None
56
+
57
+ # Prompt templates for each LoRA model
58
+ def case_1_prompt(messages):
59
+ """Prompt style for Gemma-3-1B-Instruct-Vi-Medical-LoRA: Simple user prompt with chat template"""
60
+ return tokenizer.apply_chat_template(
61
+ messages,
62
+ add_generation_prompt=True,
63
+ tokenize=False
64
+ )
65
+
66
+ def case_2_prompt(messages):
67
+ """Prompt style for Gemma-3-1B-GRPO-Vi-Medical-LoRA: System prompt with reasoning and answer format"""
68
+ SYSTEM_PROMPT = """
69
+ Trả lời theo định dạng sau đây:
70
+ <reasoning>
71
+ ...
72
+ </reasoning>
73
+ <answer>
74
+ ...
75
+ </answer>
76
+ """
77
+ print("messages:##### ", messages)
78
+ # print("isinstance(messages, list): ", isinstance(messages, list))
79
+ # print('messages[0].get("role"): ', messages[0].get("role"))
80
+ if not messages or not isinstance(messages, list) or not messages[0].get("role") == "user":
81
+ return tokenizer.apply_chat_template(
82
+ [{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": "Vui lòng cung cấp câu hỏi để tôi trả lời."}],
83
+ add_generation_prompt=True,
84
+ tokenize=False
85
+ )
86
+
87
+ conversation = [{"role": "system", "content": SYSTEM_PROMPT}]
88
+ for i, msg in enumerate(messages):
89
+ conversation.append(msg)
90
+ if msg["role"] == "user" and (i == len(messages) - 1 or messages[i + 1]["role"] != "assistant"):
91
+ conversation.append({"role": "assistant", "content": ""})
92
+
93
+ return tokenizer.apply_chat_template(
94
+ conversation,
95
+ add_generation_prompt=True,
96
+ tokenize=False
97
+ )
98
+
99
+ def case_3_prompt(messages):
100
+ """Prompt style for Llama-3.2-3B-Instruct-Vi-Medical-LoRA: Extract answer from context"""
101
+ instruction = '''Bạn là một trợ lý hữu ích được giao nhiệm vụ trích xuất các đoạn văn trả lời câu hỏi của người dùng từ một ngữ cảnh cho trước. Xuất ra các đoạn văn chính xác từng từ một trả lời câu hỏi của người dùng. Không xuất ra bất kỳ văn bản nào khác ngoài các đoạn văn trong ngữ cảnh. Xuất ra lượng tối thiểu để trả lời câu hỏi, ví dụ chỉ 2-3 từ từ đoạn văn. Nếu không thể tìm thấy câu trả lời trong ngữ cảnh, xuất ra 'Ngữ cảnh không cung cấp câu trả lời...' '''
102
+ return tokenizer.apply_chat_template(
103
+ [{"role": "system", "content": instruction}] + messages,
104
+ add_generation_prompt=True,
105
+ tokenize=False
106
+ )
107
+
108
+ def case_4_prompt(messages):
109
+ """Prompt style for Llama-3.2-1B-Instruct-Vi-Medical-LoRA: Same as Llama-3.2-3B-Instruct-Vi-Medical-LoRA"""
110
+ return case_3_prompt(messages)
111
+
112
+ def case_5_prompt(question):
113
+ """Prompt style for Llama-3.2-3B-Reasoning-Vi-Medical-LoRA: Reasoning prompt with think tag"""
114
+ inference_prompt_style = """Bên dưới là một hướng dẫn mô tả một tác vụ, đi kèm với một thông tin đầu vào để cung cấp thêm ngữ cảnh.
115
+ Hãy viết một phản hồi để hoàn thành yêu cầu một cách phù hợp.
116
+ Trước khi trả lời, hãy suy nghĩ cẩn thận về câu hỏi và tạo một chuỗi suy nghĩ từng bước để đảm bảo phản hồi logic và chính xác.
117
+
118
+ ### Instruction:
119
+ Bạn là một chuyên gia y tế có kiến thức chuyên sâu về lập luận lâm sàng, chẩn đoán và lập kế hoạch điều trị.
120
+ Vui lòng trả lời câu hỏi y tế sau đây.
121
+
122
+ ### Question:
123
+ {}
124
+
125
+ ### Response:
126
+ <think>
127
+ """
128
+ return inference_prompt_style.format(question) + tokenizer.eos_token
129
+
130
+ def case_6_prompt(messages):
131
+ """Prompt style for Qwen-3-0.6B-Instruct-Vi-Medical-LoRA: Qwen-specific with enable_thinking=False"""
132
+ return tokenizer.apply_chat_template(
133
+ messages,
134
+ add_generation_prompt=True,
135
+ tokenize=False,
136
+ enable_thinking=False
137
+ )
138
+
139
+ def case_7_prompt(question):
140
+ """Prompt style for Qwen-3-0.6B-Reasoning-Vi-Medical-LoRA: Same as Llama-3.2-3B-Reasoning-Vi-Medical-LoRA"""
141
+ return case_5_prompt(question)
142
+
143
+ # Map LoRA configuration names to prompt functions
144
+ prompt_functions = {
145
+ "Gemma-3-1B-Instruct-Vi-Medical-LoRA": case_1_prompt,
146
+ "Gemma-3-1B-GRPO-Vi-Medical-LoRA": case_2_prompt,
147
+ "Llama-3.2-3B-Instruct-Vi-Medical-LoRA": case_3_prompt,
148
+ "Llama-3.2-1B-Instruct-Vi-Medical-LoRA": case_4_prompt,
149
+ "Llama-3.2-3B-Reasoning-Vi-Medical-LoRA": case_5_prompt,
150
+ "Qwen-3-0.6B-Instruct-Vi-Medical-LoRA": case_6_prompt,
151
+ "Qwen-3-0.6B-Reasoning-Vi-Medical-LoRA": case_7_prompt
152
+ }
153
+
154
+ def load_model(model_id, chatbot_state):
155
+ """Load the model, tokenizer, and apply LoRA adapter for the given model ID."""
156
+ global model, tokenizer, current_model_id
157
+ try:
158
+ logger.info(f"Loading model: {model_id}")
159
+ print(f"Changing to model: {model_id}")
160
+ if model is not None:
161
+ print("Clearing previous model from RAM/VRAM...")
162
+ del model
163
+ del tokenizer
164
+ model = None
165
+ tokenizer = None
166
+ gc.collect()
167
+ torch.cuda.empty_cache() if torch.cuda.is_available() else None
168
+ print("Memory cleared successfully.")
169
+
170
+ if model_id not in lora_configs:
171
+ raise ValueError(f"Invalid model ID: {model_id}")
172
+
173
+ base_model_name = lora_configs[model_id]["base_model"]
174
+ lora_adapter_name = lora_configs[model_id]["lora_adapter"]
175
+
176
+ tokenizer = AutoTokenizer.from_pretrained(
177
+ base_model_name,
178
+ trust_remote_code=True
179
+ )
180
+ tokenizer.use_default_system_prompt = False
181
+
182
+ if tokenizer.pad_token is None or tokenizer.pad_token == tokenizer.eos_token:
183
+ tokenizer.pad_token = tokenizer.unk_token or "<pad>"
184
+ logger.info(f"Set pad_token to {tokenizer.pad_token}")
185
+
186
+ model = AutoModelForCausalLM.from_pretrained(
187
+ base_model_name,
188
+ torch_dtype=torch.float16,
189
+ device_map="auto",
190
+ trust_remote_code=True
191
+ )
192
+
193
+ model = PeftModel.from_pretrained(model, lora_adapter_name)
194
+ model.eval()
195
+ model.config.pad_token_id = tokenizer.pad_token_id
196
+
197
+ current_model_id = model_id
198
+ chatbot_state = []
199
+ return f"Successfully loaded model: {model_id} with LoRA adapter {lora_adapter_name}", chatbot_state
200
+ except Exception as e:
201
+ logger.error(f"Failed to load model or tokenizer: {str(e)}")
202
+ return f"Error: Failed to load model {model_id}: {str(e)}", chatbot_state
203
+
204
+ def format_time(seconds_float):
205
+ total_seconds = int(round(seconds_float))
206
+ hours = total_seconds // 3600
207
+ remaining_seconds = total_seconds % 3600
208
+ minutes = remaining_seconds // 60
209
+ seconds = remaining_seconds % 60
210
+
211
+ if hours > 0:
212
+ return f"{hours}h {minutes}m {seconds}s"
213
+ elif minutes > 0:
214
+ return f"{minutes}m {seconds}s"
215
+ else:
216
+ return f"{seconds}s"
217
+
218
+ DESCRIPTION = '''
219
+ # Medical Chatbot with LoRA-Enhanced Models
220
+ ## Demo of Medical Reasoning Models
221
+ Interact with various models fine-tuned with LoRA adapters for medical reasoning in Vietnamese.
222
+ '''
223
+
224
+ CSS = """
225
+ .spinner {
226
+ animation: spin 1s linear infinite;
227
+ display: inline-block;
228
+ margin-right: 8px;
229
+ }
230
+ @keyframes spin {
231
+ from { transform: rotate(0deg); }
232
+ to { transform: rotate(360deg); }
233
+ }
234
+ .thinking-summary {
235
+ cursor: pointer;
236
+ padding: 8px;
237
+ background: #f5f5f5;
238
+ border-radius: 4px;
239
+ margin: 4px 0;
240
+ }
241
+ .thought-content {
242
+ padding: 10px;
243
+ background: none;
244
+ border-radius: 4px;
245
+ margin: 5px 0;
246
+ }
247
+ .thinking-container {
248
+ border-left: 3px solid #facc15;
249
+ padding-left: 10px;
250
+ margin: 8px 0;
251
+ background: none;
252
+ }
253
+ .thinking-container:empty {
254
+ background: #e0e0e0;
255
+ }
256
+ details:not([open]) .thinking-container {
257
+ border-left-color: #290c15;
258
+ }
259
+ details {
260
+ border: 1px solid #e0e0e0 !important;
261
+ border-radius: 8px !important;
262
+ padding: 12px !important;
263
+ margin: 8px 0 !important;
264
+ transition: border-color 0.2s;
265
+ }
266
+ .think-section {
267
+ background-color: #e6f3ff;
268
+ border-left: 4px solid #4a90e2;
269
+ padding: 15px;
270
+ margin: 10px 0;
271
+ border-radius: 6px;
272
+ font-size: 14px;
273
+ }
274
+ .final-answer {
275
+ background-color: #f0f4f8;
276
+ border-left: 4px solid #2ecc71;
277
+ padding: 15px;
278
+ margin: 10px 0;
279
+ border-radius: 6px;
280
+ font-size: 14px;
281
+ }
282
+ #output-container {
283
+ position: relative;
284
+ }
285
+ .copy-button {
286
+ position: absolute;
287
+ top: 10px;
288
+ right: 10px;
289
+ padding: 5px 10px;
290
+ background-color: #4a90e2;
291
+ color: white;
292
+ border: none;
293
+ border-radius: 4px;
294
+ cursor: pointer;
295
+ }
296
+ .copy-button:hover {
297
+ background-color: #357abd;
298
+ }
299
+ """
300
+
301
+ JS_SCRIPTS = """
302
+ <script>
303
+ function copyToClipboard(elementId) {
304
+ const element = document.getElementById(elementId);
305
+ let text = element.innerText.replace(/^Thinking Process:\\n|^Final Answer:\\n/, '');
306
+ text = text.replace(/\\mjx-[^\\s]+/g, '');
307
+ navigator.clipboard.writeText(text).then(() => {
308
+ alert('Copied to clipboard!');
309
+ }).catch(err => {
310
+ console.error('Failed to copy: ', err);
311
+ });
312
+ }
313
+ </script>
314
+ <style>
315
+ .chatbot .message.assistant {
316
+ position: relative;
317
+ }
318
+ .chatbot .message.assistant::after {
319
+ content: 'Copy';
320
+ position: absolute;
321
+ top: 10px;
322
+ right: 10px;
323
+ padding: 5px 10px;
324
+ background-color: #4a90e2;
325
+ color: white;
326
+ border: none;
327
+ border-radius: 4px;
328
+ cursor: pointer;
329
+ }
330
+ .chatbot .message.assistant:hover::after {
331
+ background-color: #357abd;
332
+ }
333
+ </style>
334
+ """
335
+
336
+ def user(message, history):
337
+ if not isinstance(history, list):
338
+ history = []
339
+ return "", history + [[message, None]]
340
+
341
+ class ParserState:
342
+ __slots__ = ['answer', 'thought', 'in_think', 'in_answer', 'start_time', 'last_pos', 'total_think_time']
343
+ def __init__(self):
344
+ self.answer = ""
345
+ self.thought = ""
346
+ self.in_think = False
347
+ self.in_answer = False
348
+ self.start_time = 0
349
+ self.last_pos = 0
350
+ self.total_think_time = 0.0
351
+
352
+ def parse_response(text, state):
353
+ buffer = text[state.last_pos:]
354
+ state.last_pos = len(text)
355
+
356
+ while buffer:
357
+ if not state.in_think and not state.in_answer:
358
+ think_start = buffer.find('<think>')
359
+ reasoning_start = buffer.find('<reasoning>')
360
+ answer_start = buffer.find('<answer>')
361
+
362
+ starts = []
363
+ if think_start != -1:
364
+ starts.append((think_start, '<think>', 7, 'think'))
365
+ if reasoning_start != -1:
366
+ starts.append((reasoning_start, '<reasoning>', 11, 'think'))
367
+ if answer_start != -1:
368
+ starts.append((answer_start, '<answer>', 8, 'answer'))
369
+
370
+ if not starts:
371
+ state.answer += buffer
372
+ break
373
+
374
+ start_pos, start_tag, tag_length, mode = min(starts, key=lambda x: x[0])
375
+
376
+ state.answer += buffer[:start_pos]
377
+ if mode == 'think':
378
+ state.in_think = True
379
+ state.start_time = time.perf_counter()
380
+ else:
381
+ state.in_answer = True
382
+ buffer = buffer[start_pos + tag_length:]
383
+
384
+ elif state.in_think:
385
+ think_end = buffer.find('</think>')
386
+ reasoning_end = buffer.find('</reasoning>')
387
+
388
+ ends = []
389
+ if think_end != -1:
390
+ ends.append((think_end, '</think>', 8))
391
+ if reasoning_end != -1:
392
+ ends.append((reasoning_end, '</reasoning>', 12))
393
+
394
+ if ends:
395
+ end_pos, end_tag, tag_length = min(ends, key=lambda x: x[0])
396
+ state.thought += buffer[:end_pos]
397
+ duration = time.perf_counter() - state.start_time
398
+ state.total_think_time += duration
399
+ state.in_think = False
400
+ buffer = buffer[end_pos + tag_length:]
401
+ if end_tag == '</reasoning>':
402
+ state.answer += buffer
403
+ break
404
+ else:
405
+ state.thought += buffer
406
+ break
407
+
408
+ elif state.in_answer:
409
+ answer_end = buffer.find('</answer>')
410
+ if answer_end != -1:
411
+ state.answer += buffer[:answer_end]
412
+ state.in_answer = False
413
+ buffer = buffer[answer_end + 9:]
414
+ else:
415
+ state.answer += buffer
416
+ break
417
+
418
+ elapsed = time.perf_counter() - state.start_time if state.in_think else 0
419
+ return state, elapsed
420
+
421
+ def format_response(state, elapsed):
422
+ answer_part = state.answer
423
+ collapsible = []
424
+ collapsed = "<details open>"
425
+
426
+ if state.thought or state.in_think:
427
+ if state.in_think:
428
+ total_elapsed = state.total_think_time + elapsed
429
+ formatted_time = format_time(total_elapsed)
430
+ status = f"💭 Thinking for {formatted_time}"
431
+ else:
432
+ formatted_time = format_time(state.total_think_time)
433
+ status = f"✅ Thought for {formatted_time}"
434
+ collapsed = "<details>"
435
+ collapsible.append(
436
+ f"{collapsed}<summary>{status}</summary>\n\n<div class='thinking-container'>\n{state.thought}\n</div>\n</details>"
437
+ )
438
+ # print("collapsible: ", collapsible)
439
+ # print("answer_part: ", answer_part)
440
+ return collapsible, answer_part
441
+
442
+ def remove_tags(text):
443
+ if text is None:
444
+ return None
445
+ return re.sub(r'<[^>]+>', ' ', text).strip()
446
+
447
+ def generate_response(history, temperature, top_p, top_k, max_tokens, seed, active_gen, model_id, auto_clear):
448
+ global model, tokenizer, current_model_id
449
+ if auto_clear:
450
+ history = [history[-1]]
451
+
452
+ # Apply the function to the second element of each sublist
453
+ history = [[item[0], remove_tags(item[1])] for item in history]
454
+
455
+ try:
456
+ if not history or not isinstance(history, list):
457
+ logger.error("History is empty or not a list")
458
+ history = [[None, "Error: Conversation history is empty or invalid"]]
459
+ yield history
460
+ return
461
+
462
+ if not isinstance(history[-1], (list, tuple)) or len(history[-1]) < 1 or not history[-1][0]:
463
+ logger.error("Last history entry is invalid or missing user message")
464
+ history = history[:-1] + [[history[-1][0] if history else None, "Error: No valid user message provided"]]
465
+ yield history
466
+ return
467
+
468
+ if model is None or tokenizer is None or model_id != current_model_id:
469
+ status, history = load_model(model_id, history)
470
+ if "Error" in status:
471
+ logger.error(status)
472
+ history[-1][1] = status
473
+ yield history
474
+ return
475
+
476
+ torch.manual_seed(int(seed))
477
+ if torch.cuda.is_available():
478
+ torch.cuda.manual_seed(int(seed))
479
+ torch.cuda.manual_seed_all(int(seed))
480
+
481
+ if model_id not in prompt_functions:
482
+ logger.error(f"No prompt function defined for model_id: {model_id}")
483
+ history[-1][1] = f"Error: No prompt function defined for model {model_id}"
484
+ yield history
485
+ return
486
+ prompt_fn = prompt_functions[model_id]
487
+
488
+ if model_id in [
489
+ "Llama-3.2-3B-Reasoning-Vi-Medical-LoRA",
490
+ "Qwen-3-0.6B-Reasoning-Vi-Medical-LoRA"
491
+ ]:
492
+ text = prompt_fn(history[-1][0])
493
+ inputs = tokenizer(
494
+ [text],
495
+ return_tensors="pt",
496
+ padding=True,
497
+ truncation=True,
498
+ max_length=MAX_INPUT_TOKEN_LENGTH
499
+ )
500
+ else:
501
+ conversation = []
502
+ for msg in history:
503
+ if msg[0]:
504
+ conversation.append({"role": "user", "content": msg[0]})
505
+ if msg[1]:
506
+ clean_text = ' '.join(line for line in msg[1].split('\n') if not line.startswith('✅ Thought for')).strip()
507
+ conversation.append({"role": "assistant", "content": clean_text})
508
+ elif msg[0] and not msg[1]:
509
+ conversation.append({"role": "assistant", "content": ""})
510
+
511
+ if not conversation:
512
+ logger.error("No valid messages in conversation history")
513
+ history[-1][1] = "Error: No valid messages in conversation history"
514
+ yield history
515
+ return
516
+
517
+ if model_id in [
518
+ "Gemma-3-1B-GRPO-Vi-Medical-LoRA"
519
+ ]:
520
+ conversation= conversation[-2:]
521
+
522
+ text = prompt_fn(conversation)
523
+ tokenizer_kwargs = {
524
+ "return_tensors": "pt",
525
+ "padding": True,
526
+ "truncation": True,
527
+ "max_length": MAX_INPUT_TOKEN_LENGTH
528
+ }
529
+
530
+ inputs = tokenizer(text, **tokenizer_kwargs)
531
+
532
+ if inputs is None or "input_ids" not in inputs:
533
+ logger.error("Tokenizer returned invalid or None output")
534
+ history[-1][1] = "Error: Failed to tokenize input"
535
+ yield history
536
+ return
537
+
538
+ input_ids = inputs["input_ids"].to(model.device)
539
+ attention_mask = inputs.get("attention_mask").to(model.device) if "attention_mask" in inputs else None
540
+
541
+ generate_kwargs = {
542
+ "input_ids": input_ids,
543
+ "attention_mask": attention_mask,
544
+ "max_new_tokens": max_tokens,
545
+ "do_sample": True,
546
+ "temperature": temperature,
547
+ "top_p": top_p,
548
+ "top_k": top_k,
549
+ "num_beams": 1,
550
+ "repetition_penalty": 1.0,
551
+ "pad_token_id": tokenizer.pad_token_id,
552
+ "eos_token_id": tokenizer.eos_token_id,
553
+ "use_cache": True,
554
+ "cache_implementation": "dynamic",
555
+ }
556
+
557
+ streamer = TextIteratorStreamer(tokenizer, timeout=360.0, skip_prompt=True, skip_special_tokens=True)
558
+ generate_kwargs["streamer"] = streamer
559
+
560
+ def run_generation():
561
+ try:
562
+ model.generate(**generate_kwargs)
563
+ except Exception as e:
564
+ logger.error(f"Generation failed: {str(e)}")
565
+ raise
566
+
567
+ thread = Thread(target=run_generation)
568
+ thread.start()
569
+
570
+ state = ParserState()
571
+ if model_id in [
572
+ "Llama-3.2-3B-Reasoning-Vi-Medical-LoRA",
573
+ "Qwen-3-0.6B-Reasoning-Vi-Medical-LoRA"
574
+ ]:
575
+ full_response = "<think>"
576
+ else:
577
+ full_response = ""
578
+
579
+ for text in streamer:
580
+ if not active_gen[0]:
581
+ logger.info("Generation stopped by user")
582
+ break
583
+
584
+ if text:
585
+ logger.debug(f"Raw streamer output: {text}")
586
+ text = re.sub(r'<\|\w+\|>', '', text)
587
+ full_response += text
588
+ state, elapsed = parse_response(full_response, state)
589
+
590
+ collapsible, answer_part = format_response(state, elapsed)
591
+ history[-1][1] = "\n\n".join(collapsible + [answer_part])
592
+ yield history
593
+ else:
594
+ logger.debug("Streamer returned empty text")
595
+
596
+ thread.join()
597
+ thread = None
598
+ state, elapsed = parse_response(full_response, state)
599
+ collapsible, answer_part = format_response(state, elapsed)
600
+ history[-1][1] = "\n\n".join(collapsible + [answer_part])
601
+ if not full_response:
602
+ logger.warning("No response generated by model")
603
+ history[-1][1] = "No response generated. Please try again or select a different model."
604
+ print("full_response: ", full_response)
605
+ yield history
606
+
607
+ except Exception as e:
608
+ logger.error(f"Error in generate: {str(e)}")
609
+ if not history or not isinstance(history, list):
610
+ history = [[None, f"Error: {str(e)}. Please try again or select a different model."]]
611
+ else:
612
+ history[-1][1] = f"Error: {str(e)}. Please try again or select a different model."
613
+ yield history
614
+ finally:
615
+ active_gen[0] = False
616
+
617
+ MODEL_IDS = list(lora_configs.keys())
618
+ load_model(MODEL_IDS[0], [])
619
+ with gr.Blocks(css=CSS, theme=gr.themes.Default()) as demo:
620
+ gr.Markdown(DESCRIPTION)
621
+ gr.HTML(JS_SCRIPTS)
622
+ active_gen = gr.State([False])
623
+
624
+ chatbot = gr.Chatbot(
625
+ elem_id="chatbot",
626
+ height=500,
627
+ show_label=False,
628
+ render_markdown=True
629
+ )
630
+
631
+ with gr.Row():
632
+ msg = gr.Textbox(
633
+ label="Message",
634
+ placeholder="Type your medical query in Vietnamese...",
635
+ container=False,
636
+ scale=4
637
+ )
638
+ submit_btn = gr.Button("Send", variant='primary', scale=1)
639
+
640
+ with gr.Column(scale=2):
641
+ with gr.Row():
642
+ clear_btn = gr.Button("Clear", variant='secondary')
643
+ stop_btn = gr.Button("Stop", variant='stop')
644
+
645
+ with gr.Accordion("Parameters", open=False):
646
+ model_dropdown = gr.Dropdown(
647
+ choices=MODEL_IDS,
648
+ value=MODEL_IDS[0],
649
+ label="Select Model",
650
+ interactive=True
651
+ )
652
+ temperature = gr.Slider(minimum=0.1, maximum=1.5, value=0.7, label="Temperature")
653
+ top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, label="Top-p")
654
+ top_k = gr.Slider(minimum=1, maximum=100, value=64, step=1, label="Top-k")
655
+ max_tokens = gr.Slider(minimum=128, maximum=4084, value=512, step=32, label="Max Tokens")
656
+ seed = gr.Slider(minimum=0, maximum=2 ** 32, value=42, step=1, label="Random Seed")
657
+ auto_clear = gr.Checkbox(label="Auto Clear History", value=True, info="Clears internal conversation history after each response but keeps displayed messages.")
658
+
659
+ gr.Examples(
660
+ examples=[
661
+ ["Khi nghi ngờ bị loét dạ dày tá tràng nên đến khoa nào tại bệnh viện để thăm khám?"],
662
+ ["Triệu chứng của loét dạ dày tá tràng là gì?"],
663
+ ["Tôi bị mất ngủ, tôi phải làm gì?"],
664
+ ["Tôi bị trĩ, tôi có nên mổ không?"]
665
+ ],
666
+ inputs=msg,
667
+ label="Example Medical Queries"
668
+ )
669
+
670
+ model_load_output = gr.Textbox(label="Model Load Status")
671
+ model_dropdown.change(
672
+ fn=load_model,
673
+ inputs=[model_dropdown, chatbot],
674
+ outputs=[model_load_output, chatbot]
675
+ )
676
+
677
+ submit_event = submit_btn.click(
678
+ user, [msg, chatbot], [msg, chatbot], queue=False
679
+ ).then(
680
+ lambda: [True], outputs=active_gen
681
+ ).then(
682
+ generate_response, [chatbot, temperature, top_p, top_k, max_tokens, seed, active_gen, model_dropdown, auto_clear], chatbot
683
+ )
684
+
685
+ msg.submit(
686
+ user, [msg, chatbot], [msg, chatbot], queue=False
687
+ ).then(
688
+ lambda: [True], outputs=active_gen
689
+ ).then(
690
+ generate_response, [chatbot, temperature, top_p, top_k, max_tokens, seed, active_gen, model_dropdown, auto_clear], chatbot
691
+ )
692
+
693
+ stop_btn.click(
694
+ lambda: [False], None, active_gen, cancels=[submit_event]
695
+ )
696
+
697
+ clear_btn.click(lambda: None, None, chatbot, queue=False)
698
+
699
+ if __name__ == "__main__":
700
+ try:
701
+ demo.launch(server_name="0.0.0.0", server_port=7860)
702
+ except Exception as e:
703
+ logger.error(f"Failed to launch Gradio app: {str(e)}")
704
+ raise