Upload bench_eval_code/export_samples.py with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162"""Export a CPI-Bench dataset to local images + a template result JSONL,so users know which sample_index corresponds to which image(s)/instruction,and can prepare their model's output accordingly.
Automatically detects the schema based on the columns actually present in thedataset — no need to manually specify which benchmark/subset it is:
- has `source` column -> image-editing schema (uses `a_to_b_instructions` / `a_to_b_instructions_eng`, exports source images) - no `source` column, but has `prompt_cn` column -> text-to-image schema (uses `prompt_cn` / `prompt_en`, no images to export)
This covers: general / practical / intelligent (all image-editing, `source` present).
Usage: python export_samples.py \ --dataset_path "/path/to/CPI_intelligent_benchmark-*.parquet" \ --output_dir ./exported_intelligent \ --lang eng \ --workers 16
"""
import argparseimport jsonimport osimport threadingfrom concurrent.futures import ThreadPoolExecutor, as_completed
from datasets import load_datasetfrom tqdm import tqdm
def detect_schema(dataset) -> dict: """ Auto-detect field schema based on the columns present in the dataset.
- If `source` column exists -> image-editing schema (general/life/intelligent) - Otherwise -> raise, ask user to check the dataset """ columns = set(dataset.column_names)
if "source" in columns: return { "instruction_field": "a_to_b_instructions", "instruction_field_eng": "a_to_b_instructions_eng", "has_source": True, } if "prompt_cn" in columns: return { "instruction_field": "prompt_cn", "instruction_field_eng": "prompt_en", "has_source": False, } raise ValueError( f"Cannot auto-detect schema: dataset has neither 'source' nor 'prompt_cn' " f"column. Available columns: {sorted(columns)}" )
def get_expert_domain(sample: dict) -> str: return sample.get("expert_domain") or sample.get("task", "unknown")
def get_instruction(sample: dict, schema: dict, lang: str) -> str: base = sample.get(schema["instruction_field"], "") or "" if lang == "eng": eng = sample.get(schema["instruction_field_eng"], "") or "" return eng or base return base
def export_one_sample(idx: int, dataset, images_dir: str, schema: dict, lang: str) -> dict: """ Export a single sample's source image(s) (if any) to disk and return its metadata entry. Safe to call concurrently: each call only writes files unique to its own `idx`. """ sample = dataset[idx]
img_paths = [] if schema["has_source"]: source_images = sample.get("source") or [] for j, img in enumerate(source_images): img_path = os.path.join(images_dir, f"{idx:06d}_src{j}.png") img.save(img_path) img_paths.append(img_path)
return { "sample_index": idx, "id": sample.get("id"), "task": get_expert_domain(sample), "instruction": get_instruction(sample, schema, lang), "rationale": sample.get("rationale", ""), "source_images": img_paths, # empty list for text-to-image samples }
def main(): parser = argparse.ArgumentParser() parser.add_argument("--dataset_path", required=True) parser.add_argument("--output_dir", required=True) parser.add_argument("--lang", choices=["cn", "eng"], default="eng") parser.add_argument("--workers", type=int, default=16, help="Number of concurrent threads for exporting images (default: 16)") args = parser.parse_args()
os.makedirs(args.output_dir, exist_ok=True)
dataset = load_dataset("parquet", data_files=args.dataset_path, split="train") print(f"Loaded {len(dataset)} samples")
schema = detect_schema(dataset) print(f"Detected schema: instruction_field='{schema['instruction_field']}', " f"has_source={schema['has_source']}")
images_dir = os.path.join(args.output_dir, "source_images") if schema["has_source"]: os.makedirs(images_dir, exist_ok=True)
meta_path = os.path.join(args.output_dir, "samples.jsonl") template_path = os.path.join(args.output_dir, "result_template.jsonl")
results = [None] * len(dataset) write_lock = threading.Lock()
with ThreadPoolExecutor(max_workers=args.workers) as executor: futures = { executor.submit(export_one_sample, idx, dataset, images_dir, schema, args.lang): idx for idx in range(len(dataset)) } for future in tqdm(as_completed(futures), total=len(futures), desc="Exporting"): idx = futures[future] try: entry = future.result() except Exception as e: print(f"Warning: failed to export sample {idx}: {e}") entry = {"sample_index": idx, "error": str(e)} with write_lock: results[idx] = entry
with open(meta_path, "w", encoding="utf-8") as meta_f, \ open(template_path, "w", encoding="utf-8") as tpl_f: for idx, entry in enumerate(results): meta_f.write(json.dumps(entry, ensure_ascii=False) + "\n") tpl_f.write(json.dumps({"sample_index": idx, "result": f"/path/to/your/result_{idx}.png"}) + "\n")
error_count = sum(1 for e in results if e is not None and "error" in e) if schema["has_source"]: print(f"Source images saved to: {images_dir}") else: print("No source images to export (text-to-image dataset).") print(f"Sample metadata: {meta_path}") print(f"Result JSONL template: {template_path} (fill in the 'result' paths after running your model)") if error_count: print(f"Warning: {error_count} samples failed to export, check 'error' field in {meta_path}")
if __name__ == "__main__": main()bench_eval_code/export_samples.pyAdded+162