File size: 7,974 Bytes
906535b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
#!/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()