Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
@@ -1,5 +1,7 @@
|
|
1 |
import os
|
|
|
2 |
import uuid
|
|
|
3 |
import time
|
4 |
import asyncio
|
5 |
from threading import Thread
|
@@ -14,125 +16,190 @@ import cv2
|
|
14 |
from transformers import (
|
15 |
Qwen2_5_VLForConditionalGeneration,
|
16 |
AutoProcessor,
|
17 |
-
TextIteratorStreamer
|
18 |
)
|
|
|
19 |
|
20 |
-
# Constants
|
|
|
|
|
21 |
MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
|
|
|
22 |
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
23 |
|
24 |
# Load multimodal processor and model (Callisto OCR3)
|
25 |
MODEL_ID = "nvidia/Cosmos-Reason1-7B"
|
26 |
processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True)
|
27 |
-
|
28 |
MODEL_ID,
|
29 |
trust_remote_code=True,
|
30 |
torch_dtype=torch.float16
|
31 |
-
).to(
|
32 |
-
|
33 |
|
34 |
-
def downsample_video(video_path
|
|
|
|
|
|
|
|
|
35 |
vidcap = cv2.VideoCapture(video_path)
|
36 |
-
|
37 |
fps = vidcap.get(cv2.CAP_PROP_FPS)
|
38 |
-
idxs = np.linspace(0, total - 1, num_frames, dtype=int)
|
39 |
frames = []
|
40 |
-
|
|
|
|
|
41 |
vidcap.set(cv2.CAP_PROP_POS_FRAMES, i)
|
42 |
-
|
43 |
-
if
|
44 |
-
|
45 |
-
|
46 |
timestamp = round(i / fps, 2)
|
47 |
-
frames.append((
|
48 |
vidcap.release()
|
49 |
return frames
|
50 |
|
51 |
-
|
52 |
def progress_bar_html(label: str) -> str:
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
|
|
|
|
|
|
|
|
|
|
58 |
</div>
|
59 |
-
<style
|
|
|
|
|
|
|
|
|
|
|
|
|
60 |
|
61 |
@spaces.GPU
|
62 |
-
def generate(
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
|
68 |
-
if
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
{"type":"image","
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
89 |
streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
|
90 |
-
|
|
|
|
|
91 |
buffer = ""
|
92 |
-
|
93 |
-
|
|
|
|
|
94 |
time.sleep(0.01)
|
95 |
yield buffer
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
imgs = [Image.open(f) for f in files]
|
101 |
messages = [
|
102 |
-
{"role":"
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
109 |
streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
114 |
time.sleep(0.01)
|
115 |
-
yield
|
116 |
-
|
117 |
-
|
118 |
-
# No valid media
|
119 |
-
yield "Please upload at least one image or a video for inference."
|
120 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
121 |
|
122 |
-
|
123 |
-
demo = gr.ChatInterface(
|
124 |
fn=generate,
|
125 |
-
|
126 |
-
|
127 |
-
],
|
128 |
-
description="# **cosmos-reason1 by nvidia**",
|
129 |
-
textbox=gr.Textbox(label="Prompt"),
|
130 |
-
cache_examples=False,
|
131 |
-
type="messages",
|
132 |
-
multimodal=True,
|
133 |
-
stop_btn="Stop Generation"
|
134 |
)
|
135 |
-
demo.queue(max_size=10).launch(share=True)
|
136 |
|
137 |
if __name__ == "__main__":
|
138 |
-
|
|
|
1 |
import os
|
2 |
+
import random
|
3 |
import uuid
|
4 |
+
import json
|
5 |
import time
|
6 |
import asyncio
|
7 |
from threading import Thread
|
|
|
16 |
from transformers import (
|
17 |
Qwen2_5_VLForConditionalGeneration,
|
18 |
AutoProcessor,
|
19 |
+
TextIteratorStreamer,
|
20 |
)
|
21 |
+
from transformers.image_utils import load_image
|
22 |
|
23 |
+
# Constants for text generation
|
24 |
+
MAX_MAX_NEW_TOKENS = 2048
|
25 |
+
DEFAULT_MAX_NEW_TOKENS = 1024
|
26 |
MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
|
27 |
+
|
28 |
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
29 |
|
30 |
# Load multimodal processor and model (Callisto OCR3)
|
31 |
MODEL_ID = "nvidia/Cosmos-Reason1-7B"
|
32 |
processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True)
|
33 |
+
model_m = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
34 |
MODEL_ID,
|
35 |
trust_remote_code=True,
|
36 |
torch_dtype=torch.float16
|
37 |
+
).to("cuda").eval()
|
|
|
38 |
|
39 |
+
def downsample_video(video_path):
|
40 |
+
"""
|
41 |
+
Downsamples the video to 10 evenly spaced frames.
|
42 |
+
Each frame is returned as a PIL image along with its timestamp.
|
43 |
+
"""
|
44 |
vidcap = cv2.VideoCapture(video_path)
|
45 |
+
total_frames = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
|
46 |
fps = vidcap.get(cv2.CAP_PROP_FPS)
|
|
|
47 |
frames = []
|
48 |
+
# Sample 10 evenly spaced frames.
|
49 |
+
frame_indices = np.linspace(0, total_frames - 1, 10, dtype=int)
|
50 |
+
for i in frame_indices:
|
51 |
vidcap.set(cv2.CAP_PROP_POS_FRAMES, i)
|
52 |
+
success, image = vidcap.read()
|
53 |
+
if success:
|
54 |
+
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # Convert BGR to RGB
|
55 |
+
pil_image = Image.fromarray(image)
|
56 |
timestamp = round(i / fps, 2)
|
57 |
+
frames.append((pil_image, timestamp))
|
58 |
vidcap.release()
|
59 |
return frames
|
60 |
|
|
|
61 |
def progress_bar_html(label: str) -> str:
|
62 |
+
"""
|
63 |
+
Returns an HTML snippet for a thin progress bar with a label.
|
64 |
+
The progress bar is styled as a light cyan animated bar.
|
65 |
+
"""
|
66 |
+
return f'''
|
67 |
+
<div style="display: flex; align-items: center;">
|
68 |
+
<span style="margin-right: 10px; font-size: 14px;">{label}</span>
|
69 |
+
<div style="width: 110px; height: 5px; background-color: #B0E0E6; border-radius: 2px; overflow: hidden;">
|
70 |
+
<div style="width: 100%; height: 100%; background-color: #00FFFF; animation: loading 1.5s linear infinite;"></div>
|
71 |
+
</div>
|
72 |
</div>
|
73 |
+
<style>
|
74 |
+
@keyframes loading {{
|
75 |
+
0% {{ transform: translateX(-100%); }}
|
76 |
+
100% {{ transform: translateX(100%); }}
|
77 |
+
}}
|
78 |
+
</style>
|
79 |
+
'''
|
80 |
|
81 |
@spaces.GPU
|
82 |
+
def generate(text: str, files: list,
|
83 |
+
max_new_tokens: int = 1024,
|
84 |
+
temperature: float = 0.6,
|
85 |
+
top_p: float = 0.9,
|
86 |
+
top_k: int = 50,
|
87 |
+
repetition_penalty: float = 1.2):
|
88 |
+
"""
|
89 |
+
Generates responses using the Qwen2VL model for image and video inputs.
|
90 |
+
- If images are provided, performs image inference.
|
91 |
+
- If videos are provided, performs video inference by downsampling to frames.
|
92 |
+
"""
|
93 |
+
if not files:
|
94 |
+
yield "Please upload an image or video for inference."
|
95 |
+
return
|
96 |
|
97 |
+
# Determine if the files are images or videos
|
98 |
+
image_files = [f for f in files if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif'))]
|
99 |
+
video_files = [f for f in files if f.lower().endswith(('.mp4', '.avi', '.mov', '.mkv'))]
|
100 |
+
|
101 |
+
if image_files and video_files:
|
102 |
+
yield "Please upload either images or videos, not both."
|
103 |
+
return
|
104 |
+
|
105 |
+
if image_files:
|
106 |
+
# Image inference
|
107 |
+
images = [load_image(image) for image in image_files]
|
108 |
+
messages = [{
|
109 |
+
"role": "user",
|
110 |
+
"content": [
|
111 |
+
*[{"type": "image", "image": image} for image in images],
|
112 |
+
{"type": "text", "text": text},
|
113 |
+
]
|
114 |
+
}]
|
115 |
+
prompt_full = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
116 |
+
inputs = processor(
|
117 |
+
text=[prompt_full],
|
118 |
+
images=images,
|
119 |
+
return_tensors="pt",
|
120 |
+
padding=True,
|
121 |
+
truncation=True,
|
122 |
+
max_length=MAX_INPUT_TOKEN_LENGTH
|
123 |
+
).to("cuda")
|
124 |
streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
|
125 |
+
generation_kwargs = {**inputs, "streamer": streamer, "max_new_tokens": max_new_tokens}
|
126 |
+
thread = Thread(target=model_m.generate, kwargs=generation_kwargs)
|
127 |
+
thread.start()
|
128 |
buffer = ""
|
129 |
+
yield progress_bar_html("Processing images with cosmos-reasoning")
|
130 |
+
for new_text in streamer:
|
131 |
+
buffer += new_text
|
132 |
+
buffer = buffer.replace("<|im_end|>", "")
|
133 |
time.sleep(0.01)
|
134 |
yield buffer
|
135 |
+
elif video_files:
|
136 |
+
# Video inference
|
137 |
+
video_path = video_files[0] # Assuming only one video is uploaded
|
138 |
+
frames = downsample_video(video_path)
|
|
|
139 |
messages = [
|
140 |
+
{"role": "system", "content": [{"type": "text", "text": "You are a helpful assistant."}]},
|
141 |
+
{"role": "user", "content": [{"type": "text", "text": text}]}
|
142 |
+
]
|
143 |
+
# Append each frame with its timestamp.
|
144 |
+
for frame in frames:
|
145 |
+
image, timestamp = frame
|
146 |
+
image_path = f"video_frame_{uuid.uuid4().hex}.png"
|
147 |
+
image.save(image_path)
|
148 |
+
messages[1]["content"].append({"type": "text", "text": f"Frame {timestamp}:"})
|
149 |
+
messages[1]["content"].append({"type": "image", "url": image_path})
|
150 |
+
inputs = processor.apply_chat_template(
|
151 |
+
messages,
|
152 |
+
tokenize=True,
|
153 |
+
add_generation_prompt=True,
|
154 |
+
return_dict=True,
|
155 |
+
return_tensors="pt",
|
156 |
+
truncation=True,
|
157 |
+
max_length=MAX_INPUT_TOKEN_LENGTH
|
158 |
+
).to("cuda")
|
159 |
streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
|
160 |
+
generation_kwargs = {
|
161 |
+
**inputs,
|
162 |
+
"streamer": streamer,
|
163 |
+
"max_new_tokens": max_new_tokens,
|
164 |
+
"do_sample": True,
|
165 |
+
"temperature": temperature,
|
166 |
+
"top_p": top_p,
|
167 |
+
"top_k": top_k,
|
168 |
+
"repetition_penalty": repetition_penalty,
|
169 |
+
}
|
170 |
+
thread = Thread(target=model_m.generate, kwargs=generation_kwargs)
|
171 |
+
thread.start()
|
172 |
+
buffer = ""
|
173 |
+
yield progress_bar_html("Processing video with cosmos-reasoning")
|
174 |
+
for new_text in streamer:
|
175 |
+
buffer += new_text
|
176 |
+
buffer = buffer.replace("<|im_end|>", "")
|
177 |
time.sleep(0.01)
|
178 |
+
yield buffer
|
179 |
+
else:
|
180 |
+
yield "Unsupported file type. Please upload images or videos."
|
|
|
|
|
181 |
|
182 |
+
# Create the Gradio Interface
|
183 |
+
with gr.Blocks() as demo:
|
184 |
+
gr.Markdown("# **cosmos-reason1 by nvidia**")
|
185 |
+
with gr.Row():
|
186 |
+
with gr.Column():
|
187 |
+
text_input = gr.Textbox(label="Query Input", placeholder="Enter your query here...")
|
188 |
+
file_input = gr.File(label="Upload Image or Video", file_types=["image", "video"], file_count="multiple")
|
189 |
+
max_new_tokens = gr.Slider(label="Max new tokens", minimum=1, maximum=MAX_MAX_NEW_TOKENS, step=1, value=DEFAULT_MAX_NEW_TOKENS)
|
190 |
+
temperature = gr.Slider(label="Temperature", minimum=0.1, maximum=4.0, step=0.1, value=0.6)
|
191 |
+
top_p = gr.Slider(label="Top-p (nucleus sampling)", minimum=0.05, maximum=1.0, step=0.05, value=0.9)
|
192 |
+
top_k = gr.Slider(label="Top-k", minimum=1, maximum=1000, step=1, value=50)
|
193 |
+
repetition_penalty = gr.Slider(label="Repetition penalty", minimum=1.0, maximum=2.0, step=0.05, value=1.2)
|
194 |
+
submit_btn = gr.Button("Submit")
|
195 |
+
with gr.Column():
|
196 |
+
output = gr.Textbox(label="Output", interactive=False)
|
197 |
|
198 |
+
submit_btn.click(
|
|
|
199 |
fn=generate,
|
200 |
+
inputs=[text_input, file_input, max_new_tokens, temperature, top_p, top_k, repetition_penalty],
|
201 |
+
outputs=output
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
202 |
)
|
|
|
203 |
|
204 |
if __name__ == "__main__":
|
205 |
+
demo.queue(max_size=20).launch(share=True)
|