File size: 8,138 Bytes
a54e6a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Per-session state<->video lag estimate for WildWorld. For a few frames of 2 windows per session, SAM2 (point grid)
gives object masks that do not depend on the state; the monster's state joints are projected at shifts s in [-90, 90]
and the shift whose projection falls best inside one object mask wins. A constant per-session lag was seen by eye
(bear session ~-40, most sessions 0). Output: ww_offsets.json {sid: {best_s, score_best, score_0, n_frames, ...}}.
  python ww_offset_est.py <shard> <nshards> [sessions_csv]   (CUDA_VISIBLE_DEVICES picks the GPU)"""
import glob, json, subprocess, sys, time
from pathlib import Path
import numpy as np, torch
from PIL import Image
sys.path.insert(0, "/data/yuzhewu/runs/proxykit"); sys.path.insert(0, "/data/yuzhewu/datasets/wildworld")
import ww_to_bossv2v as ww
from proxykit.geometry import Camera, quat_from_matrix
from transformers import Sam2Model, Sam2Processor
ROOT = Path("/data/yuzhewu/datasets/wildworld"); edges = json.load(open(ROOT / "skeleton_edges.json"))
SHIFTS = np.arange(-90, 91); FRAMES = (20, 60, 100); GRID = (24, 14); DEV = "cuda"
model = Sam2Model.from_pretrained("facebook/sam2.1-hiera-large", torch_dtype=torch.bfloat16).to(DEV).eval(); proc = Sam2Processor.from_pretrained("facebook/sam2.1-hiera-large")


def masks_for(img):
    """SAM2 masks from a point grid: list of bool (720,1280) masks, deduped, 0.3%..50% of the frame."""
    W, H = img.size; xs = (np.arange(GRID[0]) + 0.5) / GRID[0] * W; ys = (np.arange(GRID[1]) + 0.5) / GRID[1] * H
    pts = [[[float(x), float(y)]] for y in ys for x in xs]
    inputs = proc(images=img, input_points=[pts], input_labels=[[[1]] * len(pts)], return_tensors="pt").to(DEV)
    with torch.no_grad():
        out = model(**{k: (v.to(torch.bfloat16) if v.dtype == torch.float32 else v) for k, v in inputs.items()}, multimask_output=True)
    m = proc.post_process_masks(out.pred_masks.float().cpu(), inputs["original_sizes"].cpu())[0]     # (N, 3, H, W) bool
    iou = out.iou_scores.float().cpu()[0]                                                                # (N, 3)
    best = iou.argmax(-1); m = m[torch.arange(len(m)), best].numpy(); iou = iou[torch.arange(len(iou)), best].numpy()
    keep = []
    for k in np.argsort(-iou):
        a = m[k].mean()
        if not (0.003 <= a <= 0.5): continue
        if any((m[k] & m[j]).sum() / max((m[k] | m[j]).sum(), 1) > 0.8 for j in keep): continue
        keep.append(k)
    return [m[k] for k in keep]


def session_tables(sid):
    sd = ROOT / "data_part1" / sid; st = ww.load_state(sd / "state.csv"); z = np.load(sd / "skeleton.npz"); keys = {k[0]: k for k in z.files}; km = keys["m"]
    parts = ww.assign_parts(z[km], edges[f"em_{km.split('_', 1)[1]}"], st["monster.list.1.rot"], "m")[0]
    return st, z[km], np.asarray(parts) > 0, len(z[km])


def project(st, Jm, ok, t, ground):
    if t < 0 or t >= len(Jm) or np.isnan(st["camera.rot"][t]).any(): return None
    Rgl = ww.q2R(st["camera.rot"][t]); M = np.stack([ww.S_SWAP(-Rgl[:, 2]), ww.S_SWAP(Rgl[:, 0]), ww.S_SWAP(Rgl[:, 1])], 1)
    K = st["camera.K"][t]; cam = Camera(ww.S_SWAP(st["camera.pos"][t] - np.array([0, ground, 0])) * 100, quat_from_matrix(M), float(np.degrees(2 * np.arctan(640 / K[0]))), 1280, 720)
    P = ww.S_SWAP(Jm[t] - np.array([0, ground, 0])) * 100; good = ok & ~np.isnan(P).any(1)
    if good.sum() < 6: return None
    uv, d = cam.project(P[good]); vis = d > 50
    return uv[vis] if vis.sum() >= 6 else None


def hull_mask(uv):
    """Filled convex hull of the projected joints (monotone chain), as a bool (720,1280) mask."""
    from PIL import ImageDraw
    pts = sorted(set((float(x), float(y)) for x, y in uv))
    if len(pts) < 3: return None
    cross = lambda o, a, b: (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
    lo, up = [], []
    for q in pts:
        while len(lo) >= 2 and cross(lo[-2], lo[-1], q) <= 0: lo.pop()
        lo.append(q)
    for q in reversed(pts):
        while len(up) >= 2 and cross(up[-2], up[-1], q) <= 0: up.pop()
        up.append(q)
    hull = lo[:-1] + up[:-1]
    im = Image.new("L", (1280, 720), 0); ImageDraw.Draw(im).polygon(hull, fill=255)
    return np.asarray(im) > 0


def frame_score(masks, uv):
    """max over SAM masks of IoU(convex hull of projected joints, mask); 0 if the hull is mostly off-screen."""
    ins = (uv[:, 0] >= 0) & (uv[:, 0] < 1280) & (uv[:, 1] >= 0) & (uv[:, 1] < 720)
    if ins.mean() < 0.6: return 0.0
    hm = hull_mask(np.stack([np.clip(uv[:, 0], 0, 1279), np.clip(uv[:, 1], 0, 719)], 1))
    if hm is None or hm.sum() < 200: return 0.0
    best = 0.0
    for m in masks:
        inter = (hm & m).sum()
        if inter == 0: continue
        best = max(best, inter / (hm | m).sum())
    return float(best)


def estimate(sid, wins):
    st, Jm, ok, n = session_tables(sid); rows = []; t_start = time.time()
    for win in wins:
        m = json.load(open(ROOT / "windows_121" / win / "meta.json")); t0 = m["t0"]; ground = m["ground_y_m"]
        for i in FRAMES:
            uv0 = project(st, Jm, ok, t0 + i, ground)
            if uv0 is None: continue
            fp = Path("/tmp/claude-2007/-home-yuzhewu/5fdd2e27-0190-4cf5-b6bf-9a4d1f89d67d/scratchpad") / f"off_{sid}_{i}.png"; fp.parent.mkdir(parents=True, exist_ok=True)
            subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", str(ROOT / "windows_121" / win / "rgb.mp4"), "-vf", f"select=eq(n\\,{i}),scale=1280:720", "-vframes", "1", str(fp)], check=False)
            if not fp.exists(): continue
            masks = masks_for(Image.open(fp).convert("RGB")); fp.unlink()
            if not masks: continue
            sc = np.zeros(len(SHIFTS))
            for k, s in enumerate(SHIFTS):
                uv = project(st, Jm, ok, t0 + i + s, ground)
                sc[k] = frame_score(masks, uv) if uv is not None else 0.0
            rows.append(sc)
    if not rows: return dict(sid=sid, n_frames=0)
    k0 = int(np.where(SHIFTS == 0)[0][0])
    def width(r):                                                            # frames of the plateau within 90% of the peak: sharp = informative
        return int((r >= 0.9 * r.max()).sum())
    info = [r for r in rows if r.max() - np.median(r) >= 0.12 and width(r) <= 12]   # a real, sharp peak
    use = info if info else rows
    tot = np.mean(use, 0); k = int(np.argmax(tot)); pf = [int(SHIFTS[int(np.argmax(r))]) for r in use]
    return dict(sid=sid, n_frames=len(rows), n_info=len(info), best_s=int(SHIFTS[k]), median_s=int(np.median(pf)), spread=int(max(pf) - min(pf)),
                score_best=float(tot[k]), score_0=float(tot[k0]), score_med=float(np.median(tot)),
                per_frame_best=[int(SHIFTS[int(np.argmax(r))]) for r in rows], per_frame_peak=[round(float(r.max() - np.median(r)), 2) for r in rows],
                per_frame_width=[width(r) for r in rows], curves=[np.round(r, 3).tolist() for r in rows], secs=round(time.time() - t_start, 1))


if __name__ == "__main__":
    shard, nsh = int(sys.argv[1]), int(sys.argv[2])
    by_sid = {}
    for f in sorted(glob.glob(str(ROOT / "windows_121" / "*/meta.json"))):
        win = Path(f).parent.name; sid = win.rsplit("_", 1)[0]
        if (ROOT / "data_part1" / sid).exists(): by_sid.setdefault(sid, []).append(win)
    sids = sys.argv[3].split(",") if len(sys.argv) > 3 else sorted(by_sid)
    out = Path(ROOT / f"ww_offsets_shard{shard}.json"); res = json.load(open(out)) if out.exists() else {}
    for n, sid in enumerate(sids):
        if n % nsh != shard or sid in res: continue
        w = by_sid[sid]; pick = [w[0], w[len(w) // 2]] if len(w) > 1 else w[:1]
        r = estimate(sid, pick); res[sid] = r; json.dump(res, open(out, "w"), indent=1)
        print(f"[{time.strftime('%H:%M:%S')}] {sid} frames {r.get('n_frames')} best_s {r.get('best_s')} median_s {r.get('median_s')} spread {r.get('spread')} info {r.get('n_info')} score {r.get('score_best', 0):.2f} (s=0: {r.get('score_0', 0):.2f}, med {r.get('score_med', 0):.2f}) per-frame {r.get('per_frame_best')} peaks {r.get('per_frame_peak')} widths {r.get('per_frame_width')} {r.get('secs')}s", flush=True)
    print("SHARD_DONE", shard)