Spaces:
Running
on
Zero
Running
on
Zero
Add VideoLLaMA3 interface
Browse files
app.py
CHANGED
@@ -1,64 +1,176 @@
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
-
|
|
|
|
|
|
|
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 |
-
|
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 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
|
|
|
|
|
|
|
|
|
|
25 |
|
26 |
-
|
|
|
|
|
|
|
27 |
|
28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
temperature=temperature,
|
35 |
-
top_p=top_p,
|
36 |
-
):
|
37 |
-
token = message.choices[0].delta.content
|
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 |
if __name__ == "__main__":
|
64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import os.path as osp
|
3 |
+
|
4 |
import gradio as gr
|
5 |
+
import spaces
|
6 |
+
import torch
|
7 |
+
from threading import Thread
|
8 |
+
from transformers import AutoModelForCausalLM, AutoProcessor, TextIteratorStreamer
|
9 |
|
10 |
+
HEADER = """
|
11 |
"""
|
|
|
|
|
|
|
12 |
|
13 |
|
14 |
+
class VideoLLaMA3GradioInterface(object):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
|
16 |
+
def __init__(self, model_name, device="cpu", example_dir=None, **server_kwargs):
|
17 |
+
self.device = device
|
18 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
19 |
+
model_name,
|
20 |
+
trust_remote_code=True,
|
21 |
+
torch_dtype=torch.bfloat16,
|
22 |
+
attn_implementation="flash_attention_2",
|
23 |
+
)
|
24 |
+
self.model.to(self.device)
|
25 |
+
self.processor = AutoProcessor.from_pretrained(model_name, trust_remote_code=True)
|
26 |
|
27 |
+
self.server_kwargs = server_kwargs
|
28 |
+
|
29 |
+
self.image_formats = ("png", "jpg", "jpeg")
|
30 |
+
self.video_formats = ("mp4",)
|
31 |
|
32 |
+
image_examples, video_examples = [], []
|
33 |
+
if example_dir is not None:
|
34 |
+
example_files = [
|
35 |
+
osp.join(example_dir, f) for f in os.listdir(example_dir)
|
36 |
+
]
|
37 |
+
for example_file in example_files:
|
38 |
+
if example_file.endswith(self.image_formats):
|
39 |
+
image_examples.append([example_file])
|
40 |
+
elif example_file.endswith(self.video_formats):
|
41 |
+
video_examples.append([example_file])
|
42 |
|
43 |
+
with gr.Blocks() as self.interface:
|
44 |
+
gr.Markdown(HEADER)
|
45 |
+
with gr.Row():
|
46 |
+
chatbot = gr.Chatbot(type="messages", elem_id="chatbot", height=710)
|
|
|
|
|
|
|
|
|
47 |
|
48 |
+
with gr.Column():
|
49 |
+
with gr.Tab(label="Input"):
|
50 |
|
51 |
+
with gr.Row():
|
52 |
+
input_video = gr.Video(sources=["upload"], label="Upload Video")
|
53 |
+
input_image = gr.Image(sources=["upload"], type="filepath", label="Upload Image")
|
54 |
|
55 |
+
if len(image_examples):
|
56 |
+
gr.Examples(image_examples, inputs=[input_image], label="Example Images")
|
57 |
+
if len(video_examples):
|
58 |
+
gr.Examples(video_examples, inputs=[input_video], label="Example Videos")
|
59 |
+
|
60 |
+
input_text = gr.Textbox(label="Input Text", placeholder="Type your message here and press enter to submit")
|
61 |
+
|
62 |
+
submit_button = gr.Button("Generate")
|
63 |
+
|
64 |
+
with gr.Tab(label="Configure"):
|
65 |
+
with gr.Accordion("Generation Config", open=True):
|
66 |
+
do_sample = gr.Checkbox(value=True, label="Do Sample")
|
67 |
+
temperature = gr.Slider(minimum=0.0, maximum=1.0, value=0.2, label="Temperature")
|
68 |
+
top_p = gr.Slider(minimum=0.0, maximum=1.0, value=0.9, label="Top P")
|
69 |
+
max_new_tokens = gr.Slider(minimum=0, maximum=4096, value=2048, step=1, label="Max New Tokens")
|
70 |
+
|
71 |
+
with gr.Accordion("Video Config", open=True):
|
72 |
+
fps = gr.Slider(minimum=0.0, maximum=10.0, value=1, label="FPS")
|
73 |
+
max_frames = gr.Slider(minimum=0, maximum=256, value=180, step=1, label="Max Frames")
|
74 |
+
|
75 |
+
input_video.change(self._on_video_upload, [chatbot, input_video], [chatbot, input_video])
|
76 |
+
input_image.change(self._on_image_upload, [chatbot, input_image], [chatbot, input_image])
|
77 |
+
input_text.submit(self._on_text_submit, [chatbot, input_text], [chatbot, input_text])
|
78 |
+
submit_button.click(
|
79 |
+
self._predict,
|
80 |
+
[
|
81 |
+
chatbot, input_text, do_sample, temperature, top_p, max_new_tokens,
|
82 |
+
fps, max_frames
|
83 |
+
],
|
84 |
+
[chatbot],
|
85 |
+
)
|
86 |
+
|
87 |
+
def _on_video_upload(self, messages, video):
|
88 |
+
if video is not None:
|
89 |
+
# messages.append({"role": "user", "content": gr.Video(video)})
|
90 |
+
messages.append({"role": "user", "content": {"path": video}})
|
91 |
+
return messages, None
|
92 |
+
|
93 |
+
def _on_image_upload(self, messages, image):
|
94 |
+
if image is not None:
|
95 |
+
# messages.append({"role": "user", "content": gr.Image(image)})
|
96 |
+
messages.append({"role": "user", "content": {"path": image}})
|
97 |
+
return messages, None
|
98 |
+
|
99 |
+
def _on_text_submit(self, messages, text):
|
100 |
+
messages.append({"role": "user", "content": text})
|
101 |
+
return messages, ""
|
102 |
+
|
103 |
+
@spaces.GPU(duration=120)
|
104 |
+
def _predict(self, messages, input_text, do_sample, temperature, top_p, max_new_tokens,
|
105 |
+
fps, max_frames):
|
106 |
+
if len(input_text) > 0:
|
107 |
+
messages.append({"role": "user", "content": input_text})
|
108 |
+
new_messages = []
|
109 |
+
contents = []
|
110 |
+
for message in messages:
|
111 |
+
if message["role"] == "assistant":
|
112 |
+
if len(contents):
|
113 |
+
new_messages.append({"role": "user", "content": contents})
|
114 |
+
contents = []
|
115 |
+
new_messages.append(message)
|
116 |
+
elif message["role"] == "user":
|
117 |
+
if isinstance(message["content"], str):
|
118 |
+
contents.append(message["content"])
|
119 |
+
else:
|
120 |
+
media_path = message["content"][0]
|
121 |
+
if media_path.endswith(self.video_formats):
|
122 |
+
contents.append({"type": "video", "video": {"video_path": media_path, "fps": fps, "max_frames": max_frames}})
|
123 |
+
elif media_path.endswith(self.image_formats):
|
124 |
+
contents.append({"type": "image", "image": {"image_path": media_path}})
|
125 |
+
else:
|
126 |
+
raise ValueError(f"Unsupported media type: {media_path}")
|
127 |
+
|
128 |
+
if len(contents):
|
129 |
+
new_messages.append({"role": "user", "content": contents})
|
130 |
+
|
131 |
+
if len(new_messages) == 0 or new_messages[-1]["role"] != "user":
|
132 |
+
return messages
|
133 |
+
|
134 |
+
generation_config = {
|
135 |
+
"do_sample": do_sample,
|
136 |
+
"temperature": temperature,
|
137 |
+
"top_p": top_p,
|
138 |
+
"max_new_tokens": max_new_tokens
|
139 |
+
}
|
140 |
+
|
141 |
+
inputs = self.processor(
|
142 |
+
conversation=new_messages,
|
143 |
+
add_system_prompt=True,
|
144 |
+
add_generation_prompt=True,
|
145 |
+
return_tensors="pt"
|
146 |
+
)
|
147 |
+
inputs = {k: v.to(self.device) if isinstance(v, torch.Tensor) else v for k, v in inputs.items()}
|
148 |
+
if "pixel_values" in inputs:
|
149 |
+
inputs["pixel_values"] = inputs["pixel_values"].to(torch.bfloat16)
|
150 |
+
|
151 |
+
streamer = TextIteratorStreamer(self.processor.tokenizer, skip_prompt=True, skip_special_tokens=True)
|
152 |
+
generation_kwargs = {
|
153 |
+
**inputs,
|
154 |
+
**generation_config,
|
155 |
+
"streamer": streamer,
|
156 |
+
}
|
157 |
+
|
158 |
+
thread = Thread(target=self.model.generate, kwargs=generation_kwargs)
|
159 |
+
thread.start()
|
160 |
+
|
161 |
+
messages.append({"role": "assistant", "content": ""})
|
162 |
+
for token in streamer:
|
163 |
+
messages[-1]['content'] += token
|
164 |
+
yield messages
|
165 |
+
|
166 |
+
def launch(self):
|
167 |
+
self.interface.launch(**self.server_kwargs)
|
168 |
|
169 |
|
170 |
if __name__ == "__main__":
|
171 |
+
interface = VideoLLaMA3GradioInterface(
|
172 |
+
model_name="DAMO-NLP-SG/VideoLLaMA3-7B",
|
173 |
+
device="cuda",
|
174 |
+
example_dir="./examples",
|
175 |
+
)
|
176 |
+
interface.launch()
|