Datasets:

Languages:
English
ArXiv:
License:
File size: 11,852 Bytes
234f610
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
"""Convenience reader for the supplemental Hugging Face source bundle.



This script lives inside the published `huggingface/` folder so users can read

source-side data directly from the exported package without depending on the

rest of the repository layout.

"""

import argparse
import json
import re
import sys
from pathlib import Path


HF_ROOT = Path(__file__).resolve().parents[1]
ROOT = HF_ROOT.parent
SOURCE_RECORDS_DIR = HF_ROOT / "source_records"
SOURCE_RECORDS_BY_ID_DIR = SOURCE_RECORDS_DIR / "by_id"
SUMMARY_PATH = SOURCE_RECORDS_DIR / "summary.json"


def flatten_sample_ids(sample_id_args):
    sample_ids = []
    for item in sample_id_args or []:
        sample_ids.extend(item)
    return [str(sample_id) for sample_id in sample_ids]


def load_json(path: Path):
    with open(path, "r", encoding="utf-8") as handle:
        return json.load(handle)


def load_sample_ids_from_file(path: Path):
    sample_ids = []
    with open(path, "r", encoding="utf-8") as handle:
        for line in handle:
            sample_id = line.strip()
            if sample_id:
                sample_ids.append(sample_id)
    return sample_ids


def strip_html_tags(text: str):
    text = re.sub(r"<script.*?</script>", " ", text, flags=re.IGNORECASE | re.DOTALL)
    text = re.sub(r"<style.*?</style>", " ", text, flags=re.IGNORECASE | re.DOTALL)
    text = re.sub(r"<[^>]+>", " ", text)
    text = re.sub(r"\s+", " ", text)
    return text.strip()


def walk_path(value, dotted_path: str):
    current = value
    for part in dotted_path.split("."):
        if isinstance(current, dict):
            if part not in current:
                raise KeyError(part)
            current = current[part]
            continue
        if isinstance(current, list):
            index = int(part)
            current = current[index]
            continue
        raise KeyError(part)
    return current


def first_nonempty(values):
    for value in values:
        if value not in (None, "", [], {}):
            return value
    return None


def extract_preferred_umf(record):
    candidates = []
    for dataset_name in ("property_prediction", "image_generation"):
        dataset_block = record.get(dataset_name, {})
        for split_name in ("train", "test"):
            split_block = dataset_block.get(split_name)
            if not split_block:
                continue
            recipe = split_block.get("recipe") or {}
            metadata = split_block.get("metadata") or {}
            candidates.append(recipe.get("umf"))
            candidates.append(metadata.get("umf"))
    html_metadata = record.get("html_metadata") or {}
    if isinstance(html_metadata, dict):
        candidates.append(html_metadata.get("umf"))
    return first_nonempty(candidates)


def extract_shortcut(record, field_name: str):
    html_metadata = record.get("html_metadata") or {}
    if field_name == "title":
        return first_nonempty([
            html_metadata.get("title") if isinstance(html_metadata, dict) else None,
        ])
    if field_name == "author":
        return first_nonempty([
            html_metadata.get("author") if isinstance(html_metadata, dict) else None,
        ])
    if field_name == "description":
        return first_nonempty([
            html_metadata.get("description") if isinstance(html_metadata, dict) else None,
            html_metadata.get("notes") if isinstance(html_metadata, dict) else None,
        ])
    if field_name == "umf":
        return extract_preferred_umf(record)
    raise KeyError(field_name)


def parse_args():
    parser = argparse.ArgumentParser(
        description="Read supplemental GlazyBench source-side data from the Hugging Face export."
    )
    parser.add_argument(
        "--sample-id",
        nargs="+",
        action="append",
        help="One or more sample IDs to read from huggingface/source_records/by_id.",
    )
    parser.add_argument(
        "--sample-id-file",
        help="Optional text file with one sample ID per line for batch reading.",
    )
    parser.add_argument(
        "--field",
        choices=[
            "full",
            "memberships",
            "property_prediction",
            "image_generation",
            "html_metadata",
            "raw_html_path",
            "title",
            "author",
            "description",
            "umf",
        ],
        default="full",
        help="Which part of the merged record to print.",
    )
    parser.add_argument(
        "--dataset",
        choices=["property_prediction", "image_generation"],
        help="Optional dataset selector when printing dataset-specific content.",
    )
    parser.add_argument(
        "--split",
        choices=["train", "test"],
        help="Optional split selector when printing dataset-specific content.",
    )
    parser.add_argument(
        "--summary",
        action="store_true",
        help="Print source bundle summary instead of an individual sample.",
    )
    parser.add_argument(
        "--list-sample-ids",
        type=int,
        default=0,
        help="Print the first N sample IDs available in source_records/by_id.",
    )
    parser.add_argument(
        "--list-fields",
        action="store_true",
        help="Print the top-level fields available in a sample record.",
    )
    parser.add_argument(
        "--path",
        help="Optional dotted path lookup inside the selected record value, for example property_prediction.test.recipe.umf.",
    )
    parser.add_argument(
        "--html-preview-chars",
        type=int,
        default=0,
        help="Also print the first N characters of the raw HTML file for the sample.",
    )
    parser.add_argument(
        "--html-preview-strip-tags",
        action="store_true",
        help="When previewing HTML, strip tags into rough plain text.",
    )
    parser.add_argument(
        "--output-format",
        choices=["json", "jsonl", "text"],
        default="json",
        help="Output format for batch or single-sample exports.",
    )
    parser.add_argument(
        "--output",
        help="Optional output file path. If omitted, prints to stdout.",
    )
    parser.add_argument(
        "--compact",
        action="store_true",
        help="Print compact JSON instead of pretty JSON.",
    )
    return parser.parse_args()


