""" 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, requests import psycopg2 from 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 name TABLE = "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()