| |
| """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 |
| SHARD_TGT = 2 * 1024 ** 3 |
|
|
| |
| |
| |
| PIXEL_THRESH = 10 |
| EMPTY_BUDGET = 0.03 |
| PHASH_DIST = 4 |
|
|
| |
| |
| VALIDITY_THRESH = { |
| "gelslam": dict(A_min=200, I_min=12), |
| "tactile_tracking": dict(A_min=200, I_min=12), |
| |
| |
| |
| } |
|
|
| |
| 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()), |
| |
| ("episode", pa.string()), |
| ("frame_idx", pa.int32()), |
| ("digit_class", pa.int32()), |
| ("gel_variant", pa.string()), |
| |
| ("domain", pa.string()), |
| ]) |
|
|
|
|
| |
| |
| |
|
|
| 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) |
| |
| 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:]) |
| 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") |
|
|
|
|
| |
| |
| |
| |
| |
| |
|
|
| def iter_gelslam(): |
| """GelSLAM: gelsight.avi per episode under tracking_dataset/ and reconstruction_dataset/.""" |
| import cv2 |
| root = f"{BASE_DATA}/markerless/GelSLAM" |
| |
| 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] |
| 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)) |
| 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]))] |
|
|
| |
| 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, |
| "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" |
| |
| 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" |
| 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) |
| |
| |
| |
| 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, |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| SKIP_EMPTY_FILTER = { |
| "feelanyforce": True, |
| "real_tactile_mnist": True, |
| "gelslam": False, |
| "tactile_tracking": False, |
| "sim_tactile_mnist": True, |
| "sim_starstruck": True, |
| "tacquad_mini": True, |
| } |
|
|
|
|
| |
| |
| |
| |
|
|
| 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 |
|
|
| |
| 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()) |
| |
| 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)), |
| } |
|
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| 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): |
| |
| 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 |
| |
| 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() |
| |
| 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) |
|
|
| |
| dyn = probe_info["mean_dynamism"] |
| |
| |
| |
| target = BUDGET |
|
|
| |
| 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] = [] |
|
|
| |
| BASE_FRAMES = 10 |
|
|
| def finish_capture(): |
| |
| 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) |
|
|
| |
| 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: |
| |
| 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_state["accum"] += 1.0 |
| if stride_state["accum"] < stride_state["stride"]: |
| n_stride_dropped += 1 |
| continue |
| stride_state["accum"] -= stride_state["stride"] |
|
|
| |
| if is_empty: |
| |
| if n_empty_passed >= EMPTY_BUDGET * max(n_kept, 1): |
| n_empty_dropped += 1 |
| continue |
|
|
| |
| 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) |
|
|
| |
| 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) |
|
|
| |
| |
| |
| 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) |
|
|
| |
| 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 |
|
|
|
|
| |
| |
| |
|
|
| 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) |
|
|