File size: 5,047 Bytes
e24a893
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Resume per-scene orbit renders; build the release montage only when all exist."""
import argparse
from concurrent.futures import ThreadPoolExecutor, as_completed
import json
import math
from pathlib import Path
import subprocess
import sys

from PIL import Image, ImageDraw
from package_trajectories import digest, write_json


def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('--dataset', type=Path, default=Path(__file__).resolve().parents[2] / 'batch_1st_scene')
    p.add_argument('--output-dir', type=Path, required=True)
    p.add_argument('--montage', type=Path)
    p.add_argument('--devices', nargs='+', default=['cuda:2', 'cuda:3'])
    p.add_argument('--frames', type=int, default=81)
    p.add_argument('--width', type=int, default=320)
    p.add_argument('--fps', type=int, default=10)
    p.add_argument('--amplitude', type=float, default=10)
    a = p.parse_args()
    scenes = [s for s in sorted(a.dataset.iterdir()) if s.is_dir() and s.name[:4].isdigit()]
    a.output_dir.mkdir(parents=True, exist_ok=True)
    def worker(group, device):
        rows = []
        for scene in group:
            out = a.output_dir / scene.name[:4]
            contract_path = scene / 'render/scene.json'
            if not contract_path.is_file():
                row = dict(scene=scene.name, status='missing_camera_contract')
            else:
                contract = json.loads(contract_path.read_text())
                expected = dict(camera_contract=digest(contract_path), foreground=digest(scene / contract['foreground']),
                                background=digest(scene / contract['background']))
                cached = json.loads((out / 'orbit.json').read_text()) if (out / 'orbit.json').exists() else {}
                reusable = (cached.get('hashes') == expected and len(cached.get('frames', [])) == a.frames
                            and cached.get('amplitude_degrees') == a.amplitude and cached.get('fps') == a.fps
                            and cached.get('image_size_wh', [None])[0] == a.width
                            and all((out / f'frame_{i:03d}.png').is_file() for i in range(a.frames)))
                if reusable:
                    row = dict(scene=scene.name, status='cached')
                else:
                    out.mkdir(exist_ok=True)
                    command = [sys.executable, str(Path(__file__).with_name('render_orbit.py')), '--scene', str(scene),
                               '--output-dir', str(out), '--device', device, '--frames', str(a.frames),
                               '--width', str(a.width), '--fps', str(a.fps), '--amplitude', str(a.amplitude)]
                    with (out / 'run.log').open('w') as log:
                        run = subprocess.run(command, stdout=log, stderr=subprocess.STDOUT)
                    row = dict(scene=scene.name, status='rendered' if run.returncode == 0 else 'failed', exit_code=run.returncode)
            rows.append(row)
            write_json(a.output_dir / ('status_' + device.replace(':', '_') + '.json'), rows)
            print(json.dumps(row), flush=True)
        return rows
    rows = []
    with ThreadPoolExecutor(max_workers=len(a.devices)) as pool:
        for future in as_completed([pool.submit(worker, scenes[i::len(a.devices)], device) for i, device in enumerate(a.devices)]):
            rows.extend(future.result())
    report = dict(total=len(scenes), completed=sum(r['status'] in ('rendered', 'cached') for r in rows),
                  scenes=sorted(rows, key=lambda r: r['scene']))
    write_json(a.output_dir / 'status.json', report)
    if a.montage and report['completed'] == len(scenes):
        cols = 10
        tile_h = max(Image.open(a.output_dir / s.name[:4] / 'frame_000.png').height for s in scenes)
        label_h = 20
        frames = []
        for frame in range(a.frames):
            canvas = Image.new('RGB', (cols * a.width, math.ceil(len(scenes) / cols) * (tile_h + label_h)), 'black')
            draw = ImageDraw.Draw(canvas)
            for i, scene in enumerate(scenes):
                x, y = i % cols * a.width, i // cols * (tile_h + label_h)
                with Image.open(a.output_dir / scene.name[:4] / f'frame_{frame:03d}.png') as image:
                    canvas.paste(image, (x, y + label_h))
                draw.text((x + 4, y + 3), scene.name[:4], fill='white')
            frames.append(canvas.quantize(colors=256))
        a.montage.parent.mkdir(parents=True, exist_ok=True)
        frames[0].save(a.montage, save_all=True, append_images=frames[1:], duration=round(1000 / a.fps), loop=0)
        write_json(a.montage.with_suffix('.json'), dict(scene_ids=[s.name for s in scenes], columns=cols,
                   fps=a.fps, frames=a.frames, amplitude_degrees=a.amplitude,
                   compositing_policy='foreground_alpha_priority_over_real_gs', status='all_scenes_rendered'))
    elif a.montage:
        print('Montage not published: some scenes are missing or failed.', flush=True)


if __name__ == '__main__':
    main()