File size: 7,966 Bytes
d9befd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Portable, label-free access to the frozen paper inputs (Python standard library).

    from prowm_bench import load_dataset
    for request in load_dataset('swemm').requests():
        # Send request['messages'] to a chat-completions model, without tools.
        # Save item_id, branch, prediction (or response), and finish_reason.
        ...

Targets and post-action screenshots are never read by Dataset or requests().
"""
from __future__ import annotations

import base64
import copy
import hashlib
import json
from pathlib import Path
from typing import Iterator

from ._compat import BRANCHES, parse_answer

DEFAULT_ROOT = Path(__file__).resolve().parent.parent


def canonical_sha256(value: object) -> str:
    payload = json.dumps(value, ensure_ascii=False, sort_keys=True,
                         separators=(',', ':'), allow_nan=False).encode()
    return hashlib.sha256(payload).hexdigest()


def read_json(path: Path) -> dict:
    return parse_answer(path.read_text(encoding='utf-8'))


def read_jsonl(path: Path) -> Iterator[dict]:
    with path.open(encoding='utf-8') as stream:
        for number, line in enumerate(stream, 1):
            if not line.strip():
                continue
            try:
                yield parse_answer(line)
            except (ValueError, TypeError) as error:
                raise ValueError(f'{path.name}:{number}: {error}') from error


def contained_path(root: Path, relative: str) -> Path:
    """Accept only files below root, including when a path is a symlink."""
    rel = Path(relative)
    if rel.is_absolute() or '..' in rel.parts:
        raise ValueError(f'expected a contained relative path: {relative!r}')
    path = (root / rel).resolve()
    if root.resolve() not in path.parents:
        raise ValueError(f'path escapes the dataset: {relative!r}')
    return path


def index_rows(path: Path) -> dict[str, dict]:
    result = {}
    for row in read_jsonl(path):
        key = row.get('item_id')
        if not isinstance(key, str) or not key or key in result:
            raise ValueError(f'invalid or duplicate item_id in {path.name}: {key!r}')
        result[key] = row
    return result


class Dataset:
    """One frozen test subset; image paths are resolved locally, without networking."""

    def __init__(self, subset: str, root: str | Path | None = None):
        self.root = Path(root).resolve() if root is not None else DEFAULT_ROOT
        self.manifest = read_json(self.root / 'manifest.json')
        if self.manifest.get('schema') != 'prowm-bench-release.v1':
            raise ValueError('unsupported release schema')
        if subset not in self.manifest['subsets']:
            raise ValueError(f'unknown subset {subset!r}; choose swemm or rs')
        self.subset = subset
        self.info = self.manifest['subsets'][subset]
        self.directory = contained_path(self.root, 'data/' + subset)
        self.items = index_rows(self.directory / 'items.jsonl')
        self._prompts = index_rows(self.directory / 'prompts.jsonl')
        self._provenance = index_rows(self.directory / 'provenance.jsonl')
        if (set(self.items) != set(self._prompts) or set(self.items) != set(self._provenance)
                or len(self.items) != self.info['items']):
            raise ValueError('frozen population membership mismatch')
        for item_id, item in self.items.items():
            if canonical_sha256(item) != self._provenance[item_id]['prepared']['public_sha256']:
                raise ValueError(f'public item changed: {item_id}')
            if set(self._prompts[item_id]['messages']) != set(BRANCHES):
                raise ValueError(f'prompt branch membership mismatch: {item_id}')
        self._image_cache: dict[str, str] = {}

    def __len__(self) -> int:
        return len(self.items)

    def messages(self, item_id: str, branch: str, *, inline_images: bool = True) -> list[dict]:
        """Return a fresh prompt. Inline mode reconstructs the original data URLs."""
        if branch not in BRANCHES:
            raise ValueError(f'unknown branch: {branch}')
        messages = copy.deepcopy(self._prompts[item_id]['messages'][branch])
        for message in messages:
            if not isinstance(message.get('content'), list):
                continue
            for part in message['content']:
                if part.get('type') != 'image_url':
                    continue
                relative = part['image_url']['url']
                if not relative.startswith('images/') or not relative.endswith('.png'):
                    raise ValueError('model inputs may reference input PNGs only')
                path = contained_path(self.directory, relative)
                if not path.is_file():
                    raise FileNotFoundError(path)
                if inline_images:
                    if relative not in self._image_cache:
                        blob = path.read_bytes()
                        if hashlib.sha256(blob).hexdigest() != path.stem:
                            raise ValueError(f'input image hash mismatch: {relative}')
                        self._image_cache[relative] = 'data:image/png;base64,' + base64.b64encode(blob).decode('ascii')
                    part['image_url']['url'] = self._image_cache[relative]
        if inline_images:
            expected = self._provenance[item_id]['prepared']['messages_sha256'][branch]
            if canonical_sha256(messages) != expected:
                raise ValueError(f'reconstructed prompt differs from frozen input: {item_id}/{branch}')
        return messages

    def requests(self, *, branches: tuple[str, ...] = BRANCHES,
                 limit: int | None = None, inline_images: bool = True) -> Iterator[dict]:
        """Yield one independent request per item/branch. limit counts items."""
        if limit is not None and limit < 1:
            raise ValueError('limit must be positive')
        if not branches or len(set(branches)) != len(branches) or any(b not in BRANCHES for b in branches):
            raise ValueError('branches must be a nonempty unique selection')
        for number, item_id in enumerate(self.items):
            if limit is not None and number >= limit:
                break
            for branch in branches:
                yield {'item_id': item_id, 'branch': branch,
                       'messages': self.messages(item_id, branch, inline_images=inline_images)}


def load_dataset(subset: str = 'swemm', root: str | Path | None = None) -> Dataset:
    """Load public inputs only; no Hugging Face SDK, Docker or GPU is required."""
    return Dataset(subset, root)


def verify_release(root: str | Path | None = None) -> dict:
    """Check every packaged file and every reconstructed model prompt."""
    directory = Path(root).resolve() if root is not None else DEFAULT_ROOT
    checksums = read_json(directory / 'checksums.json')
    for relative, expected in checksums['files'].items():
        path = contained_path(directory, relative)
        if path.stat().st_size != expected['size_bytes']:
            raise ValueError(f'file size mismatch: {relative}')
        if hashlib.sha256(path.read_bytes()).hexdigest() != expected['sha256']:
            raise ValueError(f'file hash mismatch: {relative}')
    subsets = {}
    for subset in read_json(directory / 'manifest.json')['subsets']:
        dataset = Dataset(subset, directory)
        count = sum(1 for _ in dataset.requests())
        targets = index_rows(dataset.directory / 'targets.jsonl')
        if set(targets) != set(dataset.items):
            raise ValueError('target membership mismatch')
        for row in read_jsonl(dataset.directory / 'gold_images.jsonl'):
            if row['image'] is not None:
                contained_path(dataset.directory, row['image']).read_bytes()
        subsets[subset] = {'items': len(dataset), 'reconstructed_prompts': count}
    return {'ok': True, 'verified_files': len(checksums['files']), 'subsets': subsets}