File size: 5,520 Bytes
39149b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Index every finished run since the capsule-character labels (v9 stylized + v10 real) for upload: v6 exporter (actions, blocks,
events, frames.jsonl, meta) with the clip list replaced by the capture's cut-grid clips (clips_81_v9.json), meta extended with the
v9 / v10 fields, plus a thumbnail (RGB | semantic | condition). Parallel; finished runs are skipped.
usage: post_v10_pool.py DSROOT [WORKERS]"""
import os, sys, json, glob, re, time, subprocess
from concurrent.futures import ProcessPoolExecutor, as_completed
import numpy as np
from PIL import Image
EXP = r'G:\GameCrafter\capture_work\v6\post\export_v6.py'
SUBSETS = {'v9_stylized': ([r'D:\GameCrafter_v9\raw', r'E:\GameCrafter_v9\raw'], re.compile(r'^(\d\d_.+?)_(P9[A-Z]?_[a-z]+_s\d+)$')),
           'v10_real': ([r'F:\GameCrafter_v10\raw', r'E:\GameCrafter_v10\raw', r'H:\GameCrafter_v10\raw', r'G:\GameCrafter_v10\raw'], re.compile(r'^(\d\d_.+?)_(R10_s\d+)$'))}
PAL = np.array([[18, 20, 26], [122, 156, 92], [196, 186, 160], [182, 98, 72], [128, 120, 132], [52, 128, 60], [214, 168, 52]] + [[0, 0, 0]] * 3 +
               [[80, 150, 255], [255, 80, 70]] + [[255, 0, 255]] * 244, np.uint8)


def one(subset, d, ds):
    name = os.path.basename(d); scene, tag = SUBSETS[subset][1].match(name).groups()
    out = os.path.join(ds, subset, scene, tag); t0 = time.time()
    if os.path.exists(os.path.join(out, 'meta.json')) and os.path.exists(os.path.join(out, 'thumb.jpg')): return name, 'skip', 0
    r = subprocess.run([sys.executable, EXP, 'index', d, out], capture_output=True, text=True)
    if r.returncode: return name, 'INDEX FAILED ' + r.stderr[-600:], time.time() - t0
    m = json.load(open(os.path.join(out, 'meta.json'), encoding='utf-8')); cr = m.get('capture_result', {}); v9 = cr.get('v9', {})
    cv = json.load(open(os.path.join(d, 'clips_81_v9.json'), encoding='utf-8'))
    ev = json.load(open(os.path.join(out, 'events.json'), encoding='utf-8')); ev = [e for e in ev if e.get('type') in ('delete', 'replace', 'spawn')]
    clips = []
    for c in cv['clips']:
        s, e = c['start'], c['end'] + 1
        clips.append({'start': s, 'end': e, 'episode': c.get('episode'), 'camera_variant': c.get('camera_variant'), 'look': c.get('look'), 'look_name': c.get('look_name'),
                      'centered': c.get('centered', True), 'max_frame_offset_cm': c.get('max_frame_offset_cm', 0.0),
                      'events': [{'offset': x['frame'] - s, 'type': x['type'], 'removed': (x.get('removed') or {}).get('class'), 'added': (x.get('added') or {}).get('class')} for x in ev if s <= x['frame'] < e]})
    json.dump(clips, open(os.path.join(out, 'clips_81.json'), 'w'))
    real = subset == 'v10_real'; vr = v9.get('v10_real') or {}
    m.update({'subset': subset, 'clips_81': len(clips), 'clips_81_dropped': len(cv.get('dropped') or []), 'clips_with_events': sum(1 for c in clips if c['events']),
              'clips_centered': sum(1 for c in clips if c['centered']), 'cut_grid': cv.get('cut_grid'), 'clip_rule': cv.get('rule'), 'looks': v9.get('looks'),
              'look_names': sorted({c['look_name'] for c in clips if c.get('look_name')}), 'capsule_labels': bool(v9.get('capsule_labels')),
              'camera': ('perspective telephoto (FOV 22-40 deg) with the 2.5D framing, player kept centred' if real else
                         'isometric orthographic 2.5D (v9 framing: ortho width 900-1600 cm, 12% wide 2000-3000 cm, pitch -68..-32 deg)'),
              'files_per_frame': {'rgb': '%06d.jpg', 'semantic_ids': '%06d.ids.png (uint8 class id, lossless; player / boss drawn as capsules)',
                                  'whitebox': '%06d.whitebox.jpg', 'condition': '%06d.cond.png (semantic palette + code-shaded capsule characters)', 'meta': '%06d.json'}})
    if real: m['v10_real'] = {'biome_variants_used': vr.get('variants_used'), 'counts': vr.get('counts')}
    json.dump(m, open(os.path.join(out, 'meta.json'), 'w', encoding='utf-8'), indent=1, ensure_ascii=False)
    n = m['frames']; rows = []
    for f in (n // 3, 2 * n // 3):
        b = os.path.join(d, 'raw', f'{f:06d}')
        rgb = np.asarray(Image.open(b + '.jpg').convert('RGB').resize((427, 235)))
        ids = PAL[np.asarray(Image.open(b + '.ids.png').resize((427, 235), Image.NEAREST))]
        cond = np.asarray(Image.open(b + '.cond.png').convert('RGB').resize((427, 235)))
        rows.append(np.concatenate([rgb, ids, cond], 1))
    Image.fromarray(np.concatenate(rows, 0)).save(os.path.join(out, 'thumb.jpg'), quality=85)
    return name, 'done', time.time() - t0


if __name__ == '__main__':
    ds = sys.argv[1]; workers = int(sys.argv[2]) if len(sys.argv) > 2 else 4
    jobs = []
    for subset, (roots, rx) in SUBSETS.items():
        for root in roots:
            for d in sorted(glob.glob(os.path.join(root, '*'))):
                if not rx.match(os.path.basename(d)): continue
                try: ok = json.load(open(os.path.join(d, 'capture_result.json'))).get('ok')
                except Exception: ok = False
                if ok and os.path.exists(os.path.join(d, 'clips_81_v9.json')): jobs.append((subset, d))
    print(time.strftime('%H:%M:%S'), len(jobs), 'runs', {s: sum(1 for j in jobs if j[0] == s) for s in SUBSETS}, flush=True)
    with ProcessPoolExecutor(workers) as ex:
        futs = [ex.submit(one, s, d, ds) for s, d in jobs]
        for k, f in enumerate(as_completed(futs)):
            name, st, sec = f.result(); print(time.strftime('%H:%M:%S'), f'{k + 1}/{len(jobs)}', name, st, f'{sec:.0f}s', flush=True)