File size: 5,838 Bytes
241ce59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Deploy helper for:
1) Uploading fine-tuned weights to a model repo.
2) Uploading Space code to a Streamlit Space repo.

Usage:
  HF_TOKEN=hf_xxx python3 deploy_hf.py
"""

from __future__ import annotations

import argparse
import os
import sys
from typing import Iterable

from huggingface_hub import HfApi
from huggingface_hub.errors import BadRequestError


DEFAULT_WEIGHTS_REPO = "griddev/vlm-caption-weights"
DEFAULT_SPACE_REPO = "griddev/project_02_DS"
DEFAULT_WEIGHTS_SOURCE = "../project_02"
DEFAULT_SPACE_DIR = "."
DEFAULT_SPACE_SDK = "streamlit"


def _abort(message: str) -> None:
    print(f"ERROR: {message}", file=sys.stderr)
    raise SystemExit(1)


def _ensure_exists(path: str) -> None:
    if not os.path.exists(path):
        _abort(f"Required path not found: {path}")


def _print_list(header: str, items: Iterable[str]) -> None:
    print(header)
    for item in items:
        print(f"  - {item}")


def upload_weights(api: HfApi, repo_id: str, weights_source: str) -> None:
    source_root = os.path.abspath(weights_source)
    outputs_dir = os.path.join(source_root, "outputs")
    shakespeare_txt = os.path.join(source_root, "input.txt")
    shakespeare_weights = os.path.join(source_root, "shakespeare_transformer.pt")

    _ensure_exists(outputs_dir)
    _ensure_exists(shakespeare_txt)
    _ensure_exists(shakespeare_weights)

    api.create_repo(repo_id=repo_id, repo_type="model", exist_ok=True)
    print(f"Uploading weights to model repo: {repo_id}")

    api.upload_folder(
        repo_id=repo_id,
        repo_type="model",
        folder_path=outputs_dir,
        path_in_repo="outputs",
        commit_message="Upload fine-tuned checkpoints",
    )
    api.upload_file(
        repo_id=repo_id,
        repo_type="model",
        path_or_fileobj=shakespeare_txt,
        path_in_repo="input.txt",
        commit_message="Upload input corpus for custom VLM",
    )
    api.upload_file(
        repo_id=repo_id,
        repo_type="model",
        path_or_fileobj=shakespeare_weights,
        path_in_repo="shakespeare_transformer.pt",
        commit_message="Upload Shakespeare decoder weights",
    )


def _create_space_repo(api: HfApi, repo_id: str, space_sdk: str) -> None:
    try:
        api.create_repo(
            repo_id=repo_id,
            repo_type="space",
            space_sdk=space_sdk,
            exist_ok=True,
        )
        return
    except BadRequestError as e:
        msg = str(e)
        if "Invalid option" not in msg or "sdk" not in msg:
            raise
        print(
            "Space creation rejected sdk value "
            f"'{space_sdk}'. Retrying with 'gradio' "
            "and relying on README.md front matter for streamlit."
        )
        api.create_repo(
            repo_id=repo_id,
            repo_type="space",
            space_sdk="gradio",
            exist_ok=True,
        )


def upload_space_code(api: HfApi, repo_id: str, space_dir: str, space_sdk: str) -> None:
    space_dir = os.path.abspath(space_dir)
    _ensure_exists(space_dir)

    _create_space_repo(api, repo_id=repo_id, space_sdk=space_sdk)
    print(f"Uploading Space code to: {repo_id}")

    ignore_patterns = [
        ".git/**",
        "__pycache__/**",
        "*.pyc",
        ".DS_Store",
        "venv/**",
        "weights_bundle/**",
        "outputs/**",
        "*.pt",
    ]
    _print_list("Ignoring during Space upload:", ignore_patterns)

    api.upload_folder(
        repo_id=repo_id,
        repo_type="space",
        folder_path=space_dir,
        ignore_patterns=ignore_patterns,
        commit_message="Deploy Streamlit Space app",
    )


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Deploy weights + Space to Hugging Face")
    parser.add_argument(
        "--weights-repo",
        default=DEFAULT_WEIGHTS_REPO,
        help=f"Model repo for fine-tuned checkpoints (default: {DEFAULT_WEIGHTS_REPO})",
    )
    parser.add_argument(
        "--space-repo",
        default=DEFAULT_SPACE_REPO,
        help=f"Space repo id (default: {DEFAULT_SPACE_REPO})",
    )
    parser.add_argument(
        "--weights-source",
        default=DEFAULT_WEIGHTS_SOURCE,
        help=f"Local folder containing outputs/, input.txt, shakespeare_transformer.pt (default: {DEFAULT_WEIGHTS_SOURCE})",
    )
    parser.add_argument(
        "--space-dir",
        default=DEFAULT_SPACE_DIR,
        help=f"Local Space code folder to upload (default: {DEFAULT_SPACE_DIR})",
    )
    parser.add_argument(
        "--space-sdk",
        default=DEFAULT_SPACE_SDK,
        help=f"Space SDK to request on create (default: {DEFAULT_SPACE_SDK})",
    )
    parser.add_argument(
        "--skip-weights",
        action="store_true",
        help="Skip uploading weights repo.",
    )
    parser.add_argument(
        "--skip-space",
        action="store_true",
        help="Skip uploading Space repo.",
    )
    parser.add_argument(
        "--token",
        default=os.getenv("HF_TOKEN"),
        help="Hugging Face token. Defaults to HF_TOKEN env var.",
    )
    return parser.parse_args()


def main() -> None:
    args = parse_args()
    if not args.token:
        _abort("No token found. Set HF_TOKEN or pass --token.")

    api = HfApi(token=args.token)

    if not args.skip_weights:
        upload_weights(api, repo_id=args.weights_repo, weights_source=args.weights_source)
    if not args.skip_space:
        upload_space_code(
            api,
            repo_id=args.space_repo,
            space_dir=args.space_dir,
            space_sdk=args.space_sdk,
        )

    print("Deployment finished.")
    print(f"Weights repo: https://huggingface.co/{args.weights_repo}")
    print(f"Space repo:   https://huggingface.co/spaces/{args.space_repo}")


if __name__ == "__main__":
    main()