"""Setup script for Hugging Face Space and Storage Bucket. Idempotent and safe to re-run. """ import os import sys from huggingface_hub import HfApi, Volume from huggingface_hub.utils import HfHubHTTPError def setup(): api = HfApi() # 1. Read username try: user_info = api.whoami() username = user_info.get("name") can_pay = user_info.get("canPay", False) is_pro = user_info.get("isPro", False) print(f"[*] Authenticated as HF user: {username} (canPay={can_pay}, isPro={is_pro})") except Exception as e: print(f"[!] Authentication error: {e}", file=sys.stderr) print("[!] Please ensure you are logged in via 'hf auth login'", file=sys.stderr) sys.exit(1) bucket_id = f"{username}/laya-browser-data" space_id = f"{username}/laya-browser-mcp" # 2. Create private storage bucket print(f"[*] Ensuring private bucket exists: {bucket_id}") try: bucket_url = api.create_bucket(bucket_id=bucket_id, private=True, exist_ok=True) print(f"[+] Bucket ready: {bucket_url}") except HfHubHTTPError as e: if "already exists" in str(e).lower() or e.response.status_code == 409: print(f"[+] Bucket already exists: {bucket_id}") else: print(f"[!] Warning creating bucket: {e}") except Exception as e: print(f"[!] Warning creating bucket: {e}") # 3. Create Space (Gradio SDK, ZeroGPU flavor) print(f"[*] Ensuring Space exists: {space_id}") try: space_url = api.create_repo( repo_id=space_id, repo_type="space", space_sdk="gradio", space_hardware="zero-a10g", exist_ok=True, private=False ) print(f"[+] Space repository ready: {space_url}") except HfHubHTTPError as e: if e.response.status_code == 403: print(f"[!] 403 Forbidden creating Space on zero-a10g hardware: {e}", file=sys.stderr) print("[!] If your free account has reached its 2-ZeroGPU Space limit, please delete or pause an existing ZeroGPU Space.") print("[!] Alternatively, navigate to your Space settings at https://huggingface.co/spaces/{space_id}/settings to set hardware manually.") else: print(f"[!] Notice during create_repo: {e}") except Exception as e: print(f"[!] Notice during create_repo: {e}") # 4. Attach the bucket at /data read-write print(f"[*] Attaching bucket {bucket_id} to {space_id} at /data") try: vol = Volume(type="bucket", source=bucket_id, mount_path="/data") api.set_space_volumes(space_id, volumes=[vol]) print(f"[+] Successfully attached volume /data -> {bucket_id}") except Exception as e: print(f"[!] Warning setting space volume: {e}") print("[!] You can also attach the volume via Space Settings -> Volumes in the web UI.") # 5. Check and print space runtime print(f"[*] Verifying Space runtime for {space_id}...") try: runtime = api.get_space_runtime(space_id) print(f"[+] Space Runtime:") print(f" Stage: {runtime.stage}") print(f" Hardware: current={runtime.hardware}, requested={runtime.requested_hardware}") print(f" Domains: {runtime.raw.get('domains', [])}") except Exception as e: print(f"[!] Error fetching runtime: {e}") if __name__ == "__main__": setup()