| import argparse |
| import glob |
| import math |
| import os |
| import re |
| from collections.abc import Sized |
| from concurrent.futures import ProcessPoolExecutor, as_completed |
| from pathlib import Path |
| from typing import Dict, List, Optional, Sequence, Tuple |
|
|
| import pyarrow.parquet as pq |
| from datasets import ( |
| Audio as HFAudio, |
| Dataset, |
| DatasetDict, |
| Features, |
| Image as HFImage, |
| Video as HFVideo, |
| load_dataset, |
| ) |
| from tqdm import tqdm |
|
|
|
|
| _MEDIA_FEATURES = Features( |
| { |
| "image": HFImage(), |
| "video": HFVideo(), |
| "audio": HFAudio(), |
| } |
| ) |
| MEDIA_TYPE_COLUMNS = ("image", "video", "audio") |
| MEDIA_ROLES = ("media", "query", "candidate") |
| DEFAULT_ROW_GROUP_SIZE = 100 |
| DEFAULT_MEDIA_ROWS_PER_SHARD = 5000 |
| KNOWN_DATA_SPLITS = ("train", "test", "validation", "valid", "dev") |
|
|
|
|
| def resolve_split_output_dir(output_root, split_name: str, subset_name: str) -> Path: |
| """Resolve the output dir for one subset of a split. |
| |
| Default layout mirrors the Hub repos: ``{output_root}/MVEB-{split}/{subset}``. |
| Override the split root with env ``MVEB_TRAIN_DIR`` / ``MVEB_TEST_DIR`` |
| (e.g. point them at locally downloaded MVEB-train / MVEB-test repos). |
| """ |
| override = os.environ.get(f"MVEB_{split_name.upper()}_DIR") |
| base = Path(override) if override else Path(output_root) / f"MVEB-{split_name}" |
| return base / subset_name |
|
|
|
|
| def _infer_collection_name(dir_path: str) -> str: |
| """Infer collection label from path basename (e.g. ``test`` / ``train`` for Hub repo name).""" |
| return os.path.basename(os.path.normpath(dir_path)) |
|
|
|
|
| def _infer_data_split(path_like: str, default: str = "train") -> str: |
| """Infer split name from path components, fallback to ``default``.""" |
| parts = [p.lower() for p in os.path.normpath(path_like).split(os.sep) if p] |
| for part in reversed(parts): |
| if part in KNOWN_DATA_SPLITS: |
| return part |
| return default |
|
|
|
|
| def infer_media_type(media_row: dict) -> Optional[str]: |
| """Return which media column is set (``image`` / ``video`` / ``audio``).""" |
| for column in MEDIA_TYPE_COLUMNS: |
| if media_row.get(column) is not None: |
| return column |
| return None |
|
|
|
|
| def get_media_payload(media_row: dict): |
| """Return the non-null media payload; raises if the row is empty.""" |
| media_type = infer_media_type(media_row) |
| if media_type is None: |
| raise ValueError("media row has no populated image/video/audio column") |
| return media_row[media_type] |
|
|
|
|
| def _make_media_row( |
| *, |
| image=None, |
| video=None, |
| audio=None, |
| ) -> dict: |
| populated = [ |
| name |
| for name, value in (("image", image), ("video", video), ("audio", audio)) |
| if value is not None |
| ] |
| if len(populated) != 1: |
| raise ValueError(f"exactly one media column must be set, got {populated}") |
| return {"image": image, "video": video, "audio": audio} |
|
|
|
|
| def _read_media_bytes(media_path: str) -> bytes: |
| with open(media_path, "rb") as f: |
| return f.read() |
|
|
|
|
| def _parse_size(size: str) -> int: |
| size = size.strip().upper() |
| m = re.fullmatch(r"(\d+(?:\.\d+)?)\s*([KMGT]?B)", size) |
| if not m: |
| raise ValueError(f"Invalid size string: {size!r}, e.g. 500MB or 1GB") |
| value = float(m.group(1)) |
| unit = m.group(2) |
| scale = {"B": 1, "KB": 1024, "MB": 1024**2, "GB": 1024**3, "TB": 1024**4} |
| return int(value * scale[unit]) |
|
|
|
|
| def _resolve_image_path(image_path: str, image_dir: str) -> str: |
| if not image_path: |
| raise ValueError("empty image_path") |
| if os.path.isabs(image_path) and os.path.exists(image_path): |
| return image_path |
| candidate = os.path.join(image_dir, image_path) |
| if os.path.exists(candidate): |
| return candidate |
| raise FileNotFoundError( |
| f"Image not found: {image_path!r} (image_dir={image_dir!r})" |
| ) |
|
|
|
|
| def _discover_subsets(split_dir: str) -> List[str]: |
| subsets: List[str] = [] |
| for name in sorted(os.listdir(split_dir)): |
| if name == "images": |
| continue |
| sub_path = os.path.join(split_dir, name) |
| if not os.path.isdir(sub_path): |
| continue |
| query_path = os.path.join(sub_path, "query.parquet") |
| candidate_path = os.path.join(sub_path, "candidate.parquet") |
| if os.path.exists(query_path) and os.path.exists(candidate_path): |
| subsets.append(name) |
| return subsets |
|
|
|
|
| def _collect_unique_paths( |
| query_rows: Sequence[dict], |
| candidate_rows: Sequence[dict], |
| ) -> Tuple[List[str], Dict[str, int]]: |
| path_to_index: Dict[str, int] = {} |
| ordered_paths: List[str] = [] |
|
|
| def add_path(path: Optional[str]) -> None: |
| if not path: |
| return |
| if path not in path_to_index: |
| path_to_index[path] = len(ordered_paths) |
| ordered_paths.append(path) |
|
|
| for row in query_rows: |
| add_path(row.get("image_path")) |
| for row in candidate_rows: |
| add_path(row.get("image_path")) |
|
|
| return ordered_paths, path_to_index |
|
|
|
|
| def _rows_with_media_index( |
| rows: Sequence[dict], |
| path_to_index: Dict[str, int], |
| ) -> List[dict]: |
| converted: List[dict] = [] |
| for row in rows: |
| new_row = { |
| k: v |
| for k, v in row.items() |
| if k not in ("image_path", "media_type") |
| } |
| image_path = row.get("image_path") |
| if image_path: |
| new_row["media_index"] = path_to_index[image_path] |
| elif "media_index" not in new_row: |
| raise ValueError(f"row id={row.get('id')}: missing image_path and media_index") |
| converted.append(new_row) |
| return converted |
|
|
|
|
| def _load_media_rows( |
| ordered_paths: Sequence[str], |
| image_dir: str, |
| desc: str = "load images", |
| show_progress: bool = True, |
| ) -> List[dict]: |
| iterator = ordered_paths |
| if show_progress: |
| iterator = tqdm(ordered_paths, desc=desc) |
| media_rows: List[dict] = [] |
| for rel_path in iterator: |
| abs_path = _resolve_image_path(rel_path, image_dir) |
| media_rows.append( |
| _make_media_row(image={"bytes": _read_media_bytes(abs_path), "path": None}) |
| ) |
| return media_rows |
|
|
|
|
| def _estimate_num_shards_by_rows( |
| media_items: Sized, |
| media_rows_per_shard: int, |
| ) -> int: |
| """Shard count for ``media_items`` (media rows or their source paths).""" |
| if media_rows_per_shard < 1: |
| raise ValueError( |
| f"media_rows_per_shard must be >= 1, got {media_rows_per_shard}" |
| ) |
| num_items = len(media_items) |
| if num_items == 0: |
| return 1 |
| return max(1, math.ceil(num_items / media_rows_per_shard)) |
|
|
|
|
| def _write_parquet( |
| rows_or_ds: Sequence[dict] | Dataset, |
| path: str, |
| row_group_size: int, |
| *, |
| features: Optional[Features] = None, |
| ) -> None: |
| """Write parquet with explicit row groups (HF ``batch_size`` = rows per group).""" |
| if row_group_size < 1: |
| raise ValueError(f"row_group_size must be >= 1, got {row_group_size}") |
| if isinstance(rows_or_ds, Dataset): |
| ds = rows_or_ds |
| elif features is not None: |
| ds = Dataset.from_list(list(rows_or_ds), features=features) |
| else: |
| ds = Dataset.from_list(list(rows_or_ds)) |
| ds.to_parquet(path, batch_size=row_group_size) |
|
|
|
|
| def _media_shard_path(output_dir: str, shard_idx: int, num_shards: int) -> str: |
| return os.path.join( |
| output_dir, |
| f"media-{shard_idx:05d}-of-{num_shards:05d}.parquet", |
| ) |
|
|
|
|
| def _write_one_media_shard( |
| shard_idx: int, |
| num_shards: int, |
| shard_paths: Sequence[str], |
| image_dir: str, |
| output_dir: str, |
| row_group_size: int, |
| ) -> Tuple[int, int, str]: |
| shard_rows = _load_media_rows( |
| shard_paths, |
| image_dir, |
| show_progress=False, |
| ) |
| shard = Dataset.from_list(shard_rows, features=_MEDIA_FEATURES) |
| out_path = _media_shard_path(output_dir, shard_idx, num_shards) |
| _write_parquet(shard, out_path, row_group_size) |
| return shard_idx, len(shard_rows), out_path |
|
|
|
|
| def _write_media_shards( |
| ordered_paths: Sequence[str], |
| image_dir: str, |
| output_dir: str, |
| media_rows_per_shard: int, |
| row_group_size: int, |
| num_workers: int, |
| *, |
| desc: str = "media", |
| show_progress: bool = True, |
| ) -> int: |
| os.makedirs(output_dir, exist_ok=True) |
| num_shards = _estimate_num_shards_by_rows(ordered_paths, media_rows_per_shard) |
| for old_path in glob.glob(os.path.join(output_dir, "media-*.parquet")): |
| os.remove(old_path) |
|
|
| shard_specs = [] |
| for shard_idx in range(num_shards): |
| start = shard_idx * media_rows_per_shard |
| end = min(start + media_rows_per_shard, len(ordered_paths)) |
| shard_specs.append((shard_idx, ordered_paths[start:end])) |
|
|
| if num_workers < 1: |
| raise ValueError(f"num_workers must be >= 1, got {num_workers}") |
|
|
| if num_workers == 1 or num_shards == 1: |
| for shard_idx, shard_paths in shard_specs: |
| shard_rows = _load_media_rows( |
| shard_paths, |
| image_dir, |
| desc=f"{desc} shard {shard_idx + 1}/{num_shards}", |
| show_progress=show_progress, |
| ) |
| shard = Dataset.from_list(shard_rows, features=_MEDIA_FEATURES) |
| out_path = _media_shard_path(output_dir, shard_idx, num_shards) |
| _write_parquet(shard, out_path, row_group_size) |
| return num_shards |
|
|
| workers = min(num_workers, num_shards) |
| with ProcessPoolExecutor(max_workers=workers) as executor: |
| futures = [ |
| executor.submit( |
| _write_one_media_shard, |
| shard_idx, |
| num_shards, |
| shard_paths, |
| image_dir, |
| output_dir, |
| row_group_size, |
| ) |
| for shard_idx, shard_paths in shard_specs |
| ] |
| iterator = as_completed(futures) |
| if show_progress: |
| iterator = tqdm( |
| iterator, |
| total=len(futures), |
| desc=f"{desc} shards", |
| ) |
| for future in iterator: |
| future.result() |
|
|
| return num_shards |
|
|
|
|
| def _write_readme( |
| output_dir: str, |
| dataset_name: str, |
| data_split: str, |
| num_media: int, |
| num_query: int, |
| num_candidate: int, |
| query_feature_names: Sequence[str], |
| candidate_feature_names: Sequence[str], |
| ) -> None: |
| readme = _render_subset_readme_yaml( |
| config_name=dataset_name, |
| path_prefix="", |
| data_split=data_split, |
| num_media=num_media, |
| num_query=num_query, |
| num_candidate=num_candidate, |
| query_feature_names=query_feature_names, |
| candidate_feature_names=candidate_feature_names, |
| pretty_name=dataset_name, |
| ) |
| with open(os.path.join(output_dir, "README.md"), "w", encoding="utf-8") as f: |
| f.write(readme) |
|
|
|
|
| def _discover_packed_subsets(output_dir: str) -> List[str]: |
| """Find packed subset folders under a split output root.""" |
| subsets: List[str] = [] |
| for name in sorted(os.listdir(output_dir)): |
| sub_path = os.path.join(output_dir, name) |
| if not os.path.isdir(sub_path): |
| continue |
| if not os.path.exists(os.path.join(sub_path, "query.parquet")): |
| continue |
| if not glob.glob(os.path.join(sub_path, "media-*.parquet")): |
| continue |
| subsets.append(name) |
| return subsets |
|
|
|
|
| def _parquet_num_rows(parquet_path: str) -> int: |
| return pq.read_metadata(parquet_path).num_rows |
|
|
|
|
| def _parquet_column_names(parquet_path: str) -> List[str]: |
| return pq.read_schema(parquet_path).names |
|
|
|
|
| def _media_num_rows(subset_dir: str) -> int: |
| media_files = sorted(glob.glob(os.path.join(subset_dir, "media-*.parquet"))) |
| if not media_files: |
| raise FileNotFoundError(f"No media shards under {subset_dir}") |
| return sum(_parquet_num_rows(path) for path in media_files) |
|
|
|
|
| def _hub_feature_yaml_lines(name: str, indent: str = " ") -> str: |
| inner = indent + " " |
| if name in ("pos_ids", "neg_ids", "pool_ids"): |
| return f"{inner}- name: {name}\n{inner} sequence: string" |
| if name == "scores": |
| return f"{inner}- name: {name}\n{inner} sequence: float64" |
| if name == "media_index": |
| return f"{inner}- name: {name}\n{inner} dtype: int64" |
| return f"{inner}- name: {name}\n{inner} dtype: string" |
|
|
|
|
| def _features_yaml_block(feature_names: Sequence[str], indent: str = " ") -> str: |
| return "\n".join(_hub_feature_yaml_lines(name, indent) for name in feature_names) |
|
|
|
|
| def _media_features_yaml() -> str: |
| inner = " " |
| return ( |
| f"{inner}- name: image\n{inner} dtype: image\n" |
| f"{inner}- name: video\n{inner} dtype: video\n" |
| f"{inner}- name: audio\n{inner} dtype: audio" |
| ) |
|
|
|
|
| def _role_config_name(subset_name: str, role: str) -> str: |
| if role not in MEDIA_ROLES: |
| raise ValueError(f"role must be one of {MEDIA_ROLES}, got {role!r}") |
| return f"{subset_name}_{role}" |
|
|
|
|
| def _render_subset_readme_yaml( |
| *, |
| config_name: str, |
| path_prefix: str, |
| data_split: str, |
| num_media: int, |
| num_query: int, |
| num_candidate: int, |
| query_feature_names: Sequence[str], |
| candidate_feature_names: Sequence[str], |
| pretty_name: Optional[str] = None, |
| ) -> str: |
| media_path = f"{path_prefix}media-*.parquet" if path_prefix else "media-*.parquet" |
| query_path = f"{path_prefix}query.parquet" if path_prefix else "query.parquet" |
| candidate_path = f"{path_prefix}candidate.parquet" if path_prefix else "candidate.parquet" |
| title_line = f"pretty_name: {pretty_name}\n" if pretty_name else "" |
| media_config = _role_config_name(config_name, "media") |
| query_config = _role_config_name(config_name, "query") |
| candidate_config = _role_config_name(config_name, "candidate") |
| return ( |
| "---\n" |
| f"{title_line}" |
| "configs:\n" |
| f"- config_name: {media_config}\n" |
| " data_files:\n" |
| f" - split: {data_split}\n" |
| f" path: {media_path}\n" |
| f"- config_name: {query_config}\n" |
| " data_files:\n" |
| f" - split: {data_split}\n" |
| f" path: {query_path}\n" |
| f"- config_name: {candidate_config}\n" |
| " data_files:\n" |
| f" - split: {data_split}\n" |
| f" path: {candidate_path}\n" |
| "---\n" |
| ) |
|
|
|
|
| def _collect_subset_hub_metadata( |
| subset_name: str, |
| subset_dir: str, |
| ) -> dict: |
| """Build hub README metadata for one subset config (splits: media/query/candidate).""" |
| query_path = os.path.join(subset_dir, "query.parquet") |
| candidate_path = os.path.join(subset_dir, "candidate.parquet") |
| return { |
| "config_name": subset_name, |
| "num_media": _media_num_rows(subset_dir), |
| "num_query": _parquet_num_rows(query_path), |
| "num_candidate": _parquet_num_rows(candidate_path), |
| "query_feature_names": _parquet_column_names(query_path), |
| "candidate_feature_names": _parquet_column_names(candidate_path), |
| } |
|
|
|
|
| def build_hub_readme( |
| output_dir: str, |
| *, |
| data_split: Optional[str] = None, |
| dataset_title: Optional[str] = None, |
| subsets: Optional[Sequence[str]] = None, |
| ) -> str: |
| """ |
| Write a top-level HuggingFace Hub README for all packed subsets under ``output_dir``. |
| |
| One config per subset; HF splits are ``media`` / ``query`` / ``candidate``. |
| Use separate repos or directories (e.g. ``.../test``, ``.../train``) for collections. |
| """ |
| output_dir = os.path.abspath(output_dir) |
| subset_names = list(subsets) if subsets else _discover_packed_subsets(output_dir) |
| if not subset_names: |
| raise ValueError(f"No packed subsets found under {output_dir}") |
|
|
| title = dataset_title or _infer_collection_name(output_dir) |
| split_name = data_split or _infer_data_split(output_dir) |
| config_blocks: List[str] = [] |
| for subset_name in subset_names: |
| _ = _collect_subset_hub_metadata(subset_name, os.path.join(output_dir, subset_name)) |
| config_blocks.append( |
| f"- config_name: {_role_config_name(subset_name, 'media')}\n" |
| " data_files:\n" |
| f" - split: {split_name}\n" |
| f" path: {subset_name}/media-*.parquet\n" |
| f"- config_name: {_role_config_name(subset_name, 'query')}\n" |
| " data_files:\n" |
| f" - split: {split_name}\n" |
| f" path: {subset_name}/query.parquet\n" |
| f"- config_name: {_role_config_name(subset_name, 'candidate')}\n" |
| " data_files:\n" |
| f" - split: {split_name}\n" |
| f" path: {subset_name}/candidate.parquet" |
| ) |
|
|
| readme = ( |
| "---\n" |
| f"pretty_name: {title}\n" |
| "configs:\n" |
| + "\n".join(config_blocks) |
| + "\n---\n" |
| ) |
| readme_path = os.path.join(output_dir, "README.md") |
| with open(readme_path, "w", encoding="utf-8") as f: |
| f.write(readme) |
| return readme_path |
|
|
|
|
| def load_hub_subset( |
| repo_or_path: str, |
| subset_name: str, |
| role: str, |
| data_split: Optional[str] = None, |
| ) -> Dataset: |
| """Load one role dataset for a subset (config: ``{subset}_{role}``, split inferred from path).""" |
| if role not in MEDIA_ROLES: |
| raise ValueError(f"role must be one of {MEDIA_ROLES}, got {role!r}") |
| config_name = _role_config_name(subset_name, role) |
| split_name = data_split or _infer_data_split(repo_or_path) |
| return load_dataset(repo_or_path, config_name, split=split_name) |
|
|
|
|
| def load_hub_subset_dict( |
| repo_or_path: str, |
| subset_name: str, |
| data_split: Optional[str] = None, |
| ) -> DatasetDict: |
| """Load media / query / candidate datasets for one subset.""" |
| return DatasetDict( |
| { |
| "media": load_hub_subset(repo_or_path, subset_name, "media", data_split=data_split), |
| "query": load_hub_subset(repo_or_path, subset_name, "query", data_split=data_split), |
| "candidate": load_hub_subset( |
| repo_or_path, subset_name, "candidate", data_split=data_split |
| ), |
| } |
| ) |
|
|
|
|
| def pack_dataset_with_media( |
| query_annotations: Sequence[dict], |
| candidate_annotations: Sequence[dict], |
| image_dir: str, |
| output_dir: str, |
| *, |
| max_shard_size: str = "500MB", |
| media_rows_per_shard: int = DEFAULT_MEDIA_ROWS_PER_SHARD, |
| num_workers: int = 1, |
| row_group_size: int = DEFAULT_ROW_GROUP_SIZE, |
| dataset_name: Optional[str] = None, |
| data_split: str = "train", |
| write_subset_readme: bool = True, |
| show_progress: bool = True, |
| ) -> Dict[str, int]: |
| query_rows = list(query_annotations) |
| candidate_rows = list(candidate_annotations) |
|
|
| if not query_rows and not candidate_rows: |
| raise ValueError("query_annotations and candidate_annotations are both empty") |
|
|
| ordered_paths, path_to_index = _collect_unique_paths(query_rows, candidate_rows) |
| if not ordered_paths: |
| raise ValueError("No image_path found in query/candidate annotations") |
|
|
| name = dataset_name or os.path.basename(os.path.normpath(output_dir)) |
| |
| _ = max_shard_size |
|
|
| os.makedirs(output_dir, exist_ok=True) |
| num_shards = _write_media_shards( |
| ordered_paths, |
| image_dir, |
| output_dir, |
| media_rows_per_shard, |
| row_group_size, |
| num_workers, |
| desc=f"{name} images", |
| show_progress=show_progress, |
| ) |
|
|
| query_out = _rows_with_media_index(query_rows, path_to_index) |
| candidate_out = _rows_with_media_index(candidate_rows, path_to_index) |
|
|
| _write_parquet(query_out, os.path.join(output_dir, "query.parquet"), row_group_size) |
| _write_parquet( |
| candidate_out, os.path.join(output_dir, "candidate.parquet"), row_group_size |
| ) |
|
|
| if write_subset_readme: |
| _write_readme( |
| output_dir=output_dir, |
| dataset_name=name, |
| data_split=data_split, |
| num_media=len(ordered_paths), |
| num_query=len(query_out), |
| num_candidate=len(candidate_out), |
| query_feature_names=list(query_out[0].keys()) if query_out else [], |
| candidate_feature_names=list(candidate_out[0].keys()) if candidate_out else [], |
| ) |
|
|
| return { |
| "num_media": len(ordered_paths), |
| "num_query": len(query_out), |
| "num_candidate": len(candidate_out), |
| "num_shards": num_shards, |
| } |
|
|
|
|
| def pack_subset_dir( |
| subset_input_dir: str, |
| subset_output_dir: str, |
| image_dir: str, |
| *, |
| subset_name: Optional[str] = None, |
| max_shard_size: str = "500MB", |
| media_rows_per_shard: int = DEFAULT_MEDIA_ROWS_PER_SHARD, |
| num_workers: int = 1, |
| row_group_size: int = DEFAULT_ROW_GROUP_SIZE, |
| data_split: str = "train", |
| write_subset_readme: bool = True, |
| show_progress: bool = True, |
| ) -> Dict[str, int]: |
| query_path = os.path.join(subset_input_dir, "query.parquet") |
| candidate_path = os.path.join(subset_input_dir, "candidate.parquet") |
| if not os.path.exists(query_path): |
| raise FileNotFoundError(f"Missing {query_path}") |
| if not os.path.exists(candidate_path): |
| raise FileNotFoundError(f"Missing {candidate_path}") |
|
|
| query_rows = pq.read_table(query_path).to_pylist() |
| candidate_rows = pq.read_table(candidate_path).to_pylist() |
|
|
| return pack_dataset_with_media( |
| query_rows, |
| candidate_rows, |
| image_dir=image_dir, |
| output_dir=subset_output_dir, |
| max_shard_size=max_shard_size, |
| media_rows_per_shard=media_rows_per_shard, |
| num_workers=num_workers, |
| row_group_size=row_group_size, |
| dataset_name=subset_name or os.path.basename(subset_input_dir), |
| data_split=data_split, |
| write_subset_readme=write_subset_readme, |
| show_progress=show_progress, |
| ) |
|
|
|
|
| def pack_split_dir( |
| input_dir: str, |
| output_dir: str, |
| *, |
| image_dir: Optional[str] = None, |
| max_shard_size: str = "500MB", |
| media_rows_per_shard: int = DEFAULT_MEDIA_ROWS_PER_SHARD, |
| num_workers: int = 1, |
| row_group_size: int = DEFAULT_ROW_GROUP_SIZE, |
| subsets: Optional[Sequence[str]] = None, |
| write_subset_readme: bool = True, |
| write_hub_readme: bool = True, |
| hub_dataset_title: Optional[str] = None, |
| show_progress: bool = True, |
| ) -> Dict[str, Dict[str, int]]: |
| """ |
| Iterate all subsets under a split directory and pack each to |
| ``{output_dir}/{subset_name}/``. |
| """ |
| input_dir = os.path.abspath(input_dir) |
| output_dir = os.path.abspath(output_dir) |
| image_root = os.path.abspath(image_dir or input_dir) |
| split_name = _infer_data_split(input_dir) |
|
|
| subset_names = list(subsets) if subsets else _discover_subsets(input_dir) |
| if not subset_names: |
| raise ValueError(f"No subsets with query/candidate parquet found under {input_dir}") |
|
|
| os.makedirs(output_dir, exist_ok=True) |
| all_stats: Dict[str, Dict[str, int]] = {} |
|
|
| subset_iter = subset_names |
| if show_progress: |
| subset_iter = tqdm(subset_names, desc="subsets") |
|
|
| for subset_name in subset_iter: |
| subset_input = os.path.join(input_dir, subset_name) |
| subset_output = os.path.join(output_dir, subset_name) |
| stats = pack_subset_dir( |
| subset_input, |
| subset_output, |
| image_dir=image_root, |
| subset_name=subset_name, |
| max_shard_size=max_shard_size, |
| media_rows_per_shard=media_rows_per_shard, |
| num_workers=num_workers, |
| row_group_size=row_group_size, |
| data_split=split_name, |
| write_subset_readme=write_subset_readme, |
| show_progress=show_progress, |
| ) |
| all_stats[subset_name] = stats |
| if show_progress and not isinstance(subset_iter, tqdm): |
| print( |
| f"[{subset_name}] media={stats['num_media']} " |
| f"({stats['num_shards']} shards), " |
| f"query={stats['num_query']}, candidate={stats['num_candidate']}" |
| ) |
|
|
| if write_hub_readme and all_stats: |
| hub_path = build_hub_readme( |
| output_dir, |
| data_split=split_name, |
| dataset_title=hub_dataset_title, |
| subsets=list(all_stats.keys()), |
| ) |
| if show_progress: |
| print(f"Hub README: {hub_path}") |
| return all_stats |
|
|
|
|
| def _build_argparser() -> argparse.ArgumentParser: |
| parser = argparse.ArgumentParser( |
| description="Pack all subsets under a split dir into media_index format.", |
| ) |
| parser.add_argument( |
| "--input-dir", |
| help="Split directory, e.g. data/preprocess/Identity/test", |
| ) |
| parser.add_argument( |
| "--output-dir", |
| required=True, |
| help="Output root; each subset is written to {output_dir}/{subset_name}/", |
| ) |
| parser.add_argument( |
| "--image-dir", |
| default=None, |
| help="Root for relative image_path values (defaults to input-dir)", |
| ) |
| parser.add_argument( |
| "--max-shard-size", |
| default="500MB", |
| help=( |
| "Deprecated. Previously used for byte-based media shard sizing; " |
| "kept for compatibility." |
| ), |
| ) |
| parser.add_argument( |
| "--media-rows-per-shard", |
| type=int, |
| default=DEFAULT_MEDIA_ROWS_PER_SHARD, |
| help=f"Fixed number of media rows per shard (default: {DEFAULT_MEDIA_ROWS_PER_SHARD})", |
| ) |
| parser.add_argument( |
| "--num-workers", |
| type=int, |
| default=4, |
| help="Number of worker processes for media shard writing (default: 1)", |
| ) |
| parser.add_argument( |
| "--row-group-size", |
| type=int, |
| default=DEFAULT_ROW_GROUP_SIZE, |
| help=( |
| "Rows per parquet row group for media/query/candidate " |
| f"(default: {DEFAULT_ROW_GROUP_SIZE}, same as colpali_train_set)" |
| ), |
| ) |
| parser.add_argument( |
| "--no-subset-readme", |
| action="store_true", |
| help="Do not write per-subset README.md (Hub root README only)", |
| ) |
| parser.add_argument( |
| "--no-hub-readme", |
| action="store_true", |
| help="Do not write top-level Hub README.md under output-dir", |
| ) |
| parser.add_argument( |
| "--hub-readme-only", |
| action="store_true", |
| help="Only (re)generate top-level Hub README from existing packed subsets", |
| ) |
| parser.add_argument( |
| "--hub-dataset-title", |
| default=None, |
| help="pretty_name for top-level Hub README (default: output-dir basename)", |
| ) |
| parser.add_argument( |
| "--subsets", |
| nargs="*", |
| default=None, |
| help="Process only these subset names (default: all under input-dir)", |
| ) |
| parser.add_argument( |
| "--no-progress", |
| action="store_true", |
| help="Disable progress bars", |
| ) |
| return parser |
|
|
|
|
| def main() -> None: |
| args = _build_argparser().parse_args() |
| if args.hub_readme_only: |
| if not args.output_dir: |
| raise SystemExit("--output-dir is required with --hub-readme-only") |
| hub_path = build_hub_readme( |
| args.output_dir, |
| data_split=_infer_data_split(args.output_dir), |
| dataset_title=args.hub_dataset_title, |
| subsets=args.subsets, |
| ) |
| print(f"Hub README written: {hub_path}") |
| return |
|
|
| if not args.input_dir: |
| raise SystemExit("--input-dir is required unless --hub-readme-only is set") |
| if not args.output_dir: |
| raise SystemExit("--output-dir is required") |
| all_stats = pack_split_dir( |
| input_dir=args.input_dir, |
| output_dir=args.output_dir, |
| image_dir=args.image_dir, |
| max_shard_size=args.max_shard_size, |
| media_rows_per_shard=args.media_rows_per_shard, |
| num_workers=args.num_workers, |
| row_group_size=args.row_group_size, |
| subsets=args.subsets, |
| write_subset_readme=not args.no_subset_readme, |
| write_hub_readme=not args.no_hub_readme, |
| hub_dataset_title=args.hub_dataset_title, |
| show_progress=not args.no_progress, |
| ) |
| print(f"Done: {len(all_stats)} subsets -> {args.output_dir}") |
| for subset_name, stats in all_stats.items(): |
| print( |
| f" {subset_name}: media={stats['num_media']} " |
| f"({stats['num_shards']} shards), " |
| f"query={stats['num_query']}, candidate={stats['num_candidate']}" |
| ) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|