File size: 6,860 Bytes
68697dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
"""
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()