Update app.py
Browse files
app.py
CHANGED
@@ -1,149 +1,92 @@
|
|
1 |
-
import gradio as gr
|
2 |
-
import spaces
|
3 |
-
from transformers import Qwen2VLForConditionalGeneration, AutoProcessor, TextIteratorStreamer
|
4 |
-
from qwen_vl_utils import process_vision_info
|
5 |
-
import torch
|
6 |
-
from PIL import Image
|
7 |
-
import subprocess
|
8 |
-
import numpy as np
|
9 |
import os
|
10 |
-
|
11 |
-
import
|
12 |
-
import
|
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 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
)
|
102 |
-
streamer = TextIteratorStreamer(
|
103 |
-
processor, skip_prompt=True, **{"skip_special_tokens": True}
|
104 |
-
)
|
105 |
-
generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=max_tokens)
|
106 |
-
|
107 |
-
thread = Thread(target=model.generate, kwargs=generation_kwargs)
|
108 |
-
thread.start()
|
109 |
-
|
110 |
-
buffer = ""
|
111 |
-
for new_text in streamer:
|
112 |
-
buffer += new_text
|
113 |
-
yield buffer
|
114 |
-
|
115 |
-
except Exception as e:
|
116 |
-
yield f"Error during inference: {e}"
|
117 |
-
|
118 |
-
|
119 |
-
css = """
|
120 |
-
#output {
|
121 |
-
height: 500px;
|
122 |
-
overflow: auto;
|
123 |
-
border: 1px solid #ccc;
|
124 |
-
}
|
125 |
-
"""
|
126 |
-
|
127 |
-
with gr.Blocks(css=css) as demo:
|
128 |
-
gr.Markdown(DESCRIPTION)
|
129 |
-
|
130 |
-
with gr.Tab(label="Image/Video Input"):
|
131 |
-
with gr.Row():
|
132 |
-
with gr.Column():
|
133 |
-
input_media = gr.File(label="Upload Image or Video", type="filepath")
|
134 |
-
system_prompt = gr.Textbox(
|
135 |
-
label="System Prompt",
|
136 |
-
value="You are a helpful assistant. Answer questions based on the image or video provided, and explain your reasoning clearly.",
|
137 |
-
lines=3
|
138 |
-
)
|
139 |
-
text_input = gr.Textbox(label="Question")
|
140 |
-
max_tokens = gr.Slider(label="Max New Tokens", minimum=16, maximum=2048, value=1024, step=16)
|
141 |
-
submit_btn = gr.Button(value="Submit")
|
142 |
-
with gr.Column():
|
143 |
-
output_text = gr.Textbox(label="Output Text", elem_id="output")
|
144 |
-
|
145 |
-
submit_btn.click(
|
146 |
-
qwen_inference, [input_media, text_input, system_prompt, max_tokens], [output_text]
|
147 |
-
)
|
148 |
-
|
149 |
-
demo.launch(debug=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
+
import gradio as gr
|
3 |
+
from argparse import ArgumentParser
|
4 |
+
import copy
|
5 |
+
import tempfile
|
6 |
+
import requests
|
7 |
+
from http import HTTPStatus
|
8 |
+
from dashscope import MultiModalConversation
|
9 |
+
|
10 |
+
# Set environment variables and API key
|
11 |
+
API_KEY = os.environ['API_KEY']
|
12 |
+
dashscope.api_key = API_KEY
|
13 |
+
|
14 |
+
# Define constants
|
15 |
+
MODEL_NAME = 'Qwen2-VL-2B-Instruct'
|
16 |
+
|
17 |
+
# Get arguments
|
18 |
+
def _get_args():
|
19 |
+
parser = ArgumentParser()
|
20 |
+
parser.add_argument("--share", action="store_true", default=False, help="Create a publicly shareable link.")
|
21 |
+
parser.add_argument("--server-port", type=int, default=7860, help="Server port.")
|
22 |
+
parser.add_argument("--server-name", type=str, default="127.0.0.1", help="Server name.")
|
23 |
+
return parser.parse_args()
|
24 |
+
|
25 |
+
# Simplify chat prediction
|
26 |
+
def predict(_chatbot, task_history, system_prompt):
|
27 |
+
chat_query = _chatbot[-1][0]
|
28 |
+
query = task_history[-1][0]
|
29 |
+
if not chat_query:
|
30 |
+
_chatbot.pop()
|
31 |
+
task_history.pop()
|
32 |
+
return _chatbot
|
33 |
+
print("User:", query)
|
34 |
+
history_cp = copy.deepcopy(task_history)
|
35 |
+
messages = [{'role': 'user', 'content': [{'text': q}]} for q, _ in history_cp]
|
36 |
+
responses = MultiModalConversation.call(
|
37 |
+
model=MODEL_NAME, messages=messages, stream=True,
|
38 |
+
)
|
39 |
+
for response in responses:
|
40 |
+
if not response.status_code == HTTPStatus.OK:
|
41 |
+
raise Exception(f'Error: {response.message}')
|
42 |
+
response_text = ''.join([ele['text'] for ele in response.output.choices[0].message.content])
|
43 |
+
_chatbot[-1] = (chat_query, response_text)
|
44 |
+
yield _chatbot
|
45 |
+
|
46 |
+
# Add text to history
|
47 |
+
def add_text(history, task_history, text):
|
48 |
+
task_text = text
|
49 |
+
history.append((_parse_text(text), None))
|
50 |
+
task_history.append((task_text, None))
|
51 |
+
return history, task_history, ""
|
52 |
+
|
53 |
+
# Reset input
|
54 |
+
def reset_user_input():
|
55 |
+
return gr.update(value="")
|
56 |
+
|
57 |
+
# Reset history
|
58 |
+
def reset_state(task_history):
|
59 |
+
task_history.clear()
|
60 |
+
return []
|
61 |
+
|
62 |
+
# Launch the demo
|
63 |
+
def _launch_demo(args):
|
64 |
+
chatbot = gr.Chatbot(label='Qwen2-VL-2B-Instruct', height=500)
|
65 |
+
query = gr.Textbox(lines=2, label='Input')
|
66 |
+
system_prompt = gr.Textbox(lines=2, label='System Prompt', placeholder="Modify system prompt here...")
|
67 |
+
task_history = gr.State([])
|
68 |
+
|
69 |
+
with gr.Row():
|
70 |
+
submit_btn = gr.Button("🚀 Submit")
|
71 |
+
regen_btn = gr.Button("🤔️ Regenerate")
|
72 |
+
empty_bin = gr.Button("🧹 Clear History")
|
73 |
+
|
74 |
+
submit_btn.click(add_text, [chatbot, task_history, query], [chatbot, task_history]).then(
|
75 |
+
predict, [chatbot, task_history, system_prompt], [chatbot], show_progress=True
|
76 |
+
)
|
77 |
+
submit_btn.click(reset_user_input, [], [query])
|
78 |
+
empty_bin.click(reset_state, [task_history], [chatbot], show_progress=True)
|
79 |
+
regen_btn.click(predict, [chatbot, task_history, system_prompt], [chatbot], show_progress=True)
|
80 |
+
|
81 |
+
gr.Markdown("""<center><font size=3>Qwen2-VL-2B-Instruct Demo</center>""")
|
82 |
+
gr.Markdown("""<center><font size=2>Note: This demo uses Qwen2-VL-2B-Instruct model. Please be mindful of ethical content creation.</center>""")
|
83 |
+
|
84 |
+
demo.queue().launch(share=args.share, server_port=args.server_port, server_name=args.server_name)
|
85 |
+
|
86 |
+
# Main function
|
87 |
+
def main():
|
88 |
+
args = _get_args()
|
89 |
+
_launch_demo(args)
|
90 |
+
|
91 |
+
if __name__ == '__main__':
|
92 |
+
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|