GiantPandas commited on
Commit
3029675
·
verified ·
1 Parent(s): e4aecb8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +235 -75
app.py CHANGED
@@ -49,88 +49,248 @@ client = OpenAI(
49
  base_url=openai_api_base,
50
  )
51
 
 
 
 
 
 
 
 
 
52
 
 
 
53
 
54
- def run_example(image, text_input=None):
55
-
56
- image_path = array_to_image_path(image)
57
- content = [
58
- {
59
- "type": "image_url",
60
- "image_url": {
61
- "url": f"data:image/jpeg;base64,{encode_image(image_path)}"
62
- }
63
- }
64
- ]
65
-
66
- # 可选文本内容
67
- if text_input is not None and text_input.strip():
68
- content.append(
69
- {
70
- "type": "text",
71
- "text": text_input
72
- }
73
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
- messages = [
76
- {
77
- "role": "user",
78
- "content": content
79
- }
80
- ]
81
-
82
- response = client.chat.completions.create(
83
- model="Qwen2_5VL",
84
- messages=messages,
85
- extra_body={},
86
- extra_headers={
87
- "apikey": "empty"
88
- },
89
- stream=False,
90
- temperature=0.7,
91
- top_p=1.0,
92
- )
93
-
94
- return response.choices[0].message.content
95
-
96
-
97
-
98
- css = """
99
- #output {
100
- height: 500px;
101
- overflow: auto;
102
- border: 1px solid #ccc;
103
- }
104
- """
105
-
106
- with gr.Blocks(css=css) as demo:
107
- gr.Markdown("## Test")
108
-
109
- with gr.Tab("Input"):
110
  with gr.Row():
 
 
 
 
111
 
112
- # --- 左列:输入 ---
113
- with gr.Column(scale=1, min_width=300):
114
- input_img = gr.Image(label="Input Picture", type="pil")
115
- text_input = gr.Textbox(label="Text Prompt")
116
- submit_btn = gr.Button("Submit")
117
-
118
- # --- 右列:输出 ---
119
- with gr.Column(scale=1, min_width=300):
120
- output_text = gr.Textbox(label="Output Text")
121
-
122
- # 事件绑定
123
- submit_btn.click(
124
- fn=run_example,
125
- inputs=[input_img, text_input],
126
- outputs=output_text, # 只一个时可直写对象
127
- queue=True # 推荐写在 click 而非全局 queue()
128
  )
 
 
 
 
 
 
 
 
 
 
 
 
129
 
130
- # 若想全局排队,也可注释上方 `queue=True` 把这两行放外面:
131
- # demo.queue() # 开启排队
132
- # demo.launch() # 启动
133
 
134
- demo.launch(debug=False)
 
 
135
 
136
 
 
 
 
49
  base_url=openai_api_base,
50
  )
51
 
52
+ # Copyright (c) Alibaba Cloud.
53
+ #
54
+ # This source code is licensed under the license found in the
55
+ # LICENSE file in the root directory of this source tree.
56
+ import os
57
+ import numpy as np
58
+ from urllib3.exceptions import HTTPError
59
+ os.system('pip install dashscope modelscope oss2 -U')
60
 
61
+ from argparse import ArgumentParser
62
+ from pathlib import Path
63
 
