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