Spaces:
Sleeping
Sleeping
Claude Opus 5
Fix scoring engine: restore ML path, remove synthetic ensemble, secure key issuance
992fce0 Download src/load_to_postgres.py from frigate-global/financial-risk-api: direct link, hf CLI and curl.
- Browser
- Download file 9.05 kB
-
https://huggingface.co/spaces/frigate-global/financial-risk-api/resolve/main/src/load_to_postgres.py
- Command line
-
hf download hf://spaces/frigate-global/financial-risk-api/src/load_to_postgres.py
-
curl -L -o load_to_postgres.py https://huggingface.co/spaces/frigate-global/financial-risk-api/resolve/main/src/load_to_postgres.py
9.05 kB
| """Loads a local SQLite financial_risk.db into a PostgreSQL database. | |
| This is the seed path the repo otherwise lacks: the Docker image ships only | |
| db/schema.sql, so a freshly provisioned Postgres has tables and zero rows and | |
| every /risk-score call returns 404 until this is run. | |
| Usage: | |
| # inspect what would happen, no writes, no psycopg2 needed | |
| python src/load_to_postgres.py --source financial_risk.db --dry-run | |
| # create the schema and load everything | |
| python src/load_to_postgres.py \\ | |
| --source financial_risk.db \\ | |
| --target "postgresql://user:pw@host:6543/postgres" \\ | |
| --create-schema | |
| # reload from scratch over an existing database | |
| python src/load_to_postgres.py --source financial_risk.db --truncate | |
| If --target is omitted the DATABASE_URL environment variable is used. | |
| Notes on the translation, which is not a straight copy: | |
| * SQLite has no boolean type and stores 0/1 in columns declared BOOLEAN. | |
| Those columns are detected from the source schema rather than hardcoded, | |
| so a new BOOLEAN column does not silently break the load. | |
| * db/schema.sql declares INTEGER PRIMARY KEY AUTOINCREMENT, which becomes | |
| SERIAL in Postgres. Inserting explicit ids does not advance the backing | |
| sequence, so every sequence is reset after the load -- without that, the | |
| first application INSERT collides with an existing id. | |
| * Tables load in foreign-key order. | |
| """ | |
| import argparse | |
| import os | |
| import re | |
| import sqlite3 as _shimmed_sqlite3 | |
| import sys | |
| from pathlib import Path | |
| BASE_DIR = Path(__file__).resolve().parent.parent | |
| SCHEMA_PATH = BASE_DIR / "db" / "schema.sql" | |
| # Foreign-key safe insert order. Tables present in the source but not listed | |
| # here are loaded afterwards, in whatever order SQLite reports them. | |
| LOAD_ORDER = [ | |
| "users", | |
| "accounts", | |
| "transactions", | |
| "feature_snapshots", | |
| "risk_outcomes", | |
| "model_predictions", | |
| "shadow_model_predictions", | |
| "repayment_outcomes", | |
| "human_overrides", | |
| "feature_trust_logs", | |
| "calibration_memory", | |
| "archetype_evolution_logs", | |
| "portfolio_telemetry", | |
| "autonomous_learning_runs", | |
| "api_keys", | |
| ] | |
| BATCH_SIZE = 1000 | |
| def real_sqlite3(): | |
| """Returns the genuine stdlib sqlite3. | |
| src/sqlite3.py shadows the stdlib module and reroutes connect() to Postgres | |
| whenever DATABASE_URL is set -- which is exactly the situation this script | |
| runs in, so it must reach past the shim to read the source file. | |
| """ | |
| return getattr(_shimmed_sqlite3, "real_sqlite3", _shimmed_sqlite3) | |
| def translate_schema(script): | |
| """Converts the SQLite schema DDL to PostgreSQL.""" | |
| script = re.sub(r"INTEGER\s+PRIMARY\s+KEY\s+AUTOINCREMENT", "SERIAL PRIMARY KEY", | |
| script, flags=re.IGNORECASE) | |
| script = re.sub(r"BOOLEAN\s+NOT\s+NULL\s+DEFAULT\s+0", "BOOLEAN NOT NULL DEFAULT FALSE", | |
| script, flags=re.IGNORECASE) | |
| script = re.sub(r"BOOLEAN\s+NOT\s+NULL\s+DEFAULT\s+1", "BOOLEAN NOT NULL DEFAULT TRUE", | |
| script, flags=re.IGNORECASE) | |
| script = re.sub(r"PRAGMA\s+[^;]+;", "", script, flags=re.IGNORECASE) | |
| return script | |
| def inspect_source(src_conn): | |
| """Returns [(table, [columns], {bool columns}, row_count)] in load order.""" | |
| cur = src_conn.cursor() | |
| cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'") | |
| present = {r[0] for r in cur.fetchall()} | |
| ordered = [t for t in LOAD_ORDER if t in present] | |
| ordered += sorted(present - set(ordered)) | |
| tables = [] | |
| for table in ordered: | |
| cur.execute(f'PRAGMA table_info("{table}")') | |
| info = cur.fetchall() | |
| columns = [row[1] for row in info] | |
| # row[2] is the declared type; SQLite keeps the literal text. | |
| bool_cols = {row[1] for row in info if str(row[2]).upper().startswith("BOOL")} | |
| cur.execute(f'SELECT COUNT(*) FROM "{table}"') | |
| count = cur.fetchone()[0] | |
| tables.append((table, columns, bool_cols, count)) | |
| return tables | |
| def coerce_row(row, columns, bool_cols): | |
| """Maps a SQLite row to Postgres-native Python values.""" | |
| out = [] | |
| for col, val in zip(columns, row): | |
| if col in bool_cols and val is not None: | |
| out.append(bool(val)) | |
| else: | |
| out.append(val) | |
| return tuple(out) | |
| def reset_sequences(pg_cur, tables): | |
| """Advances SERIAL sequences past the highest explicitly inserted id. | |
| Loading explicit primary keys leaves the sequence at 1, so the first | |
| application INSERT would raise a duplicate key error. | |
| """ | |
| reset = [] | |
| for table, columns, _bool_cols, _count in tables: | |
| for col in columns: | |
| pg_cur.execute("SELECT pg_get_serial_sequence(%s, %s)", (table, col)) | |
| seq = pg_cur.fetchone()[0] | |
| if not seq: | |
| continue | |
| pg_cur.execute( | |
| f'SELECT setval(%s, COALESCE((SELECT MAX("{col}") FROM "{table}"), 0) + 1, false)', | |
| (seq,)) | |
| reset.append(f"{table}.{col}") | |
| return reset | |
| def main(): | |
| ap = argparse.ArgumentParser(description=__doc__, | |
| formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("--source", default=str(BASE_DIR / "financial_risk.db"), | |
| help="path to the source SQLite database") | |
| ap.add_argument("--target", default=None, | |
| help="PostgreSQL DSN (defaults to $DATABASE_URL)") | |
| ap.add_argument("--create-schema", action="store_true", | |
| help="apply db/schema.sql to the target before loading") | |
| ap.add_argument("--truncate", action="store_true", | |
| help="empty the target tables before loading") | |
| ap.add_argument("--dry-run", action="store_true", | |
| help="report what would be loaded and exit without connecting") | |
| args = ap.parse_args() | |
| source = Path(args.source) | |
| if not source.exists(): | |
| sys.exit(f"Source database not found: {source}") | |
| src = real_sqlite3().connect(str(source)) | |
| tables = inspect_source(src) | |
| total = sum(c for _t, _c, _b, c in tables) | |
| print(f"Source: {source}") | |
| print(f"{'table':<28}{'rows':>10} boolean columns") | |
| print("-" * 68) | |
| for table, _columns, bool_cols, count in tables: | |
| print(f"{table:<28}{count:>10} {', '.join(sorted(bool_cols)) or '-'}") | |
| print("-" * 68) | |
| print(f"{'TOTAL':<28}{total:>10}") | |
| if args.dry_run: | |
| print("\nDry run: nothing written.") | |
| return | |
| dsn = args.target or os.environ.get("DATABASE_URL") | |
| if not dsn: | |
| sys.exit("No target given. Pass --target or set DATABASE_URL.") | |
| if dsn.startswith("postgres://"): | |
| dsn = dsn.replace("postgres://", "postgresql://", 1) | |
| try: | |
| import psycopg2 | |
| from psycopg2.extras import execute_values | |
| except ImportError: | |
| sys.exit("psycopg2 is required to load. Install with: pip install psycopg2-binary") | |
| print(f"\nTarget: {re.sub(r'//[^@]*@', '//***@', dsn)}") | |
| pg = psycopg2.connect(dsn) | |
| try: | |
| cur = pg.cursor() | |
| if args.create_schema: | |
| if not SCHEMA_PATH.exists(): | |
| sys.exit(f"Schema file not found: {SCHEMA_PATH}") | |
| print("Applying schema...") | |
| cur.execute(translate_schema(SCHEMA_PATH.read_text(encoding="utf-8"))) | |
| pg.commit() | |
| print(" schema applied.") | |
| if args.truncate: | |
| names = ", ".join(f'"{t}"' for t, _c, _b, _n in tables) | |
| print("Truncating target tables...") | |
| cur.execute(f"TRUNCATE {names} RESTART IDENTITY CASCADE") | |
| pg.commit() | |
| print(" truncated.") | |
| loaded = 0 | |
| for table, columns, bool_cols, count in tables: | |
| if count == 0: | |
| print(f" {table:<28} skipped (empty)") | |
| continue | |
| collist = ", ".join(f'"{c}"' for c in columns) | |
| sql = f'INSERT INTO "{table}" ({collist}) VALUES %s ON CONFLICT DO NOTHING' | |
| src_cur = src.cursor() | |
| src_cur.execute(f'SELECT {collist} FROM "{table}"') | |
| written = 0 | |
| while True: | |
| rows = src_cur.fetchmany(BATCH_SIZE) | |
| if not rows: | |
| break | |
| execute_values(cur, sql, | |
| [coerce_row(r, columns, bool_cols) for r in rows], | |
| page_size=BATCH_SIZE) | |
| written += len(rows) | |
| pg.commit() | |
| loaded += written | |
| print(f" {table:<28} {written:>10} rows") | |
| print("\nResetting SERIAL sequences...") | |
| reset = reset_sequences(cur, tables) | |
| pg.commit() | |
| for name in reset: | |
| print(f" {name}") | |
| if not reset: | |
| print(" (none found)") | |
| print(f"\nDone. {loaded} rows loaded into PostgreSQL.") | |
| except Exception: | |
| pg.rollback() | |
| raise | |
| finally: | |
| pg.close() | |
| src.close() | |
| if __name__ == "__main__": | |
| main() | |