byoussef commited on
Commit
34f0034
·
verified ·
1 Parent(s): 3dedf9c

Camera on the live-video model; files from commit d45bcfa0

Browse files
Files changed (2) hide show
  1. README.md +2 -1
  2. index.html +128 -26
README.md CHANGED
@@ -8,7 +8,7 @@ pinned: false
8
  license: other
9
  license_name: apple-amlr
10
  license_link: https://github.com/apple-aiml-research/ml-depth-pro-2/blob/main/LICENSE_MODEL
11
- short_description: Depth from one photo, in your browser on WebGPU
12
  models:
13
  - byoussef/DepthPro2-litert
14
  tags:
@@ -23,6 +23,7 @@ tags:
23
 
24
  - Pick a sample, upload a photo or start the camera, then drag the divider between the photo and its depth.
25
  - Model S (98 MB) or B (387 MB), in float16 or float32. float16 needs the GPU's `shader-f16` feature; without it the page stays in float32.
 
26
  - "Depth in meters" adds the field-of-view model (95 MB), which estimates the focal length. Point at the picture to read a distance.
27
 
28
  It needs WebGPU: Chrome, Edge or Firefox on a computer. Safari 27.2 runs it and returns wrong depth.
 
8
  license: other
9
  license_name: apple-amlr
10
  license_link: https://github.com/apple-aiml-research/ml-depth-pro-2/blob/main/LICENSE_MODEL
11
+ short_description: Depth from a photo or the camera, in a browser on WebGPU
12
  models:
13
  - byoussef/DepthPro2-litert
14
  tags:
 
23
 
24
  - Pick a sample, upload a photo or start the camera, then drag the divider between the photo and its depth.
25
  - Model S (98 MB) or B (387 MB), in float16 or float32. float16 needs the GPU's `shader-f16` feature; without it the page stays in float32.
26
+ - The camera runs the video file of the same size, a second download of 99 or 388 MB. In it each frame also attends to the three frames before it, as in Depth Pro 2's live video mode, so the depth flickers less from frame to frame.
27
  - "Depth in meters" adds the field-of-view model (95 MB), which estimates the focal length. Point at the picture to read a distance.
28
 
29
  It needs WebGPU: Chrome, Edge or Firefox on a computer. Safari 27.2 runs it and returns wrong depth.
index.html CHANGED
@@ -4,7 +4,7 @@
4
  <meta charset="utf-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1">
6
  <title>Depth Pro 2 on WebGPU</title>
7
- <meta name="description" content="Depth from a single photo, computed in your browser on WebGPU with LiteRT.js.">
8
  <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Crect width='8' height='16' fill='%2358626b'/%3E%3Crect x='8' width='8' height='16' fill='%23f66b19'/%3E%3Crect x='7.25' width='1.5' height='16' fill='%23fff'/%3E%3C/svg%3E">
9
  <style>
