Upload bench_eval_code/eval_general_practical.py with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547"""CPI-Bench: General / Practical benchmark evaluation script (open-source version).
Evaluates image-editing results against the CPI-General-Benchmark / CPI-Practical-Benchmarkdatasets using a VLM judge with task-specific scoring prompts.
Dataset format (HuggingFace parquet): - id : str - task : str (task category, keyed into prompts.json) - a_to_b_instructions : str (Chinese instruction) - a_to_b_instructions_eng : str (English instruction) - target_resolution : str - source : List[PIL.Image] (one or more reference/input images)
Result JSONL format (produced by the user, one line per evaluated sample): {"sample_index": 0, "result": "/path/to/result_0.png"} {"sample_index": 1, "result": "/path/to/result_1.png"} ...`sample_index` refers to the row index in the loaded HF dataset (0-based, in theorder returned by `datasets.load_dataset`). Use `export_samples.py` to dump thedataset to local images + a template result JSONL if you need to know which rowmaps to which sample.
Output: <output_dir>/cases.jsonl — Per-sample raw response + parsed dimension scores <output_dir>/summary.json — Aggregated scores: * overall_avg_score / by_task_type : sample-weighted (micro) average * hierarchy : re-aggregated by (level1, level2) following the hard-coded maps below
Note: Compared to earlier versions of this script, `overall_avg_score` and `by_task_type` are now computed as **micro (sample-weighted) averages** rather than macro averages, to stay consistent with our internal reporting pipeline. Samples whose `task` is not present in the hierarchy map are excluded from the level1/level2 aggregation and listed under `hierarchy.unmapped_tasks` for inspection.
Usage: python eval_general_practical.py \ --benchmark general \ --dataset_path "/path/to/Pi_general_benchmark-*.parquet" \ --result_jsonl /path/to/my_results.jsonl \ --prompts_json prompts/general_prompts.json \ --output_dir eval_output/my_model_general \ --api_key YOUR_KEY \ --lang eng \ --workers 8
python eval_general_practical.py \ --benchmark practical \ --dataset_path "/path/to/Pi_practical_benchmark-*.parquet" \ --result_jsonl /path/to/my_results.jsonl \ --prompts_json prompts/practical_prompts.json \ --output_dir eval_output/my_model_practical \ --api_key YOUR_KEY \ --lang eng \ --workers 8"""
import argparseimport jsonimport osfrom collections import defaultdictfrom concurrent.futures import ThreadPoolExecutor, as_completed
import numpy as npfrom datasets import load_datasetfrom tqdm import tqdm
from bench_utils import ApiKeyPool, call_vlm_with_retries, load_local_image, pil_to_base64
DEFAULT_MODEL = "gemini-3-flash-preview"DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta/openai/"
# ---------------------------------------------------------------------------# Hierarchy maps: task -> (level1, level2)## These maps define the two-level taxonomy used for hierarchical aggregation# in `summary.json -> hierarchy`. Newline characters in level1 names are kept# intentionally (used for consistent formatting with downstream reporting).# If you add new tasks to the benchmark, extend the corresponding map here.# ---------------------------------------------------------------------------
PRACTICAL_HIERARCHY_MAP = { "Smart Remove": ("Portrait Enhancement", "Basic Editing"), "Restoration": ("Portrait Enhancement", "Basic Editing"), "Image Super-Resolution": ("Portrait Enhancement", "Basic Editing"), "Filter Application": ("Portrait Enhancement", "Basic Editing"), "Background Change": ("Portrait Enhancement", "Basic Editing"), "Portrait Matting": ("Portrait Enhancement", "Basic Editing"), "Outpainting": ("Portrait Enhancement", "Basic Editing"), "Facial Expression Editing": ("Portrait Enhancement", "Appearance Change"), "Age Transformation": ("Portrait Enhancement", "Appearance Change"), "Gender Transformation": ("Portrait Enhancement", "Appearance Change"), "Figure Change": ("Portrait Enhancement", "Appearance Change"), "Hair Change": ("Portrait Enhancement", "Appearance Change"), "Face Swap (Reference-based)": ("Portrait Enhancement", "Appearance Change"), "Face Generation (Prompt-based)": ("Portrait Enhancement", "Appearance Change"), "Beauty": ("Portrait Enhancement", "Appearance Change"), "Makeup": ("Portrait Enhancement", "Appearance Change"), "ID Photo Generation": ("Portrait Enhancement", "Style and Creative Generation"), "Photoshoot Generation": ("Portrait Enhancement", "Style and Creative Generation"), "Meme Generation": ("Portrait Enhancement", "Style and Creative Generation"), "Character Poster Generation": ("Portrait Enhancement", "Style and Creative Generation"), "Viewpoint Change": ("Portrait Enhancement", "Pose and View Change"), "Human Motion": ("Portrait Enhancement", "Pose and View Change"), "Try-On": ("Portrait Enhancement", "Clothes Change"), "Clothing Editing": ("Portrait Enhancement", "Clothes Change"), "IP Product Rendering": ("E-commerce &\n Advertising Creativity", "Product Retouching"), "Hand-Held Product Generation": ("E-commerce &\n Advertising Creativity", "Product Retouching"), "Product Image Retouching": ("E-commerce &\n Advertising Creativity", "Product Retouching"), "Product Image Generation (Single Image)": ("E-commerce &\n Advertising Creativity", "Product Retouching"), "Product Image Generation (Multi Image)": ("E-commerce &\n Advertising Creativity", "Product Retouching"), "Watermark Removal": ("E-commerce &\n Advertising Creativity", "Product Retouching"), "Style-Referenced Product Image Generation": ("E-commerce &\n Advertising Creativity", "Product Retouching"), "Multi-Product Composite Generation": ("E-commerce &\n Advertising Creativity", "Product Retouching"), "Multi-Resolution Product Generation": ("E-commerce &\n Advertising Creativity", "Product Retouching"), "Object Extraction": ("E-commerce &\n Advertising Creativity", "Product Retouching"), "Promotional Poster Generation": ("E-commerce &\n Advertising Creativity", "Ad Creation"), "Splash Ad Generation": ("E-commerce &\n Advertising Creativity", "Ad Creation"), "Marketing Image Generation": ("E-commerce &\n Advertising Creativity", "Ad Creation"), "Wall and Floor Material Replacement": ("Residential \n Interior Design", "Hard Finishes"), "Door and Window Structure Modification": ("Residential \n Interior Design", "Hard Finishes"), "Floor Plan Structural Adjustment": ("Residential \n Interior Design", "Hard Finishes"), "Interior Staging": ("Residential \n Interior Design", "Soft Furnishings"), "Single Furniture Placement": ("Residential \n Interior Design", "Soft Furnishings"), "Multi-Furniture Placement": ("Residential \n Interior Design", "Soft Furnishings"), "Rough-to-Finished Interior Rendering": ("Residential \n Interior Design", "Rendering"), "Architectural Rendering Generation": ("Residential \n Interior Design", "Rendering"), "Lighting Effect Simulation": ("Residential \n Interior Design", "Lighting Simulation"), "Translation": ("Content Creation", "CN-EN Translation"), "Style Transfer": ("Content Creation", "Style and Creative Generation"), "Group Photo Generation": ("Content Creation", "Style and Creative Generation"), "Multi-Panel Story Generation": ("Content Creation", "Style and Creative Generation"), "Sketch Coloring & Refinement": ("Content Creation", "Style and Creative Generation"),}
GENERAL_HIERARCHY_MAP = { "Multi-Subject-Driven Generation": ("Multi-image editing", "Multi-Subject-Driven Generation"), "PS Human": ("Single-image editing", "PS Human"), "Ref-Based Text Modification": ("Multi-image editing", "Ref-Based Text Modification"), "Subject-Driven Generation": ("Single-image editing", "Subject-Driven Generation"), "Multi-Image Compose Edit": ("Multi-image editing", "Multi-Image Compose Edit"), "Ref-Based Addition": ("Multi-image editing", "Ref-Based Addition"), "Subject Replacement": ("Single-image editing", "Subject Replacement"), "Compose Edit": ("Single-image editing", "Compose Edit"), "Subject Removal": ("Single-image editing", "Subject Removal"), "Text Modification": ("Single-image editing", "Text Modification"), "Ref-Based Removal": ("Multi-image editing", "Ref-Based Removal"), "Subject Addition": ("Single-image editing", "Subject Addition"), "Ref-Based Replace": ("Multi-image editing", "Ref-Based Replace"), "Motion Change": ("Single-image editing", "Motion Change"), "Ref-Based Style Transfer": ("Multi-image editing", "Ref-Based Style Transfer"), "Style Transfer": ("Single-image editing", "Style Transfer"), "Ref-Based Change": ("Multi-image editing", "Ref-Based Change"), "Low Level": ("Single-image editing", "Low Level"), "Ref-Based Motion": ("Multi-image editing", "Ref-Based Motion"), "Viewpoint Change": ("Single-image editing", "Viewpoint Change"), "Subject Extraction": ("Single-image editing", "Subject Extraction"), "Ref-Based Viewpoint Change": ("Multi-image editing", "Ref-Based Viewpoint Change"), "Environment Change": ("Single-image editing", "Adjust"), "Feature Extraction": ("Single-image editing", "Low Level"), "Background Change": ("Single-image editing", "Adjust"), "Material Modification": ("Single-image editing", "Adjust"), "Color Alteration": ("Single-image editing", "Adjust"), "Subject Re-orientation": ("Single-image editing", "Adjust"), "Structure-Guided Generation": ("Single-image editing", "Structure-Guided Generation"), "Attribute Change": ("Single-image editing", "Adjust"),}
BENCHMARK_HIERARCHY_MAPS = { "general": GENERAL_HIERARCHY_MAP, "practical": PRACTICAL_HIERARCHY_MAP,}
# ---------------------------------------------------------------------------# Result JSONL# ---------------------------------------------------------------------------
def load_result_jsonl(path: str) -> "dict[int, str]": index_to_path = {} with open(path, "r", encoding="utf-8") as f: for line_no, line in enumerate(f, start=1): line = line.strip() if not line: continue try: entry = json.loads(line) except json.JSONDecodeError as e: print(f"Warning: malformed line {line_no}: {e}") continue idx = entry.get("sample_index") result_path = entry.get("result") if idx is None or result_path is None: print(f"Warning: line {line_no} missing 'sample_index' or 'result'") continue index_to_path[int(idx)] = str(result_path) return index_to_path
# ---------------------------------------------------------------------------# Scoring parse# ---------------------------------------------------------------------------
def parse_dimension_scores(raw_text: str) -> dict: """Parse lines like 'Instruction Following: 8' into a dict.""" scores = {} if not raw_text or not isinstance(raw_text, str) or raw_text.startswith("Error"): return scores for line in raw_text.splitlines(): parts = line.strip().split(": ") if len(parts) == 2 and parts[1].strip().isdigit(): scores[parts[0].strip()] = int(parts[1].strip()) return scores
def average_score(dim_scores: dict) -> "float | None": if not dim_scores: return None return round(sum(dim_scores.values()) / len(dim_scores), 2)
# ---------------------------------------------------------------------------# Single sample scoring# ---------------------------------------------------------------------------
def score_one_sample( sample_index: int, dataset, result_path: str, prompts_templates: dict, lang: str, key_pool: ApiKeyPool, base_url: str, model: str,) -> dict: try: sample = dataset[sample_index] except (IndexError, KeyError) as e: return {"sample_index": sample_index, "error": f"Dataset access failed: {e}"}
task = sample.get("task", "unknown") sample_id = sample.get("id") source_images = sample.get("source") or []
if not source_images: return {"sample_index": sample_index, "task": task, "id": sample_id, "error": "No source image(s) in dataset sample"}
if not os.path.exists(result_path): return {"sample_index": sample_index, "task": task, "id": sample_id, "error": f"Result image not found: {result_path}"}
try: result_img = load_local_image(result_path) except Exception as e: return {"sample_index": sample_index, "task": task, "id": sample_id, "error": f"Failed to load result image: {e}"}
template = prompts_templates.get(task) if not template: return {"sample_index": sample_index, "task": task, "id": sample_id, "error": f"No prompt template found for task '{task}'"}
if lang == "cn": edit_prompt = sample.get("a_to_b_instructions", "") else: edit_prompt = sample.get("a_to_b_instructions_eng", "") or sample.get("a_to_b_instructions", "")
full_prompt = template.replace("<edit_prompt>", edit_prompt)
# --- Build multimodal message --- content_parts = [] for i, ref_img in enumerate(source_images): b64 = pil_to_base64(ref_img) content_parts.append({"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64}"}}) label = "This is the original image A." if len(source_images) == 1 else f"This is reference image A{i+1}." content_parts.append({"type": "text", "text": label})
result_b64 = pil_to_base64(result_img) content_parts.append({"type": "image_url", "image_url": {"url": f"data:image/png;base64,{result_b64}"}}) content_parts.append({"type": "text", "text": "This is the edited image B. Please evaluate."}) content_parts.append({"type": "text", "text": full_prompt})
raw_text = call_vlm_with_retries( content_parts, key_pool, base_url, model, tag=f"{task}-{sample_id}" )
dim_scores = parse_dimension_scores(raw_text) avg = average_score(dim_scores)
return { "sample_index": sample_index, "id": sample_id, "task": task, "instruction": edit_prompt, "result_image": result_path, "dimension_scores": dim_scores, "avg_score": avg, "raw_response": raw_text, "error": None if avg is not None else "Failed to parse a valid score from VLM output", }
# ---------------------------------------------------------------------------# Aggregation# ---------------------------------------------------------------------------
def _agg(scores: list) -> dict: """Return {avg_score, num_samples} for a list of per-sample scores.""" if not scores: return {"avg_score": None, "num_samples": 0} return {"avg_score": round(float(np.mean(scores)), 4), "num_samples": len(scores)}
def build_hierarchy_summary(valid_cases: list, hierarchy_map: dict) -> dict: """Re-aggregate valid cases by (level1, level2) taxonomy.
Uses sample-weighted (micro) averaging: every valid sample contributes equally to the level it belongs to.
Tasks not present in `hierarchy_map` are excluded from level1/level2 aggregation and reported under `unmapped_tasks`. """ level1_scores = defaultdict(list) level2_scores = defaultdict(list) # key: (level1, level2) nested_scores = defaultdict(lambda: defaultdict(list)) # nested[level1][level2] -> [scores] unmapped_scores = defaultdict(list)
for c in valid_cases: task = c.get("task", "") score = c["avg_score"] mapping = hierarchy_map.get(task) if mapping is None: unmapped_scores[task].append(score) continue level1, level2 = mapping level1_scores[level1].append(score) level2_scores[(level1, level2)].append(score) nested_scores[level1][level2].append(score)
by_level1 = {level1: _agg(scores) for level1, scores in level1_scores.items()} by_level2 = { f"{level1} || {level2}": _agg(scores) for (level1, level2), scores in level2_scores.items() }
nested = {} for level1, level2_dict in nested_scores.items(): all_scores = [] level2_out = {} for level2, scores in level2_dict.items(): level2_out[level2] = _agg(scores) all_scores.extend(scores) node = _agg(all_scores) node["level2"] = level2_out nested[level1] = node
unmapped_tasks = {task: _agg(scores) for task, scores in unmapped_scores.items()} unmapped_total_samples = sum(v["num_samples"] for v in unmapped_tasks.values())
return { "by_level1": by_level1, "by_level2": by_level2, "nested": nested, "unmapped_tasks": unmapped_tasks, "unmapped_total_samples": unmapped_total_samples, }
def build_summary(cases: list, benchmark: str) -> dict: """Aggregate results using **micro (sample-weighted) averages**.
- `overall_avg_score`: mean over all valid samples. - `by_task_type`: mean per task, over samples of that task. - `hierarchy`: re-aggregation by (level1, level2), only present if the benchmark has a hierarchy map defined. """ valid = [c for c in cases if c.get("avg_score") is not None] task_scores = defaultdict(list) for c in valid: task_scores[c["task"]].append(c["avg_score"])
by_task = {t: round(float(np.mean(s)), 2) for t, s in task_scores.items()} overall = round(float(np.mean([c["avg_score"] for c in valid])), 2) if valid else 0.0
summary = { "overall_avg_score": overall, "by_task_type": dict(sorted(by_task.items())), "total_samples": len(cases), "scored_samples": len(valid), "error_samples": len(cases) - len(valid), }
hierarchy_map = BENCHMARK_HIERARCHY_MAPS.get(benchmark) if hierarchy_map: summary["hierarchy"] = build_hierarchy_summary(valid, hierarchy_map)
return summary
# ---------------------------------------------------------------------------# Main pipeline# ---------------------------------------------------------------------------
def run_evaluation(dataset, index_to_result, prompts_templates, args, key_pool): cases_path = os.path.join(args.output_dir, "cases.jsonl")
# Resume support done_indices = set() if os.path.exists(cases_path) and args.resume: with open(cases_path, "r", encoding="utf-8") as f: for line in f: try: entry = json.loads(line) if entry.get("avg_score") is not None: done_indices.add(entry["sample_index"]) except json.JSONDecodeError: pass
pending = [i for i in sorted(index_to_result) if i not in done_indices] print(f"Total: {len(index_to_result)}, already scored: {len(done_indices)}, pending: {len(pending)}")
mode = "a" if (args.resume and os.path.exists(cases_path)) else "w" if pending: with open(cases_path, mode, encoding="utf-8") as out_f: with ThreadPoolExecutor(max_workers=args.workers) as executor: futures = { executor.submit( score_one_sample, idx, dataset, index_to_result[idx], prompts_templates, args.lang, key_pool, args.base_url, args.model, ): idx for idx in pending } for future in tqdm(as_completed(futures), total=len(futures), desc="Scoring"): result = future.result() out_f.write(json.dumps(result, ensure_ascii=False) + "\n") out_f.flush()
all_cases = [] with open(cases_path, "r", encoding="utf-8") as f: for line in f: line = line.strip() if line: all_cases.append(json.loads(line))
summary = build_summary(all_cases, args.benchmark) summary_path = os.path.join(args.output_dir, "summary.json") with open(summary_path, "w", encoding="utf-8") as f: json.dump(summary, f, ensure_ascii=False, indent=2)
# ---- Terminal report ---- print("\n" + "=" * 60) print(f"[{args.benchmark}] Overall avg score (micro): {summary['overall_avg_score']:.2f}") print(f"Scored {summary['scored_samples']}/{summary['total_samples']} " f"(errors: {summary['error_samples']})")
print("\nBy task type (micro avg):") print(json.dumps(summary["by_task_type"], indent=2, ensure_ascii=False))
hierarchy = summary.get("hierarchy") if hierarchy: print("\nBy level1 (micro avg):") level1_display = { level1.replace("\n", " ").strip(): info for level1, info in hierarchy["by_level1"].items() } print(json.dumps(level1_display, indent=2, ensure_ascii=False))
print("\nBy level2 (micro avg):") level2_display = { key.replace("\n", " "): info for key, info in hierarchy["by_level2"].items() } print(json.dumps(level2_display, indent=2, ensure_ascii=False))
if hierarchy["unmapped_total_samples"] > 0: print("\n" + "!" * 60) print(f"WARNING: {hierarchy['unmapped_total_samples']} sample(s) belong to " f"task(s) NOT in the hierarchy map and were EXCLUDED from " f"level1/level2 aggregation:") for task, info in hierarchy["unmapped_tasks"].items(): print(f" - '{task}': {info['num_samples']} samples, " f"avg_score={info['avg_score']}") print(f"Please update {args.benchmark.upper()}_HIERARCHY_MAP in " f"eval_general_practical.py to include these tasks.") print("!" * 60)
print(f"\nCases: {cases_path}") print(f"Summary: {summary_path}") print("=" * 60)
def main(): parser = argparse.ArgumentParser(description="CPI-Bench: General/Practical benchmark evaluation") parser.add_argument("--benchmark", choices=["general", "practical"], required=True) parser.add_argument("--dataset_path", required=True, help="Glob path to the benchmark parquet shards, e.g. 'Pi_general_benchmark-*.parquet'") parser.add_argument("--result_jsonl", required=True, help='JSONL with {"sample_index": int, "result": "/path/to/img.png"} per line') parser.add_argument("--prompts_json", required=True, help="Path to the task-specific scoring prompt templates (JSON: {task: template})") parser.add_argument("--output_dir", default="eval_output") parser.add_argument("--api_key", required=True, help="Comma-separated API key(s) for round-robin") parser.add_argument("--base_url", default=DEFAULT_BASE_URL) parser.add_argument("--model", default=DEFAULT_MODEL) parser.add_argument("--lang", choices=["cn", "eng"], default="eng") parser.add_argument("--workers", type=int, default=8) parser.add_argument("--resume", action="store_true", default=True) parser.add_argument("--no_resume", dest="resume", action="store_false") parser.add_argument("--num_samples", type=int, default=None) args = parser.parse_args()
os.makedirs(args.output_dir, exist_ok=True)
key_pool = ApiKeyPool([k.strip() for k in args.api_key.split(",") if k.strip()])
print(f"Loading dataset: {args.dataset_path}") dataset = load_dataset("parquet", data_files=args.dataset_path, split="train") print(f"Dataset loaded: {len(dataset)} samples")
with open(args.prompts_json, "r", encoding="utf-8") as f: prompts_templates = json.load(f)
index_to_result = load_result_jsonl(args.result_jsonl) max_idx = len(dataset) - 1 invalid = [i for i in index_to_result if i < 0 or i > max_idx] for i in invalid: print(f"Warning: sample_index {i} out of range, skipped.") del index_to_result[i]
if args.num_samples is not None: keep = sorted(index_to_result)[:args.num_samples] index_to_result = {i: index_to_result[i] for i in keep}
if not index_to_result: print("No valid entries to evaluate. Exiting.") return
run_evaluation(dataset, index_to_result, prompts_templates, args, key_pool)
if __name__ == "__main__": main()bench_eval_code/eval_general_practical.pyAdded+547