Spaces:
Paused
Paused
Upload folder using huggingface_hub
Browse filesFiles changed (5)
- DockerfileAdded+33
- README.mdAdded+9
- check_space.pyAdded+70
- config.yamlAdded+14
- sync_to_hf.pyAdded+134
123456789101112131415161718192021222324252627282930313233FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y --no-install-recommends \ ca-certificates curl tzdata && \ rm -rf /var/lib/apt/lists/*
WORKDIR /CLIProxyAPI
# Download and extract CLIProxyAPI release binaryARG CLI_VERSION=7.2.73RUN curl -sL "https://github.com/router-for-me/CLIProxyAPI/releases/download/v${CLI_VERSION}/CLIProxyAPI_${CLI_VERSION}_linux_amd64.tar.gz" | tar xz && \ chmod +x ./cli-proxy-api
# Download management panel during build (GitHub accessible at build time, not at HF runtime)ARG PANEL_VERSION=v1.17.10RUN mkdir -p /CLIProxyAPI/static && \ curl -sL "https://github.com/router-for-me/Cli-Proxy-API-Management-Center/releases/download/${PANEL_VERSION}/management.html" \ -o /CLIProxyAPI/static/management.html
# Replace default configs with HF-optimized version# config.example.yaml is used as PG bootstrap template on first runCOPY config.yaml /CLIProxyAPI/config.yamlCOPY config.yaml /CLIProxyAPI/config.example.yaml
# Create persistent data directory for HF SpaceRUN mkdir -p /data/auths
EXPOSE 7860
ENV TZ=Asia/ShanghaiRUN cp /usr/share/zoneinfo/${TZ} /etc/localtime && echo "${TZ}" > /etc/timezone
CMD ["./cli-proxy-api"]123456789---title: CLIProxyAPIemoji: 🚀colorFrom: purplecolorTo: bluesdk: dockerapp_port: 7860pinned: false---12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970import os, requests, json
HF_TOKEN = os.environ["HF_TOKEN"]REPO_ID = "mansui52001/grok2api"ADMIN_KEY = os.environ.get("MANAGEMENT_PASSWORD", "xiaobai640438859@qq.com")headers = {"Authorization": f"Bearer {HF_TOKEN}"}
# Check runtime status and secretsprint("=== Space Runtime Status ===")stage = "unknown"try: r = requests.get(f"https://huggingface.co/api/spaces/{REPO_ID}", headers=headers, timeout=30) if r.status_code == 200: data = r.json() runtime = data.get('runtime', {}) stage = runtime.get('stage', 'unknown') print(f"Stage: {stage}") secrets_list = runtime.get('secrets', []) print(f"Secrets: {secrets_list}") else: print(f"Space API: {r.status_code} {r.text[:200]}")except Exception as e: print(f"Space check error: {e}")
# If APP_STARTING, wait and retryif stage == "APP_STARTING": import time for i in range(6): print(f"Waiting 30s for app to start (attempt {i+1}/6)...") time.sleep(30) try: r = requests.get(f"https://huggingface.co/api/spaces/{REPO_ID}/runtime", headers=headers, timeout=30) if r.status_code == 200: data = r.json() stage = data.get('stage', 'unknown') print(f" Stage: {stage}") if stage in ("RUNNING", "RUNTIME_ERROR", "CONFIG_ERROR", "STOPPED", "PAUSED"): break except: pass
# Check auth files via management APIprint("\n=== Auth Files ===")try: r = requests.get(f"https://mansui52001-grok2api.hf.space/v0/management/auth-files", headers={"Authorization": f"Bearer {ADMIN_KEY}"}, timeout=30) if r.status_code == 200: data = r.json() auths = data if isinstance(data, list) else data.get('auths', data.get('files', [])) active = [a for a in auths if a.get('status') == 'active'] disabled = [a for a in auths if a.get('status') == 'disabled'] print(f"Total: {len(auths)}, Active: {len(active)}, Disabled: {len(disabled)}") for a in auths: print(f" {a.get('email', a.get('label', a.get('id','?'))):40s} | {a.get('status','?'):10s} | source: {a.get('source','?')} | path: {a.get('path','?')}") else: print(f"Auth API: {r.status_code} {r.text[:200]}")except Exception as e: print(f"Auth check error: {e}")
# Check configprint("\n=== Config ===")try: r = requests.get(f"https://mansui52001-grok2api.hf.space/v0/management/config.yaml", headers={"Authorization": f"Bearer {ADMIN_KEY}"}, timeout=30) if r.status_code == 200: print(r.text) else: print(f"Config API: {r.status_code}")except Exception as e: print(f"Config check error: {e}")1234567891011121314host: ""port: 7860
auth-dir: /data/auths
remote-management: allow-remote: true disable-control-panel: false disable-auto-update-panel: true
commercial-mode: trueusage-statistics-enabled: true
request-retry: 3123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134import 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}")
# Restart the Space (factory rebuild to clear stale state)headers = {"Authorization": f"Bearer {HF_TOKEN}"}# Use the rebuild endpoint instead of restart to ensure clean stater = requests.post(f"https://huggingface.co/api/spaces/{REPO_ID}/rebuild", headers=headers)print(f"Rebuild result: {r.status_code}")if r.status_code == 404: # Fallback to restart r = requests.post(f"https://huggingface.co/api/spaces/{REPO_ID}/restart", headers=headers) print(f"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")DockerfileAdded+33
README.mdAdded+9
check_space.pyAdded+70
config.yamlAdded+14
sync_to_hf.pyAdded+134