10
  /* Hallmark · checked: 2026-11-24 · genre: modern-minimal (inferred)
@@ -389,7 +389,7 @@
389
  <div class="page">
390
  <header>
391
  <h1>Depth Pro 2 on WebGPU</h1>
392
- <p class="lede">Depth from a single photo, computed in this browser on your GPU. Photos stay on your device.</p>
393
  <nav>
394
  <a href="https://huggingface.co/byoussef/DepthPro2-litert" target="_blank" rel="noopener">Model files</a>
395
  <a href="https://huggingface.co/apple/DepthPro2" target="_blank" rel="noopener">Original model</a>
@@ -444,7 +444,7 @@
444
  <span id="camera-label">Camera</span>
445
  </button>
446
  </div>
447
- <p class="hint">Or drop a photo anywhere on the page. It is cropped to 16:9, the shape the models take.</p>
448
  </section>
449
 
450
  <fieldset class="group">
@@ -487,12 +487,18 @@
487
  <script type="module">
488
  const LITERT = 'https://cdn.jsdelivr.net/npm/@litertjs/core@2.6.0';
489
  // A fixed revision: what the browser has stored of it stays right.
490
- const FILES = 'https://huggingface.co/byoussef/DepthPro2-litert/resolve/85da0e06b4f3d2a733c84d4527ab45e235648654/';
 
 
491
  const MODELS = {
492
- s: {name: 'S', label: 'model S', file: 'depthpro2-s_480x854.tflite', bytes: 98344368},
493
- b: {name: 'B', label: 'model B', file: 'depthpro2-b_480x854.tflite', bytes: 387119408},
494
- fov: {label: 'the field-of-view model', file: 'depthpro2-fov_480x832.tflite', bytes: 95280716},
 
 
495
  };
 
 
496
  const SAMPLES = [
497
  ['macaques', 'Two macaques'], ['kitchen', 'A kitchen'], ['forest', 'A forest path'], ['mountains', 'A mountain reservoir'],
498
  ];
@@ -527,7 +533,9 @@
527
  const calm = matchMedia('(prefers-reduced-motion: reduce)');
528
 
529
  const want = {model: 's', precision: 'fp16', metric: false}; // what the controls ask for
530
- const loaded = {depth: null, fov: null}; // the compiled models
 
 
531
  const held = new Map(); // files downloaded and not compiled yet
532
  let litert;
533
  let gpu = '';
@@ -624,7 +632,26 @@
624
  }
625
 
626
  const keyOf = ({model, precision}) => `${model} ${precision}`;
627
- const needed = (file) => file === MODELS[want.model].file || (want.metric && file === MODELS.fov.file);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
628
 
629
  class DownloadError extends Error {}
630
 
@@ -695,6 +722,56 @@
695
  return {output, milliseconds};
696
  }
697
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
698
  // ---- Pictures -----------------------------------------------------------------------------
699
 
700
  // Draws an image or a video frame scaled to cover width x height, cropped to its center.
@@ -867,21 +944,31 @@
867
  await new Promise(requestAnimationFrame);
868
  }
869
  }
 
870
  running = false;
871
  }
872
 
873
  async function step() {
874
- const key = keyOf(want);
875
- if (loaded.depth?.key !== key) {
876
- const model = MODELS[want.model];
877
- const bytes = await download(model);
878
- if (keyOf(want) !== key) return;
879
- progress(`Preparing ${model.label} for your GPU`);
 
 
880
  // One depth model at a time: LiteRT.js aborts when it holds too many.
881
- loaded.depth?.compiled.delete();
882
  loaded.depth = null;
883
- loaded.depth = {key, compiled: await compile(model, bytes, want.precision), warm: false};
884
- if (keyOf(want) !== key) return;
 
 
 
 
 
 
 
885
  }
886
  if (want.metric && !loaded.fov) {
887
  const bytes = await download(MODELS.fov);
@@ -896,6 +983,9 @@
896
  // Whether this step is of a camera frame, even if the camera stops while it runs.
897
  const live = shot.live;
898
  if (live && !video.videoWidth) return;
 
 
 
899
  if (live) grab(video, shot.mirrored);
900
  if (want.metric && !shot.focal) {
901
  if (!live) progress('Estimating the field of view');
@@ -904,19 +994,22 @@
904
  // Its second output is the vertical angle, in degrees.
905
  shot.focal = 0.5 * HEIGHT / Math.tan(output[1] * Math.PI / 360);
906
  }
907
- if (live || depth?.shot !== shot || depth.key !== key) {
908
  if (!live) progress('Estimating depth');
909
  const input = planes(frame, WIDTH, HEIGHT);
910
- let run = await infer(loaded.depth.compiled, input, [1, 3, HEIGHT, WIDTH]);
 
911
  if (shot !== source) return;
912
- show(shot, key, run, live);
 
 
913
  if (!loaded.depth.warm && !live) {
914
  // The first run of a model also sets up the GPU: the depth is shown, and a second run times it.
915
  depth.milliseconds = null;
916
  $('progress').hidden = true;
917
  render();
918
- run = await infer(loaded.depth.compiled, input, [1, 3, HEIGHT, WIDTH]);
919
- if (depth.shot === shot && depth.key === key) depth.milliseconds = run.milliseconds;
920
  }
921
  loaded.depth.warm = true;
922
  }
@@ -1066,6 +1159,11 @@
1066
  if (!source?.live) return;
1067
  // The last frame stays, as a still, with its depth.
1068
  source.live = false;
 
 
 
 
 
1069
  for (const track of video.srcObject?.getTracks() ?? []) track.stop();
1070
  video.srcObject = null;
1071
  $('camera').setAttribute('aria-pressed', 'false');
@@ -1081,6 +1179,7 @@
1081
  function look(next, sample) {
1082
  endCamera();
1083
  source = Object.assign(next, {sample});
 
1084
  pointer = null;
1085
  cancelAnimationFrame(sweep);
1086
  delete viewer.dataset.depth;
@@ -1128,7 +1227,11 @@
1128
  let starting = false;
1129
 
1130
  async function camera() {
1131
- if (source?.live) return endCamera();
 
 
 
 
1132
  if (starting) return;
1133
  starting = true;
1134
  $('camera-label').textContent = 'Starting';
@@ -1174,8 +1277,7 @@
1174
  // ---- Controls -----------------------------------------------------------------------------
1175
 
1176
  function changed() {
1177
- if (transfer && !needed(transfer.file)) transfer.controller.abort();
1178
- for (const file of held.keys()) if (!needed(file)) held.delete(file);
1179
  render();
1180
  if (ready) refresh();
1181
  else if (adapter && !booting && !stopped) invite();
 
4
  <meta charset="utf-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1">
6
  <title>Depth Pro 2 on WebGPU</title>
7
+ <meta name="description" content="Depth from a photo or the camera, computed in your browser on WebGPU with LiteRT.js.">
8
  <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Crect width='8' height='16' fill='%2358626b'/%3E%3Crect x='8' width='8' height='16' fill='%23f66b19'/%3E%3Crect x='7.25' width='1.5' height='16' fill='%23fff'/%3E%3C/svg%3E">
9
  <style>
10
  /* Hallmark · checked: 2026-11-24 · genre: modern-minimal (inferred)
 
389
  <div class="page">
390
  <header>
391
  <h1>Depth Pro 2 on WebGPU</h1>
392
+ <p class="lede">Depth from a photo or the camera, computed in this browser on your GPU. Pictures stay on your device.</p>
393
  <nav>
394
  <a href="https://huggingface.co/byoussef/DepthPro2-litert" target="_blank" rel="noopener">Model files</a>
395
  <a href="https://huggingface.co/apple/DepthPro2" target="_blank" rel="noopener">Original model</a>
 
444
  <span id="camera-label">Camera</span>
445
  </button>
446
  </div>
447
+ <p class="hint">Or drop a photo anywhere on the page. It is cropped to 16:9, the shape the models take. The camera runs the model’s video version, a second download of the same size, in which each frame also sees the three before it: the depth holds steadier.</p>
448
  </section>
449
 
450
  <fieldset class="group">
 
487
  <script type="module">
488
  const LITERT = 'https://cdn.jsdelivr.net/npm/@litertjs/core@2.6.0';
489
  // A fixed revision: what the browser has stored of it stays right.
490
+ const FILES = 'https://huggingface.co/byoussef/DepthPro2-litert/resolve/d45bcfa0544d8ce5c351b2d5a8069f7a1be999a4/';
491
+ // A photo runs the photo file of its size. The camera runs the video file, in which each frame
492
+ // also sees the frames before it.
493
  const MODELS = {
494
+ s: {name: 'S', label: 'model S', file: 'depthpro2-s_480x854.tflite', bytes: 98417420,
495
+ video: {label: 'model S for video', file: 'depthpro2-s_480x854_w4.tflite', bytes: 99144436}},
496
+ b: {name: 'B', label: 'model B', file: 'depthpro2-b_480x854.tflite', bytes: 387092196,
497
+ video: {label: 'model B for video', file: 'depthpro2-b_480x854_w4.tflite', bytes: 388424320}},
498
+ fov: {label: 'the field-of-view model', file: 'depthpro2-fov_480x832.tflite', bytes: 95245968},
499
  };
500
+ // What a video model hands from one frame to the next, as inputs and as outputs named next_*.
501
+ const STATE = ['valid', 'keys', 'values', 'prefixes'];
502
  const SAMPLES = [
503
  ['macaques', 'Two macaques'], ['kitchen', 'A kitchen'], ['forest', 'A forest path'], ['mountains', 'A mountain reservoir'],
504
  ];
 
533
  const calm = matchMedia('(prefers-reduced-motion: reduce)');
534
 
535
  const want = {model: 's', precision: 'fp16', metric: false}; // what the controls ask for
536
+ // The compiled models; a video model with the empty state the camera starts from.
537
+ const loaded = {depth: null, fov: null};
538
+ let carried = null; // what the camera's last frame hands the next: {model, shot, state}
539
  const held = new Map(); // files downloaded and not compiled yet
540
  let litert;
541
  let gpu = '';
 
632
  }
633
 
634
  const keyOf = ({model, precision}) => `${model} ${precision}`;
635
+ // The files the controls and the picture need: the depth model's, its video file while the
636
+ // camera runs, and the field-of-view model's when asked for.
637
+ const needed = (file) => (want.metric && file === MODELS.fov.file) ||
638
+ file === (source?.live ? MODELS[want.model].video.file : MODELS[want.model].file);
639
+
640
+ // Stops a download, and forgets downloaded files, that are no longer needed.
641
+ function drop() {
642
+ if (transfer && !needed(transfer.file)) transfer.controller.abort();
643
+ for (const file of held.keys()) if (!needed(file)) held.delete(file);
644
+ }
645
+
646
+ // The depth model the picture needs: the video file while the camera runs, the photo file for
647
+ // a photo. None for a still that has its depth already from this size and precision, as the
648
+ // camera's last frame has once the camera stops.
649
+ function demand() {
650
+ const key = keyOf(want);
651
+ if (source?.live) return {key: `${key} video`, model: MODELS[want.model].video, video: true};
652
+ if (depth && depth.shot === source && (depth.key === key || depth.key === `${key} video`)) return null;
653
+ return {key, model: MODELS[want.model], video: false};
654
+ }
655
 
656
  class DownloadError extends Error {}
657
 
 
722
  return {output, milliseconds};
723
  }
724
 
725
+ // The state of a video that has shown no frame yet: zeros, kept on the GPU for every first
726
+ // frame of the camera.
727
+ async function emptyState(compiled) {
728
+ const empty = {};
729
+ for (const {name, shape} of compiled.getInputDetails()) {
730
+ if (!STATE.includes(name)) continue;
731
+ const zeros = new litert.Tensor(new Float32Array(shape.reduce((a, b) => a * b, 1)), Array.from(shape));
732
+ empty[name] = await zeros.moveTo('webgpu');
733
+ }
734
+ return empty;
735
+ }
736
+
737
+ const release = (state) => {
738
+ for (const tensor of Object.values(state ?? {})) tensor.delete();
739
+ };
740
+
741
+ // Lets go of the camera's state once nothing can take it up: the camera stopped, or the model changed.
742
+ // Called only between runs, never while one could still be reading it.
743
+ function prune() {
744
+ if (carried && !(carried.shot === source && source.live && carried.model === loaded.depth)) {
745
+ release(carried.state);
746
+ carried = null;
747
+ }
748
+ }
749
+
750
+ // Depth of a camera frame with the video model, and the milliseconds that took. The camera's
751
+ // first frame starts from the empty state; each later one from the state the one before handed
752
+ // on, which stays on the GPU.
753
+ async function estimate(values, shot) {
754
+ const model = loaded.depth;
755
+ const past = carried?.shot === shot && carried.model === model ? carried.state : model.empty;
756
+ const tensor = new litert.Tensor(values, [1, 3, HEIGHT, WIDTH]);
757
+ const begun = performance.now();
758
+ const outputs = await model.compiled.run({frame: tensor, ...past});
759
+ const onHost = await outputs.inverse_depth.moveTo('wasm');
760
+ const output = onHost.toTypedArray().slice();
761
+ const milliseconds = performance.now() - begun;
762
+ tensor.delete();
763
+ onHost.delete();
764
+ const next = Object.fromEntries(STATE.map((name) => [name, outputs[`next_${name}`]]));
765
+ // A camera stopped while this ran has no next frame to hand the state to.
766
+ if (shot.live) {
767
+ release(carried?.state);
768
+ carried = {model, shot, state: next};
769
+ } else {
770
+ release(next);
771
+ }
772
+ return {output, milliseconds};
773
+ }
774
+
775
  // ---- Pictures -----------------------------------------------------------------------------
776
 
777
  // Draws an image or a video frame scaled to cover width x height, cropped to its center.
 
944
  await new Promise(requestAnimationFrame);
945
  }
946
  }
947
+ if (!stopped) prune();
948
  running = false;
949
  }
950
 
951
  async function step() {
952
+ prune();
953
+ drop();
954
+ const need = demand();
955
+ if (need && loaded.depth?.key !== need.key) {
956
+ const bytes = await download(need.model);
957
+ // The picture or the controls changed meanwhile: go around for what they need now.
958
+ if (demand()?.key !== need.key) return void (again = true);
959
+ progress(`Preparing ${need.model.label} for your GPU`);
960
  // One depth model at a time: LiteRT.js aborts when it holds too many.
961
+ const old = loaded.depth;
962
  loaded.depth = null;
963
+ if (old) {
964
+ prune();
965
+ release(old.empty);
966
+ old.compiled.delete();
967
+ }
968
+ const compiled = await compile(need.model, bytes, want.precision);
969
+ const empty = need.video ? await emptyState(compiled) : null;
970
+ loaded.depth = {key: need.key, compiled, empty, warm: false};
971
+ if (demand()?.key !== need.key) return void (again = true);
972
  }
973
  if (want.metric && !loaded.fov) {
974
  const bytes = await download(MODELS.fov);
 
983
  // Whether this step is of a camera frame, even if the camera stops while it runs.
984
  const live = shot.live;
985
  if (live && !video.videoWidth) return;
986
+ // The model loaded is not the one this picture needs, as when the camera started while it loaded.
987
+ const wanted = demand();
988
+ if (wanted && loaded.depth?.key !== wanted.key) return void (again = true);
989
  if (live) grab(video, shot.mirrored);
990
  if (want.metric && !shot.focal) {
991
  if (!live) progress('Estimating the field of view');
 
994
  // Its second output is the vertical angle, in degrees.
995
  shot.focal = 0.5 * HEIGHT / Math.tan(output[1] * Math.PI / 360);
996
  }
997
+ if (wanted && (live || depth?.shot !== shot || depth.key !== wanted.key)) {
998
  if (!live) progress('Estimating depth');
999
  const input = planes(frame, WIDTH, HEIGHT);
1000
+ const once = () => loaded.depth.empty ? estimate(input, shot) : infer(loaded.depth.compiled, input, [1, 3, HEIGHT, WIDTH]);
1001
+ let run = await once();
1002
  if (shot !== source) return;
1003
+ // A camera stopped during its first run shows a later frame now, which goes around as a photo.
1004
+ if (live && !shot.live && depth?.shot !== shot) return void (again = true);
1005
+ show(shot, wanted.key, run, live);
1006
  if (!loaded.depth.warm && !live) {
1007
  // The first run of a model also sets up the GPU: the depth is shown, and a second run times it.
1008
  depth.milliseconds = null;
1009
  $('progress').hidden = true;
1010
  render();
1011
+ run = await once();
1012
+ if (depth.shot === shot && depth.key === wanted.key) depth.milliseconds = run.milliseconds;
1013
  }
1014
  loaded.depth.warm = true;
1015
  }
 
1159
  if (!source?.live) return;
1160
  // The last frame stays, as a still, with its depth.
1161
  source.live = false;
1162
+ // Stopped before its first depth, the camera leaves the frame it shows now, estimated as a photo.
1163
+ if (depth?.shot !== source && video.videoWidth) {
1164
+ grab(video, source.mirrored);
1165
+ present();
1166
+ }
1167
  for (const track of video.srcObject?.getTracks() ?? []) track.stop();
1168
  video.srcObject = null;
1169
  $('camera').setAttribute('aria-pressed', 'false');
 
1179
  function look(next, sample) {
1180
  endCamera();
1181
  source = Object.assign(next, {sample});
1182
+ drop();
1183
  pointer = null;
1184
  cancelAnimationFrame(sweep);
1185
  delete viewer.dataset.depth;
 
1227
  let starting = false;
1228
 
1229
  async function camera() {
1230
+ if (source?.live) {
1231
+ endCamera();
1232
+ drop();
1233
+ return refresh();
1234
+ }
1235
  if (starting) return;
1236
  starting = true;
1237
  $('camera-label').textContent = 'Starting';
 
1277
  // ---- Controls -----------------------------------------------------------------------------
1278
 
1279
  function changed() {
1280
+ drop();
 
1281
  render();
1282
  if (ready) refresh();
1283
  else if (adapter && !booting && !stopped) invite();