Skip to content

Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.

fix(out-dir): each output is judged at the path the run writes, a link already there followed — correction-loop passes every entry it writes (each attempt's folder and files, each candidate, best-candidate/, the report) and every file, folder and link its best candidate's copy reads to runio.refuse_overlap; video-extend and video-edit add the staged <out>.part and --report; video-loop-compare, video-loop-repair, video-source-manifest and shadow call it in place of their resolve() comparisons; runio looks each identity up once per call

Soohong Kim1c8a09bc3882
diff --git a/sprite_gen/effects/shadow.py b/sprite_gen/effects/shadow.py
index 9d80b24..91d2cff 100644
--- a/sprite_gen/effects/shadow.py
+++ b/sprite_gen/effects/shadow.py
@@ -15,6 +15,7 @@ from PIL import Image, ImageFilter
from sprite_gen.spec.runio import (
acquire_run_dir_lock,
atomic_write_set,
+ refuse_overlap,
release_run_dir_lock,
)
from sprite_gen.util.hexcolor import parse_hex
@@ -168,10 +169,13 @@ def _png_bytes(image: Image.Image) -> bytes:
def _validate_targets(targets, sources):
- protected = {Path(path).resolve() for path in sources}
+ source, *read = sources
+ try: # no source is a file the run writes (`runio.refuse_overlap`)
+ refuse_overlap({"--source": source, **{f"{path} (read for --source)": path for path in read}},
+ {f"{target.name} in --out-dir": target for target in targets})
+ except SystemExit as overlap:
+ raise ValueError(f"shadow output would overwrite source: {overlap}") from None
for target in targets:
- if target.resolve() in protected:
- raise ValueError(f"shadow output would overwrite source: {target}")
if target.is_symlink() or (target.exists() and not target.is_file()):
raise ValueError(f"shadow output must be a regular file: {target}")
diff --git a/sprite_gen/gen/video.py b/sprite_gen/gen/video.py
index 6b501fd..78e2073 100644
--- a/sprite_gen/gen/video.py
+++ b/sprite_gen/gen/video.py
@@ -493,6 +493,11 @@ def _ask_again(request_id: str, out: Path) -> str:
"nothing was written")
+def _staged(out: Path) -> Path:
+ """Where a result is downloaded before it is published over `out`: `<out>.part` beside it."""
+ return out.with_name(out.name + ".part")
+
+
def _submit_poll_publish(
*,
verb: str,
@@ -713,7 +718,7 @@ def _poll_publish(
elapsed = time.monotonic() - started
out.parent.mkdir(parents=True, exist_ok=True)
- tmp = out.with_name(out.name + ".part")
+ tmp = _staged(out)
tmp.write_bytes(data)
if accept is not None:
try:
@@ -806,6 +811,12 @@ def generate_video(
)
+def _published_at(out: Path) -> dict[str, Path]:
+ """What publishing a result over `--out` writes: the download staged beside it, then `--out` itself."""
+ out = out.expanduser().resolve()
+ return {"--out": out, f"{_staged(out).name} beside --out": _staged(out)}
+
+
def _validate_extend(request: ExtendRequest, *, probe: Callable[[Path], float]) -> float:
if not request.prompt.strip():
raise SystemExit("video-extend: empty prompt; pass --prompt or --prompt-file")
@@ -817,8 +828,9 @@ def _validate_extend(request: ExtendRequest, *, probe: Callable[[Path], float])
)
clip = request.video.expanduser().resolve()
_require_mp4_clip(clip, verb="video-extend")
- # The result is published over `--out`: the clip it continues is never that file (it would be replaced).
- refuse_overlap({"--video": request.video}, {"--out": request.out.expanduser().resolve()}, verb="video-extend")
+ # The result is downloaded to `<out>.part` and published over `--out`: the clip it continues is neither file (it would
+ # be written over or replaced), a link already at either followed.
+ refuse_overlap({"--video": request.video}, _published_at(request.out), verb="video-extend")
seconds = probe(clip)
low, high = EXTEND_INPUT_SECONDS
if not (low <= seconds <= high + EXTEND_INPUT_SLACK_SECONDS):
@@ -888,8 +900,9 @@ def _validate_edit(request: EditRequest, *, probe: Callable[[Path], float]) -> f
raise SystemExit(f"video-edit: only the classic {CLASSIC_MODEL} supports editing (the API answers 400 for {request.model})")
clip = request.video.expanduser().resolve()
_require_mp4_clip(clip, verb="video-edit")
- # The result is published over `--out`: the clip it edits is never that file (it would be replaced).
- refuse_overlap({"--video": request.video}, {"--out": request.out.expanduser().resolve()}, verb="video-edit")
+ # The result is downloaded to `<out>.part` and published over `--out`: the clip it edits is neither file (it would be
+ # written over or replaced), a link already at either followed.
+ refuse_overlap({"--video": request.video}, _published_at(request.out), verb="video-edit")
seconds = probe(clip)
if seconds > EDIT_INPUT_MAX_SECONDS:
raise SystemExit(
@@ -1038,8 +1051,12 @@ def _read_prompt(args: argparse.Namespace) -> str:
return (prompt or "").strip()
-def _publish_report(args: argparse.Namespace, make: Callable[[], VideoResult]) -> int:
+def _publish_report(args: argparse.Namespace, make: Callable[[], VideoResult], *, reads: dict[str, Path] | None = None,
+ verb: str | None = None) -> int:
report_path = Path(args.report).expanduser().resolve() if args.report else None
+ if reads and report_path is not None:
+ # The report is written once the result is made: what the run reads is never that file.
+ refuse_overlap(reads, {"--report": report_path}, verb=verb)
try:
result = make()
except GenerationUnfinished as unfinished:
@@ -1075,12 +1092,12 @@ def _run(args: argparse.Namespace) -> int:
def _run_extend(args: argparse.Namespace) -> int:
request = ExtendRequest(video=args.video, prompt=_read_prompt(args), out=args.out, duration=args.duration)
- return _publish_report(args, lambda: extend_video(request))
+ return _publish_report(args, lambda: extend_video(request), reads={"--video": request.video}, verb="video-extend")
def _run_edit(args: argparse.Namespace) -> int:
request = EditRequest(video=args.video, prompt=_read_prompt(args), out=args.out)
- return _publish_report(args, lambda: edit_video(request))
+ return _publish_report(args, lambda: edit_video(request), reads={"--video": request.video}, verb="video-edit")
def _run_resume(args: argparse.Namespace) -> int:
diff --git a/sprite_gen/qa/correction_loop.py b/sprite_gen/qa/correction_loop.py
index d683f26..ba34c04 100644
--- a/sprite_gen/qa/correction_loop.py
+++ b/sprite_gen/qa/correction_loop.py
@@ -19,6 +19,9 @@ from sprite_gen.qa import score as score_mod
from sprite_gen.spec.runio import LOCK_FILENAME, atomic_write_text, refuse_overlap, relative_posix, same_folder
from sprite_gen.util.console import utf8_streams
+BEST_CANDIDATE = "best-candidate"
+REPORT = "correction-loop.report.json"
+
def _build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description=__doc__)
@@ -42,10 +45,10 @@ def _skipped_by_copy(out_dir: Path) -> Callable[[Path], bool]:
or (not path.is_symlink() and same_folder(path, out_dir)))
-def _links_copied(source: Path, skipped: Callable[[Path], bool]) -> list[Path]:
- """Every link in `source` the copy follows (`shutil.copytree` reads a linked file's bytes and a linked folder's
- content), the linked folders walked too, as found there: what the copy reads beside the run dir's own entries."""
- links: list[Path] = []
+def _copied(source: Path, skipped: Callable[[Path], bool]) -> list[Path]:
+ """Every entry the copy of `source` reads, as found there: each file, folder and link (`shutil.copytree` reads a
+ linked file's bytes and a linked folder's content), the linked folders walked too."""
+ found: list[Path] = []
todo, walked = [source], set()
while todo:
with os.scandir(todo.pop()) as entries:
@@ -53,14 +56,39 @@ def _links_copied(source: Path, skipped: Callable[[Path], bool]) -> list[Path]:
path = Path(entry.path)
if skipped(path):
continue
- if entry.is_symlink():
- links.append(path)
+ found.append(path)
if entry.is_dir():
folder = entry.stat()
if (folder.st_dev, folder.st_ino) not in walked: # a folder linked twice, or a link loop, once
walked.add((folder.st_dev, folder.st_ino))
todo.append(path)
- return links
+ return sorted(found)
+
+
+def _attempt(out_dir: Path, attempt: int) -> dict[str, Path]:
+ """What attempt `attempt` writes in the out dir: its folder and, in it, the inspection, the score, the hints and the
+ provider's log (written when a provider runs after the attempt)."""
+ folder = out_dir / f"attempt-{attempt}"
+ return {"folder": folder, "inspect": folder / "inspect.json", "score": folder / "score.json",
+ "hints": folder / "correction-hints.txt", "log": folder / "provider.log"}
+
+
+def _candidate(out_dir: Path, attempt: int) -> Path:
+ """Where the provider makes the run dir attempt `attempt` inspects."""
+ return out_dir / f"candidate-{attempt}"
+
+
+def _written(out_dir: Path, *, passes: int, preserve_best: bool) -> list[Path]:
+ """Every entry the loop writes in the out dir, at the path it writes: each attempt's folder and its files, each
+ candidate the provider makes (a loop of more than one pass runs a provider), the best candidate's copy and the
+ report."""
+ written: list[Path] = []
+ for attempt in range(1, passes + 1):
+ files = _attempt(out_dir, attempt)
+ written += [path for key, path in files.items() if key != "log" or attempt < passes]
+ if attempt > 1:
+ written.append(_candidate(out_dir, attempt))
+ return [*written, *([out_dir / BEST_CANDIDATE] if preserve_best else []), out_dir / REPORT]
def _copy_run_dir(source: Path, target: Path, skipped: Callable[[Path], bool]) -> None:
@@ -97,32 +125,35 @@ def run_loop(
given = run_dir
run_dir = run_dir.expanduser().resolve()
out_dir = (out_dir or (run_dir / "correction-loop")).expanduser().resolve()
- # The loop never writes over, moves or deletes the run it reads: the run dir, and every link its copy follows
- # (each with every link or folder its path looks up), is never the out dir or inside it. The out dir may lie in
- # the run dir (the default does): it is added to it, and the copy leaves it out.
+ # The loop never writes over, moves or deletes the run it reads: the run dir, and every entry its best candidate's
+ # copy reads there (each with every link or folder its path looks up), is never anything the loop writes — the out
+ # dir and each entry the loop writes in it, at the path it writes, a link already there followed — nor inside one.
+ # The out dir may lie in the run dir (the default does): it is added to it, and the copy leaves it out.
skipped = _skipped_by_copy(out_dir)
- found = _links_copied(run_dir, skipped) if run_dir.is_dir() else []
+ found = _copied(run_dir, skipped) if run_dir.is_dir() else []
+ written = _written(out_dir, passes=max_passes if provider_command and not dry_run else 1, preserve_best=preserve_best)
refuse_overlap({"--run-dir": given, **{f"{relative_posix(p, run_dir)} in --run-dir": p for p in found}},
- {"--out-dir": out_dir}, replaces="the loop writes its attempts and best candidate there")
+ {"--out-dir": out_dir, **{f"{relative_posix(p, out_dir)} in --out-dir": p for p in written}},
+ replaces="the loop writes its attempts and best candidate there")
out_dir.mkdir(parents=True, exist_ok=True)
attempts: list[dict[str, Any]] = []
best: dict[str, Any] | None = None
current = run_dir
for attempt in range(1, max_passes + 1):
- attempt_dir = out_dir / f"attempt-{attempt}"
- attempt_dir.mkdir(parents=True, exist_ok=True)
+ files = _attempt(out_dir, attempt)
+ files["folder"].mkdir(parents=True, exist_ok=True)
inspect_report = inspect_mod.inspect_run(current, states=states)
scored = score_mod.score_inspection(inspect_report)
- atomic_write_text(attempt_dir / "inspect.json", json.dumps(inspect_report, ensure_ascii=False, indent=2) + "\n")
- atomic_write_text(attempt_dir / "score.json", json.dumps(scored, ensure_ascii=False, indent=2) + "\n")
- _write_hints(attempt_dir / "correction-hints.txt", scored["hints"])
+ atomic_write_text(files["inspect"], json.dumps(inspect_report, ensure_ascii=False, indent=2) + "\n")
+ atomic_write_text(files["score"], json.dumps(scored, ensure_ascii=False, indent=2) + "\n")
+ _write_hints(files["hints"], scored["hints"])
record = {
"attempt": attempt,
"run_dir": str(current),
- "inspect_report": str(attempt_dir / "inspect.json"),
- "score_report": str(attempt_dir / "score.json"),
- "hint_file": str(attempt_dir / "correction-hints.txt"),
+ "inspect_report": str(files["inspect"]),
+ "score_report": str(files["score"]),
+ "hint_file": str(files["hints"]),
"ok": scored["ok"],
"overall_score": scored["overall_score"],
"candidate_rank": scored["candidate_rank"],
@@ -141,8 +172,8 @@ def run_loop(
break
if not provider_command:
raise SystemExit("correction loop needs --provider-command, or use --dry-run for an inspect/score/hint demo")
- next_run_dir = out_dir / f"candidate-{attempt + 1}"
- prompt_file = attempt_dir / "correction-hints.txt"
+ next_run_dir = _candidate(out_dir, attempt + 1)
+ prompt_file = files["hints"]
# The template is split first and each argument filled in after, so a substituted
# path is never re-read as shell syntax: POSIX splitting would drop the backslashes
# of a Windows path and break a path that holds a space or a quote.
@@ -151,7 +182,7 @@ def run_loop(
command = shlex.join(argv)
completed = subprocess.run(argv, capture_output=True, text=True)
atomic_write_text(
- attempt_dir / "provider.log",
+ files["log"],
completed.stdout + ("\n--- stderr ---\n" + completed.stderr if completed.stderr else ""),
)
if completed.returncode != 0:
@@ -163,7 +194,7 @@ def run_loop(
assert best is not None
preserved_best = None
if preserve_best:
- preserved = out_dir / "best-candidate"
+ preserved = out_dir / BEST_CANDIDATE
_copy_run_dir(Path(best["run_dir"]), preserved, skipped)
preserved_best = str(preserved)
result = {
@@ -176,7 +207,7 @@ def run_loop(
"best_candidate": best,
"preserved_best": preserved_best,
}
- atomic_write_text(out_dir / "correction-loop.report.json", json.dumps(result, ensure_ascii=False, indent=2) + "\n")
+ atomic_write_text(out_dir / REPORT, json.dumps(result, ensure_ascii=False, indent=2) + "\n")
return result
diff --git a/sprite_gen/qa/motion.py b/sprite_gen/qa/motion.py
index 580b693..f38e615 100644
--- a/sprite_gen/qa/motion.py
+++ b/sprite_gen/qa/motion.py
@@ -414,7 +414,7 @@ def add_arguments(parser):
def _output_path(out, source, sequence):
path = Path(out).expanduser().resolve()
protected = {Path(source).expanduser().resolve(), *(Path(p).resolve() for p in sequence.source_files)}
- if path in protected or any(same_folder(path, p) for p in protected):
+ if any(same_folder(path, p) for p in protected):
raise ValueError("motion report must not overwrite an asset source file")
if path.name == ".sprite-gen.lock" or path.name.endswith(".sg-rwlock"):
raise ValueError("motion report must not overwrite an output lock")
diff --git a/sprite_gen/scene/inspect_scene.py b/sprite_gen/scene/inspect_scene.py
index 16e83a1..e5d68c7 100644
--- a/sprite_gen/scene/inspect_scene.py
+++ b/sprite_gen/scene/inspect_scene.py
@@ -111,7 +111,7 @@ def output_path(out, scene: Scene) -> Path:
if path.name == LOCK_FILENAME or path.name.endswith(RWLOCK_SUFFIX):
raise ValueError("inspection output must not use a reserved lock name")
protected = [Path(p) for p in scene.source_fingerprints]
- if path in protected or any(same_folder(path, p) for p in protected):
+ if any(same_folder(path, p) for p in protected):
raise ValueError("inspection output cannot overwrite scene inputs")
if path.exists() and not path.is_file():
raise ValueError("inspection output must be a file")
diff --git a/sprite_gen/spec/runio.py b/sprite_gen/spec/runio.py
index 2ba9c81..8fbb03a 100644
--- a/sprite_gen/spec/runio.py
+++ b/sprite_gen/spec/runio.py
@@ -256,15 +256,30 @@ def relative_posix(path: PurePath, start: PurePath) -> str:
return path.relative_to(start).as_posix()
+def _identity(path: Path) -> tuple[int, int] | None:
+ """`path` 를 열 때 닿는 항목의 장치·inode — 링크는 따라가고, 아직 없으면(`Path.exists` 가 없다고 하면) None."""
+ if not path.exists():
+ return None
+ found = path.stat()
+ return found.st_dev, found.st_ino
+
+
+def _ancestors(path: Path, identity: Callable[[Path], tuple[int, int] | None] = _identity) -> set[tuple[int, int]]:
+ """`path` 의 조상(`path.parents`) 가운데 있는 것들의 장치·inode."""
+ return {found for parent in path.parents if (found := identity(parent)) is not None}
+
+
def same_folder(a: Path, b: Path) -> bool:
"""같은 폴더(또는 파일)인가 — 장치·inode 로 본다. 링크로 돌아 들어와도, 대소문자를 가리지 않는 볼륨에서 철자만
달라도 같다. 둘 중 하나가 아직 없으면 같지 않다."""
- return a.exists() and b.exists() and a.samefile(b)
+ found = _identity(a)
+ return found is not None and found == _identity(b)
def inside_folder(path: Path, folder: Path) -> bool:
"""`path` 가 `folder` 안에 드는가 — 조상 가운데 `folder` 와 같은 폴더가 있다. `path` 는 아직 없어도 된다."""
- return any(same_folder(parent, folder) for parent in path.parents)
+ found = _identity(folder)
+ return found is not None and found in _ancestors(path)
_MAX_LINKS = 40 # 이보다 많은 링크를 지나면 고리다 (리눅스 커널의 한도, macOS 는 32)
@@ -334,27 +349,41 @@ def refuse_overlap(inputs: Mapping[str, Path | None], outputs: Mapping[str, Path
경로(None 은 건너뜀), `outputs` 는 이름 → 이 실행이 갈아 끼우거나 지우는 항목(파일이나 폴더 — 출력이 더해지기만
하는 폴더는 넣지 않는다). 입력마다 `follow_path` 로 따라가, 닿은 실경로가 출력과 같거나(덮어씀), 출력 안에
들거나(지움), 찾아본 항목 가운데 하나가 출력 안에 들면(그 항목이 지워져 길이 끊기거나 링크 너머가 지워짐)
- 거절한다. `holds` 에 이름이 든 출력은 입력 안에 들어도 거절한다(입력 안에 씀). 실경로와 장치·inode 로 보므로
- 링크와 대소문자를 가리지 않는 볼륨의 다른 철자도 같은 항목이다. 한 번의 호출 안에서 이미 본 항목은 다시 재지
- 않는다(찾은 입력이 많아도 공통 조상은 한 번). 따라갈 수 없는 입력(링크 고리)은 이름을 대며 거절한다."""
+ 거절한다. `holds` 에 이름이 든 출력은 입력 안에 들어도 거절한다(입력 안에 씀). 출력은 받은 이름 그대로 연다 —
+ 그 자리에 이미 있는 링크는 따라간 곳이 출력이다. 실경로와 장치·inode 로 보므로 링크와 대소문자를 가리지 않는
+ 볼륨의 다른 철자도 같은 항목이다(`same_folder`, `inside_folder` 의 비교). 한 번의 호출 안에서 이미 본 항목은
+ 다시 재지 않고, 항목마다 장치·inode 도 한 번만 찾는다(찾은 입력이 많아도 공통 조상과 출력은 한 번). 따라갈 수
+ 없는 입력(링크 고리)은 이름을 대며 거절한다."""
say = f"{verb}: " if verb else ""
looked_at: set[Path] = set()
+ known: dict[Path, tuple[int, int] | None] = {}
+
+ def identity(entry: Path) -> tuple[int, int] | None: # nothing is made or moved before the call ends
+ if entry not in known:
+ known[entry] = _identity(entry)
+ return known[entry]
+
+ places = {out: identity(place) for out, place in outputs.items()}
+ held = {out: _ancestors(outputs[out], identity) for out in holds if out in outputs}
for flag, given in inputs.items():
if given is None:
continue
looked, path = follow_input(flag, Path(given).expanduser(), verb=verb)
fresh = [entry for entry in looked if entry not in looked_at]
looked_at.update(fresh)
+ found, above = identity(path), _ancestors(path, identity)
+ passed = [(entry, _ancestors(entry, identity)) for entry in fresh]
for out, place in outputs.items():
- if same_folder(path, place):
+ at = places[out]
+ if at is not None and at == found:
kind = "folder" if path.is_dir() else "file"
raise SystemExit(f"{say}{flag} and {out} are the same {kind}: {path} (an input is never overwritten)")
- if inside_folder(path, place):
+ if at is not None and at in above:
raise SystemExit(f"{say}{flag} lies inside {out}: {path} ({replaces}, never an input)")
- through = next((entry for entry in fresh if inside_folder(entry, place)), None)
+ through = next((entry for entry, over in passed if at is not None and at in over), None)
if through is not None:
raise SystemExit(f"{say}{flag} goes through {through}, inside {out} ({replaces}, never an input)")
- if out in holds and inside_folder(place, path):
+ if out in held and found is not None and found in held[out]:
raise SystemExit(f"{say}{out} lies inside {flag}: {place} (a run is never written into its input)")
diff --git a/sprite_gen/video/compare.py b/sprite_gen/video/compare.py
index 139bf3c..5e4f0dc 100644
--- a/sprite_gen/video/compare.py
+++ b/sprite_gen/video/compare.py
@@ -20,7 +20,7 @@ from typing import Any
from PIL import Image
from sprite_gen._deps import np
-from sprite_gen.spec.runio import atomic_write_text
+from sprite_gen.spec.runio import atomic_write_text, refuse_overlap
from sprite_gen.video import evidence, repair, rife, sway
from sprite_gen.video import loop as loop_mod
from sprite_gen.video.interpolation_quality import faults
@@ -282,7 +282,7 @@ def run(**kwargs: Any) -> int:
from sprite_gen.video import restoration, source
origin = {k: kwargs.get(f"origin_{k}") for k in restoration.ARTIFACTS}
restoration_mode = any(kwargs.get(k) is not None for k in (*source.INPUTS, "repair_evidence")) or any(origin.values())
- protected = [p for row in paths.values() for p in row.values()]
+ protected: dict[str, Path] = {}
if restoration_mode:
inputs = source.input_paths(kwargs)
# The origin is never guessed from the current baseline, not even on a first request.
@@ -293,12 +293,14 @@ def run(**kwargs: Any) -> int:
paths[side].update({k: Path(kwargs[f"{side}_{k}"]) for k in ("gif", "webp")})
paths["origin"] = {k: Path(p) for k, p in origin.items()}
evidence_path = Path(kwargs["repair_evidence"])
- protected += [*inputs.values(), evidence_path, *inputs["source_frames_dir"].glob("*.png")]
- protected += [p for row in paths.values() for p in row.values()]
+ protected.update({"--" + k.replace("_", "-"): p for k, p in inputs.items()})
+ protected.update({f"{p.name} in --source-frames-dir": p for p in inputs["source_frames_dir"].glob("*.png")})
+ protected["--repair-evidence"] = evidence_path
elif any(kwargs.get(f"{s}_{k}") for s in paths for k in ("gif", "webp")):
raise ValueError("playback comparison requires source inputs and repair evidence")
- if any(output.resolve() == p.resolve() for p in protected):
- raise ValueError("comparison report cannot overwrite an input artifact")
+ # The report is written once every artifact is read: no input is that file (`runio.refuse_overlap`).
+ refuse_overlap({**{f"--{side}-{k}": p for side, row in paths.items() for k, p in row.items()}, **protected},
+ {"--report": output}, verb="video-loop-compare")
if restoration_mode:
a, ap = restoration.read_loop(paths["baseline"])
b, bp = restoration.read_loop(paths["candidate"])
diff --git a/sprite_gen/video/restoration.py b/sprite_gen/video/restoration.py
index 9c2572d..61e7b67 100644
--- a/sprite_gen/video/restoration.py
+++ b/sprite_gen/video/restoration.py
@@ -37,7 +37,7 @@ from sprite_gen._deps import np
from sprite_gen.frames.cutout import KEY_TARGETS
from sprite_gen.frames.decontam import _cap_key_hue
from sprite_gen.frames.extract import _key_channel_split, _key_excess_field, _SPILL_FULL_MIN_TINT
-from sprite_gen.spec.runio import atomic_write_text
+from sprite_gen.spec.runio import atomic_write_text, refuse_overlap
from sprite_gen.util import resample
from sprite_gen.video import evidence, playback, repair, rife, source
from sprite_gen.video.compare import KIND as COMPARISON_KIND, Loop
@@ -608,10 +608,14 @@ def run(**kwargs: Any) -> int:
output = Path(kwargs["report"])
out = Path(kwargs["out_dir"])
name = kwargs.get("name", "loop")
- protected = [*paths.values(), *origin.values(), *inputs.values(), *inputs["source_frames_dir"].glob("*.png")]
- protected += [out / (name + ext) for ext in (".strip.png", ".strip.json", ".loop.json", ".gif", ".webp")]
- if output.resolve() in {p.resolve() for p in protected}:
- raise ValueError("repair report cannot overwrite an input")
+ # The report is written once the candidate is: no input is that file (`runio.refuse_overlap`), nor is a file of
+ # the candidate (two of the run's own outputs, new paths both — the candidate folder must be new).
+ refuse_overlap({**{f"--baseline-{k}": p for k, p in paths.items()}, **{f"--origin-{k}": p for k, p in origin.items()},
+ **{"--" + k.replace("_", "-"): p for k, p in inputs.items()},
+ **{f"{p.name} in --source-frames-dir": p for p in inputs["source_frames_dir"].glob("*.png")}},
+ {"--report": output}, verb="video-loop-repair")
+ if output.resolve() in {(out / (name + ext)).resolve() for ext in (".strip.png", ".strip.json", ".loop.json", ".gif", ".webp")}:
+ raise ValueError("repair report cannot overwrite the candidate it writes")
payload = restore(paths, origin, source.Source.read(**inputs), out_dir=out,
name=name, proposal_index=kwargs.get("proposal_index", 1))
output.parent.mkdir(parents=True, exist_ok=True)
diff --git a/sprite_gen/video/source.py b/sprite_gen/video/source.py
index 42aaa0a..c28fdec 100644
--- a/sprite_gen/video/source.py
+++ b/sprite_gen/video/source.py
@@ -264,13 +264,14 @@ def add_arguments(parser: Any) -> None:
def run(**kwargs: Any) -> int:
"""Receipt existing keyed output without repeating extraction; not a source attestation."""
- from sprite_gen.spec.runio import atomic_write_text
+ from sprite_gen.spec.runio import atomic_write_text, refuse_overlap
clip, canvas, report, directory, out = (Path(kwargs[k]) for k in
("clip", "canvas", "frames_report", "frames_dir", "out"))
files = sorted(directory.glob("*.png"))
try:
- if out.resolve() in {p.resolve() for p in (clip, canvas, report, *files)}:
- raise ValueError("manifest cannot overwrite a source input")
+ # The manifest is written once every input is read: no input is that file (`runio.refuse_overlap`).
+ refuse_overlap({"--clip": clip, "--canvas": canvas, "--frames-report": report, "--frames-dir": directory,
+ **{f"{f.name} in --frames-dir": f for f in files}}, {"--out": out}, verb="video-source-manifest")
record = manifest(clip=clip, canvas=canvas, frames_report=report, files=files,
timestamps=timestamps(clip, json.loads(report.read_bytes())["stream_index"]))
out.parent.mkdir(parents=True, exist_ok=True)
diff --git a/tests/video/test_loop_compare.py b/tests/video/test_loop_compare.py
index b666761..e2847eb 100644
--- a/tests/video/test_loop_compare.py
+++ b/tests/video/test_loop_compare.py
@@ -159,7 +159,7 @@ def test_cli_writes_unknown_successfully_and_refuses_corrupt_input_or_overwrite(
r = json.loads(output.read_text())
assert r["kind"] == compare.KIND and r["verdict"] == "unknown"
assert json.loads(capsys.readouterr().out) == r
- with pytest.raises(SystemExit, match="cannot overwrite"):
+ with pytest.raises(SystemExit, match="--baseline-meta and --report are the same file"):
main(args + ["--report", str(a["meta"])])
_edit(b["meta"], lambda d: d.update(w=1))
with pytest.raises(SystemExit, match="size agrees"):
diff --git a/tests/video/test_source_restoration.py b/tests/video/test_source_restoration.py
index aea5b45..30f67a6 100644
--- a/tests/video/test_source_restoration.py
+++ b/tests/video/test_source_restoration.py
@@ -601,7 +601,7 @@ def test_overwriting_any_input_is_refused(case,tmp_path):
paths,_,_=case
baseline,origin,src=cli_args(case)
old=paths['meta'].read_bytes()
- with pytest.raises(SystemExit,match='cannot overwrite'):
+ with pytest.raises(SystemExit,match='--baseline-meta and --report are the same file'):
main(['video-loop-repair',*baseline,*origin,*src,'--out-dir',str(tmp_path/'unsafe'),'--report',str(paths['meta'])])
assert paths['meta'].read_bytes()==old and not (tmp_path/'unsafe').exists()