Spaces:
Paused
Paused
Upload folder using huggingface_hub
Browse filesFiles changed (9)
- DockerfileAdded+42
- README.mdAdded+9
- check_space.pyAdded+70
- cleanup.ymlAdded+34
- config.yamlAdded+12
- entrypoint.shAdded+23
- sync.ymlAdded+46
- sync_auths.pyAdded+206
- 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}")12345678910111213141516171819202122232425262728293031323334name: Cleanup Stale Auth
on: schedule: # Every 15 minutes: delete stale records on both PG and HF - cron: '*/15 * * * *' workflow_dispatch:
env: REPO_ID: mansui52001/grok2api
jobs: cleanup: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v4
- name: Setup Python uses: actions/setup-python@v5 with: python-version: '3.11'
- name: Install dependencies run: pip install psycopg2-binary requests
- name: Cleanup stale records env: HF_TOKEN: ${{ secrets.HF_TOKEN }} PGSTORE_DSN: ${{ secrets.PGSTORE_DSN }} REMOTE_MGMT_KEY: ${{ secrets.REMOTE_MGMT_KEY }} run: | echo "Running cleanup mode..." python sync_auths.py cleanup123456789101112host: ""port: 7860
auth-dir: /data/auths
remote-management: allow-remote: true
commercial-mode: trueusage-statistics-enabled: true
request-retry: 31234567891011121314151617181920212223#!/bin/shset -e
echo "=== CLIProxyAPI Starting ==="echo "Time: $(date)"
# Copy pre-downloaded management panel to writable /tmp directoryif [ -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 existmkdir -p /data/auths
# Check if binary exists and is executableif [ ! -x "./cli-proxy-api" ]; then echo "ERROR: cli-proxy-api binary not found or not executable" exit 1fi
echo "Starting cli-proxy-api..."exec ./cli-proxy-api12345678910111213141516171819202122232425262728293031323334353637383940414243444546name: Auth Sync
on: schedule: # Every 10 minutes: backup HF → PG, restore if HF empty - cron: '*/10 * * * *' workflow_dispatch: inputs: mode: description: 'Sync mode' required: true default: 'sync' type: choice options: - sync - backup - restore - cleanup
env: REPO_ID: mansui52001/grok2api
jobs: sync: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v4
- name: Setup Python uses: actions/setup-python@v5 with: python-version: '3.11'
- name: Install dependencies run: pip install psycopg2-binary requests
- name: Run sync env: HF_TOKEN: ${{ secrets.HF_TOKEN }} PGSTORE_DSN: ${{ secrets.PGSTORE_DSN }} REMOTE_MGMT_KEY: ${{ secrets.REMOTE_MGMT_KEY }} run: | MODE="${{ github.event.inputs.mode || 'sync' }}" echo "Running sync in mode: $MODE" python sync_auths.py "$MODE"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206"""Bidirectional auth file sync between HF Space and PostgreSQL (Aiven).
Modes: backup - HF → PG: Read auth files from HF Space, upsert to auth_store restore - PG → HF: Push auth files from auth_store to HF Space sync - backup + restore (if HF empty) + delete stale PG records cleanup - Delete PG records that no longer exist on HF
Runs as GitHub Actions cron every 10 minutes (sync) and 15 minutes (cleanup)."""
import os, sys, json, requestsimport psycopg2
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 = "https://mansui52001-grok2api.hf.space"
# PG table used by CLIProxyAPI itselfTABLE = "auth_store"
def get_pg_conn(): if not PGSTORE_DSN: print("ERROR: PGSTORE_DSN not set") sys.exit(1) return psycopg2.connect(PGSTORE_DSN)
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, } 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() file_list = data.get("files", []) except Exception as e: print(f"List auth files error: {e}") return {}
auth_files = {} for f in file_list: name = f.get("name", f.get("id", "")) 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.json() 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 auth_store table.""" 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(): content_json = json.dumps(content) cur.execute(f""" INSERT INTO {TABLE} (id, content, updated_at) VALUES (%s, %s, NOW()) ON CONFLICT (id) DO UPDATE SET content = EXCLUDED.content, updated_at = NOW() """, (name, content_json)) conn.commit() print(f"Backed up {len(auth_files)} auth files to PG ({TABLE})")
def delete_stale_from_pg(conn, hf_filenames): """Delete PG records that no longer exist on HF.""" if not hf_filenames: print("HF has 0 auth files, skipping PG cleanup to avoid accidental data loss") return with conn.cursor() as cur: cur.execute(f"SELECT id 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 id = 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 auth_store to HF Space.""" with conn.cursor() as cur: cur.execute(f"SELECT id, 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, }
restored = 0 for name, content in pg_files.items(): content_str = json.dumps(content, indent=2) if isinstance(content, dict) else str(content) files = {"file": (name, content_str, "application/json")} try: r = requests.post( f"{SPACE_URL}/v0/management/auth-files", headers=headers, files=files, timeout=30, ) if r.status_code == 200: 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 delete_hf_auth_file(name): """Delete an auth file from HF Space.""" headers = { "Authorization": f"Bearer {MANAGEMENT_PASSWORD}", "X-Management-Key": MANAGEMENT_PASSWORD, } try: r = requests.delete( f"{SPACE_URL}/v0/management/auth-files", headers=headers, json={"name": name}, timeout=30, ) return r.status_code == 200 except Exception as e: print(f" Delete {name} error: {e}") return False
def cleanup_stale(conn): """Delete PG records that no longer exist on HF (cleanup mode).""" hf_auth_files = get_hf_auth_files() print(f"HF Space has {len(hf_auth_files)} auth files")
if not hf_auth_files: print("HF has 0 auth files, skipping cleanup to avoid accidental data loss") return
delete_stale_from_pg(conn, set(hf_auth_files.keys()))
# Also check for stale files on HF that are not in PG with conn.cursor() as cur: cur.execute(f"SELECT id FROM {TABLE}") pg_filenames = {row[0] for row in cur.fetchall()}
stale_hf = set(hf_auth_files.keys()) - pg_filenames if stale_hf: print(f"Found {len(stale_hf)} stale files on HF not in PG: {stale_hf}") for name in stale_hf: if delete_hf_auth_file(name): print(f" Deleted {name} from HF") else: print(f" Failed to delete {name} from HF") else: print("No stale files on HF")
def main(): mode = sys.argv[1] if len(sys.argv) > 1 else "sync" print(f"=== Auth Sync Mode: {mode} ===")
conn = get_pg_conn()
if mode in ("backup", "sync"): hf_auth_files = get_hf_auth_files() print(f"HF Space has {len(hf_auth_files)} auth files") 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"): if mode == "restore": hf_auth_files = get_hf_auth_files() 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")
if mode == "cleanup": cleanup_stale(conn)
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
cleanup.ymlAdded+34
config.yamlAdded+12
entrypoint.shAdded+23
sync.ymlAdded+46
sync_auths.pyAdded+206
sync_to_hf.pyAdded+140