""" SF API Public Loader Downloads and runs private backend code from sixfingerdev/sf-api-private """ import os import sys import subprocess import tempfile import shutil from pathlib import Path from huggingface_hub import HfApi, hf_hub_download PRIVATE_REPO = "sixfingerdev/sf-api-private" HF_TOKEN = os.environ.get("HF_TOKEN") if not HF_TOKEN: print("ERROR: HF_TOKEN environment variable not set!") print("Add it in Settings -> Secrets") sys.exit(1) def download_private_space(): """Download all files from private space to temp directory""" print(f"Downloading private code from {PRIVATE_REPO}...") api = HfApi(token=HF_TOKEN) # Create temp directory temp_dir = Path(tempfile.mkdtemp(prefix="sf_api_")) print(f"Temp directory: {temp_dir}") # List files in private repo files = api.list_repo_files(PRIVATE_REPO, repo_type="space") print(f"Found files: {files}") # Download each file for filename in files: if filename.startswith('.'): continue print(f" Downloading {filename}...") try: downloaded = hf_hub_download( repo_id=PRIVATE_REPO, filename=filename, repo_type="space", token=HF_TOKEN, local_dir=temp_dir ) print(f" -> {downloaded}") except Exception as e: print(f" ERROR: {e}") return temp_dir def start_backend(code_dir: Path): """Start the backend server from downloaded code""" app_file = code_dir / "app.py" if not app_file.exists(): print(f"ERROR: app.py not found in {code_dir}") sys.exit(1) print(f"Starting backend from {app_file}...") # Copy requirements and install req_file = code_dir / "requirements.txt" if req_file.exists(): print("Installing requirements...") subprocess.run( [sys.executable, "-m", "pip", "install", "-r", str(req_file)], check=True ) # Run the app env = os.environ.copy() env["PYTHONPATH"] = str(code_dir) + os.pathsep + env.get("PYTHONPATH", "") cmd = [sys.executable, "-m", "uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"] print(f"Running: {' '.join(cmd)}") process = subprocess.Popen(cmd, cwd=str(code_dir), env=env) return process def main(): print("=" * 50) print("SF API Public Loader") print("=" * 50) # Download private code code_dir = download_private_space() # Start backend process = start_backend(code_dir) # Wait for process try: process.wait() except KeyboardInterrupt: process.terminate() process.wait() if __name__ == "__main__": main()