""" Bootstrap script for IP-Check project. Run this once before your first pipeline run to verify everything is set up correctly. Idempotent — safe to run multiple times. Usage: python bootstrap.py """ import os import sys import pickle import subprocess from pathlib import Path try: from rich.console import Console from rich.table import Table except ImportError: print("ERROR: 'rich' not installed. Run: pip install -r requirements.txt") sys.exit(1) console = Console() REQUIRED_SCOPES = { 'https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive', } REQUIRED_KEYS = [ ("OPENAI_API_KEY", "Required for IP/QC (GPT-5.2)"), ("GOOGLE_API_KEY", "Required for Gemini + Narration Matching"), ("ANTHROPIC_API_KEY", "Required for IP/QC (Claude Opus 4.6)"), ] OPTIONAL_KEYS = [ ("SUPABASE_URL", "Optional — enables run history"), ("SUPABASE_KEY", "Optional — enables run history"), ] def check_python() -> tuple[bool, str]: v = sys.version_info if v >= (3, 10): return True, f"Python {v.major}.{v.minor}.{v.micro}" return False, f"Python {v.major}.{v.minor} — need 3.10+" def check_env() -> tuple[bool, str]: if os.path.exists(".env"): return True, ".env found" if os.path.exists(".env.example"): import shutil shutil.copy(".env.example", ".env") return False, ".env created from .env.example — fill in your API keys" return False, ".env missing and no .env.example found" def check_api_keys() -> list[tuple[bool, str, str]]: """Load .env manually and check each required key.""" # Load .env if exists env_vars = {} if os.path.exists(".env"): with open(".env") as f: for line in f: line = line.strip() if line and not line.startswith("#") and "=" in line: k, _, v = line.partition("=") env_vars[k.strip()] = v.strip() results = [] for key, desc in REQUIRED_KEYS: val = env_vars.get(key) or os.getenv(key, "") ok = bool(val and not val.startswith("sk-...") and not val.startswith("AIza...") and val != "...") results.append((ok, key, desc)) return results def check_oauth_credentials() -> tuple[bool, str]: if os.path.exists("oauth_credentials.json"): return True, "oauth_credentials.json found" return False, ( "oauth_credentials.json missing\n" " Fix: Go to console.cloud.google.com → APIs & Services → Credentials\n" " Create an OAuth 2.0 Client ID (Desktop app) → Download JSON → save as oauth_credentials.json" ) def check_token() -> tuple[bool, str]: if not os.path.exists("token.pickle"): return False, "token.pickle missing — run: python authenticate_oauth.py" try: with open("token.pickle", "rb") as f: creds = pickle.load(f) if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: return True, "token.pickle found (will auto-refresh on next run)" return False, "token.pickle is invalid — run: python authenticate_oauth.py" granted = set(creds.scopes or []) missing = REQUIRED_SCOPES - granted if missing: return False, ( f"token.pickle has wrong scopes (missing: drive scope)\n" f" Fix: delete token.pickle then run: python authenticate_oauth.py" ) return True, "token.pickle valid with correct scopes" except Exception as e: return False, f"Could not read token.pickle: {e} — run: python authenticate_oauth.py" def check_supabase() -> tuple[bool, str]: url = os.getenv("SUPABASE_URL") key = os.getenv("SUPABASE_KEY") if not url or not key: # Also check .env file env_vars = {} if os.path.exists(".env"): with open(".env") as f: for line in f: line = line.strip() if line and not line.startswith("#") and "=" in line: k, _, v = line.partition("=") env_vars[k.strip()] = v.strip() url = env_vars.get("SUPABASE_URL", "") key = env_vars.get("SUPABASE_KEY", "") if not url or not key: return None, "Not configured (optional — add SUPABASE_URL + SUPABASE_KEY to .env to enable)" try: from supabase import create_client client = create_client(url, key) # Light ping — just instantiation is enough to validate URL format return True, "Supabase client connected" except ImportError: return False, "supabase package missing — run: pip install supabase>=2.0.0" except Exception as e: return False, f"Supabase connection failed: {e}" def main(): console.print("\n[bold cyan]IP-Check Bootstrap[/bold cyan]") console.print("Checking setup for all pipelines...\n") table = Table(show_header=True, header_style="bold white on blue") table.add_column("Check", style="cyan", min_width=28) table.add_column("Status", min_width=8) table.add_column("Details") all_ok = True def add_row(label, ok, detail): nonlocal all_ok if ok is True: status = "[bold green]OK[/bold green]" elif ok is False: status = "[bold red]FAIL[/bold red]" all_ok = False else: # None = optional status = "[dim]SKIP[/dim]" table.add_row(label, status, detail) # Python version ok, msg = check_python() add_row("Python version", ok, msg) # .env file ok, msg = check_env() add_row(".env file", ok, msg) # API keys for key_ok, key_name, key_desc in check_api_keys(): add_row(key_name, key_ok, key_desc if not key_ok else "set") # OAuth credentials ok, msg = check_oauth_credentials() add_row("oauth_credentials.json", ok, msg) # OAuth token + scopes ok, msg = check_token() add_row("token.pickle (OAuth)", ok, msg) # Supabase (optional) ok, msg = check_supabase() add_row("Supabase (optional)", ok, msg) console.print(table) if all_ok: console.print("\n[bold green]All checks passed! Ready to run.[/bold green]") console.print("\nQuick start:") console.print(" [cyan]python run_analysis.py --pdf your_comic.pdf[/cyan]") console.print(" [cyan]python run_narration_matching.py --pdf your_comic.pdf --audio-dir ./audio[/cyan]") else: console.print("\n[bold yellow]Some checks failed — fix the issues above before running pipelines.[/bold yellow]") console.print("Re-run [cyan]python bootstrap.py[/cyan] after fixing.\n") sys.exit(1) if __name__ == "__main__": main()