64
+ import copy
65
+ import gradio as gr
66
+ import oss2
67
+ import os
68
+ import re
69
+ import secrets
70
+ import tempfile
71
+ import requests
72
+ from http import HTTPStatus
73
+ from dashscope import MultiModalConversation
74
+ import dashscope
75
+
76
+ API_KEY = os.environ['API_KEY']
77
+ dashscope.api_key = API_KEY
78
+
79
+ REVISION = 'v1.0.4'
80
+ BOX_TAG_PATTERN = r"<box>([\s\S]*?)</box>"
81
+ PUNCTUATION = "!?。"#$%&'()*+,-/:;<=>@[\]^_`{|}~⦅⦆「」、、〃》「」『』【】〔〕〖〗〘〙〚〛〜〝〞〟〰〾〿–—‘’‛“”„‟…‧﹏."
82
+
83
+
84
+ def _get_args():
85
+ parser = ArgumentParser()
86
+ parser.add_argument("--revision", type=str, default=REVISION)
87
+ parser.add_argument("--cpu-only", action="store_true", help="Run demo with CPU only")
88
+
89
+ parser.add_argument("--share", action="store_true", default=False,
90
+ help="Create a publicly shareable link for the interface.")
91
+ parser.add_argument("--inbrowser", action="store_true", default=False,
92
+ help="Automatically launch the interface in a new tab on the default browser.")
93
+ parser.add_argument("--server-port", type=int, default=7860,
94
+ help="Demo server port.")
95
+ parser.add_argument("--server-name", type=str, default="127.0.0.1",
96
+ help="Demo server name.")
97
+
98
+ args = parser.parse_args()
99
+ return args
100
+
101
+ def _parse_text(text):
102
+ lines = text.split("\n")
103
+ lines = [line for line in lines if line != ""]
104
+ count = 0
105
+ for i, line in enumerate(lines):
106
+ if "```" in line:
107
+ count += 1
108
+ items = line.split("`")
109
+ if count % 2 == 1:
110
+ lines[i] = f'<pre><code class="language-{items[-1]}">'
111
+ else:
112
+ lines[i] = f"<br></code></pre>"
113
+ else:
114
+ if i > 0:
115
+ if count % 2 == 1:
116
+ line = line.replace("`", r"\`")
117
+ line = line.replace("<", "&lt;")
118
+ line = line.replace(">", "&gt;")
119
+ line = line.replace(" ", "&nbsp;")
120
+ line = line.replace("*", "&ast;")
121
+ line = line.replace("_", "&lowbar;")
122
+ line = line.replace("-", "&#45;")
123
+ line = line.replace(".", "&#46;")
124
+ line = line.replace("!", "&#33;")
125
+ line = line.replace("(", "&#40;")
126
+ line = line.replace(")", "&#41;")
127
+ line = line.replace("$", "&#36;")
128
+ lines[i] = "<br>" + line
129
+ text = "".join(lines)
130
+ return text
131
+
132
+
133
+ def _remove_image_special(text):
134
+ text = text.replace('<ref>', '').replace('</ref>', '')
135
+ return re.sub(r'<box>.*?(</box>|$)', '', text)
136
+
137
+
138
+ def is_video_file(filename):
139
+ video_extensions = ['.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv', '.webm', '.mpeg']
140
+ return any(filename.lower().endswith(ext) for ext in video_extensions)
141
+
142
+
143
+ def _launch_demo(args):
144
+ uploaded_file_dir = os.environ.get("GRADIO_TEMP_DIR") or str(
145
+ Path(tempfile.gettempdir()) / "gradio"
146
+ )
147
+
148
+ def predict(_chatbot, task_history):
149
+ chat_query = _chatbot[-1][0]
150
+ query = task_history[-1][0]
151
+ if len(chat_query) == 0:
152
+ _chatbot.pop()
153
+ task_history.pop()
154
+ return _chatbot
155
+ print("User: " + _parse_text(query))
156
+ history_cp = copy.deepcopy(task_history)
157
+ full_response = ""
158
+ messages = []
159
+ content = []
160
+ for q, a in history_cp:
161
+ if isinstance(q, (tuple, list)):
162
+ if is_video_file(q[0]):
163
+ content.append({'video': f'file://{q[0]}'})
164
+ else:
165
+ content.append({'image': f'file://{q[0]}'})
166
+ else:
167
+ content.append({'text': q})
168
+ messages.append({'role': 'user', 'content': content})
169
+ messages.append({'role': 'assistant', 'content': [{'text': a}]})
170
+ content = []
171
+ messages.pop()
172
+
173
+
174
+ response = client.chat.completions.create(
175
+ model="Qwen2_5VL",
176
+ messages=messages,
177
+ extra_body={},
178
+ extra_headers={
179
+ "apikey": "empty"
180
+ },
181
+ stream=True,
182
+ temperature=0.7,
183
+ top_p=1.0,
184
+ )
185
+
186
+
187
+
188
+ for response in responses:
189
+ if not response.status_code == HTTPStatus.OK:
190
+ raise HTTPError(f'response.code: {response.code}\nresponse.message: {response.message}')
191
+ response = response.output.choices[0].message.content
192
+ response_text = []
193
+ for ele in response:
194
+ if 'text' in ele:
195
+ response_text.append(ele['text'])
196
+ elif 'box' in ele:
197
+ response_text.append(ele['box'])
198
+ response_text = ''.join(response_text)
199
+ _chatbot[-1] = (_parse_text(chat_query), _remove_image_special(response_text))
200
+ yield _chatbot
201
+
202
+ if len(response) > 1:
203
+ result_image = response[-1]['result_image']
204
+ resp = requests.get(result_image)
205
+ os.makedirs(uploaded_file_dir, exist_ok=True)
206
+ name = f"tmp{secrets.token_hex(20)}.jpg"
207
+ filename = os.path.join(uploaded_file_dir, name)
208
+ with open(filename, 'wb') as f:
209
+ f.write(resp.content)
210
+ response = ''.join(r['box'] if 'box' in r else r['text'] for r in response[:-1])
211
+ _chatbot.append((None, (filename,)))
212
+ else:
213
+ response = response[0]['text']
214
+ _chatbot[-1] = (_parse_text(chat_query), response)
215
+ full_response = _parse_text(response)
216
+
217
+ task_history[-1] = (query, full_response)
218
+ print("Qwen2.5-VL-Chat: " + _parse_text(full_response))
219
+ yield _chatbot
220
+
221
+
222
+ def regenerate(_chatbot, task_history):
223
+ if not task_history:
224
+ return _chatbot
225
+ item = task_history[-1]
226
+ if item[1] is None:
227
+ return _chatbot
228
+ task_history[-1] = (item[0], None)
229
+ chatbot_item = _chatbot.pop(-1)
230
+ if chatbot_item[0] is None:
231
+ _chatbot[-1] = (_chatbot[-1][0], None)
232
+ else:
233
+ _chatbot.append((chatbot_item[0], None))
234
+ _chatbot_gen = predict(_chatbot, task_history)
235
+ for _chatbot in _chatbot_gen:
236
+ yield _chatbot
237
+
238
+ def add_text(history, task_history, text):
239
+ task_text = text
240
+ history = history if history is not None else []
241
+ task_history = task_history if task_history is not None else []
242
+ history = history + [(_parse_text(text), None)]
243
+ task_history = task_history + [(task_text, None)]
244
+ return history, task_history, ""
245
+
246
+ def add_file(history, task_history, file):
247
+ history = history if history is not None else []
248
+ task_history = task_history if task_history is not None else []
249
+ history = history + [((file.name,), None)]
250
+ task_history = task_history + [((file.name,), None)]
251
+ return history, task_history
252
+
253
+ def reset_user_input():
254
+ return gr.update(value="")
255
+
256
+ def reset_state(task_history):
257
+ task_history.clear()
258
+ return []
259
+
260
+ with gr.Blocks() as demo:
261
+ gr.Markdown("""<center><font size=3> Qwen2.5-VL-32B-Instruct Demo </center>""")
262
+
263
+ chatbot = gr.Chatbot(label='Qwen2.5-VL-32B-Instruct', elem_classes="control-height", height=500)
264
+ query = gr.Textbox(lines=2, label='Input')
265
+ task_history = gr.State([])
266
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
267
  with gr.Row():
