File size: 10,476 Bytes
fa1b65a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c75247
fa1b65a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfaf05b
fa1b65a
cfaf05b
fa1b65a
cfaf05b
fa1b65a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfaf05b
fa1b65a
 
cfaf05b
fa1b65a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfaf05b
fa1b65a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c75247
fa1b65a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfaf05b
fa1b65a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfaf05b
fa1b65a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfaf05b
 
fa1b65a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
StudyCraft deployment script β€” HuggingFace Spaces & local Docker.

Usage:
    uv run python scripts/deploy.py --target huggingface --setup
        Create a new HuggingFace Space (Docker SDK) for studycraft.

    uv run python scripts/deploy.py --target huggingface --deploy
        Push code to HuggingFace Spaces (uses hf-deploy branch, swaps README).

    uv run python scripts/deploy.py --target huggingface --secret
        Set OPENROUTER_API_KEY secret on the HuggingFace Space.

    uv run python scripts/deploy.py --target local
        Build and run locally with docker-compose up -d --build.

    uv run python scripts/deploy.py --target local --stop
        Stop local docker-compose deployment.

Options:
    --space-name NAME    Space name (default: studycraft)
    --org ORG           HuggingFace organization/username
    --branch BRANCH     Deploy branch name (default: hf-deploy)
    --secret-value VAL  Secret value (if not provided, will prompt)
"""

import argparse
import shutil
import subprocess
import sys
from pathlib import Path

RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
RESET = "\033[0m"
DIM = "\033[2m"

PROJECT_ROOT = Path(__file__).parent.parent
HF_README = PROJECT_ROOT / "README.hf-spaces.md"
MAIN_README = PROJECT_ROOT / "README.md"


def run(cmd: list[str], check: bool = True) -> subprocess.CompletedProcess:
    """Run a command, echo it, and return the result."""
    print(f"{DIM}$ {' '.join(cmd)}{RESET}")
    result = subprocess.run(cmd, cwd=PROJECT_ROOT)
    if check and result.returncode != 0:
        print(f"{RED}Command failed: {' '.join(cmd)}{RESET}")
        sys.exit(1)
    return result


def _ensure_hf_cli() -> None:
    """Check that hf CLI is available."""
    try:
        run(["hf", "--help"], check=False)
    except FileNotFoundError:
        print(f"{RED}Error: hf CLI not found. Install with:{RESET}")
        print(f"  {DIM}pip install huggingface_hub{RESET}")
        sys.exit(1)


def cmd_hf_setup(args: argparse.Namespace) -> None:
    """Create the HuggingFace Space if it doesn't exist."""
    _ensure_hf_cli()
    space_name = args.space_name
    org = args.org or "YOUR_HF_USERNAME"

    repo_id = f"{org}/{space_name}" if org else space_name

    print(f"{YELLOW}Creating HuggingFace Space: {repo_id}{RESET}")
    print(f"  SDK: docker")
    print(f"  Port: 8000")

    # Use hf CLI to create the space
    # The CLI will prompt for confirmation if the space already exists
    cmd = [
        "hf",
        "repo",
        "create",
        space_name,
        "--type",
        "space",
        "--space-sdk",
        "docker",
    ]
    if org:
        cmd.extend(["--organization", org])

    try:
        run(cmd)
        print(f"{GREEN}βœ“ Space created: https://huggingface.co/spaces/{repo_id}{RESET}")
    except SystemExit:
        print(f"{YELLOW}Space may already exist. Continuing...{RESET}")

    print(f"\nNext steps:")
    print(
        f"  1. Set secrets: {DIM}hf env --repo-id {repo_id} set OPENROUTER_API_KEY <your-key>{RESET}"
    )
    print(
        f"  2. Deploy:      {DIM}uv run python scripts/deploy.py --target huggingface --deploy{RESET}"
    )


def cmd_hf_deploy(args: argparse.Namespace) -> None:
    """Push code to HuggingFace Spaces via a dedicated deploy branch."""
    _ensure_hf_cli()
    space_name = args.space_name
    org = args.org or "YOUR_HF_USERNAME"
    branch = args.branch
    repo_id = f"{org}/{space_name}" if org else space_name

    print(f"{YELLOW}Deploying to HuggingFace Space: {repo_id}{RESET}")
    print(f"  Branch: {branch}")

    # 1. Check for uncommitted changes
    result = subprocess.run(["git", "status", "--porcelain"], capture_output=True, text=True)
    if result.stdout.strip():
        print(f"{RED}Error: You have uncommitted changes. Commit or stash them first.{RESET}")
        sys.exit(1)

    # 2. Ensure HF README exists
    if not HF_README.exists():
        print(f"{RED}Error: Missing {HF_README}{RESET}")
        print(f"  This file should contain the YAML frontmatter for HF Spaces.")
        sys.exit(1)

    # 3. Create/update deploy branch
    current_branch = subprocess.run(
        ["git", "branch", "--show-current"], capture_output=True, text=True
    ).stdout.strip()

    # Check if branch exists
    branches = subprocess.run(["git", "branch", "-a"], capture_output=True, text=True).stdout
    if branch not in branches:
        print(f"{YELLOW}Creating deploy branch '{branch}'...{RESET}")
        run(["git", "checkout", "-b", branch])
    else:
        print(f"{YELLOW}Switching to deploy branch '{branch}'...{RESET}")
        run(["git", "checkout", branch])

    # 4. Replace README.md with HF version
    print(f"{YELLOW}Swapping README.md for HF Spaces version...{RESET}")
    backup = MAIN_README.with_suffix(".md.backup")
    MAIN_README.rename(backup)
    shutil.copy(HF_README, MAIN_README)
    run(["git", "add", "README.md"])
    run(["git", "commit", "-m", "chore: use HF Spaces README for deployment"], check=False)

    # 5. Push to HF
    # Add remote if not present
    remote_name = "hf"
    remotes = subprocess.run(["git", "remote"], capture_output=True, text=True).stdout.split()
    if remote_name not in remotes:
        remote_url = f"https://huggingface.co/spaces/{repo_id}"
        print(f"{YELLOW}Adding remote '{remote_name}': {remote_url}{RESET}")
        run(["git", "remote", "add", remote_name, remote_url])

    print(f"{YELLOW}Pushing to HuggingFace Spaces (branch:main)...{RESET}")
    run(["git", "push", remote_name, f"{branch}:main", "--force"])

    # 6. Restore main branch README
    print(f"{YELLOW}Restoring original README...{RESET}")
    run(["git", "checkout", current_branch])
    backup.rename(MAIN_README)

    print(f"\n{GREEN}βœ“ Deployment complete!{RESET}")
    print(f"  https://huggingface.co/spaces/{repo_id}")
    print(f"\nTo set secrets:")
    print(f"  {DIM}hf env --repo-id {repo_id} set OPENROUTER_API_KEY <your-key>{RESET}")


