File size: 32,592 Bytes
bcd600f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b1daed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcd600f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b1daed
 
bcd600f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b1daed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcd600f
 
 
 
5b1daed
 
 
bcd600f
 
 
 
 
 
 
 
 
 
 
5b9d9bf
 
 
bcd600f
 
 
 
 
 
 
5b1daed
bcd600f
 
 
5b1daed
 
 
 
 
bcd600f
 
 
5b1daed
 
 
 
5b9d9bf
5b1daed
5b9d9bf
 
 
 
 
 
5b1daed
 
 
5b9d9bf
5b1daed
 
 
 
 
 
 
 
 
 
 
 
 
bcd600f
 
 
 
 
 
 
5b1daed
bcd600f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b1daed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcd600f
 
 
 
 
5b1daed
 
 
bcd600f
 
 
 
 
 
 
 
 
 
 
 
 
 
5b1daed
 
 
bcd600f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b1daed
bcd600f
 
 
 
 
 
 
 
 
 
 
 
5b1daed
 
 
 
 
 
 
 
bcd600f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
#!/usr/bin/env python3
"""V2 pipeline: pack GelSLAM, TactileTracking, RealTactileMNIST, FeelAnyForce
into the unified parquet schema used by `yxma/gelsight-mini-pretrain`.

Adaptive subsampling per source:
  - per-source frame budget = min(200_000, contact_frames_available)
  - dynamism-aware stride (high inter-frame delta -> denser sample)
  - validity filter: drop frames where central deformation < threshold
  - perceptual-hash dedupe

Outputs sit alongside existing fota_*/threedcal/feats:
  /media/yxma/Disk1/yuxiang/mini_data_parquet/<sub>/{train|...}-####-of-####.parquet

Usage:
  python make_parquet_v2.py probe <sub>       # measure dynamism + empty fraction
  python make_parquet_v2.py process <sub>     # full pipeline + write
  python make_parquet_v2.py stats             # show row counts across all subs
"""

import io
import json
import os
import sys
import time
from collections import defaultdict
from glob import glob
from typing import Iterator, Optional, Tuple

import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
from PIL import Image

BASE_DATA   = "/media/yxma/Disk1/yuxiang/mini_data"
BASE_OUT    = "/media/yxma/Disk1/yuxiang/mini_data_parquet"
BUDGET      = 200_000                # max kept frames per source
SHARD_TGT   = 2 * 1024 ** 3          # 2 GB shard target

# Validity filter — area + intensity rule (replaces former mean-deform tau).
# A frame is valid iff, on the central-50%-crop |frame - baseline| diff:
#     n_pixels_above(PIXEL_THRESH) >= A_min   AND   their mean diff >= I_min
PIXEL_THRESH = 10                    # sensor-noise floor, grey-levels
EMPTY_BUDGET = 0.03                  # ≤ 3 % of kept frames may sneak below A_min/I_min
PHASH_DIST   = 4                     # max hamming distance for "duplicate"

# Per-source validity thresholds (A_min in pixels, I_min in grey-levels).
# Calibrated visually for each sensor/recording style.
VALIDITY_THRESH = {
    "gelslam":           dict(A_min=200, I_min=12),
    "tactile_tracking":  dict(A_min=200, I_min=12),
    # All non-listed sources are entered in SKIP_EMPTY_FILTER below and use
    # source-specific selection (e.g. RTM has its own area+intensity inside
    # the iterator).
}

