Spaces:
Running on Zero
Running on Zero
Demo of gradio-app/gradio#13965 @ 7be3bb2
Browse files- README.md +14 -6
- app.py +541 -0
- browser.js +0 -0
- index.html +1421 -0
- requirements.txt +128 -0
README.md
CHANGED
|
@@ -1,13 +1,21 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
colorTo: green
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version: 6.
|
| 8 |
-
python_version:
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
|
|
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Depth Anything 3 in 3D (gradio PR 13965)
|
| 3 |
+
emoji: 🧊
|
| 4 |
+
colorFrom: indigo
|
| 5 |
colorTo: green
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 6.30.0
|
| 8 |
+
python_version: "3.12"
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
| 11 |
+
hf_oauth: true
|
| 12 |
+
short_description: Your camera in 3D, with depth from Depth Anything 3
|
| 13 |
---
|
| 14 |
|
| 15 |
+
Example of WebRTC streaming in a `gr.Server` app, a demo of [gradio-app/gradio#13965](https://github.com/gradio-app/gradio/pull/13965).
|
| 16 |
+
|
| 17 |
+
The page is plain HTML (`index.html`) that streams the webcam with `client.submit()` from `@gradio/client` and draws what comes back in 3D with three.js. On the server, a `VideoStreamHandler` class registered with `@app.api(transport=...)` runs for each stream; its `video_receive()` declares the page's inputs (model, length). Depth Anything 3 (Apache-2.0 checkpoints: Large 1.1, Mono Large, Metric Large, Base, Small) estimates the depth of every frame, and the any-view models also estimate the camera's field of view. Each frame comes back with its depth beside it in the same video frame, so color and depth always match. The model can be switched while the stream runs.
|
| 18 |
+
|
| 19 |
+
Each stream makes a single ZeroGPU call for its whole length. The visitor picks the length (30 s to 5 min), which sets how much GPU time is requested. Signing in is needed: the GPU time comes from your own ZeroGPU quota, and the TURN relay is issued with your account.
|
| 20 |
+
|
| 21 |
+
The `sdk_version` is only what the builder installs first: `app.py` replaces it with the PR's preview build and installs `depth-anything-3` (without its export dependencies) at startup, and the page loads the JS client (`browser.js`) built from the same commit.
|
app.py
ADDED
|
@@ -0,0 +1,541 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Webcam depth in 3D: a gr.Server app with its own page, on ZeroGPU.
|
| 2 |
+
|
| 3 |
+
A demo of gradio-app/gradio#13965: the handler class is an
|
| 4 |
+
`@app.api(transport=...)` endpoint whose video_receive() declares the page's
|
| 5 |
+
inputs, and the page calls it with `client.submit()`.
|
| 6 |
+
|
| 7 |
+
The page streams the webcam to the `/depth` endpoint. Each stream makes one
|
| 8 |
+
@spaces.GPU generator call: the webcam frames go to it through a queue, and
|
| 9 |
+
each frame comes back with its depth map beside it in the same video frame
|
| 10 |
+
(RGBD side by side), so color and depth always match. The page turns that
|
| 11 |
+
into a 3D view in WebGL.
|
| 12 |
+
|
| 13 |
+
Depth comes from Depth Anything 3, run entirely on the GPU. Its any-view models
|
| 14 |
+
also estimate the camera, so the page draws with the estimated field of view
|
| 15 |
+
instead of an assumed one.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import importlib.metadata
|
| 19 |
+
import os
|
| 20 |
+
import subprocess
|
| 21 |
+
import sys
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
|
| 24 |
+
HERE = Path(__file__).parent
|
| 25 |
+
GRADIO_SHA = "7be3bb27b39c87cdda51e7d8f4171664a0c94a75"
|
| 26 |
+
PREVIEWS = "https://huggingface.co/buckets/gradio/pypi-previews/resolve"
|
| 27 |
+
|
| 28 |
+
ON_SPACES = bool(os.environ.get("SPACE_ID"))
|
| 29 |
+
|
| 30 |
+
# The Gradio SDK installs only released versions, so the PR's preview build
|
| 31 |
+
# replaces it at startup and the app starts again.
|
| 32 |
+
if (
|
| 33 |
+
ON_SPACES
|
| 34 |
+
and not os.environ.get("PREVIEW_GRADIO_INSTALLED")
|
| 35 |
+
and importlib.metadata.version("gradio") != "7.0.0.dev0"
|
| 36 |
+
):
|
| 37 |
+
subprocess.run(
|
| 38 |
+
[
|
| 39 |
+
sys.executable,
|
| 40 |
+
"-m",
|
| 41 |
+
"pip",
|
| 42 |
+
"install",
|
| 43 |
+
"--no-cache-dir",
|
| 44 |
+
f"gradio[webrtc,oauth] @ {PREVIEWS}/{GRADIO_SHA}/gradio-7.0.0.dev0-py3-none-any.whl",
|
| 45 |
+
f"gradio_client @ git+https://github.com/gradio-app/gradio@{GRADIO_SHA}#subdirectory=client/python",
|
| 46 |
+
],
|
| 47 |
+
check=True,
|
| 48 |
+
)
|
| 49 |
+
subprocess.run(
|
| 50 |
+
[
|
| 51 |
+
sys.executable,
|
| 52 |
+
"-m",
|
| 53 |
+
"pip",
|
| 54 |
+
"install",
|
| 55 |
+
"--no-deps",
|
| 56 |
+
# gradio 7.0-dev's native ZeroGPU support (#13969) hands spaces 0.52
|
| 57 |
+
# the request context; 0.51 reads it from gradio internals instead
|
| 58 |
+
"spaces==0.52.0.dev6",
|
| 59 |
+
# Its declared dependencies are for exports and the CLI (open3d,
|
| 60 |
+
# xformers, pycolmap, ...); the network itself needs only what
|
| 61 |
+
# requirements.txt has (addict, einops, omegaconf)
|
| 62 |
+
"depth-anything-3==0.1.1",
|
| 63 |
+
],
|
| 64 |
+
check=True,
|
| 65 |
+
)
|
| 66 |
+
os.environ["PREVIEW_GRADIO_INSTALLED"] = "1"
|
| 67 |
+
os.execv(sys.executable, [sys.executable, *sys.argv])
|
| 68 |
+
|
| 69 |
+
import contextvars # noqa: E402 (after the install block on purpose)
|
| 70 |
+
import functools # noqa: E402
|
| 71 |
+
import json # noqa: E402
|
| 72 |
+
import logging # noqa: E402
|
| 73 |
+
import math # noqa: E402
|
| 74 |
+
import multiprocessing # noqa: E402
|
| 75 |
+
import queue # noqa: E402
|
| 76 |
+
import statistics # noqa: E402
|
| 77 |
+
import threading # noqa: E402
|
| 78 |
+
import time # noqa: E402
|
| 79 |
+
|
| 80 |
+
import httpx2 # noqa: E402
|
| 81 |
+
import numpy as np # noqa: E402
|
| 82 |
+
import spaces # noqa: E402
|
| 83 |
+
import torch # noqa: E402
|
| 84 |
+
from depth_anything_3.cfg import create_object, load_config # noqa: E402
|
| 85 |
+
from depth_anything_3.registry import MODEL_REGISTRY # noqa: E402
|
| 86 |
+
from fastapi.responses import FileResponse, HTMLResponse # noqa: E402
|
| 87 |
+
from huggingface_hub import hf_hub_download # noqa: E402
|
| 88 |
+
from PIL import Image # noqa: E402
|
| 89 |
+
from safetensors.torch import load_file # noqa: E402
|
| 90 |
+
from torch.nn.functional import interpolate # noqa: E402
|
| 91 |
+
|
| 92 |
+
import gradio as gr # noqa: E402
|
| 93 |
+
from gradio.streaming import CloseStream, VideoStreamHandler # noqa: E402
|
| 94 |
+
|
| 95 |
+
logger = logging.getLogger(__name__)
|
| 96 |
+
|
| 97 |
+
TURN_URL = "https://fastrtc-turn-service.hf.space/credentials"
|
| 98 |
+
# The visitor picks how long a stream lasts, between these (seconds). The
|
| 99 |
+
# longest is also the stream's time limit, so that nobody holds a slot longer.
|
| 100 |
+
MIN_SECONDS = 30
|
| 101 |
+
MAX_SECONDS = 300
|
| 102 |
+
DEFAULT_SECONDS = 60
|
| 103 |
+
# The GPU is asked for this much longer than the stream, for its warm-up; the
|
| 104 |
+
# stream ends first, and ZeroGPU counts only the time actually used
|
| 105 |
+
GPU_MARGIN = 15
|
| 106 |
+
# How long the first frames wait for the page's inputs (the length among
|
| 107 |
+
# them) before the GPU call starts with the defaults
|
| 108 |
+
ARGS_WAIT = 3.0
|
| 109 |
+
# Layout of the frames sent back: color (HALF_WIDTH wide), a gutter, depth (as
|
| 110 |
+
# wide). The gutter keeps the codec from bleeding color into depth at the seam.
|
| 111 |
+
# The page reads the halves with normalized coordinates from these numbers, so
|
| 112 |
+
# a frame that WebRTC scales down on the way still lines up.
|
| 113 |
+
HALF_WIDTH = 320
|
| 114 |
+
GUTTER = 16
|
| 115 |
+
# Frames waiting for the GPU; when full the oldest is dropped, so the output
|
| 116 |
+
# follows the camera rather than falling behind it
|
| 117 |
+
MAX_PENDING = 1
|
| 118 |
+
# Camera frames are scaled so that the longer side is at most this
|
| 119 |
+
MAX_SIDE = 640
|
| 120 |
+
# Depth Anything 3 checkpoints (all Apache-2.0) the page can switch between
|
| 121 |
+
# while it streams: key -> (repo, kind). "any-view" models give depth up to
|
| 122 |
+
# scale and estimate the camera (field of view); "mono" gives depth up to scale;
|
| 123 |
+
# "metric" gives depth that becomes meters with the focal length.
|
| 124 |
+
MODELS = {
|
| 125 |
+
"large": ("depth-anything/DA3-LARGE-1.1", "any-view"),
|
| 126 |
+
"mono": ("depth-anything/DA3MONO-LARGE", "mono"),
|
| 127 |
+
"metric": ("depth-anything/DA3METRIC-LARGE", "metric"),
|
| 128 |
+
"base": ("depth-anything/DA3-BASE", "any-view"),
|
| 129 |
+
"small": ("depth-anything/DA3-SMALL", "any-view"),
|
| 130 |
+
}
|
| 131 |
+
DEFAULT_MODEL = "large"
|
| 132 |
+
# The model's input: the longer side (DA3's default), a multiple of its 14 px patches
|
| 133 |
+
MODEL_SIDE = 504
|
| 134 |
+
# Field of view assumed for a webcam when the model does not estimate one
|
| 135 |
+
ASSUMED_FOV = 62.0
|
| 136 |
+
# Depth up to scale is scaled so that its median is this many meters
|
| 137 |
+
MEDIAN_DEPTH = 1.5
|
| 138 |
+
# DA3 metric: meters = output * focal length (px) / this
|
| 139 |
+
METRIC_SCALE = 300.0
|
| 140 |
+
# Depth goes to the page as inverse depth between these distances (meters),
|
| 141 |
+
# which keeps most of the 256 gray levels for what is close to the camera
|
| 142 |
+
NEAR = 0.4
|
| 143 |
+
FAR = 5.0
|
| 144 |
+
# Weight of the previous frame in a running average of the depth, against flicker
|
| 145 |
+
SMOOTHING = 0.4
|
| 146 |
+
IMAGENET_MEAN = (0.485, 0.456, 0.406)
|
| 147 |
+
IMAGENET_STD = (0.229, 0.224, 0.225)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def load_da3(repo: str):
|
| 151 |
+
"""The network of a DA3 checkpoint, built as the package's own loader does:
|
| 152 |
+
from the YAML of the repo's model_name (config.json's other keys are not
|
| 153 |
+
used by it). fp32 weights; calls run in bf16 autocast like the package's
|
| 154 |
+
API, which keeps the heads in fp32.
|
| 155 |
+
|
| 156 |
+
The package loads weights non-strictly (PyTorchModelHubMixin's default),
|
| 157 |
+
and the any-view checkpoints (Large 1.1, Base, Small) have no weights for
|
| 158 |
+
some of the head's auxiliary ray outputs, which the network drops when it
|
| 159 |
+
has a camera head. Only those may
|
| 160 |
+
be missing here; any other mismatch fails at startup instead of giving
|
| 161 |
+
wrong depth."""
|
| 162 |
+
with open(hf_hub_download(repo, "config.json"), encoding="utf-8") as f:
|
| 163 |
+
model_name = json.load(f)["model_name"]
|
| 164 |
+
net = create_object(load_config(MODEL_REGISTRY[model_name]))
|
| 165 |
+
weights = load_file(hf_hub_download(repo, "model.safetensors"))
|
| 166 |
+
result = net.load_state_dict(
|
| 167 |
+
{k.removeprefix("model."): v for k, v in weights.items()}, strict=False
|
| 168 |
+
)
|
| 169 |
+
has_camera = getattr(net, "cam_dec", None) is not None
|
| 170 |
+
tolerated = [k for k in result.missing_keys if ".output_conv2_aux." in k]
|
| 171 |
+
if result.unexpected_keys or len(tolerated) != len(result.missing_keys):
|
| 172 |
+
raise RuntimeError(f"{repo}: weights do not match the network: {result}")
|
| 173 |
+
if tolerated and not has_camera:
|
| 174 |
+
raise RuntimeError(
|
| 175 |
+
f"{repo}: missing ray head weights it would use: {tolerated}"
|
| 176 |
+
)
|
| 177 |
+
return net.to("cuda").eval()
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
# On ZeroGPU this registers the weights; the real GPU is attached in the
|
| 181 |
+
# worker. All of them stay there (about 5 GB in fp32), so switching is instant.
|
| 182 |
+
models = {key: load_da3(repo) for key, (repo, _) in MODELS.items()}
|
| 183 |
+
|
| 184 |
+
app = gr.Server()
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
@functools.cache
|
| 188 |
+
def get_manager():
|
| 189 |
+
"""Starts the Manager process once, at startup, before any thread starts."""
|
| 190 |
+
return multiprocessing.Manager()
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
async def turn_credentials(token: gr.OAuthToken | None) -> dict:
|
| 194 |
+
"""ICE servers for the browser, issued with the visitor's own account."""
|
| 195 |
+
if token is None:
|
| 196 |
+
raise gr.Error("Sign in with Hugging Face first.")
|
| 197 |
+
async with httpx2.AsyncClient(timeout=10) as client:
|
| 198 |
+
response = await client.get(
|
| 199 |
+
TURN_URL,
|
| 200 |
+
headers={"Authorization": f"Bearer {token.token}"},
|
| 201 |
+
params={"ttl": 600},
|
| 202 |
+
)
|
| 203 |
+
if response.status_code != 200:
|
| 204 |
+
raise gr.Error(f"TURN endpoint returned {response.status_code}")
|
| 205 |
+
return response.json()
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def out_height(height: int, width: int) -> int:
|
| 209 |
+
"""Height of each half for a HALF_WIDTH-wide half, a multiple of 16."""
|
| 210 |
+
return max(16, round(HALF_WIDTH * height / width / 16) * 16)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def fit(frame: np.ndarray, width: int = HALF_WIDTH) -> np.ndarray:
|
| 214 |
+
"""Scales the frame to `width` wide (HALF_WIDTH: height a multiple of 16)."""
|
| 215 |
+
height, old_width = frame.shape[:2]
|
| 216 |
+
if width == HALF_WIDTH:
|
| 217 |
+
size = (HALF_WIDTH, out_height(height, old_width))
|
| 218 |
+
elif old_width <= width and height <= width:
|
| 219 |
+
return frame
|
| 220 |
+
else:
|
| 221 |
+
scale = width / max(height, old_width)
|
| 222 |
+
size = (round(old_width * scale), round(height * scale))
|
| 223 |
+
return np.asarray(Image.fromarray(frame).resize(size, Image.BILINEAR))
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def side_by_side(color: np.ndarray, depth: np.ndarray | None) -> np.ndarray:
|
| 227 |
+
"""Color, gutter, depth as gray (R = G = B, so it rides on full-resolution luma)."""
|
| 228 |
+
h = color.shape[0]
|
| 229 |
+
out = np.zeros((h, 2 * HALF_WIDTH + GUTTER, 3), dtype=np.uint8)
|
| 230 |
+
out[:, :HALF_WIDTH] = color
|
| 231 |
+
if depth is not None:
|
| 232 |
+
out[:, HALF_WIDTH + GUTTER :] = (depth * 255).astype(np.uint8)[..., None]
|
| 233 |
+
return out
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def smooth(state: dict, name: str, value):
|
| 237 |
+
"""A running average across frames, against flicker and pumping."""
|
| 238 |
+
if name in state:
|
| 239 |
+
value = SMOOTHING * state[name] + (1 - SMOOTHING) * value
|
| 240 |
+
state[name] = value
|
| 241 |
+
return value
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def rgbd_on_gpu(frame: np.ndarray, key: str, state: dict) -> tuple[np.ndarray, float]:
|
| 245 |
+
"""The RGBD frame for one camera frame and the horizontal field of view
|
| 246 |
+
(degrees) to draw it with, all on the GPU. Depth up to scale is scaled to a
|
| 247 |
+
median of MEDIAN_DEPTH, metric depth becomes meters with the focal length,
|
| 248 |
+
and either goes as inverse depth between NEAR and FAR (0..1) beside the
|
| 249 |
+
color as gray. Values are averaged with the previous frame's (`state`,
|
| 250 |
+
reset when the model changes)."""
|
| 251 |
+
if state.get("key") != key:
|
| 252 |
+
state.clear()
|
| 253 |
+
state["key"] = key
|
| 254 |
+
_, kind = MODELS[key]
|
| 255 |
+
height, width = frame.shape[:2]
|
| 256 |
+
image = torch.from_numpy(frame).to("cuda").permute(2, 0, 1)[None].float() / 255
|
| 257 |
+
scale = MODEL_SIDE / max(height, width)
|
| 258 |
+
size = (
|
| 259 |
+
max(14, round(height * scale / 14) * 14),
|
| 260 |
+
max(14, round(width * scale / 14) * 14),
|
| 261 |
+
)
|
| 262 |
+
pixels = interpolate(image, size=size, mode="bilinear", antialias=True)
|
| 263 |
+
mean = torch.tensor(IMAGENET_MEAN, device="cuda").view(1, 3, 1, 1)
|
| 264 |
+
std = torch.tensor(IMAGENET_STD, device="cuda").view(1, 3, 1, 1)
|
| 265 |
+
pixels = (pixels - mean) / std
|
| 266 |
+
# The network takes (batch, views, 3, H, W): one view here
|
| 267 |
+
with torch.autocast("cuda", dtype=torch.bfloat16):
|
| 268 |
+
output = models[key](pixels[:, None])
|
| 269 |
+
depth = output.depth.float().reshape(-1, *size)[:1, None]
|
| 270 |
+
|
| 271 |
+
# Intrinsics are for the network's input size
|
| 272 |
+
assumed_fx = (size[1] / 2) / math.tan(math.radians(ASSUMED_FOV) / 2)
|
| 273 |
+
fov = ASSUMED_FOV
|
| 274 |
+
if kind == "any-view" and output.get("intrinsics") is not None:
|
| 275 |
+
fx = output.intrinsics.float().reshape(-1, 3, 3)[0, 0, 0]
|
| 276 |
+
estimated = torch.rad2deg(2 * torch.atan((size[1] / 2) / fx.clamp_min(1)))
|
| 277 |
+
fov = float(smooth(state, "fov", estimated.clamp(20, 120)))
|
| 278 |
+
if kind == "metric":
|
| 279 |
+
depth = depth * assumed_fx / METRIC_SCALE
|
| 280 |
+
else:
|
| 281 |
+
median = smooth(state, "median", depth.flatten()[::4].median().clamp_min(1e-6))
|
| 282 |
+
depth = depth * (MEDIAN_DEPTH / median)
|
| 283 |
+
|
| 284 |
+
out_size = (out_height(height, width), HALF_WIDTH)
|
| 285 |
+
color = interpolate(image, size=out_size, mode="bilinear", antialias=True)
|
| 286 |
+
depth = interpolate(depth, size=out_size, mode="bilinear")
|
| 287 |
+
inverse = 1 / depth.clamp(NEAR, FAR)
|
| 288 |
+
level = (inverse - 1 / FAR) / (1 / NEAR - 1 / FAR)
|
| 289 |
+
previous = state.get("level")
|
| 290 |
+
if previous is not None and previous.shape == level.shape:
|
| 291 |
+
level = SMOOTHING * previous + (1 - SMOOTHING) * level
|
| 292 |
+
state["level"] = level
|
| 293 |
+
|
| 294 |
+
out = torch.zeros((3, out_size[0], 2 * HALF_WIDTH + GUTTER), device="cuda")
|
| 295 |
+
out[:, :, :HALF_WIDTH] = color[0]
|
| 296 |
+
out[:, :, HALF_WIDTH + GUTTER :] = level[0]
|
| 297 |
+
rgbd = (out * 255).round().clamp(0, 255).byte().permute(1, 2, 0).cpu().numpy()
|
| 298 |
+
return rgbd, fov
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def gpu_duration(frames, seconds: int) -> int:
|
| 302 |
+
"""What the stream asks ZeroGPU for: the length the visitor picked."""
|
| 303 |
+
return seconds + GPU_MARGIN
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
@spaces.GPU(duration=gpu_duration)
|
| 307 |
+
def run(frames, seconds: int):
|
| 308 |
+
"""Runs in the GPU process for the whole stream, one frame at a time.
|
| 309 |
+
`seconds` only sets how long the GPU is asked for (see gpu_duration)."""
|
| 310 |
+
device = torch.cuda.get_device_name()
|
| 311 |
+
state: dict = {}
|
| 312 |
+
with torch.inference_mode():
|
| 313 |
+
while (item := frames.get()) is not None:
|
| 314 |
+
received_at, frame, key = item
|
| 315 |
+
rgbd, fov = rgbd_on_gpu(frame, key, state)
|
| 316 |
+
yield (
|
| 317 |
+
rgbd,
|
| 318 |
+
{
|
| 319 |
+
"received_at": received_at,
|
| 320 |
+
"device": device,
|
| 321 |
+
"fov": fov,
|
| 322 |
+
"fov_estimated": MODELS[key][1] == "any-view",
|
| 323 |
+
},
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
@app.api(
|
| 328 |
+
name="depth",
|
| 329 |
+
transport=gr.WebRTCOptions(
|
| 330 |
+
rtc_configuration=turn_credentials if ON_SPACES else None,
|
| 331 |
+
video_bitrate={"min": 800, "start": 1500, "max": 3000},
|
| 332 |
+
),
|
| 333 |
+
time_limit=MAX_SECONDS,
|
| 334 |
+
concurrency_limit=2,
|
| 335 |
+
)
|
| 336 |
+
class Depth(VideoStreamHandler):
|
| 337 |
+
"""
|
| 338 |
+
One stream: the webcam frames go to the `run` GPU call through a Manager
|
| 339 |
+
queue, and the RGBD frames come back one by one. shutdown() ends the GPU
|
| 340 |
+
call when the connection closes.
|
| 341 |
+
"""
|
| 342 |
+
|
| 343 |
+
def __init__(self) -> None:
|
| 344 |
+
super().__init__(fps=30)
|
| 345 |
+
self._lock = threading.Lock()
|
| 346 |
+
self._frames = None
|
| 347 |
+
self._closed = False
|
| 348 |
+
self._end_message: str | None = None
|
| 349 |
+
self._latest: np.ndarray | None = None
|
| 350 |
+
self._new_result = threading.Event()
|
| 351 |
+
self._preview: np.ndarray | None = None
|
| 352 |
+
# When the first frame came, and when the stream ends (the length the
|
| 353 |
+
# visitor picked, counted from the start of the GPU call)
|
| 354 |
+
self._first_frame_at: float | None = None
|
| 355 |
+
self._ends_at: float | None = None
|
| 356 |
+
# The fps and latency figures of the status, recomputed once a second
|
| 357 |
+
self._metrics: dict = {"fps": 0.0, "latency_ms": None}
|
| 358 |
+
self._metrics_at = 0.0
|
| 359 |
+
self.ready = False
|
| 360 |
+
self.latency_ms: list[float] = []
|
| 361 |
+
self.out_times: list[float] = []
|
| 362 |
+
self.device = ""
|
| 363 |
+
self.fov = ASSUMED_FOV
|
| 364 |
+
self.fov_estimated = False
|
| 365 |
+
|
| 366 |
+
def copy(self) -> "Depth":
|
| 367 |
+
return Depth()
|
| 368 |
+
|
| 369 |
+
def _ensure_started(self, seconds: int) -> bool:
|
| 370 |
+
"""Starts the GPU call once the page's inputs have come (they hold the
|
| 371 |
+
length, which sets how long the GPU is asked for), or after
|
| 372 |
+
ARGS_WAIT seconds with the defaults. False while it has not started."""
|
| 373 |
+
with self._lock:
|
| 374 |
+
if self._closed:
|
| 375 |
+
return False
|
| 376 |
+
if self._frames is not None:
|
| 377 |
+
return True
|
| 378 |
+
now = time.monotonic()
|
| 379 |
+
if self._first_frame_at is None:
|
| 380 |
+
self._first_frame_at = now
|
| 381 |
+
if not self.args_set.is_set() and now - self._first_frame_at < ARGS_WAIT:
|
| 382 |
+
return False
|
| 383 |
+
seconds = read_seconds(seconds)
|
| 384 |
+
self._ends_at = now + seconds
|
| 385 |
+
self._frames = get_manager().Queue(maxsize=MAX_PENDING)
|
| 386 |
+
# A new thread starts with an empty context; pyspaces needs the
|
| 387 |
+
# connection's Gradio context and the visitor's request
|
| 388 |
+
context = contextvars.copy_context()
|
| 389 |
+
threading.Thread(
|
| 390 |
+
target=context.run,
|
| 391 |
+
args=(self._consume, self._frames, seconds),
|
| 392 |
+
daemon=True,
|
| 393 |
+
).start()
|
| 394 |
+
return True
|
| 395 |
+
|
| 396 |
+
def _consume(self, frames, seconds: int) -> None:
|
| 397 |
+
try:
|
| 398 |
+
for image, info in run(frames, seconds):
|
| 399 |
+
now = time.monotonic()
|
| 400 |
+
self.latency_ms.append((now - info["received_at"]) * 1000)
|
| 401 |
+
self.out_times.append(now)
|
| 402 |
+
self.device = info["device"]
|
| 403 |
+
self.fov = info["fov"]
|
| 404 |
+
self.fov_estimated = info["fov_estimated"]
|
| 405 |
+
self.ready = True
|
| 406 |
+
self._latest = image
|
| 407 |
+
self._new_result.set()
|
| 408 |
+
except BaseException as e: # reported through the log and to the page
|
| 409 |
+
self._end_message = getattr(e, "message", None) or str(e) or repr(e)
|
| 410 |
+
logger.exception("GPU stream ended with an error")
|
| 411 |
+
finally:
|
| 412 |
+
with self._lock:
|
| 413 |
+
self._closed = True
|
| 414 |
+
|
| 415 |
+
def video_receive(
|
| 416 |
+
self,
|
| 417 |
+
frame: gr.VideoFrame,
|
| 418 |
+
model: str = DEFAULT_MODEL,
|
| 419 |
+
seconds: int = DEFAULT_SECONDS,
|
| 420 |
+
) -> None:
|
| 421 |
+
if self._closed:
|
| 422 |
+
return
|
| 423 |
+
self._preview = fit(frame)
|
| 424 |
+
if not self._ensure_started(seconds):
|
| 425 |
+
return
|
| 426 |
+
# The page can change the model while the stream runs
|
| 427 |
+
key = model if model in MODELS else DEFAULT_MODEL
|
| 428 |
+
item = (time.monotonic(), fit(frame, MAX_SIDE), key)
|
| 429 |
+
try:
|
| 430 |
+
self._frames.put_nowait(item)
|
| 431 |
+
except queue.Full:
|
| 432 |
+
try:
|
| 433 |
+
self._frames.get_nowait()
|
| 434 |
+
except queue.Empty:
|
| 435 |
+
pass
|
| 436 |
+
try:
|
| 437 |
+
self._frames.put_nowait(item)
|
| 438 |
+
except queue.Full:
|
| 439 |
+
pass
|
| 440 |
+
|
| 441 |
+
def video_emit(self) -> tuple[gr.VideoFrame, dict] | None:
|
| 442 |
+
if self._end_message is not None:
|
| 443 |
+
# e.g. a ZeroGPU quota error: end the stream with its message,
|
| 444 |
+
# which the page shows as the reason
|
| 445 |
+
return CloseStream(self._end_message)
|
| 446 |
+
if self._ends_at is not None and time.monotonic() >= self._ends_at:
|
| 447 |
+
# The length the visitor picked is over: an end without a message
|
| 448 |
+
return CloseStream("")
|
| 449 |
+
self._new_result.wait(1 / 30)
|
| 450 |
+
self._new_result.clear()
|
| 451 |
+
if self._latest is not None:
|
| 452 |
+
image = self._latest
|
| 453 |
+
elif self._preview is not None:
|
| 454 |
+
# Until the GPU answers: the camera with no depth (a flat picture)
|
| 455 |
+
image = side_by_side(self._preview, None)
|
| 456 |
+
else:
|
| 457 |
+
image = side_by_side(np.zeros((240, HALF_WIDTH, 3), np.uint8), None)
|
| 458 |
+
return image, self._status(time.monotonic())
|
| 459 |
+
|
| 460 |
+
def _status(self, now: float) -> dict:
|
| 461 |
+
"""The status the page shows. The stream sends it only when it changes
|
| 462 |
+
(at most every WebRTCOptions.output_every), so it can be returned with
|
| 463 |
+
every frame; the figures in it are worked out once a second."""
|
| 464 |
+
if now - self._metrics_at >= 1:
|
| 465 |
+
recent = [t for t in self.out_times[-60:] if now - t < 2]
|
| 466 |
+
self._metrics = {
|
| 467 |
+
# The page draws with this field of view; it changes slowly
|
| 468 |
+
"fov": round(self.fov, 1),
|
| 469 |
+
"fov_estimated": self.fov_estimated,
|
| 470 |
+
"fps": round(len(recent) / 2, 1),
|
| 471 |
+
"latency_ms": round(statistics.median(self.latency_ms[-30:]))
|
| 472 |
+
if self.latency_ms
|
| 473 |
+
else None,
|
| 474 |
+
}
|
| 475 |
+
self._metrics_at = now
|
| 476 |
+
return {"ready": self.ready, "device": self.device, **self._metrics}
|
| 477 |
+
|
| 478 |
+
def shutdown(self) -> None:
|
| 479 |
+
with self._lock:
|
| 480 |
+
already_closed = self._closed
|
| 481 |
+
self._closed = True
|
| 482 |
+
frames = self._frames
|
| 483 |
+
if frames is None or already_closed:
|
| 484 |
+
return
|
| 485 |
+
# Make room for the sentinel: the worker may be busy with a frame
|
| 486 |
+
while True:
|
| 487 |
+
try:
|
| 488 |
+
frames.get_nowait()
|
| 489 |
+
except queue.Empty:
|
| 490 |
+
break
|
| 491 |
+
try:
|
| 492 |
+
frames.put(None, timeout=5)
|
| 493 |
+
except Exception:
|
| 494 |
+
logger.exception("Could not send the end of the stream to the GPU")
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
def read_seconds(seconds) -> int:
|
| 498 |
+
"""The stream's length from the page's inputs, kept within the limits
|
| 499 |
+
whatever the page sends."""
|
| 500 |
+
try:
|
| 501 |
+
seconds = int(seconds)
|
| 502 |
+
except (TypeError, ValueError):
|
| 503 |
+
return DEFAULT_SECONDS
|
| 504 |
+
return min(max(seconds, MIN_SECONDS), MAX_SECONDS)
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
@app.api(name="whoami")
|
| 508 |
+
def whoami(profile: gr.OAuthProfile | None) -> str:
|
| 509 |
+
return profile.username if profile else ""
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
@app.get("/client.js")
|
| 513 |
+
def client_js():
|
| 514 |
+
# The JS client from the same commit (its npm preview build)
|
| 515 |
+
return FileResponse(HERE / "browser.js", media_type="text/javascript")
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
PAGE_FILE = HERE / "index.html"
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
@app.get("/", response_class=HTMLResponse)
|
| 522 |
+
async def homepage():
|
| 523 |
+
with open(PAGE_FILE, encoding="utf-8") as f:
|
| 524 |
+
page = f.read()
|
| 525 |
+
return (
|
| 526 |
+
page.replace("__CLIENT_URL__", "/client.js")
|
| 527 |
+
.replace("__COMMIT__", GRADIO_SHA[:7])
|
| 528 |
+
.replace("__MIN_SECONDS__", str(MIN_SECONDS))
|
| 529 |
+
.replace("__MAX_SECONDS__", str(MAX_SECONDS))
|
| 530 |
+
.replace("__DEFAULT_SECONDS__", str(DEFAULT_SECONDS))
|
| 531 |
+
.replace("__HALF_WIDTH__", str(HALF_WIDTH))
|
| 532 |
+
.replace("__GUTTER__", str(GUTTER))
|
| 533 |
+
.replace("__ON_SPACES__", "true" if ON_SPACES else "false")
|
| 534 |
+
.replace("__NEAR__", str(NEAR))
|
| 535 |
+
.replace("__FAR__", str(FAR))
|
| 536 |
+
)
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
if __name__ == "__main__":
|
| 540 |
+
get_manager()
|
| 541 |
+
app.launch()
|
browser.js
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
index.html
ADDED
|
@@ -0,0 +1,1421 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!doctype html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="utf-8" />
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
| 6 |
+
<title>Depth Anything 3, live</title>
|
| 7 |
+
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
| 8 |
+
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
| 9 |
+
<link
|
| 10 |
+
href="https://fonts.googleapis.com/css2?family=Instrument+Sans:wght@400;500;600&display=swap"
|
| 11 |
+
rel="stylesheet"
|
| 12 |
+
/>
|
| 13 |
+
<script>
|
| 14 |
+
// The Hugging Face page passes its theme to the Space as ?__theme=
|
| 15 |
+
const theme = new URLSearchParams(location.search).get("__theme");
|
| 16 |
+
if (theme === "dark" || theme === "light")
|
| 17 |
+
document.documentElement.dataset.theme = theme;
|
| 18 |
+
</script>
|
| 19 |
+
<script type="importmap">
|
| 20 |
+
{
|
| 21 |
+
"imports": {
|
| 22 |
+
"three": "https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js",
|
| 23 |
+
"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.170.0/examples/jsm/"
|
| 24 |
+
}
|
| 25 |
+
}
|
| 26 |
+
</script>
|
| 27 |
+
<style>
|
| 28 |
+
:root {
|
| 29 |
+
color-scheme: light;
|
| 30 |
+
--ink: #12162b;
|
| 31 |
+
--glass: rgba(18, 22, 43, 0.72);
|
| 32 |
+
--glass-line: rgba(231, 234, 243, 0.22);
|
| 33 |
+
--on-ink: #e7eaf3;
|
| 34 |
+
--on-ink-muted: rgba(231, 234, 243, 0.7);
|
| 35 |
+
--near: #ffb547;
|
| 36 |
+
--far: #2ec4b6;
|
| 37 |
+
--bg: #eef1f6;
|
| 38 |
+
--fg: #1b2033;
|
| 39 |
+
--muted: #5b6378;
|
| 40 |
+
--line: #cdd3df;
|
| 41 |
+
--field: #ffffff;
|
| 42 |
+
}
|
| 43 |
+
:root[data-theme="dark"] {
|
| 44 |
+
color-scheme: dark;
|
| 45 |
+
--bg: #171b2e;
|
| 46 |
+
--fg: #e7eaf3;
|
| 47 |
+
--muted: #9aa2b8;
|
| 48 |
+
--line: #2c3350;
|
| 49 |
+
--field: #1f2440;
|
| 50 |
+
}
|
| 51 |
+
@media (prefers-color-scheme: dark) {
|
| 52 |
+
:root:not([data-theme="light"]) {
|
| 53 |
+
color-scheme: dark;
|
| 54 |
+
--bg: #171b2e;
|
| 55 |
+
--fg: #e7eaf3;
|
| 56 |
+
--muted: #9aa2b8;
|
| 57 |
+
--line: #2c3350;
|
| 58 |
+
--field: #1f2440;
|
| 59 |
+
}
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
* {
|
| 63 |
+
box-sizing: border-box;
|
| 64 |
+
}
|
| 65 |
+
html,
|
| 66 |
+
body {
|
| 67 |
+
margin: 0;
|
| 68 |
+
height: 100%;
|
| 69 |
+
}
|
| 70 |
+
body {
|
| 71 |
+
background: var(--bg);
|
| 72 |
+
color: var(--fg);
|
| 73 |
+
font-family: "Instrument Sans", system-ui, sans-serif;
|
| 74 |
+
font-size: 15px;
|
| 75 |
+
line-height: 1.5;
|
| 76 |
+
}
|
| 77 |
+
a {
|
| 78 |
+
color: inherit;
|
| 79 |
+
text-underline-offset: 3px;
|
| 80 |
+
}
|
| 81 |
+
button {
|
| 82 |
+
font: inherit;
|
| 83 |
+
cursor: pointer;
|
| 84 |
+
}
|
| 85 |
+
:focus-visible {
|
| 86 |
+
outline: 2px solid var(--near);
|
| 87 |
+
outline-offset: 2px;
|
| 88 |
+
}
|
| 89 |
+
[hidden] {
|
| 90 |
+
display: none !important;
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
.stage {
|
| 94 |
+
display: grid;
|
| 95 |
+
grid-template-columns: minmax(0, 1fr) 340px;
|
| 96 |
+
height: 100vh;
|
| 97 |
+
height: 100dvh;
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
/* The viewport: always dark, the 3D scene fills it */
|
| 101 |
+
.viewport {
|
| 102 |
+
position: relative;
|
| 103 |
+
background: radial-gradient(
|
| 104 |
+
120% 90% at 50% 40%,
|
| 105 |
+
#1a2040 0%,
|
| 106 |
+
var(--ink) 70%
|
| 107 |
+
);
|
| 108 |
+
overflow: hidden;
|
| 109 |
+
color: var(--on-ink);
|
| 110 |
+
}
|
| 111 |
+
.viewport canvas {
|
| 112 |
+
display: block;
|
| 113 |
+
width: 100%;
|
| 114 |
+
height: 100%;
|
| 115 |
+
touch-action: none;
|
| 116 |
+
}
|
| 117 |
+
/* Sources of the textures: in the DOM and playing, but not seen
|
| 118 |
+
(iOS stops updating hidden videos) */
|
| 119 |
+
.source {
|
| 120 |
+
position: absolute;
|
| 121 |
+
left: 0;
|
| 122 |
+
top: 0;
|
| 123 |
+
width: 2px;
|
| 124 |
+
height: 2px;
|
| 125 |
+
opacity: 0;
|
| 126 |
+
pointer-events: none;
|
| 127 |
+
}
|
| 128 |
+
.viewport.raw #remote {
|
| 129 |
+
width: 100%;
|
| 130 |
+
height: 100%;
|
| 131 |
+
opacity: 1;
|
| 132 |
+
object-fit: contain;
|
| 133 |
+
background: var(--ink);
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
/* Phones only: a strip above the view for the account, so that it does
|
| 137 |
+
not cover the camera */
|
| 138 |
+
.topbar {
|
| 139 |
+
display: none;
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
.bar {
|
| 143 |
+
position: absolute;
|
| 144 |
+
left: 14px;
|
| 145 |
+
right: 14px;
|
| 146 |
+
top: 14px;
|
| 147 |
+
display: flex;
|
| 148 |
+
align-items: center;
|
| 149 |
+
gap: 10px;
|
| 150 |
+
pointer-events: none;
|
| 151 |
+
}
|
| 152 |
+
.bar > * {
|
| 153 |
+
pointer-events: auto;
|
| 154 |
+
}
|
| 155 |
+
.spacer {
|
| 156 |
+
flex: 1;
|
| 157 |
+
pointer-events: none;
|
| 158 |
+
}
|
| 159 |
+
.pill {
|
| 160 |
+
border: 1px solid var(--glass-line);
|
| 161 |
+
background: var(--glass);
|
| 162 |
+
color: var(--on-ink);
|
| 163 |
+
border-radius: 999px;
|
| 164 |
+
padding: 7px 14px;
|
| 165 |
+
font-size: 14px;
|
| 166 |
+
text-decoration: none;
|
| 167 |
+
backdrop-filter: blur(8px);
|
| 168 |
+
-webkit-backdrop-filter: blur(8px);
|
| 169 |
+
white-space: nowrap;
|
| 170 |
+
}
|
| 171 |
+
.signin {
|
| 172 |
+
background: var(--on-ink);
|
| 173 |
+
color: var(--ink);
|
| 174 |
+
font-weight: 600;
|
| 175 |
+
border-color: transparent;
|
| 176 |
+
display: inline-flex;
|
| 177 |
+
align-items: center;
|
| 178 |
+
gap: 8px;
|
| 179 |
+
}
|
| 180 |
+
.signin svg {
|
| 181 |
+
width: 18px;
|
| 182 |
+
height: 18px;
|
| 183 |
+
}
|
| 184 |
+
.who {
|
| 185 |
+
display: inline-flex;
|
| 186 |
+
align-items: center;
|
| 187 |
+
gap: 10px;
|
| 188 |
+
}
|
| 189 |
+
.who a {
|
| 190 |
+
color: var(--on-ink-muted);
|
| 191 |
+
font-size: 13px;
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
.ring {
|
| 195 |
+
width: 40px;
|
| 196 |
+
height: 40px;
|
| 197 |
+
position: relative;
|
| 198 |
+
}
|
| 199 |
+
.ring svg {
|
| 200 |
+
width: 100%;
|
| 201 |
+
height: 100%;
|
| 202 |
+
transform: rotate(-90deg);
|
| 203 |
+
}
|
| 204 |
+
.ring .track {
|
| 205 |
+
stroke: rgba(231, 234, 243, 0.18);
|
| 206 |
+
}
|
| 207 |
+
.ring .left {
|
| 208 |
+
stroke: url(#depth-gradient);
|
| 209 |
+
transition: stroke-dashoffset 0.25s linear;
|
| 210 |
+
}
|
| 211 |
+
.ring span {
|
| 212 |
+
position: absolute;
|
| 213 |
+
inset: 0;
|
| 214 |
+
display: grid;
|
| 215 |
+
place-items: center;
|
| 216 |
+
font-size: 12px;
|
| 217 |
+
font-weight: 600;
|
| 218 |
+
font-variant-numeric: tabular-nums;
|
| 219 |
+
}
|
| 220 |
+
|
| 221 |
+
.overlay {
|
| 222 |
+
position: absolute;
|
| 223 |
+
left: 50%;
|
| 224 |
+
bottom: 28px;
|
| 225 |
+
transform: translateX(-50%);
|
| 226 |
+
width: min(420px, calc(100% - 32px));
|
| 227 |
+
display: grid;
|
| 228 |
+
justify-items: center;
|
| 229 |
+
gap: 12px;
|
| 230 |
+
text-align: center;
|
| 231 |
+
pointer-events: none;
|
| 232 |
+
}
|
| 233 |
+
.overlay > * {
|
| 234 |
+
pointer-events: auto;
|
| 235 |
+
}
|
| 236 |
+
.overlay.center {
|
| 237 |
+
bottom: auto;
|
| 238 |
+
top: 50%;
|
| 239 |
+
transform: translate(-50%, -50%);
|
| 240 |
+
}
|
| 241 |
+
.overlay p {
|
| 242 |
+
margin: 0;
|
| 243 |
+
font-size: 17px;
|
| 244 |
+
text-wrap: balance;
|
| 245 |
+
text-shadow: 0 1px 12px var(--ink);
|
| 246 |
+
}
|
| 247 |
+
.overlay .sub {
|
| 248 |
+
font-size: 14px;
|
| 249 |
+
color: var(--on-ink-muted);
|
| 250 |
+
}
|
| 251 |
+
.overlay.error p:first-child {
|
| 252 |
+
color: #ffb3a8;
|
| 253 |
+
}
|
| 254 |
+
.primary {
|
| 255 |
+
border: 0;
|
| 256 |
+
background: var(--near);
|
| 257 |
+
color: var(--ink);
|
| 258 |
+
font-weight: 600;
|
| 259 |
+
border-radius: 999px;
|
| 260 |
+
padding: 12px 26px;
|
| 261 |
+
font-size: 16px;
|
| 262 |
+
text-decoration: none;
|
| 263 |
+
display: inline-flex;
|
| 264 |
+
align-items: center;
|
| 265 |
+
gap: 10px;
|
| 266 |
+
}
|
| 267 |
+
.primary svg {
|
| 268 |
+
width: 20px;
|
| 269 |
+
height: 20px;
|
| 270 |
+
}
|
| 271 |
+
.actions {
|
| 272 |
+
display: flex;
|
| 273 |
+
flex-wrap: wrap;
|
| 274 |
+
justify-content: center;
|
| 275 |
+
align-items: center;
|
| 276 |
+
gap: 10px;
|
| 277 |
+
}
|
| 278 |
+
.actions .pill {
|
| 279 |
+
padding: 11px 18px;
|
| 280 |
+
font-size: 15px;
|
| 281 |
+
}
|
| 282 |
+
.busy {
|
| 283 |
+
width: 120px;
|
| 284 |
+
height: 3px;
|
| 285 |
+
border-radius: 2px;
|
| 286 |
+
background: linear-gradient(90deg, var(--far), var(--near), var(--far));
|
| 287 |
+
background-size: 200% 100%;
|
| 288 |
+
animation: slide 1.4s linear infinite;
|
| 289 |
+
}
|
| 290 |
+
@keyframes slide {
|
| 291 |
+
to {
|
| 292 |
+
background-position: -200% 0;
|
| 293 |
+
}
|
| 294 |
+
}
|
| 295 |
+
|
| 296 |
+
/* The panel: the controls, what this is, and the numbers */
|
| 297 |
+
.panel {
|
| 298 |
+
border-left: 1px solid var(--line);
|
| 299 |
+
padding: 28px 24px;
|
| 300 |
+
overflow-y: auto;
|
| 301 |
+
display: flex;
|
| 302 |
+
flex-direction: column;
|
| 303 |
+
gap: 22px;
|
| 304 |
+
}
|
| 305 |
+
.about {
|
| 306 |
+
order: 0;
|
| 307 |
+
}
|
| 308 |
+
.controls {
|
| 309 |
+
order: 1;
|
| 310 |
+
display: grid;
|
| 311 |
+
gap: 20px;
|
| 312 |
+
}
|
| 313 |
+
.details {
|
| 314 |
+
order: 2;
|
| 315 |
+
}
|
| 316 |
+
.footnote {
|
| 317 |
+
order: 3;
|
| 318 |
+
margin-top: auto;
|
| 319 |
+
font-size: 13px;
|
| 320 |
+
color: var(--muted);
|
| 321 |
+
}
|
| 322 |
+
h1 {
|
| 323 |
+
font-size: 26px;
|
| 324 |
+
line-height: 1.15;
|
| 325 |
+
font-weight: 600;
|
| 326 |
+
margin: 0;
|
| 327 |
+
letter-spacing: -0.01em;
|
| 328 |
+
}
|
| 329 |
+
.lede {
|
| 330 |
+
margin: 8px 0 0;
|
| 331 |
+
color: var(--muted);
|
| 332 |
+
max-width: 60ch;
|
| 333 |
+
}
|
| 334 |
+
|
| 335 |
+
.control {
|
| 336 |
+
display: grid;
|
| 337 |
+
gap: 8px;
|
| 338 |
+
}
|
| 339 |
+
.control > .name {
|
| 340 |
+
font-size: 14px;
|
| 341 |
+
font-weight: 500;
|
| 342 |
+
}
|
| 343 |
+
.control > .hint {
|
| 344 |
+
font-size: 13px;
|
| 345 |
+
color: var(--muted);
|
| 346 |
+
}
|
| 347 |
+
.segmented {
|
| 348 |
+
display: grid;
|
| 349 |
+
grid-auto-flow: column;
|
| 350 |
+
grid-auto-columns: 1fr;
|
| 351 |
+
border: 1px solid var(--line);
|
| 352 |
+
border-radius: 10px;
|
| 353 |
+
padding: 3px;
|
| 354 |
+
gap: 3px;
|
| 355 |
+
background: var(--field);
|
| 356 |
+
}
|
| 357 |
+
.segmented button {
|
| 358 |
+
border: 0;
|
| 359 |
+
background: transparent;
|
| 360 |
+
color: var(--muted);
|
| 361 |
+
border-radius: 7px;
|
| 362 |
+
padding: 7px 0;
|
| 363 |
+
font-size: 14px;
|
| 364 |
+
}
|
| 365 |
+
.segmented button[aria-pressed="true"] {
|
| 366 |
+
background: var(--fg);
|
| 367 |
+
color: var(--bg);
|
| 368 |
+
}
|
| 369 |
+
.segmented button:disabled {
|
| 370 |
+
opacity: 0.5;
|
| 371 |
+
cursor: default;
|
| 372 |
+
}
|
| 373 |
+
|
| 374 |
+
input[type="range"] {
|
| 375 |
+
-webkit-appearance: none;
|
| 376 |
+
appearance: none;
|
| 377 |
+
width: 100%;
|
| 378 |
+
height: 6px;
|
| 379 |
+
border-radius: 3px;
|
| 380 |
+
margin: 6px 0;
|
| 381 |
+
background: linear-gradient(90deg, var(--far), var(--near));
|
| 382 |
+
}
|
| 383 |
+
input[type="range"]::-webkit-slider-thumb {
|
| 384 |
+
-webkit-appearance: none;
|
| 385 |
+
appearance: none;
|
| 386 |
+
width: 20px;
|
| 387 |
+
height: 20px;
|
| 388 |
+
border-radius: 50%;
|
| 389 |
+
background: var(--field);
|
| 390 |
+
border: 2px solid var(--fg);
|
| 391 |
+
}
|
| 392 |
+
input[type="range"]::-moz-range-thumb {
|
| 393 |
+
width: 16px;
|
| 394 |
+
height: 16px;
|
| 395 |
+
border-radius: 50%;
|
| 396 |
+
background: var(--field);
|
| 397 |
+
border: 2px solid var(--fg);
|
| 398 |
+
}
|
| 399 |
+
.scale {
|
| 400 |
+
display: flex;
|
| 401 |
+
justify-content: space-between;
|
| 402 |
+
font-size: 12px;
|
| 403 |
+
color: var(--muted);
|
| 404 |
+
}
|
| 405 |
+
.scale output {
|
| 406 |
+
color: var(--fg);
|
| 407 |
+
font-weight: 600;
|
| 408 |
+
font-variant-numeric: tabular-nums;
|
| 409 |
+
}
|
| 410 |
+
input[type="range"]:disabled {
|
| 411 |
+
opacity: 0.45;
|
| 412 |
+
}
|
| 413 |
+
|
| 414 |
+
details {
|
| 415 |
+
border-top: 1px solid var(--line);
|
| 416 |
+
padding-top: 14px;
|
| 417 |
+
font-size: 14px;
|
| 418 |
+
}
|
| 419 |
+
summary {
|
| 420 |
+
cursor: pointer;
|
| 421 |
+
color: var(--muted);
|
| 422 |
+
}
|
| 423 |
+
dl {
|
| 424 |
+
display: grid;
|
| 425 |
+
grid-template-columns: auto 1fr;
|
| 426 |
+
gap: 4px 14px;
|
| 427 |
+
margin: 12px 0 0;
|
| 428 |
+
}
|
| 429 |
+
dt {
|
| 430 |
+
color: var(--muted);
|
| 431 |
+
}
|
| 432 |
+
dd {
|
| 433 |
+
margin: 0;
|
| 434 |
+
font-variant-numeric: tabular-nums;
|
| 435 |
+
overflow-wrap: anywhere;
|
| 436 |
+
}
|
| 437 |
+
|
| 438 |
+
/* Phones: the controls come right under the view, compact; the text after */
|
| 439 |
+
@media (max-width: 820px) {
|
| 440 |
+
.stage {
|
| 441 |
+
grid-template-columns: 1fr;
|
| 442 |
+
grid-template-rows: auto 58vh auto;
|
| 443 |
+
height: auto;
|
| 444 |
+
}
|
| 445 |
+
.stage {
|
| 446 |
+
grid-template-rows: auto 58dvh auto;
|
| 447 |
+
}
|
| 448 |
+
.topbar {
|
| 449 |
+
display: flex;
|
| 450 |
+
justify-content: flex-end;
|
| 451 |
+
align-items: center;
|
| 452 |
+
padding: 10px 14px 0;
|
| 453 |
+
background: var(--ink);
|
| 454 |
+
color: var(--on-ink);
|
| 455 |
+
}
|
| 456 |
+
.topbar:has(#account:empty) {
|
| 457 |
+
display: none;
|
| 458 |
+
}
|
| 459 |
+
.panel {
|
| 460 |
+
border-left: 0;
|
| 461 |
+
padding: 14px 16px 28px;
|
| 462 |
+
gap: 18px;
|
| 463 |
+
}
|
| 464 |
+
.controls {
|
| 465 |
+
order: 0;
|
| 466 |
+
gap: 12px;
|
| 467 |
+
}
|
| 468 |
+
.about {
|
| 469 |
+
order: 1;
|
| 470 |
+
border-top: 1px solid var(--line);
|
| 471 |
+
padding-top: 16px;
|
| 472 |
+
}
|
| 473 |
+
.control {
|
| 474 |
+
grid-template-columns: 64px 1fr;
|
| 475 |
+
align-items: center;
|
| 476 |
+
gap: 4px 10px;
|
| 477 |
+
}
|
| 478 |
+
.control > .name {
|
| 479 |
+
font-size: 13px;
|
| 480 |
+
color: var(--muted);
|
| 481 |
+
}
|
| 482 |
+
.control > .hint,
|
| 483 |
+
.control > .scale {
|
| 484 |
+
grid-column: 2;
|
| 485 |
+
}
|
| 486 |
+
.control > .hint {
|
| 487 |
+
font-size: 12px;
|
| 488 |
+
}
|
| 489 |
+
.segmented {
|
| 490 |
+
border-radius: 9px;
|
| 491 |
+
padding: 2px;
|
| 492 |
+
gap: 2px;
|
| 493 |
+
}
|
| 494 |
+
.segmented button {
|
| 495 |
+
padding: 5px 0;
|
| 496 |
+
font-size: 13px;
|
| 497 |
+
}
|
| 498 |
+
h1 {
|
| 499 |
+
font-size: 22px;
|
| 500 |
+
}
|
| 501 |
+
.overlay {
|
| 502 |
+
bottom: 18px;
|
| 503 |
+
}
|
| 504 |
+
.primary {
|
| 505 |
+
padding: 10px 22px;
|
| 506 |
+
font-size: 15px;
|
| 507 |
+
}
|
| 508 |
+
}
|
| 509 |
+
@media (prefers-reduced-motion: reduce) {
|
| 510 |
+
.busy {
|
| 511 |
+
animation: none;
|
| 512 |
+
}
|
| 513 |
+
.ring .left {
|
| 514 |
+
transition: none;
|
| 515 |
+
}
|
| 516 |
+
}
|
| 517 |
+
</style>
|
| 518 |
+
</head>
|
| 519 |
+
<body data-state="loading">
|
| 520 |
+
<svg width="0" height="0" style="position: absolute" aria-hidden="true">
|
| 521 |
+
<defs>
|
| 522 |
+
<linearGradient id="depth-gradient" x1="0" y1="0" x2="1" y2="1">
|
| 523 |
+
<stop offset="0" stop-color="#2ec4b6" />
|
| 524 |
+
<stop offset="1" stop-color="#ffb547" />
|
| 525 |
+
</linearGradient>
|
| 526 |
+
<symbol id="hf" viewBox="0 0 24 24">
|
| 527 |
+
<circle cx="12" cy="12" r="10" fill="#ffd21e" />
|
| 528 |
+
<circle cx="8.6" cy="10" r="1.3" fill="#3a2a10" />
|
| 529 |
+
<circle cx="15.4" cy="10" r="1.3" fill="#3a2a10" />
|
| 530 |
+
<path
|
| 531 |
+
d="M8 14.2c1 1.6 2.4 2.4 4 2.4s3-.8 4-2.4"
|
| 532 |
+
stroke="#3a2a10"
|
| 533 |
+
stroke-width="1.5"
|
| 534 |
+
fill="none"
|
| 535 |
+
stroke-linecap="round"
|
| 536 |
+
/>
|
| 537 |
+
</symbol>
|
| 538 |
+
</defs>
|
| 539 |
+
</svg>
|
| 540 |
+
<main class="stage">
|
| 541 |
+
<div class="topbar" id="topbar"></div>
|
| 542 |
+
<section
|
| 543 |
+
class="viewport"
|
| 544 |
+
id="viewport"
|
| 545 |
+
aria-label="3D view of the camera"
|
| 546 |
+
>
|
| 547 |
+
<video id="local" class="source" autoplay playsinline muted></video>
|
| 548 |
+
<video id="remote" class="source" autoplay playsinline muted></video>
|
| 549 |
+
|
| 550 |
+
<div class="bar">
|
| 551 |
+
<div class="ring" id="ring" aria-label="Seconds left" hidden>
|
| 552 |
+
<svg viewBox="0 0 40 40" aria-hidden="true">
|
| 553 |
+
<circle
|
| 554 |
+
class="track"
|
| 555 |
+
cx="20"
|
| 556 |
+
cy="20"
|
| 557 |
+
r="17"
|
| 558 |
+
fill="none"
|
| 559 |
+
stroke-width="3"
|
| 560 |
+
/>
|
| 561 |
+
<circle
|
| 562 |
+
class="left"
|
| 563 |
+
id="ring-left"
|
| 564 |
+
cx="20"
|
| 565 |
+
cy="20"
|
| 566 |
+
r="17"
|
| 567 |
+
fill="none"
|
| 568 |
+
stroke-width="3"
|
| 569 |
+
stroke-linecap="round"
|
| 570 |
+
stroke-dasharray="106.8"
|
| 571 |
+
stroke-dashoffset="0"
|
| 572 |
+
/>
|
| 573 |
+
</svg>
|
| 574 |
+
<span id="seconds"></span>
|
| 575 |
+
</div>
|
| 576 |
+
<button class="pill" id="stop" type="button" hidden>Stop</button>
|
| 577 |
+
<span class="spacer"></span>
|
| 578 |
+
<div id="account"></div>
|
| 579 |
+
</div>
|
| 580 |
+
|
| 581 |
+
<div class="overlay" id="overlay">
|
| 582 |
+
<p id="message">Loading</p>
|
| 583 |
+
<p class="sub" id="submessage" hidden></p>
|
| 584 |
+
<div class="busy" id="busy" hidden></div>
|
| 585 |
+
<button class="primary" id="start" type="button" hidden>
|
| 586 |
+
Turn on camera
|
| 587 |
+
</button>
|
| 588 |
+
<div class="actions" id="ready-actions" hidden>
|
| 589 |
+
<button class="primary" id="go" type="button">Start 3D view</button>
|
| 590 |
+
<button class="pill" id="camera-off" type="button">
|
| 591 |
+
Turn off camera
|
| 592 |
+
</button>
|
| 593 |
+
</div>
|
| 594 |
+
<a class="primary" id="signin-main" hidden
|
| 595 |
+
><svg aria-hidden="true"><use href="#hf" /></svg>Sign in with
|
| 596 |
+
Hugging Face</a
|
| 597 |
+
>
|
| 598 |
+
</div>
|
| 599 |
+
</section>
|
| 600 |
+
|
| 601 |
+
<aside class="panel">
|
| 602 |
+
<div class="about">
|
| 603 |
+
<h1>Your camera, in depth</h1>
|
| 604 |
+
<p class="lede">
|
| 605 |
+
Each frame goes to a GPU and comes back with how far away every
|
| 606 |
+
pixel is, and this page draws it as points you can turn around. Drag
|
| 607 |
+
to orbit, scroll or pinch to zoom.
|
| 608 |
+
</p>
|
| 609 |
+
</div>
|
| 610 |
+
|
| 611 |
+
<div class="controls">
|
| 612 |
+
<div class="control">
|
| 613 |
+
<span class="name" id="view-label">View</span>
|
| 614 |
+
<div class="segmented" role="group" aria-labelledby="view-label">
|
| 615 |
+
<button type="button" data-view="points" aria-pressed="true">
|
| 616 |
+
Points
|
| 617 |
+
</button>
|
| 618 |
+
<button type="button" data-view="surface" aria-pressed="false">
|
| 619 |
+
Surface
|
| 620 |
+
</button>
|
| 621 |
+
<button type="button" data-view="raw" aria-pressed="false">
|
| 622 |
+
Raw
|
| 623 |
+
</button>
|
| 624 |
+
</div>
|
| 625 |
+
</div>
|
| 626 |
+
|
| 627 |
+
<div class="control" id="camera-control" hidden>
|
| 628 |
+
<span class="name" id="camera-label">Camera</span>
|
| 629 |
+
<div class="segmented" role="group" aria-labelledby="camera-label">
|
| 630 |
+
<button type="button" data-facing="user" aria-pressed="true">
|
| 631 |
+
Front
|
| 632 |
+
</button>
|
| 633 |
+
<button
|
| 634 |
+
type="button"
|
| 635 |
+
data-facing="environment"
|
| 636 |
+
aria-pressed="false"
|
| 637 |
+
>
|
| 638 |
+
Back
|
| 639 |
+
</button>
|
| 640 |
+
</div>
|
| 641 |
+
</div>
|
| 642 |
+
|
| 643 |
+
<div class="control">
|
| 644 |
+
<span class="name" id="model-label">Model</span>
|
| 645 |
+
<div class="segmented" role="group" aria-labelledby="model-label">
|
| 646 |
+
<button type="button" data-model="large" aria-pressed="true">
|
| 647 |
+
Large
|
| 648 |
+
</button>
|
| 649 |
+
<button type="button" data-model="mono" aria-pressed="false">
|
| 650 |
+
Mono
|
| 651 |
+
</button>
|
| 652 |
+
<button type="button" data-model="metric" aria-pressed="false">
|
| 653 |
+
Metric
|
| 654 |
+
</button>
|
| 655 |
+
<button type="button" data-model="base" aria-pressed="false">
|
| 656 |
+
Base
|
| 657 |
+
</button>
|
| 658 |
+
<button type="button" data-model="small" aria-pressed="false">
|
| 659 |
+
Small
|
| 660 |
+
</button>
|
| 661 |
+
</div>
|
| 662 |
+
<span class="hint" id="model-hint"></span>
|
| 663 |
+
</div>
|
| 664 |
+
|
| 665 |
+
<label class="control">
|
| 666 |
+
<span class="name">Depth</span>
|
| 667 |
+
<input
|
| 668 |
+
id="strength"
|
| 669 |
+
type="range"
|
| 670 |
+
min="0"
|
| 671 |
+
max="2.5"
|
| 672 |
+
step="0.05"
|
| 673 |
+
value="1"
|
| 674 |
+
/>
|
| 675 |
+
<span class="scale"><span>Flat</span><span>Deep</span></span>
|
| 676 |
+
</label>
|
| 677 |
+
|
| 678 |
+
<label class="control">
|
| 679 |
+
<span class="name">Length</span>
|
| 680 |
+
<input
|
| 681 |
+
id="length"
|
| 682 |
+
type="range"
|
| 683 |
+
min="__MIN_SECONDS__"
|
| 684 |
+
max="__MAX_SECONDS__"
|
| 685 |
+
step="30"
|
| 686 |
+
value="__DEFAULT_SECONDS__"
|
| 687 |
+
/>
|
| 688 |
+
<span class="scale"
|
| 689 |
+
><span>30 s</span><output id="length-value" for="length"></output
|
| 690 |
+
><span>5 min</span></span
|
| 691 |
+
>
|
| 692 |
+
<span class="hint"
|
| 693 |
+
>GPU time, from your ZeroGPU quota. Fixed once a stream
|
| 694 |
+
starts.</span
|
| 695 |
+
>
|
| 696 |
+
</label>
|
| 697 |
+
</div>
|
| 698 |
+
|
| 699 |
+
<details class="details">
|
| 700 |
+
<summary>Stream details</summary>
|
| 701 |
+
<dl>
|
| 702 |
+
<dt>GPU</dt>
|
| 703 |
+
<dd id="d-device">-</dd>
|
| 704 |
+
<dt>Field of view</dt>
|
| 705 |
+
<dd id="d-fov">-</dd>
|
| 706 |
+
<dt>Frames back</dt>
|
| 707 |
+
<dd id="d-fps">-</dd>
|
| 708 |
+
<dt>Camera to GPU and back</dt>
|
| 709 |
+
<dd id="d-latency">-</dd>
|
| 710 |
+
</dl>
|
| 711 |
+
</details>
|
| 712 |
+
|
| 713 |
+
<p class="footnote">
|
| 714 |
+
Depth from
|
| 715 |
+
<a
|
| 716 |
+
href="https://huggingface.co/depth-anything"
|
| 717 |
+
target="_blank"
|
| 718 |
+
rel="noopener"
|
| 719 |
+
>Depth Anything 3</a
|
| 720 |
+
>, shown from __NEAR__ m to __FAR__ m; models without real scale are
|
| 721 |
+
scaled so that the middle of the scene sits at 1.5 m. A
|
| 722 |
+
<code>gr.Server</code> app streaming with
|
| 723 |
+
<code>@app.api(transport="webrtc")</code> and
|
| 724 |
+
<code>client.submit()</code>, from
|
| 725 |
+
<a
|
| 726 |
+
href="https://github.com/gradio-app/gradio/pull/13965"
|
| 727 |
+
target="_blank"
|
| 728 |
+
rel="noopener"
|
| 729 |
+
>gradio-app/gradio#13965</a
|
| 730 |
+
>
|
| 731 |
+
(<code>__COMMIT__</code>), one ZeroGPU call per stream, as long as you
|
| 732 |
+
pick, up to 5 min.
|
| 733 |
+
</p>
|
| 734 |
+
</aside>
|
| 735 |
+
</main>
|
| 736 |
+
|
| 737 |
+
<script type="module">
|
| 738 |
+
import * as THREE from "three";
|
| 739 |
+
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
|
| 740 |
+
import { Client } from "__CLIENT_URL__";
|
| 741 |
+
|
| 742 |
+
const ON_SPACES = __ON_SPACES__;
|
| 743 |
+
// The stream's length in seconds, picked with the slider before it starts
|
| 744 |
+
let seconds = __DEFAULT_SECONDS__;
|
| 745 |
+
const mmss = (s) =>
|
| 746 |
+
`${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
|
| 747 |
+
// Layout of the frames the server sends back: color, gutter, depth
|
| 748 |
+
const HALF = __HALF_WIDTH__;
|
| 749 |
+
const GUTTER = __GUTTER__;
|
| 750 |
+
const SBS_HALF_U = HALF / (2 * HALF + GUTTER);
|
| 751 |
+
const SBS_DEPTH_U = (HALF + GUTTER) / (2 * HALF + GUTTER);
|
| 752 |
+
// Gray in the depth half is inverse depth between these distances (meters)
|
| 753 |
+
const NEAR = __NEAR__;
|
| 754 |
+
const FAR = __FAR__;
|
| 755 |
+
// The distance the picture sits at before it has depth, and the orbit center
|
| 756 |
+
const Z_REF = 1.6;
|
| 757 |
+
// Assumed horizontal field of view of a webcam
|
| 758 |
+
const FOV_H = (62 * Math.PI) / 180;
|
| 759 |
+
const SEG_X = 192;
|
| 760 |
+
const SEG_Y = 144;
|
| 761 |
+
const REDUCED_MOTION = matchMedia(
|
| 762 |
+
"(prefers-reduced-motion: reduce)"
|
| 763 |
+
).matches;
|
| 764 |
+
const MODEL_HINTS = {
|
| 765 |
+
large:
|
| 766 |
+
"Estimates the camera's field of view too, so shapes keep their proportions.",
|
| 767 |
+
mono: "Made for single images; predicts depth itself rather than disparity. Assumes a 62° camera.",
|
| 768 |
+
metric: "Real distances in meters. Assumes a 62° camera.",
|
| 769 |
+
base: "Like Large, smaller and faster.",
|
| 770 |
+
small: "Like Large, smallest and fastest."
|
| 771 |
+
};
|
| 772 |
+
|
| 773 |
+
const $ = (id) => document.getElementById(id);
|
| 774 |
+
const setState = (s) => (document.body.dataset.state = s);
|
| 775 |
+
// The running stream, its camera, and whether that camera is shown mirrored
|
| 776 |
+
let stream = null;
|
| 777 |
+
let media = null;
|
| 778 |
+
let mirror = true;
|
| 779 |
+
|
| 780 |
+
// ---------- 3D scene ----------
|
| 781 |
+
const viewport = $("viewport");
|
| 782 |
+
const renderer = new THREE.WebGLRenderer({
|
| 783 |
+
antialias: true,
|
| 784 |
+
alpha: true
|
| 785 |
+
});
|
| 786 |
+
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
|
| 787 |
+
viewport.prepend(renderer.domElement);
|
| 788 |
+
|
| 789 |
+
const scene = new THREE.Scene();
|
| 790 |
+
const camera = new THREE.PerspectiveCamera(55, 1, 0.05, 50);
|
| 791 |
+
camera.position.set(0, 0, 0.35);
|
| 792 |
+
const controls = new OrbitControls(camera, renderer.domElement);
|
| 793 |
+
controls.target.set(0, 0, -Z_REF);
|
| 794 |
+
controls.enableDamping = true;
|
| 795 |
+
controls.minAzimuthAngle = -1.1;
|
| 796 |
+
controls.maxAzimuthAngle = 1.1;
|
| 797 |
+
controls.minPolarAngle = 0.5;
|
| 798 |
+
controls.maxPolarAngle = Math.PI - 0.5;
|
| 799 |
+
controls.minDistance = 0.4;
|
| 800 |
+
controls.maxDistance = 6;
|
| 801 |
+
controls.update();
|
| 802 |
+
let touched = false;
|
| 803 |
+
controls.addEventListener("start", () => (touched = true));
|
| 804 |
+
|
| 805 |
+
const uniforms = {
|
| 806 |
+
uTex: { value: null },
|
| 807 |
+
uHalfU: { value: 1 },
|
| 808 |
+
uDepthU: { value: 0 },
|
| 809 |
+
uHasDepth: { value: 0 },
|
| 810 |
+
uRise: { value: 1 },
|
| 811 |
+
uStrength: { value: 1 },
|
| 812 |
+
uTanH: { value: Math.tan(FOV_H / 2) },
|
| 813 |
+
uAspect: { value: 4 / 3 },
|
| 814 |
+
uTexel: { value: new THREE.Vector2(1 / SEG_X, 1 / SEG_Y) },
|
| 815 |
+
uPointScale: { value: 2 },
|
| 816 |
+
uEdgeCut: { value: 0.12 },
|
| 817 |
+
uRound: { value: 1 },
|
| 818 |
+
uMirror: { value: 1 }
|
| 819 |
+
};
|
| 820 |
+
const vertexShader = /* glsl */ `
|
| 821 |
+
uniform sampler2D uTex;
|
| 822 |
+
uniform float uHalfU, uDepthU, uHasDepth, uRise, uStrength, uTanH, uAspect, uPointScale, uMirror;
|
| 823 |
+
uniform vec2 uTexel;
|
| 824 |
+
varying vec3 vColor;
|
| 825 |
+
varying float vEdge;
|
| 826 |
+
const float NEAR = ${NEAR.toFixed(3)};
|
| 827 |
+
const float FAR = ${FAR.toFixed(3)};
|
| 828 |
+
const float Z_REF = ${Z_REF.toFixed(3)};
|
| 829 |
+
float zAt(vec2 st) {
|
| 830 |
+
float g = texture2D(uTex, vec2(uDepthU + st.x * uHalfU, st.y)).r;
|
| 831 |
+
float z = 1.0 / mix(1.0 / FAR, 1.0 / NEAR, g);
|
| 832 |
+
return Z_REF + uStrength * uHasDepth * uRise * (z - Z_REF);
|
| 833 |
+
}
|
| 834 |
+
void main() {
|
| 835 |
+
vec2 st = uv;
|
| 836 |
+
float z = zAt(st);
|
| 837 |
+
float x = (st.x - 0.5) * 2.0 * uTanH * z * uMirror;
|
| 838 |
+
float y = (st.y - 0.5) * 2.0 * uTanH / uAspect * z;
|
| 839 |
+
vColor = texture2D(uTex, vec2(st.x * uHalfU, st.y)).rgb;
|
| 840 |
+
float zx = zAt(st + vec2(uTexel.x, 0.0));
|
| 841 |
+
float zy = zAt(st + vec2(0.0, uTexel.y));
|
| 842 |
+
vEdge = max(abs(zx - z), abs(zy - z)) / z;
|
| 843 |
+
vec4 mv = modelViewMatrix * vec4(x, y, -z, 1.0);
|
| 844 |
+
gl_Position = projectionMatrix * mv;
|
| 845 |
+
gl_PointSize = uPointScale * ${(SEG_X / 96).toFixed(1)} / -mv.z * 3.0;
|
| 846 |
+
}
|
| 847 |
+
`;
|
| 848 |
+
const fragmentShader = /* glsl */ `
|
| 849 |
+
uniform float uEdgeCut, uRound;
|
| 850 |
+
varying vec3 vColor;
|
| 851 |
+
varying float vEdge;
|
| 852 |
+
void main() {
|
| 853 |
+
if (vEdge > uEdgeCut) discard;
|
| 854 |
+
if (uRound > 0.5) {
|
| 855 |
+
vec2 c = gl_PointCoord - 0.5;
|
| 856 |
+
if (dot(c, c) > 0.25) discard;
|
| 857 |
+
}
|
| 858 |
+
gl_FragColor = vec4(vColor, 1.0);
|
| 859 |
+
}
|
| 860 |
+
`;
|
| 861 |
+
const geometry = new THREE.PlaneGeometry(1, 1, SEG_X, SEG_Y);
|
| 862 |
+
const pointsMaterial = new THREE.ShaderMaterial({
|
| 863 |
+
uniforms,
|
| 864 |
+
vertexShader,
|
| 865 |
+
fragmentShader
|
| 866 |
+
});
|
| 867 |
+
const surfaceUniforms = {
|
| 868 |
+
...uniforms,
|
| 869 |
+
uEdgeCut: { value: 0.05 },
|
| 870 |
+
uRound: { value: 0 }
|
| 871 |
+
};
|
| 872 |
+
const surfaceMaterial = new THREE.ShaderMaterial({
|
| 873 |
+
uniforms: surfaceUniforms,
|
| 874 |
+
vertexShader,
|
| 875 |
+
fragmentShader,
|
| 876 |
+
side: THREE.DoubleSide
|
| 877 |
+
});
|
| 878 |
+
const points = new THREE.Points(geometry, pointsMaterial);
|
| 879 |
+
const surface = new THREE.Mesh(geometry, surfaceMaterial);
|
| 880 |
+
points.frustumCulled = surface.frustumCulled = false;
|
| 881 |
+
scene.add(points);
|
| 882 |
+
surface.visible = false;
|
| 883 |
+
scene.add(surface);
|
| 884 |
+
|
| 885 |
+
function useTexture(texture, { sbs, width, height, mirror }) {
|
| 886 |
+
uniforms.uTex.value = texture;
|
| 887 |
+
uniforms.uHalfU.value = sbs ? SBS_HALF_U : 1;
|
| 888 |
+
uniforms.uDepthU.value = sbs ? SBS_DEPTH_U : 0;
|
| 889 |
+
uniforms.uAspect.value = ((sbs ? SBS_HALF_U : 1) * width) / height;
|
| 890 |
+
uniforms.uMirror.value = mirror ? -1 : 1;
|
| 891 |
+
}
|
| 892 |
+
|
| 893 |
+
// Before the stream: a small made-up RGBD scene, drawn the same way
|
| 894 |
+
function demoTexture() {
|
| 895 |
+
const h = 240;
|
| 896 |
+
const canvas = document.createElement("canvas");
|
| 897 |
+
canvas.width = 2 * HALF + GUTTER;
|
| 898 |
+
canvas.height = h;
|
| 899 |
+
const ctx = canvas.getContext("2d");
|
| 900 |
+
const blobs = [
|
| 901 |
+
{ x: 0.32, y: 0.55, r: 0.2, near: 0.95, color: "#ffb547" },
|
| 902 |
+
{ x: 0.62, y: 0.45, r: 0.16, near: 0.75, color: "#ff7a6b" },
|
| 903 |
+
{ x: 0.78, y: 0.7, r: 0.12, near: 0.6, color: "#2ec4b6" }
|
| 904 |
+
];
|
| 905 |
+
const bg = ctx.createLinearGradient(0, 0, 0, h);
|
| 906 |
+
bg.addColorStop(0, "#2a3466");
|
| 907 |
+
bg.addColorStop(1, "#141a33");
|
| 908 |
+
ctx.fillStyle = bg;
|
| 909 |
+
ctx.fillRect(0, 0, HALF, h);
|
| 910 |
+
for (const b of blobs) {
|
| 911 |
+
ctx.fillStyle = b.color;
|
| 912 |
+
ctx.beginPath();
|
| 913 |
+
ctx.arc(b.x * HALF, b.y * h, b.r * HALF, 0, Math.PI * 2);
|
| 914 |
+
ctx.fill();
|
| 915 |
+
}
|
| 916 |
+
// depth half: a sloping floor, the blobs as domes in front of it
|
| 917 |
+
const x0 = HALF + GUTTER;
|
| 918 |
+
const floor = ctx.createLinearGradient(0, 0, 0, h);
|
| 919 |
+
floor.addColorStop(0, "#000");
|
| 920 |
+
floor.addColorStop(1, "#555");
|
| 921 |
+
ctx.fillStyle = floor;
|
| 922 |
+
ctx.fillRect(x0, 0, HALF, h);
|
| 923 |
+
for (const b of blobs) {
|
| 924 |
+
const g = ctx.createRadialGradient(
|
| 925 |
+
x0 + b.x * HALF,
|
| 926 |
+
b.y * h,
|
| 927 |
+
0,
|
| 928 |
+
x0 + b.x * HALF,
|
| 929 |
+
b.y * h,
|
| 930 |
+
b.r * HALF
|
| 931 |
+
);
|
| 932 |
+
const v = Math.round(b.near * 255);
|
| 933 |
+
g.addColorStop(0, `rgb(${v},${v},${v})`);
|
| 934 |
+
g.addColorStop(1, `rgb(${v - 50},${v - 50},${v - 50})`);
|
| 935 |
+
ctx.fillStyle = g;
|
| 936 |
+
ctx.beginPath();
|
| 937 |
+
ctx.arc(x0 + b.x * HALF, b.y * h, b.r * HALF, 0, Math.PI * 2);
|
| 938 |
+
ctx.fill();
|
| 939 |
+
}
|
| 940 |
+
const texture = new THREE.CanvasTexture(canvas);
|
| 941 |
+
texture.minFilter = texture.magFilter = THREE.LinearFilter;
|
| 942 |
+
texture.generateMipmaps = false;
|
| 943 |
+
return { texture, width: canvas.width, height: h };
|
| 944 |
+
}
|
| 945 |
+
const demo = demoTexture();
|
| 946 |
+
function setFov(degrees) {
|
| 947 |
+
uniforms.uTanH.value = Math.tan((degrees * Math.PI) / 360);
|
| 948 |
+
}
|
| 949 |
+
function showDemo() {
|
| 950 |
+
useTexture(demo.texture, {
|
| 951 |
+
sbs: true,
|
| 952 |
+
width: demo.width,
|
| 953 |
+
height: demo.height,
|
| 954 |
+
mirror: false
|
| 955 |
+
});
|
| 956 |
+
setFov(62);
|
| 957 |
+
uniforms.uHasDepth.value = 1;
|
| 958 |
+
uniforms.uRise.value = 1;
|
| 959 |
+
}
|
| 960 |
+
showDemo();
|
| 961 |
+
|
| 962 |
+
function videoTexture(video) {
|
| 963 |
+
const t = new THREE.VideoTexture(video);
|
| 964 |
+
t.minFilter = t.magFilter = THREE.LinearFilter;
|
| 965 |
+
t.generateMipmaps = false;
|
| 966 |
+
return t;
|
| 967 |
+
}
|
| 968 |
+
const localTexture = videoTexture($("local"));
|
| 969 |
+
const remoteTexture = videoTexture($("remote"));
|
| 970 |
+
|
| 971 |
+
// The one animation: the flat picture rises into depth
|
| 972 |
+
let rise = null;
|
| 973 |
+
function riseIntoDepth() {
|
| 974 |
+
if (REDUCED_MOTION) {
|
| 975 |
+
uniforms.uRise.value = 1;
|
| 976 |
+
return;
|
| 977 |
+
}
|
| 978 |
+
rise = { start: performance.now(), ms: 1400 };
|
| 979 |
+
uniforms.uRise.value = 0;
|
| 980 |
+
}
|
| 981 |
+
|
| 982 |
+
function resize() {
|
| 983 |
+
const { clientWidth: w, clientHeight: h } = viewport;
|
| 984 |
+
renderer.setSize(w, h, false);
|
| 985 |
+
camera.aspect = w / h;
|
| 986 |
+
// Keep about 70 degrees across, so that a portrait phone sees the whole frame
|
| 987 |
+
const fovX = (70 * Math.PI) / 180;
|
| 988 |
+
camera.fov = Math.min(
|
| 989 |
+
100,
|
| 990 |
+
Math.max(
|
| 991 |
+
55,
|
| 992 |
+
(2 * Math.atan(Math.tan(fovX / 2) / camera.aspect) * 180) / Math.PI
|
| 993 |
+
)
|
| 994 |
+
);
|
| 995 |
+
camera.updateProjectionMatrix();
|
| 996 |
+
uniforms.uPointScale.value = (renderer.getPixelRatio() * h) / 480;
|
| 997 |
+
}
|
| 998 |
+
new ResizeObserver(resize).observe(viewport);
|
| 999 |
+
resize();
|
| 1000 |
+
|
| 1001 |
+
const clock = new THREE.Clock();
|
| 1002 |
+
renderer.setAnimationLoop(() => {
|
| 1003 |
+
const t = clock.getElapsedTime();
|
| 1004 |
+
if (rise) {
|
| 1005 |
+
const k = Math.min(1, (performance.now() - rise.start) / rise.ms);
|
| 1006 |
+
uniforms.uRise.value = 1 - Math.pow(1 - k, 3);
|
| 1007 |
+
if (k >= 1) rise = null;
|
| 1008 |
+
}
|
| 1009 |
+
if (!touched && !REDUCED_MOTION) {
|
| 1010 |
+
// A slow swing, so that the depth shows without touching anything
|
| 1011 |
+
const a = 0.35 * Math.sin(t * 0.45);
|
| 1012 |
+
const r = Z_REF + 0.35;
|
| 1013 |
+
camera.position.set(
|
| 1014 |
+
Math.sin(a) * r,
|
| 1015 |
+
0.08 * Math.sin(t * 0.3),
|
| 1016 |
+
-Z_REF + Math.cos(a) * r
|
| 1017 |
+
);
|
| 1018 |
+
}
|
| 1019 |
+
controls.update();
|
| 1020 |
+
renderer.render(scene, camera);
|
| 1021 |
+
});
|
| 1022 |
+
|
| 1023 |
+
// ---------- Controls ----------
|
| 1024 |
+
function press(attribute, value) {
|
| 1025 |
+
for (const b of document.querySelectorAll(`[data-${attribute}]`)) {
|
| 1026 |
+
b.setAttribute(
|
| 1027 |
+
"aria-pressed",
|
| 1028 |
+
String(b.dataset[attribute] === value)
|
| 1029 |
+
);
|
| 1030 |
+
}
|
| 1031 |
+
}
|
| 1032 |
+
function setView(view) {
|
| 1033 |
+
press("view", view);
|
| 1034 |
+
points.visible = view === "points";
|
| 1035 |
+
surface.visible = view === "surface";
|
| 1036 |
+
viewport.classList.toggle("raw", view === "raw");
|
| 1037 |
+
}
|
| 1038 |
+
for (const b of document.querySelectorAll("[data-view]")) {
|
| 1039 |
+
b.onclick = () => setView(b.dataset.view);
|
| 1040 |
+
}
|
| 1041 |
+
|
| 1042 |
+
let model = "large";
|
| 1043 |
+
function setModel(next) {
|
| 1044 |
+
model = next;
|
| 1045 |
+
press("model", model);
|
| 1046 |
+
$("model-hint").textContent = MODEL_HINTS[model];
|
| 1047 |
+
// A running stream switches on its next frame
|
| 1048 |
+
stream?.send_chunk({ data: [null, model, seconds] });
|
| 1049 |
+
}
|
| 1050 |
+
for (const b of document.querySelectorAll("[data-model]")) {
|
| 1051 |
+
b.onclick = () => setModel(b.dataset.model);
|
| 1052 |
+
}
|
| 1053 |
+
setModel(model);
|
| 1054 |
+
|
| 1055 |
+
function showLength() {
|
| 1056 |
+
seconds = Number($("length").value);
|
| 1057 |
+
$("length-value").textContent = mmss(seconds);
|
| 1058 |
+
$("seconds").textContent = String(seconds);
|
| 1059 |
+
}
|
| 1060 |
+
$("length").oninput = showLength;
|
| 1061 |
+
|
| 1062 |
+
$("strength").oninput = (e) =>
|
| 1063 |
+
(uniforms.uStrength.value = Number(e.target.value));
|
| 1064 |
+
|
| 1065 |
+
let facing = "user";
|
| 1066 |
+
const COARSE = matchMedia("(pointer: coarse)").matches;
|
| 1067 |
+
async function showCameraControl() {
|
| 1068 |
+
let cameras = 0;
|
| 1069 |
+
try {
|
| 1070 |
+
const devices = await navigator.mediaDevices.enumerateDevices();
|
| 1071 |
+
cameras = devices.filter((d) => d.kind === "videoinput").length;
|
| 1072 |
+
} catch {}
|
| 1073 |
+
$("camera-control").hidden = !(COARSE || cameras > 1);
|
| 1074 |
+
}
|
| 1075 |
+
showCameraControl();
|
| 1076 |
+
for (const b of document.querySelectorAll("[data-facing]")) {
|
| 1077 |
+
b.onclick = () => setFacing(b.dataset.facing);
|
| 1078 |
+
}
|
| 1079 |
+
|
| 1080 |
+
// ---------- Messages and the time ring ----------
|
| 1081 |
+
function overlay({
|
| 1082 |
+
message,
|
| 1083 |
+
sub = "",
|
| 1084 |
+
busy = false,
|
| 1085 |
+
action = null,
|
| 1086 |
+
error = false,
|
| 1087 |
+
center = false
|
| 1088 |
+
}) {
|
| 1089 |
+
const box = $("overlay");
|
| 1090 |
+
box.hidden = false;
|
| 1091 |
+
box.classList.toggle("error", error);
|
| 1092 |
+
box.classList.toggle("center", center);
|
| 1093 |
+
$("message").textContent = message;
|
| 1094 |
+
$("submessage").textContent = sub;
|
| 1095 |
+
$("submessage").hidden = !sub;
|
| 1096 |
+
$("busy").hidden = !busy;
|
| 1097 |
+
$("start").hidden = action !== "start";
|
| 1098 |
+
$("ready-actions").hidden = action !== "go";
|
| 1099 |
+
$("signin-main").hidden = action !== "signin";
|
| 1100 |
+
}
|
| 1101 |
+
const hideOverlay = () => ($("overlay").hidden = true);
|
| 1102 |
+
|
| 1103 |
+
let countdown = null;
|
| 1104 |
+
function startCountdown() {
|
| 1105 |
+
const length = seconds;
|
| 1106 |
+
const ends = performance.now() + length * 1000;
|
| 1107 |
+
const circle = $("ring-left");
|
| 1108 |
+
const ring = 2 * Math.PI * 17;
|
| 1109 |
+
const tick = () => {
|
| 1110 |
+
const left = Math.max(0, (ends - performance.now()) / 1000);
|
| 1111 |
+
$("seconds").textContent = Math.ceil(left);
|
| 1112 |
+
circle.style.strokeDashoffset = String(ring * (1 - left / length));
|
| 1113 |
+
};
|
| 1114 |
+
tick();
|
| 1115 |
+
countdown = setInterval(tick, 250);
|
| 1116 |
+
}
|
| 1117 |
+
function streaming(on) {
|
| 1118 |
+
// The length goes with the GPU request, made when the stream starts
|
| 1119 |
+
$("length").disabled = on;
|
| 1120 |
+
$("ring").hidden = !on;
|
| 1121 |
+
$("stop").hidden = !on;
|
| 1122 |
+
if (!on) {
|
| 1123 |
+
clearInterval(countdown);
|
| 1124 |
+
countdown = null;
|
| 1125 |
+
}
|
| 1126 |
+
}
|
| 1127 |
+
|
| 1128 |
+
// ---------- Account ----------
|
| 1129 |
+
const app = await Client.connect(location.origin, {
|
| 1130 |
+
events: ["data", "status"]
|
| 1131 |
+
});
|
| 1132 |
+
const back = encodeURIComponent("/" + location.search);
|
| 1133 |
+
const signInUrl = `/login/huggingface?_target_url=${back}`;
|
| 1134 |
+
$("signin-main").href = signInUrl;
|
| 1135 |
+
let user = "";
|
| 1136 |
+
if (ON_SPACES) {
|
| 1137 |
+
user = (await app.predict("/whoami", [])).data[0];
|
| 1138 |
+
const account = $("account");
|
| 1139 |
+
const narrow = matchMedia("(max-width: 820px)");
|
| 1140 |
+
const place = () =>
|
| 1141 |
+
(narrow.matches
|
| 1142 |
+
? $("topbar")
|
| 1143 |
+
: document.querySelector(".bar")
|
| 1144 |
+
).append(account);
|
| 1145 |
+
narrow.addEventListener("change", place);
|
| 1146 |
+
place();
|
| 1147 |
+
if (user) {
|
| 1148 |
+
account.className = "pill who";
|
| 1149 |
+
account.innerHTML = `<span></span><a href="/logout?_target_url=${back}">Sign out</a>`;
|
| 1150 |
+
account.querySelector("span").textContent = user;
|
| 1151 |
+
} else {
|
| 1152 |
+
account.innerHTML = `<a class="pill signin" href="${signInUrl}"><svg aria-hidden="true"><use href="#hf"/></svg>Sign in</a>`;
|
| 1153 |
+
}
|
| 1154 |
+
}
|
| 1155 |
+
|
| 1156 |
+
// The camera is off
|
| 1157 |
+
function idle(
|
| 1158 |
+
message = "Your camera, drawn in depth.",
|
| 1159 |
+
sub = "",
|
| 1160 |
+
error = false
|
| 1161 |
+
) {
|
| 1162 |
+
setState(error ? "error" : "idle");
|
| 1163 |
+
streaming(false);
|
| 1164 |
+
showDemo();
|
| 1165 |
+
if (ON_SPACES && !user) {
|
| 1166 |
+
overlay({
|
| 1167 |
+
message:
|
| 1168 |
+
"Sign in to start. The GPU time is counted on your Hugging Face account.",
|
| 1169 |
+
action: "signin"
|
| 1170 |
+
});
|
| 1171 |
+
return;
|
| 1172 |
+
}
|
| 1173 |
+
overlay({ message, sub, action: "start", error });
|
| 1174 |
+
}
|
| 1175 |
+
|
| 1176 |
+
// The camera is on and nothing streams: the visitor picks the camera, the
|
| 1177 |
+
// model and the length, then starts. The GPU is asked for only then.
|
| 1178 |
+
async function preview(
|
| 1179 |
+
message = "Your camera is on.",
|
| 1180 |
+
sub = "Line up your shot. GPU time starts with the 3D view.",
|
| 1181 |
+
error = false
|
| 1182 |
+
) {
|
| 1183 |
+
setState("preview");
|
| 1184 |
+
streaming(false);
|
| 1185 |
+
uniforms.uHasDepth.value = 0;
|
| 1186 |
+
overlay({ message, sub, action: "go", error });
|
| 1187 |
+
if (media) await showLocal();
|
| 1188 |
+
}
|
| 1189 |
+
|
| 1190 |
+
// ---------- Camera and stream ----------
|
| 1191 |
+
$("stop").onclick = () => stream?.cancel();
|
| 1192 |
+
$("start").onclick = startCamera;
|
| 1193 |
+
$("go").onclick = startStream;
|
| 1194 |
+
$("camera-off").onclick = releaseCamera;
|
| 1195 |
+
|
| 1196 |
+
// A camera that stops by itself (unplugged, permission taken back)
|
| 1197 |
+
function watchCamera(stream_media) {
|
| 1198 |
+
stream_media.getVideoTracks()[0]?.addEventListener("ended", () => {
|
| 1199 |
+
if (media === stream_media && !stream)
|
| 1200 |
+
releaseCamera("The camera stopped.");
|
| 1201 |
+
});
|
| 1202 |
+
}
|
| 1203 |
+
|
| 1204 |
+
async function startCamera() {
|
| 1205 |
+
if (stream) return;
|
| 1206 |
+
if (media) return preview();
|
| 1207 |
+
setState("camera");
|
| 1208 |
+
overlay({
|
| 1209 |
+
message: "Asking for your camera",
|
| 1210 |
+
busy: true,
|
| 1211 |
+
center: true
|
| 1212 |
+
});
|
| 1213 |
+
try {
|
| 1214 |
+
media = await openCamera(facing);
|
| 1215 |
+
} catch (error) {
|
| 1216 |
+
media = null;
|
| 1217 |
+
idle("The camera did not start.", error.message, true);
|
| 1218 |
+
return;
|
| 1219 |
+
}
|
| 1220 |
+
watchCamera(media);
|
| 1221 |
+
showCameraControl();
|
| 1222 |
+
mirror = facing === "user";
|
| 1223 |
+
await preview();
|
| 1224 |
+
}
|
| 1225 |
+
|
| 1226 |
+
function releaseCamera(message) {
|
| 1227 |
+
if (stream) return;
|
| 1228 |
+
media?.getTracks().forEach((track) => track.stop());
|
| 1229 |
+
media = null;
|
| 1230 |
+
$("local").srcObject = null;
|
| 1231 |
+
idle(typeof message === "string" ? message : undefined);
|
| 1232 |
+
}
|
| 1233 |
+
|
| 1234 |
+
function openCamera(which) {
|
| 1235 |
+
return navigator.mediaDevices.getUserMedia({
|
| 1236 |
+
video: {
|
| 1237 |
+
facingMode: which,
|
| 1238 |
+
width: { ideal: 640 },
|
| 1239 |
+
height: { ideal: 480 }
|
| 1240 |
+
},
|
| 1241 |
+
audio: false
|
| 1242 |
+
});
|
| 1243 |
+
}
|
| 1244 |
+
|
| 1245 |
+
// The camera as a flat picture, while waiting for the first depth
|
| 1246 |
+
async function showLocal() {
|
| 1247 |
+
const local = $("local");
|
| 1248 |
+
local.srcObject = media;
|
| 1249 |
+
await local.play().catch(() => {});
|
| 1250 |
+
const settings = media.getVideoTracks()[0].getSettings();
|
| 1251 |
+
useTexture(localTexture, {
|
| 1252 |
+
sbs: false,
|
| 1253 |
+
width: settings.width || local.videoWidth || 640,
|
| 1254 |
+
height: settings.height || local.videoHeight || 480,
|
| 1255 |
+
mirror
|
| 1256 |
+
});
|
| 1257 |
+
}
|
| 1258 |
+
|
| 1259 |
+
async function setFacing(next) {
|
| 1260 |
+
if (next === facing) return;
|
| 1261 |
+
const previous = facing;
|
| 1262 |
+
facing = next;
|
| 1263 |
+
press("facing", facing);
|
| 1264 |
+
if (!media) return; // used at the next start
|
| 1265 |
+
// A running stream keeps going: the new camera's track replaces the old
|
| 1266 |
+
// one in the connection, so there is no new turn in line
|
| 1267 |
+
const old = media;
|
| 1268 |
+
old.getVideoTracks().forEach((track) => track.stop());
|
| 1269 |
+
try {
|
| 1270 |
+
media = await openCamera(facing);
|
| 1271 |
+
} catch (error) {
|
| 1272 |
+
facing = previous;
|
| 1273 |
+
press("facing", facing);
|
| 1274 |
+
try {
|
| 1275 |
+
media = await openCamera(facing);
|
| 1276 |
+
} catch {
|
| 1277 |
+
media = old;
|
| 1278 |
+
}
|
| 1279 |
+
overlay({
|
| 1280 |
+
message: "That camera did not start.",
|
| 1281 |
+
sub: error.message,
|
| 1282 |
+
error: true
|
| 1283 |
+
});
|
| 1284 |
+
setTimeout(
|
| 1285 |
+
() => document.body.dataset.state === "live" && hideOverlay(),
|
| 1286 |
+
3000
|
| 1287 |
+
);
|
| 1288 |
+
}
|
| 1289 |
+
watchCamera(media);
|
| 1290 |
+
mirror = facing === "user";
|
| 1291 |
+
uniforms.uMirror.value = mirror ? -1 : 1;
|
| 1292 |
+
// The new camera in the media slot: the running stream swaps tracks
|
| 1293 |
+
stream?.send_chunk({ data: [media, model, seconds] });
|
| 1294 |
+
if (uniforms.uTex.value === localTexture) await showLocal();
|
| 1295 |
+
else $("local").srcObject = media;
|
| 1296 |
+
}
|
| 1297 |
+
|
| 1298 |
+
async function startStream() {
|
| 1299 |
+
if (stream || !media) return;
|
| 1300 |
+
uniforms.uHasDepth.value = 0;
|
| 1301 |
+
setState("waiting");
|
| 1302 |
+
overlay({ message: "Joining the line", busy: true, center: true });
|
| 1303 |
+
// Stop also leaves the line; the length is fixed from here
|
| 1304 |
+
$("stop").hidden = false;
|
| 1305 |
+
$("length").disabled = true;
|
| 1306 |
+
|
| 1307 |
+
let ready = false;
|
| 1308 |
+
let failure = "";
|
| 1309 |
+
let connected = false;
|
| 1310 |
+
const current = app.submit("/depth", {
|
| 1311 |
+
frame: media,
|
| 1312 |
+
model,
|
| 1313 |
+
seconds
|
| 1314 |
+
});
|
| 1315 |
+
stream = current;
|
| 1316 |
+
// The camera stays on after the stream: back to the preview, from where
|
| 1317 |
+
// the visitor starts again or turns the camera off
|
| 1318 |
+
const after = (message, sub, error = false) => {
|
| 1319 |
+
$("remote").srcObject = null;
|
| 1320 |
+
if (stream === current) stream = null;
|
| 1321 |
+
if (media) preview(message, sub, error);
|
| 1322 |
+
else idle(message, sub, error);
|
| 1323 |
+
};
|
| 1324 |
+
const onStatus = (s) => {
|
| 1325 |
+
$("d-device").textContent = s.device || "-";
|
| 1326 |
+
if (s.fov) {
|
| 1327 |
+
// The model's estimate of the camera, when it makes one
|
| 1328 |
+
setFov(s.fov);
|
| 1329 |
+
$("d-fov").textContent =
|
| 1330 |
+
`${s.fov}° (${s.fov_estimated ? "estimated" : "assumed"})`;
|
| 1331 |
+
}
|
| 1332 |
+
$("d-fps").textContent = `${s.fps} per second`;
|
| 1333 |
+
$("d-latency").textContent =
|
| 1334 |
+
s.latency_ms == null ? "-" : `${s.latency_ms} ms`;
|
| 1335 |
+
if (s.ready && !ready) {
|
| 1336 |
+
ready = true;
|
| 1337 |
+
setState("live");
|
| 1338 |
+
hideOverlay();
|
| 1339 |
+
uniforms.uHasDepth.value = 1;
|
| 1340 |
+
riseIntoDepth();
|
| 1341 |
+
}
|
| 1342 |
+
};
|
| 1343 |
+
try {
|
| 1344 |
+
for await (const msg of current) {
|
| 1345 |
+
if (msg.type === "data") {
|
| 1346 |
+
const [video, s] = msg.data;
|
| 1347 |
+
if (video instanceof MediaStream && !connected) {
|
| 1348 |
+
// The video coming back means the stream is connected
|
| 1349 |
+
const remote = $("remote");
|
| 1350 |
+
remote.srcObject = video;
|
| 1351 |
+
remote.play().catch(() => {});
|
| 1352 |
+
const fitRemote = () =>
|
| 1353 |
+
useTexture(remoteTexture, {
|
| 1354 |
+
sbs: true,
|
| 1355 |
+
width: remote.videoWidth,
|
| 1356 |
+
height: remote.videoHeight,
|
| 1357 |
+
mirror
|
| 1358 |
+
});
|
| 1359 |
+
const swap = () => {
|
| 1360 |
+
if (stream !== current) return;
|
| 1361 |
+
if (remote.videoWidth === 0)
|
| 1362 |
+
return requestAnimationFrame(swap);
|
| 1363 |
+
fitRemote();
|
| 1364 |
+
remote.onresize = fitRemote;
|
| 1365 |
+
};
|
| 1366 |
+
swap();
|
| 1367 |
+
if (stream === current) {
|
| 1368 |
+
connected = true;
|
| 1369 |
+
setState("connecting");
|
| 1370 |
+
streaming(true);
|
| 1371 |
+
startCountdown();
|
| 1372 |
+
if (!ready)
|
| 1373 |
+
overlay({
|
| 1374 |
+
message: "Getting a GPU",
|
| 1375 |
+
busy: true,
|
| 1376 |
+
center: true
|
| 1377 |
+
});
|
| 1378 |
+
}
|
| 1379 |
+
}
|
| 1380 |
+
if (s && stream === current) onStatus(s);
|
| 1381 |
+
} else if (msg.type === "status") {
|
| 1382 |
+
if (msg.stage === "error")
|
| 1383 |
+
failure = msg.message || "Something went wrong.";
|
| 1384 |
+
if (
|
| 1385 |
+
stream !== current ||
|
| 1386 |
+
msg.stage !== "pending" ||
|
| 1387 |
+
msg.position == null
|
| 1388 |
+
)
|
| 1389 |
+
continue;
|
| 1390 |
+
const eta = msg.eta ? `About ${Math.round(msg.eta)} s.` : "";
|
| 1391 |
+
overlay({
|
| 1392 |
+
message:
|
| 1393 |
+
msg.position === 0
|
| 1394 |
+
? "You are next in line."
|
| 1395 |
+
: `${msg.position} ahead of you.`,
|
| 1396 |
+
sub: eta,
|
| 1397 |
+
busy: true,
|
| 1398 |
+
center: true
|
| 1399 |
+
});
|
| 1400 |
+
} else if (msg.type === "log" && msg.level !== "info" && msg.log) {
|
| 1401 |
+
// The server ends the stream with a reason when something went wrong
|
| 1402 |
+
// (e.g. ZeroGPU quota), and with none when the picked length is over
|
| 1403 |
+
failure = msg.log;
|
| 1404 |
+
}
|
| 1405 |
+
}
|
| 1406 |
+
failure
|
| 1407 |
+
? after("The stream stopped.", failure, true)
|
| 1408 |
+
: connected
|
| 1409 |
+
? after("The stream ended.", "Start again to keep going.")
|
| 1410 |
+
: after();
|
| 1411 |
+
} catch (error) {
|
| 1412 |
+
after("The stream stopped.", error.message, true);
|
| 1413 |
+
}
|
| 1414 |
+
}
|
| 1415 |
+
|
| 1416 |
+
showLength();
|
| 1417 |
+
idle();
|
| 1418 |
+
document.body.dataset.ready = "1";
|
| 1419 |
+
</script>
|
| 1420 |
+
</body>
|
| 1421 |
+
</html>
|
requirements.txt
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Pinned to a stack known to work on ZeroGPU. The PR's gradio wheel is installed
|
| 2 |
+
# by app.py at startup. psutil is left to spaces.
|
| 3 |
+
accelerate==1.14.0
|
| 4 |
+
addict==2.4.0
|
| 5 |
+
aioice==0.10.2
|
| 6 |
+
aiortc==1.15.0
|
| 7 |
+
annotated-doc==0.0.5
|
| 8 |
+
annotated-types==0.8.0
|
| 9 |
+
antlr4-python3-runtime==4.9.3
|
| 10 |
+
anyio==4.15.1
|
| 11 |
+
attrs==26.1.0
|
| 12 |
+
authlib==1.9.0
|
| 13 |
+
av==17.1.0
|
| 14 |
+
brotli==1.2.0
|
| 15 |
+
certifi==2026.7.22
|
| 16 |
+
cffi==2.1.1
|
| 17 |
+
charset-normalizer==3.5.2
|
| 18 |
+
click==8.5.0
|
| 19 |
+
cryptography==50.0.2
|
| 20 |
+
cuda-bindings==13.3.1
|
| 21 |
+
cuda-pathfinder==1.5.6
|
| 22 |
+
cuda-toolkit==13.0.2
|
| 23 |
+
diffusers==0.35.1
|
| 24 |
+
dnspython==2.8.0
|
| 25 |
+
einops==0.8.2
|
| 26 |
+
exceptiongroup==1.3.1
|
| 27 |
+
fastapi==0.143.0
|
| 28 |
+
filelock==4.1.0
|
| 29 |
+
fsspec==2026.9.0
|
| 30 |
+
ftfy==6.3.1
|
| 31 |
+
google-crc32c==1.9.0
|
| 32 |
+
gradio==6.30.0
|
| 33 |
+
gradio-client==2.7.2
|
| 34 |
+
groovy==0.1.2
|
| 35 |
+
h11==0.16.0
|
| 36 |
+
hf-gradio==0.4.1
|
| 37 |
+
hf-xet==1.7.0
|
| 38 |
+
httpcore==1.0.9
|
| 39 |
+
httpcore2==2.13.1
|
| 40 |
+
httpx==0.28.1
|
| 41 |
+
httpx-sse==0.4.3
|
| 42 |
+
httpx2==2.13.1
|
| 43 |
+
huggingface-hub==1.21.0
|
| 44 |
+
idna==3.20
|
| 45 |
+
ifaddr==0.2.0
|
| 46 |
+
imageio==2.37.3
|
| 47 |
+
imageio-ffmpeg==0.6.0
|
| 48 |
+
importlib-metadata==9.0.1
|
| 49 |
+
itsdangerous==2.2.0
|
| 50 |
+
jinja2==3.1.6
|
| 51 |
+
joserfc==1.7.5
|
| 52 |
+
jsonschema==4.26.0
|
| 53 |
+
jsonschema-specifications==2025.9.1
|
| 54 |
+
markdown-it-py==4.2.0
|
| 55 |
+
markdown2==2.5.5
|
| 56 |
+
markupsafe==3.0.4
|
| 57 |
+
mcp==1.30.0
|
| 58 |
+
mdurl==0.1.2
|
| 59 |
+
mpmath==1.3.0
|
| 60 |
+
networkx==3.4.2
|
| 61 |
+
numpy==1.26.4
|
| 62 |
+
nvidia-cublas==13.1.1.3
|
| 63 |
+
nvidia-cuda-cupti==13.0.85
|
| 64 |
+
nvidia-cuda-nvrtc==13.0.88
|
| 65 |
+
nvidia-cuda-runtime==13.0.96
|
| 66 |
+
nvidia-cudnn-cu13==9.20.0.48
|
| 67 |
+
nvidia-cufft==12.0.0.61
|
| 68 |
+
nvidia-cufile==1.15.1.6
|
| 69 |
+
nvidia-curand==10.4.0.35
|
| 70 |
+
nvidia-cusolver==12.0.4.66
|
| 71 |
+
nvidia-cusparse==12.6.3.3
|
| 72 |
+
nvidia-cusparselt-cu13==0.8.1
|
| 73 |
+
nvidia-nccl-cu13==2.29.7
|
| 74 |
+
nvidia-nvjitlink==13.0.88
|
| 75 |
+
nvidia-nvshmem-cu13==3.4.5
|
| 76 |
+
nvidia-nvtx==13.0.85
|
| 77 |
+
omegaconf==2.3.1
|
| 78 |
+
opentelemetry-api==1.45.1
|
| 79 |
+
orjson==3.13.0
|
| 80 |
+
packaging==26.3
|
| 81 |
+
pandas==2.3.3
|
| 82 |
+
pillow==12.3.0
|
| 83 |
+
pycparser==3.11
|
| 84 |
+
pydantic==2.12.5
|
| 85 |
+
pydantic-core==2.41.5
|
| 86 |
+
pydantic-settings==2.15.0
|
| 87 |
+
pydub==0.25.1
|
| 88 |
+
pyee==13.0.1
|
| 89 |
+
pygments==2.21.0
|
| 90 |
+
pyjwt==2.15.1
|
| 91 |
+
pylibsrtp==1.0.0
|
| 92 |
+
pyopenssl==26.4.0
|
| 93 |
+
python-dateutil==2.9.0.post0
|
| 94 |
+
python-dotenv==1.2.4
|
| 95 |
+
python-multipart==0.0.32
|
| 96 |
+
pytz==2026.5
|
| 97 |
+
pyyaml==6.0.3
|
| 98 |
+
referencing==0.37.0
|
| 99 |
+
regex==2026.6.28
|
| 100 |
+
requests==2.34.2
|
| 101 |
+
rich==15.0.0
|
| 102 |
+
rpds-py==0.30.0
|
| 103 |
+
safehttpx==0.1.7
|
| 104 |
+
safetensors==0.8.0
|
| 105 |
+
semantic-version==2.10.0
|
| 106 |
+
sentencepiece==0.2.1
|
| 107 |
+
setuptools==81.0.0
|
| 108 |
+
shellingham==1.5.4
|
| 109 |
+
six==1.17.0
|
| 110 |
+
sse-starlette==3.5.0
|
| 111 |
+
starlette==1.7.0
|
| 112 |
+
sympy==1.14.0
|
| 113 |
+
tokenizers==0.22.2
|
| 114 |
+
tomlkit==0.14.0
|
| 115 |
+
torch==2.12.1
|
| 116 |
+
torchvision==0.27.1
|
| 117 |
+
tqdm==4.70.1
|
| 118 |
+
transformers==5.12.1
|
| 119 |
+
triton==3.7.1
|
| 120 |
+
truststore==0.10.5
|
| 121 |
+
typer==0.25.1
|
| 122 |
+
typing-extensions==4.16.0
|
| 123 |
+
typing-inspection==0.4.4
|
| 124 |
+
tzdata==2026.5
|
| 125 |
+
urllib3==2.8.0
|
| 126 |
+
uvicorn==0.54.0
|
| 127 |
+
wcwidth==0.9.2
|
| 128 |
+
zipp==4.1.1
|