268
+ addfile_btn = gr.UploadButton("📁 Upload (上传文件)", file_types=["image", "video"])
269
+ submit_btn = gr.Button("🚀 Submit (发送)")
270
+ regen_btn = gr.Button("🤔️ Regenerate (重试)")
271
+ empty_bin = gr.Button("🧹 Clear History (清除历史)")
272
 
273
+ submit_btn.click(add_text, [chatbot, task_history, query], [chatbot, task_history]).then(
274
+ predict, [chatbot, task_history], [chatbot], show_progress=True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
275
  )
276
+ submit_btn.click(reset_user_input, [], [query])
277
+ empty_bin.click(reset_state, [task_history], [chatbot], show_progress=True)
278
+ regen_btn.click(regenerate, [chatbot, task_history], [chatbot], show_progress=True)
279
+ addfile_btn.upload(add_file, [chatbot, task_history, addfile_btn], [chatbot, task_history], show_progress=True)
280
+
281
+
282
+ demo.queue(default_concurrency_limit=40).launch(
283
+ share=args.share,
284
+ # inbrowser=args.inbrowser,
285
+ # server_port=args.server_port,
286
+ # server_name=args.server_name,
287
+ )
288
 
 
 
 
289
 
290
+ def main():
291
+ args = _get_args()
292
+ _launch_demo(args)
293
 
294
 
295
+ if __name__ == '__main__':
296
+ main()