-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdoctor.py
More file actions
executable file
·772 lines (701 loc) · 27.7 KB
/
Copy pathdoctor.py
File metadata and controls
executable file
·772 lines (701 loc) · 27.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
#!/usr/bin/env python3
"""Cross-platform setup/doctor for DepthLens Pro.
This script intentionally runs before the project virtualenv exists. It finds a
supported Python (3.10-3.12), verifies core stdlib modules that frequently break
on misconfigured installs, creates/repairs the repo-root venv, installs backend
and Electron dependencies, and prints a deterministic summary.
"""
from __future__ import annotations
import argparse
import json
import os
import platform
import shutil
import subprocess
import sys
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Iterable
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
VENV = ROOT / "venv"
MIN_VERSION = (3, 10)
MAX_VERSION = (3, 12)
REQUIRED_STDLIB = ("ensurepip", "ssl", "venv", "pyexpat")
PYTHON_310_WARNING = (
"Python 3.10 was selected. The pinned backend dependencies are only guaranteed "
"on Python 3.11-3.12. If pip install fails, install Python 3.12 from "
"python.org and re-run."
)
SUPPORTED_ARCHES = {"arm64", "aarch64", "x86_64", "amd64"}
try:
from backend.constants import SUPPORTED_ONNX_MODEL_IDS
from backend.core.paths import TORCH_CACHE_ROOT
except ImportError: # Runs before the venv exists; keep stdlib-only fallbacks in sync.
SUPPORTED_ONNX_MODEL_IDS = ("midas_small", "dpt_hybrid", "dpt_large")
TORCH_CACHE_ROOT = ROOT / "models" / "torch-cache"
ONNX_MODEL_IDS = SUPPORTED_ONNX_MODEL_IDS
try:
from scripts.setup_state import write_setup_report
except ImportError:
from setup_state import write_setup_report
DETECTOR_TORCH_CACHE = TORCH_CACHE_ROOT
MIDAS_TORCH_CACHE = DETECTOR_TORCH_CACHE
def parse_onnx_model_list(value: str | None) -> list[str]:
"""Parse a comma-separated ONNX model selection into canonical model IDs."""
if value is None or value == "":
return ["midas_small"]
raw = [item.strip() for item in value.split(",") if item.strip()]
if raw == ["all"]:
return list(ONNX_MODEL_IDS)
invalid = [item for item in raw if item not in ONNX_MODEL_IDS]
if invalid:
expected = ", ".join(ONNX_MODEL_IDS)
raise argparse.ArgumentTypeError(
f"Unsupported ONNX model(s): {', '.join(invalid)}. "
f"Expected one of: {expected} or all"
)
return raw
def verify_detector_cache(cache_root: Path = DETECTOR_TORCH_CACHE) -> tuple[bool, str]:
"""Verify TorchVision detector checkpoints exist in the setup-created cache."""
checkpoints = cache_root / "hub" / "checkpoints"
if not checkpoints.is_dir():
return False, f"Detector checkpoint directory is missing: {checkpoints}"
if not any(path.is_file() and path.suffix == ".pth" for path in checkpoints.iterdir()):
return False, f"No .pth detector checkpoint files found in: {checkpoints}"
display_root = cache_root.relative_to(ROOT) if cache_root.is_relative_to(ROOT) else cache_root
return True, f"Detector weights cached under {display_root}"
def should_prefetch_detector_weights(args: argparse.Namespace) -> bool:
"""Return whether normal setup should cache RGB detector weights."""
if args.with_detector_weights and args.without_detector_weights:
raise SystemExit(
"Choose either --with-detector-weights or --without-detector-weights, not both."
)
if args.without_detector_weights:
return False
if args.doctor_only:
return False
if os.environ.get("CI") == "1" or os.environ.get("TESTING") == "1":
return bool(args.with_detector_weights)
return True
def prefetch_detector_weights(py: Path, env: dict[str, str]) -> None:
print("Caching RGB object detector weights for offline / packaged use...")
detector_env = env.copy()
detector_env.pop("DEPTHLENS_DISABLE_MODEL_DOWNLOADS", None)
detector_env["TORCH_HOME"] = str(DETECTOR_TORCH_CACHE)
_run(
[str(py), str(ROOT / "scripts" / "prefetch-detector-weights.py")],
env=detector_env,
stream=True,
)
ok, message = verify_detector_cache()
if not ok:
raise SystemExit(message)
print(message)
def should_export_onnx(args: argparse.Namespace, *, stdin_is_tty: bool | None = None) -> bool:
"""Return whether setup should export/validate ONNX. Default is non-interactive No."""
if args.with_onnx and args.without_onnx:
raise SystemExit("Choose either --with-onnx or --without-onnx, not both.")
if args.with_onnx or args.onnx_validate_only:
return True
if args.without_onnx:
return False
if stdin_is_tty is None:
stdin_is_tty = sys.stdin.isatty()
if not stdin_is_tty:
print(
"ONNX export skipped by default in non-interactive setup. "
"Pass --with-onnx to export or --without-onnx to make the skip explicit."
)
return False
answer = (
input("Export optional ONNX model files now? This may download large weights. [y/N]: ")
.strip()
.lower()
)
return answer in {"y", "yes"}
def onnx_export_command(py: Path, args: argparse.Namespace) -> list[str]:
models = parse_onnx_model_list(args.onnx_models)
cmd = [
str(py),
str(ROOT / "backend" / "scripts" / "export_onnx.py"),
"--output-dir",
str(ROOT / "models" / "onnx"),
]
if args.onnx_validate_only:
cmd.append("--validate-only")
if args.onnx_force:
cmd.append("--force")
if args.onnx_strict:
cmd.append("--strict")
if models == list(ONNX_MODEL_IDS):
cmd.append("--all")
elif len(models) == 1:
cmd.extend(["--model", models[0]])
else:
cmd.extend(["--models", ",".join(models)])
return cmd
@dataclass
class Candidate:
command: list[str]
label: str
@dataclass
class CheckResult:
ok: bool
version: tuple[int, int, int] | None = None
executable: str | None = None
error: str | None = None
def remediation_command(kind: str, args: argparse.Namespace | None = None) -> str:
"""Return an exact setup command users can retry after a failed setup step."""
platform_key = {"Darwin": "mac", "Linux": "linux", "Windows": "win"}.get(
platform.system(), "<platform>"
)
suffix = ":onnx" if args is not None and getattr(args, "with_onnx", False) else ""
if kind == "midas":
return f"npm run setup:{platform_key}{suffix}"
if kind == "onnx":
return f"npm run setup:{platform_key}:onnx"
return f"npm run setup:{platform_key}{suffix}"
def onnx_verify_mode(args: argparse.Namespace, *, export_onnx: bool | None = None) -> str:
"""Map setup arguments to verify-resources ONNX modes."""
if args.without_onnx:
return "off"
if args.with_onnx or args.onnx_validate_only or export_onnx:
models = parse_onnx_model_list(args.onnx_models)
return "require-all" if models == list(ONNX_MODEL_IDS) else "required"
return "optional"
def _run(
cmd: list[str],
*,
cwd: Path = ROOT,
check: bool = True,
env: dict[str, str] | None = None,
stream: bool = False,
) -> subprocess.CompletedProcess[str]:
print(f"$ {' '.join(cmd)}", flush=True)
if stream:
return subprocess.run(cmd, cwd=cwd, check=check, text=True, env=env)
try:
return subprocess.run(
cmd,
cwd=cwd,
check=check,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
env=env,
)
except subprocess.CalledProcessError as exc:
if exc.stdout:
print(exc.stdout, end="" if exc.stdout.endswith("\n") else "\n")
raise
def _probe_python(command: list[str]) -> CheckResult:
code = """
import importlib, json, sys
mods = ['ensurepip', 'ssl', 'venv', 'pyexpat']
missing = []
for mod in mods:
try:
importlib.import_module(mod)
except Exception as exc:
missing.append(f'{mod}: {type(exc).__name__}: {exc}')
try:
import ensurepip
ensurepip.version()
except Exception as exc:
missing.append(f'ensurepip.version: {type(exc).__name__}: {exc}')
print(json.dumps({
'version': list(sys.version_info[:3]),
'executable': sys.executable,
'missing': missing,
}))
raise SystemExit(1 if missing else 0)
"""
try:
proc = subprocess.run(
command + ["-c", code],
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
timeout=20,
)
except (OSError, subprocess.SubprocessError) as exc:
return CheckResult(False, error=f"{type(exc).__name__}: {exc}")
try:
payload = json.loads(proc.stdout.strip().splitlines()[-1])
version = tuple(int(x) for x in payload["version"])
executable = str(payload["executable"])
missing = payload.get("missing") or []
except Exception:
return CheckResult(False, error=proc.stdout.strip() or "could not run Python")
if not (MIN_VERSION <= version[:2] <= MAX_VERSION):
return CheckResult(
False,
version=version,
executable=executable,
error=f"unsupported Python {version[0]}.{version[1]}; DepthLens Pro supports 3.10-3.12",
)
if proc.returncode != 0 or missing:
return CheckResult(
False,
version=version,
executable=executable,
error="; ".join(missing) or proc.stdout.strip(),
)
return CheckResult(True, version=version, executable=executable)
def candidate_pythons() -> list[Candidate]:
system = platform.system()
candidates: list[Candidate] = []
if system == "Darwin":
for minor in (12, 11):
candidates.append(
Candidate(
[f"/Library/Frameworks/Python.framework/Versions/3.{minor}/bin/python3"],
f"python.org 3.{minor}",
)
)
for minor in (12, 11):
candidates.append(
Candidate(
[f"/opt/homebrew/bin/python3.{minor}"], f"Homebrew Apple Silicon 3.{minor}"
)
)
candidates.append(
Candidate([f"/usr/local/bin/python3.{minor}"], f"Homebrew Intel/Rosetta 3.{minor}")
)
candidates.append(
Candidate(
["/Library/Frameworks/Python.framework/Versions/3.10/bin/python3"],
"python.org 3.10",
)
)
candidates.append(
Candidate(["/opt/homebrew/bin/python3.10"], "Homebrew Apple Silicon 3.10")
)
candidates.append(Candidate(["/usr/local/bin/python3.10"], "Homebrew Intel/Rosetta 3.10"))
candidates.append(Candidate(["python3"], "PATH python3"))
elif system == "Windows":
for minor in (12, 11, 10):
candidates.append(Candidate(["py", f"-3.{minor}"], f"Windows py launcher 3.{minor}"))
candidates.append(Candidate(["python"], "PATH python"))
else:
for minor in (12, 11):
candidates.append(Candidate([f"/usr/bin/python3.{minor}"], f"system python3.{minor}"))
for minor in (12, 11, 10):
candidates.append(Candidate([f"python3.{minor}"], f"PATH python3.{minor}"))
candidates.append(Candidate(["python3"], "PATH python3"))
return candidates
def find_python() -> tuple[list[str], CheckResult, list[tuple[Candidate, CheckResult]]]:
failures: list[tuple[Candidate, CheckResult]] = []
seen: set[tuple[str, ...]] = set()
for cand in candidate_pythons():
if tuple(cand.command) in seen:
continue
seen.add(tuple(cand.command))
exe = cand.command[0]
if (os.path.sep in exe or (os.path.altsep and os.path.altsep in exe)) and not Path(
exe
).exists():
continue
if os.path.sep not in exe and shutil.which(exe) is None:
continue
result = _probe_python(cand.command)
if result.ok:
executable = result.executable or " ".join(cand.command)
version = ".".join(map(str, result.version or ()))
print(f"Selected Python: {executable} (version {version})")
return cand.command, result, failures
failures.append((cand, result))
lines = [
"No working supported Python found "
"(required: 3.10-3.12 with ensurepip, ssl, venv, pyexpat)."
]
for cand, res in failures:
lines.append(f"- {cand.label} ({' '.join(cand.command)}): {res.error}")
if platform.system() == "Darwin":
lines.append(
"Recommended macOS remediation: install Python 3.12 from "
"https://www.python.org/downloads/macos/ if Homebrew Python fails "
"ensurepip/pyexpat. " + PYTHON_310_WARNING
)
elif platform.system() == "Windows":
lines.append(
"Recommended Windows remediation: install Python 3.12 for ARM64/x64 "
"from python.org and enable the py launcher."
)
else:
lines.append(
"Recommended Linux remediation: install python3.12/python3.11 plus the "
"matching venv package (for example python3.12-venv)."
)
raise SystemExit("\n".join(lines))
def venv_python() -> Path:
if platform.system() == "Windows":
return VENV / "Scripts" / "python.exe"
return VENV / "bin" / "python"
def existing_venv_status() -> CheckResult | None:
py = venv_python()
if not py.exists():
return None
return _probe_python([str(py)])
def recreate_venv(python_cmd: list[str]) -> None:
if VENV.exists():
print(f"Removing unsupported/broken venv at {VENV}")
shutil.rmtree(VENV)
_run(python_cmd + ["-m", "venv", str(VENV)], stream=True)
status = existing_venv_status()
if not status or not status.ok:
raise SystemExit(
f"Created venv is not usable: {status.error if status else 'missing python'}"
)
def cert_env(py: Path) -> dict[str, str]:
env = os.environ.copy()
code = "import certifi; print(certifi.where())"
proc = subprocess.run(
[str(py), "-c", code], text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL
)
if proc.returncode == 0:
bundle = proc.stdout.strip()
env["SSL_CERT_FILE"] = bundle
env["REQUESTS_CA_BUNDLE"] = bundle
env["CURL_CA_BUNDLE"] = bundle
env.setdefault("PYTHONUNBUFFERED", "1")
env.setdefault("DEPTHLENS_DISABLE_MODEL_DOWNLOADS", "1")
env.setdefault("DEPTHLENS_SKIP_WARMUP", "1")
env.setdefault("DEPTHLENS_CACHE_BACKEND", "memory")
return env
def select_python(args: argparse.Namespace) -> tuple[list[str], CheckResult]:
arch = platform.machine().lower()
system = platform.system()
if args.enforce_arch:
if system == "Darwin" and arch not in {"arm64", "aarch64"}:
raise SystemExit(
f"Unsupported macOS native app architecture {platform.machine()}. "
"Supported macOS native builds are Apple Silicon arm64 only."
)
if system in {"Windows", "Linux"} and arch not in SUPPORTED_ARCHES:
raise SystemExit(
f"Unsupported native app architecture {platform.machine()}. "
"Supported Windows/Linux native builds are arm64/aarch64 and x64/x86_64."
)
selected_cmd, selected, _failures = find_python()
if selected.version and selected.version[:2] == (3, 10):
print(f"WARNING: {PYTHON_310_WARNING}")
if platform.system() == "Darwin" and "zsh" in os.environ.get("SHELL", ""):
print(
"Tip: if pasting multi-line command blocks into Terminal causes "
"'zsh: command not found: #', run: setopt interactivecomments"
)
return selected_cmd, selected
def ensure_venv(selected_cmd: list[str]) -> Path:
status = existing_venv_status()
if status is None or not status.ok:
recreate_venv(selected_cmd)
else:
version = ".".join(map(str, status.version or ()))
print(f"Existing venv is valid: Python {version} at {status.executable}")
return venv_python()
def upgrade_python_tooling(py: Path, args: argparse.Namespace) -> dict[str, str]:
try:
_run(
[
str(py),
"-m",
"pip",
"install",
"--upgrade",
"pip",
"setuptools<82",
"wheel",
"certifi",
],
stream=True,
)
return cert_env(py)
except subprocess.CalledProcessError as exc:
print(f"Retry/remediation command: {remediation_command('pip', args)}", file=sys.stderr)
raise SystemExit(
f"Python tooling upgrade failed. Re-run: {remediation_command('pip', args)}"
) from exc
def install_python_dependencies(py: Path, env: dict[str, str], args: argparse.Namespace) -> None:
try:
if not args.doctor_only:
_run(
[
str(py),
"-m",
"pip",
"install",
"-r",
str(ROOT / "backend" / "requirements.txt"),
],
env=env,
stream=True,
)
else:
print("SKIPPED backend dependency install (--doctor-only)")
pip_check = _run([str(py), "-m", "pip", "check"], check=False, env=env)
if pip_check.returncode != 0:
raise SystemExit(pip_check.stdout)
except subprocess.CalledProcessError as exc:
print(f"Retry/remediation command: {remediation_command('pip', args)}", file=sys.stderr)
raise SystemExit(
f"Python dependency installation failed. Re-run: {remediation_command('pip', args)}"
) from exc
def install_electron_dependencies(args: argparse.Namespace) -> None:
if args.doctor_only:
print("SKIPPED Electron dependency install (--doctor-only)")
return
try:
_run(["npm", "install"], cwd=ROOT / "electron-app", stream=True)
except (FileNotFoundError, subprocess.CalledProcessError) as exc:
print(f"Retry/remediation command: {remediation_command('npm', args)}", file=sys.stderr)
raise SystemExit(
f"Electron dependency installation failed. Re-run: {remediation_command('npm', args)}"
) from exc
def ensure_model_dirs() -> None:
DETECTOR_TORCH_CACHE.mkdir(parents=True, exist_ok=True)
(ROOT / "models" / "onnx").mkdir(parents=True, exist_ok=True)
for keep in [ROOT / "models" / ".gitkeep", ROOT / "models" / "onnx" / ".gitkeep"]:
if not keep.exists():
keep.touch()
print("Ensured models/onnx and models/torch-cache directory structure.")
def cache_midas_assets(py: Path, env: dict[str, str], args: argparse.Namespace) -> str:
if args.doctor_only:
print("SKIPPED MiDaS asset caching (--doctor-only)")
return "skipped"
if args.offline:
print("Offline mode: validating PyTorch MiDaS cache only; no downloads will be attempted.")
midas_env = env.copy()
midas_env.pop("DEPTHLENS_DISABLE_MODEL_DOWNLOADS", None)
midas_env["TORCH_HOME"] = str(MIDAS_TORCH_CACHE)
midas_cmd = [
str(py),
str(ROOT / "scripts" / "prefetch-midas-assets.py"),
"--models",
args.models,
"--timeout-seconds",
str(args.timeout_seconds),
"--retries",
str(args.retries),
]
if args.offline:
midas_cmd.append("--offline")
try:
_run(midas_cmd, env=midas_env, stream=True)
except subprocess.CalledProcessError as exc:
print(f"Retry/remediation command: {remediation_command('midas', args)}", file=sys.stderr)
raise SystemExit(
f"PyTorch MiDaS asset caching failed. Re-run: {remediation_command('midas', args)}"
) from exc
print("OK PyTorch MiDaS assets cached/verified.")
return "ok"
def cache_detector_assets(py: Path, env: dict[str, str], args: argparse.Namespace) -> str:
if should_prefetch_detector_weights(args):
try:
prefetch_detector_weights(py, env)
return "ok"
except subprocess.CalledProcessError as exc:
cmd = remediation_command("detector", args)
raise SystemExit(
"RGB detector weights could not be cached. Re-run setup with network access "
f"using `{cmd}`, or pass --without-detector-weights to skip "
"RGB object detection support."
) from exc
print("WARNING: RGB Camera detection may fail until detector weights are cached.")
return "skipped"
def handle_onnx_assets(py: Path, env: dict[str, str], args: argparse.Namespace) -> bool:
export_onnx = should_export_onnx(args)
if export_onnx:
if args.onnx_validate_only:
print("ONNX validation-only mode: validating requested files without exporting.")
try:
_run(onnx_export_command(py, args), env=env, stream=True)
except subprocess.CalledProcessError as exc:
print(
f"Retry/remediation command: {remediation_command('onnx', args)}", file=sys.stderr
)
raise SystemExit(
f"ONNX asset handling failed. Re-run: {remediation_command('onnx', args)}"
) from exc
else:
print(
"SKIPPED ONNX export intentionally; PyTorch MiDaS cache is required "
"and ONNX remains optional for standard builds."
)
return export_onnx
def verify_resources(
py: Path, env: dict[str, str], args: argparse.Namespace, export_onnx: bool
) -> tuple[subprocess.CompletedProcess[str], str, str, str]:
mode = onnx_verify_mode(args, export_onnx=export_onnx)
models = "all" if mode == "require-all" else args.onnx_models
cmd = [
"node",
"scripts/verify-resources.js",
"--root-kind",
"repo",
"--mode",
"native",
"--torch-cache",
"required",
"--onnx",
mode,
"--models",
models,
"..",
]
resources = _run(cmd, cwd=ROOT / "electron-app", check=False, stream=True)
verify_command = "cd electron-app && " + " ".join(cmd)
if resources.returncode != 0:
raise SystemExit(
"Resource verification failed. Re-run setup with "
f"`{remediation_command('verify', args)}` then retry `{verify_command}`."
)
return resources, verify_command, mode, models
def build_setup_report(
py: Path,
env: dict[str, str],
selected_cmd: list[str],
selected: CheckResult,
verify_command: str,
mode: str,
midas_status: str,
detector_status: str,
) -> dict[str, Any]:
node_v = (
_run(["node", "--version"], check=False).stdout.strip()
if shutil.which("node")
else "missing"
)
npm_v = (
_run(["npm", "--version"], check=False).stdout.strip() if shutil.which("npm") else "missing"
)
onnx = _run(
[
str(py),
"-c",
(
"from backend.services.onnx_diagnostics import onnx_status_payload; "
"import json; "
"print(json.dumps(onnx_status_payload(), default=str))"
),
],
check=False,
env={**env, "PYTHONPATH": str(ROOT)},
)
return {
"generated_at": datetime.now(timezone.utc).isoformat(),
"platform": platform.system(),
"arch": platform.machine(),
"selected_python": selected.executable or " ".join(selected_cmd),
"python_version": ".".join(map(str, selected.version or ())),
"venv_path": str(VENV),
"venv_python": str(py),
"pip_version": _run([str(py), "-m", "pip", "--version"], check=False).stdout.strip(),
"node_version": node_v,
"npm_version": npm_v,
"torch_cache_status": midas_status,
"detector_cache_status": detector_status,
"onnx_status": "ok" if onnx.returncode == 0 else "unavailable/degraded",
"onnx_verify_mode": mode,
"verification_command": verify_command,
}
def setup(args: argparse.Namespace) -> dict[str, Any]:
total_steps = 8
def step(n: int, title: str) -> None:
print(f"\n[{n}/{total_steps}] {title}", flush=True)
step(1, "Selecting Python")
selected_cmd, selected = select_python(args)
step(2, "Creating or validating venv")
py = ensure_venv(selected_cmd)
step(3, "Upgrading pip/setuptools<82/wheel/certifi")
env = upgrade_python_tooling(py, args)
step(4, "Installing backend dependencies")
install_python_dependencies(py, env, args)
step(5, "Installing Electron dependencies")
install_electron_dependencies(args)
ensure_model_dirs()
step(6, "Caching PyTorch MiDaS assets")
midas_status = cache_midas_assets(py, env, args)
detector_status = cache_detector_assets(py, env, args)
step(7, "Handling optional ONNX assets")
export_onnx = handle_onnx_assets(py, env, args)
step(8, "Verifying resources")
_resources, verify_command, mode, _models = verify_resources(py, env, args, export_onnx)
summary = build_setup_report(
py, env, selected_cmd, selected, verify_command, mode, midas_status, detector_status
)
report_path = write_setup_report(summary)
print(f"Wrote setup report: {report_path.relative_to(ROOT)}")
print("\nDepthLens Pro environment summary")
print(json.dumps(summary, indent=2))
return summary
def parse_args(argv: Iterable[str] | None = None) -> argparse.Namespace:
p = argparse.ArgumentParser(description="DepthLens Pro setup and environment doctor")
p.add_argument(
"--doctor-only",
action="store_true",
help="check/create venv and verify tools without installing app dependencies",
)
p.add_argument(
"--enforce-arch",
action="store_true",
help="fail if the current machine cannot build the supported native app",
)
p.add_argument(
"--with-onnx",
action="store_true",
help="export/validate requested ONNX models during setup",
)
p.add_argument(
"--with-detector-weights",
action="store_true",
help="cache RGB object detector weights during setup even when CI/TESTING is set",
)
p.add_argument(
"--without-detector-weights",
action="store_true",
help="skip RGB object detector weight caching",
)
p.add_argument("--without-onnx", action="store_true", help="skip ONNX export explicitly")
p.add_argument(
"--onnx-models",
default="midas_small",
help="comma-separated ONNX models: midas_small, dpt_hybrid, dpt_large, or all",
)
p.add_argument(
"--onnx-strict",
action="store_true",
help="fail setup if any requested ONNX model is missing or invalid",
)
p.add_argument(
"--onnx-validate-only",
action="store_true",
help="validate requested ONNX models without exporting",
)
p.add_argument(
"--onnx-force",
action="store_true",
help="regenerate requested ONNX models even when cached files validate",
)
p.add_argument(
"--models",
default="all",
help="MiDaS PyTorch models to cache: midas_small,dpt_hybrid,dpt_large or all",
)
p.add_argument(
"--offline", action="store_true", help="validate model caches without downloading"
)
p.add_argument("--timeout-seconds", type=int, default=900, help="model asset prefetch timeout")
p.add_argument("--retries", type=int, default=2, help="model asset prefetch retries")
args = p.parse_args(argv)
parse_onnx_model_list(args.onnx_models)
if args.with_onnx and args.without_onnx:
p.error("choose either --with-onnx or --without-onnx, not both")
if args.with_detector_weights and args.without_detector_weights:
p.error("choose either --with-detector-weights or --without-detector-weights, not both")
return args
if __name__ == "__main__":
setup(parse_args())