TaobaoTmall-AlgorithmProducts commited on
Commit
bb4dd44
·
verified ·
1 Parent(s): 0e38484

Upload bench_eval_code/export_samples.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. bench_eval_code/export_samples.py +162 -0
bench_eval_code/export_samples.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Export a CPI-Bench dataset to local images + a template result JSONL,
3
+ so users know which sample_index corresponds to which image(s)/instruction,
4
+ and can prepare their model's output accordingly.
5
+
6
+ Automatically detects the schema based on the columns actually present in the
7
+ dataset — no need to manually specify which benchmark/subset it is:
8
+
9
+ - has `source` column -> image-editing schema
10
+ (uses `a_to_b_instructions` / `a_to_b_instructions_eng`, exports source images)
11
+ - no `source` column, but has `prompt_cn` column -> text-to-image schema
12
+ (uses `prompt_cn` / `prompt_en`, no images to export)
13
+
14
+ This covers: general / practical / intelligent (all image-editing, `source` present).
15
+
16
+ Usage:
17
+ python export_samples.py \
18
+ --dataset_path "/path/to/CPI_intelligent_benchmark-*.parquet" \
19
+ --output_dir ./exported_intelligent \
20
+ --lang eng \
21
+ --workers 16
22
+
23
+ """
24
+
25
+ import argparse
26
+ import json
27
+ import os
28
+ import threading
29
+ from concurrent.futures import ThreadPoolExecutor, as_completed
30
+
31
+ from datasets import load_dataset
32
+ from tqdm import tqdm
33
+
34
+
35
+ def detect_schema(dataset) -> dict:
36
+ """
37
+ Auto-detect field schema based on the columns present in the dataset.
38
+
39
+ - If `source` column exists -> image-editing schema (general/life/intelligent)
40
+ - Otherwise -> raise, ask user to check the dataset
41
+ """
42
+ columns = set(dataset.column_names)
43
+
44
+ if "source" in columns:
45
+ return {
46
+ "instruction_field": "a_to_b_instructions",
47
+ "instruction_field_eng": "a_to_b_instructions_eng",
48
+ "has_source": True,
49
+ }
50
+ if "prompt_cn" in columns:
51
+ return {
52
+ "instruction_field": "prompt_cn",
53
+ "instruction_field_eng": "prompt_en",
54
+ "has_source": False,
55
+ }
56
+ raise ValueError(
57
+ f"Cannot auto-detect schema: dataset has neither 'source' nor 'prompt_cn' "
58
+ f"column. Available columns: {sorted(columns)}"
59
+ )
60
+
61
+
62
+ def get_expert_domain(sample: dict) -> str:
63
+ return sample.get("expert_domain") or sample.get("task", "unknown")
64
+
65
+
66
+ def get_instruction(sample: dict, schema: dict, lang: str) -> str:
67
+ base = sample.get(schema["instruction_field"], "") or ""
68
+ if lang == "eng":
69
+ eng = sample.get(schema["instruction_field_eng"], "") or ""
70
+ return eng or base
71
+ return base
72
+
73
+
74
+ def export_one_sample(idx: int, dataset, images_dir: str, schema: dict, lang: str) -> dict:
75
+ """
76
+ Export a single sample's source image(s) (if any) to disk and return its
77
+ metadata entry. Safe to call concurrently: each call only writes files
78
+ unique to its own `idx`.
79
+ """
80
+ sample = dataset[idx]
81
+
82
+ img_paths = []
83
+ if schema["has_source"]:
84
+ source_images = sample.get("source") or []
85
+ for j, img in enumerate(source_images):
86
+ img_path = os.path.join(images_dir, f"{idx:06d}_src{j}.png")
87
+ img.save(img_path)
88
+ img_paths.append(img_path)
89
+
90
+ return {
91
+ "sample_index": idx,
92
+ "id": sample.get("id"),
93
+ "task": get_expert_domain(sample),
94
+ "instruction": get_instruction(sample, schema, lang),
95
+ "rationale": sample.get("rationale", ""),
96
+ "source_images": img_paths, # empty list for text-to-image samples
97
+ }
98
+
99
+
100
+ def main():
101
+ parser = argparse.ArgumentParser()
102
+ parser.add_argument("--dataset_path", required=True)
103
+ parser.add_argument("--output_dir", required=True)
104
+ parser.add_argument("--lang", choices=["cn", "eng"], default="eng")
105
+ parser.add_argument("--workers", type=int, default=16,
106
+ help="Number of concurrent threads for exporting images (default: 16)")
107
+ args = parser.parse_args()
108
+
109
+ os.makedirs(args.output_dir, exist_ok=True)
110
+
111
+ dataset = load_dataset("parquet", data_files=args.dataset_path, split="train")
112
+ print(f"Loaded {len(dataset)} samples")
113
+
114
+ schema = detect_schema(dataset)
115
+ print(f"Detected schema: instruction_field='{schema['instruction_field']}', "
116
+ f"has_source={schema['has_source']}")
117
+
118
+
119
+ images_dir = os.path.join(args.output_dir, "source_images")
120
+ if schema["has_source"]:
121
+ os.makedirs(images_dir, exist_ok=True)
122
+
123
+ meta_path = os.path.join(args.output_dir, "samples.jsonl")
124
+ template_path = os.path.join(args.output_dir, "result_template.jsonl")
125
+
126
+ results = [None] * len(dataset)
127
+ write_lock = threading.Lock()
128
+
129
+ with ThreadPoolExecutor(max_workers=args.workers) as executor:
130
+ futures = {
131
+ executor.submit(export_one_sample, idx, dataset, images_dir, schema, args.lang): idx
132
+ for idx in range(len(dataset))
133
+ }
134
+ for future in tqdm(as_completed(futures), total=len(futures), desc="Exporting"):
135
+ idx = futures[future]
136
+ try:
137
+ entry = future.result()
138
+ except Exception as e:
139
+ print(f"Warning: failed to export sample {idx}: {e}")
140
+ entry = {"sample_index": idx, "error": str(e)}
141
+ with write_lock:
142
+ results[idx] = entry
143
+
144
+ with open(meta_path, "w", encoding="utf-8") as meta_f, \
145
+ open(template_path, "w", encoding="utf-8") as tpl_f:
146
+ for idx, entry in enumerate(results):
147
+ meta_f.write(json.dumps(entry, ensure_ascii=False) + "\n")
148
+ tpl_f.write(json.dumps({"sample_index": idx, "result": f"/path/to/your/result_{idx}.png"}) + "\n")
149
+
150
+ error_count = sum(1 for e in results if e is not None and "error" in e)
151
+ if schema["has_source"]:
152
+ print(f"Source images saved to: {images_dir}")
153
+ else:
154
+ print("No source images to export (text-to-image dataset).")
155
+ print(f"Sample metadata: {meta_path}")
156
+ print(f"Result JSONL template: {template_path} (fill in the 'result' paths after running your model)")
157
+ if error_count:
158
+ print(f"Warning: {error_count} samples failed to export, check 'error' field in {meta_path}")
159
+
160
+
161
+ if __name__ == "__main__":
162
+ main()