ReShot — copy the shot, not the actors. Video → depth map, OpenPose skeleton or canny lines for Seedance 2.0/2.5 reference video, MiniMax H3 Fun ControlNet and Wan VACE. Apache-2.0. Open-sourced by Maosika 猫斯卡 (www.maosika.com), the AI short-drama production system.
Python ai-short-dramaai-videocannycomfyuicontrolnetdepth-anythingdepth-estimationdwposemaosikaminimaxopenposepose-controlnetpose-estimationseedanceshort-dramavideo-generationvideo-to-videowan
0.4.0: local web page — reshot with no arguments opens a Studio Air UI (drop clip → target → quality → depth map, side-by-side preview, download, prompt); stdlib only
wangfeng1a14bbf31761
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3e55592..20b5b22 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,12 @@# Changelog+## 0.4.0 — 2026-09-12+- **Web page.** `reshot` with no arguments (or `reshot web`) starts a local UI in the browser:+ drop a clip, pick the target model and quality, run, preview reference and depth side by+ side, download, copy the prompt line for Seedance / MiniMax H3. Studio Air look (the+ Maosika design system), Chinese and English. Standard library only — no new dependencies;+ listens on 127.0.0.1; results in `~/ReShot`. Verified in Chrome with the real model.+## 0.3.8 — 2026-09-12- Fix: on Apple Silicon with torch ≥ 2.14 the model failed to load with`invalid low watermark ratio 1.4` — the MPS low watermark is now set alongside the high one.diff --git a/README.md b/README.mdindex b0e545f..8ba0611 100644--- a/README.md+++ b/README.md@@ -57,6 +57,15 @@ on a short clip with --metrics and show me the numbers. Don't say it's done unti### 2. Make the depth map+**Easiest — the web page.** Type `reshot` with nothing after it: a page opens in your browser (everything stays on your computer). Drop the clip in, pick which model it is for, click **Make depth map**. You get the reference and the depth map side by side, the numbers, a download button, and the prompt line to paste into Seedance or MiniMax H3.++```bash+reshot # opens http://127.0.0.1:8765 — results land in ~/ReShot+reshot web --port 9000 --out ./depth --no-browser # options, if you want them+```++**Or the command line**, for scripts and folders:+```bashreshot reference.mp4 -o depth.mp4 --target seedance```@@ -129,6 +138,8 @@ Things we learned making the demo:| `fast` (default) | 644×364 · 364×644 · 490×364 | ~3 GB | 34 ms/frame on a 3080 Ti | large shapes identical to full; a loose strand of hair merges into the cheek || `full` | 924×518 · 518×924 · 686×518 | ~11 GB | 83 ms/frame on a 3080 Ti | sharper fine silhouettes |+The web page has the same two choices under **Quality**; the command line takes `--quality`.+We recommend `fast`: for copying blocking and camera it is all a video model needs — the demo takes were made from a depth map shrunk to 320×176 before it even reached MiniMax H3, far below either setting. Measured full against fast on the same 294-frame clip: mean difference 5.3 of 255 grey levels, 95 % of pixels within 15, edge energy −4.5 %. Use `full` for close-ups where thin silhouettes matter and you have the VRAM. The run prints the exact resolution it uses (`model fast: the model sees 644x364`) and records it in `--metrics`. Experts can set any short side with `--input-size`.Verified on rented cards on 2026-09-12; the numbers are in the `--metrics` output of those runs.diff --git a/README.zh-CN.md b/README.zh-CN.mdindex c43d91a..6b94874 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -57,6 +57,15 @@ depth.mp4 没生成出来之前不要说完成。### 2. 抽深度图+**最省事——网页。** 只敲 `reshot`,后面什么都不加,浏览器会打开一个页面(所有处理都在你自己电脑上)。把片子拖进去,选给哪家模型用,点**生成深度图**。参考片和深度图并排预览,数字、下载按钮、要粘到 Seedance 或 MiniMax H3 的提示词都在同一屏。++```bash+reshot # 打开 http://127.0.0.1:8765,结果存到 ~/ReShot+reshot web --port 9000 --out ./depth --no-browser # 想改端口 / 目录 / 不自动开浏览器+```++**或者命令行**,适合脚本和批量:+```bashreshot 参考片.mp4 -o 深度图.mp4 --target seedance```@@ -129,6 +138,8 @@ is transferred onto <Subject 1> and <Subject 2>; its grey depth look is not tran| `fast`(默认) | 644×364 · 364×644 · 490×364 | 约 3 GB | 3080 Ti 上 34 ms/帧 | 大形状与 full 一模一样;脸颊旁一缕散发会糊进脸里 || `full` | 924×518 · 518×924 · 686×518 | 约 11 GB | 3080 Ti 上 83 ms/帧 | 细轮廓更锐 |+网页上「画质」就是这两档;命令行用 `--quality`。+我们推荐 `fast`:复制走位和运镜,视频模型要的它全有——演示里的三段片,深度图交给 MiniMax H3 之前还缩到了 320×176,比这两档都小得多。同一段 294 帧的片上 full 对 fast 实测:平均差 5.3 个灰阶(满量程 255),95% 的像素差在 15 以内,边缘锐度低 4.5%。特写里在意细轮廓、显存又够,再用 `full`。运行时会打印实际用的分辨率(`model fast: the model sees 644x364`),也写进 `--metrics`。要指定任意短边用 `--input-size`。2026-09-12 在租来的显卡上实测;数字都在那几次运行的 `--metrics` 输出里。diff --git a/demo/requirements.txt b/demo/requirements.txtindex 08e576d..ed684df 100644--- a/demo/requirements.txt+++ b/demo/requirements.txt@@ -1,5 +1,5 @@--extra-index-url https://download.pytorch.org/whl/cputorchtorchvision-reshot[ffmpeg]==0.3.8+reshot[ffmpeg]==0.4.0gradio>=4.0diff --git a/docs/USAGE.md b/docs/USAGE.mdindex 6e7ab7a..4641c6c 100644--- a/docs/USAGE.md+++ b/docs/USAGE.md@@ -29,6 +29,23 @@ Model weights (111 MB) download from Hugging Face on first run into `~/.cache/huOffline machines: copy that cache, or pass `--checkpoint /path/video_depth_anything_vits.pth`.In China: `export HF_ENDPOINT=https://hf-mirror.com`.+## Web page++`reshot` with no arguments starts a local web page and opens it in your browser. It is the+same pipeline behind a form: drop a clip, choose the target model and quality, run, preview+reference and depth side by side, download. Nothing leaves your machine; the server listens on+127.0.0.1 only. Results are saved to `~/ReShot` with `<clip>_depth_<target>.mp4` names (never+overwriting an earlier result) and a `.json` of metrics next to each.++```bash+reshot # http://127.0.0.1:8765 (next free port if taken)+reshot web --port 9000 --out ./depth # choose port and folder+reshot web --no-browser # print the URL only, e.g. over SSH+```++The model loads once when the first job runs and stays loaded; later runs start immediately.+Jobs queue one after another (one GPU).+## Command line```diff --git a/docs/USAGE.zh-CN.md b/docs/USAGE.zh-CN.mdindex da29220..884ee90 100644--- a/docs/USAGE.zh-CN.md+++ b/docs/USAGE.zh-CN.md@@ -28,6 +28,20 @@ PyTorch 不锁 CUDA 版本;如果 `pip` 装错了,先按 https://pytorch.org离线机器:把这个缓存目录拷过去,或用 `--checkpoint /路径/video_depth_anything_vits.pth`。国内:`export HF_ENDPOINT=https://hf-mirror.com`。+## 网页++只敲 `reshot` 不带参数,会在本机起一个网页并用浏览器打开。它和命令行是同一条流水线,只是套了个表单:+拖入片子、选给哪家模型用和画质、运行、参考片与深度图并排预览、下载。什么都不会离开你的电脑,服务只监听+127.0.0.1。结果存在 `~/ReShot`,文件名 `<片名>_depth_<目标>.mp4`(不会覆盖之前的结果),旁边有一份同名 `.json` 指标。++```bash+reshot # http://127.0.0.1:8765(被占就用下一个空闲端口)+reshot web --port 9000 --out ./depth # 指定端口和目录+reshot web --no-browser # 只打印地址不开浏览器,比如通过 SSH 用+```++模型在第一次运行时加载一次,之后常驻;后面的任务立刻开始。任务排队一个个跑(一块显卡)。+## 命令行```diff --git a/pyproject.toml b/pyproject.tomlindex 1fdad20..ce7dec9 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -56,6 +56,7 @@ include = ["reshot*"][tool.setuptools.package-data]"reshot.third_party.video_depth_anything" = ["LICENSE"]"reshot" = ["py.typed"]+"reshot.web" = ["index.html"][tool.ruff]line-length = 120diff --git a/reshot/_version.py b/reshot/_version.pyindex 4ad67eb..6a9beea 100644--- a/reshot/_version.py+++ b/reshot/_version.py@@ -1 +1 @@-__version__ = "0.3.8"+__version__ = "0.4.0"diff --git a/reshot/cli.py b/reshot/cli.pyindex a030cbf..dd602e8 100644--- a/reshot/cli.py+++ b/reshot/cli.py@@ -4,6 +4,8 @@reshot in.mp4 -o out.mp4 --target h3 # 24 fps, ×32 dims, ≤15 s for MiniMax H3reshot in.mp4 -o out.mp4 --npz d.npz --metrics run.jsonreshot clips/*.mp4 -o depth/ --target seedance # batch: one model load, out/<name>_depth.mp4+ reshot # no arguments: local web UI, opens in the browser+ reshot web --port 8765 --no-browser --out ~/ReShotBatch mode (several inputs, or `-o` naming a directory): `--npz` / `--metrics`, if given,are directories too and get `<name>.npz` / `<name>.json` per clip. One bad clip is@@ -141,7 +143,30 @@ def config_from_args(args: argparse.Namespace) -> RunConfig:return configs_from_args(args)[0]+def _web_parser() -> argparse.ArgumentParser:+ p = argparse.ArgumentParser(+ prog="reshot web", description="Local web UI for ReShot (everything stays on this machine)."+ )+ p.add_argument(+ "--port", type=int, default=8765, help="port to listen on (default 8765; the next free one is used if taken)"+ )+ p.add_argument("--out", type=Path, default=None, help="where depth videos are saved (default ~/ReShot)")+ p.add_argument("--no-browser", action="store_true", help="don't open the browser automatically")+ p.add_argument("-v", "--verbose", action="store_true")+ return p++def main(argv: list[str] | None = None) -> int:+ argv = list(sys.argv[1:] if argv is None else argv)+ # `reshot` alone, or `reshot web …`: the web UI. Anything else is the classic CLI.+ if not argv or argv[0] == "web":+ wargs = _web_parser().parse_args(argv[1:] if argv else [])+ logging.basicConfig(+ level=logging.INFO if wargs.verbose else logging.WARNING, format="%(levelname)s %(name)s: %(message)s"+ )+ from .web import serve++ return serve(out_dir=wargs.out, port=wargs.port, open_browser=not wargs.no_browser)args = build_parser().parse_args(argv)logging.basicConfig(level=logging.INFO if args.verbose else logging.WARNING, format="%(levelname)s %(name)s: %(message)s"diff --git a/reshot/web/__init__.py b/reshot/web/__init__.pynew file mode 100644index 0000000..f90f0a2--- /dev/null+++ b/reshot/web/__init__.py@@ -0,0 +1,386 @@+"""The local web UI: `reshot` with no arguments (or `reshot web`) starts it and opens a browser.++One HTML page (``index.html`` next to this file) talks to a small JSON API served by the+standard library — no framework, no extra dependency, so ``pip install reshot`` is all a+user needs. Everything stays on the user's machine: uploads go to a temp folder, results to+``~/ReShot`` (or ``--out``).++API+ POST /api/upload multipart "file" → source info (id, size, fps, frames, seconds)+ GET /api/source/<id> the uploaded clip, for the preview player+ POST /api/jobs JSON options → {"id"}; runs in the single worker thread+ GET /api/jobs/<id> status, progress steps, result / error+ GET /api/output/<id> the depth video (``?download=1`` for an attachment)+ GET /api/info version, device, VRAM, output folder++Why one worker thread with a cached model: the depth model is loaded once per server+process (3–6 s) and every job reuses it; two jobs at once would fight for the GPU, so they+queue. Why polling instead of SSE: 500 ms polls are plenty for a 20-second job and keep+the server a plain ``http.server``.+"""++from __future__ import annotations++import json+import logging+import mimetypes+import queue+import socket+import sys+import threading+import time+import traceback+import uuid+import webbrowser+from email.parser import BytesParser+from email.policy import HTTP+from http import HTTPStatus+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path+from urllib.parse import parse_qs, urlparse++from .._version import __version__+from ..config import RunConfig+from ..errors import ReshotError+from ..io import probe_video+from ..pipeline import _cuda_total_bytes, _make_backend, _run_one+from ..targets import TARGETS++log = logging.getLogger("reshot.web")++MAX_UPLOAD_BYTES = 500 * 2**20+DEFAULT_PORT = 8765+++class _Job:+ """One depth run: options in, progress steps and a result (or error) out."""++ def __init__(self, cfg: RunConfig, source_name: str) -> None:+ self.id = uuid.uuid4().hex[:12]+ self.cfg = cfg+ self.source_name = source_name+ self.status = "queued" # queued | running | done | error+ self.steps: list[dict] = []+ self.result: dict | None = None+ self.error: str | None = None+ self.created = time.time()+ self.started: float | None = None+ self.finished: float | None = None++ # Reporter protocol — the pipeline calls this for every stage.+ def step(self, tag: str, message: str) -> None:+ self.steps.append({"tag": tag, "message": message, "t": round(time.time() - (self.started or time.time()), 1)})++ def to_dict(self) -> dict:+ return {+ "id": self.id,+ "status": self.status,+ "source_name": self.source_name,+ "target": self.cfg.target,+ "quality": self.cfg.quality,+ "steps": self.steps,+ "result": self.result,+ "error": self.error,+ "elapsed": round((self.finished or time.time()) - (self.started or self.created), 1),+ }+++class _State:+ """Everything the handlers share. One instance per server."""++ def __init__(self, out_dir: Path, tmp_dir: Path) -> None:+ self.out_dir = out_dir+ self.tmp_dir = tmp_dir+ self.sources: dict[str, dict] = {}+ self.jobs: dict[str, _Job] = {}+ self.queue: queue.Queue[_Job] = queue.Queue()+ self.backend = None+ self.backend_name = ""+ self.lock = threading.Lock()+ self.device = "?"++ def worker(self) -> None:+ while True:+ job = self.queue.get()+ job.status = "running"+ job.started = time.time()+ try:+ if self.backend is None:+ job.step("model", "loading the depth model (once per session)")+ self.backend, self.backend_name = _make_backend(job.cfg)+ self.device = self.backend.device+ res = _run_one(job.cfg, job, self.backend, self.backend_name)+ job.result = {+ "output": str(res.output),+ "output_url": f"/api/output/{job.id}",+ "frames": res.frames,+ "fps": res.fps,+ "width": res.width,+ "height": res.height,+ "device": res.device,+ "precision": res.precision,+ "ms_per_frame": round(res.ms_per_frame, 1),+ "depth_seconds": round(res.depth_seconds, 1),+ "total_seconds": round(res.total_seconds, 1),+ "model_input_resolution": res.metrics.get("model_input_resolution"),+ "gpu_peak_reserved_bytes": res.metrics.get("gpu_peak_reserved_bytes"),+ "output_bytes": res.metrics.get("output_bytes"),+ }+ job.status = "done"+ except ReshotError as exc:+ job.error = str(exc)+ job.status = "error"+ except Exception as exc: # a bug, not a user problem — show it rather than hang+ job.error = f"{type(exc).__name__}: {exc}"+ job.status = "error"+ log.error("job %s crashed:\n%s", job.id, traceback.format_exc())+ finally:+ job.finished = time.time()+ self.queue.task_done()+++def _safe_stem(name: str) -> str:+ stem = Path(name).stem or "clip"+ return "".join(c if c.isalnum() or c in "-_ ." else "_" for c in stem)[:80].strip() or "clip"+++class _Handler(BaseHTTPRequestHandler):+ state: _State # set by serve()+ index_html: bytes++ # ---- plumbing -------------------------------------------------------------+ def log_message(self, fmt, *args): # quiet unless -v+ log.debug("%s " + fmt, self.address_string(), *args)++ def _json(self, obj, status=HTTPStatus.OK) -> None:+ body = json.dumps(obj, ensure_ascii=False).encode()+ self.send_response(status)+ self.send_header("Content-Type", "application/json; charset=utf-8")+ self.send_header("Content-Length", str(len(body)))+ self.send_header("Cache-Control", "no-store")+ self.end_headers()+ self.wfile.write(body)++ def _file(self, path: Path, download_name: str | None = None) -> None:+ if not path.is_file():+ return self._json({"error": "not found"}, HTTPStatus.NOT_FOUND)+ size = path.stat().st_size+ ctype = mimetypes.guess_type(str(path))[0] or "application/octet-stream"+ # Range support so the <video> element can seek.+ start, end = 0, size - 1+ rng = self.headers.get("Range")+ status = HTTPStatus.OK+ if rng and rng.startswith("bytes="):+ a, _, b = rng[6:].partition("-")+ start = int(a) if a else max(0, size - int(b))+ end = int(b) if b and a else size - 1+ end = min(end, size - 1)+ status = HTTPStatus.PARTIAL_CONTENT+ self.send_response(status)+ self.send_header("Content-Type", ctype)+ self.send_header("Accept-Ranges", "bytes")+ self.send_header("Content-Length", str(end - start + 1))+ if status == HTTPStatus.PARTIAL_CONTENT:+ self.send_header("Content-Range", f"bytes {start}-{end}/{size}")+ if download_name:+ self.send_header("Content-Disposition", f'attachment; filename="{download_name}"')+ self.end_headers()+ with open(path, "rb") as fh:+ fh.seek(start)+ remaining = end - start + 1+ while remaining > 0:+ chunk = fh.read(min(1 << 20, remaining))+ if not chunk:+ break+ self.wfile.write(chunk)+ remaining -= len(chunk)++ # ---- routes -----------------------------------------------------------------+ def do_GET(self) -> None:+ url = urlparse(self.path)+ parts = [p for p in url.path.split("/") if p]+ try:+ if not parts or parts == ["index.html"]:+ self.send_response(HTTPStatus.OK)+ self.send_header("Content-Type", "text/html; charset=utf-8")+ self.send_header("Content-Length", str(len(self.index_html)))+ self.send_header("Cache-Control", "no-store")+ self.end_headers()+ self.wfile.write(self.index_html)+ elif parts == ["api", "info"]:+ self._json(self._info())+ elif parts[:2] == ["api", "source"] and len(parts) == 3:+ src = self.state.sources.get(parts[2])+ self._file(Path(src["path"])) if src else self._json({"error": "unknown source"}, HTTPStatus.NOT_FOUND)+ elif parts[:2] == ["api", "jobs"] and len(parts) == 3:+ job = self.state.jobs.get(parts[2])+ self._json(job.to_dict()) if job else self._json({"error": "unknown job"}, HTTPStatus.NOT_FOUND)+ elif parts == ["api", "jobs"]:+ self._json([j.to_dict() for j in sorted(self.state.jobs.values(), key=lambda j: j.created)])+ elif parts[:2] == ["api", "output"] and len(parts) == 3:+ job = self.state.jobs.get(parts[2])+ if not job or not job.result:+ return self._json({"error": "no output yet"}, HTTPStatus.NOT_FOUND)+ q = parse_qs(url.query)+ self._file(Path(job.result["output"]), Path(job.result["output"]).name if q.get("download") else None)+ else:+ self._json({"error": "not found"}, HTTPStatus.NOT_FOUND)+ except (BrokenPipeError, ConnectionResetError):+ pass # the browser closed the video stream; normal++ def do_POST(self) -> None:+ parts = [p for p in urlparse(self.path).path.split("/") if p]+ if parts == ["api", "upload"]:+ return self._upload()+ if parts == ["api", "jobs"]:+ return self._create_job()+ self._json({"error": "not found"}, HTTPStatus.NOT_FOUND)++ def _info(self) -> dict:+ st = self.state+ vram = _cuda_total_bytes("cuda") if st.device == "cuda" else 0+ return {+ "version": __version__,+ "device": st.device,+ "vram_bytes": vram,+ "out_dir": str(st.out_dir),+ "targets": {+ k: {"fps": v.fps, "multiple": v.multiple, "max_seconds": v.max_seconds} for k, v in TARGETS.items()+ },+ "model_loaded": st.backend is not None,+ }++ def _upload(self) -> None:+ length = int(self.headers.get("Content-Length") or 0)+ if length <= 0 or length > MAX_UPLOAD_BYTES:+ return self._json(+ {"error": f"upload must be 1 byte – {MAX_UPLOAD_BYTES // 2**20} MB"}, HTTPStatus.BAD_REQUEST+ )+ ctype = self.headers.get("Content-Type", "")+ if "multipart/form-data" not in ctype:+ return self._json({"error": "expected multipart/form-data"}, HTTPStatus.BAD_REQUEST)+ raw = self.rfile.read(length)+ # The email parser handles multipart/form-data correctly and is in the stdlib.+ msg = BytesParser(policy=HTTP).parsebytes(b"Content-Type: " + ctype.encode() + b"\r\n\r\n" + raw)+ part = next((p for p in msg.iter_parts() if p.get_param("name", header="content-disposition") == "file"), None)+ if part is None:+ return self._json({"error": "no 'file' field"}, HTTPStatus.BAD_REQUEST)+ filename = part.get_filename() or "clip.mp4"+ data = part.get_payload(decode=True)+ sid = uuid.uuid4().hex[:12]+ path = self.state.tmp_dir / f"{sid}_{_safe_stem(filename)}{Path(filename).suffix.lower() or '.mp4'}"+ path.write_bytes(data)+ try:+ w, h, fps, n = probe_video(path)+ except Exception as exc:+ path.unlink(missing_ok=True)+ return self._json({"error": f"cannot read that file as a video ({exc})"}, HTTPStatus.BAD_REQUEST)+ if w <= 0 or h <= 0:+ path.unlink(missing_ok=True)+ return self._json({"error": "that file has no video stream"}, HTTPStatus.BAD_REQUEST)+ info = {+ "id": sid,+ "name": filename,+ "path": str(path),+ "bytes": len(data),+ "width": w,+ "height": h,+ "fps": round(fps, 3),+ "frames": n,+ "seconds": round(n / fps, 2) if fps else 0,+ "url": f"/api/source/{sid}",+ }+ self.state.sources[sid] = info+ self._json({k: v for k, v in info.items() if k != "path"})++ def _create_job(self) -> None:+ length = int(self.headers.get("Content-Length") or 0)+ try:+ body = json.loads(self.rfile.read(length) or b"{}")+ except json.JSONDecodeError:+ return self._json({"error": "bad JSON"}, HTTPStatus.BAD_REQUEST)+ src = self.state.sources.get(str(body.get("source_id", "")))+ if not src:+ return self._json({"error": "upload a video first"}, HTTPStatus.BAD_REQUEST)+ target = str(body.get("target", "seedance"))+ stem = _safe_stem(src["name"])+ out = self.state.out_dir / f"{stem}_depth_{target}.mp4"+ n = 2+ while out.exists(): # never overwrite an earlier result+ out = self.state.out_dir / f"{stem}_depth_{target}_{n}.mp4"+ n += 1+ try:+ cfg = RunConfig(+ input=Path(src["path"]),+ output=out,+ target=target,+ quality=str(body.get("quality", "fast")),+ max_res=int(body.get("max_side") or 1280) if body.get("max_side") else 1280,+ max_frames=int(body["max_frames"]) if body.get("max_frames") else None,+ invert=bool(body.get("invert", False)),+ clip_percent=float(body.get("clip_percent", 0.0) or 0.0),+ gamma=float(body.get("gamma", 1.0) or 1.0),+ metrics=out.with_suffix(".json"),+ force=bool(body.get("force", False)),+ )+ except (ReshotError, ValueError) as exc:+ return self._json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)+ job = _Job(cfg, src["name"])+ self.state.jobs[job.id] = job+ self.state.queue.put(job)+ self._json({"id": job.id})+++def _free_port(preferred: int) -> int:+ for port in range(preferred, preferred + 20):+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:+ try:+ s.bind(("127.0.0.1", port))+ return port+ except OSError:+ continue+ return 0+++def make_server(out_dir: Path, port: int = 0, tmp_dir: Path | None = None) -> ThreadingHTTPServer:+ """Build (but don't run) the server — used by `serve()` and by the tests."""+ import tempfile++ out_dir = Path(out_dir).expanduser()+ out_dir.mkdir(parents=True, exist_ok=True)+ tmp = Path(tmp_dir) if tmp_dir else Path(tempfile.mkdtemp(prefix="reshot-web-"))+ tmp.mkdir(parents=True, exist_ok=True)+ state = _State(out_dir, tmp)+ threading.Thread(target=state.worker, name="reshot-worker", daemon=True).start()++ handler = type("ReShotHandler", (_Handler,), {})+ handler.state = state+ handler.index_html = (Path(__file__).parent / "index.html").read_bytes()+ server = ThreadingHTTPServer(("127.0.0.1", port), handler)+ server.daemon_threads = True+ server.reshot_state = state # type: ignore[attr-defined]+ return server+++def serve(out_dir: Path | None = None, port: int = DEFAULT_PORT, open_browser: bool = True) -> int:+ """Run the UI until Ctrl-C. Returns an exit code."""+ out = Path(out_dir) if out_dir else Path.home() / "ReShot"+ chosen = _free_port(port)+ if not chosen:+ print(f"reshot: no free port between {port} and {port + 19}", file=sys.stderr)+ return 1+ server = make_server(out, chosen)+ url = f"http://127.0.0.1:{chosen}/"+ print(f"ReShot {__version__} — open {url} (results go to {out}; Ctrl-C to stop)", file=sys.stderr)+ if open_browser:+ threading.Timer(0.4, lambda: webbrowser.open(url)).start()+ try:+ server.serve_forever()+ except KeyboardInterrupt:+ print("\nreshot: stopped", file=sys.stderr)+ finally:+ server.server_close()+ return 0+++__all__ = ["DEFAULT_PORT", "make_server", "serve"]diff --git a/reshot/web/index.html b/reshot/web/index.htmlnew file mode 100644index 0000000..3a4610f--- /dev/null+++ b/reshot/web/index.html@@ -0,0 +1,441 @@+<!doctype html>+<html lang="zh">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width,initial-scale=1">+<title>ReShot · 猫斯卡</title>+<style>+/* Studio Air tokens — the Maosika visual system (dark studio, lime accent, system fonts). */+:root{+ --bg:#0d0d0f;--surface:#1a1a1e;--surface-2:#28282c;--card:#101216;+ --text:#eaeaef;--text-2:#adadb8;--text-3:#72727c;+ --accent:#d8ff42;--accent-bright:#e2f060;--accent-border:rgba(216,255,66,.45);--accent-ink:#2a3208;--active-ink:#0a0b0d;+ --error:#ff6b6b;--line:rgba(255,255,255,.07);--line-2:rgba(255,255,255,.12);+ --cinema-bg:#0b0f0f;--cinema-deep:#080b0b;--teal:#5cc4bc;--teal-border:rgba(92,196,188,.32);--teal-soft:rgba(92,196,188,.12);+ --font:-apple-system,BlinkMacSystemFont,"SF Pro Text","Segoe UI",Roboto,"Helvetica Neue",Arial,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","Noto Sans CJK SC",sans-serif;+ --mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Consolas,monospace;+ --ease:cubic-bezier(.22,1,.36,1);--radius:22px;--radius-sm:16px;+}+*{box-sizing:border-box}+html,body{margin:0;background:var(--bg);color:var(--text);font:15px/1.55 var(--font);letter-spacing:-.01em;-webkit-font-smoothing:antialiased}+a{color:var(--accent);text-decoration:none}+button{font:inherit;letter-spacing:inherit;cursor:pointer}+[hidden]{display:none!important}++/* header */+.hdr{height:60px;display:flex;align-items:center;justify-content:space-between;padding:0 28px;border-bottom:.5px solid rgba(255,255,255,.06);background:rgba(13,13,15,.85);backdrop-filter:blur(14px);position:sticky;top:0;z-index:5}+.logo{display:inline-flex;align-items:center;gap:10px;font-weight:750;font-size:1.25rem;color:var(--text);white-space:nowrap}+.logo:hover{color:var(--accent-bright)}+.logo-mark{display:inline-flex;align-items:center;justify-content:center;width:32px;height:32px;border-radius:10px;font-size:1.05rem;font-weight:800;color:var(--accent-ink);background:linear-gradient(160deg,var(--accent-bright),var(--accent));border:.5px solid var(--accent-border);box-shadow:0 2px 10px rgba(216,255,66,.18)}+.logo-sep{color:var(--text-3);font-weight:500;margin:0 2px}+.logo-app{color:var(--text)}+.hdr-right{display:flex;align-items:center;gap:14px;font-size:.875rem;color:var(--text-2)}+.hdr-right a{color:var(--text-2)}.hdr-right a:hover{color:var(--accent-bright)}+.lang{border:1px solid var(--line-2);background:transparent;color:var(--text-2);border-radius:999px;padding:4px 11px;font-size:.78rem;font-weight:600}+.lang:hover{color:var(--text);border-color:rgba(255,255,255,.22)}++/* page */+.wrap{max-width:1120px;margin:0 auto;padding:26px 28px 60px}+.intro{margin:6px 0 20px}+.intro h1{margin:0 0 6px;font-size:1.5rem;font-weight:700;letter-spacing:-.02em}+.intro p{margin:0;color:var(--text-2);font-size:.95rem;max-width:760px}++/* the one card */+.card{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);display:grid;grid-template-columns:minmax(0,1.15fr) minmax(360px,.85fr);overflow:hidden}+.stage{background:var(--cinema-deep);border-right:1px solid var(--line);padding:22px;display:flex;flex-direction:column;gap:14px;min-height:520px}+.opts{padding:22px 24px 24px;display:flex;flex-direction:column;gap:20px}++/* stage: drop zone / players */+.drop{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;border-radius:18px;background:linear-gradient(180deg,#1c2128,#12151a);border:1px solid var(--line);cursor:pointer;transition:border-color .18s,background .18s;text-align:center;padding:30px}+.drop:hover,.drop.is-over{border-color:var(--teal-border);background:linear-gradient(180deg,#1e262b,#12181a)}+.drop .big{font-size:1.05rem;font-weight:650;color:var(--text)}+.drop .sub{font-size:.85rem;color:var(--text-2)}+.drop .hint{font-size:.78rem;color:var(--text-3);margin-top:8px}+.drop .icon{width:44px;height:44px;border-radius:12px;background:var(--teal-soft);border:1px solid var(--teal-border);display:flex;align-items:center;justify-content:center;color:var(--teal);font-size:1.3rem}+.players{display:grid;grid-template-columns:1fr;gap:12px;align-content:start}+/* portrait clips sit side by side, landscape clips stack — either way the boxes hug the video */+.players.two.portrait{grid-template-columns:1fr 1fr}+.player{position:relative;border-radius:18px;overflow:hidden;background:#000;border:1px solid var(--line)}+.player video{display:block;width:100%;height:auto;max-height:56vh;object-fit:contain;background:#000}+.players.two.portrait .player video{max-height:62vh}+.player .tag{position:absolute;top:10px;left:10px;font-size:.72rem;font-weight:650;letter-spacing:.02em;padding:4px 9px;border-radius:999px;background:rgba(0,0,0,.55);color:var(--text);border:1px solid rgba(255,255,255,.12)}+.player .tag.depth{background:rgba(92,196,188,.18);border-color:var(--teal-border);color:#dff7f4}+.meta{display:flex;flex-wrap:wrap;gap:6px 14px;font-size:.8rem;color:var(--text-2);font-family:var(--mono)}+.meta b{color:var(--text);font-weight:600;font-family:var(--font)}+.meta .name{font-family:var(--font);color:var(--text);max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}+.stage-foot{display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap}+.ghost{border:1px solid var(--line-2);background:transparent;color:var(--text);border-radius:12px;padding:7px 12px;font-size:.82rem;font-weight:600}+.ghost:hover{border-color:rgba(255,255,255,.22);background:rgba(255,255,255,.04)}+.ghost.teal{border-color:var(--teal-border);color:#dff7f4;background:var(--teal-soft)}++/* options */+.opt h3{margin:0 0 8px;font-size:.8rem;font-weight:650;letter-spacing:.02em;color:var(--text-2);text-transform:uppercase}+.seg{display:flex;background:var(--surface);border:1px solid var(--line);border-radius:18px;padding:4px;gap:2px}+.seg button{flex:1;border:0;background:transparent;color:var(--text-2);border-radius:13px;padding:9px 6px;font-size:.86rem;font-weight:650;white-space:nowrap;transition:color .15s,background .15s}+.seg button:hover{color:var(--text)}+.seg button.on{background:var(--accent);color:var(--active-ink)}+.seg button:focus-visible{outline:2px solid var(--accent);outline-offset:2px}+.note{margin:8px 2px 0;font-size:.8rem;color:var(--text-3);line-height:1.5}+.note b{color:var(--text-2);font-weight:600}+.warn{margin-top:8px;font-size:.8rem;color:#ffd08a;background:rgba(255,184,108,.08);border:1px solid rgba(255,184,108,.25);border-radius:12px;padding:8px 11px}++details.adv{border:1px solid var(--line);border-radius:var(--radius-sm);background:var(--surface)}+details.adv summary{cursor:pointer;list-style:none;padding:11px 14px;font-size:.85rem;font-weight:600;color:var(--text-2);display:flex;justify-content:space-between;align-items:center}+details.adv summary::-webkit-details-marker{display:none}+details.adv summary::after{content:"+";font-size:1rem;color:var(--text-3)}+details.adv[open] summary::after{content:"−"}+.adv-body{padding:2px 14px 14px;display:grid;grid-template-columns:1fr 1fr;gap:12px 16px}+.field label{display:block;font-size:.78rem;color:var(--text-2);margin-bottom:5px;font-weight:600}+.field input[type=number]{width:100%;background:var(--surface-2);border:1px solid var(--line);color:var(--text);border-radius:10px;padding:8px 10px;font:inherit;font-size:.9rem}+.field input[type=number]:focus{outline:none;border-color:var(--accent-border)}+.field .tip{font-size:.72rem;color:var(--text-3);margin-top:4px;line-height:1.4}+.check{display:flex;align-items:center;gap:8px;font-size:.85rem;color:var(--text);cursor:pointer;grid-column:1/-1}+.check input{accent-color:var(--accent);width:16px;height:16px}++.cta{margin-top:auto;border:0;border-radius:14px;padding:14px 18px;font-size:1rem;font-weight:700;color:var(--accent-ink);background:var(--accent);transition:transform .18s var(--ease),box-shadow .18s,background .15s}+.cta:hover:not(:disabled){background:var(--accent-bright);transform:scale(1.02);box-shadow:0 4px 14px rgba(216,255,66,.32)}+.cta:active:not(:disabled){transform:scale(.98)}+.cta:disabled{opacity:.45;cursor:not-allowed}++/* progress + result */+.prog{border:1px solid var(--line);border-radius:var(--radius-sm);background:var(--surface);padding:12px 14px;font-size:.82rem}+.prog .row{display:flex;gap:10px;padding:3px 0;color:var(--text-2)}+.prog .row .t{font-family:var(--mono);color:var(--text-3);width:52px;flex:none}+.prog .row .k{font-family:var(--mono);color:var(--teal);width:60px;flex:none}+.prog .row.warn-row .k{color:#ffd08a}+.prog .spin{display:inline-block;width:12px;height:12px;border:2px solid rgba(216,255,66,.25);border-top-color:var(--accent);border-radius:50%;animation:spin .9s linear infinite;vertical-align:-2px;margin-right:6px}+@keyframes spin{to{transform:rotate(360deg)}}+.result{border:1px solid var(--teal-border);background:var(--teal-soft);border-radius:var(--radius-sm);padding:14px}+.result h4{margin:0 0 8px;font-size:.95rem;font-weight:700;color:#dff7f4}+.chips{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:12px}+.chip{font-size:.74rem;font-family:var(--mono);color:var(--text-2);border:1px solid var(--line-2);border-radius:999px;padding:3px 9px}+.chip b{color:var(--text);font-weight:600}+.btns{display:flex;gap:8px;flex-wrap:wrap}+.btn{border-radius:12px;padding:9px 14px;font-size:.85rem;font-weight:650;border:1px solid var(--line-2);background:transparent;color:var(--text)}+.btn:hover{border-color:rgba(255,255,255,.25);background:rgba(255,255,255,.04)}+.btn.primary{background:var(--accent);color:var(--accent-ink);border-color:transparent}+.btn.primary:hover{background:var(--accent-bright)}+.path{margin-top:10px;font-size:.74rem;color:var(--text-3);font-family:var(--mono);word-break:break-all}+.next{margin-top:12px;border-top:1px solid rgba(255,255,255,.08);padding-top:10px;font-size:.82rem;color:var(--text-2);line-height:1.55}+.next code{display:block;margin-top:6px;padding:9px 11px;border-radius:10px;background:rgba(0,0,0,.35);color:var(--text);font-family:var(--font);font-size:.8rem;white-space:pre-wrap}+.err{border:1px solid rgba(255,107,107,.4);background:rgba(255,107,107,.08);color:#ffb3b3;border-radius:var(--radius-sm);padding:12px 14px;font-size:.85rem;white-space:pre-wrap}++footer{margin-top:26px;display:flex;flex-wrap:wrap;gap:6px 18px;font-size:.8rem;color:var(--text-3)}+footer a{color:var(--text-2)}footer a:hover{color:var(--accent-bright)}++@media (max-width:900px){+ .card{grid-template-columns:1fr}+ .stage{border-right:0;border-bottom:1px solid var(--line);min-height:0}+ .wrap{padding:18px 16px 40px}.hdr{padding:0 16px}+ .adv-body{grid-template-columns:1fr}+ .players.two{grid-template-columns:1fr}+}+@media (prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}+</style>+</head>+<body>+<header class="hdr">+ <a class="logo" href="https://www.maosika.com" target="_blank" rel="noopener" title="www.maosika.com">+ <span class="logo-mark" aria-hidden="true">M</span>+ <span data-i18n="brand">猫斯卡</span><span class="logo-sep">·</span><span class="logo-app">ReShot</span>+ </a>+ <div class="hdr-right">+ <a href="https://www.maosika.com" target="_blank" rel="noopener" data-i18n="hdr.maosika">去猫斯卡做 AI 短剧 ↗</a>+ <a href="https://github.com/maosika-ai/reshot" target="_blank" rel="noopener">GitHub</a>+ <button class="lang" id="lang" type="button">EN</button>+ </div>+</header>++<main class="wrap">+ <div class="intro">+ <h1 data-i18n="intro.h1">复制走位,不复制演员。</h1>+ <p data-i18n="intro.p">把一段参考视频变成深度图视频,交给 Seedance 或 MiniMax H3 当参考,它就会照着这段的动作和运镜再拍一遍——人物换成你的。所有处理都在这台电脑上完成。</p>+ </div>++ <section class="card">+ <!-- left: source / result stage -->+ <div class="stage">+ <div class="drop" id="drop" role="button" tabindex="0">+ <div class="icon">▶</div>+ <div class="big" data-i18n="drop.big">拖入参考视频,或点击选择</div>+ <div class="sub" data-i18n="drop.sub">mp4 / mov / webm · 15 秒以内效果最好</div>+ <div class="hint" data-i18n="drop.hint">视频不会上传到任何服务器</div>+ <input type="file" id="file" accept="video/*,.mp4,.mov,.webm,.mkv" hidden>+ </div>+ <div class="players" id="players" hidden>+ <div class="player" id="srcPlayer"><span class="tag" data-i18n="tag.src">参考片</span><video id="srcVideo" controls muted loop playsinline></video></div>+ <div class="player" id="outPlayer" hidden><span class="tag depth" data-i18n="tag.depth">深度图</span><video id="outVideo" controls muted loop playsinline></video></div>+ </div>+ <div class="meta" id="meta" hidden></div>+ <div class="stage-foot" id="stageFoot" hidden>+ <button class="ghost" id="changeBtn" type="button" data-i18n="stage.change">换一段视频</button>+ <button class="ghost teal" id="syncBtn" type="button" hidden data-i18n="stage.sync">同步播放</button>+ </div>+ </div>++ <!-- right: options -->+ <div class="opts">+ <div class="opt">+ <h3 data-i18n="opt.target">给谁用</h3>+ <div class="seg" id="target">+ <button type="button" data-v="seedance" class="on">Seedance</button>+ <button type="button" data-v="h3">MiniMax H3</button>+ <button type="button" data-v="wan">Wan</button>+ <button type="button" data-v="none" data-i18n="opt.none">通用</button>+ </div>+ <div class="note" id="targetNote"></div>+ <div class="warn" id="lenWarn" hidden></div>+ </div>++ <div class="opt">+ <h3 data-i18n="opt.quality">画质</h3>+ <div class="seg" id="quality">+ <button type="button" data-v="fast" class="on" data-i18n="q.fast">快速(推荐)</button>+ <button type="button" data-v="full" data-i18n="q.full">完整</button>+ </div>+ <div class="note" id="qualityNote"></div>+ </div>++ <details class="adv">+ <summary data-i18n="adv.title">高级选项</summary>+ <div class="adv-body">+ <div class="field"><label for="maxSide" data-i18n="adv.maxSide">输出长边上限</label><input type="number" id="maxSide" min="0" step="2" placeholder="0"><div class="tip" data-i18n="adv.maxSideTip">0 = 原片尺寸。给 MiniMax H3 当参考视频建议 320。</div></div>+ <div class="field"><label for="maxFrames" data-i18n="adv.maxFrames">只处理前 N 帧</label><input type="number" id="maxFrames" min="1" step="1" placeholder="全部"><div class="tip" data-i18n="adv.maxFramesTip">试效果时用,比如 48。</div></div>+ <div class="field"><label for="clip" data-i18n="adv.clip">裁掉两端 %</label><input type="number" id="clip" min="0" max="10" step="0.1" value="0"><div class="tip" data-i18n="adv.clipTip">有东西贴着镜头把其他全压黑时用 0.5–1。</div></div>+ <div class="field"><label for="gamma">Gamma</label><input type="number" id="gamma" min="0.2" max="3" step="0.05" value="1"><div class="tip" data-i18n="adv.gammaTip">>1 压暗中间调,把近处拉开。一般不动。</div></div>+ <label class="check"><input type="checkbox" id="invert"><span data-i18n="adv.invert">反转:远白近黑(默认近白远黑,Seedance / H3 / ControlNet 都要这个)</span></label>+ </div>+ </details>++ <div class="prog" id="prog" hidden></div>+ <div class="err" id="err" hidden></div>+ <div class="result" id="result" hidden></div>++ <button class="cta" id="run" type="button" disabled data-i18n="cta">生成深度图</button>+ </div>+ </section>++ <footer>+ <span><span data-i18n="foot.by">出品</span> <a href="https://www.maosika.com" target="_blank" rel="noopener">猫斯卡 · www.maosika.com</a></span>+ <span data-i18n="foot.what">AI 短剧 / AI 短视频自动生产系统</span>+ <a href="https://github.com/maosika-ai/reshot" target="_blank" rel="noopener">GitHub</a>+ <a href="https://github.com/maosika-ai/ComfyUI-ReShot" target="_blank" rel="noopener" data-i18n="foot.comfy">ComfyUI 节点</a>+ <span id="ver"></span>+ </footer>+</main>++<script>+(() => {+const I18N = {+ zh: {+ brand:"猫斯卡", "hdr.maosika":"去猫斯卡做 AI 短剧 ↗",+ "intro.h1":"复制走位,不复制演员。",+ "intro.p":"把一段参考视频变成深度图视频,交给 Seedance 或 MiniMax H3 当参考,它就会照着这段的动作和运镜再拍一遍——人物换成你的。所有处理都在这台电脑上完成。",+ "drop.big":"拖入参考视频,或点击选择","drop.sub":"mp4 / mov / webm · 15 秒以内效果最好","drop.hint":"视频不会上传到任何服务器",+ "tag.src":"参考片","tag.depth":"深度图","stage.change":"换一段视频","stage.sync":"同步播放",+ "opt.target":"给谁用","opt.none":"通用","opt.quality":"画质","q.fast":"快速(推荐)","q.full":"完整",+ "adv.title":"高级选项","adv.maxSide":"输出长边上限","adv.maxSideTip":"0 = 原片尺寸。给 MiniMax H3 当参考视频建议 320。",+ "adv.maxFrames":"只处理前 N 帧","adv.maxFramesTip":"试效果时用,比如 48。","adv.clip":"裁掉两端 %","adv.clipTip":"有东西贴着镜头把其他全压黑时用 0.5–1。",+ "adv.gammaTip":">1 压暗中间调,把近处拉开。一般不动。","adv.invert":"反转:远白近黑(默认近白远黑,Seedance / H3 / ControlNet 都要这个)",+ cta:"生成深度图", "cta.running":"生成中…", "cta.again":"再生成一次",+ "foot.by":"出品","foot.what":"AI 短剧 / AI 短视频自动生产系统","foot.comfy":"ComfyUI 节点",+ t_seedance:"<b>Seedance 2.0 / 2.5 参考视频</b>:24 fps,宽高 16 的倍数,≤ 15 秒。上传后提示词写「参考@视频1的动作与运镜」。",+ t_h3:"<b>MiniMax H3</b>:24 fps,宽高 32 的倍数,≤ 15 秒。当参考视频挂 <Video 1> 时,高级选项里把长边限到 320 效果最好。",+ t_wan:"<b>Wan 2.1 VACE</b>:16 fps,宽高 16 的倍数,作为 control_video。(这条我们未端到端验证。)",+ t_none:"<b>通用</b>:保持原 fps,只把宽高凑成偶数。给任何认深度视频的模型。",+ q_fast:"模型看 <b>644×364</b>(16:9)/ 364×644(9:16)。约 3 GB 显存,快。复制走位和运镜足够。",+ q_full:"模型看 <b>924×518</b> / 518×924。约 11 GB 显存,慢 2.5 倍,细轮廓更锐。特写、在意发丝时用。",+ lenWarn:"这段 {s} 秒,{t} 只收 ≤ {m} 秒的参考视频——先剪短,或在高级选项里限制帧数。",+ meta_fmt:"{w}×{h} · {fps} fps · {n} 帧 · {s} 秒 · {mb} MB",+ uploading:"读取视频…", queued:"排队中", loading_model:"加载模型(每次启动只一次)",+ step_plan:"计划", step_read:"解码", step_model:"模型", step_depth:"深度", step_size:"尺寸", step_wrote:"写出", step_warn:"提醒", step_vram:"显存", step_quality:"画质", step_metrics:"指标", step_npz:"npz", step_note:"注",+ done:"完成", chips:{frames:"帧",fps:"fps",size:"尺寸",speed:"ms/帧",device:"设备",model:"模型看到",vram:"显存峰值",file:"文件"},+ download:"下载深度图", openFolder:"保存在", next_title:"下一步",+ next_seedance:"到 Seedance 把这个文件当「参考视频」上传,提示词开头写:",+ next_seedance_p:"参考@视频1的动作与运镜,顺序与视频保持一致。\n(接着写你的人物、服装、场景和画风)",+ next_h3:"在 MiniMax H3 里把它挂成 <Video 1>(定妆图挂 <Picture 1>),提示词里定义它并说明灰色外观不要抄:",+ next_h3_p:"<Subject 3> is the fight choreography and camera movement shown in <Video 1>, a grey depth map in which near objects are white and far objects are black: (用一句话写清灰片里发生了什么)\n<Subject 3>: attribute_transfer - every action, position, timing and camera move of <Video 1> is transferred onto <Subject 1>; its grey depth look is not transferred.",+ next_wan:"在 ComfyUI 里接到 WanVaceToVideo 的 control_video。", next_none:"交给任何认深度视频的模型。",+ copy:"复制提示词", copied:"已复制 ✓", err_title:"没成功",+ "info.device":"本机:{d}",+ },+ en: {+ brand:"Maosika", "hdr.maosika":"Make AI short drama at Maosika ↗",+ "intro.h1":"Copy the shot, not the actors.",+ "intro.p":"Turn a reference video into a depth-map video, give it to Seedance or MiniMax H3 as the reference, and it repeats the moves and camera with your own characters. Everything runs on this computer.",+ "drop.big":"Drop a reference video, or click to choose","drop.sub":"mp4 / mov / webm · under 15 s works best","drop.hint":"Nothing is uploaded to any server",+ "tag.src":"Reference","tag.depth":"Depth map","stage.change":"Change video","stage.sync":"Play both",+ "opt.target":"For which model","opt.none":"Generic","opt.quality":"Quality","q.fast":"Fast (recommended)","q.full":"Full",+ "adv.title":"Advanced","adv.maxSide":"Max output long side","adv.maxSideTip":"0 = source size. 320 recommended for MiniMax H3 reference videos.",+ "adv.maxFrames":"Only the first N frames","adv.maxFramesTip":"For a quick test, e.g. 48.","adv.clip":"Clip both ends %","adv.clipTip":"0.5–1 when something at the lens crushes everything else to black.",+ "adv.gammaTip":">1 darkens mid-tones, spreading the near range. Rarely needed.","adv.invert":"Invert: far = white (default near = white, what Seedance / H3 / ControlNets expect)",+ cta:"Make depth map", "cta.running":"Working…", "cta.again":"Run again",+ "foot.by":"Made by","foot.what":"AI short drama & short video production system","foot.comfy":"ComfyUI nodes",+ t_seedance:"<b>Seedance 2.0 / 2.5 reference video</b>: 24 fps, sides ×16, ≤ 15 s. Prompt with “参考@视频1的动作与运镜”.",+ t_h3:"<b>MiniMax H3</b>: 24 fps, sides ×32, ≤ 15 s. As a reference video (<Video 1>) it works best small — set max long side 320 in Advanced.",+ t_wan:"<b>Wan 2.1 VACE</b>: 16 fps, sides ×16, as control_video. (Not verified end to end by us.)",+ t_none:"<b>Generic</b>: keep the source fps, only make dimensions even. For anything that reads a depth video.",+ q_fast:"The model sees <b>644×364</b> (16:9) / 364×644 (9:16). ~3 GB VRAM, fast. Enough for blocking and camera.",+ q_full:"The model sees <b>924×518</b> / 518×924. ~11 GB VRAM, 2.5× slower, sharper fine silhouettes. For close-ups.",+ lenWarn:"This clip is {s} s; {t} accepts reference videos ≤ {m} s — trim it first, or limit frames in Advanced.",+ meta_fmt:"{w}×{h} · {fps} fps · {n} frames · {s} s · {mb} MB",+ uploading:"Reading video…", queued:"Queued", loading_model:"Loading the model (once per session)",+ step_plan:"plan", step_read:"decode", step_model:"model", step_depth:"depth", step_size:"size", step_wrote:"wrote", step_warn:"note", step_vram:"vram", step_quality:"quality", step_metrics:"metrics", step_npz:"npz", step_note:"note",+ done:"Done", chips:{frames:"frames",fps:"fps",size:"size",speed:"ms/frame",device:"device",model:"model saw",vram:"VRAM peak",file:"file"},+ download:"Download depth map", openFolder:"Saved in", next_title:"Next",+ next_seedance:"Upload this file to Seedance as a reference video and start the prompt with:",+ next_seedance_p:"参考@视频1的动作与运镜,顺序与视频保持一致。\n(then describe your people, wardrobe, set and look)",+ next_h3:"In MiniMax H3 attach it as <Video 1> (character sheet as <Picture 1>); define it in the prompt and say the grey look is not to be copied:",+ next_h3_p:"<Subject 3> is the fight choreography and camera movement shown in <Video 1>, a grey depth map in which near objects are white and far objects are black: (one sentence on what happens in the clip)\n<Subject 3>: attribute_transfer - every action, position, timing and camera move of <Video 1> is transferred onto <Subject 1>; its grey depth look is not transferred.",+ next_wan:"Connect it to WanVaceToVideo → control_video in ComfyUI.", next_none:"Hand it to any model that reads a depth video.",+ copy:"Copy prompt", copied:"Copied ✓", err_title:"That didn't work",+ "info.device":"This machine: {d}",+ }+};+let lang = (localStorage.getItem("reshot.lang") || (navigator.language || "zh").toLowerCase().startsWith("zh") ? "zh" : "en");+if (localStorage.getItem("reshot.lang")) lang = localStorage.getItem("reshot.lang");+const t = (k, vars) => { let s = (I18N[lang][k] ?? I18N.zh[k] ?? k); if (typeof s === "string" && vars) for (const [a,b] of Object.entries(vars)) s = s.replaceAll(`{${a}}`, b); return s; };+const $ = id => document.getElementById(id);++const state = { source:null, target:"seedance", quality:"fast", job:null, info:null, poll:null };++function applyLang() {+ document.documentElement.lang = lang;+ document.querySelectorAll("[data-i18n]").forEach(el => { el.textContent = t(el.dataset.i18n); });+ $("lang").textContent = lang === "zh" ? "EN" : "中文";+ document.title = lang === "zh" ? "ReShot · 猫斯卡" : "ReShot · Maosika";+ renderNotes(); renderMeta(); renderRunBtn();+ if (state.job && state.job.status === "done") renderResult(state.job);+}+$("lang").onclick = () => { lang = lang === "zh" ? "en" : "zh"; localStorage.setItem("reshot.lang", lang); applyLang(); };++function renderNotes() {+ $("targetNote").innerHTML = t("t_" + state.target);+ $("qualityNote").innerHTML = t("q_" + state.quality);+ const info = state.info, tg = info && info.targets[state.target];+ const w = $("lenWarn");+ if (state.source && tg && tg.max_seconds && state.source.seconds > tg.max_seconds + 0.05 && !$("maxFrames").value) {+ w.textContent = t("lenWarn", { s: state.source.seconds, t: ({seedance:"Seedance",h3:"MiniMax H3",wan:"Wan"})[state.target] || state.target, m: tg.max_seconds });+ w.hidden = false;+ } else w.hidden = true;+}+function seg(id, key) {+ $(id).querySelectorAll("button").forEach(b => b.onclick = () => {+ $(id).querySelectorAll("button").forEach(x => x.classList.toggle("on", x === b));+ state[key] = b.dataset.v;+ if (key === "target" && b.dataset.v === "h3" && !$("maxSide").value) $("maxSide").placeholder = "320";+ renderNotes();+ });+}+seg("target", "target"); seg("quality", "quality");+$("maxFrames").addEventListener("input", renderNotes);++// ---- source ----+const drop = $("drop"), file = $("file");+drop.onclick = () => file.click();+drop.onkeydown = e => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); file.click(); } };+["dragenter","dragover"].forEach(ev => drop.addEventListener(ev, e => { e.preventDefault(); drop.classList.add("is-over"); }));+["dragleave","drop"].forEach(ev => drop.addEventListener(ev, e => { e.preventDefault(); drop.classList.remove("is-over"); }));+drop.addEventListener("drop", e => { const f = e.dataTransfer.files && e.dataTransfer.files[0]; if (f) upload(f); });+file.onchange = () => { if (file.files[0]) upload(file.files[0]); file.value = ""; };+$("changeBtn").onclick = () => resetSource();+document.addEventListener("dragover", e => e.preventDefault());+document.addEventListener("drop", e => { e.preventDefault(); if (!drop.hidden) return; const f = e.dataTransfer.files && e.dataTransfer.files[0]; if (f) upload(f); });++async function upload(f) {+ hideErr(); clearResult();+ drop.querySelector(".big").textContent = t("uploading");+ const fd = new FormData(); fd.append("file", f, f.name);+ try {+ const r = await fetch("/api/upload", { method: "POST", body: fd });+ const j = await r.json();+ if (!r.ok) throw new Error(j.error || r.statusText);+ state.source = j;+ $("srcVideo").src = j.url; $("srcVideo").play().catch(()=>{});+ drop.hidden = true; $("players").hidden = false; $("meta").hidden = false; $("stageFoot").hidden = false;+ $("players").classList.toggle("portrait", j.height > j.width);+ renderMeta(); renderNotes(); renderRunBtn();+ } catch (e) { showErr(e.message); drop.querySelector(".big").textContent = t("drop.big"); }+}+function resetSource() {+ state.source = null; clearResult(); hideErr();+ $("srcVideo").removeAttribute("src"); $("srcVideo").load();+ drop.hidden = false; $("players").hidden = true; $("meta").hidden = true; $("stageFoot").hidden = true;+ drop.querySelector(".big").textContent = t("drop.big");+ renderNotes(); renderRunBtn();+}+function renderMeta() {+ const s = state.source; if (!s) return;+ $("meta").innerHTML = `<span class="name"><b>${esc(s.name)}</b></span><span>${t("meta_fmt",{w:s.width,h:s.height,fps:s.fps,n:s.frames,s:s.seconds,mb:(s.bytes/1048576).toFixed(1)})}</span>`;+}+function renderRunBtn() {+ const b = $("run"), running = state.job && (state.job.status === "queued" || state.job.status === "running");+ b.disabled = !state.source || !!running;+ b.textContent = running ? t("cta.running") : (state.job && state.job.status === "done" ? t("cta.again") : t("cta"));+}++// ---- run ----+$("run").onclick = async () => {+ if (!state.source) return;+ hideErr(); clearResult();+ const body = {+ source_id: state.source.id, target: state.target, quality: state.quality,+ max_side: +$("maxSide").value || 0, max_frames: +$("maxFrames").value || 0,+ clip_percent: +$("clip").value || 0, gamma: +$("gamma").value || 1, invert: $("invert").checked,+ };+ try {+ const r = await fetch("/api/jobs", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });+ const j = await r.json(); if (!r.ok) throw new Error(j.error || r.statusText);+ state.job = { id: j.id, status: "queued", steps: [] };+ renderRunBtn(); renderProg(state.job);+ clearInterval(state.poll); state.poll = setInterval(poll, 500); poll();+ } catch (e) { showErr(e.message); }+};+async function poll() {+ if (!state.job) return;+ const r = await fetch("/api/jobs/" + state.job.id); if (!r.ok) return;+ const j = await r.json(); state.job = j; renderProg(j);+ if (j.status === "done") { clearInterval(state.poll); renderResult(j); renderRunBtn(); }+ else if (j.status === "error") { clearInterval(state.poll); $("prog").hidden = true; showErr(j.error); renderRunBtn(); }+}+function renderProg(j) {+ const p = $("prog"); p.hidden = false;+ const rows = j.steps.map(s => `<div class="row${s.tag === "warn" ? " warn-row" : ""}"><span class="t">+${s.t}s</span><span class="k">${t("step_" + s.tag)}</span><span>${esc(s.message)}</span></div>`);+ const head = j.status === "queued" ? `<div class="row"><span class="spin"></span>${t("queued")}</div>`+ : j.status === "running" ? `<div class="row"><span class="spin"></span>${lang === "zh" ? "处理中" : "Working"} · ${j.elapsed}s</div>` : "";+ p.innerHTML = head + rows.join("");+}+function renderResult(j) {+ const r = j.result; if (!r) return;+ $("prog").hidden = true;+ $("outVideo").src = r.output_url + "?t=" + Date.now(); $("outPlayer").hidden = false; $("players").classList.add("two"); $("syncBtn").hidden = false;+ const c = t("chips"), chips = [+ [c.frames, r.frames], [c.fps, r.fps], [c.size, `${r.width}×${r.height}`], [c.speed, r.ms_per_frame], [c.device, `${r.device} ${r.precision}`],+ r.model_input_resolution ? [c.model, r.model_input_resolution.join("×")] : null,+ r.gpu_peak_reserved_bytes ? [c.vram, (r.gpu_peak_reserved_bytes / 2**30).toFixed(1) + " GB"] : null,+ r.output_bytes ? [c.file, (r.output_bytes / 1048576).toFixed(2) + " MB"] : null,+ ].filter(Boolean).map(([k, v]) => `<span class="chip">${k} <b>${v}</b></span>`).join("");+ const nextKey = "next_" + j.target, prompt = I18N[lang][nextKey + "_p"];+ $("result").innerHTML = `+ <h4>${t("done")} · ${j.elapsed}s</h4>+ <div class="chips">${chips}</div>+ <div class="btns"><a class="btn primary" href="${r.output_url}?download=1" download>${t("download")}</a></div>+ <div class="path">${t("openFolder")} ${esc(r.output)}</div>+ <div class="next"><b>${t("next_title")}</b> · ${t(nextKey)}${prompt ? `<code id="promptText">${esc(prompt)}</code><div class="btns" style="margin-top:8px"><button class="btn" id="copyBtn" type="button">${t("copy")}</button></div>` : ""}</div>`;+ $("result").hidden = false;+ const cb = $("copyBtn"); if (cb) cb.onclick = async () => { await navigator.clipboard.writeText(prompt); cb.textContent = t("copied"); setTimeout(() => cb.textContent = t("copy"), 1600); };+ $("srcVideo").currentTime = 0; $("outVideo").currentTime = 0;+}+$("syncBtn").onclick = () => { const a = $("srcVideo"), b = $("outVideo"); a.currentTime = 0; b.currentTime = 0; a.play(); b.play(); };+function clearResult() { $("result").hidden = true; $("outPlayer").hidden = true; $("players").classList.remove("two"); $("syncBtn").hidden = true; $("prog").hidden = true; clearInterval(state.poll); if (state.job && state.job.status === "done") state.job = null; }+function showErr(m) { $("err").textContent = `${t("err_title")}: ${m}`; $("err").hidden = false; }+function hideErr() { $("err").hidden = true; }+function esc(s) { return String(s).replace(/[&<>"]/g, c => ({"&":"&","<":"<",">":">",'"':"""})[c]); }++// ---- boot ----+fetch("/api/info").then(r => r.json()).then(i => { state.info = i; $("ver").textContent = `ReShot ${i.version}`; renderNotes(); }).catch(()=>{});+applyLang();+})();+</script>+</body>+</html>diff --git a/tests/test_web.py b/tests/test_web.pynew file mode 100644index 0000000..4bb3d5e--- /dev/null+++ b/tests/test_web.py@@ -0,0 +1,132 @@+"""The local web UI's JSON API, end to end on a random port with the fake backend:+upload → job → poll → download, plus the page itself and the error paths."""++import json+import os+import threading+import time+import urllib.request+from pathlib import Path++import cv2+import numpy as np+import pytest++from reshot.web import make_server++os.environ["RESHOT_FAKE_BACKEND"] = "1"+++def _clip(path: Path, frames=12, w=200, h=120, fps=30):+ vw = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))+ for i in range(frames):+ vw.write(np.full((h, w, 3), (i * 10) % 256, np.uint8))+ vw.release()+ return path+++def server(tmp_path):+ srv = make_server(tmp_path / "out", port=0, tmp_dir=tmp_path / "tmp")+ th = threading.Thread(target=srv.serve_forever, daemon=True)+ th.start()+ yield f"http://127.0.0.1:{srv.server_address[1]}", srv+ srv.shutdown()+ srv.server_close()+++def _multipart(field, filename, data, ctype="video/mp4"):+ boundary = "----reshottest"+ body = (+ (+ f'--{boundary}\r\nContent-Disposition: form-data; name="{field}"; filename="{filename}"\r\n'+ f"Content-Type: {ctype}\r\n\r\n"+ ).encode()+ + data+ + f"\r\n--{boundary}--\r\n".encode()+ )+ return body, f"multipart/form-data; boundary={boundary}"+++def _post(url, body, ctype):+ req = urllib.request.Request(url, data=body, headers={"Content-Type": ctype}, method="POST")+ try:+ with urllib.request.urlopen(req) as r:+ return r.status, json.loads(r.read())+ except urllib.error.HTTPError as e:+ return e.code, json.loads(e.read())+++def _get(url):+ with urllib.request.urlopen(url) as r:+ return r.status, r.read(), dict(r.headers)+++def test_page_and_info(server):+ base, _ = server+ st, body, _ = _get(base + "/")+ assert st == 200 and b"ReShot" in body and b"maosika.com" in body+ st, body, _ = _get(base + "/api/info")+ info = json.loads(body)+ assert info["targets"]["seedance"]["fps"] == 24 and info["out_dir"].endswith("out")+++def test_upload_job_download(server, tmp_path):+ base, _ = server+ clip = _clip(tmp_path / "ref clip.mp4", frames=30)+ body, ctype = _multipart("file", "ref clip.mp4", clip.read_bytes())+ st, src = _post(base + "/api/upload", body, ctype)+ assert st == 200 and src["width"] == 200 and src["frames"] == 30 and src["seconds"] == 1.0+ st, raw, _ = _get(base + src["url"])+ assert st == 200 and len(raw) == clip.stat().st_size++ st, j = _post(+ base + "/api/jobs",+ json.dumps({"source_id": src["id"], "target": "h3", "max_side": 160}).encode(),+ "application/json",+ )+ assert st == 200+ for _ in range(100):+ _, body, _ = _get(base + f"/api/jobs/{j['id']}")+ job = json.loads(body)+ if job["status"] in ("done", "error"):+ break+ time.sleep(0.1)+ assert job["status"] == "done", job+ assert job["result"]["fps"] == 24 and job["result"]["width"] % 32 == 0 and job["result"]["width"] <= 160+ assert any(s["tag"] == "wrote" for s in job["steps"])+ out = Path(job["result"]["output"])+ assert out.exists() and out.parent == tmp_path / "out" and out.name.startswith("ref clip_depth_h3")+ st, raw, hdr = _get(base + job["result"]["output_url"] + "?download=1")+ assert st == 200 and len(raw) == out.stat().st_size and "attachment" in hdr["Content-Disposition"]+ # a second run must not overwrite the first+ st, j2 = _post(+ base + "/api/jobs", json.dumps({"source_id": src["id"], "target": "h3"}).encode(), "application/json"+ )+ for _ in range(100):+ _, body, _ = _get(base + f"/api/jobs/{j2['id']}")+ if json.loads(body)["status"] in ("done", "error"):+ break+ time.sleep(0.1)+ assert Path(json.loads(body)["result"]["output"]).name == "ref clip_depth_h3_2.mp4"+++def test_range_request_for_video_seeking(server, tmp_path):+ base, _ = server+ clip = _clip(tmp_path / "c.mp4")+ body, ctype = _multipart("file", "c.mp4", clip.read_bytes())+ _, src = _post(base + "/api/upload", body, ctype)+ req = urllib.request.Request(base + src["url"], headers={"Range": "bytes=0-99"})+ with urllib.request.urlopen(req) as r:+ assert r.status == 206 and len(r.read()) == 100 and r.headers["Content-Range"].startswith("bytes 0-99/")+++def test_bad_inputs(server):+ base, _ = server+ body, ctype = _multipart("file", "x.mp4", b"not a video")+ st, j = _post(base + "/api/upload", body, ctype)+ assert st == 400 and "error" in j+ st, j = _post(base + "/api/jobs", json.dumps({"source_id": "nope"}).encode(), "application/json")+ assert st == 400+ st, j = _post(base + "/api/jobs", b"{", "application/json")+ assert st == 400