# Existing schema + 3 new nullable cols
SCHEMA = pa.schema([
    ("image", pa.binary()),
    ("image_format", pa.string()),
    ("source", pa.string()),
    ("markered", pa.bool_()),
    ("capture", pa.string()),
    ("split", pa.string()),
    ("height", pa.int32()),
    ("width", pa.int32()),
    ("obj_name", pa.string()),
    ("init_pose", pa.int32()),
    ("side", pa.string()),
    ("x_mm", pa.float32()),
    ("y_mm", pa.float32()),
    ("z_mm", pa.float32()),
    ("quat_x", pa.float32()),
    ("quat_y", pa.float32()),
    ("quat_z", pa.float32()),
    ("quat_w", pa.float32()),
    ("indenter", pa.string()),
    ("indenter_param", pa.string()),
    ("f_x", pa.float32()),
    ("f_y", pa.float32()),
    ("f_z", pa.float32()),
    ("grid_z_max", pa.float32()),
    ("grid_z_mean", pa.float32()),
    # NEW columns (nullable for old data)
    ("episode", pa.string()),
    ("frame_idx", pa.int32()),
    ("digit_class", pa.int32()),
    ("gel_variant", pa.string()),
    # v3 — distinguish real-world capture vs synthetic
    ("domain", pa.string()),    # "real" | "sim"
])


# ─────────────────────────────────────────────────────────────────
# helpers
# ─────────────────────────────────────────────────────────────────

def encode_jpeg(arr_rgb: np.ndarray, q=92) -> bytes:
    im = Image.fromarray(arr_rgb)
    buf = io.BytesIO()
    im.save(buf, format="JPEG", quality=q, optimize=True)
    return buf.getvalue()


