Spaces:
Running on Zero

NicolasCC commited on
Commit
f32e31f
·
verified ·
1 Parent(s): 2f36ebe

Deploy CameraVLM demo

Browse files
Files changed (4) hide show
  1. .gitignore +2 -0
  2. README.md +10 -6
  3. app.py +230 -0
  4. requirements.txt +12 -0
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ __pycache__/
2
+ .gradio/
README.md CHANGED
@@ -1,13 +1,17 @@
1
  ---
2
  title: CameraVLM
3
- emoji: 🐨
4
- colorFrom: green
5
- colorTo: pink
6
  sdk: gradio
7
- sdk_version: 6.30.0
8
- python_version: '3.13'
9
  app_file: app.py
10
  pinned: false
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
1
  ---
2
  title: CameraVLM
 
 
 
3
  sdk: gradio
4
+ sdk_version: 6.29.0
5
+ python_version: "3.12"
6
  app_file: app.py
7
  pinned: false
8
+ short_description: Video QA with camera poses and point tracks
9
  ---
10
 
11
+ # CameraVLM
12
+
13
+ Online demo and API of CameraVLM, a video language model that jointly answers questions about a video, estimates a per-frame camera trajectory, and tracks a dense grid of points.
14
+
15
+ API usage and documentation: https://github.com/nicolascc1/CameraVLM
16
+
17
+ Code and model weights will be open-sourced upon acceptance of the paper.
app.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import sys
4
+ import tempfile
5
+
6
+ import gradio as gr
7
+ import numpy as np
8
+ import spaces
9
+ from huggingface_hub import snapshot_download
10
+
11
+ MODEL_REPO = os.environ.get("CAMERAVLM_REPO", "NicolasCC/CameraVLM-9B")
12
+ MAX_FRAMES = 128
13
+ CHAT_HEIGHT = 380
14
+ GEOMETRY_FIELDS = ("extrinsics", "camera_to_world", "intrinsics", "pose_encoding", "tracks", "track_visibility")
15
+
16
+ # Weights and the `cameravlm` package live in a private model repo and are downloaded at runtime
17
+ # (never at build time), so they are not part of this Space's files or its Docker image.
18
+ model_dir = snapshot_download(MODEL_REPO, token=os.environ["HF_TOKEN"])
19
+ sys.path.insert(0, model_dir)
20
+
21
+ from cameravlm import CAMERA_MOTION_PROMPT, CameraVLM # noqa: E402
22
+
23
+ model = CameraVLM.from_pretrained(model_dir, device="cuda", attn_implementation="sdpa")
24
+
25
+
26
+ def gpu_duration(video, prompt, num_frames):
27
+ return int(30 + 0.7 * num_frames) # ~120 s at 128 frames; calibrate after deployment
28
+
29
+
30
+ @spaces.GPU(duration=gpu_duration)
31
+ def run_model(video, prompt, num_frames):
32
+ return model(video, prompt=prompt, num_frames=num_frames)
33
+
34
+
35
+ def infer(video, task, prompt, num_frames):
36
+ if not video:
37
+ raise gr.Error("Please upload a video first.")
38
+ if task == "camera_motion":
39
+ prompt = CAMERA_MOTION_PROMPT
40
+ elif not (prompt or "").strip():
41
+ raise gr.Error("Please enter a question.")
42
+ try:
43
+ return run_model(video, prompt, max(2, min(int(num_frames), MAX_FRAMES)))
44
+ except Exception as error:
45
+ # Log only the error type and message: tracebacks would expose source lines of the private code.
46
+ print(f"Inference failed: {type(error).__name__}: {error}", flush=True)
47
+ raise gr.Error("Inference failed on this video.") from None
48
+
49
+
50
+ def predict(video, task, prompt, num_frames):
51
+ """API endpoint: the answer plus camera poses and point tracks as an .npz file."""
52
+ result = infer(video, task, prompt, num_frames)
53
+ path = tempfile.NamedTemporaryFile(prefix="cameravlm_", suffix=".npz", delete=False).name
54
+ groups = [list(group) + [group[-1]] * (2 - len(group)) for group in result.track_group_frames] # odd frame count
55
+ np.savez_compressed(
56
+ path,
57
+ **{name: np.asarray(getattr(result, name), dtype=np.float32) for name in GEOMETRY_FIELDS},
58
+ frame_indices=np.asarray(result.frame_indices), timestamps=np.asarray(result.timestamps),
59
+ image_size=np.asarray(result.image_size), track_group_frames=np.asarray(groups),
60
+ track_window_starts=np.asarray(result.track_window_starts),
61
+ )
62
+ return result.text, path
63
+
64
+
65
+ # ---------- chat UI ----------
66
+
67
+ def show_chat(history):
68
+ """The upload box is shown until a video is attached; afterwards the conversation is shown."""
69
+ return gr.Chatbot(value=history, visible=bool(history)), gr.Video(value=None, visible=not history)
70
+
71
+
72
+ def upload_video(history, video):
73
+ if not video:
74
+ return (*show_chat(history), None)
75
+ history = history + [{"role": "user", "content": {"path": video}}]
76
+ return (*show_chat(history), video)
77
+
78
+
79
+ def add_message(history, video, message):
80
+ """Appends the attached video (if any) and the question; a new video replaces the current one."""
81
+ files, text = message.get("files") or [], (message.get("text") or "").strip()
82
+ if files:
83
+ video = files[-1]
84
+ history = history + [{"role": "user", "content": {"path": video}}]
85
+ request = None
86
+ if text:
87
+ if video:
88
+ history = history + [{"role": "user", "content": text}]
89
+ request = ("question", text)
90
+ else:
91
+ gr.Warning("Please upload a video first.")
92
+ return (*show_chat(history), video, request, gr.MultimodalTextbox(value=None if request or files else message))
93
+
94
+
95
+ def add_camera_motion(history, video, message):
96
+ chat, upload, video, _, cleared = add_message(history, video, {"files": (message or {}).get("files")})
97
+ if not video:
98
+ gr.Warning("Please upload a video first.")
99
+ return chat, upload, video, None, cleared
100
+ history = chat.value + [{"role": "user", "content": "Describe the camera motion."}]
101
+ return (*show_chat(history), video, ("camera_motion", ""), cleared)
102
+
103
+
104
+ def respond(history, video, request, num_frames):
105
+ if request is None:
106
+ return history
107
+ task, prompt = request
108
+ try:
109
+ text = infer(video, task, prompt, num_frames).text
110
+ except gr.Error as error:
111
+ text = f"**Error:** {error.message}"
112
+ else:
113
+ if task == "camera_motion":
114
+ try:
115
+ parsed = json.loads(text[text.index("{"):text.rindex("}") + 1])
116
+ text = "```json\n" + json.dumps(parsed, indent=2, ensure_ascii=False) + "\n```"
117
+ except ValueError:
118
+ pass
119
+ return history + [{"role": "assistant", "content": text}]
120
+
121
+
122
+ def drop_last_answer(history):
123
+ while history and history[-1]["role"] == "assistant":
124
+ history = history[:-1]
125
+ return history
126
+
127
+
128
+ DESCRIPTION = """
129
+ <div style="text-align: center">
130
+ <h1 style="margin-bottom: 0.3rem">CameraVLM</h1>
131
+ <p>A video language model for understanding camera motion and 3D space in videos.<br>
132
+ Code and model weights will be released upon acceptance of the paper.</p>
133
+ </div>
134
+ """
135
+
136
+ NOTE = """
137
+ <p style="font-size: 0.85rem; opacity: 0.8">
138
+ Each question is answered independently from the most recently attached video; attach another video with the paperclip
139
+ to switch. The demo runs on a shared ZeroGPU with a daily per-user quota; log in to Hugging Face for more quota.
140
+ Please do not upload personal or sensitive content. The API additionally returns per-frame camera poses and point
141
+ tracks: click <i>Use via API</i> at the bottom of the page, or see the GitHub repository.
142
+ </p>
143
+ """
144
+
145
+ DEFAULT_PROMPT = "How does the camera move?"
146
+
147
+ API_DESCRIPTION = (
148
+ "Answers a question about a video. Returns (answer, geometry): answer is the text answer, a JSON string "
149
+ "when task=\"camera_motion\"; geometry is the path of an .npz with per-frame camera poses and point tracks "
150
+ "(fields: GitHub README)."
151
+ )
152
+
153
+ API_DOCS = {
154
+ "video": "Video to analyse: a local path or URL wrapped in handle_file() (.mp4, .mov, ...; up to 200 MB).",
155
+ "task": '"question" answers prompt; "camera_motion" returns a JSON camera-motion description and ignores prompt.',
156
+ "prompt": f'Question about the video (default: "{DEFAULT_PROMPT}"). Ignored when task="camera_motion".',
157
+ "num_frames": "Frames sampled uniformly from the video, 2-128. Fewer frames run faster and use less GPU quota.",
158
+ }
159
+
160
+
161
+ def document_api(component, text):
162
+ """Replaces Gradio's generic per-parameter text in the 'Use via API' page with a real description."""
163
+ info = {**component.api_info_as_input(), "additional_description": text}
164
+ component.api_info_as_input = lambda: info
165
+
166
+
167
+ CSS = """
168
+ #chat video {max-height: 180px; width: auto !important; max-width: 320px;}
169
+ """
170
+
171
+ # System fonts only: no requests to external font servers.
172
+ THEME = gr.themes.Default(
173
+ font=["ui-sans-serif", "system-ui", "-apple-system", "Segoe UI", "Helvetica", "Arial", "sans-serif"],
174
+ font_mono=["ui-monospace", "SFMono-Regular", "Menlo", "Consolas", "monospace"],
175
+ )
176
+
177
+ with gr.Blocks(title="CameraVLM", delete_cache=(3600, 3600)) as demo:
178
+ gr.HTML(DESCRIPTION)
179
+ video_state = gr.State(None)
180
+ request_state = gr.State(None)
181
+
182
+ upload = gr.Video(label="Click or drop a video here", sources=["upload"], height=CHAT_HEIGHT)
183
+ chatbot = gr.Chatbot(show_label=False, height=CHAT_HEIGHT, visible=False, elem_id="chat")
184
+ message = gr.MultimodalTextbox(
185
+ show_label=False, file_types=["video"], file_count="single", sources=["upload"],
186
+ placeholder="Ask a question about the video, e.g. How does the camera move relative to the car?",
187
+ )
188
+ with gr.Row():
189
+ motion_btn = gr.Button("Describe camera motion", variant="primary")
190
+ regen_btn = gr.Button("Regenerate")
191
+ clear_btn = gr.Button("Clear")
192
+ with gr.Accordion("Advanced", open=False):
193
+ num_frames = gr.Slider(2, MAX_FRAMES, value=MAX_FRAMES, step=2, label="Frames sampled uniformly",
194
+ info="Fewer frames run faster and use less GPU quota.")
195
+ gr.HTML(NOTE)
196
+
197
+ private = {"api_visibility": "private"}
198
+ views = [chatbot, upload]
199
+ respond_inputs = [chatbot, video_state, request_state, num_frames]
200
+ upload.upload(upload_video, [chatbot, upload], [*views, video_state], **private)
201
+ message.submit(add_message, [chatbot, video_state, message], [*views, video_state, request_state, message],
202
+ **private).then(respond, respond_inputs, chatbot, **private)
203
+ motion_btn.click(add_camera_motion, [chatbot, video_state, message],
204
+ [*views, video_state, request_state, message], **private).then(
205
+ respond, respond_inputs, chatbot, **private)
206
+ regen_btn.click(drop_last_answer, chatbot, chatbot, **private).then(respond, respond_inputs, chatbot, **private)
207
+ for trigger in (clear_btn.click, chatbot.clear):
208
+ trigger(lambda: (*show_chat([]), None, None), None, [*views, video_state, request_state], **private)
209
+
210
+ # Programmatic API (hidden from the page): predict(video, task, prompt, num_frames) -> (answer, geometry)
211
+ with gr.Group(visible=False):
212
+ api_video = gr.Video(label="video")
213
+ api_task = gr.Radio(["question", "camera_motion"], value="question", label="task")
214
+ api_prompt = gr.Textbox(value=DEFAULT_PROMPT, label="prompt")
215
+ api_frames = gr.Number(value=MAX_FRAMES, precision=0, minimum=2, maximum=MAX_FRAMES, label="num_frames")
216
+ api_answer = gr.Textbox(label="answer")
217
+ api_geometry = gr.File(label="geometry")
218
+ api_btn = gr.Button()
219
+ for component in (api_video, api_task, api_prompt, api_frames):
220
+ document_api(component, API_DOCS[component.label])
221
+ api_btn.click(predict, [api_video, api_task, api_prompt, api_frames], [api_answer, api_geometry],
222
+ api_name="predict", api_description=API_DESCRIPTION)
223
+
224
+ demo.queue(max_size=20).launch(
225
+ theme=THEME,
226
+ css=CSS,
227
+ max_file_size="200mb",
228
+ blocked_paths=[model_dir],
229
+ show_error=False,
230
+ )
requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch==2.8.0
2
+ torchvision==0.23.0
3
+ transformers==5.16.0
4
+ xformers==0.0.32.post2
5
+ decord==0.6.0
6
+ huggingface_hub
7
+ spaces
8
+ numpy
9
+ pillow
10
+ safetensors
11
+ opencv-python-headless
12
+ psutil