Spaces:
Running
Running
ok
Browse files- .gitignore +3 -1
- deploy.py +0 -990
.gitignore
CHANGED
|
@@ -126,4 +126,6 @@ persistence/
|
|
| 126 |
|
| 127 |
local_deploy.py
|
| 128 |
test_vector_store_async.py
|
| 129 |
-
deploy_sdk.py
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
local_deploy.py
|
| 128 |
test_vector_store_async.py
|
| 129 |
+
deploy_sdk.py
|
| 130 |
+
|
| 131 |
+
deploy_hf.py
|
deploy.py
DELETED
|
@@ -1,990 +0,0 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
"""
|
| 3 |
-
deploy.py — Persistent data deployment for Hugging Face Spaces.
|
| 4 |
-
|
| 5 |
-
Usage:
|
| 6 |
-
python deploy.py
|
| 7 |
-
|
| 8 |
-
Flow:
|
| 9 |
-
1. Back up existing data from the deployed Space -> persistence/
|
| 10 |
-
2. Commit and push local changes to the Space repository
|
| 11 |
-
3. Wait for the Space to redeploy (poll /health)
|
| 12 |
-
4. Restore the backed-up data to the new deployment
|
| 13 |
-
5. Generate a comprehensive audit report
|
| 14 |
-
"""
|
| 15 |
-
|
| 16 |
-
import argparse
|
| 17 |
-
import io
|
| 18 |
-
import json
|
| 19 |
-
import os
|
| 20 |
-
import re
|
| 21 |
-
import subprocess
|
| 22 |
-
import sys
|
| 23 |
-
import tarfile
|
| 24 |
-
import time
|
| 25 |
-
import urllib.error
|
| 26 |
-
import urllib.request
|
| 27 |
-
from datetime import datetime, timezone
|
| 28 |
-
from pathlib import Path
|
| 29 |
-
from typing import Any, Optional
|
| 30 |
-
|
| 31 |
-
# ─────────────────────────────────────────────────────────────
|
| 32 |
-
# Console encoding detection
|
| 33 |
-
# ─────────────────────────────────────────────────────────────
|
| 34 |
-
|
| 35 |
-
_USE_UNICODE = True
|
| 36 |
-
try:
|
| 37 |
-
"\u2713".encode(sys.stdout.encoding or "utf-8")
|
| 38 |
-
except (UnicodeEncodeError, UnicodeDecodeError, LookupError):
|
| 39 |
-
_USE_UNICODE = False
|
| 40 |
-
|
| 41 |
-
# ─────────────────────────────────────────────────────────────
|
| 42 |
-
# ANSI colours & helpers
|
| 43 |
-
# ─────────────────────────────────────────────────────────────
|
| 44 |
-
|
| 45 |
-
GREEN = "\033[92m"
|
| 46 |
-
RED = "\033[91m"
|
| 47 |
-
YELLOW = "\033[93m"
|
| 48 |
-
CYAN = "\033[96m"
|
| 49 |
-
BOLD = "\033[1m"
|
| 50 |
-
RESET = "\033[0m"
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
def _c(colour: str, text: str) -> str:
|
| 54 |
-
return f"{colour}{text}{RESET}"
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
def _ok(text: str) -> str:
|
| 58 |
-
return _c(GREEN, text)
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
def _fail(text: str) -> str:
|
| 62 |
-
return _c(RED, text)
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
def _warn(text: str) -> str:
|
| 66 |
-
return _c(YELLOW, text)
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
def _info(text: str) -> str:
|
| 70 |
-
return _c(CYAN, text)
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
def _bold(text: str) -> str:
|
| 74 |
-
return _c(BOLD, text)
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
# Icon constants (must be defined outside f-string expressions for Python < 3.12)
|
| 78 |
-
# Unicode vs ASCII fallbacks for Windows console compatibility
|
| 79 |
-
if _USE_UNICODE:
|
| 80 |
-
_OK_ICON = _ok("\u2713")
|
| 81 |
-
_FAIL_ICON = _fail("\u2717")
|
| 82 |
-
_WARN_ICON = _warn("\u26A0")
|
| 83 |
-
_INFO_ICON = _info("\u25B8")
|
| 84 |
-
_BULLET = "\u2022"
|
| 85 |
-
_DASH = "\u2014"
|
| 86 |
-
_TABLE_TL = "\u2554"
|
| 87 |
-
_TABLE_TR = "\u2557"
|
| 88 |
-
_TABLE_BL = "\u255A"
|
| 89 |
-
_TABLE_BR = "\u255D"
|
| 90 |
-
_TABLE_H = "\u2550"
|
| 91 |
-
_TABLE_V = "\u2551"
|
| 92 |
-
_TABLE_TM = "\u2560"
|
| 93 |
-
_TABLE_BM = "\u255A"
|
| 94 |
-
_TABLE_ML = "\u251C"
|
| 95 |
-
_TABLE_MR = "\u2524"
|
| 96 |
-
_TABLE_MM = "\u253C"
|
| 97 |
-
_TABLE_MH = "\u2500"
|
| 98 |
-
_TABLE_MV = "\u2502"
|
| 99 |
-
_TABLE_TML = "\u255F"
|
| 100 |
-
_TABLE_TMR = "\u257E"
|
| 101 |
-
else:
|
| 102 |
-
_OK_ICON = _ok("v")
|
| 103 |
-
_FAIL_ICON = _fail("x")
|
| 104 |
-
_WARN_ICON = _warn("!")
|
| 105 |
-
_INFO_ICON = _info(">")
|
| 106 |
-
_BULLET = "*"
|
| 107 |
-
_DASH = "-"
|
| 108 |
-
_TABLE_TL = "+"
|
| 109 |
-
_TABLE_TR = "+"
|
| 110 |
-
_TABLE_BL = "+"
|
| 111 |
-
_TABLE_BR = "+"
|
| 112 |
-
_TABLE_H = "="
|
| 113 |
-
_TABLE_V = "|"
|
| 114 |
-
_TABLE_TM = "+"
|
| 115 |
-
_TABLE_BM = "+"
|
| 116 |
-
_TABLE_ML = "+"
|
| 117 |
-
_TABLE_MR = "+"
|
| 118 |
-
_TABLE_MM = "+"
|
| 119 |
-
_TABLE_MH = "-"
|
| 120 |
-
_TABLE_MV = "|"
|
| 121 |
-
_TABLE_TML = "+"
|
| 122 |
-
_TABLE_TMR = "-"
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
def _indicator(status: str) -> str:
|
| 126 |
-
mapping = {
|
| 127 |
-
"passed": _OK_ICON,
|
| 128 |
-
"failed": _FAIL_ICON,
|
| 129 |
-
"skipped": _WARN_ICON,
|
| 130 |
-
"running": _INFO_ICON,
|
| 131 |
-
}
|
| 132 |
-
return mapping.get(status, _DASH)
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
def _timestamp() -> str:
|
| 136 |
-
return datetime.now(timezone.utc).strftime("%H:%M:%S")
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
def _human_size(n_bytes: int) -> str:
|
| 140 |
-
for unit in ("B", "KB", "MB", "GB"):
|
| 141 |
-
if n_bytes < 1024:
|
| 142 |
-
return f"{n_bytes:.2f} {unit}"
|
| 143 |
-
n_bytes /= 1024
|
| 144 |
-
return f"{n_bytes:.2f} TB"
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
def _human_duration(seconds: float) -> str:
|
| 148 |
-
if seconds < 60:
|
| 149 |
-
return f"{seconds:.1f}s"
|
| 150 |
-
mins = int(seconds // 60)
|
| 151 |
-
secs = int(seconds % 60)
|
| 152 |
-
return f"{mins}m {secs}s"
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
# ─────────────────────────────────────────────────────────────
|
| 156 |
-
# Environment loading
|
| 157 |
-
# ─────────────────────────────────────────────────────────────
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
def load_env(env_path: str = ".env") -> dict[str, str]:
|
| 161 |
-
env: dict[str, str] = {}
|
| 162 |
-
p = Path(env_path)
|
| 163 |
-
if not p.is_file():
|
| 164 |
-
return env
|
| 165 |
-
for line in p.read_text(encoding="utf-8").splitlines():
|
| 166 |
-
line = line.strip()
|
| 167 |
-
if not line or line.startswith("#"):
|
| 168 |
-
continue
|
| 169 |
-
m = re.match(r"^([A-Za-z_][A-Za-z_0-9]*)\s*=\s*(.*?)\s*$", line)
|
| 170 |
-
if not m:
|
| 171 |
-
continue
|
| 172 |
-
key = m.group(1)
|
| 173 |
-
val = m.group(2)
|
| 174 |
-
if val.startswith('"') and val.endswith('"'):
|
| 175 |
-
val = val[1:-1]
|
| 176 |
-
elif val.startswith("'") and val.endswith("'"):
|
| 177 |
-
val = val[1:-1]
|
| 178 |
-
env[key] = val
|
| 179 |
-
return env
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
# ─────────────────────────────────────────────────────────────
|
| 183 |
-
# HTTP helpers
|
| 184 |
-
# ─────────────────────────────────────────────────────────────
|
| 185 |
-
|
| 186 |
-
BACKUP_ARCHIVE = "backup.tar.gz"
|
| 187 |
-
RESTORE_ENDPOINT = "/api/v1/backup/restore"
|
| 188 |
-
BACKUP_ENDPOINT = "/api/v1/backup"
|
| 189 |
-
HEALTH_ENDPOINT = "/health"
|
| 190 |
-
HF_API_SPACES = "https://huggingface.co/api/spaces"
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
def _build_url(base: str, path: str) -> str:
|
| 194 |
-
base = base.rstrip("/")
|
| 195 |
-
path = path.lstrip("/")
|
| 196 |
-
return f"{base}/{path}"
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
def http_get(url: str, headers: dict[str, str], timeout: int = 120) -> tuple[int, bytes]:
|
| 200 |
-
req = urllib.request.Request(url, headers=headers, method="GET")
|
| 201 |
-
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
| 202 |
-
return resp.status, resp.read()
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
def http_get_stream(
|
| 206 |
-
url: str, headers: dict[str, str], dest: Path, timeout: int = 300
|
| 207 |
-
) -> tuple[int, int]:
|
| 208 |
-
req = urllib.request.Request(url, headers=headers, method="GET")
|
| 209 |
-
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
| 210 |
-
total = 0
|
| 211 |
-
with open(dest, "wb") as f:
|
| 212 |
-
while True:
|
| 213 |
-
chunk = resp.read(65536)
|
| 214 |
-
if not chunk:
|
| 215 |
-
break
|
| 216 |
-
f.write(chunk)
|
| 217 |
-
total += len(chunk)
|
| 218 |
-
return resp.status, total
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
def http_post_multipart(
|
| 222 |
-
url: str,
|
| 223 |
-
file_path: Path,
|
| 224 |
-
field_name: str,
|
| 225 |
-
headers: dict[str, str],
|
| 226 |
-
timeout: int = 300,
|
| 227 |
-
) -> tuple[int, bytes]:
|
| 228 |
-
boundary = "----DeployBoundary" + hex(int(time.time() * 1e6))[2:]
|
| 229 |
-
data = io.BytesIO()
|
| 230 |
-
|
| 231 |
-
data.write(f"--{boundary}\r\n".encode())
|
| 232 |
-
data.write(
|
| 233 |
-
f'Content-Disposition: form-data; name="{field_name}"; filename="{file_path.name}"\r\n'.encode()
|
| 234 |
-
)
|
| 235 |
-
data.write(b"Content-Type: application/gzip\r\n\r\n")
|
| 236 |
-
data.write(file_path.read_bytes())
|
| 237 |
-
data.write(f"\r\n--{boundary}--\r\n".encode())
|
| 238 |
-
|
| 239 |
-
body = data.getvalue()
|
| 240 |
-
content_type = f"multipart/form-data; boundary={boundary}"
|
| 241 |
-
|
| 242 |
-
req_headers = {**headers, "Content-Type": content_type}
|
| 243 |
-
req = urllib.request.Request(url, data=body, headers=req_headers, method="POST")
|
| 244 |
-
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
| 245 |
-
return resp.status, resp.read()
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
def http_get_json(
|
| 249 |
-
url: str, headers: dict[str, str], timeout: int = 30
|
| 250 |
-
) -> Optional[dict[str, Any]]:
|
| 251 |
-
try:
|
| 252 |
-
req = urllib.request.Request(url, headers=headers, method="GET")
|
| 253 |
-
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
| 254 |
-
return json.loads(resp.read().decode("utf-8"))
|
| 255 |
-
except Exception:
|
| 256 |
-
return None
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
def http_post_json(
|
| 260 |
-
url: str, headers: dict[str, str], data: Optional[bytes] = None, timeout: int = 30
|
| 261 |
-
) -> Optional[int]:
|
| 262 |
-
try:
|
| 263 |
-
req = urllib.request.Request(url, data=data, headers=headers, method="POST")
|
| 264 |
-
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
| 265 |
-
return resp.status
|
| 266 |
-
except urllib.error.HTTPError as e:
|
| 267 |
-
return e.code
|
| 268 |
-
except Exception:
|
| 269 |
-
return None
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
def http_head(url: str, timeout: int = 30) -> Optional[int]:
|
| 273 |
-
try:
|
| 274 |
-
req = urllib.request.Request(url, method="HEAD")
|
| 275 |
-
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
| 276 |
-
return resp.status
|
| 277 |
-
except urllib.error.URLError:
|
| 278 |
-
return None
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
# ─────────────────────────────────────────────────────────────
|
| 282 |
-
# Git helpers
|
| 283 |
-
# ─────────────────────────────────────────────────────────────
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
def _run_git(args: list[str], cwd: str | None = None) -> tuple[int, str]:
|
| 287 |
-
cmd = ["git"] + args
|
| 288 |
-
result = subprocess.run(cmd, capture_output=True, text=True, cwd=cwd)
|
| 289 |
-
return result.returncode, result.stdout.strip()
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
def git_status(cwd: str) -> list[str]:
|
| 293 |
-
rc, out = _run_git(["status", "--porcelain"], cwd=cwd)
|
| 294 |
-
if rc != 0:
|
| 295 |
-
return []
|
| 296 |
-
lines = [line for line in out.split("\n") if line.strip()]
|
| 297 |
-
return lines
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
def git_add_all(cwd: str) -> bool:
|
| 301 |
-
rc, _ = _run_git(["add", "-A", "."], cwd=cwd)
|
| 302 |
-
return rc == 0
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
def git_commit(cwd: str, message: str) -> tuple[bool, str]:
|
| 306 |
-
rc, out = _run_git(["commit", "-m", message], cwd=cwd)
|
| 307 |
-
if rc == 0:
|
| 308 |
-
m = re.search(r"\[[^\]]+ ([a-f0-9]+)\]", out)
|
| 309 |
-
sha = m.group(1) if m else "unknown"
|
| 310 |
-
return True, sha
|
| 311 |
-
if "nothing to commit" in out.lower() or "no changes" in out.lower():
|
| 312 |
-
return True, "no-change"
|
| 313 |
-
return False, out
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
def git_push(cwd: str, remote: str = "origin", branch: str = "main") -> tuple[bool, str]:
|
| 317 |
-
rc, out = _run_git(["push", remote, branch], cwd=cwd)
|
| 318 |
-
return rc == 0, out
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
def _parse_hf_space_from_url(url: str) -> tuple[str, str]:
|
| 322 |
-
m = re.search(r"huggingface\.co/spaces/([^/]+)/([^/\s]+)", url)
|
| 323 |
-
if m:
|
| 324 |
-
return m.group(1), m.group(2).rstrip("/")
|
| 325 |
-
return "aetherbase", "llm-ready-data"
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
def git_remote_url(cwd: str) -> str:
|
| 329 |
-
rc, out = _run_git(["remote", "get-url", "origin"], cwd=cwd)
|
| 330 |
-
if rc != 0:
|
| 331 |
-
return ""
|
| 332 |
-
return out
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
def git_log(cwd: str, n: int = 3) -> str:
|
| 336 |
-
_, out = _run_git(["log", "--oneline", f"-{n}"], cwd=cwd)
|
| 337 |
-
return out
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
# ─────────────────────────────────────────────────────────────
|
| 341 |
-
# Core deployment logic
|
| 342 |
-
# ─────────────────────────────────────────────────────────────
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
class AuditReport:
|
| 346 |
-
def __init__(self):
|
| 347 |
-
self.start_time = time.time()
|
| 348 |
-
self.fields: dict[str, Any] = {
|
| 349 |
-
"backup_started": "",
|
| 350 |
-
"backup_completed": "",
|
| 351 |
-
"backup_files": 0,
|
| 352 |
-
"backup_size": 0,
|
| 353 |
-
"backup_status": "pending",
|
| 354 |
-
"commit_status": "pending",
|
| 355 |
-
"commit_hash": "",
|
| 356 |
-
"push_status": "pending",
|
| 357 |
-
"deploy_status": "pending",
|
| 358 |
-
"deploy_duration": "",
|
| 359 |
-
"restore_status": "pending",
|
| 360 |
-
"restore_files": 0,
|
| 361 |
-
"verification_status": "pending",
|
| 362 |
-
"errors": [],
|
| 363 |
-
"warnings": [],
|
| 364 |
-
}
|
| 365 |
-
|
| 366 |
-
def end(self):
|
| 367 |
-
self.fields["total_duration"] = _human_duration(time.time() - self.start_time)
|
| 368 |
-
|
| 369 |
-
def set(self, key: str, value: Any):
|
| 370 |
-
self.fields[key] = value
|
| 371 |
-
|
| 372 |
-
def error(self, msg: str):
|
| 373 |
-
self.fields["errors"].append(msg)
|
| 374 |
-
|
| 375 |
-
def warn(self, msg: str):
|
| 376 |
-
self.fields["warnings"].append(msg)
|
| 377 |
-
|
| 378 |
-
def _row(self, label: str, status: str, detail: str) -> str:
|
| 379 |
-
icon = _indicator(status)
|
| 380 |
-
return f"{_TABLE_MV} {label:<28} {icon:<2} {detail:<30} {_TABLE_MV}"
|
| 381 |
-
|
| 382 |
-
def _sep(self) -> str:
|
| 383 |
-
return f"{_TABLE_ML}{_TABLE_MH * 28}{_TABLE_MM}{_TABLE_MH * 4}{_TABLE_MM}{_TABLE_MH * 32}{_TABLE_MR}"
|
| 384 |
-
|
| 385 |
-
def print(self):
|
| 386 |
-
self.end()
|
| 387 |
-
f = self.fields
|
| 388 |
-
err_count = len(f["errors"])
|
| 389 |
-
warn_count = len(f["warnings"])
|
| 390 |
-
|
| 391 |
-
start_dt = datetime.fromtimestamp(self.start_time).strftime("%c")
|
| 392 |
-
|
| 393 |
-
lines: list[str] = []
|
| 394 |
-
lines.append("")
|
| 395 |
-
lines.append(
|
| 396 |
-
f"{_TABLE_TL}{_TABLE_H * 16}{_TABLE_H * 16}{_TABLE_H * 18}{_TABLE_H * 20}"
|
| 397 |
-
f"{_TABLE_TR}"
|
| 398 |
-
)
|
| 399 |
-
|
| 400 |
-
title = "DEPLOYMENT AUDIT REPORT"
|
| 401 |
-
padding = (70 - len(title)) // 2
|
| 402 |
-
lines.append(
|
| 403 |
-
f"{_TABLE_V} {' ' * padding}{_bold(title)}{' ' * (70 - padding - len(title))} {_TABLE_V}"
|
| 404 |
-
)
|
| 405 |
-
lines.append(
|
| 406 |
-
f"{_TABLE_V} {' ' * (70 - len(start_dt))}{start_dt} {_TABLE_V}"
|
| 407 |
-
)
|
| 408 |
-
lines.append(
|
| 409 |
-
f"{_TABLE_TM}{_TABLE_H * 70}{_TABLE_H * 0}"
|
| 410 |
-
)
|
| 411 |
-
|
| 412 |
-
lines.append(self._row("Category", "", "Status | Detail"))
|
| 413 |
-
lines.append(
|
| 414 |
-
f"{_TABLE_TML}{_TABLE_MH * 70}"
|
| 415 |
-
)
|
| 416 |
-
|
| 417 |
-
lines.append(self._row("", "", ""))
|
| 418 |
-
|
| 419 |
-
# ── Backup section ──
|
| 420 |
-
lines.append(
|
| 421 |
-
self._row(
|
| 422 |
-
"Backup Started",
|
| 423 |
-
"passed" if f["backup_started"] else "failed",
|
| 424 |
-
f["backup_started"] or "\u2014",
|
| 425 |
-
)
|
| 426 |
-
)
|
| 427 |
-
lines.append(
|
| 428 |
-
self._row(
|
| 429 |
-
"Backup Completed",
|
| 430 |
-
"passed" if f["backup_completed"] else "failed",
|
| 431 |
-
f["backup_completed"] or "\u2014",
|
| 432 |
-
)
|
| 433 |
-
)
|
| 434 |
-
lines.append(
|
| 435 |
-
self._row(
|
| 436 |
-
"Files Backed Up",
|
| 437 |
-
"passed" if f["backup_files"] > 0 else "failed",
|
| 438 |
-
str(f["backup_files"]),
|
| 439 |
-
)
|
| 440 |
-
)
|
| 441 |
-
lines.append(
|
| 442 |
-
self._row(
|
| 443 |
-
"Total Backup Size",
|
| 444 |
-
"passed" if f["backup_size"] > 0 else "failed",
|
| 445 |
-
_human_size(f["backup_size"]),
|
| 446 |
-
)
|
| 447 |
-
)
|
| 448 |
-
|
| 449 |
-
lines.append(self._sep())
|
| 450 |
-
|
| 451 |
-
# ── Deployment section ──
|
| 452 |
-
lines.append(
|
| 453 |
-
self._row(
|
| 454 |
-
"Commit Status",
|
| 455 |
-
f["commit_status"],
|
| 456 |
-
f["commit_hash"] or "\u2014",
|
| 457 |
-
)
|
| 458 |
-
)
|
| 459 |
-
lines.append(
|
| 460 |
-
self._row(
|
| 461 |
-
"Push Status",
|
| 462 |
-
f["push_status"],
|
| 463 |
-
_ok("Pushed") if f["push_status"] == "passed" else _fail("Failed"),
|
| 464 |
-
)
|
| 465 |
-
)
|
| 466 |
-
dep_icon = "passed" if f["deploy_status"] == "passed" else "failed"
|
| 467 |
-
lines.append(
|
| 468 |
-
self._row(
|
| 469 |
-
"HF Space Deployment",
|
| 470 |
-
dep_icon,
|
| 471 |
-
f["deploy_duration"] or "\u2014",
|
| 472 |
-
)
|
| 473 |
-
)
|
| 474 |
-
|
| 475 |
-
lines.append(self._sep())
|
| 476 |
-
|
| 477 |
-
# ── Restore section ──
|
| 478 |
-
lines.append(
|
| 479 |
-
self._row(
|
| 480 |
-
"Data Restoration",
|
| 481 |
-
f["restore_status"],
|
| 482 |
-
_ok("Restored") if f["restore_status"] == "passed" else _fail("Failed"),
|
| 483 |
-
)
|
| 484 |
-
)
|
| 485 |
-
lines.append(
|
| 486 |
-
self._row(
|
| 487 |
-
"Files Restored",
|
| 488 |
-
"passed" if f["restore_files"] > 0 else "failed",
|
| 489 |
-
str(f["restore_files"]),
|
| 490 |
-
)
|
| 491 |
-
)
|
| 492 |
-
lines.append(
|
| 493 |
-
self._row(
|
| 494 |
-
"Verification Status",
|
| 495 |
-
f["verification_status"],
|
| 496 |
-
_ok("Verified") if f["verification_status"] == "passed" else _fail("Failed"),
|
| 497 |
-
)
|
| 498 |
-
)
|
| 499 |
-
|
| 500 |
-
lines.append(self._sep())
|
| 501 |
-
|
| 502 |
-
# ── Summary section ──
|
| 503 |
-
lines.append(
|
| 504 |
-
self._row(
|
| 505 |
-
"Total Execution Time",
|
| 506 |
-
"passed",
|
| 507 |
-
f.get("total_duration", ""),
|
| 508 |
-
)
|
| 509 |
-
)
|
| 510 |
-
lines.append(
|
| 511 |
-
self._row(
|
| 512 |
-
"Errors",
|
| 513 |
-
"failed" if err_count > 0 else "passed",
|
| 514 |
-
str(err_count),
|
| 515 |
-
)
|
| 516 |
-
)
|
| 517 |
-
lines.append(
|
| 518 |
-
self._row(
|
| 519 |
-
"Warnings",
|
| 520 |
-
"passed" if warn_count == 0 else "skipped",
|
| 521 |
-
str(warn_count),
|
| 522 |
-
)
|
| 523 |
-
)
|
| 524 |
-
|
| 525 |
-
lines.append(
|
| 526 |
-
f"{_TABLE_BL}{_TABLE_H * 16}{_TABLE_H * 16}{_TABLE_H * 18}{_TABLE_H * 20}"
|
| 527 |
-
f"{_TABLE_BR}"
|
| 528 |
-
)
|
| 529 |
-
|
| 530 |
-
for line in lines:
|
| 531 |
-
print(line)
|
| 532 |
-
|
| 533 |
-
if err_count > 0:
|
| 534 |
-
print(f"\n{_fail('Errors:')}")
|
| 535 |
-
for e in f["errors"]:
|
| 536 |
-
print(f" {_fail(_BULLET)} {e}")
|
| 537 |
-
|
| 538 |
-
if warn_count > 0:
|
| 539 |
-
print(f"\n{_warn('Warnings:')}")
|
| 540 |
-
for w in f["warnings"]:
|
| 541 |
-
print(f" {_warn(_BULLET)} {w}")
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
def run_deployment(args: argparse.Namespace, env: dict[str, str]) -> int:
|
| 545 |
-
audit = AuditReport()
|
| 546 |
-
cwd = os.getcwd()
|
| 547 |
-
persistence_dir = Path(cwd) / "persistence"
|
| 548 |
-
persistence_dir.mkdir(parents=True, exist_ok=True)
|
| 549 |
-
|
| 550 |
-
space_url = args.space_url or env.get("SPACE_URL", "https://aetherbase-llm-ready-data.hf.space")
|
| 551 |
-
api_key = args.api_key or env.get("api_key", env.get("API_KEY", ""))
|
| 552 |
-
hf_token = args.hf_token or env.get("hf_token", env.get("HF_TOKEN", ""))
|
| 553 |
-
skip_backup = args.skip_backup
|
| 554 |
-
|
| 555 |
-
if not api_key:
|
| 556 |
-
print(f" {_fail('ERROR:')} No API key found. Set API_KEY in .env or pass --api-key.")
|
| 557 |
-
return 1
|
| 558 |
-
|
| 559 |
-
if not hf_token:
|
| 560 |
-
print(f" {_warn('WARNING:')} No HF token. Can't verify Space build status. Set HF_TOKEN in .env or pass --hf-token.")
|
| 561 |
-
hf_token = None
|
| 562 |
-
|
| 563 |
-
auth_headers = {
|
| 564 |
-
"Authorization": f"Bearer {api_key}",
|
| 565 |
-
"User-Agent": "deploy.py/1.0",
|
| 566 |
-
}
|
| 567 |
-
|
| 568 |
-
remote_url = git_remote_url(cwd)
|
| 569 |
-
owner, space_name = _parse_hf_space_from_url(remote_url) if remote_url else ("aetherbase", "llm-ready-data")
|
| 570 |
-
hf_api_headers = None
|
| 571 |
-
if hf_token:
|
| 572 |
-
hf_api_headers = {
|
| 573 |
-
"Authorization": f"Bearer {hf_token}",
|
| 574 |
-
"User-Agent": "deploy.py/1.0",
|
| 575 |
-
}
|
| 576 |
-
|
| 577 |
-
# ──────────────────────────────────────────────
|
| 578 |
-
# PHASE 1: LOCK WRITES + BACKUP
|
| 579 |
-
# ──────────────────────────────────────────────
|
| 580 |
-
print(f"\n{_bold('PHASE 1/4: Lock Writes & Backup')}")
|
| 581 |
-
print(f" {_INFO_ICON} Backing up data from: {space_url}")
|
| 582 |
-
|
| 583 |
-
if skip_backup:
|
| 584 |
-
print(f" {_WARN_ICON} Backup skipped (--skip-backup)")
|
| 585 |
-
audit.set("backup_status", "skipped")
|
| 586 |
-
else:
|
| 587 |
-
# Enable maintenance mode to freeze data state
|
| 588 |
-
maint_url = _build_url(space_url, "/api/v1/maintenance/enable")
|
| 589 |
-
maint_enabled = False
|
| 590 |
-
try:
|
| 591 |
-
status = http_post_json(maint_url, auth_headers, timeout=15)
|
| 592 |
-
if status == 200:
|
| 593 |
-
maint_enabled = True
|
| 594 |
-
print(f" {_OK_ICON} Maintenance enabled — writes blocked")
|
| 595 |
-
except Exception:
|
| 596 |
-
print(f" {_WARN_ICON} Could not enable maintenance (endpoint may not exist yet)")
|
| 597 |
-
print(f" {_WARN_ICON} Data may be lost if writes occur during deployment")
|
| 598 |
-
|
| 599 |
-
backup_file = persistence_dir / BACKUP_ARCHIVE
|
| 600 |
-
backup_url = _build_url(space_url, BACKUP_ENDPOINT)
|
| 601 |
-
audit.set("backup_started", _timestamp())
|
| 602 |
-
backed_up = False
|
| 603 |
-
|
| 604 |
-
# Try remote backup endpoint first
|
| 605 |
-
try:
|
| 606 |
-
status, total_bytes = http_get_stream(backup_url, auth_headers, backup_file, timeout=120)
|
| 607 |
-
if status == 200:
|
| 608 |
-
backed_up = True
|
| 609 |
-
print(f" {_OK_ICON} Remote backup successful")
|
| 610 |
-
except Exception as exc:
|
| 611 |
-
print(f" {_WARN_ICON} Remote backup unavailable: {exc}")
|
| 612 |
-
|
| 613 |
-
# Fall back to local backup
|
| 614 |
-
if not backed_up:
|
| 615 |
-
data_dir = Path(cwd) / "data"
|
| 616 |
-
if data_dir.is_dir():
|
| 617 |
-
print(f" {_INFO_ICON} Falling back to local backup: {data_dir}")
|
| 618 |
-
try:
|
| 619 |
-
buf = io.BytesIO()
|
| 620 |
-
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
|
| 621 |
-
for path in sorted(data_dir.rglob("*")):
|
| 622 |
-
if path.is_file():
|
| 623 |
-
arcname = path.relative_to(data_dir.parent)
|
| 624 |
-
tar.add(str(path), arcname=str(arcname))
|
| 625 |
-
buf.seek(0)
|
| 626 |
-
backup_file.write_bytes(buf.read())
|
| 627 |
-
|
| 628 |
-
total_bytes = backup_file.stat().st_size
|
| 629 |
-
file_count = 0
|
| 630 |
-
with tarfile.open(backup_file, "r:gz") as tar:
|
| 631 |
-
file_count = sum(1 for m in tar.getmembers() if m.isfile())
|
| 632 |
-
|
| 633 |
-
backed_up = True
|
| 634 |
-
print(f" {_OK_ICON} Local backup saved: {backup_file}")
|
| 635 |
-
except Exception as exc:
|
| 636 |
-
msg = f"Local backup failed: {exc}"
|
| 637 |
-
audit.error(msg)
|
| 638 |
-
print(f" {_FAIL_ICON} {msg}")
|
| 639 |
-
audit.print()
|
| 640 |
-
return 1
|
| 641 |
-
else:
|
| 642 |
-
msg = f"No data found locally ({data_dir}) and remote backup unavailable"
|
| 643 |
-
audit.warn(msg)
|
| 644 |
-
print(f" {_WARN_ICON} {msg}")
|
| 645 |
-
audit.set("backup_files", 0)
|
| 646 |
-
audit.set("backup_size", 0)
|
| 647 |
-
audit.set("backup_completed", _timestamp())
|
| 648 |
-
audit.set("backup_status", "skipped")
|
| 649 |
-
|
| 650 |
-
if backed_up:
|
| 651 |
-
file_count = 0
|
| 652 |
-
try:
|
| 653 |
-
with tarfile.open(backup_file, "r:gz") as tar:
|
| 654 |
-
file_count = sum(1 for m in tar.getmembers() if m.isfile())
|
| 655 |
-
except Exception:
|
| 656 |
-
audit.warn("Could not count files in backup archive")
|
| 657 |
-
file_count = backup_file.stat().st_size
|
| 658 |
-
|
| 659 |
-
audit.set("backup_completed", _timestamp())
|
| 660 |
-
audit.set("backup_files", file_count)
|
| 661 |
-
audit.set("backup_size", total_bytes)
|
| 662 |
-
audit.set("backup_status", "passed")
|
| 663 |
-
print(f" {_OK_ICON} Files: {file_count} | Size: {_human_size(total_bytes)}")
|
| 664 |
-
if maint_enabled:
|
| 665 |
-
print(f" {_OK_ICON} Writes frozen — backup is consistent")
|
| 666 |
-
|
| 667 |
-
# ──────────────────────────────────────────────
|
| 668 |
-
# PHASE 2: GIT COMMIT & PUSH
|
| 669 |
-
# ──────────────────────────────────────────────
|
| 670 |
-
print(f"\n{_bold('PHASE 2/4: Git Commit & Push')}")
|
| 671 |
-
|
| 672 |
-
if args.skip_git:
|
| 673 |
-
print(f" {_WARN_ICON} Git phase skipped (--skip-git)")
|
| 674 |
-
audit.set("commit_status", "skipped")
|
| 675 |
-
audit.set("commit_hash", "skipped")
|
| 676 |
-
audit.set("push_status", "skipped")
|
| 677 |
-
else:
|
| 678 |
-
changed = git_status(cwd)
|
| 679 |
-
if not changed:
|
| 680 |
-
print(f" {_WARN_ICON} No changes to commit (working tree clean)")
|
| 681 |
-
print(f" {_INFO_ICON} Nothing to deploy — exiting")
|
| 682 |
-
audit.set("commit_status", "passed")
|
| 683 |
-
audit.set("commit_hash", "no-change")
|
| 684 |
-
audit.set("push_status", "passed")
|
| 685 |
-
audit.print()
|
| 686 |
-
return 0
|
| 687 |
-
|
| 688 |
-
print(f" {_INFO_ICON} Staging {len(changed)} file(s)...")
|
| 689 |
-
if not git_add_all(cwd):
|
| 690 |
-
msg = "Git add failed"
|
| 691 |
-
audit.error(msg)
|
| 692 |
-
audit.set("commit_status", "failed")
|
| 693 |
-
print(f" {_FAIL_ICON} {msg}")
|
| 694 |
-
audit.print()
|
| 695 |
-
return 1
|
| 696 |
-
|
| 697 |
-
commit_msg = args.message or f"deploy: auto-deploy {_timestamp()}"
|
| 698 |
-
print(f" {_INFO_ICON} Committing: {commit_msg}")
|
| 699 |
-
ok, sha = git_commit(cwd, commit_msg)
|
| 700 |
-
if not ok:
|
| 701 |
-
msg = f"Git commit failed: {sha}"
|
| 702 |
-
audit.error(msg)
|
| 703 |
-
audit.set("commit_status", "failed")
|
| 704 |
-
print(f" {_FAIL_ICON} {msg}")
|
| 705 |
-
audit.print()
|
| 706 |
-
return 1
|
| 707 |
-
|
| 708 |
-
audit.set("commit_status", "passed")
|
| 709 |
-
audit.set("commit_hash", sha)
|
| 710 |
-
print(f" {_OK_ICON} Committed: {sha}")
|
| 711 |
-
|
| 712 |
-
print(f" {_INFO_ICON} Pushing to origin/main...")
|
| 713 |
-
ok, push_out = git_push(cwd)
|
| 714 |
-
if not ok:
|
| 715 |
-
msg = f"Git push failed"
|
| 716 |
-
audit.error(msg)
|
| 717 |
-
audit.set("push_status", "failed")
|
| 718 |
-
print(f" {_FAIL_ICON} {msg}")
|
| 719 |
-
print(f" {push_out}")
|
| 720 |
-
audit.print()
|
| 721 |
-
return 1
|
| 722 |
-
|
| 723 |
-
audit.set("push_status", "passed")
|
| 724 |
-
print(f" {_OK_ICON} Push successful")
|
| 725 |
-
|
| 726 |
-
# ──────────────────────────────────────────────
|
| 727 |
-
# PHASE 3: WAIT FOR REDEPLOYMENT (via HF API)
|
| 728 |
-
# ──────────────────────────────────────────────
|
| 729 |
-
print(f"\n{_bold('PHASE 3/4: Waiting for HF Space Redeployment')}")
|
| 730 |
-
|
| 731 |
-
api_url = f"{HF_API_SPACES}/{owner}/{space_name}"
|
| 732 |
-
deploy_start = time.time()
|
| 733 |
-
max_wait = args.timeout
|
| 734 |
-
poll_interval = 10
|
| 735 |
-
waited = 0
|
| 736 |
-
deployed = False
|
| 737 |
-
last_error = ""
|
| 738 |
-
seen_building = False
|
| 739 |
-
|
| 740 |
-
print(f" {_INFO_ICON} Tracking {owner}/{space_name} via HF API...")
|
| 741 |
-
|
| 742 |
-
if hf_api_headers:
|
| 743 |
-
initial = http_get_json(api_url, hf_api_headers, timeout=15) or {}
|
| 744 |
-
prev_stage = initial.get("runtime", {}).get("stage", "")
|
| 745 |
-
|
| 746 |
-
while waited < max_wait:
|
| 747 |
-
data = http_get_json(api_url, hf_api_headers, timeout=15)
|
| 748 |
-
stage = (data or {}).get("runtime", {}).get("stage", "")
|
| 749 |
-
|
| 750 |
-
if stage == "BUILDING":
|
| 751 |
-
if not seen_building:
|
| 752 |
-
print(f" {_INFO_ICON} Build started (stage: BUILDING)")
|
| 753 |
-
seen_building = True
|
| 754 |
-
|
| 755 |
-
elif stage == "RUNNING":
|
| 756 |
-
if seen_building:
|
| 757 |
-
print(f" {_OK_ICON} Build complete (stage: RUNNING)")
|
| 758 |
-
deployed = True
|
| 759 |
-
break
|
| 760 |
-
if waited > 30 and prev_stage == "RUNNING":
|
| 761 |
-
print(f" {_OK_ICON} Space is running (may have skipped BUILDING stage)")
|
| 762 |
-
deployed = True
|
| 763 |
-
break
|
| 764 |
-
|
| 765 |
-
elif stage in ("PAUSED", "STOPPED", "NO_APP"):
|
| 766 |
-
last_error = f"Space in unexpected state: {stage}"
|
| 767 |
-
deployed = False
|
| 768 |
-
break
|
| 769 |
-
|
| 770 |
-
prev_stage = stage
|
| 771 |
-
time.sleep(poll_interval)
|
| 772 |
-
waited += poll_interval
|
| 773 |
-
if waited % 30 == 0 and not seen_building:
|
| 774 |
-
print(f" {_INFO_ICON} Still waiting for build to start... ({waited}s)")
|
| 775 |
-
elif waited % 30 == 0 and seen_building:
|
| 776 |
-
print(f" {_INFO_ICON} Still building... ({waited}s)")
|
| 777 |
-
|
| 778 |
-
deploy_duration = time.time() - deploy_start
|
| 779 |
-
|
| 780 |
-
if not hf_api_headers:
|
| 781 |
-
print(f" {_WARN_ICON} No HF token — assuming deployment is underway")
|
| 782 |
-
print(f" {_INFO_ICON} Waiting {max_wait}s for build + startup...")
|
| 783 |
-
time.sleep(max_wait)
|
| 784 |
-
deployed = True
|
| 785 |
-
|
| 786 |
-
if deployed:
|
| 787 |
-
health_url = _build_url(space_url, HEALTH_ENDPOINT)
|
| 788 |
-
try:
|
| 789 |
-
req = urllib.request.Request(health_url, method="GET")
|
| 790 |
-
with urllib.request.urlopen(req, timeout=15) as resp:
|
| 791 |
-
if resp.status == 200:
|
| 792 |
-
print(f" {_OK_ICON} App health check passed (new instance serving)")
|
| 793 |
-
except Exception:
|
| 794 |
-
print(f" {_WARN_ICON} App health check unavailable (may still be starting)")
|
| 795 |
-
|
| 796 |
-
audit.set("deploy_status", "passed")
|
| 797 |
-
audit.set("deploy_duration", _human_duration(deploy_duration))
|
| 798 |
-
print(f" {_OK_ICON} Space redeployed in {_human_duration(deploy_duration)}")
|
| 799 |
-
else:
|
| 800 |
-
audit.set("deploy_status", "failed")
|
| 801 |
-
audit.set("deploy_duration", _human_duration(deploy_duration))
|
| 802 |
-
msg = f"Space did not redeploy within {max_wait}s (last stage: {stage}, error: {last_error})"
|
| 803 |
-
audit.error(msg)
|
| 804 |
-
print(f" {_FAIL_ICON} {msg}")
|
| 805 |
-
audit.print()
|
| 806 |
-
return 1
|
| 807 |
-
|
| 808 |
-
# ──────────────────────────────────────────────
|
| 809 |
-
# PHASE 4: DATA RESTORE
|
| 810 |
-
# ──────────────────────────────────────────────
|
| 811 |
-
print(f"\n{_bold('PHASE 4/4: Data Restoration')}")
|
| 812 |
-
|
| 813 |
-
if skip_backup:
|
| 814 |
-
print(f" {_WARN_ICON} Restore skipped (no backup)")
|
| 815 |
-
audit.set("restore_status", "skipped")
|
| 816 |
-
audit.set("verification_status", "skipped")
|
| 817 |
-
audit.set("restore_files", 0)
|
| 818 |
-
else:
|
| 819 |
-
backup_file = persistence_dir / BACKUP_ARCHIVE
|
| 820 |
-
if not backup_file.is_file():
|
| 821 |
-
msg = f"Backup file not found: {backup_file}"
|
| 822 |
-
audit.error(msg)
|
| 823 |
-
audit.set("restore_status", "failed")
|
| 824 |
-
print(f" {_FAIL_ICON} {msg}")
|
| 825 |
-
audit.print()
|
| 826 |
-
return 1
|
| 827 |
-
|
| 828 |
-
restore_url = _build_url(space_url, RESTORE_ENDPOINT)
|
| 829 |
-
print(f" {_INFO_ICON} Restoring data to: {space_url}")
|
| 830 |
-
|
| 831 |
-
try:
|
| 832 |
-
status, body = http_post_multipart(
|
| 833 |
-
restore_url, backup_file, "file", auth_headers, timeout=300
|
| 834 |
-
)
|
| 835 |
-
|
| 836 |
-
if status == 200:
|
| 837 |
-
try:
|
| 838 |
-
result = json.loads(body)
|
| 839 |
-
restored = result.get("files_restored", 0)
|
| 840 |
-
except Exception:
|
| 841 |
-
restored = 0
|
| 842 |
-
|
| 843 |
-
audit.set("restore_files", max(restored, 1))
|
| 844 |
-
audit.set("restore_status", "passed")
|
| 845 |
-
print(f" {_OK_ICON} Data restored: {restored} files")
|
| 846 |
-
|
| 847 |
-
# Verification
|
| 848 |
-
print(f" {_INFO_ICON} Verifying data restoration...")
|
| 849 |
-
try:
|
| 850 |
-
verify_backup = persistence_dir / "verify_check.tar.gz"
|
| 851 |
-
status_v, _ = http_get_stream(
|
| 852 |
-
_build_url(space_url, BACKUP_ENDPOINT),
|
| 853 |
-
auth_headers,
|
| 854 |
-
verify_backup,
|
| 855 |
-
timeout=120,
|
| 856 |
-
)
|
| 857 |
-
|
| 858 |
-
if status_v == 200:
|
| 859 |
-
with tarfile.open(verify_backup, "r:gz") as tar:
|
| 860 |
-
verify_files = sum(1 for m in tar.getmembers() if m.isfile())
|
| 861 |
-
verify_backup.unlink(missing_ok=True)
|
| 862 |
-
|
| 863 |
-
if verify_files >= audit.fields.get("backup_files", 0) * 0.9:
|
| 864 |
-
audit.set("verification_status", "passed")
|
| 865 |
-
print(f" {_OK_ICON} Verification passed: {verify_files} files found")
|
| 866 |
-
else:
|
| 867 |
-
audit.set("verification_status", "failed")
|
| 868 |
-
audit.warn(
|
| 869 |
-
f"Verification file count ({verify_files}) mismatch with backup ({audit.fields.get('backup_files', 0)})"
|
| 870 |
-
)
|
| 871 |
-
print(f" {_WARN_ICON} Verification: file count mismatch ({verify_files} vs {audit.fields.get('backup_files', 0)})")
|
| 872 |
-
else:
|
| 873 |
-
audit.set("verification_status", "failed")
|
| 874 |
-
audit.warn(f"Verification request returned HTTP {status_v}")
|
| 875 |
-
print(f" {_WARN_ICON} Verification failed (HTTP {status_v})")
|
| 876 |
-
except Exception as exc:
|
| 877 |
-
audit.set("verification_status", "failed")
|
| 878 |
-
audit.warn(f"Verification error: {exc}")
|
| 879 |
-
print(f" {_WARN_ICON} Verification error: {exc}")
|
| 880 |
-
else:
|
| 881 |
-
audit.set("restore_status", "failed")
|
| 882 |
-
msg = f"Restore returned HTTP {status}: {body[:200]}"
|
| 883 |
-
audit.error(msg)
|
| 884 |
-
print(f" {_FAIL_ICON} {msg}")
|
| 885 |
-
audit.print()
|
| 886 |
-
return 1
|
| 887 |
-
|
| 888 |
-
except Exception as exc:
|
| 889 |
-
audit.set("restore_status", "failed")
|
| 890 |
-
msg = f"Restore failed: {exc}"
|
| 891 |
-
audit.error(msg)
|
| 892 |
-
print(f" {_FAIL_ICON} {msg}")
|
| 893 |
-
audit.print()
|
| 894 |
-
return 1
|
| 895 |
-
|
| 896 |
-
# ──────────────────────────────────────────────
|
| 897 |
-
# SUMMARY
|
| 898 |
-
# ──────────────────────────────────────────────
|
| 899 |
-
print(f"\n{_bold('=' * 70)}")
|
| 900 |
-
audit.print()
|
| 901 |
-
|
| 902 |
-
has_errors = len(audit.fields["errors"]) > 0
|
| 903 |
-
if has_errors:
|
| 904 |
-
print(f"\n{_fail('Deployment completed with errors.')}")
|
| 905 |
-
return 1
|
| 906 |
-
else:
|
| 907 |
-
print(f"\n{_ok('Deployment completed successfully.')}")
|
| 908 |
-
return 0
|
| 909 |
-
|
| 910 |
-
|
| 911 |
-
# ─────────────────────────────────────────────────────────────
|
| 912 |
-
# CLI entrypoint
|
| 913 |
-
# ─────────────────────────────────────────────────────────────
|
| 914 |
-
|
| 915 |
-
|
| 916 |
-
def main():
|
| 917 |
-
parser = argparse.ArgumentParser(
|
| 918 |
-
description="Deploy to Hugging Face Spaces with persistent data handling.",
|
| 919 |
-
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 920 |
-
epilog=(
|
| 921 |
-
"Environment variables (from .env or process env):\n"
|
| 922 |
-
" API_KEY API key for the Hugging Face Space\n"
|
| 923 |
-
" SPACE_URL Base URL of the deployed Space\n"
|
| 924 |
-
" HF_TOKEN Hugging Face API token (for build tracking)\n"
|
| 925 |
-
),
|
| 926 |
-
)
|
| 927 |
-
parser.add_argument(
|
| 928 |
-
"--space-url",
|
| 929 |
-
default="",
|
| 930 |
-
help="Base URL of the Hugging Face Space (e.g. https://aetherbase-llm-ready-data.hf.space)",
|
| 931 |
-
)
|
| 932 |
-
parser.add_argument(
|
| 933 |
-
"--api-key",
|
| 934 |
-
default="",
|
| 935 |
-
help="API key for authenticating with the Space",
|
| 936 |
-
)
|
| 937 |
-
parser.add_argument(
|
| 938 |
-
"--message", "-m",
|
| 939 |
-
default="",
|
| 940 |
-
help="Git commit message",
|
| 941 |
-
)
|
| 942 |
-
parser.add_argument(
|
| 943 |
-
"--timeout",
|
| 944 |
-
type=int,
|
| 945 |
-
default=300,
|
| 946 |
-
help="Maximum wait time (seconds) for Space redeployment (default: 300)",
|
| 947 |
-
)
|
| 948 |
-
parser.add_argument(
|
| 949 |
-
"--hf-token",
|
| 950 |
-
default="",
|
| 951 |
-
help="Hugging Face API token (for tracking Space build status)",
|
| 952 |
-
)
|
| 953 |
-
parser.add_argument(
|
| 954 |
-
"--skip-backup",
|
| 955 |
-
action="store_true",
|
| 956 |
-
help="Skip the backup and restore phases",
|
| 957 |
-
)
|
| 958 |
-
parser.add_argument(
|
| 959 |
-
"--skip-git",
|
| 960 |
-
action="store_true",
|
| 961 |
-
help="Skip the git commit and push phase",
|
| 962 |
-
)
|
| 963 |
-
parser.add_argument(
|
| 964 |
-
"--env-file",
|
| 965 |
-
default=".env",
|
| 966 |
-
help="Path to .env file (default: .env)",
|
| 967 |
-
)
|
| 968 |
-
|
| 969 |
-
args = parser.parse_args()
|
| 970 |
-
env = load_env(args.env_file)
|
| 971 |
-
|
| 972 |
-
# Merge with process environment (process env takes precedence)
|
| 973 |
-
for key in ("API_KEY", "SPACE_URL", "HF_TOKEN"):
|
| 974 |
-
if os.environ.get(key):
|
| 975 |
-
env[key] = os.environ[key]
|
| 976 |
-
|
| 977 |
-
try:
|
| 978 |
-
rc = run_deployment(args, env)
|
| 979 |
-
except KeyboardInterrupt:
|
| 980 |
-
print(f"\n{_warn('Deployment interrupted by user.')}")
|
| 981 |
-
rc = 130
|
| 982 |
-
except Exception as exc:
|
| 983 |
-
print(f"\n{_fail('Unexpected error: ' + str(exc))}")
|
| 984 |
-
rc = 1
|
| 985 |
-
|
| 986 |
-
sys.exit(rc)
|
| 987 |
-
|
| 988 |
-
|
| 989 |
-
if __name__ == "__main__":
|
| 990 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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