| |
| """Process MultiID-2M for MVEB: crop, build annotations from split JSON, pack parquet.""" |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import shutil |
| import sys |
| import threading |
| from concurrent.futures import ThreadPoolExecutor, as_completed |
| from pathlib import Path |
| from typing import Dict, List, Sequence, Tuple |
|
|
| from PIL import Image |
| from tqdm import tqdm |
|
|
| _SCRIPTS_ROOT = Path(__file__).resolve().parent.parent |
| if str(_SCRIPTS_ROOT) not in sys.path: |
| sys.path.insert(0, str(_SCRIPTS_ROOT)) |
| from pack_media_parquet import pack_dataset_with_media, resolve_split_output_dir |
|
|
| SCRIPT_DIR = Path(__file__).resolve().parent |
| ROOT_DIR = SCRIPT_DIR.parent.parent.parent |
|
|
| QUERY_INSTRUCTION = "You are a helpful assistant." |
| QUERY_TEXT = "Represent the face in the given image." |
| CANDIDATE_INSTRUCTION = "You are a helpful assistant." |
| CANDIDATE_TEXT = "Represent all faces in the given image." |
|
|
|
|
| def crop_faces(source_dir: Path, *, num_workers: int = 10, force: bool = False) -> None: |
| """Crop faces from train_cp json/jpg pairs into cropped_grounding_cp_images.""" |
| train_cp_dir = source_dir / "train_cp" |
| cropped_dir = source_dir / "cropped_grounding_cp_images" |
| if not train_cp_dir.is_dir(): |
| raise FileNotFoundError(f"Missing train_cp dir: {train_cp_dir}") |
|
|
| cropped_dir.mkdir(parents=True, exist_ok=True) |
| subdirs = sorted(d.name for d in train_cp_dir.iterdir() if d.is_dir()) |
| if not subdirs: |
| raise FileNotFoundError(f"No extracted shards under {train_cp_dir}") |
|
|
| lock = threading.Lock() |
| fail_count = 0 |
|
|
| def process_subdir(subdir: str) -> int: |
| local_fail = 0 |
| anno_files = sorted((train_cp_dir / subdir).glob("*.json")) |
| for anno_file in tqdm(anno_files, desc=f"crop {subdir}", leave=False): |
| try: |
| anno = json.loads(anno_file.read_text(encoding="utf-8")) |
| img_path = anno_file.with_suffix(".jpg") |
| if not img_path.is_file(): |
| local_fail += 1 |
| continue |
| crop_box = anno["crop"] |
| img = Image.open(img_path) |
| for i, bbox in enumerate(anno["bboxes"]): |
| inst_id = str(anno["name"][i]) |
| out_name = f"{img_path.stem}_{inst_id}.jpg" |
| out_path = cropped_dir / subdir / out_name |
| if out_path.is_file() and not force: |
| continue |
| face_bbox = [ |
| bbox[0] - crop_box[0], |
| bbox[1] - crop_box[1], |
| bbox[2] - crop_box[0], |
| bbox[3] - crop_box[1], |
| ] |
| out_path.parent.mkdir(parents=True, exist_ok=True) |
| img.crop(face_bbox).save(out_path) |
| except Exception: |
| local_fail += 1 |
| return local_fail |
|
|
| with ThreadPoolExecutor(max_workers=num_workers) as executor: |
| futures = {executor.submit(process_subdir, subdir): subdir for subdir in subdirs} |
| for future in tqdm(as_completed(futures), total=len(futures), desc="Cropping shards"): |
| local_fail = future.result() |
| with lock: |
| fail_count += local_fail |
|
|
| if fail_count: |
| print(f"[warn] crop failed samples: {fail_count}") |
|
|
|
|
| def _parse_query_instance_id(query_rel_path: str) -> str: |
| |
| stem = Path(query_rel_path).stem |
| if "_" not in stem: |
| raise ValueError(f"Invalid query filename (expect *_<instance>): {query_rel_path}") |
| return stem.rsplit("_", 1)[1] |
|
|
|
|
| def _candidate_json_rel_path(candidate_rel_path: str) -> str: |
| |
| return str(Path(candidate_rel_path).with_suffix(".json")).replace("\\", "/") |
|
|
|
|
| def _load_split(split_json: Path) -> Dict[str, List[str]]: |
| data = json.loads(split_json.read_text(encoding="utf-8")) |
| for key in ("train", "test"): |
| if key not in data or not isinstance(data[key], list): |
| raise ValueError(f"{split_json} must contain {key!r} list") |
| return data |
|
|
|
|
| def _build_annotations_for_split( |
| split_name: str, |
| split_paths: Sequence[str], |
| source_dir: Path, |
| ) -> Tuple[List[dict], List[dict]]: |
| """Build annotations from split JSON per user-specified logic. |
| |
| - candidates: all `train_cp/...` images in split |
| - query: all `cropped_grounding_cp_images/...` images in split |
| - candidate instance mapping: parse corresponding train_cp/*.json `name` list |
| - query pos_ids: mapping_dict[query_instance_id] |
| """ |
| candidate_paths = sorted({p.replace("\\", "/") for p in split_paths if p.startswith("train_cp/")}) |
| query_paths = sorted( |
| {p.replace("\\", "/") for p in split_paths if p.startswith("cropped_grounding_cp_images/")} |
| ) |
| if not candidate_paths or not query_paths: |
| raise ValueError( |
| f"[{split_name}] split must contain both train_cp and cropped_grounding_cp_images paths" |
| ) |
|
|
| candidate_rows: List[dict] = [] |
| inst_to_candidate_ids: Dict[str, List[str]] = {} |
|
|
| for idx, rel_path in tqdm(enumerate(candidate_paths), total=len(candidate_paths), desc="Building candidate rows"): |
| abs_path = source_dir / rel_path |
| if not abs_path.is_file(): |
| raise FileNotFoundError(f"[{split_name}] missing candidate image: {abs_path}") |
|
|
| anno_rel = _candidate_json_rel_path(rel_path) |
| anno_abs = source_dir / anno_rel |
| if not anno_abs.is_file(): |
| raise FileNotFoundError(f"[{split_name}] missing candidate json: {anno_abs}") |
|
|
| anno = json.loads(anno_abs.read_text(encoding="utf-8")) |
| instance_ids = [str(x) for x in anno.get("name", [])] |
| if not instance_ids: |
| continue |
|
|
| candidate_rows.append( |
| { |
| "id": rel_path, |
| |
| "instance_id": "|".join(sorted(set(instance_ids))), |
| "image_path": rel_path, |
| "instruction": CANDIDATE_INSTRUCTION, |
| "text": CANDIDATE_TEXT, |
| } |
| ) |
| for inst_id in set(instance_ids): |
| inst_to_candidate_ids.setdefault(inst_id, []).append(rel_path) |
|
|
| query_rows: List[dict] = [] |
| missing_pos = 0 |
| for rel_path in tqdm(query_paths, total=len(query_paths), desc="Building query rows"): |
| abs_path = source_dir / rel_path |
| if not abs_path.is_file(): |
| raise FileNotFoundError(f"[{split_name}] missing query image: {abs_path}") |
|
|
| inst_id = _parse_query_instance_id(rel_path) |
| pos_ids = inst_to_candidate_ids.get(inst_id, []) |
| if not pos_ids: |
| missing_pos += 1 |
| continue |
|
|
| query_rows.append( |
| { |
| "id": rel_path, |
| "instance_id": inst_id, |
| "image_path": rel_path, |
| "instruction": QUERY_INSTRUCTION, |
| "text": QUERY_TEXT, |
| "pos_ids": sorted(set(pos_ids)), |
| } |
| ) |
|
|
| if missing_pos: |
| print(f"[{split_name}] warn: {missing_pos} query images have no matched candidate") |
| if not query_rows or not candidate_rows: |
| raise ValueError(f"[{split_name}] empty query/candidate after building") |
| return query_rows, candidate_rows |
|
|
|
|
| def _process_one_split( |
| split_name: str, |
| split_paths: Sequence[str], |
| source_dir: Path, |
| output_root: Path, |
| overwrite: bool, |
| media_rows_per_shard: int, |
| row_group_size: int, |
| num_workers: int, |
| ) -> None: |
| out_dir = resolve_split_output_dir(output_root, split_name, "MultiID") |
| if overwrite and out_dir.exists(): |
| shutil.rmtree(out_dir) |
| out_dir.mkdir(parents=True, exist_ok=True) |
|
|
| query_rows, candidate_rows = _build_annotations_for_split(split_name, split_paths, source_dir) |
| stats = pack_dataset_with_media( |
| query_annotations=query_rows, |
| candidate_annotations=candidate_rows, |
| image_dir=str(source_dir), |
| output_dir=str(out_dir), |
| media_rows_per_shard=media_rows_per_shard, |
| row_group_size=row_group_size, |
| num_workers=num_workers, |
| dataset_name="MultiID", |
| data_split=split_name, |
| write_subset_readme=True, |
| show_progress=True, |
| ) |
| print( |
| f"[{split_name}] done: media={stats['num_media']}, " |
| f"query={stats['num_query']}, candidate={stats['num_candidate']}, " |
| f"shards={stats['num_shards']} -> {out_dir}" |
| ) |
|
|
|
|
| def parse_args() -> argparse.Namespace: |
| parser = argparse.ArgumentParser(description=__doc__) |
| parser.add_argument( |
| "--source-dir", |
| type=Path, |
| default=ROOT_DIR / "source" / "MultiID-2M", |
| help="Root containing train_cp/ and cropped_grounding_cp_images/.", |
| ) |
| parser.add_argument( |
| "--split-json", |
| type=Path, |
| default=SCRIPT_DIR / "train_test_split.json", |
| help="JSON with split image paths (train_cp + cropped_grounding_cp_images).", |
| ) |
| parser.add_argument( |
| "--skip-crop", |
| action="store_true", |
| help="Skip face cropping; require existing cropped images + anno file.", |
| ) |
| parser.add_argument( |
| "--force-crop", |
| action="store_true", |
| help="Re-crop even if cropped jpg already exists.", |
| ) |
| parser.add_argument("--crop-workers", type=int, default=10) |
| parser.add_argument("--output-root", type=Path, default=ROOT_DIR) |
| parser.add_argument("--overwrite", action="store_true") |
| parser.add_argument("--media-rows-per-shard", type=int, default=5000) |
| parser.add_argument("--row-group-size", type=int, default=100) |
| parser.add_argument("--num-workers", type=int, default=1) |
| parser.add_argument("--splits", nargs="+", default=["train", "test"], choices=["train", "test"]) |
| return parser.parse_args() |
|
|
|
|
| def main() -> None: |
| args = parse_args() |
| source_dir = args.source_dir |
| if not source_dir.exists(): |
| raise FileNotFoundError(f"source dir not found: {source_dir}") |
|
|
| if not args.skip_crop: |
| print(f"==> Crop faces from {source_dir / 'train_cp'}") |
| crop_faces(source_dir, num_workers=args.crop_workers, force=args.force_crop) |
|
|
| split_data = _load_split(args.split_json) |
| for split_name in args.splits: |
| _process_one_split( |
| split_name=split_name, |
| split_paths=split_data[split_name], |
| source_dir=source_dir, |
| output_root=args.output_root, |
| overwrite=args.overwrite, |
| media_rows_per_shard=args.media_rows_per_shard, |
| row_group_size=args.row_group_size, |
| num_workers=args.num_workers, |
| ) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|