File size: 10,948 Bytes
ae1ed83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
#!/usr/bin/env python3
"""TRACE-VLA v2 Data Factory — pilot D1/D2 (spec 21/11/2026, Task 2-5).

Scene: libero_object task 0 BDDL (native goal alphabet_soup_1, ds24).
It is the one physical scene; the second goal is salad_dressing_1
(ds26, train task Object #2) scored by LIBERO's own predicate
_eval_predicate(('in', obj, 'basket_1_contain_region')), validated
20/20 against env.check_success() in df_audit.py.

Per pair: ONE official init state (+ layout intervention), TWO goals,
each with a fresh scripted-expert trajectory starting from a restore
of the identical state. Layouts: 'orig' and 'swap' (the two targets
exchange positions -> D1 target relocation + distractor relocation +
target/distractor swap in one intervention). Support demos are real
dataset episodes (different episode from every query; RGB only).
"""
import hashlib
import json
import sys
import time
from pathlib import Path

import numpy as np

sys.path.insert(0, str(Path(__file__).parent))
from eval_trace_heldout import make_env          # noqa: E402
from v2_scene import (object_positions, settle,  # noqa: E402
                      swap_objects)
from df_expert import (ExpertFail, Recorder,     # noqa: E402
                       ScriptedExpert, goal_in)
from v2_dash import merge_item                   # noqa: E402

EXP = Path.home() / "sera_v4_experiments"
OUT = EXP / "data_factory" / "pilot"
EP_DIR = OUT / "episodes"
DEMO_DIR = OUT / "demos"
for d in (EP_DIR, DEMO_DIR):
    d.mkdir(parents=True, exist_ok=True)

OBJ_A = "alphabet_soup_1"      # Object #0, ds24, native goal of scene
OBJ_B = "salad_dressing_1"     # Object #2, ds26, second valid goal
TARGETS = {"A": {"object": OBJ_A, "ds": 24, "suite_task": 0,
                 "grasp_off": 0.03, "demo_ep": 813},
           "B": {"object": OBJ_B, "ds": 26, "suite_task": 2,
                 "grasp_off": 0.05, "demo_ep": 816}}
HELD_OUT_GOAL_OBJECTS = {"cream_cheese_1", "tomato_sauce_1", "milk_1"}
INIT_POOL = list(range(10))
PAIRS_PER_LAYOUT = 4
SIM_SEED = 0

attempts = []
pairs = []
episodes_meta = []


def log_attempt(**kw):
    kw["ts"] = time.strftime("%H:%M:%S")
    attempts.append(kw)
    print("ATTEMPT", json.dumps(kw), flush=True)


def setup(env, init_states, init_idx, layout):
    obs = env.reset()
    obs = env.set_init_state(init_states[init_idx])
    if layout == "swap":
        obs = swap_objects(env, obs, OBJ_A, OBJ_B)
    else:
        obs = settle(env)
    return obs


def init_hash(init_state, layout):
    h = hashlib.sha256(np.asarray(init_state).tobytes()
                       + layout.encode()).hexdigest()
    return h[:16]


def run_goal(env, init_states, init_idx, layout, goal_key):
    """One expert trajectory from a fresh restore. Returns
    (meta_dict, arrays_or_None)."""
    tgt = TARGETS[goal_key]
    obs = setup(env, init_states, init_idx, layout)
    start_poses = {k: np.round(v, 4).tolist()
                   for k, v in object_positions(obs).items()}
    rec = Recorder(env)
    rec.start(obs)
    ex = ScriptedExpert(env, rec)
    ex.obs = obs
    meta = {"goal_id": goal_key, "target_id": tgt["object"],
            "target_ds": tgt["ds"], "layout": layout,
            "init_index": init_idx,
            "init_hash": init_hash(init_states[init_idx], layout),
            "start_poses": start_poses, "grasp_off": tgt["grasp_off"]}
    try:
        diag = ex.pick_place(tgt["object"],
                             grasp_off=tgt["grasp_off"])
    except ExpertFail as e:
        meta["expert_success"] = False
        meta["fail_reason"] = str(e)
        return meta, None
    meta.update(diag)
    meta["expert_success"] = bool(diag["success"])
    if goal_key == "A":
        meta["native_check_success"] = bool(env.check_success())
        meta["predicate_agrees_native"] = bool(
            meta["native_check_success"] == meta["expert_success"])
    if not meta["expert_success"]:
        meta["fail_reason"] = "goal_predicate_false_after_place"
        return meta, None
    arr = rec.arrays()
    meta["frames"] = int(len(arr["states"]))
    return meta, arr


