#!/usr/bin/env python3 """Build MVEB Product1m test subset from downloaded images and test_split.json. Input: scripts/Product1m/test_split.json { "test": [{"id": "...", "line_number": N}, ...], "gallery": [{"id": "...", "line_number": N}, ...] } source/product1m/{test,gallery}/*.jpg downloads/product1m/Product1M/Poudct1M/product1m_{test,gallery}_ossurl_v2.txt Output (when executed from MVEB root): ./MVEB-test/Product1m/{query.parquet,candidate.parquet,media-*.parquet,README.md} """ from __future__ import annotations import argparse import json import shutil import sys from collections import defaultdict from pathlib import Path from typing import Dict, List, Sequence, Tuple SCRIPT_DIR = Path(__file__).resolve().parent SCRIPTS_ROOT = SCRIPT_DIR.parent ROOT_DIR = SCRIPT_DIR.parent.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 QUERY_INSTRUCTION = "You are a helpful assistant." QUERY_TEXT = "Represent the product in the given image." CANDIDATE_INSTRUCTION = "You are a helpful assistant." CANDIDATE_TEXT = "Represent the product in the given image." TXT_FILES = { "test": "product1m_test_ossurl_v2.txt", "gallery": "product1m_gallery_ossurl_v2.txt", } def _load_split(path: Path) -> dict: with path.open("r", encoding="utf-8") as f: data = json.load(f) for key in ("test", "gallery"): if key not in data or not isinstance(data[key], list): raise ValueError(f"split json must contain key {key!r} with a list value") return data def _read_lines_at(txt_path: Path, line_numbers: Sequence[int]) -> Dict[int, str]: wanted = set(line_numbers) max_line = max(line_numbers) found: Dict[int, str] = {} with txt_path.open("r", encoding="utf-8") as f: for lineno, line in enumerate(f, 1): if lineno in wanted: found[lineno] = line.strip() if lineno >= max_line and len(found) == len(wanted): break missing = sorted(wanted - found.keys()) if missing: raise ValueError(f"Missing lines in {txt_path}: {missing[:10]}") return found def _parse_record(line: str) -> Tuple[str, List[str]]: """Parse Product1M txt line -> (image_id, product_ids).""" parts = line.split("#####") if len(parts) < 4: raise ValueError(f"Invalid Product1M line (<4 fields): {line[:120]}") image_id = parts[0] # Official converter uses split("####") then strip('#') on product tokens. infos = line.split("####") product_ids = [item.strip("#") for item in infos[-1].split(";") if item.strip("#")] return image_id, product_ids def _make_annotations( split_data: dict, anno_dir: Path, image_root: Path, ) -> Tuple[List[dict], List[dict]]: """Build query/candidate rows aligned with converter/product1m.py test logic. - candidates: all gallery images in test_split.json - queries: all test images that have >=1 matching gallery product_id - pos_ids: gallery candidate ids sharing any product_id with the query """ gallery_entries = split_data["gallery"] test_entries = split_data["test"] gallery_lines = _read_lines_at( anno_dir / TXT_FILES["gallery"], [item["line_number"] for item in gallery_entries], ) test_lines = _read_lines_at( anno_dir / TXT_FILES["test"], [item["line_number"] for item in test_entries], ) productid2candidate_ids: Dict[str, List[str]] = defaultdict(list) candidate_rows: List[dict] = [] for idx, item in enumerate(gallery_entries): line = gallery_lines[item["line_number"]] image_id, product_ids = _parse_record(line) if image_id != item["id"]: raise ValueError( f"Gallery ID mismatch at line {item['line_number']}: " f"split={item['id']}, txt={image_id}" ) rel_path = f"gallery/{image_id}.jpg" abs_path = image_root / rel_path if not abs_path.is_file(): raise FileNotFoundError(f"Missing gallery image: {abs_path}") candidate_rows.append( { "id": rel_path, "image_path": rel_path, "instruction": CANDIDATE_INSTRUCTION, "text": CANDIDATE_TEXT, } ) for product_id in product_ids: productid2candidate_ids[product_id].append(rel_path) query_rows: List[dict] = [] skipped = 0 for item in test_entries: line = test_lines[item["line_number"]] image_id, product_ids = _parse_record(line) if image_id != item["id"]: raise ValueError( f"Test ID mismatch at line {item['line_number']}: " f"split={item['id']}, txt={image_id}" ) rel_path = f"test/{image_id}.jpg" abs_path = image_root / rel_path if not abs_path.is_file(): raise FileNotFoundError(f"Missing test image: {abs_path}") pos_ids: List[str] = [] seen = set() for product_id in product_ids: for cid in productid2candidate_ids.get(product_id, []): if cid not in seen: seen.add(cid) pos_ids.append(cid) if not pos_ids: skipped += 1 continue query_rows.append( { "id": str(len(query_rows)), "image_path": rel_path, "instruction": QUERY_INSTRUCTION, "text": QUERY_TEXT, "pos_ids": pos_ids, } ) if skipped: print(f"[warn] skipped {skipped} test queries with empty pos_ids") if not query_rows: raise ValueError("No valid query annotations were built") if not candidate_rows: raise ValueError("No candidate annotations were built") return query_rows, candidate_rows def _process_test( split_data: dict, anno_dir: Path, image_root: 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, "test", "Product1m") if overwrite and out_dir.exists(): shutil.rmtree(out_dir) out_dir.mkdir(parents=True, exist_ok=True) query_rows, candidate_rows = _make_annotations(split_data, anno_dir, image_root) stats = pack_dataset_with_media( query_annotations=query_rows, candidate_annotations=candidate_rows, image_dir=str(image_root), 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="Product1m", data_split="test", write_subset_readme=True, show_progress=True, ) print( f"[test] done: media={stats['num_media']}, " f"query={stats['num_query']}, candidate={stats['num_candidate']}, " f"shards={stats['num_shards']} -> {out_dir}" ) def main() -> None: parser = argparse.ArgumentParser( description="Process Product1m test_split.json to MVEB parquet format." ) parser.add_argument( "--split-json", type=Path, default=SCRIPT_DIR / "test_split.json", help="JSON containing test/gallery id + line_number entries.", ) parser.add_argument( "--image-root", type=Path, default=ROOT_DIR / "source" / "product1m", help="Root directory containing test/ and gallery/ images.", ) parser.add_argument( "--repo-dir", type=Path, default=ROOT_DIR / "downloads" / "product1m" / "Product1M", help="Cloned Product1M github repo.", ) parser.add_argument( "--output-root", type=Path, default=ROOT_DIR, help="Output MVEB root directory (contains test/).", ) parser.add_argument( "--overwrite", action="store_true", help="Delete existing output split dir before writing.", ) 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) args = parser.parse_args() if not args.split_json.exists(): raise FileNotFoundError(f"split json not found: {args.split_json}") if not args.image_root.exists(): raise FileNotFoundError(f"image root not found: {args.image_root}") anno_dir = args.repo_dir / "Poudct1M" if not anno_dir.exists(): raise FileNotFoundError(f"anno dir not found: {anno_dir}") for name in TXT_FILES.values(): txt_path = anno_dir / name if not txt_path.exists(): raise FileNotFoundError(f"annotation txt not found: {txt_path}") split_data = _load_split(args.split_json) _process_test( split_data=split_data, anno_dir=anno_dir, image_root=args.image_root, 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()