Update app.py
Browse files
app.py
CHANGED
@@ -1,439 +1,46 @@
|
|
1 |
-
|
2 |
-
# InternVL
|
3 |
-
# Copyright (c) 2024 OpenGVLab
|
4 |
-
# Licensed under The MIT License [see LICENSE for details]
|
5 |
-
# --------------------------------------------------------
|
6 |
-
|
7 |
-
import argparse
|
8 |
-
import base64
|
9 |
-
import datetime
|
10 |
-
import hashlib
|
11 |
-
import json
|
12 |
-
import os
|
13 |
-
import random
|
14 |
-
import re
|
15 |
import sys
|
16 |
-
# from streamlit_js_eval import streamlit_js_eval
|
17 |
-
from functools import partial
|
18 |
-
from io import BytesIO
|
19 |
-
|
20 |
-
import cv2
|
21 |
-
import numpy as np
|
22 |
-
import requests
|
23 |
-
import streamlit as st
|
24 |
-
from constants import LOGDIR, server_error_msg
|
25 |
-
from library import Library
|
26 |
-
from PIL import Image, ImageDraw, ImageFont
|
27 |
-
from streamlit_image_select import image_select
|
28 |
-
|
29 |
-
custom_args = sys.argv[1:]
|
30 |
-
parser = argparse.ArgumentParser()
|
31 |
-
parser.add_argument('--controller_url', type=str, default='http://10.140.60.209:10075', help='url of the controller')
|
32 |
-
parser.add_argument('--sd_worker_url', type=str, default='http://0.0.0.0:40006', help='url of the stable diffusion worker')
|
33 |
-
parser.add_argument('--max_image_limit', type=int, default=4, help='maximum number of images')
|
34 |
-
args = parser.parse_args(custom_args)
|
35 |
-
controller_url = args.controller_url
|
36 |
-
sd_worker_url = args.sd_worker_url
|
37 |
-
max_image_limit = args.max_image_limit
|
38 |
-
print('args:', args)
|
39 |
-
|
40 |
-
|
41 |
-
def get_model_list():
|
42 |
-
ret = requests.post(controller_url + '/refresh_all_workers')
|
43 |
-
assert ret.status_code == 200
|
44 |
-
ret = requests.post(controller_url + '/list_models')
|
45 |
-
models = ret.json()['models']
|
46 |
-
return models
|
47 |
-
|
48 |
-
|
49 |
-
def load_upload_file_and_show():
|
50 |
-
if uploaded_files is not None:
|
51 |
-
images = []
|
52 |
-
for file in uploaded_files:
|
53 |
-
file_bytes = np.asarray(bytearray(file.read()), dtype=np.uint8)
|
54 |
-
img = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
|
55 |
-
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
56 |
-
img = Image.fromarray(img)
|
57 |
-
images.append(img)
|
58 |
-
with upload_image_preview.container():
|
59 |
-
Library(images)
|
60 |
-
|
61 |
-
image_hashes = [hashlib.md5(image.tobytes()).hexdigest() for image in images]
|
62 |
-
for image, hash in zip(images, image_hashes):
|
63 |
-
t = datetime.datetime.now()
|
64 |
-
filename = os.path.join(LOGDIR, 'serve_images', f'{t.year}-{t.month:02d}-{t.day:02d}', f'{hash}.jpg')
|
65 |
-
if not os.path.isfile(filename):
|
66 |
-
os.makedirs(os.path.dirname(filename), exist_ok=True)
|
67 |
-
image.save(filename)
|
68 |
-
return images
|
69 |
-
|
70 |
-
|
71 |
-
def get_selected_worker_ip():
|
72 |
-
ret = requests.post(controller_url + '/get_worker_address',
|
73 |
-
json={'model': selected_model})
|
74 |
-
worker_addr = ret.json()['address']
|
75 |
-
return worker_addr
|
76 |
-
|
77 |
-
|
78 |
-
def generate_response(messages):
|
79 |
-
send_messages = [{'role': 'system', 'content': persona_rec}]
|
80 |
-
for message in messages:
|
81 |
-
if message['role'] == 'user':
|
82 |
-
user_message = {'role': 'user', 'content': message['content']}
|
83 |
-
if 'image' in message and len('image') > 0:
|
84 |
-
user_message['image'] = []
|
85 |
-
for image in message['image']:
|
86 |
-
user_message['image'].append(pil_image_to_base64(image))
|
87 |
-
send_messages.append(user_message)
|
88 |
-
else:
|
89 |
-
send_messages.append({'role': 'assistant', 'content': message['content']})
|
90 |
-
pload = {
|
91 |
-
'model': selected_model,
|
92 |
-
'prompt': send_messages,
|
93 |
-
'temperature': float(temperature),
|
94 |
-
'top_p': float(top_p),
|
95 |
-
'max_new_tokens': max_length,
|
96 |
-
'max_input_tiles': max_input_tiles,
|
97 |
-
'repetition_penalty': float(repetition_penalty),
|
98 |
-
}
|
99 |
-
worker_addr = get_selected_worker_ip()
|
100 |
-
headers = {'User-Agent': 'InternVL-Chat Client'}
|
101 |
-
placeholder, output = st.empty(), ''
|
102 |
-
try:
|
103 |
-
response = requests.post(worker_addr + '/worker_generate_stream',
|
104 |
-
headers=headers, json=pload, stream=True, timeout=10)
|
105 |
-
for chunk in response.iter_lines(decode_unicode=False, delimiter=b'\0'):
|
106 |
-
if chunk:
|
107 |
-
data = json.loads(chunk.decode())
|
108 |
-
if data['error_code'] == 0:
|
109 |
-
output = data['text']
|
110 |
-
# Phi3-3.8B will produce abnormal `�` output
|
111 |
-
if '4B' in selected_model and '�' in output[-2:]:
|
112 |
-
output = output.replace('�', '')
|
113 |
-
break
|
114 |
-
placeholder.markdown(output + '▌')
|
115 |
-
else:
|
116 |
-
output = data['text'] + f" (error_code: {data['error_code']})"
|
117 |
-
placeholder.markdown(output)
|
118 |
-
placeholder.markdown(output)
|
119 |
-
except requests.exceptions.RequestException as e:
|
120 |
-
placeholder.markdown(server_error_msg)
|
121 |
-
return output
|
122 |
-
|
123 |
-
|
124 |
-
def pil_image_to_base64(image):
|
125 |
-
buffered = BytesIO()
|
126 |
-
image.save(buffered, format='PNG')
|
127 |
-
return base64.b64encode(buffered.getvalue()).decode('utf-8')
|
128 |
-
|
129 |
-
|
130 |
-
def clear_chat_history():
|
131 |
-
st.session_state.messages = []
|
132 |
-
st.session_state['image_select'] = -1
|
133 |
-
|
134 |
-
|
135 |
-
def clear_file_uploader():
|
136 |
-
st.session_state.uploader_key += 1
|
137 |
-
st.rerun()
|
138 |
-
|
139 |
-
|
140 |
-
def combined_func(func_list):
|
141 |
-
for func in func_list:
|
142 |
-
func()
|
143 |
-
|
144 |
-
|
145 |
-
def show_one_or_multiple_images(message, total_image_num, is_input=True):
|
146 |
-
if 'image' in message:
|
147 |
-
if is_input:
|
148 |
-
total_image_num = total_image_num + len(message['image'])
|
149 |
-
if lan == 'English':
|
150 |
-
if len(message['image']) == 1 and total_image_num == 1:
|
151 |
-
label = f"(In this conversation, {len(message['image'])} image was uploaded, {total_image_num} image in total)"
|
152 |
-
elif len(message['image']) == 1 and total_image_num > 1:
|
153 |
-
label = f"(In this conversation, {len(message['image'])} image was uploaded, {total_image_num} images in total)"
|
154 |
-
else:
|
155 |
-
label = f"(In this conversation, {len(message['image'])} images were uploaded, {total_image_num} images in total)"
|
156 |
-
else:
|
157 |
-
label = f"(在本次对话中,上传了{len(message['image'])}张图片,总共上传了{total_image_num}张图片)"
|
158 |
-
upload_image_preview = st.empty()
|
159 |
-
with upload_image_preview.container():
|
160 |
-
Library(message['image'])
|
161 |
-
if is_input and len(message['image']) > 0:
|
162 |
-
st.markdown(label)
|
163 |
-
|
164 |
-
|
165 |
-
def find_bounding_boxes(response):
|
166 |
-
pattern = re.compile(r'<ref>\s*(.*?)\s*</ref>\s*<box>\s*(\[\[.*?\]\])\s*</box>')
|
167 |
-
matches = pattern.findall(response)
|
168 |
-
results = []
|
169 |
-
for match in matches:
|
170 |
-
results.append((match[0], eval(match[1])))
|
171 |
-
returned_image = None
|
172 |
-
for message in st.session_state.messages:
|
173 |
-
if message['role'] == 'user' and 'image' in message and len(message['image']) > 0:
|
174 |
-
last_image = message['image'][-1]
|
175 |
-
width, height = last_image.size
|
176 |
-
returned_image = last_image.copy()
|
177 |
-
draw = ImageDraw.Draw(returned_image)
|
178 |
-
for result in results:
|
179 |
-
line_width = max(1, int(min(width, height) / 200))
|
180 |
-
random_color = (random.randint(0, 128), random.randint(0, 128), random.randint(0, 128))
|
181 |
-
category_name, coordinates = result
|
182 |
-
coordinates = [(float(x[0]) / 1000, float(x[1]) / 1000, float(x[2]) / 1000, float(x[3]) / 1000) for x in coordinates]
|
183 |
-
coordinates = [(int(x[0] * width), int(x[1] * height), int(x[2] * width), int(x[3] * height)) for x in coordinates]
|
184 |
-
for box in coordinates:
|
185 |
-
draw.rectangle(box, outline=random_color, width=line_width)
|
186 |
-
font = ImageFont.truetype('static/SimHei.ttf', int(20 * line_width / 2))
|
187 |
-
text_size = font.getbbox(category_name)
|
188 |
-
text_width, text_height = text_size[2] - text_size[0], text_size[3] - text_size[1]
|
189 |
-
text_position = (box[0], max(0, box[1] - text_height))
|
190 |
-
draw.rectangle(
|
191 |
-
[text_position, (text_position[0] + text_width, text_position[1] + text_height)],
|
192 |
-
fill=random_color
|
193 |
-
)
|
194 |
-
draw.text(text_position, category_name, fill='white', font=font)
|
195 |
-
return returned_image if len(matches) > 0 else None
|
196 |
-
|
197 |
-
|
198 |
-
def query_image_generation(response, sd_worker_url, timeout=15):
|
199 |
-
sd_worker_url = f'{sd_worker_url}/generate_image/'
|
200 |
-
pattern = r'```drawing-instruction\n(.*?)\n```'
|
201 |
-
match = re.search(pattern, response, re.DOTALL)
|
202 |
-
if match:
|
203 |
-
payload = {'caption': match.group(1)}
|
204 |
-
print('drawing-instruction:', payload)
|
205 |
-
response = requests.post(sd_worker_url, json=payload, timeout=timeout)
|
206 |
-
response.raise_for_status() # 检查HTTP请求是否成功
|
207 |
-
image = Image.open(BytesIO(response.content))
|
208 |
-
return image
|
209 |
-
else:
|
210 |
-
return None
|
211 |
-
|
212 |
-
|
213 |
-
def regenerate():
|
214 |
-
st.session_state.messages = st.session_state.messages[:-1]
|
215 |
-
st.rerun()
|
216 |
-
|
217 |
-
|
218 |
-
logo_code = """
|
219 |
-
<svg width="1700" height="200" xmlns="http://www.w3.org/2000/svg">
|
220 |
-
<defs>
|
221 |
-
<linearGradient id="gradient1" x1="0%" y1="0%" x2="100%" y2="0%">
|
222 |
-
<stop offset="0%" style="stop-color: red; stop-opacity: 1" />
|
223 |
-
<stop offset="100%" style="stop-color: orange; stop-opacity: 1" />
|
224 |
-
</linearGradient>
|
225 |
-
</defs>
|
226 |
-
<text x="000" y="160" font-size="180" font-weight="bold" fill="url(#gradient1)" style="font-family: Arial, sans-serif;">
|
227 |
-
InternVL2 Demo
|
228 |
-
</text>
|
229 |
-
</svg>
|
230 |
-
"""
|
231 |
-
|
232 |
-
# App title
|
233 |
-
st.set_page_config(page_title='InternVL2')
|
234 |
-
|
235 |
-
if 'uploader_key' not in st.session_state:
|
236 |
-
st.session_state.uploader_key = 0
|
237 |
-
|
238 |
-
# 如果用户要求绘图,请以生成符合Stable Diffusion要求的、满足```drawing-instruction\n{instruction}\n```格式的绘图指令。
|
239 |
-
system_message = """我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。人工智能实验室致力于原始技术创新,开源开放,共享共创,推动科技进步和产业发展。
|
240 |
-
|
241 |
-
对于目标检测任务,请按照以下格式输出坐标框:<ref>某类物体</ref><box>[[x1, y1, x2, y2], ...]</box>
|
242 |
-
|
243 |
-
对于画画任务,请按照以下格式输出绘图指令,注意指令需要英文:```drawing-instruction\n{instruction}\n```
|
244 |
-
|
245 |
-
在处理输入包含多张图像的情况下,请严格按照以下规则区分和处理每一张图像,并小心区分用户的提问针对的是哪一张图片:
|
246 |
-
|
247 |
-
1. 图像编号和标记:每张图像都将使用明确的编号标记,例如 "Image-1: <img></img>","Image-2: <img></img>","Image-3: <img></img>" 等等。
|
248 |
-
|
249 |
-
2. 用户提问关联:用户的提问可能会具体指向某一张编号的图像,请仔细辨别用户问题中提到的图像编号。
|
250 |
-
|
251 |
-
请尽可能详细地回答用户的问题。"""
|
252 |
-
|
253 |
-
# Replicate Credentials
|
254 |
-
with st.sidebar:
|
255 |
-
model_list = get_model_list()
|
256 |
-
# "[![Open in GitHub](https://github.com/codespaces/badge.svg)](https://github.com/OpenGVLab/InternVL)"
|
257 |
-
lan = st.selectbox('#### Language / 语言', ['English', '中文'], on_change=st.rerun)
|
258 |
-
if lan == 'English':
|
259 |
-
st.logo(logo_code, link='https://github.com/OpenGVLab/InternVL', icon_image=logo_code)
|
260 |
-
st.subheader('Models and parameters')
|
261 |
-
selected_model = st.sidebar.selectbox('Choose a InternVL2 chat model', model_list, key='selected_model', on_change=clear_chat_history)
|
262 |
-
with st.expander('🤖 System Prompt'):
|
263 |
-
persona_rec = st.text_area('System Prompt', value=system_message,
|
264 |
-
help='System prompt is a pre-defined message used to instruct the assistant at the beginning of a conversation.',
|
265 |
-
height=200)
|
266 |
-
with st.expander('🔥 Advanced Options'):
|
267 |
-
temperature = st.slider('temperature', min_value=0.0, max_value=1.0, value=0.8, step=0.1)
|
268 |
-
top_p = st.slider('top_p', min_value=0.0, max_value=1.0, value=0.7, step=0.1)
|
269 |
-
repetition_penalty = st.slider('repetition_penalty', min_value=1.0, max_value=1.5, value=1.1, step=0.02)
|
270 |
-
max_length = st.slider('max_length', min_value=0, max_value=4096, value=2048, step=128)
|
271 |
-
max_input_tiles = st.slider('max_input_tiles (control image resolution)', min_value=1, max_value=24, value=12, step=1)
|
272 |
-
upload_image_preview = st.empty()
|
273 |
-
uploaded_files = st.file_uploader('Upload files', accept_multiple_files=True,
|
274 |
-
type=['png', 'jpg', 'jpeg', 'webp'],
|
275 |
-
help='You can upload multiple images (max to 4) or a single video.',
|
276 |
-
key=f'uploader_{st.session_state.uploader_key}',
|
277 |
-
on_change=st.rerun)
|
278 |
-
uploaded_pil_images = load_upload_file_and_show()
|
279 |
-
else:
|
280 |
-
st.subheader('模型和参数')
|
281 |
-
selected_model = st.sidebar.selectbox('选择一个 InternVL2 对话模型', model_list, key='selected_model', on_change=clear_chat_history)
|
282 |
-
with st.expander('🤖 系统提示'):
|
283 |
-
persona_rec = st.text_area('系统提示', value=system_message,
|
284 |
-
help='系统提示是在对话开始时用于指示助手的预定义消息。',
|
285 |
-
height=200)
|
286 |
-
with st.expander('🔥 高级选项'):
|
287 |
-
temperature = st.slider('temperature', min_value=0.0, max_value=1.0, value=0.8, step=0.1)
|
288 |
-
top_p = st.slider('top_p', min_value=0.0, max_value=1.0, value=0.7, step=0.1)
|
289 |
-
repetition_penalty = st.slider('重复惩罚', min_value=1.0, max_value=1.5, value=1.1, step=0.02)
|
290 |
-
max_length = st.slider('最大输出长度', min_value=0, max_value=4096, value=2048, step=128)
|
291 |
-
max_input_tiles = st.slider('最大图像块数 (控制图像分辨率)', min_value=1, max_value=24, value=12, step=1)
|
292 |
-
upload_image_preview = st.empty()
|
293 |
-
uploaded_files = st.file_uploader('上传文件', accept_multiple_files=True,
|
294 |
-
type=['png', 'jpg', 'jpeg', 'webp'],
|
295 |
-
help='你可以上传多张图像(最多4张)或者一个视频。',
|
296 |
-
key=f'uploader_{st.session_state.uploader_key}',
|
297 |
-
on_change=st.rerun)
|
298 |
-
uploaded_pil_images = load_upload_file_and_show()
|
299 |
-
|
300 |
-
|
301 |
-
gradient_text_html = """
|
302 |
-
<style>
|
303 |
-
.gradient-text {
|
304 |
-
font-weight: bold;
|
305 |
-
background: -webkit-linear-gradient(left, red, orange);
|
306 |
-
background: linear-gradient(to right, red, orange);
|
307 |
-
-webkit-background-clip: text;
|
308 |
-
-webkit-text-fill-color: transparent;
|
309 |
-
display: inline;
|
310 |
-
font-size: 3em;
|
311 |
-
}
|
312 |
-
</style>
|
313 |
-
<div class="gradient-text">InternVL2</div>
|
314 |
-
"""
|
315 |
-
if lan == 'English':
|
316 |
-
st.markdown(gradient_text_html, unsafe_allow_html=True)
|
317 |
-
st.caption('Expanding Performance Boundaries of Open-Source Multimodal Large Language Models')
|
318 |
-
else:
|
319 |
-
st.markdown(gradient_text_html.replace('InternVL2', '书生·万象'), unsafe_allow_html=True)
|
320 |
-
st.caption('扩展开源多模态大语言模型的性能边界')
|
321 |
-
|
322 |
-
# Store LLM generated responses
|
323 |
-
if 'messages' not in st.session_state.keys():
|
324 |
-
clear_chat_history()
|
325 |
-
|
326 |
-
gallery_placeholder = st.empty()
|
327 |
-
with gallery_placeholder.container():
|
328 |
-
images = ['gallery/prod_en_17.png', 'gallery/astro_on_unicorn.png',
|
329 |
-
'gallery/prod_12.png', 'gallery/prod_9.jpg',
|
330 |
-
'gallery/prod_4.png', 'gallery/cheetah.png', 'gallery/prod_1.jpeg']
|
331 |
-
images = [Image.open(image) for image in images]
|
332 |
-
if lan == 'English':
|
333 |
-
captions = ["I'm on a diet, but I really want to eat them.",
|
334 |
-
'Could you help me draw a picture like this one?',
|
335 |
-
'What are the consequences of the easy decisions shown in this image?',
|
336 |
-
"What's at the far end of the image?",
|
337 |
-
'Is this a real plant? Analyze the reasons.',
|
338 |
-
'Detect the <ref>the middle leopard</ref> in the image with its bounding box.',
|
339 |
-
'What is the atmosphere of this image?']
|
340 |
-
else:
|
341 |
-
captions = ['我在减肥,但我真的很想吃这个。',
|
342 |
-
'请画一张类似这样的画',
|
343 |
-
'这张图上 easy decisions 导致了什么后果?',
|
344 |
-
'画面最远处是什么?',
|
345 |
-
'这是真的植物吗?分析原因',
|
346 |
-
'在以下图像中进行目标检测,并标出所有物体。',
|
347 |
-
'这幅图的氛围如何?']
|
348 |
-
img_idx = image_select(
|
349 |
-
label='',
|
350 |
-
images=images,
|
351 |
-
captions=captions,
|
352 |
-
use_container_width=True,
|
353 |
-
index=-1,
|
354 |
-
return_value='index',
|
355 |
-
key='image_select'
|
356 |
-
)
|
357 |
-
if lan == 'English':
|
358 |
-
st.caption('Note: For non-commercial research use only. AI responses may contain errors. Users should not spread or allow others to spread hate speech, violence, pornography, or fraud-related harmful information.')
|
359 |
-
else:
|
360 |
-
st.caption('注意:仅限非商业研究使用。用户应不传播或允许他人传播仇恨言论、暴力、色情内容或与欺诈相关的有害信息。')
|
361 |
-
if img_idx != -1 and len(st.session_state.messages) == 0 and selected_model is not None:
|
362 |
-
gallery_placeholder.empty()
|
363 |
-
st.session_state.messages.append({'role': 'user', 'content': captions[img_idx], 'image': [images[img_idx]]})
|
364 |
-
st.rerun() # Fixed an issue where examples were not emptied
|
365 |
-
|
366 |
-
if len(st.session_state.messages) > 0:
|
367 |
-
gallery_placeholder.empty()
|
368 |
-
|
369 |
-
# Display or clear chat messages
|
370 |
-
total_image_num = 0
|
371 |
-
for message in st.session_state.messages:
|
372 |
-
with st.chat_message(message['role']):
|
373 |
-
st.markdown(message['content'])
|
374 |
-
show_one_or_multiple_images(message, total_image_num, is_input=message['role'] == 'user')
|
375 |
-
if 'image' in message and message['role'] == 'user':
|
376 |
-
total_image_num += len(message['image'])
|
377 |
-
|
378 |
-
input_disable_flag = (len(model_list) == 0) or total_image_num + len(uploaded_files) > max_image_limit
|
379 |
-
if lan == 'English':
|
380 |
-
st.sidebar.button('Clear Chat History', on_click=partial(combined_func, func_list=[clear_chat_history, clear_file_uploader]))
|
381 |
-
if input_disable_flag:
|
382 |
-
prompt = st.chat_input('Too many images have been uploaded. Please clear the history.', disabled=input_disable_flag)
|
383 |
-
else:
|
384 |
-
prompt = st.chat_input('Send messages to InternVL', disabled=input_disable_flag)
|
385 |
-
else:
|
386 |
-
st.sidebar.button('清空聊天记录', on_click=partial(combined_func, func_list=[clear_chat_history, clear_file_uploader]))
|
387 |
-
if input_disable_flag:
|
388 |
-
prompt = st.chat_input('输入的图片太多了,请清空历史记录。', disabled=input_disable_flag)
|
389 |
-
else:
|
390 |
-
prompt = st.chat_input('给 “InternVL” 发送消息', disabled=input_disable_flag)
|
391 |
-
|
392 |
-
alias_instructions = {
|
393 |
-
'目标检测': '在以下图像中进行目标检测,并标出所有物体。',
|
394 |
-
'检测': '在以下图像中进行目标检测,并标出所有物体。',
|
395 |
-
'object detection': 'Please identify and label all objects in the following image.',
|
396 |
-
'detection': 'Please identify and label all objects in the following image.'
|
397 |
-
}
|
398 |
-
|
399 |
-
if prompt:
|
400 |
-
prompt = alias_instructions[prompt] if prompt in alias_instructions else prompt
|
401 |
-
gallery_placeholder.empty()
|
402 |
-
image_list = uploaded_pil_images
|
403 |
-
st.session_state.messages.append({'role': 'user', 'content': prompt, 'image': image_list})
|
404 |
-
with st.chat_message('user'):
|
405 |
-
st.write(prompt)
|
406 |
-
show_one_or_multiple_images(st.session_state.messages[-1], total_image_num, is_input=True)
|
407 |
-
if image_list:
|
408 |
-
clear_file_uploader()
|
409 |
-
|
410 |
-
# Generate a new response if last message is not from assistant
|
411 |
-
if len(st.session_state.messages) > 0 and st.session_state.messages[-1]['role'] != 'assistant':
|
412 |
-
with st.chat_message('assistant'):
|
413 |
-
with st.spinner('Thinking...'):
|
414 |
-
if not prompt:
|
415 |
-
prompt = st.session_state.messages[-1]['content']
|
416 |
-
response = generate_response(st.session_state.messages)
|
417 |
-
message = {'role': 'assistant', 'content': response}
|
418 |
-
with st.spinner('Drawing...'):
|
419 |
-
if '<ref>' in response:
|
420 |
-
has_returned_image = find_bounding_boxes(response)
|
421 |
-
message['image'] = [has_returned_image] if has_returned_image else []
|
422 |
-
if '```drawing-instruction' in response:
|
423 |
-
has_returned_image = query_image_generation(response, sd_worker_url=sd_worker_url)
|
424 |
-
message['image'] = [has_returned_image] if has_returned_image else []
|
425 |
-
st.session_state.messages.append(message)
|
426 |
-
show_one_or_multiple_images(message, total_image_num, is_input=False)
|
427 |
-
|
428 |
-
if len(st.session_state.messages) > 0:
|
429 |
-
col1, col2, col3, col4 = st.columns([1, 1, 1, 1.3])
|
430 |
-
text1 = 'Clear Chat History' if lan == 'English' else '清空聊天记录'
|
431 |
-
text2 = 'Regenerate' if lan == 'English' else '重新生成'
|
432 |
-
text3 = 'Copy' if lan == 'English' else '复制回答'
|
433 |
-
with col1:
|
434 |
-
st.button(text1, on_click=partial(combined_func, func_list=[clear_chat_history, clear_file_uploader]),
|
435 |
-
key='clear_chat_history_button')
|
436 |
-
with col2:
|
437 |
-
st.button(text2, on_click=regenerate, key='regenerate_button')
|
438 |
|
439 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import subprocess
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
import sys
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
|
4 |
+
# Function to install a package using pip
|
5 |
+
def install_package(package):
|
6 |
+
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
|
7 |
+
|
8 |
+
# Install Flask
|
9 |
+
install_package("flask")
|
10 |
+
|
11 |
+
from flask import Flask, render_template_string
|
12 |
+
|
13 |
+
app = Flask(__name__)
|
14 |
+
|
15 |
+
@app.route('/')
|
16 |
+
def index():
|
17 |
+
return render_template_string('''
|
18 |
+
<!DOCTYPE html>
|
19 |
+
<html lang="en">
|
20 |
+
<head>
|
21 |
+
<meta charset="UTF-8">
|
22 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
23 |
+
<title>Embed Webpage</title>
|
24 |
+
<style>
|
25 |
+
body, html {
|
26 |
+
margin: 0;
|
27 |
+
padding: 0;
|
28 |
+
height: 100%;
|
29 |
+
overflow: hidden;
|
30 |
+
}
|
31 |
+
iframe {
|
32 |
+
position: absolute;
|
33 |
+
width: 100%;
|
34 |
+
height: 100%;
|
35 |
+
border: none;
|
36 |
+
}
|
37 |
+
</style>
|
38 |
+
</head>
|
39 |
+
<body>
|
40 |
+
<iframe src="http://101.132.98.120:10003/"></iframe>
|
41 |
+
</body>
|
42 |
+
</html>
|
43 |
+
''')
|
44 |
+
|
45 |
+
if __name__ == '__main__':
|
46 |
+
app.run(debug=True)
|