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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
# encoding: utf-8
|
3 |
+
|
4 |
+
import timm
|
5 |
+
import gradio as gr
|
6 |
+
from PIL import Image
|
7 |
+
import traceback
|
8 |
+
import re
|
9 |
+
import torch
|
10 |
+
import argparse
|
11 |
+
from transformers import AutoModel, AutoTokenizer
|
12 |
+
|
13 |
+
# Suppress FutureWarnings
|
14 |
+
import warnings
|
15 |
+
warnings.filterwarnings("ignore", category=FutureWarning)
|
16 |
+
|
17 |
+
# README, How to run demo on different devices
|
18 |
+
# For CPU usage, you can simply run:
|
19 |
+
# python app.py
|
20 |
+
|
21 |
+
# Argparser
|
22 |
+
parser = argparse.ArgumentParser(description='Demo Application Configuration')
|
23 |
+
parser.add_argument('--device', type=str, default='cpu', choices=['cpu'], help='Device to run the model on. Currently only "cpu" is supported.')
|
24 |
+
parser.add_argument('--dtype', type=str, default='fp32', choices=['fp32'], help='Data type for model computations. "fp32" is standard for CPU.')
|
25 |
+
args = parser.parse_args()
|
26 |
+
|
27 |
+
device = args.device
|
28 |
+
|
29 |
+
# Since we're using CPU, set dtype to float32
|
30 |
+
if args.dtype == 'fp32':
|
31 |
+
dtype = torch.float32
|
32 |
+
else:
|
33 |
+
dtype = torch.float32 # Fallback to float32 if an unsupported dtype is somehow passed
|
34 |
+
|
35 |
+
# Load model
|
36 |
+
model_path = 'openbmb/MiniCPM-V-2'
|
37 |
+
|
38 |
+
try:
|
39 |
+
print("Loading model...")
|
40 |
+
model = AutoModel.from_pretrained(model_path, trust_remote_code=True).to(device=device, dtype=dtype)
|
41 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
|
42 |
+
print("Model loaded successfully.")
|
43 |
+
except Exception as e:
|
44 |
+
print(f"Error loading model: {e}")
|
45 |
+
traceback.print_exc()
|
46 |
+
exit(1)
|
47 |
+
|
48 |
+
model.eval()
|
49 |
+
|
50 |
+
ERROR_MSG = "Error, please retry"
|
51 |
+
model_name = 'MiniCPM-V 2.0'
|
52 |
+
|
53 |
+
# Define UI components parameters
|
54 |
+
form_radio = {
|
55 |
+
'choices': ['Beam Search', 'Sampling'],
|
56 |
+
'value': 'Sampling',
|
57 |
+
'interactive': True,
|
58 |
+
'label': 'Decode Type'
|
59 |
+
}
|
60 |
+
|
61 |
+
# Beam Search Parameters
|
62 |
+
num_beams_slider = {
|
63 |
+
'minimum': 1, # Changed minimum from 0 to 1 as 0 beams doesn't make sense
|
64 |
+
'maximum': 10, # Increased maximum for more flexibility
|
65 |
+
'value': 3,
|
66 |
+
'step': 1,
|
67 |
+
'interactive': True,
|
68 |
+
'label': 'Num Beams'
|
69 |
+
}
|
70 |
+
repetition_penalty_slider = {
|
71 |
+
'minimum': 0.5, # Changed minimum to a reasonable value
|
72 |
+
'maximum': 3.0,
|
73 |
+
'value': 1.2,
|
74 |
+
'step': 0.01,
|
75 |
+
'interactive': True,
|
76 |
+
'label': 'Repetition Penalty'
|
77 |
+
}
|
78 |
+
|
79 |
+
# Sampling Parameters
|
80 |
+
repetition_penalty_slider2 = {
|
81 |
+
'minimum': 0.5,
|
82 |
+
'maximum': 3.0,
|
83 |
+
'value': 1.05,
|
84 |
+
'step': 0.01,
|
85 |
+
'interactive': True,
|
86 |
+
'label': 'Repetition Penalty'
|
87 |
+
}
|
88 |
+
max_new_tokens_slider = {
|
89 |
+
'minimum': 1,
|
90 |
+
'maximum': 4096,
|
91 |
+
'value': 1024,
|
92 |
+
'step': 1,
|
93 |
+
'interactive': True,
|
94 |
+
'label': 'Max New Tokens'
|
95 |
+
}
|
96 |
+
|
97 |
+
top_p_slider = {
|
98 |
+
'minimum': 0.1, # Avoid extreme low values
|
99 |
+
'maximum': 1.0,
|
100 |
+
'value': 0.8,
|
101 |
+
'step': 0.05,
|
102 |
+
'interactive': True,
|
103 |
+
'label': 'Top P'
|
104 |
+
}
|
105 |
+
top_k_slider = {
|
106 |
+
'minimum': 10, # Avoid extreme low values
|
107 |
+
'maximum': 200,
|
108 |
+
'value': 100,
|
109 |
+
'step': 1,
|
110 |
+
'interactive': True,
|
111 |
+
'label': 'Top K'
|
112 |
+
}
|
113 |
+
temperature_slider = {
|
114 |
+
'minimum': 0.1, # Avoid extreme low values
|
115 |
+
'maximum': 2.0,
|
116 |
+
'value': 0.7,
|
117 |
+
'step': 0.05,
|
118 |
+
'interactive': True,
|
119 |
+
'label': 'Temperature'
|
120 |
+
}
|
121 |
+
|
122 |
+
def create_component(params, comp='Slider'):
|
123 |
+
"""
|
124 |
+
Utility function to create Gradio UI components based on parameters.
|
125 |
+
"""
|
126 |
+
if comp == 'Slider':
|
127 |
+
return gr.Slider(
|
128 |
+
minimum=params['minimum'],
|
129 |
+
maximum=params['maximum'],
|
130 |
+
value=params['value'],
|
131 |
+
step=params['step'],
|
132 |
+
interactive=params['interactive'],
|
133 |
+
label=params['label']
|
134 |
+
)
|
135 |
+
elif comp == 'Radio':
|
136 |
+
return gr.Radio(
|
137 |
+
choices=params['choices'],
|
138 |
+
value=params['value'],
|
139 |
+
interactive=params['interactive'],
|
140 |
+
label=params['label']
|
141 |
+
)
|
142 |
+
elif comp == 'Button':
|
143 |
+
return gr.Button(
|
144 |
+
value=params['value'],
|
145 |
+
interactive=True
|
146 |
+
)
|
147 |
+
|
148 |
+
def chat(img, msgs, ctx, params=None, vision_hidden_states=None):
|
149 |
+
"""
|
150 |
+
Function to handle the chat interaction.
|
151 |
+
"""
|
152 |
+
print("Entering chat function...")
|
153 |
+
default_params = {"num_beams": 3, "repetition_penalty": 1.2, "max_new_tokens": 1024}
|
154 |
+
if params is None:
|
155 |
+
params = default_params
|
156 |
+
if img is None:
|
157 |
+
return -1, "Error, invalid image, please upload a new image", None, None
|
158 |
+
try:
|
159 |
+
image = img.convert('RGB')
|
160 |
+
answer, context, _ = model.chat(
|
161 |
+
image=image,
|
162 |
+
msgs=msgs,
|
163 |
+
context=None,
|
164 |
+
tokenizer=tokenizer,
|
165 |
+
**params
|
166 |
+
)
|
167 |
+
# Clean up the answer text
|
168 |
+
res = re.sub(r'(<box>.*</box>)', '', answer)
|
169 |
+
res = res.replace('<ref>', '').replace('</ref>', '').replace('<box>', '').replace('</box>', '')
|
170 |
+
answer = res
|
171 |
+
return -1, answer, None, None
|
172 |
+
except Exception as err:
|
173 |
+
print(err)
|
174 |
+
traceback.print_exc()
|
175 |
+
return -1, ERROR_MSG, None, None
|
176 |
+
|
177 |
+
def upload_img(image, _chatbot, _app_session):
|
178 |
+
"""
|
179 |
+
Function to handle image uploads.
|
180 |
+
"""
|
181 |
+
print("Uploading image...")
|
182 |
+
try:
|
183 |
+
image = Image.fromarray(image)
|
184 |
+
_app_session['sts'] = None
|
185 |
+
_app_session['ctx'] = []
|
186 |
+
_app_session['img'] = image
|
187 |
+
_chatbot.append(('', 'Image uploaded successfully, I am ready to take up your queries'))
|
188 |
+
print("Image uploaded successfully.")
|
189 |
+
return _chatbot, _app_session
|
190 |
+
except Exception as e:
|
191 |
+
print(f"Error uploading image: {e}")
|
192 |
+
traceback.print_exc()
|
193 |
+
return _chatbot, _app_session
|
194 |
+
|
195 |
+
def respond(_question, _chat_bot, _app_cfg, params_form, num_beams, repetition_penalty, repetition_penalty_2, top_p, top_k, temperature):
|
196 |
+
"""
|
197 |
+
Function to handle user input and generate responses.
|
198 |
+
"""
|
199 |
+
print("Respond function called.")
|
200 |
+
if _app_cfg.get('ctx', None) is None:
|
201 |
+
_chat_bot.append((_question, 'Please upload an image to detect'))
|
202 |
+
return '', _chat_bot, _app_cfg
|
203 |
+
|
204 |
+
_context = _app_cfg['ctx'].copy()
|
205 |
+
if _context:
|
206 |
+
_context.append({"role": "user", "content": _question})
|
207 |
+
else:
|
208 |
+
_context = [{"role": "user", "content": _question}]
|
209 |
+
print('<User>:', _question)
|
210 |
+
|
211 |
+
if params_form == 'Beam Search':
|
212 |
+
params = {
|
213 |
+
'sampling': False,
|
214 |
+
'num_beams': num_beams,
|
215 |
+
'repetition_penalty': repetition_penalty,
|
216 |
+
"max_new_tokens": 896
|
217 |
+
}
|
218 |
+
else:
|
219 |
+
params = {
|
220 |
+
'sampling': True,
|
221 |
+
'top_p': top_p,
|
222 |
+
'top_k': top_k,
|
223 |
+
'temperature': temperature,
|
224 |
+
'repetition_penalty': repetition_penalty_2,
|
225 |
+
"max_new_tokens": 896
|
226 |
+
}
|
227 |
+
code, _answer, _, sts = chat(_app_cfg['img'], _context, None, params)
|
228 |
+
print('<Assistant>:', _answer)
|
229 |
+
|
230 |
+
_context.append({"role": "assistant", "content": _answer})
|
231 |
+
_chat_bot.append((_question, _answer))
|
232 |
+
if code == 0:
|
233 |
+
_app_cfg['ctx'] = _context
|
234 |
+
_app_cfg['sts'] = sts
|
235 |
+
return '', _chat_bot, _app_cfg
|
236 |
+
|
237 |
+
def regenerate_button_clicked(_question, _chat_bot, _app_cfg, params_form, num_beams, repetition_penalty, repetition_penalty_2, top_p, top_k, temperature):
|
238 |
+
"""
|
239 |
+
Function to handle the regeneration of the last assistant response.
|
240 |
+
"""
|
241 |
+
print("Regenerate button clicked.")
|
242 |
+
if len(_chat_bot) <= 1:
|
243 |
+
_chat_bot.append(('Regenerate', 'No question for regeneration.'))
|
244 |
+
return '', _chat_bot, _app_cfg
|
245 |
+
elif _chat_bot[-1][0] == 'Regenerate':
|
246 |
+
return '', _chat_bot, _app_cfg
|
247 |
+
else:
|
248 |
+
_question = _chat_bot[-1][0]
|
249 |
+
_chat_bot = _chat_bot[:-1]
|
250 |
+
_app_cfg['ctx'] = _app_cfg['ctx'][:-2]
|
251 |
+
return respond(_question, _chat_bot, _app_cfg, params_form, num_beams, repetition_penalty, repetition_penalty_2, top_p, top_k, temperature)
|
252 |
+
|
253 |
+
# Building the Gradio Interface
|
254 |
+
with gr.Blocks() as demo:
|
255 |
+
with gr.Row():
|
256 |
+
with gr.Column(scale=1, min_width=300):
|
257 |
+
# Decode Type Selection
|
258 |
+
params_form = create_component(form_radio, comp='Radio')
|
259 |
+
|
260 |
+
# Beam Search Settings
|
261 |
+
with gr.Accordion("Beam Search"):
|
262 |
+
num_beams = create_component(num_beams_slider)
|
263 |
+
repetition_penalty = create_component(repetition_penalty_slider)
|
264 |
+
|
265 |
+
# Sampling Settings
|
266 |
+
with gr.Accordion("Sampling"):
|
267 |
+
top_p = create_component(top_p_slider)
|
268 |
+
top_k = create_component(top_k_slider)
|
269 |
+
temperature = create_component(temperature_slider)
|
270 |
+
repetition_penalty_2 = create_component(repetition_penalty_slider2)
|
271 |
+
|
272 |
+
# Regenerate Button
|
273 |
+
regenerate = create_component({'value': 'Regenerate'}, comp='Button')
|
274 |
+
|
275 |
+
with gr.Column(scale=3, min_width=500):
|
276 |
+
# Application State
|
277 |
+
app_session = gr.State({'sts': None, 'ctx': None, 'img': None})
|
278 |
+
|
279 |
+
# Image Upload Component
|
280 |
+
bt_pic = gr.Image(label="Upload an image to start")
|
281 |
+
|
282 |
+
# Chatbot Display
|
283 |
+
chat_bot = gr.Chatbot(label="Ask anything about the image")
|
284 |
+
|
285 |
+
# Text Input for User Messages
|
286 |
+
txt_message = gr.Textbox(label="Input text")
|
287 |
+
|
288 |
+
# Define Actions
|
289 |
+
regenerate.click(
|
290 |
+
regenerate_button_clicked,
|
291 |
+
[
|
292 |
+
txt_message,
|
293 |
+
chat_bot,
|
294 |
+
app_session,
|
295 |
+
params_form,
|
296 |
+
num_beams,
|
297 |
+
repetition_penalty,
|
298 |
+
repetition_penalty_2,
|
299 |
+
top_p,
|
300 |
+
top_k,
|
301 |
+
temperature
|
302 |
+
],
|
303 |
+
[txt_message, chat_bot, app_session]
|
304 |
+
)
|
305 |
+
|
306 |
+
txt_message.submit(
|
307 |
+
respond,
|
308 |
+
[
|
309 |
+
txt_message,
|
310 |
+
chat_bot,
|
311 |
+
app_session,
|
312 |
+
params_form,
|
313 |
+
num_beams,
|
314 |
+
repetition_penalty,
|
315 |
+
repetition_penalty_2,
|
316 |
+
top_p,
|
317 |
+
top_k,
|
318 |
+
temperature
|
319 |
+
],
|
320 |
+
[txt_message, chat_bot, app_session]
|
321 |
+
)
|
322 |
+
|
323 |
+
bt_pic.upload(
|
324 |
+
lambda: None,
|
325 |
+
None,
|
326 |
+
chat_bot,
|
327 |
+
queue=False
|
328 |
+
).then(
|
329 |
+
upload_img,
|
330 |
+
inputs=[bt_pic, chat_bot, app_session],
|
331 |
+
outputs=[chat_bot, app_session]
|
332 |
+
)
|
333 |
+
|
334 |
+
# Launch the Gradio App with share=True for testing
|
335 |
+
demo.launch(share=True, debug=True)
|