Spaces:
Paused
Paused
Upload folder using huggingface_hub
Browse filesFiles changed (7)
- DockerfileAdded+42
- README.mdAdded+9
- check_space.pyAdded+70
- config.yamlAdded+12
- entrypoint.shAdded+12
- sync_auths.pyAdded+179
- sync_to_hf.pyAdded+140
123456789101112131415161718192021222324252627282930313233343536373839404142FROM 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)# Store in a build-time location; the entrypoint script will copy it to /tmp at runtimeARG PANEL_VERSION=v1.17.10RUN mkdir -p /CLIProxyAPI/panel-assets && \ curl -sL "https://github.com/router-for-me/Cli-Proxy-API-Management-Center/releases/download/${PANEL_VERSION}/management.html" \ -o /CLIProxyAPI/panel-assets/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
# HF Space root filesystem is read-only; /tmp is writableENV MANAGEMENT_STATIC_PATH=/tmpENV PGSTORE_LOCAL_PATH=/tmp
# Entrypoint: copy pre-downloaded panel to writable /tmp, then start the serverCOPY entrypoint.sh /CLIProxyAPI/entrypoint.shRUN chmod +x /CLIProxyAPI/entrypoint.sh
ENV TZ=Asia/ShanghaiRUN cp /usr/share/zoneinfo/${TZ} /etc/localtime && echo "${TZ}" > /etc/timezone
CMD ["./entrypoint.sh"]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}")123456789101112host: ""port: 7860
auth-dir: /data/auths
remote-management: allow-remote: true
commercial-mode: trueusage-statistics-enabled: true
request-retry: 3123456789101112#!/bin/sh# Copy pre-downloaded management panel to writable /tmp directory# (HF Space root filesystem is read-only; /tmp is writable)if [ -f /CLIProxyAPI/panel-assets/management.html ] && [ ! -f /tmp/management.html ]; then cp /CLIProxyAPI/panel-assets/management.html /tmp/management.html echo "Copied management.html to /tmp/"fi
# Create auth directory if it doesn't exist (HF persistent volume may be empty on first run)mkdir -p /data/auths
exec ./cli-proxy-api123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179"""Bidirectional auth file sync between HF Space and PostgreSQL.
Modes: backup - HF → PG: Read auth files from HF Space, upsert to PG restore - PG → HF: If HF has no auth files, push from PG sync - backup + restore + delete stale PG records
Runs as GitHub Actions cron every 10 minutes."""
import os, sys, json, time, requestsimport psycopg2from psycopg2.extras import execute_values
REPO_ID = "mansui52001/grok2api"HF_TOKEN = os.environ["HF_TOKEN"]PGSTORE_DSN = os.environ.get("PGSTORE_DSN", "")MANAGEMENT_PASSWORD = os.environ.get("REMOTE_MGMT_KEY", "")SPACE_URL = f"https://mansui52001-grok2api.hf.space"
# PG table nameTABLE = "auth_backup"
def get_pg_conn(): if not PGSTORE_DSN: print("ERROR: PGSTORE_DSN not set") sys.exit(1) return psycopg2.connect(PGSTORE_DSN)
def ensure_table(conn): """Create the backup table if not exists.""" with conn.cursor() as cur: cur.execute(f""" CREATE TABLE IF NOT EXISTS {TABLE} ( filename TEXT PRIMARY KEY, content TEXT NOT NULL, updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ) """) conn.commit()
def get_hf_auth_files(): """List and read all auth files from HF Space via Management API.""" headers = { "Authorization": f"Bearer {MANAGEMENT_PASSWORD}", "X-Management-Key": MANAGEMENT_PASSWORD, } # List auth files try: r = requests.get(f"{SPACE_URL}/v0/management/auth-files", headers=headers, timeout=30) if r.status_code != 200: print(f"List auth files failed: {r.status_code} {r.text[:200]}") return {} data = r.json() # Response format: {"files": [{"name": "...", "size": ...}, ...]} file_list = data.get("files", data) if isinstance(data, dict) else data if isinstance(file_list, dict): file_list = file_list.get("files", []) except Exception as e: print(f"List auth files error: {e}") return {}
# Read each file content auth_files = {} for f in file_list: name = f if isinstance(f, str) else f.get("name", "") if not name: continue try: r2 = requests.get( f"{SPACE_URL}/v0/management/auth-files/{name}", headers=headers, timeout=30 ) if r2.status_code == 200: auth_files[name] = r2.text else: print(f" Read {name} failed: {r2.status_code}") except Exception as e: print(f" Read {name} error: {e}") return auth_files
def backup_to_pg(conn, auth_files): """Upsert auth files to PG.""" if not auth_files: print("No auth files on HF, skipping backup") return with conn.cursor() as cur: for name, content in auth_files.items(): cur.execute(f""" INSERT INTO {TABLE} (filename, content, updated_at) VALUES (%s, %s, NOW()) ON CONFLICT (filename) DO UPDATE SET content = EXCLUDED.content, updated_at = NOW() """, (name, content)) conn.commit() print(f"Backed up {len(auth_files)} auth files to PG")
def delete_stale_from_pg(conn, hf_filenames): """Delete PG records that no longer exist on HF.""" if not hf_filenames: # HF has no files - don't delete everything (might be temporary) print("HF has 0 auth files, skipping PG cleanup to avoid accidental data loss") return with conn.cursor() as cur: cur.execute(f"SELECT filename FROM {TABLE}") pg_filenames = {row[0] for row in cur.fetchall()} stale = pg_filenames - set(hf_filenames) if stale: with conn.cursor() as cur: cur.execute(f"DELETE FROM {TABLE} WHERE filename = ANY(%s)", (list(stale),)) conn.commit() print(f"Deleted {len(stale)} stale records from PG: {stale}") else: print("No stale records in PG")
def restore_from_pg(conn): """Push auth files from PG to HF if HF has none.""" with conn.cursor() as cur: cur.execute(f"SELECT filename, content FROM {TABLE}") pg_files = {row[0]: row[1] for row in cur.fetchall()}
if not pg_files: print("PG has no auth files to restore") return
headers = { "Authorization": f"Bearer {MANAGEMENT_PASSWORD}", "X-Management-Key": MANAGEMENT_PASSWORD, "Content-Type": "application/json", }
restored = 0 for name, content in pg_files.items(): try: r = requests.put( f"{SPACE_URL}/v0/management/auth-files/{name}", headers=headers, data=content, timeout=30, ) if r.status_code in (200, 201): restored += 1 else: print(f" Restore {name} failed: {r.status_code} {r.text[:200]}") except Exception as e: print(f" Restore {name} error: {e}")
print(f"Restored {restored}/{len(pg_files)} auth files from PG to HF")
def main(): mode = sys.argv[1] if len(sys.argv) > 1 else "sync" print(f"=== Auth Sync Mode: {mode} ===")
conn = get_pg_conn() ensure_table(conn)
hf_auth_files = get_hf_auth_files() print(f"HF Space has {len(hf_auth_files)} auth files")
if mode in ("backup", "sync"): backup_to_pg(conn, hf_auth_files)
if mode in ("sync",): delete_stale_from_pg(conn, set(hf_auth_files.keys()))
if mode in ("restore", "sync"): # Only restore if HF has 0 files (indicating restart with data loss) if len(hf_auth_files) == 0: print("HF has no auth files - restoring from PG...") restore_from_pg(conn) else: print(f"HF has {len(hf_auth_files)} files, no restore needed")
conn.close() print("=== Sync Complete ===")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140import 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")DockerfileAdded+42
README.mdAdded+9
check_space.pyAdded+70
config.yamlAdded+12
entrypoint.shAdded+12
sync_auths.pyAdded+179
sync_to_hf.pyAdded+140