Spaces:
Paused
Paused
Delete sync_to_hf.py with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140import os, requests, timefrom huggingface_hub import HfApi
REPO_ID = "mansui52001/grok2api"HF_TOKEN = os.environ["HF_TOKEN"]PGSTORE_DSN = os.environ.get("PGSTORE_DSN", "")REMOTE_MGMT_KEY = os.environ.get("REMOTE_MGMT_KEY", "")
api = HfApi(token=HF_TOKEN)
# List and delete ALL existing files in the Space repo firstprint("Listing existing files in Space...")try: existing_files = api.list_repo_files(repo_id=REPO_ID, repo_type="space") files_to_delete = [f for f in existing_files if f not in (".gitattributes",)] print(f"Found {len(existing_files)} files, deleting {len(files_to_delete)}...") for f in files_to_delete: try: api.delete_file(path_in_repo=f, repo_id=REPO_ID, repo_type="space") print(f" Deleted: {f}") except Exception as e: print(f" Delete {f} note: {e}")except Exception as e: print(f"List files error: {e}")
# Upload current filesprint("Uploading files...")api.upload_folder( folder_path='.', repo_id=REPO_ID, repo_type='space', ignore_patterns=['.git/*', '.github/*'],)
# Delete old secrets that may contain stale valuesheaders = {"Authorization": f"Bearer {HF_TOKEN}"}for old_key in ["REMOTE_MGMT_KEY", "MANAGEMENT_PASSWORD", "PGSTORE_DSN"]: try: r = requests.delete( f"https://huggingface.co/api/spaces/{REPO_ID}/secrets/{old_key}", headers=headers, ) print(f"Delete old secret {old_key}: {r.status_code}") except Exception as e: print(f"Delete old secret {old_key} note: {e}")
# Set Space secrets (MANAGEMENT_PASSWORD replaces secret-key in config.yaml)secrets_to_set = {}# NOTE: PGSTORE_DSN is NOT set because Aiven PG is not reachable from HF Space network.# The connectivity test from GitHub Actions passes, but HF Space cannot connect to Aiven.# This causes CONFIG_ERROR / stuck APP_STARTING. Use file storage instead.if REMOTE_MGMT_KEY: secrets_to_set["MANAGEMENT_PASSWORD"] = REMOTE_MGMT_KEY
if secrets_to_set: for key, value in secrets_to_set.items(): r = requests.post( f"https://huggingface.co/api/spaces/{REPO_ID}/secrets", headers=headers, json={"key": key, "value": value}, ) print(f"Set secret {key}: {r.status_code}")
# Factory reboot the Space to force Docker image rebuild# Using huggingface_hub SDK which handles the correct API endpointprint("Triggering factory reboot (full Docker image rebuild)...")try: api.restart_space(repo_id=REPO_ID, factory_reboot=True) print("Factory reboot triggered successfully!")except Exception as e: print(f"Factory reboot failed: {e}") # Fallback: try raw API headers_fb = {"Authorization": f"Bearer {HF_TOKEN}"} r = requests.post(f"https://huggingface.co/api/spaces/{REPO_ID}/restart", headers=headers_fb, json={"factory": True}) print(f"Raw restart result: {r.status_code}") if r.status_code not in (200, 201): r = requests.post(f"https://huggingface.co/api/spaces/{REPO_ID}/restart", headers=headers_fb) print(f"Simple restart result: {r.status_code}")
# Wait for Space build to completeprint("\nWaiting for Space build...")print(" Waiting 60s for build to start...")time.sleep(60)
max_wait = 600start = time.time()last_stage = Noneerror_count = 0while time.time() - start < max_wait: try: resp = requests.get( f"https://huggingface.co/api/spaces/{REPO_ID}/runtime", headers=headers, timeout=30 ) if resp.status_code == 200: data = resp.json() stage = data.get("stage", "UNKNOWN") if stage != last_stage: print(f" Stage: {stage}") last_stage = stage if stage == "RUNNING": print("Space is RUNNING!") break elif stage == "BUILDING" or stage == "APP_STARTING": error_count = 0 elif stage in ("STOPPED", "PAUSED", "DELETED"): print(f"Space is {stage}, may need manual start") break elif stage == "RUNTIME_ERROR": error_count += 1 if error_count >= 3: print(f"Space has RUNTIME_ERROR (confirmed {error_count} times)") try: log_resp = requests.get( f"https://huggingface.co/api/spaces/{REPO_ID}/logs/build", headers=headers, timeout=30 ) if log_resp.status_code == 200: print(f"Build logs (first 2000 chars): {log_resp.text[:2000]}") except: pass try: log_resp2 = requests.get( f"https://huggingface.co/api/spaces/{REPO_ID}/logs/run", headers=headers, timeout=30 ) if log_resp2.status_code == 200: print(f"Run logs (first 2000 chars): {log_resp2.text[:2000]}") except: pass break except Exception as e: print(f" Check error: {e}") time.sleep(20)else: print(f"Timeout after {max_wait}s, last stage: {last_stage}")
print(f"\n=== DEPLOY COMPLETE ===")print(f"Space URL: https://huggingface.co/spaces/{REPO_ID}")print(f"Storage: PostgreSQL via PGSTORE_DSN")sync_to_hf.pyDeleted-140