yxma commited on
Commit
5b1daed
·
verified ·
1 Parent(s): 0599962

scripts: update make_parquet_v2.py for v3 schema (domain column) + 10-subset coverage

Browse files
Files changed (1) hide show
  1. scripts/make_parquet_v2.py +218 -35
scripts/make_parquet_v2.py CHANGED
@@ -35,9 +35,23 @@ BASE_DATA = "/media/yxma/Disk1/yuxiang/mini_data"
35
  BASE_OUT = "/media/yxma/Disk1/yuxiang/mini_data_parquet"
36
  BUDGET = 200_000 # max kept frames per source
37
  SHARD_TGT = 2 * 1024 ** 3 # 2 GB shard target
38
- EMPTY_TAU = 4.0 # mean |frame - baseline| threshold (greylevels)
39
- EMPTY_BUDGET= 0.03 # allow up to 3% empties through
40
- PHASH_DIST = 4 # max hamming distance for "duplicate"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
  # Existing schema + 3 new nullable cols
43
  SCHEMA = pa.schema([
@@ -71,6 +85,8 @@ SCHEMA = pa.schema([
71
  ("frame_idx", pa.int32()),
72
  ("digit_class", pa.int32()),
73
  ("gel_variant", pa.string()),
 
 
74
  ])
75
 
76
 
@@ -189,16 +205,29 @@ def iter_tactile_tracking():
189
 
190
  def iter_real_tactile_mnist():
191
  """RTM seq-320x240: parquet with 'sensor_video' list-of-struct{bytes,path}.
192
- Each row is one 'round' = one digit touched ~256 times. Each touch video
193
- is 60-75 frames long but the actual contact window is only ~6 frames
194
- (typically near the end of the video). We pick the frame at the *middle
195
- of the touch window* using `touch_start_time_rel` / `touch_end_time_rel`
196
- plus the per-frame `time_stamp_rel_seq`. As a fallback when timestamps
197
- are missing or stale, we pick the frame with highest central std.
 
 
 
 
 
 
 
 
 
 
198
  """
199
  import cv2
200
  root = f"{BASE_DATA}/markerless/RealTactileMNIST"
201
  pq_files = sorted(glob(f"{root}/data/*.parquet"))
 
 
 
202
  for p in pq_files:
203
  split = "test" if "test" in os.path.basename(p).lower() else "train"
204
  pf = pq.ParquetFile(p)
@@ -220,41 +249,47 @@ def iter_real_tactile_mnist():
220
  tmpf = f"/tmp/_rtm_{os.getpid()}.mp4"
221
  with open(tmpf, "wb") as f: f.write(vid_bytes)
222
  cap = cv2.VideoCapture(tmpf)
223
- frames = []
224
  while True:
225
  ok, fr = cap.read()
226
  if not ok: break
227
- frames.append(fr[:, :, ::-1])
 
 
 
 
228
  cap.release()
229
  try: os.remove(tmpf)
230
  except: pass
231
- if not frames: continue
 
 
 
232
 
233
- pick_idx = None
234
- # Try timestamp-based pick first
235
  try:
236
  ts = ts_seq[tj] if tj < len(ts_seq) else None
237
  ts0 = t_start[tj] if tj < len(t_start) else None
238
  ts1 = t_end[tj] if tj < len(t_end) else None
239
  if ts is not None and ts0 is not None and ts1 is not None \
240
  and len(ts) == len(frames):
241
- t_mid = (ts0 + (ts1 - ts0) / 2)
242
- diffs = [abs((t - t_mid).total_seconds()) for t in ts]
243
- pick_idx = int(np.argmin(diffs))
244
  except Exception:
245
- pick_idx = None
246
-
247
- # Fallback: frame with max central-region std
248
- if pick_idx is None:
249
- stds = []
250
- for fr in frames:
251
- g = np.asarray(Image.fromarray(fr).convert("L"),
252
- dtype=np.float32)
253
- h, w = g.shape
254
- stds.append(float(g[h//4:3*h//4, w//4:3*w//4].std()))
255
- pick_idx = int(np.argmax(stds))
256
-
257
- yield frames[pick_idx], {
258
  "source": "real_tactile_mnist",
259
  "markered": False,
260
  "capture": f"r{round_id}_t{tj}",
@@ -262,7 +297,7 @@ def iter_real_tactile_mnist():
262
  "obj_name": f"digit_{label}",
263
  "digit_class": int(label) if label is not None else None,
264
  "episode": str(obj_id) if obj_id is not None else None,
265
- "frame_idx": pick_idx,
266
  }
267
 
268
 
@@ -290,11 +325,151 @@ def iter_feelanyforce():
290
  }
291
 
292
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293
  SOURCE_ITERS = {
294
  "gelslam": iter_gelslam,
295
  "tactile_tracking": iter_tactile_tracking,
296
  "real_tactile_mnist": iter_real_tactile_mnist,
297
  "feelanyforce": iter_feelanyforce,
 
 
 
298
  }
299
 
300
  # Per-source overrides for the validity filter.
@@ -309,6 +484,9 @@ SKIP_EMPTY_FILTER = {
309
  "real_tactile_mnist": True,
310
  "gelslam": False,
311
  "tactile_tracking": False,
 
 
 
312
  }
313
 
314
 
@@ -460,7 +638,7 @@ def process(sub: str, probe_info: dict):
460
  g_center = grey_center(fr)
461
  skip_empty = SKIP_EMPTY_FILTER.get(sub, False)
462
 
463
- # Build baseline from first BASE_FRAMES (only when empty-filter is active)
464
  if not skip_empty and cap_baseline is None:
465
  cap_buffer.append(g_center)
466
  cap_seen_within += 1
@@ -471,11 +649,16 @@ def process(sub: str, probe_info: dict):
471
 
472
  n_seen += 1
473
  if skip_empty:
474
- deformation = 0.0
475
  is_empty = False
476
  else:
477
- deformation = float(np.abs(g_center - cap_baseline).mean())
478
- is_empty = deformation < EMPTY_TAU
 
 
 
 
 
 
479
 
480
  # Stride decision (uniform stride based on target/total estimate later)
481
  # We use a live rate-limiter: every K frames, keep 1 (K adjusted live)
 
35
  BASE_OUT = "/media/yxma/Disk1/yuxiang/mini_data_parquet"
36
  BUDGET = 200_000 # max kept frames per source
37
  SHARD_TGT = 2 * 1024 ** 3 # 2 GB shard target
38
+
39
+ # Validity filter area + intensity rule (replaces former mean-deform tau).
40
+ # A frame is valid iff, on the central-50%-crop |frame - baseline| diff:
41
+ # n_pixels_above(PIXEL_THRESH) >= A_min AND their mean diff >= I_min
42
+ PIXEL_THRESH = 10 # sensor-noise floor, grey-levels
43
+ EMPTY_BUDGET = 0.03 # ≤ 3 % of kept frames may sneak below A_min/I_min
44
+ PHASH_DIST = 4 # max hamming distance for "duplicate"
45
+
46
+ # Per-source validity thresholds (A_min in pixels, I_min in grey-levels).
47
+ # Calibrated visually for each sensor/recording style.
48
+ VALIDITY_THRESH = {
49
+ "gelslam": dict(A_min=200, I_min=12),
50
+ "tactile_tracking": dict(A_min=200, I_min=12),
51
+ # All non-listed sources are entered in SKIP_EMPTY_FILTER below and use
52
+ # source-specific selection (e.g. RTM has its own area+intensity inside
53
+ # the iterator).
54
+ }
55
 
56
  # Existing schema + 3 new nullable cols
57
  SCHEMA = pa.schema([
 
85
  ("frame_idx", pa.int32()),
86
  ("digit_class", pa.int32()),
87
  ("gel_variant", pa.string()),
88
+ # v3 — distinguish real-world capture vs synthetic
89
+ ("domain", pa.string()), # "real" | "sim"
90
  ])
91
 
92
 
 
205
 
206
  def iter_real_tactile_mnist():
207
  """RTM seq-320x240: parquet with 'sensor_video' list-of-struct{bytes,path}.
208
+
209
+ Frame-picking strategy (v4 area+intensity rule):
210
+ 1. Decode all frames in the touch video clip (~60-73 frames).
211
+ 2. Compute a per-clip baseline = median of first 5 frames (no-contact prologue).
212
+ 3. Use `touch_start_time_rel`/`touch_end_time_rel` to find frames inside
213
+ the contact window. Within that window, pick the frame with maximum
214
+ mean-|diff| from baseline (the peak-contact frame).
215
+ 4. On the picked frame, compute:
216
+ pixel_diff = |frame - baseline| on central 50% crop (grey-levels)
217
+ mask = pixel_diff > PIXEL_THRESH (default 10)
218
+ contact_area = mask.sum() (in pixels)
219
+ contact_int = pixel_diff[mask].mean() (avg deformation in lit pixels)
220
+ 5. Keep iff `contact_area >= RTM_A_MIN` AND `contact_int >= RTM_I_MIN`.
221
+ Tunables: RTM_PIXEL_THRESH=10, RTM_A_MIN=40, RTM_I_MIN=15.
222
+ Probe at these values: ~16% keep, ~24K final rows, every kept frame
223
+ visually shows a clear digit-edge imprint.
224
  """
225
  import cv2
226
  root = f"{BASE_DATA}/markerless/RealTactileMNIST"
227
  pq_files = sorted(glob(f"{root}/data/*.parquet"))
228
+ PIXEL_THRESH = 10
229
+ A_MIN = 40
230
+ I_MIN = 15
231
  for p in pq_files:
232
  split = "test" if "test" in os.path.basename(p).lower() else "train"
233
  pf = pq.ParquetFile(p)
 
249
  tmpf = f"/tmp/_rtm_{os.getpid()}.mp4"
250
  with open(tmpf, "wb") as f: f.write(vid_bytes)
251
  cap = cv2.VideoCapture(tmpf)
252
+ frames = []; grays = []
253
  while True:
254
  ok, fr = cap.read()
255
  if not ok: break
256
+ rgb = fr[:, :, ::-1]
257
+ frames.append(rgb)
258
+ g = cv2.cvtColor(fr, cv2.COLOR_BGR2GRAY).astype(np.float32)
259
+ h, w = g.shape
260
+ grays.append(g[h//4:3*h//4, w//4:3*w//4])
261
  cap.release()
262
  try: os.remove(tmpf)
263
  except: pass
264
+ if len(frames) < 8: continue
265
+
266
+ baseline = np.median(np.stack(grays[:5]), axis=0)
267
+ deforms = [float(np.abs(g - baseline).mean()) for g in grays]
268
 
269
+ in_window = list(range(len(frames)))
 
270
  try:
271
  ts = ts_seq[tj] if tj < len(ts_seq) else None
272
  ts0 = t_start[tj] if tj < len(t_start) else None
273
  ts1 = t_end[tj] if tj < len(t_end) else None
274
  if ts is not None and ts0 is not None and ts1 is not None \
275
  and len(ts) == len(frames):
276
+ in_window = [k for k, t in enumerate(ts) if ts0 <= t <= ts1]
277
+ if not in_window:
278
+ in_window = list(range(len(frames)))
279
  except Exception:
280
+ pass
281
+
282
+ peak_idx = in_window[int(np.argmax([deforms[k] for k in in_window]))]
283
+
284
+ # area + intensity rule on the picked peak frame
285
+ pixel_diff = np.abs(grays[peak_idx] - baseline)
286
+ mask = pixel_diff > PIXEL_THRESH
287
+ contact_area = int(mask.sum())
288
+ if contact_area < A_MIN: continue
289
+ contact_int = float(pixel_diff[mask].mean())
290
+ if contact_int < I_MIN: continue
291
+
292
+ yield frames[peak_idx], {
293
  "source": "real_tactile_mnist",
294
  "markered": False,
295
  "capture": f"r{round_id}_t{tj}",
 
297
  "obj_name": f"digit_{label}",
298
  "digit_class": int(label) if label is not None else None,
299
  "episode": str(obj_id) if obj_id is not None else None,
300
+ "frame_idx": peak_idx,
301
  }
302
 
303
 
 
325
  }
326
 
327
 
328
+ def iter_sim_tactile_mnist():
329
+ """Sim Tactile MNIST seq-320x240 (Taxim Mini-calibrated).
330
+ Schema: parquet rows, each row = one digit, with `sensor_image` = list of
331
+ 32 JPEG-bytes structs (one image per touch, already at peak contact).
332
+ No video decoding, no filtering — sim frames are by construction valid.
333
+ """
334
+ root = f"{BASE_DATA}/markerless/SimTactileMNIST"
335
+ pq_files = sorted(glob(f"{root}/data/*.parquet"))
336
+ for p in pq_files:
337
+ fn = os.path.basename(p).lower()
338
+ if "test" in fn: split = "test"
339
+ elif "val" in fn: split = "val"
340
+ else: split = "train"
341
+ pf = pq.ParquetFile(p)
342
+ for batch in pf.iter_batches(batch_size=8):
343
+ cols = batch.to_pydict()
344
+ n = len(cols.get("label", cols.get("id", [])))
345
+ for i in range(n):
346
+ round_id = cols.get("id", [None]*n)[i]
347
+ label = cols.get("label", [None]*n)[i]
348
+ obj_id = cols.get("object_id", [None]*n)[i]
349
+ images = cols["sensor_image"][i] or []
350
+ for tj, img_struct in enumerate(images):
351
+ if not img_struct: continue
352
+ img_bytes = img_struct.get("bytes") if isinstance(img_struct, dict) else None
353
+ if not img_bytes: continue
354
+ try:
355
+ rgb = np.array(Image.open(io.BytesIO(img_bytes)).convert("RGB"))
356
+ except Exception:
357
+ continue
358
+ yield rgb, {
359
+ "source": "sim_tactile_mnist",
360
+ "markered": False,
361
+ "domain": "sim",
362
+ "capture": f"r{round_id}_t{tj}",
363
+ "split": split,
364
+ "obj_name": f"digit_{label}",
365
+ "digit_class": int(label) if label is not None else None,
366
+ "episode": str(obj_id) if obj_id is not None else None,
367
+ "frame_idx": tj,
368
+ }
369
+
370
+
371
+ def iter_sim_starstruck():
372
+ """Sim Star-Struck (Taxim Mini-calibrated). Same schema as sim_tactile_mnist
373
+ but objects are star-shapes instead of digits.
374
+ """
375
+ root = f"{BASE_DATA}/markerless/SimStarStruck"
376
+ pq_files = sorted(glob(f"{root}/data/*.parquet"))
377
+ for p in pq_files:
378
+ fn = os.path.basename(p).lower()
379
+ if "test" in fn: split = "test"
380
+ elif "val" in fn: split = "val"
381
+ else: split = "train"
382
+ pf = pq.ParquetFile(p)
383
+ for batch in pf.iter_batches(batch_size=8):
384
+ cols = batch.to_pydict()
385
+ n = len(cols.get("label", cols.get("id", [])))
386
+ for i in range(n):
387
+ round_id = cols.get("id", [None]*n)[i]
388
+ obj_id = cols.get("object_id", [None]*n)[i]
389
+ images = cols["sensor_image"][i] or []
390
+ for tj, img_struct in enumerate(images):
391
+ if not img_struct: continue
392
+ img_bytes = img_struct.get("bytes") if isinstance(img_struct, dict) else None
393
+ if not img_bytes: continue
394
+ try:
395
+ rgb = np.array(Image.open(io.BytesIO(img_bytes)).convert("RGB"))
396
+ except Exception:
397
+ continue
398
+ yield rgb, {
399
+ "source": "sim_starstruck",
400
+ "markered": False,
401
+ "domain": "sim",
402
+ "capture": f"r{round_id}_t{tj}",
403
+ "split": split,
404
+ "obj_name": "starstruck",
405
+ "episode": str(obj_id) if obj_id is not None else None,
406
+ "frame_idx": tj,
407
+ }
408
+
409
+
410
+ def iter_tacquad_mini():
411
+ """TacQuad multi-sensor → keep only the GelSight Mini frames per
412
+ `contact_*.csv` index ranges.
413
+ """
414
+ import csv
415
+ root = f"{BASE_DATA}/multi_sensor/TacQuad"
416
+ # extracted layout: per-object folders + contact_*.csv index files
417
+ csv_files = sorted(glob(f"{root}/**/contact_*.csv", recursive=True))
418
+ for csv_path in csv_files:
419
+ sub_dir = os.path.dirname(csv_path)
420
+ split = "train" # tacquad has no formal splits in csv naming
421
+ with open(csv_path) as f:
422
+ reader = csv.DictReader(f)
423
+ for row in reader:
424
+ folder = row.get("folder", "")
425
+ try:
426
+ mini_start = int(row.get("GelSight Mini start", "-1") or -1)
427
+ mini_end = int(row.get("GelSight Mini end", "-1") or -1)
428
+ except Exception:
429
+ continue
430
+ if mini_start < 0 or mini_end < 0: continue
431
+ obj_folder = os.path.join(sub_dir, folder)
432
+ # The Mini frames live in a per-sensor subfolder; common layouts:
433
+ # <folder>/gelsight_mini/<idx>.png
434
+ # <folder>/GelSight_Mini/<idx>.png
435
+ cand_dirs = [
436
+ os.path.join(obj_folder, "gelsight_mini"),
437
+ os.path.join(obj_folder, "GelSight_Mini"),
438
+ os.path.join(obj_folder, "gs_mini"),
439
+ ]
440
+ d = next((c for c in cand_dirs if os.path.isdir(c)), None)
441
+ if d is None: continue
442
+ for idx in range(mini_start, mini_end + 1):
443
+ for ext in (".png", ".jpg", ".jpeg"):
444
+ fp = os.path.join(d, f"{idx}{ext}")
445
+ if os.path.isfile(fp):
446
+ try:
447
+ rgb = np.array(Image.open(fp).convert("RGB"))
448
+ except Exception:
449
+ rgb = None
450
+ if rgb is None: continue
451
+ text = row.get("text", "")
452
+ yield rgb, {
453
+ "source": "tacquad_mini",
454
+ "markered": False,
455
+ "domain": "real",
456
+ "capture": f"{folder}_{idx}",
457
+ "split": split,
458
+ "obj_name": folder,
459
+ "episode": folder,
460
+ "frame_idx": idx,
461
+ }
462
+ break
463
+
464
+
465
  SOURCE_ITERS = {
466
  "gelslam": iter_gelslam,
467
  "tactile_tracking": iter_tactile_tracking,
468
  "real_tactile_mnist": iter_real_tactile_mnist,
469
  "feelanyforce": iter_feelanyforce,
470
+ "sim_tactile_mnist": iter_sim_tactile_mnist,
471
+ "sim_starstruck": iter_sim_starstruck,
472
+ "tacquad_mini": iter_tacquad_mini,
473
  }
474
 
475
  # Per-source overrides for the validity filter.
 
484
  "real_tactile_mnist": True,
485
  "gelslam": False,
486
  "tactile_tracking": False,
487
+ "sim_tactile_mnist": True, # sim frames already at peak contact by construction
488
+ "sim_starstruck": True,
489
+ "tacquad_mini": True, # tacquad CSV already picks contact frames
490
  }
491
 
492
 
 
638
  g_center = grey_center(fr)
639
  skip_empty = SKIP_EMPTY_FILTER.get(sub, False)
640
 
641
+ # Build baseline from first BASE_FRAMES (only when validity filter is active)
642
  if not skip_empty and cap_baseline is None:
643
  cap_buffer.append(g_center)
644
  cap_seen_within += 1
 
649
 
650
  n_seen += 1
651
  if skip_empty:
 
652
  is_empty = False
653
  else:
654
+ # Area + intensity validity rule (replaces former mean-deform tau)
655
+ pixel_diff = np.abs(g_center - cap_baseline)
656
+ mask = pixel_diff > PIXEL_THRESH
657
+ contact_area = int(mask.sum())
658
+ contact_intensity = float(pixel_diff[mask].mean()) if contact_area > 0 else 0.0
659
+ thresh = VALIDITY_THRESH.get(sub, dict(A_min=200, I_min=12))
660
+ is_empty = (contact_area < thresh["A_min"]) \
661
+ or (contact_intensity < thresh["I_min"])
662
 
663
  # Stride decision (uniform stride based on target/total estimate later)
664
  # We use a live rate-limiter: every K frames, keep 1 (K adjusted live)