Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,64 +1,233 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) Kuaishou.
|
2 |
+
#
|
3 |
+
# This source code is licensed under the license found in the
|
4 |
+
# LICENSE file in the root directory of this source tree.
|
5 |
+
import os
|
6 |
+
import base64
|
7 |
+
import numpy as np
|
8 |
+
os.system('pip install huggingface_hub gradio openai keye_vl_utils -U')
|
9 |
+
|
10 |
+
from argparse import ArgumentParser
|
11 |
+
from pathlib import Path
|
12 |
+
|
13 |
+
import copy
|
14 |
import gradio as gr
|
15 |
+
import os
|
16 |
+
import re
|
17 |
+
import tempfile
|
18 |
+
from openai import OpenAI
|
19 |
+
from PIL import Image
|
20 |
+
from io import BytesIO
|
21 |
+
from keye_vl_utils import fetch_video, process_vision_info
|
22 |
+
|
23 |
+
|
24 |
+
def _get_args():
|
25 |
+
parser = ArgumentParser()
|
26 |
+
parser.add_argument("--share", action="store_true", default=False,
|
27 |
+
help="Create a publicly shareable link for the interface.")
|
28 |
+
parser.add_argument("--inbrowser", action="store_true", default=False,
|
29 |
+
help="Automatically launch the interface in a new tab on the default browser.")
|
30 |
+
parser.add_argument("--server-port", type=int, default=7860,
|
31 |
+
help="Demo server port.")
|
32 |
+
parser.add_argument("--server-name", type=str, default="127.0.0.1",
|
33 |
+
help="Demo server name.")
|
34 |
+
args = parser.parse_args()
|
35 |
+
return args
|
36 |
+
|
37 |
+
|
38 |
+
def _parse_text(text):
|
39 |
+
lines = text.split("\n")
|
40 |
+
lines = [line for line in lines if line != ""]
|
41 |
+
count = 0
|
42 |
+
for i, line in enumerate(lines):
|
43 |
+
line = line.replace("<think>", "**ζθθΏη¨εΌε§**οΌ\n")
|
44 |
+
line = line.replace("</think>", "\n**ζθθΏη¨η»ζ**\n")
|
45 |
+
line = line.replace("<answer>", "**εηεΌε§**οΌ\n")
|
46 |
+
line = line.replace("</answer>", "\n**εηη»ζ**\n")
|
47 |
+
line = line.replace("<analysis>", "**εζεΌε§**οΌ\n")
|
48 |
+
line = line.replace("</analysis>", "\n**εζη»ζ**\n")
|
49 |
+
if "```" in line:
|
50 |
+
count += 1
|
51 |
+
items = line.split("`")
|
52 |
+
if count % 2 == 1:
|
53 |
+
lines[i] = f'<pre><code class="language-{items[-1]}">'
|
54 |
+
else:
|
55 |
+
lines[i] = f"<br></code></pre>"
|
56 |
+
else:
|
57 |
+
if True or i > 0:
|
58 |
+
if count % 2 == 1:
|
59 |
+
line = line.replace("`", r"\`")
|
60 |
+
line = line.replace("<", "<")
|
61 |
+
line = line.replace(">", ">")
|
62 |
+
line = line.replace(" ", " ")
|
63 |
+
line = line.replace("*", "*")
|
64 |
+
line = line.replace("_", "_")
|
65 |
+
line = line.replace("-", "-")
|
66 |
+
line = line.replace(".", ".")
|
67 |
+
line = line.replace("!", "!")
|
68 |
+
line = line.replace("(", "(")
|
69 |
+
line = line.replace(")", ")")
|
70 |
+
line = line.replace("$", "$")
|
71 |
+
lines[i] = "<br>" + line
|
72 |
+
text = "".join(lines)
|
73 |
+
return text
|
74 |
+
|
75 |
+
|
76 |
+
def is_video_file(filename):
|
77 |
+
video_extensions = ['.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv', '.webm', '.mpeg']
|
78 |
+
return any(filename.lower().endswith(ext) for ext in video_extensions)
|
79 |
+
|
80 |
+
|
81 |
+
def video_processor(video_path):
|
82 |
+
video_inputs, video_sample_fps = fetch_video({"video": video_path, "max_frames": 8, "max_pixels": 256*28*28}, return_video_sample_fps=True)
|
83 |
+
video_input = video_inputs.permute(0, 2, 3, 1).numpy().astype(np.uint8)
|
84 |
+
|
85 |
+
# encode image with base64
|
86 |
+
base64_frames = []
|
87 |
+
for frame in video_input:
|
88 |
+
img = Image.fromarray(frame)
|
89 |
+
output_buffer = BytesIO()
|
90 |
+
img.save(output_buffer, format="jpeg")
|
91 |
+
byte_data = output_buffer.getvalue()
|
92 |
+
base64_str = base64.b64encode(byte_data).decode("utf-8")
|
93 |
+
base64_frames.append(base64_str)
|
94 |
+
|
95 |
+
video_info = {
|
96 |
+
"type": "video_url",
|
97 |
+
"video_url": {"url": f"data:video/jpeg;base64,{','.join(base64_frames)}"}
|
98 |
+
}
|
99 |
+
return video_info
|
100 |
+
|
101 |
+
|
102 |
+
def _launch_demo(args):
|
103 |
+
EP_URL = os.getenv("ENDPOINT_URL")
|
104 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
105 |
+
client = OpenAI(
|
106 |
+
base_url=f"{EP_URL}/v1/",
|
107 |
+
api_key=HF_TOKEN
|
108 |
+
)
|
109 |
+
|
110 |
+
def predict(_chatbot, task_history):
|
111 |
+
chat_query = _chatbot[-1][0]
|
112 |
+
query = task_history[-1][0]
|
113 |
+
if len(chat_query) == 0:
|
114 |
+
_chatbot.pop()
|
115 |
+
task_history.pop()
|
116 |
+
return _chatbot
|
117 |
+
print("User: " + _parse_text(query))
|
118 |
+
history_cp = copy.deepcopy(task_history)
|
119 |
+
full_response = ""
|
120 |
+
messages = []
|
121 |
+
content = []
|
122 |
+
for q, a in history_cp:
|
123 |
+
if isinstance(q, (tuple, list)):
|
124 |
+
if is_video_file(q[0]):
|
125 |
+
video_info = video_processor(q[0])
|
126 |
+
content.append(video_info)
|
127 |
+
else:
|
128 |
+
# convert image to base64
|
129 |
+
with open(q[0], 'rb') as img_file:
|
130 |
+
img_base64 = base64.b64encode(img_file.read()).decode('utf-8')
|
131 |
+
content.append({'type': 'image_url', 'image_url': {"url": f"data:image/jpeg;base64,{img_base64}"}})
|
132 |
+
else:
|
133 |
+
content.append({'type': 'text', 'text': q})
|
134 |
+
messages.append({'role': 'user', 'content': content})
|
135 |
+
messages.append({'role': 'assistant', 'content': [{'type': 'text', 'text': a}]})
|
136 |
+
content = []
|
137 |
+
messages.pop()
|
138 |
+
|
139 |
+
responses = client.chat.completions.create(
|
140 |
+
model="Kwai-Keye/Keye-VL-8B-Preview",
|
141 |
+
messages=messages,
|
142 |
+
top_p=0.95,
|
143 |
+
temperature=0.6,
|
144 |
+
stream=True,
|
145 |
+
timeout=360
|
146 |
+
)
|
147 |
+
response_text = ""
|
148 |
+
for response in responses:
|
149 |
+
response = response.choices[0].delta.content
|
150 |
+
response_text += response
|
151 |
+
_chatbot[-1] = (chat_query, _parse_text(response_text))
|
152 |
+
yield _chatbot
|
153 |
+
|
154 |
+
response = response_text
|
155 |
+
_chatbot[-1] = (chat_query, _parse_text(response))
|
156 |
+
full_response = _parse_text(response)
|
157 |
+
|
158 |
+
task_history[-1] = (query, full_response)
|
159 |
+
print("Kwai-Keye-VL-Chat: " + full_response)
|
160 |
+
yield _chatbot
|
161 |
+
|
162 |
+
|
163 |
+
def regenerate(_chatbot, task_history):
|
164 |
+
if not task_history:
|
165 |
+
return _chatbot
|
166 |
+
item = task_history[-1]
|
167 |
+
if item[1] is None:
|
168 |
+
return _chatbot
|
169 |
+
task_history[-1] = (item[0], None)
|
170 |
+
chatbot_item = _chatbot.pop(-1)
|
171 |
+
if chatbot_item[0] is None:
|
172 |
+
_chatbot[-1] = (_chatbot[-1][0], None)
|
173 |
+
else:
|
174 |
+
_chatbot.append((chatbot_item[0], None))
|
175 |
+
_chatbot_gen = predict(_chatbot, task_history)
|
176 |
+
for _chatbot in _chatbot_gen:
|
177 |
+
yield _chatbot
|
178 |
+
|
179 |
+
def add_text(history, task_history, text):
|
180 |
+
task_text = text
|
181 |
+
history = history if history is not None else []
|
182 |
+
task_history = task_history if task_history is not None else []
|
183 |
+
history = history + [(_parse_text(text), None)]
|
184 |
+
task_history = task_history + [(task_text, None)]
|
185 |
+
return history, task_history, ""
|
186 |
+
|
187 |
+
def add_file(history, task_history, file):
|
188 |
+
history = history if history is not None else []
|
189 |
+
task_history = task_history if task_history is not None else []
|
190 |
+
history = history + [((file.name,), None)]
|
191 |
+
task_history = task_history + [((file.name,), None)]
|
192 |
+
return history, task_history
|
193 |
+
|
194 |
+
def reset_user_input():
|
195 |
+
return gr.update(value="")
|
196 |
+
|
197 |
+
def reset_state(task_history):
|
198 |
+
task_history.clear()
|
199 |
+
return []
|
200 |
+
|
201 |
+
with gr.Blocks() as demo:
|
202 |
+
gr.Markdown("""<center><font size=3> Kwai-Keye-VL Demo </center>""")
|
203 |
+
|
204 |
+
chatbot = gr.Chatbot(label='Kwai-Keye-VL', elem_classes="control-height", height=500)
|
205 |
+
query = gr.Textbox(lines=2, label='Input')
|
206 |
+
task_history = gr.State([])
|
207 |
+
|
208 |
+
with gr.Row():
|
209 |
+
addfile_btn = gr.UploadButton("π Upload (δΈδΌ ζδ»Ά)", file_types=["image", "video"])
|
210 |
+
submit_btn = gr.Button("π Submit (ει)")
|
211 |
+
regen_btn = gr.Button("π€οΈ Regenerate (ιθ―)")
|
212 |
+
empty_bin = gr.Button("π§Ή Clear History (ζΈ
ι€εε²)")
|
213 |
+
|
214 |
+
submit_btn.click(add_text, [chatbot, task_history, query], [chatbot, task_history]).then(
|
215 |
+
predict, [chatbot, task_history], [chatbot], show_progress=True
|
216 |
+
)
|
217 |
+
submit_btn.click(reset_user_input, [], [query])
|
218 |
+
empty_bin.click(reset_state, [task_history], [chatbot], show_progress=True)
|
219 |
+
regen_btn.click(regenerate, [chatbot, task_history], [chatbot], show_progress=True)
|
220 |
+
addfile_btn.upload(add_file, [chatbot, task_history, addfile_btn], [chatbot, task_history], show_progress=True)
|
221 |
+
|
222 |
+
demo.queue(default_concurrency_limit=40).launch(
|
223 |
+
share=args.share,
|
224 |
+
)
|
225 |
+
|
226 |
+
|
227 |
+
def main():
|
228 |
+
args = _get_args()
|
229 |
+
_launch_demo(args)
|
230 |
+
|
231 |
+
|
232 |
+
if __name__ == '__main__':
|
233 |
+
main()
|