File size: 7,127 Bytes
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ad60ce
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3460f
f877698
 
 
 
 
 
 
 
 
 
 
2ad60ce
f877698
 
 
 
 
2ad60ce
 
 
f877698
2ad60ce
f877698
 
 
 
2ad60ce
f877698
 
2ad60ce
f877698
 
 
 
 
 
 
 
 
 
 
 
 
2ad60ce
f877698
 
 
2ad60ce
f877698
 
2ad60ce
f877698
 
 
2ad60ce
f877698
 
 
 
2ad60ce
f877698
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import argparse
import json
import os
import shutil
import subprocess
import sys
from pathlib import Path

REPO = Path(__file__).resolve().parent


def run(python, module, *args):
    command = [python, '-m', module, *map(str, args)]
    print('+', ' '.join(command), flush=True)
    env = dict(os.environ, PYTHONPATH=os.pathsep.join(filter(None, [str(REPO), os.environ.get('PYTHONPATH')])))
    subprocess.run(command, check=True, env=env)


def prepare_case(case: Path, out: Path):
    clip = json.loads((case / 'clip.json').read_text())
    clip_id = clip['clip_id']
    export, masks = out / 'export', out / 'masks'
    export.mkdir(parents=True, exist_ok=True)
    masks.mkdir(parents=True, exist_ok=True)
    (export / 'manifest.json').write_text(json.dumps({'clips': [clip_id]}))
    for link, target in ((export / clip_id, case), (masks / f'{clip_id}.png', case / 'mask.png')):
        if link.is_symlink() or link.exists():
            link.unlink()
        link.symlink_to(target)
    info = {}
    index = case.parent / 'index.json'
    if index.is_file():
        info = next((c for c in json.loads(index.read_text())['cases'] if c['clip_id'] == clip_id), {})
    return export, masks, info.get('mask', {}).get('dilate_px', 0), info.get('input_positions')


def subset_export(export: Path, clips, out: Path) -> Path:
    known = set(json.loads((export / 'manifest.json').read_text())['clips'])
    missing = [c for c in clips if c not in known]
    if missing:
        raise SystemExit(f'clips not in {export}: {missing}')
    subset = out / 'export'
    subset.mkdir(parents=True, exist_ok=True)
    (subset / 'manifest.json').write_text(json.dumps({'clips': list(clips)}))
    for clip_id in clips:
        link = subset / clip_id
        if link.is_symlink() or link.exists():
            link.unlink()
        link.symlink_to(export / clip_id)
    return subset


def write_pngs(final: Path, out: Path):
    import numpy as np
    from PIL import Image
    meta = json.loads((final / 'meta.json').read_text())
    for clip_id in meta['files']:
        with np.load(final / clip_id / 'frames.npz') as z:
            rgb = z['rgb']
        if rgb.dtype != np.uint8:
            rgb = (np.clip(rgb.astype(np.float32), 0, 1) * 255 + 0.5).astype(np.uint8)
        directory = out / clip_id
        directory.mkdir(parents=True, exist_ok=True)
        for position, frame in zip(meta['positions'], rgb):
            Image.fromarray(frame).save(directory / f'frame_{position:02d}.png')


def main(argv=None):
    p = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter)
    source = p.add_mutually_exclusive_group(required=True)
    source.add_argument('--case', type=Path, help='example case directory (frame_XX.png, clip.json, mask.png)')
    source.add_argument('--export', type=Path, help='clip export (tools/prepare_clip.py)')
    p.add_argument('--masks', choices=('dir', 'dataset'), default='dir',
                   help='with --export: dir = --mask-dir from tools/make_masks.py; dataset = the predicted masks of '
                        'the AmodalDrive dataset under --data-root (benchmark clips)')
    p.add_argument('--mask-dir', type=Path, help='with --masks dir: mask directory (tools/make_masks.py)')
    p.add_argument('--data-root', type=Path, help='with --masks dataset: AmodalDrive dataset root')
    p.add_argument('--clips', nargs='+', help='with --export: only these clip ids')
    p.add_argument('--out', type=Path, required=True)
    p.add_argument('--checkpoint-dir', type=Path, default=REPO / 'checkpoints',
                   help='agt_reconstruction.safetensors, agt_completion_lora.safetensors, motion_head.pth')
    p.add_argument('--segformer', default=None, help='SegFormer-B5 Cityscapes: local directory or hub id')
    p.add_argument('--flux', default=None, help='FLUX.1-Fill-dev: local diffusers directory or hub id')
    p.add_argument('--completion-python', default=sys.executable, help='python of the completion environment')
    p.add_argument('--mask-dilate', type=int, default=None,
                   help='mask dilation in pixels (default: the case setting; 4 for --masks dir; 0 for --masks dataset)')
    p.add_argument('--input-frames', type=int, nargs='+', default=None,
                   help='positions of the input frames; the frames from the first to the last input are rendered '
                        '(default: the case setting; the input frames of clip.json for --export)')
    p.add_argument('--reconstruction-only', action='store_true')
    p.add_argument('--keep-captures', action='store_true', help='keep the large capture files of the scene optimization')
    args = p.parse_args(argv)
    out = args.out.resolve()
    ckpt = args.checkpoint_dir.resolve()
    if args.case:
        export, masks, dilate, inputs = prepare_case(args.case.resolve(), out)
        mask_kind = 'images'
    else:
        export, inputs = args.export.resolve(), None
        if args.clips:
            export = subset_export(export, args.clips, out)
        if args.masks == 'dataset':
            if not args.data_root:
                p.error('--masks dataset needs --data-root')
            mask_kind, dilate, location = 'dataset', 0, ['--data-root', args.data_root.resolve()]
        else:
            if not args.mask_dir:
                p.error('--masks dir needs --mask-dir')
            mask_kind, dilate, location = 'dir', 4, ['--mask-dir', args.mask_dir.resolve()]
    if args.case:
        location = ['--mask-dir', masks]
    dilate = dilate if args.mask_dilate is None else args.mask_dilate
    inputs = inputs if args.input_frames is None else args.input_frames
    mask = ['--masks', mask_kind, *location, '--mask-dilate', dilate]
    py = sys.executable

    pass1, completion = out / 'reconstruction', out / 'completion'
    run(py, 'agt.recon.reconstruct', 'render', '--inputs', export, '--out', pass1, '--checkpoint-dir', ckpt, *mask,
        *(['--segformer', args.segformer] if args.segformer else []),
        *(['--input-frames', *inputs] if inputs else []))
    if args.reconstruction_only:
        write_pngs(pass1, out / 'frames')
        return
    run(args.completion_python, 'agt.completion.flux_fill', '--pass1', pass1, '--out', completion,
        '--lora', ckpt / 'agt_completion_lora.safetensors', *(['--base', args.flux] if args.flux else []))
    render_json = next(iter(sorted(pass1.glob('render.*.json'))))
    cap0, cap1, work, final = out / 'capture0', out / 'capture1', out / 'refinement', out / 'final'
    run(py, 'agt.refine.capture', '--render-json', render_json, '--out', cap0)
    run(py, 'agt.refine.refine', 'run', '--capture', cap0, '--handoff', completion, '--work', work)
    run(py, 'agt.refine.capture', '--render-json', render_json, '--out', cap1, '--repaired', work / 'views')
    run(py, 'agt.refine.refine', 'final', '--capture', cap1, '--work', work, '--out', final, '--check-capture', cap0)
    if not args.keep_captures:
        shutil.rmtree(cap0)
        shutil.rmtree(cap1)
    write_pngs(final, out / 'frames')


if __name__ == '__main__':
    main()