sunbv56 commited on
Commit
9bc5cc9
·
verified ·
1 Parent(s): 4bfeff8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -25
app.py CHANGED
@@ -1,4 +1,4 @@
1
- # app.py (Phiên bản cuối cùng đã sửa lỗi TypeErrorcác cảnh báo)
2
 
3
  import gradio as gr
4
  import torch
@@ -12,7 +12,7 @@ import requests
12
  warnings.filterwarnings("ignore", category=UserWarning, message="Overriding torch_dtype=None")
13
 
14
  # --- 1. Tải Model và Processor ---
15
- MODEL_ID = "sunbv56/qwen2.5-vl-vqa-vibook"
16
  print(f"🚀 Đang tải model '{MODEL_ID}' và processor...")
17
  try:
18
  dtype = torch.bfloat16 if torch.cuda.is_available() and torch.cuda.is_bf16_supported() else torch.float16
@@ -31,12 +31,24 @@ def process_vqa(image: Image.Image, question: str):
31
  messages = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": question}]}]
32
  prompt_text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
33
  model_inputs = processor(text=[prompt_text], images=[image], return_tensors="pt").to(model.device)
34
- generated_ids = model.generate(**model_inputs, max_new_tokens=128, do_sample=False, eos_token_id=processor.tokenizer.eos_token_id, pad_token_id=processor.tokenizer.pad_token_id)
 
 
 
 
 
 
 
 
 
 
 
35
  generated_ids = generated_ids[:, model_inputs['input_ids'].shape[1]:]
36
  response = processor.tokenizer.decode(generated_ids[0], skip_special_tokens=True).strip()
37
  return response
38
 
39
  # --- 3. Logic Chatbot ---
 
40
  def manual_chat_responder(user_question: str, chat_history: list, uploaded_image: Image.Image):
41
  if uploaded_image is None:
42
  gr.Warning("Vui lòng tải ảnh lên trước để đặt câu hỏi về nó.")
@@ -44,12 +56,42 @@ def manual_chat_responder(user_question: str, chat_history: list, uploaded_image
44
  if not user_question or not user_question.strip():
45
  gr.Warning("Vui lòng nhập một câu hỏi.")
46
  return "", chat_history
 
 
47
  chat_history.append({"role": "user", "content": user_question})
 
48
  yield "", chat_history
 
49
  bot_response = process_vqa(uploaded_image, user_question)
50
- chat_history.append({"role": "assistant", "content": bot_response})
 
 
51
  yield "", chat_history
52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  def clear_chat():
54
  return []
55
 
@@ -63,19 +105,6 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="sky"), ti
63
  ["./assets/book_example_2.jpg", "tác giả và tên của cuốn sách là gì?"],
64
  ]
65
 
66
- # SỬA LỖI: Di chuyển hàm xử lý ví dụ vào bên trong khối `with`
67
- # để nó có thể truy cập `example_list` từ phạm vi bên ngoài.
68
- def run_example(evt: SelectData):
69
- # `example_list` giờ đây là biến list chính xác từ phạm vi ngoài
70
- selected_example = example_list[evt.index]
71
- image_path, question = selected_example
72
- gr.Info(f"Đang chạy ví dụ: \"{question}\"")
73
- image = Image.open(image_path).convert("RGB")
74
- chat_history = [{"role": "user", "content": question}]
75
- bot_response = process_vqa(image, question)
76
- chat_history.append({"role": "assistant", "content": bot_response})
77
- return image, question, chat_history
78
-
79
  with gr.Row(equal_height=False):
80
  with gr.Column(scale=1, min_width=350):
81
  gr.Markdown("### Bảng điều khiển")
@@ -84,20 +113,14 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="sky"), ti
84
  gr.Markdown("### Ví dụ (Nhấn để chạy)")
85
  example_dataset = gr.Dataset(components=[gr.Image(visible=False), gr.Textbox(visible=False)], samples=example_list, label="Ví dụ", type="index")
86
  with gr.Column(scale=2):
87
- # Sửa cảnh báo: Xóa `bubble_full_width` đã lỗi thời
88
  chatbot = gr.Chatbot(label="Cuộc trò chuyện", height=600, avatar_images=(None, "https://huggingface.co/datasets/huggingface/brand-assets/resolve/main/hf-logo.png"), type="messages", value=[])
89
  question_input = gr.Textbox(label="Hoặc nhập câu hỏi về ảnh đã tải lên", placeholder="Nhập câu hỏi và nhấn Enter...", container=False, scale=7)
90
 
91
  # --- 5. Xử lý Sự kiện ---
92
  question_input.submit(fn=manual_chat_responder, inputs=[question_input, chatbot, image_input], outputs=[question_input, chatbot])
93
 
94
- # SỬA LỖI: Loại bỏ `inputs` để hàm chỉ nhận `evt`
95
- example_dataset.select(
96
- fn=run_example,
97
- inputs=None,
98
- outputs=[image_input, question_input, chatbot],
99
- show_progress="full"
100
- )
101
 
102
  image_input.upload(fn=clear_chat, inputs=None, outputs=[chatbot])
103
  image_input.clear(fn=clear_chat, inputs=None, outputs=[chatbot])
 
1
+ # app.py (Phiên bản cuối cùng: Sửa lỗi cảnh báo thêm tin nhắn "Thinking...")
2
 
3
  import gradio as gr
4
  import torch
 
12
  warnings.filterwarnings("ignore", category=UserWarning, message="Overriding torch_dtype=None")
