Kwai-Keye commited on
Commit
627030b
Β·
verified Β·
1 Parent(s): 32b91a2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +232 -63
app.py CHANGED
@@ -1,64 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
-
62
-
63
- if __name__ == "__main__":
64
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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("<", "&lt;")
61
+ line = line.replace(">", "&gt;")
62
+ line = line.replace(" ", "&nbsp;")
63
+ line = line.replace("*", "&ast;")
64
+ line = line.replace("_", "&lowbar;")
65
+ line = line.replace("-", "&#45;")
66
+ line = line.replace(".", "&#46;")
67
+ line = line.replace("!", "&#33;")
68
+ line = line.replace("(", "&#40;")
69
+ line = line.replace(")", "&#41;")
70
+ line = line.replace("$", "&#36;")
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()