Download training_yutubeasl/scripts/1_preprocess.py from SignerX/SignX: direct link, hf CLI and curl.
- Browser
- Download file 15.4 kB
-
https://huggingface.co/datasets/SignerX/SignX/resolve/main/training_yutubeasl/scripts/1_preprocess.py
- Command line
-
hf download hf://datasets/SignerX/SignX/training_yutubeasl/scripts/1_preprocess.py
-
curl -L -o 1_preprocess.py https://huggingface.co/datasets/SignerX/SignX/resolve/main/training_yutubeasl/scripts/1_preprocess.py
15.4 kB
| """ | |
| YouTubeASL Dataset Preprocessing for SMKD | |
| Generates {mode}_info.npy and gloss_dict.npy in the same format as Phoenix/CSL-Daily. | |
| """ | |
| import argparse | |
| import csv | |
| import os | |
| import random | |
| import re | |
| from collections import Counter | |
| import numpy as np | |
| BASE_COLUMNS = {"VIDEO_NAME", "CLIP_INDEX", "CLIP_PATH"} | |
| def _str2bool(value): | |
| if isinstance(value, bool): | |
| return value | |
| if value is None: | |
| return False | |
| value = str(value).strip().lower() | |
| if value in {"1", "true", "yes", "y", "t"}: | |
| return True | |
| if value in {"0", "false", "no", "n", "f"}: | |
| return False | |
| raise ValueError(f"Invalid boolean value: {value}") | |
| def _normalize_label(raw_text, label_column): | |
| text = (raw_text or "").strip() | |
| if not text: | |
| return "" | |
| if label_column.upper() == "TEXT": | |
| normalized = text.lower() | |
| normalized = re.sub(r"[^\w']+", " ", normalized) | |
| normalized = " ".join(normalized.split()) | |
| return normalized | |
| return " ".join(text.split()) | |
| def _read_manifest(manifest_path, label_column, video_root=None): | |
| samples = [] | |
| skipped = {"missing": 0, "empty": 0, "no_text": 0} | |
| with open(manifest_path, "r", encoding="utf-8") as f: | |
| reader = csv.DictReader(f, delimiter="\t") | |
| fieldnames = reader.fieldnames or [] | |
| field_map = {name.upper(): name for name in fieldnames} | |
| required = {c.upper() for c in BASE_COLUMNS} | |
| required.add(label_column.upper()) | |
| missing = sorted([c for c in required if c not in field_map]) | |
| if missing: | |
| raise ValueError( | |
| f"Manifest missing required columns: {missing}. " | |
| f"Available: {fieldnames}" | |
| ) | |
| video_key = field_map["VIDEO_NAME"] | |
| clip_index_key = field_map["CLIP_INDEX"] | |
| clip_path_key = field_map["CLIP_PATH"] | |
| label_key = field_map[label_column.upper()] | |
| start_key = field_map.get("START") | |
| end_key = field_map.get("END") | |
| for row in reader: | |
| clip_path = (row.get(clip_path_key) or "").strip() | |
| raw_label = (row.get(label_key) or "").strip() | |
| label = _normalize_label(raw_label, label_column) | |
| if not label: | |
| skipped["no_text"] += 1 | |
| continue | |
| if video_root and clip_path and not os.path.isabs(clip_path): | |
| clip_path = os.path.join(video_root, clip_path) | |
| if not clip_path or not os.path.exists(clip_path): | |
| skipped["missing"] += 1 | |
| continue | |
| if os.path.getsize(clip_path) == 0: | |
| skipped["empty"] += 1 | |
| continue | |
| video_name = (row.get(video_key) or "").strip() | |
| clip_index_raw = (row.get(clip_index_key) or "").strip() | |
| try: | |
| clip_index = int(clip_index_raw) | |
| file_id = f"{video_name}_{clip_index:04d}" | |
| except ValueError: | |
| file_id = f"{video_name}_{clip_index_raw}" | |
| sample = { | |
| "id": file_id, | |
| "video_name": video_name, | |
| "clip_index": clip_index_raw, | |
| "label": label, | |
| "clip_path": clip_path, | |
| "start": (row.get(start_key) or "").strip() if start_key else "", | |
| "end": (row.get(end_key) or "").strip() if end_key else "", | |
| } | |
| samples.append(sample) | |
| return samples, skipped | |
| def _split_by_video(samples, seed, val_size, test_size): | |
| groups = {} | |
| for sample in samples: | |
| groups.setdefault(sample["video_name"], []).append(sample) | |
| rng = random.Random(seed) | |
| video_names = list(groups.keys()) | |
| rng.shuffle(video_names) | |
| train, val, test = [], [], [] | |
| for video_name in video_names: | |
| group = groups[video_name] | |
| if len(test) < test_size: | |
| test.extend(group) | |
| continue | |
| if len(val) < val_size: | |
| val.extend(group) | |
| continue | |
| train.extend(group) | |
| return train, val, test | |
| def _move_one_video_group(src, dst): | |
| if not src: | |
| return False | |
| video_name = src[0]["video_name"] | |
| group = [s for s in src if s["video_name"] == video_name] | |
| if not group: | |
| return False | |
| src[:] = [s for s in src if s["video_name"] != video_name] | |
| dst.extend(group) | |
| return True | |
| def preprocess_youtubeasl( | |
| manifest_path, | |
| label_column, | |
| output_dir, | |
| prefix_for_smkd=None, | |
| seed=1234, | |
| val_size=300, | |
| test_size=100, | |
| sample_ratio=1.0, | |
| val_ratio=None, | |
| test_ratio=None, | |
| dev_from_train_count=0, | |
| dev_from_train_keep=False, | |
| video_root=None, | |
| frames_root=None, | |
| min_frames=0, | |
| max_frames=0, | |
| evaluation_prefix="youtubeasl-groundtruth", | |
| ): | |
| print(f"Loading manifest: {manifest_path}") | |
| samples, skipped = _read_manifest( | |
| manifest_path, label_column=label_column, video_root=video_root | |
| ) | |
| print(f"Total samples: {len(samples)}") | |
| if not (0 < sample_ratio <= 1.0): | |
| raise ValueError(f"sample_ratio must be in (0, 1], got {sample_ratio}") | |
| if sample_ratio < 1.0: | |
| rng = random.Random(seed) | |
| rng.shuffle(samples) | |
| keep = max(1, int(len(samples) * sample_ratio)) | |
| samples = samples[:keep] | |
| print(f"Sampled {len(samples)} samples ({sample_ratio:.2%} of manifest)") | |
| if any(skipped.values()): | |
| print( | |
| "Skipped samples: " | |
| + ", ".join(f"{k}={v}" for k, v in skipped.items() if v) | |
| ) | |
| if val_ratio is not None or test_ratio is not None: | |
| if val_ratio is None or test_ratio is None: | |
| raise ValueError("Both val_ratio and test_ratio must be set when using ratios") | |
| if not (0 <= val_ratio < 1.0 and 0 <= test_ratio < 1.0): | |
| raise ValueError("val_ratio and test_ratio must be in [0, 1)") | |
| if val_ratio + test_ratio >= 1.0: | |
| raise ValueError("val_ratio + test_ratio must be < 1.0") | |
| val_size = max(1, int(len(samples) * val_ratio)) if val_ratio > 0 else 0 | |
| test_size = max(1, int(len(samples) * test_ratio)) if test_ratio > 0 else 0 | |
| print( | |
| f"Using ratio-based split: val={val_ratio:.2%} ({val_size}), " | |
| f"test={test_ratio:.2%} ({test_size})" | |
| ) | |
| train_samples, val_samples, test_samples = _split_by_video( | |
| samples, seed=seed, val_size=val_size, test_size=test_size | |
| ) | |
| # Ensure non-empty dev/test splits when possible by moving one video group. | |
| if len(val_samples) == 0: | |
| moved = _move_one_video_group(train_samples, val_samples) | |
| if not moved: | |
| _move_one_video_group(test_samples, val_samples) | |
| if len(val_samples) > 0: | |
| print(f"Adjusted split to ensure non-empty dev; dev={len(val_samples)}") | |
| if len(test_samples) == 0: | |
| moved = _move_one_video_group(train_samples, test_samples) | |
| if not moved: | |
| _move_one_video_group(val_samples, test_samples) | |
| if len(test_samples) > 0: | |
| print(f"Adjusted split to ensure non-empty test; test={len(test_samples)}") | |
| if dev_from_train_count and train_samples: | |
| rng = random.Random(seed) | |
| rng.shuffle(train_samples) | |
| count = min(int(dev_from_train_count), len(train_samples)) | |
| val_samples = train_samples[:count] | |
| if not dev_from_train_keep: | |
| train_samples = train_samples[count:] | |
| print(f"Dev set overridden by {count} sample(s) from train (removed from train).") | |
| else: | |
| print(f"Dev set overridden by {count} sample(s) from train (kept in train).") | |
| elif dev_from_train_count and not train_samples: | |
| print("Warning: dev_from_train_count set but train split is empty; dev unchanged.") | |
| if len(val_samples) < val_size or len(test_samples) < test_size: | |
| print( | |
| "Warning: requested split sizes not reached. " | |
| f"val={len(val_samples)} (target {val_size}), " | |
| f"test={len(test_samples)} (target {test_size})." | |
| ) | |
| if len(val_samples) > val_size or len(test_samples) > test_size: | |
| print( | |
| "Note: split sizes exceeded targets due to grouping by VIDEO_NAME. " | |
| f"val={len(val_samples)} (target {val_size}), " | |
| f"test={len(test_samples)} (target {test_size})." | |
| ) | |
| splits = { | |
| "train": train_samples, | |
| "dev": val_samples, | |
| "test": test_samples, | |
| } | |
| print( | |
| f"Split - Train: {len(train_samples)}, Dev: {len(val_samples)}, Test: {len(test_samples)}" | |
| ) | |
| os.makedirs(output_dir, exist_ok=True) | |
| if frames_root: | |
| frames_root = os.path.abspath(frames_root) | |
| prefix_for_smkd = frames_root | |
| kept_by_split = {} | |
| for mode, samples_list in splits.items(): | |
| info_dict = {"prefix": prefix_for_smkd} | |
| kept = 0 | |
| kept_samples = [] | |
| for sample in samples_list: | |
| frame_count = -1 | |
| if frames_root: | |
| clip_name = os.path.splitext(os.path.basename(sample["clip_path"]))[0] | |
| folder_path = os.path.join(sample["video_name"], clip_name, "crop_frame", "*.jpg") | |
| abs_dir = os.path.join(frames_root, sample["video_name"], clip_name, "crop_frame") | |
| if not os.path.isdir(abs_dir): | |
| continue | |
| frame_count = len([p for p in os.listdir(abs_dir) if p.lower().endswith(".jpg")]) | |
| if min_frames and frame_count < min_frames: | |
| continue | |
| if max_frames and frame_count > max_frames: | |
| continue | |
| else: | |
| folder_path = sample["clip_path"] | |
| info_dict[kept] = { | |
| "fileid": sample["id"], | |
| "folder": folder_path, | |
| "signer": "Unknown", | |
| "label": sample["label"], | |
| "num_frames": frame_count, | |
| "original_info": (sample, kept, sample["id"]), | |
| } | |
| kept += 1 | |
| kept_samples.append(sample) | |
| info_path = os.path.join(output_dir, f"{mode}_info.npy") | |
| np.save(info_path, info_dict) | |
| print(f"Saved {mode}_info.npy with {kept} samples") | |
| kept_by_split[mode] = kept_samples | |
| gloss_counter = Counter() | |
| for kept_samples in kept_by_split.values(): | |
| for sample in kept_samples: | |
| gloss_counter.update(sample["label"].split()) | |
| gloss_dict = {} | |
| for idx, (gloss, count) in enumerate(sorted(gloss_counter.items()), start=1): | |
| gloss_dict[gloss] = [idx, count] | |
| gloss_dict_path = os.path.join(output_dir, "gloss_dict.npy") | |
| np.save(gloss_dict_path, gloss_dict) | |
| print(f"Saved gloss_dict.npy with {len(gloss_dict)} glosses") | |
| for mode, kept_samples in kept_by_split.items(): | |
| stm_path = os.path.join(output_dir, f"{evaluation_prefix}-{mode}.stm") | |
| with open(stm_path, "w", encoding="utf-8") as f: | |
| for sample in kept_samples: | |
| utt_id = sample["id"] | |
| gloss = sample["label"] | |
| signer = "Unknown" | |
| f.write(f"{utt_id} 1 {signer} 0.0 1.79769e+308 {gloss}\n") | |
| print(f"Saved {stm_path}") | |
| print("\nPreprocessing complete!") | |
| print(f"Output directory: {output_dir}") | |
| print("Files generated:") | |
| print(" - gloss_dict.npy") | |
| print(" - train_info.npy, dev_info.npy, test_info.npy") | |
| print( | |
| f" - {evaluation_prefix}-train.stm, {evaluation_prefix}-dev.stm, {evaluation_prefix}-test.stm" | |
| ) | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser( | |
| description="Preprocess YouTubeASL dataset for SMKD (video inputs)." | |
| ) | |
| parser.add_argument( | |
| "--manifest-path", | |
| type=str, | |
| default="../../../YouTubeASL/video1000size/manifest_top1000.tsv", | |
| help="Path to manifest_top1000.tsv (relative to scripts/)", | |
| ) | |
| parser.add_argument( | |
| "--label-column", | |
| type=str, | |
| default="TEXT", | |
| help="Column to use as label (e.g., TEXT or GLOSS).", | |
| ) | |
| parser.add_argument( | |
| "--video-root", | |
| type=str, | |
| default="../../../YouTubeASL", | |
| help="Root for relative CLIP_PATH entries (relative to scripts/)", | |
| ) | |
| parser.add_argument( | |
| "--prefix-for-smkd", | |
| type=str, | |
| default="", | |
| help="Prefix stored in info.npy; leave empty to use absolute clip paths", | |
| ) | |
| parser.add_argument( | |
| "--output-dir", | |
| type=str, | |
| default="../../smkd/youtubeasl", | |
| help="Output directory for preprocessed files", | |
| ) | |
| parser.add_argument("--seed", type=int, default=1234, help="Random seed") | |
| parser.add_argument( | |
| "--val-size", | |
| type=int, | |
| default=300, | |
| help="Validation split size (by clips)", | |
| ) | |
| parser.add_argument( | |
| "--test-size", | |
| type=int, | |
| default=100, | |
| help="Test split size (by clips)", | |
| ) | |
| parser.add_argument( | |
| "--val-ratio", | |
| type=float, | |
| default=None, | |
| help="Validation split ratio over the sampled manifest (e.g., 0.06)", | |
| ) | |
| parser.add_argument( | |
| "--test-ratio", | |
| type=float, | |
| default=None, | |
| help="Test split ratio over the sampled manifest (e.g., 0.04)", | |
| ) | |
| parser.add_argument( | |
| "--dev-from-train-count", | |
| type=int, | |
| default=0, | |
| help="Override dev split with N samples drawn from train.", | |
| ) | |
| parser.add_argument( | |
| "--dev-from-train-keep", | |
| type=_str2bool, | |
| default=False, | |
| help="Keep dev samples in train when overriding dev split.", | |
| ) | |
| parser.add_argument( | |
| "--sample-ratio", | |
| type=float, | |
| default=1.0, | |
| help="Randomly sample this fraction of the manifest before splitting", | |
| ) | |
| parser.add_argument( | |
| "--frames-root", | |
| type=str, | |
| default="../../../YouTubeASL/video1000size_frames", | |
| help="Root directory containing extracted frames (relative to scripts/).", | |
| ) | |
| parser.add_argument( | |
| "--min-frames", | |
| type=int, | |
| default=5, | |
| help="Minimum number of frames required when using extracted frames.", | |
| ) | |
| parser.add_argument( | |
| "--evaluation-prefix", | |
| type=str, | |
| default="youtubeasl-groundtruth", | |
| help="Prefix for generated STM files", | |
| ) | |
| args = parser.parse_args() | |
| prefix_for_smkd = args.prefix_for_smkd if args.prefix_for_smkd else None | |
| video_root = args.video_root if args.video_root else None | |
| frames_root = args.frames_root if args.frames_root else None | |
| min_frames = args.min_frames if args.min_frames else 0 | |
| if frames_root and not prefix_for_smkd: | |
| prefix_for_smkd = frames_root | |
| preprocess_youtubeasl( | |
| manifest_path=args.manifest_path, | |
| label_column=args.label_column, | |
| output_dir=args.output_dir, | |
| prefix_for_smkd=prefix_for_smkd, | |
| seed=args.seed, | |
| val_size=args.val_size, | |
| test_size=args.test_size, | |
| sample_ratio=args.sample_ratio, | |
| val_ratio=args.val_ratio, | |
| test_ratio=args.test_ratio, | |
| dev_from_train_count=args.dev_from_train_count, | |
| dev_from_train_keep=args.dev_from_train_keep, | |
| video_root=video_root, | |
| frames_root=frames_root, | |
| min_frames=min_frames, | |
| evaluation_prefix=args.evaluation_prefix, | |
| ) | |