13
 
14
  # --- 1. Tải Model và Processor ---
15
+ MODEL_ID = "sunbv56/qwen2.5-vl-vqa-vibook-lora-merged"
16
  print(f"🚀 Đang tải model '{MODEL_ID}' và processor...")
17
  try:
18
  dtype = torch.bfloat16 if torch.cuda.is_available() and torch.cuda.is_bf16_supported() else torch.float16
 
31
  messages = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": question}]}]
32
  prompt_text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
33
  model_inputs = processor(text=[prompt_text], images=[image], return_tensors="pt").to(model.device)
34
+
35
+ # SỬA LỖI 1: Ghi đè `temperature` để tắt cảnh báo.
36
+ # Đặt là 1.0 (trung tính) vì do_sample=False nên nó sẽ không được sử dụng.
37
+ generated_ids = model.generate(
38
+ **model_inputs,
39
+ max_new_tokens=1024,
40
+ do_sample=False,
41
+ temperature=1.0,
42
+ eos_token_id=processor.tokenizer.eos_token_id,
43
+ pad_token_id=processor.tokenizer.pad_token_id
44
+ )
45
+
46
  generated_ids = generated_ids[:, model_inputs['input_ids'].shape[1]:]
47
  response = processor.tokenizer.decode(generated_ids[0], skip_special_tokens=True).strip()
48
  return response
49
 
50
  # --- 3. Logic Chatbot ---
51
+ # Hàm dành cho việc người dùng tự nhập câu hỏi
52
  def manual_chat_responder(user_question: str, chat_history: list, uploaded_image: Image.Image):
53
  if uploaded_image is None:
54
  gr.Warning("Vui lòng tải ảnh lên trước để đặt câu hỏi về nó.")
 
56
  if not user_question or not user_question.strip():
57
  gr.Warning("Vui lòng nhập một câu hỏi.")
58
  return "", chat_history
59
+
60
+ # THÊM TÍNH NĂNG 2: Hiển thị tin nhắn chờ
61
  chat_history.append({"role": "user", "content": user_question})
62
+ chat_history.append({"role": "assistant", "content": "🤔 Thinking..."})
63
  yield "", chat_history
64
+
65
  bot_response = process_vqa(uploaded_image, user_question)
66
+
67
+ # THÊM TÍNH NĂNG 2: Cập nhật tin nhắn chờ bằng câu trả lời thật
68
+ chat_history[-1]["content"] = bot_response
69
  yield "", chat_history
70
 
71
+ # Hàm dành riêng cho việc xử lý khi nhấn vào ví dụ
72
+ def run_example(evt: SelectData):
73
+ # Dùng list toàn cục đã được định nghĩa trong khối `with`
74
+ selected_example = example_list[evt.index]
75
+ image_path, question = selected_example
76
+ gr.Info(f"Đang chạy ví dụ: \"{question}\"")
77
+ image = Image.open(image_path).convert("RGB")
78
+
79
+ # THÊM TÍNH NĂNG 2: Hiển thị tin nhắn chờ
80
+ chat_history = [
81
+ {"role": "user", "content": question},
82
+ {"role": "assistant", "content": "🤔 Thinking..."}
83
+ ]
84
+ # `yield` lần đầu để cập nhật UI ngay lập tức
85
+ yield image, question, chat_history
86
+
87
+ # Chạy xử lý và lấy câu trả lời thật
88
+ bot_response = process_vqa(image, question)
89
+
90
+ # THÊM TÍNH NĂNG 2: Cập nhật tin nhắn chờ bằng câu trả lời thật
91
+ chat_history[-1]["content"] = bot_response
92
+ # `yield` lần cuối để hiển thị kết quả cuối cùng
93
+ yield image, question, chat_history
94
+
95
  def clear_chat():
96
  return []
97
 
 
105
  ["./assets/book_example_2.jpg", "tác giả và tên của cuốn sách là gì?"],
106
  ]
107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  with gr.Row(equal_height=False):
109
  with gr.Column(scale=1, min_width=350):
110
  gr.Markdown("### Bảng điều khiển")
 
113
  gr.Markdown("### Ví dụ (Nhấn để chạy)")
114
  example_dataset = gr.Dataset(components=[gr.Image(visible=False), gr.Textbox(visible=False)], samples=example_list, label="Ví dụ", type="index")
115
  with gr.Column(scale=2):
 
116
  chatbot = gr.Chatbot(label="Cuộc trò chuyện", height=600, avatar_images=(None, "https://huggingface.co/datasets/huggingface/brand-assets/resolve/main/hf-logo.png"), type="messages", value=[])
117
  question_input = gr.Textbox(label="Hoặc nhập câu hỏi về ảnh đã tải lên", placeholder="Nhập câu hỏi và nhấn Enter...", container=False, scale=7)
118
 
119
  # --- 5. Xử lý Sự kiện ---
120
  question_input.submit(fn=manual_chat_responder, inputs=[question_input, chatbot, image_input], outputs=[question_input, chatbot])
121
 
122
+ # THÊM TÍNH NĂNG 2: Hàm `run_example` giờ một generator, Gradio sẽ tự động xử lý các `yield`
123
+ example_dataset.select(fn=run_example, inputs=None, outputs=[image_input, question_input, chatbot], show_progress="full")
 
 
 
 
 
124
 
125
  image_input.upload(fn=clear_chat, inputs=None, outputs=[chatbot])
126
  image_input.clear(fn=clear_chat, inputs=None, outputs=[chatbot])