File size: 2,091 Bytes
311c1fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import json
from pathlib import Path

import pandas as pd


REPO_ROOT = Path(__file__).resolve().parents[2]
RELEASE_ROOT = Path(__file__).resolve().parents[1]
SOURCE_JSON = REPO_ROOT / "dataset_with_images.json"
OUTPUT_DIR = RELEASE_ROOT / "data"
PARQUET_PATH = OUTPUT_DIR / "train-00000-of-00001.parquet"
JSONL_PATH = OUTPUT_DIR / "train.jsonl"


def load_records() -> list[dict]:
    with SOURCE_JSON.open("r", encoding="utf-8") as f:
        raw_records = json.load(f)

    records = []
    for raw in raw_records:
        record = {
            "id": raw["id"].strip(),
            "category": raw["category"].strip(),
            "website": raw["website"].strip(),
            "brief": raw["brief"].strip(),
            "content": raw["content"].strip(),
            "function": raw["function"].strip(),
            "style": raw["style"].strip(),
        }
        records.append(record)

    return sorted(records, key=lambda item: item["id"])


def validate_records(records: list[dict]) -> None:
    ids = [record["id"] for record in records]
    if len(ids) != len(set(ids)):
        raise ValueError("Duplicate ids detected in release data.")

    for record in records:
        for key, value in record.items():
            if not isinstance(value, str) or not value:
                raise ValueError(f"Invalid value for {key!r} in record {record['id']}.")


def write_jsonl(records: list[dict]) -> None:
    with JSONL_PATH.open("w", encoding="utf-8") as f:
        for record in records:
            f.write(json.dumps(record, ensure_ascii=False) + "\n")


def write_parquet(records: list[dict]) -> None:
    frame = pd.DataFrame.from_records(records)
    frame.to_parquet(PARQUET_PATH, index=False)


def main() -> None:
    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
    records = load_records()
    validate_records(records)
    write_jsonl(records)
    write_parquet(records)
    print(f"Wrote {len(records)} records to {JSONL_PATH}")
    print(f"Wrote {len(records)} records to {PARQUET_PATH}")


if __name__ == "__main__":
    main()