def cmd_hf_secret(args: argparse.Namespace) -> None:
    """Set a secret on the HuggingFace Space."""
    _ensure_hf_cli()
    space_name = args.space_name
    org = args.org or "YOUR_HF_USERNAME"
    repo_id = f"{org}/{space_name}" if org else space_name
    secret_name = args.secret_name or "OPENROUTER_API_KEY"
    secret_value = args.secret_value

    if not secret_value:
        import getpass

        secret_value = getpass.getpass(f"Enter value for {secret_name}: ")

    print(f"{YELLOW}Setting secret '{secret_name}' on {repo_id}...{RESET}")
    run(["hf", "env", "--repo-id", repo_id, "set", secret_name, secret_value])
    print(f"{GREEN}βœ“ Secret set{RESET}")


def cmd_local(args: argparse.Namespace) -> None:
    """Build and run locally with docker-compose."""
    print(f"{YELLOW}Local Docker Compose deployment{RESET}")

    compose_file = PROJECT_ROOT / "docker-compose.yml"
    if not compose_file.exists():
        print(f"{RED}Error: {compose_file} not found{RESET}")
        sys.exit(1)

    if args.stop:
        print(f"{YELLOW}Stopping StudyCraft...{RESET}")
        run(["docker-compose", "-f", str(compose_file), "down"])
        print(f"{GREEN}βœ“ Stopped{RESET}")
        return

    # Build and start
    print(f"{YELLOW}Building and starting StudyCraft...{RESET}")
    run(["docker-compose", "-f", str(compose_file), "up", "-d", "--build"])
    print(f"{GREEN}βœ“ StudyCraft is running{RESET}")
    print(f"  Web UI: {DIM}http://localhost:8000{RESET}")
    print(f"  API docs: {DIM}http://localhost:8000/docs{RESET}")
    print(f"\nTo view logs:")
    print(f"  {DIM}docker-compose -f {compose_file} logs -f{RESET}")
    print(f"\nTo stop:")
    print(f"  {DIM}uv run python scripts/deploy.py --target local --stop{RESET}")


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Deploy StudyCraft to HuggingFace Spaces or local Docker.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  # One-time HF Space setup
  uv run python scripts/deploy.py --target huggingface --setup --org my-org

  # Deploy code to HF Spaces
  uv run python scripts/deploy.py --target huggingface --deploy

  # Set API key secret on HF Space
  uv run python scripts/deploy.py --target huggingface --secret

  # Deploy locally with docker-compose
  uv run python scripts/deploy.py --target local

Note: Uses the 'hf' CLI (huggingface_hub). Install with: pip install huggingface_hub
        """,
    )

    parser.add_argument(
        "--target",
        "-t",
        choices=["huggingface", "local"],
        required=True,
        help="Deployment target: huggingface (HF Spaces) or local (docker-compose)",
    )

    # HuggingFace actions
    parser.add_argument(
        "--setup",
        action="store_true",
        help="Create the HuggingFace Space (one-time setup)",
    )
    parser.add_argument(
        "--deploy",
        action="store_true",
        help="Push code to HuggingFace Spaces (requires hf-deploy branch workflow)",
    )
    parser.add_argument(
        "--secret",
        action="store_true",
        help="Set a secret on the HuggingFace Space",
    )
    parser.add_argument(
        "--secret-name",
        default="OPENROUTER_API_KEY",
        help="Secret name (default: OPENROUTER_API_KEY)",
    )
    parser.add_argument(
        "--secret-value",
        help="Secret value (will prompt if not provided)",
    )

    # Local actions
    parser.add_argument(
        "--stop",
        action="store_true",
        help="Stop local docker-compose deployment",
    )

    # Common options
    parser.add_argument(
        "--space-name",
        default="studycraft",
        help="HuggingFace Space name (default: studycraft)",
    )
    parser.add_argument(
        "--org",
        default=None,
        help="HuggingFace organization/username (default: your logged-in user)",
    )
    parser.add_argument(
        "--branch",
        default="hf-deploy",
        help="Deploy branch name (default: hf-deploy)",
    )

    args = parser.parse_args()

    if args.target == "huggingface":
        if args.setup:
            cmd_hf_setup(args)
        elif args.deploy:
            cmd_hf_deploy(args)
        elif args.secret:
            cmd_hf_secret(args)
        else:
            parser.error("Specify --setup, --deploy, or --secret for HuggingFace target")
    elif args.target == "local":
        cmd_local(args)


if __name__ == "__main__":
    main()