Spaces:
Sleeping
Sleeping
File size: 5,633 Bytes
c50a873 | 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 | # HALE API β Hugging Face Spaces Deployment
#
# This script prepares and deploys the HALE backend to HF Spaces.
# Your API will be live at: https://<username>-hale-api.hf.space
#
# Prerequisites:
# pip install huggingface-hub
# huggingface-cli login
import os
import shutil
import subprocess
import sys
import tempfile
SPACE_NAME = "hale-api" # Change this to your desired space name
HF_USERNAME = None # Will be auto-detected from huggingface-cli
def run(cmd, check=True):
print(f" β {cmd}")
return subprocess.run(cmd, shell=True, check=check, capture_output=True, text=True)
def get_hf_username():
result = run("huggingface-cli whoami", check=False)
if result.returncode != 0:
print("β Not logged in to Hugging Face. Run: huggingface-cli login")
sys.exit(1)
username = result.stdout.strip().split("\n")[0]
print(f" β Logged in as: {username}")
return username
def main():
global HF_USERNAME
print("\nπ HALE API β Hugging Face Spaces Deployer\n")
# 1. Check HF login
print("[1/5] Checking Hugging Face login...")
HF_USERNAME = get_hf_username()
space_id = f"{HF_USERNAME}/{SPACE_NAME}"
# 2. Create Space (if not exists)
print(f"\n[2/5] Creating Space: {space_id}...")
try:
from huggingface_hub import HfApi
api = HfApi()
api.create_repo(
repo_id=space_id,
repo_type="space",
space_sdk="docker",
private=False,
exist_ok=True,
)
print(f" β Space ready: https://huggingface.co/spaces/{space_id}")
except Exception as e:
print(f" β Space creation: {e}")
# 3. Prepare deploy directory
print("\n[3/5] Preparing deploy files...")
deploy_dir = os.path.join(tempfile.gettempdir(), "hale-deploy")
if os.path.exists(deploy_dir):
shutil.rmtree(deploy_dir)
# Clone the space repo
run(f"git clone https://huggingface.co/spaces/{space_id} \"{deploy_dir}\"", check=False)
if not os.path.exists(deploy_dir):
os.makedirs(deploy_dir)
run(f"git init", check=True)
# Copy project files
project_dir = os.path.dirname(os.path.abspath(__file__))
ignore_patterns = {'.git', '__pycache__', '.pytest_cache', 'hale-frontend',
'node_modules', '.env', 'data', 'logs', '.planning', 'Dockerfile.spaces'}
for item in os.listdir(project_dir):
if item in ignore_patterns:
continue
src = os.path.join(project_dir, item)
dst = os.path.join(deploy_dir, item)
if os.path.isdir(src):
shutil.copytree(src, dst, dirs_exist_ok=True,
ignore=shutil.ignore_patterns('__pycache__', '*.pyc', '.pytest_cache'))
else:
shutil.copy2(src, dst)
# Copy Dockerfile.spaces as Dockerfile
shutil.copy2(
os.path.join(project_dir, "Dockerfile.spaces"),
os.path.join(deploy_dir, "Dockerfile")
)
# Create .env for spaces (no secrets β those go in HF Settings)
with open(os.path.join(deploy_dir, ".env"), "w") as f:
f.write("APP_ENV=production\n")
f.write("DATABASE_URL=sqlite:///./data/hale.db\n")
f.write("CORS_ORIGINS=*\n")
f.write("LOG_LEVEL=INFO\n")
# Create README.md with HF Spaces metadata
with open(os.path.join(deploy_dir, "README.md"), "w") as f:
f.write(f"""---
title: HALE - Adaptive Learning Engine API
emoji: π§
colorFrom: purple
colorTo: blue
sdk: docker
app_port: 7860
pinned: true
---
# π§ HALE β Adaptive Learning Engine
AI-powered adaptive learning API with Reinforcement Learning behavioral engine.
**API Docs**: [/docs](https://{HF_USERNAME}-{SPACE_NAME}.hf.space/docs)
## Endpoints
- `POST /api/auth/register` β Register
- `POST /api/auth/login` β Login
- `GET /api/plan` β Get today's adaptive plan
- `POST /api/complete-task` β Mark task done
- `GET /api/stats` β User analytics
""")
print(f" β Deploy files ready at: {deploy_dir}")
# 4. Set secrets
print("\n[4/5] Setting secrets...")
print(" β You need to set GEMINI_API_KEYS and SECRET_KEY in HF Space Settings:")
print(f" β https://huggingface.co/spaces/{space_id}/settings")
print(" β Add these as 'Repository secrets':")
print(" GEMINI_API_KEYS = your,comma,separated,keys")
print(" SECRET_KEY = some-random-64-char-string")
# 5. Push to HF
print(f"\n[5/5] Pushing to HF Spaces...")
os.chdir(deploy_dir)
run("git add -A")
run('git commit -m "Deploy HALE API v3.1"', check=False)
run(f"git push https://huggingface.co/spaces/{space_id} main --force", check=False)
print(f"""
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β
DEPLOYMENT COMPLETE! β
β β
β π API URL: https://{HF_USERNAME}-{SPACE_NAME}.hf.space β
β π Docs: https://{HF_USERNAME}-{SPACE_NAME}.hf.space/docs β
β βοΈ Settings: https://huggingface.co/spaces/{space_id}/settings β
β β
β β οΈ Don't forget to add secrets in Settings! β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
""")
if __name__ == "__main__":
main()
|