def grey_center(arr: np.ndarray) -> np.ndarray:
    """Central 50% crop, greyscale, float32."""
    if arr.ndim == 3:
        g = arr.mean(axis=2)
    else:
        g = arr
    h, w = g.shape
    return g[h//4:3*h//4, w//4:3*w//4].astype(np.float32)


def phash(arr_rgb: np.ndarray) -> int:
    """8x8 DCT-low-freq perceptual hash, returned as 64-bit int."""
    im = Image.fromarray(arr_rgb).convert("L").resize((32, 32), Image.LANCZOS)
    a = np.array(im, dtype=np.float32)
    # 2D DCT via numpy
    def dct1(x): return np.fft.fft(np.concatenate([x, x[::-1]], axis=-1)).real[..., :x.shape[-1]]
    d = dct1(dct1(a).T).T
    low = d[:8, :8].flatten()
    med = np.median(low[1:])  # skip DC
    h = 0
    for bit in (low > med):
        h = (h << 1) | int(bit)
    return h


def hamming(a: int, b: int) -> int:
    return bin(a ^ b).count("1")


# ─────────────────────────────────────────────────────────────────
# Per-source iterators
# Each yields (frame_rgb_np, base_meta_dict) for ONE frame at a time.
# Within each episode/capture, frames are emitted in order so we can
# compute a baseline image for the validity filter.
# ─────────────────────────────────────────────────────────────────

def iter_gelslam():
    """GelSLAM: gelsight.avi per episode under tracking_dataset/ and reconstruction_dataset/."""
    import cv2
    root = f"{BASE_DATA}/markerless/GelSLAM"
    # The HF download puts content under root or root/dataset/ depending on extraction
    for sub in ("tracking_dataset", "reconstruction_dataset"):
        candidates = (
            glob(f"{root}/{sub}/*/gelsight.avi") +
            glob(f"{root}/dataset/{sub}/*/gelsight.avi")
        )
        for vid in candidates:
            episode = os.path.basename(os.path.dirname(vid))
            split = "train" if sub == "tracking_dataset" else "recon"
            cap = cv2.VideoCapture(vid)
            fi = 0
            while True:
                ok, fr = cap.read()
                if not ok:
                    break
                fr = fr[:, :, ::-1]  # BGR->RGB
                yield fr, {
                    "source": "gelslam",
                    "markered": False,
                    "capture": f"{sub}/{episode}",
                    "split": split,
                    "obj_name": episode,
                    "episode": episode,
                    "frame_idx": fi,
                }
                fi += 1
            cap.release()


def iter_tactile_tracking():
    import cv2
    import re
    root = f"{BASE_DATA}/markerless/TactileTracking"
    candidates = sorted(glob(f"{root}/normalflow_dataset/*/gelsight.avi"))
    obj_re = re.compile(r"^([a-zA-Z]+)(\d+)$")
    for vid in candidates:
        trial_dir = os.path.basename(os.path.dirname(vid))  # e.g. 'corner3'
        m = obj_re.match(trial_dir)
        if m:
            obj, trial = m.group(1), m.group(2)
        else:
            obj, trial = trial_dir, "0"
        cap = cv2.VideoCapture(vid)
        fi = 0
        while True:
            ok, fr = cap.read()
            if not ok:
                break
            fr = fr[:, :, ::-1]
            yield fr, {
                "source": "tactile_tracking",
                "markered": False,
                "capture": f"{obj}/{trial}",
                "split": "train",
                "obj_name": obj,
                "episode": trial,
                "frame_idx": fi,
            }
            fi += 1
        cap.release()


def iter_real_tactile_mnist():
    """RTM seq-320x240: parquet with 'sensor_video' list-of-struct{bytes,path}.

    Frame-picking strategy (v4 — area+intensity rule):
      1. Decode all frames in the touch video clip (~60-73 frames).
      2. Compute a per-clip baseline = median of first 5 frames (no-contact prologue).
      3. Use `touch_start_time_rel`/`touch_end_time_rel` to find frames inside
         the contact window. Within that window, pick the frame with maximum
         mean-|diff| from baseline (the peak-contact frame).
      4. On the picked frame, compute:
           pixel_diff   = |frame - baseline|  on central 50% crop (grey-levels)
           mask         = pixel_diff > PIXEL_THRESH   (default 10)
           contact_area = mask.sum()                 (in pixels)
           contact_int  = pixel_diff[mask].mean()    (avg deformation in lit pixels)
      5. Keep iff `contact_area >= RTM_A_MIN` AND `contact_int >= RTM_I_MIN`.
         Tunables: RTM_PIXEL_THRESH=10, RTM_A_MIN=40, RTM_I_MIN=15.
         Probe at these values: ~16% keep, ~24K final rows, every kept frame
         visually shows a clear digit-edge imprint.
    """
    import cv2
    root = f"{BASE_DATA}/markerless/RealTactileMNIST"
    pq_files = sorted(glob(f"{root}/data/*.parquet"))
    PIXEL_THRESH = 10
    A_MIN = 40
    I_MIN = 15
    for p in pq_files:
        split = "test" if "test" in os.path.basename(p).lower() else "train"
        pf = pq.ParquetFile(p)
        for batch in pf.iter_batches(batch_size=4):
            cols = batch.to_pydict()
            n = len(cols.get("label", cols.get("id", [])))
            for i in range(n):
                round_id = cols.get("id", [None]*n)[i]
                label = cols.get("label", [None]*n)[i]
                obj_id = cols.get("object_id", [None]*n)[i]
                videos = cols["sensor_video"][i] or []
                ts_seq = cols.get("time_stamp_rel_seq", [None]*n)[i] or []
                t_start = cols.get("touch_start_time_rel", [None]*n)[i] or []
                t_end = cols.get("touch_end_time_rel", [None]*n)[i] or []
                for tj, vid_struct in enumerate(videos):
                    if not vid_struct: continue
                    vid_bytes = vid_struct.get("bytes") if isinstance(vid_struct, dict) else None
                    if not vid_bytes: continue
                    tmpf = f"/tmp/_rtm_{os.getpid()}.mp4"
                    with open(tmpf, "wb") as f: f.write(vid_bytes)
                    cap = cv2.VideoCapture(tmpf)
                    frames = []; grays = []
                    while True:
                        ok, fr = cap.read()
                        if not ok: break
                        rgb = fr[:, :, ::-1]
                        frames.append(rgb)
                        g = cv2.cvtColor(fr, cv2.COLOR_BGR2GRAY).astype(np.float32)
                        h, w = g.shape
                        grays.append(g[h//4:3*h//4, w//4:3*w//4])
                    cap.release()
                    try: os.remove(tmpf)
                    except: pass
                    if len(frames) < 8: continue

                    baseline = np.median(np.stack(grays[:5]), axis=0)
                    deforms = [float(np.abs(g - baseline).mean()) for g in grays]

                    in_window = list(range(len(frames)))
                    try:
                        ts = ts_seq[tj] if tj < len(ts_seq) else None
                        ts0 = t_start[tj] if tj < len(t_start) else None
                        ts1 = t_end[tj] if tj < len(t_end) else None
                        if ts is not None and ts0 is not None and ts1 is not None \
                                and len(ts) == len(frames):
                            in_window = [k for k, t in enumerate(ts) if ts0 <= t <= ts1]
                            if not in_window:
                                in_window = list(range(len(frames)))
                    except Exception:
                        pass

                    peak_idx = in_window[int(np.argmax([deforms[k] for k in in_window]))]

                    # area + intensity rule on the picked peak frame
                    pixel_diff = np.abs(grays[peak_idx] - baseline)
                    mask = pixel_diff > PIXEL_THRESH
                    contact_area = int(mask.sum())
                    if contact_area < A_MIN: continue
                    contact_int = float(pixel_diff[mask].mean())
                    if contact_int < I_MIN: continue

                    yield frames[peak_idx], {
                        "source": "real_tactile_mnist",
                        "markered": False,
                        "capture": f"r{round_id}_t{tj}",
                        "split": split,
                        "obj_name": f"digit_{label}",
                        "digit_class": int(label) if label is not None else None,
                        "episode": str(obj_id) if obj_id is not None else None,
                        "frame_idx": peak_idx,
                    }


def iter_feelanyforce():
    """FAF: loose 320x240 PNG per indentation under dataset/<object>/tactile/."""
    root = f"{BASE_DATA}/markerless/FeelAnyForce/dataset/dataset"
    objects = sorted(d for d in os.listdir(root) if os.path.isdir(f"{root}/{d}"))
    for obj in objects:
        p = f"{root}/{obj}/tactile"
        if not os.path.isdir(p): continue
        files = sorted(os.listdir(p))
        for fi, fn in enumerate(files):
            try:
                fr = np.array(Image.open(f"{p}/{fn}").convert("RGB"))
            except Exception:
                continue
            yield fr, {
                "source": "feelanyforce",
                "markered": False,    # visually verified markerless
                "capture": obj,
                "split": "train",
                "obj_name": obj.split("_")[0],
                "episode": obj,
                "frame_idx": fi,
            }


def iter_sim_tactile_mnist():
    """Sim Tactile MNIST seq-320x240 (Taxim Mini-calibrated).
    Schema: parquet rows, each row = one digit, with `sensor_image` = list of
    32 JPEG-bytes structs (one image per touch, already at peak contact).
    No video decoding, no filtering — sim frames are by construction valid.
    """
    root = f"{BASE_DATA}/markerless/SimTactileMNIST"
    pq_files = sorted(glob(f"{root}/data/*.parquet"))
    for p in pq_files:
        fn = os.path.basename(p).lower()
        if "test" in fn: split = "test"
        elif "val" in fn: split = "val"
        else: split = "train"
        pf = pq.ParquetFile(p)
        for batch in pf.iter_batches(batch_size=8):
            cols = batch.to_pydict()
            n = len(cols.get("label", cols.get("id", [])))
            for i in range(n):
                round_id = cols.get("id", [None]*n)[i]
                label = cols.get("label", [None]*n)[i]
                obj_id = cols.get("object_id", [None]*n)[i]
                images = cols["sensor_image"][i] or []
                for tj, img_struct in enumerate(images):
                    if not img_struct: continue
                    img_bytes = img_struct.get("bytes") if isinstance(img_struct, dict) else None
                    if not img_bytes: continue
                    try:
                        rgb = np.array(Image.open(io.BytesIO(img_bytes)).convert("RGB"))
                    except Exception:
                        continue
                    yield rgb, {
                        "source": "sim_tactile_mnist",
                        "markered": False,
                        "domain": "sim",
                        "capture": f"r{round_id}_t{tj}",
                        "split": split,
                        "obj_name": f"digit_{label}",
                        "digit_class": int(label) if label is not None else None,
                        "episode": str(obj_id) if obj_id is not None else None,
                        "frame_idx": tj,
                    }


def iter_sim_starstruck():
    """Sim Star-Struck (Taxim Mini-calibrated). Same schema as sim_tactile_mnist
    but objects are star-shapes instead of digits.
    """
    root = f"{BASE_DATA}/markerless/SimStarStruck"
    pq_files = sorted(glob(f"{root}/data/*.parquet"))
    for p in pq_files:
        fn = os.path.basename(p).lower()
        if "test" in fn: split = "test"
        elif "val" in fn: split = "val"
        else: split = "train"
        pf = pq.ParquetFile(p)
        for batch in pf.iter_batches(batch_size=8):
            cols = batch.to_pydict()
            n = len(cols.get("label", cols.get("id", [])))
            for i in range(n):
                round_id = cols.get("id", [None]*n)[i]
                obj_id = cols.get("object_id", [None]*n)[i]
                images = cols["sensor_image"][i] or []
                for tj, img_struct in enumerate(images):
                    if not img_struct: continue
                    img_bytes = img_struct.get("bytes") if isinstance(img_struct, dict) else None
                    if not img_bytes: continue
                    try:
                        rgb = np.array(Image.open(io.BytesIO(img_bytes)).convert("RGB"))
                    except Exception:
                        continue
                    yield rgb, {
                        "source": "sim_starstruck",
                        "markered": False,
                        "domain": "sim",
                        "capture": f"r{round_id}_t{tj}",
                        "split": split,
                        "obj_name": "starstruck",
                        "episode": str(obj_id) if obj_id is not None else None,
                        "frame_idx": tj,
                    }


def iter_tacquad_mini():
    """TacQuad multi-sensor → keep only the GelSight Mini frames per
    `contact_*.csv` index ranges.
    """
    import csv
    root = f"{BASE_DATA}/multi_sensor/TacQuad"
    # extracted layout: per-object folders + contact_*.csv index files
    csv_files = sorted(glob(f"{root}/**/contact_*.csv", recursive=True))
    for csv_path in csv_files:
        sub_dir = os.path.dirname(csv_path)
        split = "train"  # tacquad has no formal splits in csv naming
        with open(csv_path) as f:
            reader = csv.DictReader(f)
            for row in reader:
                folder = row.get("folder", "")
                try:
                    mini_start = int(row.get("GelSight Mini start", "-1") or -1)
                    mini_end   = int(row.get("GelSight Mini end",   "-1") or -1)
                except Exception:
                    continue
                if mini_start < 0 or mini_end < 0: continue
                obj_folder = os.path.join(sub_dir, folder)
                # The Mini frames live in a per-sensor subfolder; common layouts:
                #   <folder>/gelsight_mini/<idx>.png
                #   <folder>/GelSight_Mini/<idx>.png
                cand_dirs = [
                    os.path.join(obj_folder, "gelsight_mini"),
                    os.path.join(obj_folder, "GelSight_Mini"),
                    os.path.join(obj_folder, "gs_mini"),
                ]
                d = next((c for c in cand_dirs if os.path.isdir(c)), None)
                if d is None: continue
                for idx in range(mini_start, mini_end + 1):
                    for ext in (".png", ".jpg", ".jpeg"):
                        fp = os.path.join(d, f"{idx}{ext}")
                        if os.path.isfile(fp):
                            try:
                                rgb = np.array(Image.open(fp).convert("RGB"))
                            except Exception:
                                rgb = None
                            if rgb is None: continue
                            text = row.get("text", "")
                            yield rgb, {
                                "source": "tacquad_mini",
                                "markered": False,
                                "domain": "real",
                                "capture": f"{folder}_{idx}",
                                "split": split,
                                "obj_name": folder,
                                "episode": folder,
                                "frame_idx": idx,
                            }
                            break


SOURCE_ITERS = {
    "gelslam":            iter_gelslam,
    "tactile_tracking":   iter_tactile_tracking,
    "real_tactile_mnist": iter_real_tactile_mnist,
    "feelanyforce":       iter_feelanyforce,
    "sim_tactile_mnist":  iter_sim_tactile_mnist,
    "sim_starstruck":     iter_sim_starstruck,
    "tacquad_mini":       iter_tacquad_mini,
}

# Per-source overrides for the validity filter.
# FAF: data is pre-curated, every frame is an indentation moment, baseline median
#      includes contact frames -> filter must be disabled.
# RTM: we already pick 1 middle frame per video, every frame is peak contact ->
#      filter unnecessary.
# Video sources: keep filter active (baseline = median of first 10 frames
#      typically captures the pre-contact prologue).
SKIP_EMPTY_FILTER = {
    "feelanyforce":       True,
    "real_tactile_mnist": True,
    "gelslam":            False,
    "tactile_tracking":   False,
    "sim_tactile_mnist":  True,   # sim frames already at peak contact by construction
    "sim_starstruck":     True,
    "tacquad_mini":       True,   # tacquad CSV already picks contact frames
}


# ─────────────────────────────────────────────────────────────────
# Probe pass: measure dynamism + empty fraction per source.
# Samples N frames per capture and computes |frame - capture_baseline|.
# ─────────────────────────────────────────────────────────────────

def probe(sub: str, n_per_capture=30, max_total=2000):
    print(f"probe {sub}...", flush=True)
    by_cap = defaultdict(list)
    total = 0
    for fr, meta in SOURCE_ITERS[sub]():
        c = meta["capture"]
        if len(by_cap[c]) < n_per_capture:
            by_cap[c].append(fr)
            total += 1
        if total >= max_total:
            break

    # Per-capture baseline = median over the sampled frames
    deltas, dynamisms = [], []
    for c, frames in by_cap.items():
        if len(frames) < 3:
            continue
        stack = np.stack([grey_center(f) for f in frames], axis=0)
        baseline = np.median(stack, axis=0)
        deformation = np.abs(stack - baseline).mean(axis=(1, 2))
        deltas.extend(deformation.tolist())
        # dynamism = mean inter-frame |Δ|
        diffs = np.abs(stack[1:] - stack[:-1]).mean(axis=(1, 2))
        dynamisms.extend(diffs.tolist())

    deltas = np.array(deltas)
    dyn = np.array(dynamisms) if dynamisms else np.array([0.0])
    empty_frac = float((deltas < EMPTY_TAU).mean()) if len(deltas) else 0.0
    return {
        "n_probed_frames":   total,
        "n_probed_captures": len(by_cap),
        "mean_dynamism":     float(dyn.mean()),
        "median_dynamism":   float(np.median(dyn)),
        "mean_deformation":  float(deltas.mean()) if len(deltas) else 0.0,
        "empty_frac":        empty_frac,
        "n_captures_with_3plus_frames": int(sum(1 for c, fs in by_cap.items() if len(fs) >= 3)),
    }


# ─────────────────────────────────────────────────────────────────
# Two-pass full processing:
#   pass 1: scan ALL frames; per capture, store baseline + count valid + collect phashes
#   pass 2: re-iterate, apply stride+validity+dedupe; write parquet
# To avoid two full scans (RTM is large), we do a single streaming pass:
#   - maintain a per-capture rolling baseline from first 10 frames
#   - then for subsequent frames in same capture, compute validity online
#   - apply stride based on a target_keep_per_capture pre-computed at probe time
# ─────────────────────────────────────────────────────────────────

class ShardWriter:
    def __init__(self, out_dir, prefix):
        self.out_dir = out_dir
        self.prefix = prefix
        os.makedirs(out_dir, exist_ok=True)
        self.rows = []
        self.shard_idx = 0
        self.total = 0
        self.bytes_in = 0

    def add(self, row):
        # ensure all keys present
        row = {f.name: row.get(f.name) for f in SCHEMA}
        self.rows.append(row)
        self.bytes_in += len(row["image"]) if row["image"] else 0
        self.total += 1
        if self.bytes_in >= SHARD_TGT:
            self._flush()

    def _flush(self):
        if not self.rows: return
        # Build columns
        cols = {f.name: [r[f.name] for r in self.rows] for f in SCHEMA}
        t = pa.Table.from_pydict(cols, schema=SCHEMA)
        path = f"{self.out_dir}/{self.prefix}-{self.shard_idx:05d}.parquet"
        pq.write_table(t, path, compression="snappy")
        print(f"  wrote {path}  rows={len(self.rows)}  bytes={self.bytes_in/1e9:.2f}GB",
              flush=True)
        self.shard_idx += 1
        self.rows = []
        self.bytes_in = 0

    def close(self):
        self._flush()
        # rename shards to "PREFIX-NNNNN-of-NNNNN.parquet"
        files = sorted(glob(f"{self.out_dir}/{self.prefix}-?????.parquet"))
        total_shards = len(files)
        for i, fp in enumerate(files):
            base = os.path.dirname(fp)
            new = f"{base}/{self.prefix}-{i:05d}-of-{total_shards:05d}.parquet"
            if fp != new:
                os.rename(fp, new)


def process(sub: str, probe_info: dict):
    """Run pipeline on one source and write parquet shards."""
    print(f"\n=== processing {sub} ===", flush=True)

    # Decide global stride
    dyn = probe_info["mean_dynamism"]
    # Estimate effective contact frames after empty filter
    # (We'll re-tune as we go since we don't know R_total precisely)
    # Target = BUDGET. We adjust the stride live by checking running fill rate.
    target = BUDGET

    # Group by split, write to <sub>/<split>-####.parquet
    out_dir = f"{BASE_OUT}/{sub}"
    writers: dict[str, ShardWriter] = {}

    n_seen = 0
    n_empty_dropped = 0
    n_dup_dropped = 0
    n_stride_dropped = 0
    n_kept = 0
    n_empty_passed = 0
    cur_capture = None
    cap_seen_within = 0
    cap_baseline = None
    cap_buffer: list[np.ndarray] = []
    cap_phashes: list[int] = []

    # We compute capture-baseline as the median of the first 10 frames seen
    BASE_FRAMES = 10

    def finish_capture():
        # nothing to do per se; arrays cleared on capture change
        pass

    t0 = time.time()
    stride_state = {"stride": 1.0, "accum": 0.0}

    for fr, meta in SOURCE_ITERS[sub]():
        cap = meta["capture"]
        if cap != cur_capture:
            finish_capture()
            cur_capture = cap
            cap_seen_within = 0
            cap_baseline = None
            cap_buffer = []
            cap_phashes = []

        g_center = grey_center(fr)
        skip_empty = SKIP_EMPTY_FILTER.get(sub, False)

        # Build baseline from first BASE_FRAMES (only when validity filter is active)
        if not skip_empty and cap_baseline is None:
            cap_buffer.append(g_center)
            cap_seen_within += 1
            n_seen += 1
            if len(cap_buffer) >= BASE_FRAMES:
                cap_baseline = np.median(np.stack(cap_buffer, axis=0), axis=0)
            continue

        n_seen += 1
        if skip_empty:
            is_empty = False
        else:
            # Area + intensity validity rule (replaces former mean-deform tau)
            pixel_diff = np.abs(g_center - cap_baseline)
            mask = pixel_diff > PIXEL_THRESH
            contact_area = int(mask.sum())
            contact_intensity = float(pixel_diff[mask].mean()) if contact_area > 0 else 0.0
            thresh = VALIDITY_THRESH.get(sub, dict(A_min=200, I_min=12))
            is_empty = (contact_area < thresh["A_min"]) \
                       or (contact_intensity < thresh["I_min"])

        # Stride decision (uniform stride based on target/total estimate later)
        # We use a live rate-limiter: every K frames, keep 1 (K adjusted live)
        stride_state["accum"] += 1.0
        if stride_state["accum"] < stride_state["stride"]:
            n_stride_dropped += 1
            continue
        stride_state["accum"] -= stride_state["stride"]

        # Empty-budget: allow up to EMPTY_BUDGET fraction of kept frames to be empty
        if is_empty:
            # Allow only if we're under budget
            if n_empty_passed >= EMPTY_BUDGET * max(n_kept, 1):
                n_empty_dropped += 1
                continue

        # Dedupe via phash within capture
        h = phash(fr)
        is_dup = any(hamming(h, hh) <= PHASH_DIST for hh in cap_phashes[-30:])
        if is_dup:
            n_dup_dropped += 1
            continue
        cap_phashes.append(h)

        # Keep!
        img_bytes = encode_jpeg(fr)
        row = dict(meta)
        row["image"] = img_bytes
        row["image_format"] = "jpeg"
        row["height"] = int(fr.shape[0])
        row["width"] = int(fr.shape[1])
        if is_empty:
            n_empty_passed += 1
        n_kept += 1

        split = row.get("split", "train") or "train"
        if split not in writers:
            writers[split] = ShardWriter(out_dir, split)
        writers[split].add(row)

        # Adapt stride live: aim for target frames over the source.
        # We don't know R_total, but we tweak so that fill rate is sensible.
        # If n_kept exceeds BUDGET, raise stride aggressively.
        if n_kept > 0 and n_kept % 5000 == 0:
            if n_kept > BUDGET:
                stride_state["stride"] = max(1.0, stride_state["stride"] * 1.5)
            elif n_kept > BUDGET * 0.95:
                stride_state["stride"] = max(1.0, stride_state["stride"] * 1.2)

        # Hard cap
        if n_kept >= BUDGET:
            print(f"  reached BUDGET={BUDGET}, stopping iteration", flush=True)
            break

        if n_seen % 20000 == 0:
            dt = time.time() - t0
            print(f"  seen={n_seen:,}  kept={n_kept:,}  "
                  f"empty_drop={n_empty_dropped:,}  dup_drop={n_dup_dropped:,}  "
                  f"stride_drop={n_stride_dropped:,}  "
                  f"({n_seen/max(dt,0.01):.0f} fps)", flush=True)

    for w in writers.values():
        w.close()

    stats = {
        "source":           sub,
        "n_seen":           n_seen,
        "n_kept":           n_kept,
        "n_empty_dropped":  n_empty_dropped,
        "n_empty_passed":   n_empty_passed,
        "n_dup_dropped":    n_dup_dropped,
        "n_stride_dropped": n_stride_dropped,
        "splits":           {k: w.total for k, w in writers.items()},
        "wall_time_sec":    time.time() - t0,
    }
    with open(f"/home/yxma/MultimodalData/stats_v2_{sub}.json", "w") as f:
        json.dump(stats, f, indent=2)
    print(f"  {sub} stats: {stats}", flush=True)
    return stats


# ─────────────────────────────────────────────────────────────────
# CLI
# ─────────────────────────────────────────────────────────────────

def cmd_probe(sub):
    info = probe(sub)
    out = f"/home/yxma/MultimodalData/probe_{sub}.json"
    with open(out, "w") as f:
        json.dump(info, f, indent=2)
    print(json.dumps(info, indent=2))
    print(f"saved {out}")


def cmd_process(sub):
    probe_file = f"/home/yxma/MultimodalData/probe_{sub}.json"
    if os.path.exists(probe_file):
        info = json.load(open(probe_file))
    else:
        info = probe(sub)
        with open(probe_file, "w") as f:
            json.dump(info, f, indent=2)
    process(sub, info)


def cmd_stats():
    totals = {}
    for sub in os.listdir(BASE_OUT):
        p = f"{BASE_OUT}/{sub}"
        if not os.path.isdir(p): continue
        paths = sorted(glob(f"{p}/*.parquet"))
        n = sum(pq.read_metadata(x).num_rows for x in paths)
        bytes_total = sum(os.path.getsize(x) for x in paths)
        totals[sub] = {"rows": n, "bytes": bytes_total, "shards": len(paths)}
    print(json.dumps(totals, indent=2))


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print(__doc__); sys.exit(1)
    cmd = sys.argv[1]
    if cmd == "probe":
        cmd_probe(sys.argv[2])
    elif cmd == "process":
        cmd_process(sys.argv[2])
    elif cmd == "stats":
        cmd_stats()
    else:
        print(f"unknown command: {cmd}"); sys.exit(1)