def extract_demo(goal_key):
    """RGB demo from the real LeRobot dataset (support only)."""
    import glob
    import cv2
    import pandas as pd
    tgt = TARGETS[goal_key]
    ep = tgt["demo_ep"]
    snap = sorted(glob.glob(str(
        Path.home() / ".cache/huggingface/hub/datasets--lerobot--libero"
        / "snapshots" / "*")))[0]
    meta_f = sorted(glob.glob(
        str(Path(snap) / "meta/episodes/**/*.parquet"), recursive=True))[0]
    df = pd.read_parquet(meta_f)
    row = df[df["episode_index"] == ep].iloc[0]
    import torch
    store = torch.load(EXP / "fewshot/demo_store.pt",
                       weights_only=False)
    ep_task = np.asarray(store["ep_task"])
    assert int(ep_task[ep]) == tgt["ds"], (
        f"demo episode {ep} has task {int(ep_task[ep])}, "
        f"expected ds{tgt['ds']}")
    out = {"dataset_episode": int(ep), "length": int(row["length"]),
           "verified_task_ds": int(ep_task[ep])}
    frames = {}
    for key, cam in (("observation.images.image", "agentview"),
                     ("observation.images.image2", "wrist")):
        ci = int(row[f"videos/{key}/chunk_index"])
        fi = int(row[f"videos/{key}/file_index"])
        t0 = float(row[f"videos/{key}/from_timestamp"])
        t1 = float(row[f"videos/{key}/to_timestamp"])
        path = (Path(snap) / "videos" / key / f"chunk-{ci:03d}"
                / f"file-{fi:03d}.mp4")
        cap = cv2.VideoCapture(str(path))
        cap.set(cv2.CAP_PROP_POS_MSEC, t0 * 1000.0)
        n = int(round((t1 - t0) * 10.0))
        buf = []
        for _ in range(n):
            ok, fr = cap.read()
            if not ok:
                break
            buf.append(cv2.cvtColor(fr, cv2.COLOR_BGR2RGB))
        cap.release()
        arr = np.stack(buf)
        idx = np.unique(np.linspace(0, len(arr) - 1, 64)
                        .round().astype(int))
        frames[cam] = arr[idx]
        out[f"{cam}_frames_full"] = int(len(arr))
        out[f"{cam}_frames_saved"] = int(len(idx))
    np.savez(DEMO_DIR / f"demo_goal{goal_key}_ds{tgt['ds']}_ep{ep}.npz",
             **frames)
    out["file"] = f"demo_goal{goal_key}_ds{tgt['ds']}_ep{ep}.npz"
    return out


