File size: 5,781 Bytes
7c33ebc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Export ground-truth HTML from Hugging Face ``SALT-NLP/Design2Code-hf`` into
``data/gt_html/{id}.html``, aligned to ``data/ref_screenshots/{id}.png`` by
per-pixel MD5 (RGB).

Background:
  - Local ``design2code`` on disk may be image-only; this script re-fetches the
    HF split that includes the ``text`` column.
  - ``ref_screenshots/124.png`` is often truncated; when exactly one HF row is
    unmatched and stem ``124`` has no match, that row is treated as sample 124:
    optional PNG repair + ``gt_html/124.html``.

Usage:
  python scripts/export_design2code_gt_html.py
  python scripts/export_design2code_gt_html.py --output_dir data/gt_html --no-repair-124

Requires network; uses HF mirror by default (override with ``HF_ENDPOINT``).
"""

from __future__ import annotations

import argparse
import hashlib
import os
import shutil
import sys
from pathlib import Path

os.environ.setdefault("HF_ENDPOINT", "https://hf-mirror.com")
os.environ.setdefault("HF_HOME", os.environ.get("HF_HOME", "/root/rivermind-data/huggingface"))

from datasets import load_dataset
from PIL import Image

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


def _rgb_md5(pil: Image.Image) -> str:
    return hashlib.md5(pil.convert("RGB").tobytes()).hexdigest()


def _load_ref_hashes(ref_dir: Path) -> dict[str, str | None]:
    """stem -> md5 or None if unreadable."""
    out: dict[str, str | None] = {}
    for p in sorted(ref_dir.glob("*.png")):
        try:
            out[p.stem] = _rgb_md5(Image.open(p))
        except Exception:
            out[p.stem] = None
    return out


def main() -> int:
    parser = argparse.ArgumentParser(description="Export Design2Code GT HTML for ref_screenshots.")
    parser.add_argument("--ref_dir", type=Path, default=PROJECT_ROOT / "data" / "ref_screenshots")
    parser.add_argument("--output_dir", type=Path, default=PROJECT_ROOT / "data" / "gt_html")
    parser.add_argument("--hf_dataset", default="SALT-NLP/Design2Code-hf")
    parser.add_argument(
        "--repair-124",
        dest="repair_124",
        action="store_true",
        default=True,
        help="If one orphan HF row and stem 124 unmatched, save its image/HTML for 124 (default: on).",
    )
    parser.add_argument("--no-repair-124", dest="repair_124", action="store_false")
    args = parser.parse_args()

    ref_dir = args.ref_dir.resolve()
    out_dir = args.output_dir.resolve()
    if not ref_dir.is_dir():
        print(f"ref_dir not found: {ref_dir}", file=sys.stderr)
        return 1

    out_dir.mkdir(parents=True, exist_ok=True)

    print(f"Loading {args.hf_dataset} (HF_ENDPOINT={os.environ.get('HF_ENDPOINT')})...")
    ds = load_dataset(args.hf_dataset, split="train")
    n = len(ds)
    print(f"  HF rows: {n}")

    stem_hash = _load_ref_hashes(ref_dir)
    hash_to_stem: dict[str, str] = {}
    for stem, h in stem_hash.items():
        if h is not None:
            hash_to_stem[h] = stem

    idx_to_stem: dict[int, str] = {}
    for i in range(n):
        h = _rgb_md5(ds[i]["image"])
        if h in hash_to_stem:
            idx_to_stem[i] = hash_to_stem[h]

    orphan_idx = [i for i in range(n) if i not in idx_to_stem]
    all_stems = set(stem_hash.keys())
    mapped_stems = set(idx_to_stem.values())
    stems_no_gt = sorted(all_stems - mapped_stems, key=lambda x: int(x))

    print(f"  Matched by image hash: {len(idx_to_stem)} / {n}")
    print(f"  HF rows without ref match: {orphan_idx}")
    print(f"  Ref stems without HF match: {stems_no_gt}")

    repair_pair: tuple[int, str] | None = None
    if (
        args.repair_124
        and len(orphan_idx) == 1
        and stems_no_gt == ["124", "484"]
        and stem_hash.get("124") is None
    ):
        repair_pair = (orphan_idx[0], "124")
        print(f"  Repair: assign HF row {repair_pair[0]} -> stem 124 (truncated PNG + GT).")
    elif args.repair_124 and len(orphan_idx) == 1 and "124" in stems_no_gt:
        # e.g. 484 already matched elsewhere
        only = [s for s in stems_no_gt if s != "484"]
        if len(only) == 1 and only[0] == "124" and stem_hash.get("124") is None:
            repair_pair = (orphan_idx[0], "124")
            print(f"  Repair: assign HF row {repair_pair[0]} -> stem 124.")

    written = 0
    for i in range(n):
        if repair_pair and i == repair_pair[0]:
            continue
        stem = idx_to_stem.get(i)
        if not stem:
            continue
        text = ds[i]["text"]
        if not isinstance(text, str) or not text.strip():
            print(f"  [skip] row {i} stem {stem}: empty text", file=sys.stderr)
            continue
        (out_dir / f"{stem}.html").write_text(text, encoding="utf-8")
        written += 1

    if repair_pair:
        i, stem = repair_pair
        text = ds[i]["text"]
        if not isinstance(text, str) or not text.strip():
            print(f"  [error] repair row {i} has empty text", file=sys.stderr)
            return 1
        png_path = ref_dir / f"{stem}.png"
        bak = ref_dir / f"{stem}.png.broken"
        if png_path.exists() and not bak.exists():
            shutil.copy2(png_path, bak)
            print(f"  Backed up broken PNG to {bak.name}")
        ds[i]["image"].convert("RGB").save(png_path, format="PNG")
        (out_dir / f"{stem}.html").write_text(text, encoding="utf-8")
        written += 1
        print(f"  Wrote repaired {png_path.name} and gt_html/{stem}.html")

    if "484" in stems_no_gt:
        print(
            "  Note: stem 484 has no row in Design2Code-hf (484 HF rows vs 485 local PNGs). "
            "No gt_html/484.html; drop or supply GT manually if needed.",
            file=sys.stderr,
        )

    print(f"Done. Wrote {written} HTML files under {out_dir}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())