Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,302 +1,49 @@
|
|
1 |
-
import argparse
|
2 |
-
import datetime
|
3 |
-
import json
|
4 |
-
import os
|
5 |
-
import time
|
6 |
-
|
7 |
import gradio as gr
|
8 |
import requests
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
from
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
"""
|
40 |
-
|
41 |
-
|
42 |
-
def load_demo(url_params, request: gr.Request):
|
43 |
-
logger.info(f"load_demo. ip: {request.client.host}. params: {url_params}")
|
44 |
-
state = default_conversation.copy()
|
45 |
-
return state
|
46 |
-
|
47 |
-
|
48 |
-
def vote_last_response(state, vote_type, request: gr.Request):
|
49 |
-
with open(get_conv_log_filename(), "a") as fout:
|
50 |
-
data = {
|
51 |
-
"tstamp": round(time.time(), 4),
|
52 |
-
"type": vote_type,
|
53 |
-
"state": state.dict(),
|
54 |
-
"ip": request.client.host,
|
55 |
-
}
|
56 |
-
fout.write(json.dumps(data) + "\n")
|
57 |
-
|
58 |
-
|
59 |
-
def upvote_last_response(state, request: gr.Request):
|
60 |
-
logger.info(f"upvote. ip: {request.client.host}")
|
61 |
-
vote_last_response(state, "upvote", request)
|
62 |
-
return ("",) + (disable_btn,) * 3
|
63 |
-
|
64 |
-
|
65 |
-
def downvote_last_response(state, request: gr.Request):
|
66 |
-
logger.info(f"downvote. ip: {request.client.host}")
|
67 |
-
vote_last_response(state, "downvote", request)
|
68 |
-
return ("",) + (disable_btn,) * 3
|
69 |
-
|
70 |
-
|
71 |
-
def flag_last_response(state, request: gr.Request):
|
72 |
-
logger.info(f"flag. ip: {request.client.host}")
|
73 |
-
vote_last_response(state, "flag", request)
|
74 |
-
return ("",) + (disable_btn,) * 3
|
75 |
-
|
76 |
-
|
77 |
-
def regenerate(state, image_process_mode, request: gr.Request):
|
78 |
-
logger.info(f"regenerate. ip: {request.client.host}")
|
79 |
-
state.messages[-1][-1] = None
|
80 |
-
prev_human_msg = state.messages[-2]
|
81 |
-
if type(prev_human_msg[1]) in (tuple, list):
|
82 |
-
prev_human_msg[1] = (*prev_human_msg[1][:2], image_process_mode)
|
83 |
-
state.skip_next = False
|
84 |
-
return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5
|
85 |
-
|
86 |
-
|
87 |
-
def clear_history(request: gr.Request):
|
88 |
-
logger.info(f"clear_history. ip: {request.client.host}")
|
89 |
-
state = default_conversation.copy()
|
90 |
-
return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5
|
91 |
-
|
92 |
-
|
93 |
-
def add_text(state, text, image, image_process_mode, request: gr.Request):
|
94 |
-
logger.info(f"add_text. ip: {request.client.host}. len: {len(text)}")
|
95 |
-
if len(text) <= 0 and image is None:
|
96 |
-
state.skip_next = True
|
97 |
-
return (state, state.to_gradio_chatbot(), "", None) + (no_change_btn,) * 5
|
98 |
-
if args.moderate:
|
99 |
-
flagged = violates_moderation(text)
|
100 |
-
if flagged:
|
101 |
-
state.skip_next = True
|
102 |
-
return (state, state.to_gradio_chatbot(), moderation_msg, None) + (
|
103 |
-
no_change_btn,) * 5
|
104 |
-
|
105 |
-
text = text[:3584] # Hard cut-off
|
106 |
-
if image is not None:
|
107 |
-
text = text[:3500] # Hard cut-off for images
|
108 |
-
if '<|image|>' not in text:
|
109 |
-
text = '<|image|>' + text
|
110 |
-
text = (text, image, image_process_mode)
|
111 |
-
if len(state.get_images(return_pil=True)) > 0:
|
112 |
-
state = default_conversation.copy()
|
113 |
-
state.append_message(state.roles[0], text)
|
114 |
-
state.append_message(state.roles[1], None)
|
115 |
-
state.skip_next = False
|
116 |
-
print(text)
|
117 |
-
return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5
|
118 |
-
|
119 |
-
|
120 |
-
def http_bot(state, temperature, top_p, max_new_tokens, request: gr.Request):
|
121 |
-
logger.info(f"http_bot. ip: {request.client.host}")
|
122 |
-
start_tstamp = time.time()
|
123 |
-
if state.skip_next:
|
124 |
-
# This generate call is skipped due to invalid inputs
|
125 |
-
yield (state, state.to_gradio_chatbot()) + (no_change_btn,) * 5
|
126 |
-
return
|
127 |
-
|
128 |
-
if len(state.messages) == state.offset + 2:
|
129 |
-
# First round of conversation
|
130 |
-
template_name = "mplug_owl2"
|
131 |
-
new_state = conv_templates[template_name].copy()
|
132 |
-
new_state.append_message(new_state.roles[0], state.messages[-2][1])
|
133 |
-
new_state.append_message(new_state.roles[1], None)
|
134 |
-
state = new_state
|
135 |
-
|
136 |
-
# Construct prompt
|
137 |
-
prompt = state.get_prompt()
|
138 |
-
|
139 |
-
all_images = state.get_images(return_pil=True)
|
140 |
-
all_image_hash = [hashlib.md5(image.tobytes()).hexdigest() for image in all_images]
|
141 |
-
for image, hash in zip(all_images, all_image_hash):
|
142 |
-
t = datetime.datetime.now()
|
143 |
-
filename = os.path.join(LOGDIR, "serve_images", f"{t.year}-{t.month:02d}-{t.day:02d}", f"{hash}.jpg")
|
144 |
-
if not os.path.isfile(filename):
|
145 |
-
os.makedirs(os.path.dirname(filename), exist_ok=True)
|
146 |
-
image.save(filename)
|
147 |
-
|
148 |
-
# Make requests
|
149 |
-
pload = {
|
150 |
-
"prompt": prompt,
|
151 |
-
"temperature": float(temperature),
|
152 |
-
"top_p": float(top_p),
|
153 |
-
"max_new_tokens": min(int(max_new_tokens), 2048),
|
154 |
-
"stop": state.sep if state.sep_style in [SeparatorStyle.SINGLE, SeparatorStyle.MPT] else state.sep2,
|
155 |
-
"images": f'List of {len(state.get_images())} images: {all_image_hash}',
|
156 |
-
}
|
157 |
-
logger.info(f"==== request ====\n{pload}")
|
158 |
-
|
159 |
-
pload['images'] = state.get_images()
|
160 |
-
|
161 |
-
state.messages[-1][-1] = "▌"
|
162 |
-
yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
|
163 |
-
|
164 |
-
try:
|
165 |
-
# Stream output
|
166 |
-
# response = requests.post(worker_addr + "/worker_generate_stream",
|
167 |
-
# headers=headers, json=pload, stream=True, timeout=10)
|
168 |
-
# for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
|
169 |
-
response = model.generate_stream_gate(pload)
|
170 |
-
for chunk in response:
|
171 |
-
if chunk:
|
172 |
-
data = json.loads(chunk.decode())
|
173 |
-
if data["error_code"] == 0:
|
174 |
-
output = data["text"][len(prompt):].strip()
|
175 |
-
state.messages[-1][-1] = output + "▌"
|
176 |
-
yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
|
177 |
-
else:
|
178 |
-
output = data["text"] + f" (error_code: {data['error_code']})"
|
179 |
-
state.messages[-1][-1] = output
|
180 |
-
yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
|
181 |
-
return
|
182 |
-
time.sleep(0.03)
|
183 |
-
except requests.exceptions.RequestException as e:
|
184 |
-
state.messages[-1][-1] = server_error_msg
|
185 |
-
yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
|
186 |
-
return
|
187 |
-
|
188 |
-
state.messages[-1][-1] = state.messages[-1][-1][:-1]
|
189 |
-
yield (state, state.to_gradio_chatbot()) + (enable_btn,) * 5
|
190 |
-
|
191 |
-
finish_tstamp = time.time()
|
192 |
-
logger.info(f"{output}")
|
193 |
-
|
194 |
-
with open(get_conv_log_filename(), "a") as fout:
|
195 |
-
data = {
|
196 |
-
"tstamp": round(finish_tstamp, 4),
|
197 |
-
"type": "chat",
|
198 |
-
"start": round(start_tstamp, 4),
|
199 |
-
"finish": round(start_tstamp, 4),
|
200 |
-
"state": state.dict(),
|
201 |
-
"images": all_image_hash,
|
202 |
-
"ip": request.client.host,
|
203 |
-
}
|
204 |
-
fout.write(json.dumps(data) + "\n")
|
205 |
-
|
206 |
-
def http_bot_modified(state, request: gr.Request):
|
207 |
-
logger.info(f"http_bot. ip: {request.client.host}")
|
208 |
-
start_tstamp = time.time()
|
209 |
-
if state.skip_next:
|
210 |
-
# This generate call is skipped due to invalid inputs
|
211 |
-
yield (state, state.to_gradio_chatbot()) + (no_change_btn,) * 5
|
212 |
-
return
|
213 |
|
214 |
-
print(
|
215 |
-
state.messages[-2][1] = ('<|image|>Rate the quality of the image.',) + state.messages[-2][1][1:]
|
216 |
-
print(state.messages[-2][1])
|
217 |
|
218 |
-
|
219 |
-
# First round of conversation
|
220 |
-
template_name = "mplug_owl2"
|
221 |
-
new_state = conv_templates[template_name].copy()
|
222 |
-
new_state.append_message(new_state.roles[0], state.messages[-2][1])
|
223 |
-
new_state.append_message(new_state.roles[1], None)
|
224 |
-
state = new_state
|
225 |
-
|
226 |
-
# Construct prompt
|
227 |
-
prompt = state.get_prompt()
|
228 |
-
|
229 |
-
all_images = state.get_images(return_pil=True)
|
230 |
-
all_image_hash = [hashlib.md5(image.tobytes()).hexdigest() for image in all_images]
|
231 |
-
for image, hash in zip(all_images, all_image_hash):
|
232 |
-
t = datetime.datetime.now()
|
233 |
-
filename = os.path.join(LOGDIR, "serve_images", f"{t.year}-{t.month:02d}-{t.day:02d}", f"{hash}.jpg")
|
234 |
-
if not os.path.isfile(filename):
|
235 |
-
os.makedirs(os.path.dirname(filename), exist_ok=True)
|
236 |
-
image.save(filename)
|
237 |
-
|
238 |
-
# Make requests
|
239 |
-
pload = {
|
240 |
-
"prompt": prompt,
|
241 |
-
"images": f'List of {len(state.get_images())} images: {all_image_hash}',
|
242 |
-
}
|
243 |
-
logger.info(f"==== request ====\n{pload}")
|
244 |
|
245 |
-
pload['images'] = state.get_images()
|
246 |
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
try:
|
251 |
-
# Stream output
|
252 |
-
# response = requests.post(worker_addr + "/worker_generate_stream",
|
253 |
-
# headers=headers, json=pload, stream=True, timeout=10)
|
254 |
-
# for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
|
255 |
-
response = model.predict_stream_gate(pload)
|
256 |
-
for chunk in response:
|
257 |
-
if chunk:
|
258 |
-
data = json.loads(chunk.decode())
|
259 |
-
if data["error_code"] == 0:
|
260 |
-
output = data["text"][len(prompt):].strip()
|
261 |
-
state.messages[-1][-1] = output + "▌"
|
262 |
-
yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
|
263 |
-
else:
|
264 |
-
output = data["text"] + f" (error_code: {data['error_code']})"
|
265 |
-
state.messages[-1][-1] = output
|
266 |
-
yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
|
267 |
-
return
|
268 |
-
time.sleep(0.03)
|
269 |
-
except requests.exceptions.RequestException as e:
|
270 |
-
state.messages[-1][-1] = server_error_msg
|
271 |
-
yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
|
272 |
-
return
|
273 |
-
|
274 |
-
state.messages[-1][-1] = state.messages[-1][-1][:-1]
|
275 |
-
yield (state, state.to_gradio_chatbot()) + (enable_btn,) * 5
|
276 |
-
|
277 |
-
finish_tstamp = time.time()
|
278 |
-
logger.info(f"{output}")
|
279 |
-
|
280 |
-
with open(get_conv_log_filename(), "a") as fout:
|
281 |
-
data = {
|
282 |
-
"tstamp": round(finish_tstamp, 4),
|
283 |
-
"type": "chat",
|
284 |
-
"start": round(start_tstamp, 4),
|
285 |
-
"finish": round(start_tstamp, 4),
|
286 |
-
"state": state.dict(),
|
287 |
-
"images": all_image_hash,
|
288 |
-
"ip": request.client.host,
|
289 |
-
}
|
290 |
-
fout.write(json.dumps(data) + "\n")
|
291 |
-
|
292 |
-
|
293 |
-
title_markdown = ("""
|
294 |
<h1 align="center"><a href="https://github.com/Q-Future/Q-Instruct"><img src="https://github.com/Q-Future/Q-Instruct/blob/main/q_instruct_logo.png?raw=true", alt="Q-Instruct (mPLUG-Owl-2)" border="0" style="margin: 0 auto; height: 85px;" /></a> </h1>
|
295 |
-
|
296 |
<h2 align="center">Q-Instruct: Improving Low-level Visual Abilities for Multi-modality Foundation Models</h2>
|
297 |
-
|
298 |
-
<h5 align="center"> If you like our project, please give us a star ✨ on [Github](https://github.com/Q-Future/Q-Instruct) for latest update. </h2>
|
299 |
-
|
300 |
<div align="center">
|
301 |
<div style="display:flex; gap: 0.25rem;" align="center">
|
302 |
<a href='https://github.com/Q-Future/Q-Instruct'><img src='https://img.shields.io/badge/Github-Code-blue'></a>
|
@@ -304,200 +51,10 @@ title_markdown = ("""
|
|
304 |
<a href='https://github.com/Q-Future/Q-Instruct/stargazers'><img src='https://img.shields.io/github/stars/Q-Future/Q-Instruct.svg?style=social'></a>
|
305 |
</div>
|
306 |
</div>
|
307 |
-
|
308 |
-
### Special Usage: *Rate!*
|
309 |
-
To get an image quality score, just upload a new image and click the **Rate!** button. This will redirect to a special method that return a quality score in [0,1].
|
310 |
-
Always make sure that there is some text in the textbox before you click the **Rate!** button.
|
311 |
-
|
312 |
-
""")
|
313 |
-
|
314 |
-
|
315 |
-
tos_markdown = ("""
|
316 |
-
|
317 |
-
### Terms of use
|
318 |
-
By using this service, users are required to agree to the following terms:
|
319 |
-
The service is a research preview intended for non-commercial use only. It only provides limited safety measures and may generate offensive content. It must not be used for any illegal, harmful, violent, racist, or sexual purposes. The service may collect user dialogue data for future research.
|
320 |
-
Please click the "Flag" button if you get any inappropriate answer! We will collect those to keep improving our moderator.
|
321 |
-
For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality.
|
322 |
""")
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
|
327 |
-
|
328 |
-
|
329 |
-
|
330 |
-
block_css = """
|
331 |
-
|
332 |
-
#buttons button {
|
333 |
-
min-width: min(120px,100%);
|
334 |
-
}
|
335 |
-
|
336 |
-
"""
|
337 |
-
|
338 |
-
def build_demo(embed_mode):
|
339 |
-
textbox = gr.Textbox(show_label=False, value="Rate the quality of the image.", placeholder="Enter text and press ENTER", container=False)
|
340 |
-
with gr.Blocks(title="Q-Instruct-on-mPLUG-Owl-2", theme=gr.themes.Default(), css=block_css) as demo:
|
341 |
-
state = gr.State()
|
342 |
-
|
343 |
-
if not embed_mode:
|
344 |
-
gr.Markdown(title_markdown)
|
345 |
-
|
346 |
-
with gr.Row():
|
347 |
-
with gr.Column(scale=3):
|
348 |
-
imagebox = gr.Image(type="pil")
|
349 |
-
image_process_mode = gr.Radio(
|
350 |
-
["Crop", "Resize", "Pad", "Default"],
|
351 |
-
value="Default",
|
352 |
-
label="Preprocess for non-square image", visible=False)
|
353 |
-
|
354 |
-
cur_dir = os.path.dirname(os.path.abspath(__file__))
|
355 |
-
gr.Examples(examples=[
|
356 |
-
[f"{cur_dir}/examples/sausage.jpg", "Describe and evaluate the quality of the image."],
|
357 |
-
[f"{cur_dir}/examples/211.jpg", "Is this image clear?"],
|
358 |
-
], inputs=[imagebox, textbox])
|
359 |
-
|
360 |
-
with gr.Accordion("Parameters", open=True) as parameter_row:
|
361 |
-
temperature = gr.Slider(minimum=0.0, maximum=1.0, value=0.2, step=0.1, interactive=True, label="Temperature",)
|
362 |
-
top_p = gr.Slider(minimum=0.0, maximum=1.0, value=0.7, step=0.1, interactive=True, label="Top P",)
|
363 |
-
max_output_tokens = gr.Slider(minimum=0, maximum=1024, value=512, step=64, interactive=True, label="Max output tokens",)
|
364 |
-
|
365 |
-
with gr.Column(scale=8):
|
366 |
-
chatbot = gr.Chatbot(elem_id="Chatbot", label="Q-Instruct-Chatbot", height=750)
|
367 |
-
with gr.Row():
|
368 |
-
with gr.Column(scale=8):
|
369 |
-
textbox.render()
|
370 |
-
with gr.Column(scale=1, min_width=50):
|
371 |
-
submit_btn = gr.Button(value="Send", variant="primary")
|
372 |
-
with gr.Column(scale=1, min_width=50):
|
373 |
-
rate_btn = gr.Button(value="Rate!", variant="primary")
|
374 |
-
with gr.Row(elem_id="buttons") as button_row:
|
375 |
-
upvote_btn = gr.Button(value="👍 Upvote", interactive=False)
|
376 |
-
downvote_btn = gr.Button(value="👎 Downvote", interactive=False)
|
377 |
-
flag_btn = gr.Button(value="⚠️ Flag", interactive=False)
|
378 |
-
#stop_btn = gr.Button(value="⏹️ Stop Generation", interactive=False)
|
379 |
-
regenerate_btn = gr.Button(value="🔄 Regenerate", interactive=False)
|
380 |
-
clear_btn = gr.Button(value="🗑️ Clear", interactive=False)
|
381 |
-
|
382 |
-
if not embed_mode:
|
383 |
-
gr.Markdown(tos_markdown)
|
384 |
-
gr.Markdown(learn_more_markdown)
|
385 |
-
url_params = gr.JSON(visible=False)
|
386 |
-
|
387 |
-
# Register listeners
|
388 |
-
btn_list = [upvote_btn, downvote_btn, flag_btn, regenerate_btn, clear_btn]
|
389 |
-
upvote_btn.click(
|
390 |
-
upvote_last_response,
|
391 |
-
state,
|
392 |
-
[textbox, upvote_btn, downvote_btn, flag_btn],
|
393 |
-
queue=False,
|
394 |
-
concurrency_limit=10,
|
395 |
-
)
|
396 |
-
downvote_btn.click(
|
397 |
-
downvote_last_response,
|
398 |
-
state,
|
399 |
-
[textbox, upvote_btn, downvote_btn, flag_btn],
|
400 |
-
queue=False,
|
401 |
-
concurrency_limit=10,
|
402 |
-
)
|
403 |
-
flag_btn.click(
|
404 |
-
flag_last_response,
|
405 |
-
state,
|
406 |
-
[textbox, upvote_btn, downvote_btn, flag_btn],
|
407 |
-
queue=False,
|
408 |
-
concurrency_limit=10,
|
409 |
-
)
|
410 |
-
|
411 |
-
regenerate_btn.click(
|
412 |
-
regenerate,
|
413 |
-
[state, image_process_mode],
|
414 |
-
[state, chatbot, textbox, imagebox] + btn_list,
|
415 |
-
queue=False,
|
416 |
-
concurrency_limit=10,
|
417 |
-
).then(
|
418 |
-
http_bot,
|
419 |
-
[state, temperature, top_p, max_output_tokens],
|
420 |
-
[state, chatbot] + btn_list
|
421 |
-
)
|
422 |
-
|
423 |
-
clear_btn.click(
|
424 |
-
clear_history,
|
425 |
-
None,
|
426 |
-
[state, chatbot, textbox, imagebox] + btn_list,
|
427 |
-
queue=False,
|
428 |
-
concurrency_limit=10,
|
429 |
-
)
|
430 |
-
|
431 |
-
textbox.submit(
|
432 |
-
add_text,
|
433 |
-
[state, textbox, imagebox, image_process_mode],
|
434 |
-
[state, chatbot, textbox, imagebox] + btn_list,
|
435 |
-
queue=False
|
436 |
-
).then(
|
437 |
-
http_bot,
|
438 |
-
[state, temperature, top_p, max_output_tokens],
|
439 |
-
[state, chatbot] + btn_list
|
440 |
-
)
|
441 |
-
|
442 |
-
submit_btn.click(
|
443 |
-
add_text,
|
444 |
-
[state, textbox, imagebox, image_process_mode],
|
445 |
-
[state, chatbot, textbox, imagebox] + btn_list,
|
446 |
-
queue=False,
|
447 |
-
concurrency_limit=10,
|
448 |
-
).then(
|
449 |
-
http_bot,
|
450 |
-
[state, temperature, top_p, max_output_tokens],
|
451 |
-
[state, chatbot] + btn_list
|
452 |
-
)
|
453 |
-
|
454 |
-
rate_btn.click(
|
455 |
-
add_text,
|
456 |
-
[state, textbox, imagebox, image_process_mode],
|
457 |
-
[state, chatbot, textbox, imagebox] + btn_list,
|
458 |
-
queue=False,
|
459 |
-
concurrency_limit=10,
|
460 |
-
).then(
|
461 |
-
http_bot_modified,
|
462 |
-
[state],
|
463 |
-
[state, chatbot] + btn_list
|
464 |
-
)
|
465 |
-
|
466 |
-
demo.load(
|
467 |
-
load_demo,
|
468 |
-
[url_params],
|
469 |
-
state,
|
470 |
-
js=get_window_url_params,
|
471 |
-
queue=False
|
472 |
-
)
|
473 |
-
|
474 |
-
return demo
|
475 |
-
|
476 |
-
|
477 |
-
if __name__ == "__main__":
|
478 |
-
parser = argparse.ArgumentParser()
|
479 |
-
parser.add_argument("--host", type=str, default="0.0.0.0")
|
480 |
-
parser.add_argument("--port", type=int)
|
481 |
-
parser.add_argument("--concurrency-count", type=int, default=10)
|
482 |
-
parser.add_argument("--model-list-mode", type=str, default="once",
|
483 |
-
choices=["once", "reload"])
|
484 |
-
parser.add_argument("--model-path", type=str, default="teowu/mplug_owl2_7b_448_qinstruct_preview_v0.2")
|
485 |
-
parser.add_argument("--device", type=str, default="cuda")
|
486 |
-
parser.add_argument("--load-8bit", action="store_true")
|
487 |
-
parser.add_argument("--load-4bit", action="store_true")
|
488 |
-
parser.add_argument("--moderate", action="store_true")
|
489 |
-
parser.add_argument("--embed", action="store_true")
|
490 |
-
args = parser.parse_args()
|
491 |
-
logger.info(f"args: {args}")
|
492 |
-
|
493 |
-
model = ModelWorker(args.model_path, None, None, args.load_8bit, args.load_4bit, args.device)
|
494 |
-
|
495 |
-
logger.info(args)
|
496 |
-
demo = build_demo(args.embed)
|
497 |
-
demo.queue(
|
498 |
-
api_open=False
|
499 |
-
).launch(
|
500 |
-
server_name=args.host,
|
501 |
-
server_port=args.port,
|
502 |
-
share=True
|
503 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
import requests
|
3 |
+
from PIL import Image
|
4 |
+
|
5 |
+
import torch
|
6 |
+
from transformers import AutoModelForCausalLM
|
7 |
+
|
8 |
+
model = AutoModelForCausalLM.from_pretrained("q-future/co-instruct-preview",
|
9 |
+
trust_remote_code=True,
|
10 |
+
torch_dtype=torch.float16,
|
11 |
+
device_map={"":"cuda:0"})
|
12 |
+
|
13 |
+
def chat(message, history, image_1, image_2):
|
14 |
+
print(history)
|
15 |
+
if history:
|
16 |
+
if image_1 is not None and image_2 is None:
|
17 |
+
past_message = "USER: The image: <|image|> " + history[0][0] + " ASSISTANT:" + history[0][1]
|
18 |
+
for i in range((len(history) - 1)):
|
19 |
+
past_message += "USER:" +history[i][0] + " ASSISTANT:" + history[i][1] + "</s>"
|
20 |
+
message = past_message + "USER:" + message + " ASSISTANT:"
|
21 |
+
images = [image_1]
|
22 |
+
if image_1 is not None and image_2 is not None:
|
23 |
+
past_message = "USER: The first image: <|image|>\nThe second image: <|image|>" + history[0][0] + " ASSISTANT:" + history[0][1] + "</s>"
|
24 |
+
for i in range((len(history) - 1)):
|
25 |
+
past_message += "USER:" + history[i][0] + " ASSISTANT:" + history[i][1] + "</s>"
|
26 |
+
message = past_message + "USER:" + message + " ASSISTANT:"
|
27 |
+
images = [image_1, image_2]
|
28 |
+
else:
|
29 |
+
if image_1 is not None and image_2 is None:
|
30 |
+
message = "USER: The image: <|image|> " + message + " ASSISTANT:"
|
31 |
+
images = [image_1]
|
32 |
+
if image_1 is not None and image_2 is not None:
|
33 |
+
message = "USER: The first image: <|image|>\nThe second image: <|image|>" + message + " ASSISTANT:"
|
34 |
+
images = [image_1, image_2]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
35 |
|
36 |
+
print(message)
|
|
|
|
|
37 |
|
38 |
+
return model.tokenizer.batch_decode(model.chat(message, images, max_new_tokens=150).clamp(0, 100000))[0].split("ASSISTANT:")[-1]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
|
|
|
40 |
|
41 |
+
with gr.Blocks(title="img") as demo:
|
42 |
+
title_markdown = ("""
|
43 |
+
<div align="center">*Preview Version (v1)! Now we support two images as inputs! Try it now!*</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
<h1 align="center"><a href="https://github.com/Q-Future/Q-Instruct"><img src="https://github.com/Q-Future/Q-Instruct/blob/main/q_instruct_logo.png?raw=true", alt="Q-Instruct (mPLUG-Owl-2)" border="0" style="margin: 0 auto; height: 85px;" /></a> </h1>
|
|
|
45 |
<h2 align="center">Q-Instruct: Improving Low-level Visual Abilities for Multi-modality Foundation Models</h2>
|
46 |
+
<h5 align="center"> Please find our more accurate visual scoring demo on <a href='https://huggingface.co/spaces/teowu/OneScorer'>[OneScorer]</a>!</h2>
|
|
|
|
|
47 |
<div align="center">
|
48 |
<div style="display:flex; gap: 0.25rem;" align="center">
|
49 |
<a href='https://github.com/Q-Future/Q-Instruct'><img src='https://img.shields.io/badge/Github-Code-blue'></a>
|
|
|
51 |
<a href='https://github.com/Q-Future/Q-Instruct/stargazers'><img src='https://img.shields.io/github/stars/Q-Future/Q-Instruct.svg?style=social'></a>
|
52 |
</div>
|
53 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
54 |
""")
|
55 |
+
gr.Markdown(title_markdown)
|
56 |
+
with gr.Row():
|
57 |
+
input_img_1 = gr.Image(type='pil', label="Image 1 (The first image)")
|
58 |
+
input_img_2 = gr.Image(type='pil', label="Image 2 (The second image)")
|
59 |
+
gr.ChatInterface(fn = chat, additional_inputs=[input_img_1, input_img_2])
|
60 |
+
demo.launch(share=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|