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4 |
+
|
5 |
+
import copy
|
6 |
+
import gradio as gr
|
7 |
+
import os
|
8 |
+
import re
|
9 |
+
import secrets
|
10 |
+
import tempfile
|
11 |
+
|
12 |
+
from PIL import Image
|
13 |
+
|
14 |
+
|
15 |
+
import shutil
|
16 |
+
from pathlib import Path
|
17 |
+
import json
|
18 |
+
DEFAULT_CKPT_PATH = '/home/zhangli/demo/'
|
19 |
+
BOX_TAG_PATTERN = r"<box>([\s\S]*?)</box>"
|
20 |
+
PUNCTUATION = "!?。"#$%&'()*+,-/:;<=>@[\]^_`{|}~⦅⦆「」、、〃》「」『』【】〔〕〖〗〘〙〚〛〜〝〞〟〰〾〿–—‘’‛“”„‟…‧﹏."
|
21 |
+
title_markdown = ("""
|
22 |
+
# Welcome to Monkey
|
23 |
+
|
24 |
+
Hello! I'm Monkey, a Large Language and Vision Assistant. Before talking to me, please read the **Operation Guide** and **Terms of Use**.
|
25 |
+
你好!我是Monkey,一个大型语言和视觉助理。在与我交谈之前,请阅读**操作指南**和**使用条款**。
|
26 |
+
## Operation Guide 操作指南
|
27 |
+
|
28 |
+
Click the **Upload** button to upload an image. Then, you can get Monkey's answer in two ways:点击**Upload**上传图像。你可以通过两种方式得到Monkey的回答:
|
29 |
+
- Click the **Generate** and Monkey will generate a description of the image. 点击**Generate**,Monkey将生成图像的描述。
|
30 |
+
- Enter the question in the dialog box, click the **Submit**, and Monkey will answer the question based on the image. 在对话框中输入问题,点击**Submit**,Monkey会根据图片回答问题。
|
31 |
+
- Click **Clear History** to clear the current image and Q&A content.点击**Clear History**,清除当前图片和问答内容。
|
32 |
+
> Note: Monkey does not have a multi-round dialogue function. Perhaps we will further develop its capabilities in the future. 注意:Monkey没有多轮对话功能,或许我们在未来会进一步开发它的能力。
|
33 |
+
> Monkey支持中文,但使用英文提问会比使用中文效果明显好.""")
|
34 |
+
|
35 |
+
policy_markdown = ("""
|
36 |
+
## Terms of Use
|
37 |
+
|
38 |
+
By using this service, users are required to agree to the following terms:
|
39 |
+
|
40 |
+
- Monkey is for research use only and unauthorized commercial use is prohibited. For any query, please contact the author.
|
41 |
+
- Monkey's generation capabilities are limited, so we recommend that users do not rely entirely on its answers.
|
42 |
+
- Monkey's security measures are limited, so we cannot guarantee that the output is completely appropriate. We strongly recommend that users do not intentionally guide Monkey to generate harmful content, including hate speech, discrimination, violence, pornography, deception, etc.
|
43 |
+
|
44 |
+
""")
|
45 |
+
def _get_args():
|
46 |
+
parser = ArgumentParser()
|
47 |
+
parser.add_argument("-c", "--checkpoint-path", type=str, default=DEFAULT_CKPT_PATH,
|
48 |
+
help="Checkpoint name or path, default to %(default)r")
|
49 |
+
parser.add_argument("--cpu-only", action="store_true", help="Run demo with CPU only")
|
50 |
+
|
51 |
+
parser.add_argument("--share", action="store_true", default=False,
|
52 |
+
help="Create a publicly shareable link for the interface.")
|
53 |
+
parser.add_argument("--inbrowser", action="store_true", default=False,
|
54 |
+
help="Automatically launch the interface in a new tab on the default browser.")
|
55 |
+
parser.add_argument("--server-port", type=int, default=8000,
|
56 |
+
help="Demo server port.")
|
57 |
+
parser.add_argument("--server-name", type=str, default="127.0.0.1",
|
58 |
+
help="Demo server name.")
|
59 |
+
|
60 |
+
args = parser.parse_args()
|
61 |
+
return args
|
62 |
+
|
63 |
+
|
64 |
+
|
65 |
+
|
66 |
+
def _parse_text(text):
|
67 |
+
lines = text.split("\n")
|
68 |
+
lines = [line for line in lines if line != ""]
|
69 |
+
count = 0
|
70 |
+
for i, line in enumerate(lines):
|
71 |
+
if "```" in line:
|
72 |
+
count += 1
|
73 |
+
items = line.split("`")
|
74 |
+
if count % 2 == 1:
|
75 |
+
lines[i] = f'<pre><code class="language-{items[-1]}">'
|
76 |
+
else:
|
77 |
+
lines[i] = f"<br></code></pre>"
|
78 |
+
else:
|
79 |
+
if i > 0:
|
80 |
+
if count % 2 == 1:
|
81 |
+
line = line.replace("`", r"\`")
|
82 |
+
line = line.replace("<", "<")
|
83 |
+
line = line.replace(">", ">")
|
84 |
+
line = line.replace(" ", " ")
|
85 |
+
line = line.replace("*", "*")
|
86 |
+
line = line.replace("_", "_")
|
87 |
+
line = line.replace("-", "-")
|
88 |
+
line = line.replace(".", ".")
|
89 |
+
line = line.replace("!", "!")
|
90 |
+
line = line.replace("(", "(")
|
91 |
+
line = line.replace(")", ")")
|
92 |
+
line = line.replace("$", "$")
|
93 |
+
lines[i] = "<br>" + line
|
94 |
+
text = "".join(lines)
|
95 |
+
return text
|
96 |
+
|
97 |
+
|
98 |
+
def _launch_demo():
|
99 |
+
def predict(_chatbot, task_history):
|
100 |
+
chat_query = _chatbot[-1][0]
|
101 |
+
query = task_history[-1][0]
|
102 |
+
question = _parse_text(query)
|
103 |
+
print("User: " + _parse_text(query))
|
104 |
+
full_response = ""
|
105 |
+
|
106 |
+
|
107 |
+
img_path = _chatbot[0][0][0]
|
108 |
+
try:
|
109 |
+
Image.open(img_path)
|
110 |
+
except:
|
111 |
+
response = "Please upload a picture."
|
112 |
+
_chatbot[-1] = (_parse_text(chat_query), response)
|
113 |
+
full_response = _parse_text(response)
|
114 |
+
|
115 |
+
task_history[-1] = (query, full_response)
|
116 |
+
print("Monkey: " + _parse_text(full_response))
|
117 |
+
return _chatbot
|
118 |
+
|
119 |
+
query = f'<img>{img_path}</img> {question} Answer: '
|
120 |
+
print(query)
|
121 |
+
|
122 |
+
|
123 |
+
return _chatbot
|
124 |
+
|
125 |
+
def caption(_chatbot, task_history):
|
126 |
+
|
127 |
+
|
128 |
+
query = "Generate the detailed caption in English:"
|
129 |
+
chat_query = "Generate the detailed caption in English:"
|
130 |
+
question = _parse_text(query)
|
131 |
+
print("User: " + _parse_text(query))
|
132 |
+
|
133 |
+
full_response = ""
|
134 |
+
|
135 |
+
try:
|
136 |
+
img_path = _chatbot[0][0][0]
|
137 |
+
Image.open(img_path)
|
138 |
+
except:
|
139 |
+
response = "Please upload a picture."
|
140 |
+
|
141 |
+
_chatbot.append((None, response))
|
142 |
+
full_response = _parse_text(response)
|
143 |
+
|
144 |
+
task_history.append((None, full_response))
|
145 |
+
print("Monkey: " + _parse_text(full_response))
|
146 |
+
return _chatbot
|
147 |
+
img_path = _chatbot[0][0][0]
|
148 |
+
query = f'<img>{img_path}</img> {chat_query} '
|
149 |
+
print(query)
|
150 |
+
|
151 |
+
_chatbot.append((None, response))
|
152 |
+
full_response = _parse_text(response)
|
153 |
+
|
154 |
+
task_history.append((None, full_response))
|
155 |
+
print("Monkey: " + _parse_text(full_response))
|
156 |
+
return _chatbot
|
157 |
+
|
158 |
+
|
159 |
+
|
160 |
+
def add_text(history, task_history, text):
|
161 |
+
task_text = text
|
162 |
+
if len(text) >= 2 and text[-1] in PUNCTUATION and text[-2] not in PUNCTUATION:
|
163 |
+
task_text = text[:-1]
|
164 |
+
history = history + [(_parse_text(text), None)]
|
165 |
+
task_history = task_history + [(task_text, None)]
|
166 |
+
print(history, task_history, text)
|
167 |
+
return history, task_history, ""
|
168 |
+
|
169 |
+
def add_file(history, task_history, file):
|
170 |
+
history = [((file.name,), None)]
|
171 |
+
task_history = [((file.name,), None)]
|
172 |
+
print(history, task_history, file)
|
173 |
+
return history, task_history
|
174 |
+
|
175 |
+
def reset_user_input():
|
176 |
+
return gr.update(value="")
|
177 |
+
|
178 |
+
def reset_state(task_history):
|
179 |
+
task_history.clear()
|
180 |
+
return []
|
181 |
+
|
182 |
+
|
183 |
+
with gr.Blocks() as demo:
|
184 |
+
gr.Markdown(title_markdown)
|
185 |
+
|
186 |
+
chatbot = gr.Chatbot(label='Monkey', elem_classes="control-height", height=600,avatar_images=("https://ooo.0x0.ooo/2023/11/09/OehsLx.png","https://ooo.0x0.ooo/2023/11/09/OehGBC.png"),layout="bubble",bubble_full_width=False,show_copy_button=True)
|
187 |
+
query = gr.Textbox(lines=1, label='Input')
|
188 |
+
task_history = gr.State([])
|
189 |
+
|
190 |
+
with gr.Row():
|
191 |
+
empty_bin = gr.Button("Clear History (清空)")
|
192 |
+
submit_btn = gr.Button("Submit (提问)")
|
193 |
+
|
194 |
+
generate_btn_en = gr.Button("Generate")
|
195 |
+
addfile_btn = gr.UploadButton("Upload (上传图片)", file_types=["image"])
|
196 |
+
|
197 |
+
submit_btn.click(add_text, [chatbot, task_history, query], [chatbot, task_history]).then(
|
198 |
+
predict, [chatbot, task_history], [chatbot], show_progress=True
|
199 |
+
)
|
200 |
+
generate_btn_en.click(caption, [chatbot, task_history], [chatbot], show_progress=True)
|
201 |
+
|
202 |
+
submit_btn.click(reset_user_input, [], [query])
|
203 |
+
empty_bin.click(reset_state, [task_history], [chatbot], show_progress=True)
|
204 |
+
|
205 |
+
addfile_btn.upload(add_file, [chatbot, task_history, addfile_btn], [chatbot, task_history], show_progress=True,scroll_to_output=True)
|
206 |
+
|
207 |
+
|
208 |
+
|
209 |
+
gr.Markdown(policy_markdown)
|
210 |
+
demo.queue().launch(
|
211 |
+
server_name="0.0.0.0",
|
212 |
+
server_port=7681
|
213 |
+
)
|
214 |
+
|
215 |
+
|
216 |
+
def main():
|
217 |
+
|
218 |
+
_launch_demo()
|
219 |
+
|
220 |
+
|
221 |
+
if __name__ == '__main__':
|
222 |
+
main()
|