def render_json(value, compact: bool):
    if compact:
        return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
    return json.dumps(value, ensure_ascii=False, indent=2)


def write_output(text: str, output_path: str | None):
    if output_path:
        path = Path(output_path)
        path.parent.mkdir(parents=True, exist_ok=True)
        with open(path, "w", encoding="utf-8") as handle:
            handle.write(text)
        return
    print(text)


def list_sample_ids(limit: int):
    sample_ids = sorted(path.stem for path in SOURCE_RECORDS_BY_ID_DIR.glob("*.json"))
    if limit > 0:
        sample_ids = sample_ids[:limit]
    return sample_ids


def get_record(sample_id: str):
    path = SOURCE_RECORDS_BY_ID_DIR / f"{sample_id}.json"
    if not path.exists():
        raise FileNotFoundError(f"Sample record not found: {path}")
    return load_json(path), path


def select_value(record, args):
    if args.field == "full":
        value = record
    elif args.field == "memberships":
        value = record.get("memberships", [])
    elif args.field == "html_metadata":
        value = record.get("html_metadata")
    elif args.field == "raw_html_path":
        raw_relpath = record.get("raw_html_relpath")
        value = None if raw_relpath is None else str(HF_ROOT / raw_relpath)
    elif args.field in {"title", "author", "description", "umf"}:
        value = extract_shortcut(record, args.field)
    else:
        dataset_block = record.get(args.field, {})
        if args.split:
            value = dataset_block.get(args.split)
        elif args.dataset and args.dataset != args.field:
            value = record.get(args.dataset, {})
        else:
            value = dataset_block
    if args.path:
        value = walk_path(value, args.path)
    return value


def maybe_get_html_preview(record, chars: int, strip_tags: bool):
    if chars <= 0:
        return None
    raw_relpath = record.get("raw_html_relpath")
    if raw_relpath is None:
        return "<missing raw html>"
    html_path = HF_ROOT / raw_relpath
    if not html_path.exists():
        return f"<file missing: {html_path}>"
    with open(html_path, "r", encoding="utf-8", errors="ignore") as handle:
        preview = handle.read(chars)
    if strip_tags:
        preview = strip_html_tags(preview)
    return preview


def build_sample_payload(sample_id: str, args):
    record, record_path = get_record(str(sample_id))

    if args.list_fields:
        payload = {
            "sample_id": str(sample_id),
            "record_path": str(record_path),
            "top_level_fields": sorted(record.keys()),
            "memberships": record.get("memberships", []),
        }
    else:
        value = select_value(record, args)
        payload = {
            "sample_id": str(sample_id),
            "record_path": str(record_path),
            "selected_field": args.field,
            "value": value,
        }

    html_preview = maybe_get_html_preview(record, args.html_preview_chars, args.html_preview_strip_tags)
    if html_preview is not None:
        payload["raw_html_preview"] = html_preview
    return payload


def render_payloads(payloads, args):
    if args.output_format == "jsonl":
        return "\n".join(render_json(payload, compact=True) for payload in payloads)
    if args.output_format == "text":
        lines = []
        for payload in payloads:
            lines.append(f"sample_id={payload.get('sample_id')}")
            lines.append(f"record_path={payload.get('record_path')}")
            if "selected_field" in payload:
                lines.append(f"selected_field={payload['selected_field']}")
                lines.append(f"value={payload.get('value')}")
            else:
                lines.append(f"top_level_fields={payload.get('top_level_fields')}")
            if "raw_html_preview" in payload:
                lines.append("raw_html_preview=")
                lines.append(str(payload["raw_html_preview"]))
            lines.append("")
        return "\n".join(lines).rstrip()
    if len(payloads) == 1:
        return render_json(payloads[0], args.compact)
    return render_json(payloads, args.compact)


def main():
    args = parse_args()

    if args.summary:
        write_output(render_json(load_json(SUMMARY_PATH), args.compact), args.output)
        return

    if args.list_sample_ids:
        payload = {
            "count": len(list_sample_ids(0)),
            "sample_ids": list_sample_ids(args.list_sample_ids),
        }
        write_output(render_json(payload, args.compact), args.output)
        return

    sample_ids = flatten_sample_ids(args.sample_id)
    if args.sample_id_file:
        sample_ids.extend(load_sample_ids_from_file(Path(args.sample_id_file)))
    if not sample_ids:
        raise SystemExit("Provide --sample-id, --sample-id-file, --summary, or --list-sample-ids.")

    payloads = [build_sample_payload(sample_id, args) for sample_id in sample_ids]
    write_output(render_payloads(payloads, args), args.output)


if __name__ == "__main__":
    try:
        main()
    except FileNotFoundError as exc:
        print(str(exc), file=sys.stderr)
        raise SystemExit(1)