File size: 5,712 Bytes
bb01096
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
UIPress: Download all required datasets and verify integrity.

Usage:
    python scripts/download_data.py
    python scripts/download_data.py --skip_webcode  # skip WebCode2M
"""

# ---- HuggingFace 镜像 (必须在其他 import 之前) ----
import os
os.environ["HF_ENDPOINT"] = "https://hf-mirror.com"
os.environ["HF_HOME"] = "/root/rivermind-data/huggingface"

import argparse
import subprocess
import sys
from pathlib import Path

PROJECT_ROOT = Path(__file__).parent.parent
DATA_DIR = PROJECT_ROOT / "data"
REPOS_DIR = PROJECT_ROOT / "repos"


def run(cmd, cwd=None):
    """Run shell command with error handling."""
    print(f"  >> {cmd}")
    result = subprocess.run(cmd, shell=True, cwd=cwd, capture_output=True, text=True)
    if result.returncode != 0:
        print(f"  [WARN] {result.stderr.strip()}")
    return result.returncode == 0


def download_design2code():
    """Download Design2Code dataset from HuggingFace."""
    print("\n[1/4] Downloading Design2Code dataset...")
    d2c_dir = DATA_DIR / "design2code"

    if d2c_dir.exists() and any(d2c_dir.iterdir()):
        print("  Already exists, skipping.")
        return

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

    try:
        from datasets import load_dataset
        # Use Design2Code-hf: cleaner format with 'image' + 'text' (HTML code) columns
        print("  Loading from HuggingFace: SALT-NLP/Design2Code-hf...")
        try:
            ds = load_dataset("SALT-NLP/Design2Code-hf")
        except Exception:
            print("  Fallback to SALT-NLP/Design2Code...")
            ds = load_dataset("SALT-NLP/Design2Code")
        ds.save_to_disk(str(d2c_dir))
        for split in ds:
            print(f"  Split '{split}': {len(ds[split])} samples")
    except Exception as e:
        print(f"  [ERROR] HuggingFace download failed: {e}")
        print("  Fallback: trying git clone of the eval repo (includes test data)...")
        clone_design2code_repo()


def clone_design2code_repo():
    """Clone Design2Code GitHub repo for evaluation code."""
    print("\n[2/4] Cloning Design2Code evaluation repo...")
    repo_dir = REPOS_DIR / "Design2Code"

    if repo_dir.exists():
        print("  Already exists, skipping.")
        return

    REPOS_DIR.mkdir(parents=True, exist_ok=True)
    run("git clone https://github.com/NoviScl/Design2Code.git", cwd=str(REPOS_DIR))

    if repo_dir.exists():
        print(f"  Cloned to {repo_dir}")
        # Check if testset exists in the repo
        testset = repo_dir / "testset_final"
        if testset.exists():
            print(f"  Found testset at {testset}")
            # Symlink to data dir for convenience
            link_path = DATA_DIR / "testset_final"
            if not link_path.exists():
                os.symlink(str(testset), str(link_path))
                print(f"  Symlinked to {link_path}")
    else:
        print("  [ERROR] Clone failed. Please clone manually:")
        print("    git clone https://github.com/NoviScl/Design2Code.git repos/Design2Code")


def clone_deepseek_ocr_repo():
    """Clone DeepSeek-OCR repo for reference code."""
    print("\n[3/4] Cloning DeepSeek-OCR repo...")
    repo_dir = REPOS_DIR / "DeepSeek-OCR"

    if repo_dir.exists():
        print("  Already exists, skipping.")
        return

    REPOS_DIR.mkdir(parents=True, exist_ok=True)
    run("git clone https://github.com/deepseek-ai/DeepSeek-OCR.git", cwd=str(REPOS_DIR))

    if repo_dir.exists():
        print(f"  Cloned to {repo_dir}")
    else:
        print("  [ERROR] Clone failed. Please clone manually.")


def verify_model_access():
    """Verify HuggingFace model access (doesn't download full weights)."""
    print("\n[4/4] Verifying model access on HuggingFace...")
    models = [
        "Qwen/Qwen3-VL-2B-Instruct",
        "Qwen/Qwen2.5-VL-7B-Instruct",
        "deepseek-ai/DeepSeek-OCR",
    ]
    for model_id in models:
        try:
            from huggingface_hub import model_info
            info = model_info(model_id)
            size_gb = sum(s.size for s in info.siblings if s.rfilename.endswith(('.safetensors', '.bin')) and s.size is not None) / 1e9
            print(f"  {model_id}: OK ({size_gb:.1f} GB)")
        except Exception as e:
            print(f"  {model_id}: [WARN] {e}")
            print(f"    Model will be downloaded on first use.")


def print_summary():
    """Print summary of downloaded data."""
    print("\n" + "=" * 60)
    print("DOWNLOAD SUMMARY")
    print("=" * 60)

    # Check data
    for name, path in [
        ("Design2Code (HF)", DATA_DIR / "design2code"),
        ("Design2Code (raw)", DATA_DIR / "testset_final"),
    ]:
        status = "OK" if path.exists() and any(path.iterdir()) else "MISSING"
        print(f"  {name:<30} [{status}] {path}")

    # Check repos
    for name, path in [
        ("Design2Code eval repo", REPOS_DIR / "Design2Code"),
        ("DeepSeek-OCR repo", REPOS_DIR / "DeepSeek-OCR"),
    ]:
        status = "OK" if path.exists() else "MISSING"
        print(f"  {name:<30} [{status}] {path}")

    print("=" * 60)
    print("\nNext: run baseline evaluation:")
    print("  python scripts/step1_baseline.py --model qwen3_vl_2b --max_samples 5")


def main():
    parser = argparse.ArgumentParser(description="Download UIPress datasets")
    parser.add_argument("--skip_webcode", action="store_true",
                        help="Skip WebCode2M download")
    args = parser.parse_args()

    DATA_DIR.mkdir(parents=True, exist_ok=True)
    REPOS_DIR.mkdir(parents=True, exist_ok=True)

    download_design2code()
    clone_design2code_repo()
    clone_deepseek_ocr_repo()
    verify_model_access()
    print_summary()


if __name__ == "__main__":
    main()