def main():
    merge_item("data_factory.pilot", {
        "status": "running",
        "note": "Pilot D1/D2: scene libero_object#0, goal A alphabet_soup "
                "(ds24), goal B salad_dressing (ds26)"})
    demos = {k: extract_demo(k) for k in ("A", "B")}
    print("DEMOS", json.dumps(demos), flush=True)

    env, init_states = make_env("libero_object", 0)
    total_attempts = 0
    total_success = 0
    for layout in ("orig", "swap"):
        valid = 0
        for init_idx in INIT_POOL:
            if valid >= PAIRS_PER_LAYOUT:
                break
            pair_id = f"{layout}_init{init_idx}"
            members = {}
            ref_poses = None
            ok_pair = True
            for goal_key in ("A", "B"):
                total_attempts += 1
                meta, arr = run_goal(env, init_states, init_idx,
                                     layout, goal_key)
                log_attempt(pair=pair_id, goal=goal_key,
                            success=meta["expert_success"],
                            reason=meta.get("fail_reason", ""))
                if ref_poses is None:
                    ref_poses = meta["start_poses"]
                    meta["start_pose_drift_m"] = 0.0
                else:
                    drift = max(
                        float(np.linalg.norm(
                            np.array(meta["start_poses"][k])
                            - np.array(ref_poses[k])))
                        for k in ref_poses)
                    meta["start_pose_drift_m"] = round(drift, 5)
                if arr is None:
                    ok_pair = False
                    continue
                total_success += 1
                ep_id = f"ep_{pair_id}_goal{goal_key}"
                np.savez(EP_DIR / f"{ep_id}.npz", **arr)
                meta["episode_id"] = ep_id
                meta["file"] = f"episodes/{ep_id}.npz"
                meta["support_demo_episode"] = TARGETS[goal_key][
                    "demo_ep"]
                meta["support_demo_file"] = demos[goal_key]["file"]
                members[goal_key] = meta
                episodes_meta.append(meta)
            if ok_pair and len(members) == 2:
                valid += 1
                pairs.append({
                    "pair_id": pair_id, "layout": layout,
                    "init_index": init_idx,
                    "init_hash": members["A"]["init_hash"],
                    "episodes": {k: members[k]["episode_id"]
                                 for k in ("A", "B")}})
                print(f"PAIR OK {pair_id} ({valid}/{PAIRS_PER_LAYOUT} "
                      f"for {layout})", flush=True)
            else:
                print(f"PAIR REJECTED {pair_id}", flush=True)
            merge_item("data_factory.pilot", {
                "status": "running",
                "pct": round(100.0 * len(pairs) / 8.0, 1),
                "metrics": {
                    "Cặp hợp lệ": f"{len(pairs)}/8",
                    "Trajectory thành công": str(total_success),
                    "Tổng lần thử": str(total_attempts)}})
    manifest = {
        "created": time.strftime("%Y-%m-%d %H:%M:%S"),
        "spec": "TRACE-VLA v2 Data Factory pilot (D1/D2 feasibility)",
        "scene": {"suite": "libero_object", "bddl_task_index": 0,
                  "native_goal": "alphabet_soup_1",
                  "sim_seed": SIM_SEED, "control_freq": 20,
                  "record_fps": 10},
        "targets": TARGETS,
        "held_out_objects_in_scene_as_distractors_only": sorted(
            HELD_OUT_GOAL_OBJECTS),
        "support_demos": demos,
        "split_rule": "Factory pilot episodes are TRAIN split. Init "
                      "indices 0-9 of this scene are reserved to the "
                      "factory; dev/final evaluation on this scene "
                      "must use init indices >= 10.",
        "pairs": pairs,
        "episodes": episodes_meta,
        "n_attempts": total_attempts,
        "n_success_trajectories": total_success,
    }
    (OUT / "manifest.json").write_text(json.dumps(manifest, indent=1))
    (OUT / "attempts_log.json").write_text(json.dumps(attempts,
                                                      indent=1))
    merge_item("data_factory.pilot", {
        "status": "done" if len(pairs) == 8 else "fail",
        "pct": round(100.0 * len(pairs) / 8.0, 1),
        "metrics": {"Cặp hợp lệ": f"{len(pairs)}/8",
                    "Trajectory thành công": str(total_success),
                    "Tổng lần thử": str(total_attempts)}})
    print(f"DONE pairs={len(pairs)}/8 success={total_success}/"
          f"{total_attempts}", flush=True)


if __name__ == "__main__":
    main()