File size: 3,174 Bytes
c7a38a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Re-run an "Enhance with AI" dump locally: coverage repair, lighting and compositing.

    VISUALIZER_CONFIG=... python scripts/enhance_replay.py <run_dir> [--reuse-answer] [--out <dir>]

Reads the dumped manifest and layer PNGs and the job (photo, bundle, class map) from
this renderer's data directory, so repair and lighting can be tuned without the browser.
With --reuse-answer the dumped AI answer is used instead of a new AI call (no cost).
Nothing is charged either way. Writes a new dump (and its comparison sheet) to --out.
"""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path
from unittest import mock

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from PIL import Image  # noqa: E402

from scripts.enhance_compare_sheet import build_sheet  # noqa: E402
from services.enhance import debug_dump  # noqa: E402
from services.enhance.job_context import load_job_context  # noqa: E402
from services.enhance.pipeline import finish, prepare  # noqa: E402
from services.enhance.validate import parse_layers  # noqa: E402


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument("run", type=Path)
    parser.add_argument("--reuse-answer", action="store_true")
    parser.add_argument("--out", type=Path)
    args = parser.parse_args()

    manifest = json.loads((args.run / "manifest.json").read_text())
    files = {}
    for layer in manifest["layers"]:
        for kind in ("layer", "coverage", "planes"):
            files[f"{kind}.{layer['id']}"] = (args.run / f"{kind}.{layer['id']}.png").read_bytes()
    context = load_job_context(manifest["jobId"])
    layers = parse_layers(manifest, files, context)
    prepared = prepare(context, layers)
    out = args.out or args.run.with_name(args.run.name + "-replay")
    out.mkdir(parents=True, exist_ok=True)
    debug_dump.dump_prepared(out, prepared, manifest)

    timings: dict[str, int] = {}
    if args.reuse_answer:
        answer_png = args.run / "ai_answer.png"

        def reuse(preview, original, surfaces, outside, timings):
            with Image.open(answer_png) as opened:
                import numpy as np

                return np.asarray(opened.convert("RGB")), 0

        with mock.patch("services.enhance.pipeline.relight_reference", side_effect=reuse):
            result = finish(prepared, timings)
    else:
        result = finish(prepared, timings)
    summary = {
        "replayOf": args.run.name,
        "lighting": [{"id": item.layer.id, "status": light.status, **light.stats} for item, light in zip(prepared.refined, result.lighting)],
        "coverage": [{"id": item.layer.id, "repairedPx": int(item.repaired.sum()), "trimmedPx": int(item.trimmed.sum()),
                      "restoredPx": int(restored.sum()), "restoredRegions": regions}
                     for item, restored, regions in zip(prepared.refined, result.restored, result.restored_regions)],
        "timings": timings,
    }
    debug_dump.dump_result(out, result, summary)
    print(json.dumps(build_sheet(out, out / "sheet.png"), indent=2))


if __name__ == "__main__":
    main()