Datasets:
Download evaluation/bench.py from OpenMOSS-Team/RealLayoutArena: direct link, hf CLI and curl.
- Browser
- Download file 7.97 kB
-
https://huggingface.co/datasets/OpenMOSS-Team/RealLayoutArena/resolve/main/evaluation/bench.py
- Command line
-
hf download hf://datasets/OpenMOSS-Team/RealLayoutArena/evaluation/bench.py
-
curl -L -o bench.py https://huggingface.co/datasets/OpenMOSS-Team/RealLayoutArena/resolve/main/evaluation/bench.py
7.97 kB
| #!/usr/bin/env python3 | |
| """Export generation jobs, inspect images, and aggregate completed rubric ratings.""" | |
| import argparse | |
| from collections import defaultdict | |
| import hashlib | |
| import json | |
| from pathlib import Path | |
| ROOT = Path(__file__).resolve().parents[1] | |
| def read_rows(path): | |
| return [json.loads(line) for line in Path(path).read_text(encoding='utf-8').splitlines() | |
| if line.strip()] | |
| def require(condition, message): | |
| if not condition: | |
| raise ValueError(message) | |
| def positive_integer(value): | |
| return type(value) is int and value > 0 | |
| def load_data(): | |
| rows = read_rows(ROOT / 'layout_arena.jsonl') | |
| require(len(rows) == 61 and len({r['id'] for r in rows}) == 61, | |
| 'Dataset must contain 61 unique IDs') | |
| for row in rows: | |
| sid = row['id'] | |
| require(isinstance(sid, str) and sid not in ('.', '..') and '/' not in sid | |
| and '\\' not in sid and bool(sid), f'Invalid sample ID: {sid}') | |
| require(positive_integer(row['width']) and positive_integer(row['height']), | |
| f'{sid}: invalid target size') | |
| rubric = row['rubric'] | |
| digest = hashlib.sha256(row['prompt'].encode('utf-8')).hexdigest() | |
| require(rubric['prompt_sha256'] == digest and rubric['prompt_field'] == 'prompt', | |
| f'{sid}: prompt/rubric mismatch') | |
| dimensions = rubric['dimensions'] | |
| require(len(dimensions) == 6 and len({d['id'] for d in dimensions}) == 6, | |
| f'{sid}: expected six rubric dimensions') | |
| require(all(positive_integer(d['weight']) for d in dimensions) | |
| and sum(d['weight'] for d in dimensions) == 100, f'{sid}: invalid rubric weights') | |
| return rows | |
| def write_rows(path, rows): | |
| path = Path(path) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| with path.open('x', encoding='utf-8') as handle: | |
| for row in rows: | |
| handle.write(json.dumps(row, ensure_ascii=False) + '\n') | |
| def inspect_images(rows, directory): | |
| from PIL import Image | |
| root = Path(directory).resolve() | |
| images, errors = [], [] | |
| for row in rows: | |
| path = root / f"{row['id']}.png" | |
| try: | |
| with Image.open(path) as image: | |
| image.load() | |
| width, height = image.size | |
| except (OSError, ValueError) as exc: | |
| errors.append(f"{row['id']}: {exc}") | |
| continue | |
| images.append({'id': row['id'], 'image_path': str(path), | |
| 'actual_width': width, 'actual_height': height, | |
| 'size_compliant': (width, height) == (row['width'], row['height'])}) | |
| require(not errors, 'Missing or unreadable images:\n' + '\n'.join(errors)) | |
| return images | |
| def export(args, rows): | |
| jobs = [{'id': row['id'], 'prompt': row['prompt'], | |
| 'seed': args.seed + index, 'width': row['width'], 'height': row['height'], | |
| 'output_relpath': f"{row['id']}.png"} for index, row in enumerate(rows)] | |
| write_rows(args.output, jobs) | |
| print(json.dumps({'jobs': len(jobs), 'output': args.output})) | |
| def check(args, rows): | |
| images = inspect_images(rows, args.images) | |
| print(json.dumps({'n': len(images), 'complete': True, | |
| 'size_compliant_images': sum(i['size_compliant'] for i in images), | |
| 'images': images}, ensure_ascii=False, indent=2)) | |
| def judge_tasks(args, rows): | |
| images = inspect_images(rows, args.images) | |
| tasks = [] | |
| for row, image in zip(rows, images): | |
| rubric = row['rubric'] | |
| tasks.append({'id': row['id'], | |
| 'prompt': row['prompt'], 'prompt_sha256': rubric['prompt_sha256'], | |
| 'image_path': image['image_path'], 'actual_width': image['actual_width'], | |
| 'actual_height': image['actual_height'], 'rubric': rubric, | |
| 'scores': {d['id']: {'score': None, 'reason': ''} for d in rubric['dimensions']}}) | |
| write_rows(args.output, tasks) | |
| print(json.dumps({'tasks': len(tasks), 'output': args.output})) | |
| def aggregate(results): | |
| names = results[0]['scores'] | |
| return {'n': len(results), 'mean_total': sum(r['total'] for r in results) / len(results), | |
| 'dimension_means': {name: sum(r['scores'][name]['score'] for r in results) / len(results) | |
| for name in names}, | |
| 'size_compliant_images': sum(r['size_compliant'] for r in results)} | |
| def summarize(args, rows): | |
| ratings = read_rows(args.scores) | |
| expected = {r['id']: r for r in rows} | |
| by_id = {} | |
| for rating in ratings: | |
| sid = rating['id'] | |
| require(sid in expected, f'Unknown sample ID: {sid}') | |
| require(sid not in by_id, f'Duplicate sample ID: {sid}') | |
| by_id[sid] = rating | |
| require(set(by_id) == set(expected), 'Missing ratings: ' + ', '.join(sorted(set(expected) - set(by_id)))) | |
| results, categories = [], defaultdict(list) | |
| for row in rows: | |
| sid = row['id'] | |
| rating = by_id[sid] | |
| rubric = row['rubric'] | |
| require(rating['prompt_sha256'] == rubric['prompt_sha256'], f'{sid}: prompt hash mismatch') | |
| require(rating['prompt'] == row['prompt'], f'{sid}: prompt changed') | |
| require(rating['rubric'] == rubric, f'{sid}: rubric changed') | |
| scores = rating['scores'] | |
| require(isinstance(scores, dict) and set(scores) == {d['id'] for d in rubric['dimensions']}, | |
| f'{sid}: dimension mismatch') | |
| for name, entry in scores.items(): | |
| require(isinstance(entry, dict), f'{sid}/{name}: expected score and reason') | |
| score, reason = entry.get('score'), entry.get('reason') | |
| require(type(score) is int and 0 <= score <= 5, f'{sid}/{name}: score must be integer 0..5') | |
| require(isinstance(reason, str) and bool(reason.strip()), f'{sid}/{name}: reason is required') | |
| width, height = rating['actual_width'], rating['actual_height'] | |
| require(positive_integer(width) and positive_integer(height), f'{sid}: invalid actual size') | |
| total = sum(scores[d['id']]['score'] * d['weight'] for d in rubric['dimensions']) / 5 | |
| result = {**rating, 'category': row['category'], 'total': total, | |
| 'size_compliant': (width, height) == (row['width'], row['height'])} | |
| results.append(result) | |
| categories[row['category']].append(result) | |
| summary = {'complete': True, **aggregate(results), | |
| 'aggregation': 'Equal mean over 61 tasks', | |
| 'categories': {name: aggregate(items) for name, items in sorted(categories.items())}} | |
| output = Path(args.output) | |
| require(not output.exists() or (output.is_dir() and not any(output.iterdir())), | |
| 'Output directory must be new or empty') | |
| output.mkdir(parents=True, exist_ok=True) | |
| write_rows(output / 'results.jsonl', results) | |
| (output / 'summary.json').write_text(json.dumps(summary, ensure_ascii=False, indent=2) + '\n', encoding='utf-8') | |
| print(json.dumps(summary, ensure_ascii=False)) | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| commands = parser.add_subparsers(dest='command', required=True) | |
| for name, handler in [('export', export), ('check', check), ('judge-tasks', judge_tasks), ('summarize', summarize)]: | |
| command = commands.add_parser(name) | |
| command.set_defaults(handler=handler) | |
| if name in ('check', 'judge-tasks'): | |
| command.add_argument('--images', required=True) | |
| if name != 'check': | |
| command.add_argument('--output', required=True) | |
| if name == 'export': | |
| command.add_argument('--seed', type=int, default=42) | |
| if name == 'summarize': | |
| command.add_argument('--scores', required=True) | |
| args = parser.parse_args() | |
| try: | |
| args.handler(args, load_data()) | |
| except (OSError, ValueError, KeyError, TypeError) as exc: | |
| parser.exit(1, f'Error: {exc}\n') | |
| if __name__ == '__main__': | |
| main() | |