#!/usr/bin/env python3 """Push HF Space secrets via REST API. Run from repo root: `python3 scripts/push_hf_secrets.py` Legge i secret dal .env locale (parsing python-dotenv-style, gestisce spazi e quoting senza casino), li manda a: POST https://huggingface.co/api/spaces/BattleFiven/ai-tester-platform/secrets """ import json import os import sys import urllib.error import urllib.request from pathlib import Path # Il token HF DEVE essere passato via env var (HF Spaces secret scanner # blocca i push che contengono `hf_...` hardcoded nel repo). Genera un # token write da https://huggingface.co/settings/tokens e esporta: # export HF_TOKEN=hf_xxx # Poi lancia: `python3 scripts/push_hf_secrets.py` HF_TOKEN = os.environ.get("HF_TOKEN", "").strip() REPO = os.environ.get("HF_SPACE_REPO", "BattleFiven/ai-tester-platform").strip() POOLER_URL = ( "postgresql+psycopg2://postgres.qcnwwabdftoadsxovpkg:" "7gOgS9adRmW9i1HP@aws-1-eu-west-1.pooler.supabase.com:5432/postgres" ) def load_env(path: Path) -> dict[str, str]: """Minimal .env parser. Skips comments / empty lines, strips matching quote pairs, leaves the rest as-is (spaces and special chars OK).""" out: dict[str, str] = {} for line in path.read_text().splitlines(): s = line.strip() if not s or s.startswith("#") or "=" not in s: continue k, _, v = s.partition("=") k = k.strip() v = v.strip() # Strip matching surrounding quotes (single or double). if len(v) >= 2 and v[0] == v[-1] and v[0] in ('"', "'"): v = v[1:-1] out[k] = v return out def set_secret(key: str, value: str) -> bool: if not value: print(f" · {key:35s} SKIPPED (empty)") return True url = f"https://huggingface.co/api/spaces/{REPO}/secrets" body = json.dumps({"key": key, "value": value}).encode() req = urllib.request.Request( url, data=body, headers={ "Authorization": f"Bearer {HF_TOKEN}", "Content-Type": "application/json", }, method="POST", ) try: with urllib.request.urlopen(req, timeout=20) as resp: print(f" ✓ {key:35s} HTTP {resp.status}") return True except urllib.error.HTTPError as e: print(f" ✗ {key:35s} HTTP {e.code}: {e.read().decode()[:120]}") except Exception as e: # noqa: BLE001 print(f" ✗ {key:35s} {type(e).__name__}: {e}") return False def main() -> int: if not HF_TOKEN: print("ERROR: env var HF_TOKEN non settata.") print(" 1. Crea un token write su https://huggingface.co/settings/tokens") print(" 2. Lancia: HF_TOKEN=hf_xxx python3 scripts/push_hf_secrets.py") return 2 env_path = Path(__file__).resolve().parents[1] / ".env" if not env_path.exists(): print(f"ERROR: .env not found at {env_path}") return 1 env = load_env(env_path) # Start with everything from .env (the user's source of truth for keys), # then apply prod-specific overrides. This way new vars added to .env # (e.g. OPENPROJECT_*, EVALUATOR_*) get pushed automatically next time. secrets: dict[str, str] = dict(env) # ── Skip list: things we never want on HF or that have prod overrides # below (no point pushing them twice). Empty strings are skipped anyway # by set_secret(). for skip in ( # Will be overridden below; no point pushing the local value first. "DATABASE_URL", "ENFORCE_AUTH", "BROWSER_HEADLESS", "BROWSER_SLOW_MO", "PUBLIC_BASE_URL", "SUPABASE_SCREENSHOTS_BUCKET", ): secrets.pop(skip, None) # ── Prod overrides ────────────────────────────────────────────────────── # Database: pooler URL (IPv4-compatibile), non il direct dev di .env. secrets["DATABASE_URL"] = POOLER_URL # Auth: in prod usiamo il vero flusso Supabase, mai il dev bypass. secrets["ENFORCE_AUTH"] = "true" # Browser: HF Space non ha display, headless obbligatorio + no slow_mo. secrets["BROWSER_HEADLESS"] = "true" secrets["BROWSER_SLOW_MO"] = "0" # Bucket Supabase Storage per screenshot (override del default vuoto). secrets["SUPABASE_SCREENSHOTS_BUCKET"] = "ai-tester-screenshots" # URL pubblico dell'app su HF (sostituisce localhost del dev). secrets["PUBLIC_BASE_URL"] = "https://battlefiven-ai-tester-platform.hf.space" # Tuning specifico per HF Space free tier (2 vCPU + 16GB): # - Chromium su 2vCPU diventa CPU-bound durante streaming bot → # pause naturali tra token possono superare il default 6.5s e far # dichiarare "stable" troppo presto, salvando risposte troncate. # - Polling più rilassato (500ms) per ridurre overhead query DOM # che competono con il rendering del bot per CPU. # - Grace di recupero extra a 60s per dare margine ai bot lenti. # Stabilization scese da 10000→8000ms dopo il fix truncation heuristic # esteso (60-180 char + ultima parola corta). Save ~2s/turno. secrets["BOT_RESPONSE_STABILIZATION_MS"] = "8000" secrets["BOT_RESPONSE_TRUNCATED_GRACE_S"] = "60" secrets["BOT_RESPONSE_POLL_MS"] = "500" secrets["BOT_RESPONSE_MIN_AGE_MS"] = "2000" # Zoom-out di default per far entrare più contenuto chat negli # screenshot live. "0.8" = ~25% di contenuto in più, "1.0" disabilita. secrets["BROWSER_ZOOM_LEVEL"] = "0.8" # Typing istantaneo del messaggio user (no simulazione char-by-char). # Save 2-4s/turno su messaggi lunghi. Trade-off: meno "umano" per il # bot remoto, ma su Playwright headless non importa. secrets["INSTANT_TYPING"] = "true" # Salta le fasi LLM secondarie (intent/actionability/critic) quando il # bot ha rifiutato: il rejudge retroattivo (UI "Forza rivalutazione") # può ricalcolarle on-demand. Save ~15s sui turni con refusal. secrets["JUDGE_SKIP_REFUSAL_PHASES"] = "true" # DB pool size: con polling cross-page + endpoint pesanti che fanno # bulk fetch, 5+10 (default) si saturava facilmente. 15+20 evita # contention sotto carico. secrets["DB_POOL_SIZE"] = "15" secrets["DB_MAX_OVERFLOW"] = "20" # TTL cache per /api/reports/* (lettura aggregata). 30s di stale OK, # i dati sono già "report" non real-time. secrets["REPORTS_CACHE_TTL_S"] = "30" # Feature flag che gata il calcolo del Wilson session verdict al # completion (session_runner.py). Default False in feature_flags.py # significava che il completion NON ricalcolava `verdict_p_hat`/ # `verdict_label`/etc., e dopo un "Riesegui" la tabella sessions # mostrava valori stale (1.0 / n=6) mentre il detail ricalcolava # 0.92 / n=13 dai turni live. Issue 2026-05-15. Stessa flag gata # anche `_compute_verdict_fields_from_logs` usato in `_mark_failed`. secrets["ENABLE_WILSON_SESSION_VERDICT"] = "true" # ais_verdict_enabled: per-turn AIS labels. Era a False per # "shadow mode" di rollout; ora il sistema lo usa pienamente. secrets["ENABLE_AIS_VERDICT"] = "true" # Bug tickets linked al turno (UI prompt-bug-from-turn). secrets["ENABLE_TURN_LEVEL_BUGS"] = "true" print(f"→ Pushing {len(secrets)} secrets to {REPO}") print() ok = fail = 0 for k, v in secrets.items(): if set_secret(k, v): ok += 1 else: fail += 1 print() print(f"Done. {ok} OK, {fail} failed.") print(f"Space si riavvia: https://huggingface.co/spaces/{REPO}") return 0 if fail == 0 else 1 if __name__ == "__main__": sys.exit(main())