Spaces:
Paused
Paused
Upload folder using huggingface_hub
Browse filesFiles changed (8)
- DockerfileAdded+42
- README.mdAdded+9
- check_space.pyAdded+73
- config.yamlAdded+12
- entrypoint.shAdded+23
- sync.ymlAdded+46
- sync_auths.pyAdded+116
- 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---12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273import os, requests, json
HF_TOKEN = os.environ["HF_TOKEN"]REPO_ID = "mansui52001/grok2api"ADMIN_KEY = os.environ.get("MANAGEMENT_PASSWORD")if not ADMIN_KEY: print("ERROR: MANAGEMENT_PASSWORD environment variable not set") exit(1)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: 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"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116"""Cleanup expired auth accounts from PostgreSQL auth_store.
In PG mode, CLIProxyAPI writes auth files directly to PG. This scriptcleans up expired accounts to keep the database tidy.
Modes: cleanup - Delete expired accounts from PG (where content->>'expired' < now) sync - Same as cleanup (alias for backward compatibility) backup - No-op in PG mode (CLIProxyAPI writes to PG directly) restore - No-op in PG mode (CLIProxyAPI reads from PG directly)
Runs as GitHub Actions cron every 10 minutes."""
import os, sys, json, requests, psycopg2from datetime import datetime, timezone
PGSTORE_DSN = os.environ.get("PGSTORE_DSN", "")MGMT_PWD = os.environ.get("REMOTE_MGMT_KEY", "")SPACE_URL = "https://mansui52001-grok2api.hf.space"TABLE = "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 cleanup_expired(conn): """Delete expired auth accounts from PG.""" now_utc = datetime.now(timezone.utc).isoformat() with conn.cursor() as cur: cur.execute(f""" SELECT id, content->>'expired' as expired FROM {TABLE} WHERE content->>'expired' IS NOT NULL AND (content->>'expired')::timestamptz < NOW() - INTERVAL '1 hour' """) expired = cur.fetchall()
if not expired: print("No expired accounts to clean up") return 0
print(f"Found {len(expired)} expired accounts:") for name, exp_time in expired[:10]: print(f" {name} (expired: {exp_time})") if len(expired) > 10: print(f" ... and {len(expired) - 10} more")
with conn.cursor() as cur: cur.execute(f""" DELETE FROM {TABLE} WHERE content->>'expired' IS NOT NULL AND (content->>'expired')::timestamptz < NOW() - INTERVAL '1 hour' """) deleted = cur.rowcount conn.commit() print(f"Deleted {deleted} expired accounts from PG") return deleted
def sync_hf_with_pg(conn): """Ensure HF Space and PG are in sync (delete HF files not in PG).""" headers = { "Authorization": f"Bearer {MGMT_PWD}", "X-Management-Key": MGMT_PWD, } try: r = requests.get(f"{SPACE_URL}/v0/management/auth-files", headers=headers, timeout=30) if r.status_code != 200: print(f"Cannot list HF files: {r.status_code}") return hf_files = {f.get("name", f.get("id", "")) for f in r.json().get("files", [])} except Exception as e: print(f"Cannot reach HF Space: {e}") return
with conn.cursor() as cur: cur.execute(f"SELECT id FROM {TABLE}") pg_files = {row[0] for row in cur.fetchall()}
stale_hf = hf_files - pg_files if stale_hf: print(f"Deleting {len(stale_hf)} stale files from HF (not in PG)") for name in stale_hf: try: requests.delete(f"{SPACE_URL}/v0/management/auth-files", headers=headers, json={"name": name}, timeout=10) except: pass else: print("HF and PG are in sync")
def main(): mode = sys.argv[1] if len(sys.argv) > 1 else "cleanup" print(f"=== Auth Cleanup Mode: {mode} ===")
conn = get_pg_conn()
if mode in ("cleanup", "sync"): cleanup_expired(conn) sync_hf_with_pg(conn) elif mode in ("backup", "restore"): print(f"No-op in PG mode (CLIProxyAPI uses PG directly)")
conn.close() print("=== Cleanup 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+73
config.yamlAdded+12
entrypoint.shAdded+23
sync.ymlAdded+46
sync_auths.pyAdded+116
sync_to_hf.pyAdded+140