---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\"Import offline-scored UK results through the canonical event sink.\"\"\" from __future__ import annotations import argparse import json import sys import db_uk as db def."
resource: "https://uk.copecheck.com"
tags: ["copecheck", "uk", "source-file", "py"]
timestamp: "2026-08-24T12:57:08Z"
site: "uk"
source_path: "copecheck-uk/import_scores.py"
---

# !/usr/bin/env python3

Source path: `copecheck-uk/import_scores.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-08-24T12:57:08Z`

```py
#!/usr/bin/env python3
"""Import offline-scored UK results through the canonical event sink."""
from __future__ import annotations

import argparse
import json
import sys

import db_uk as db


def _delete_pending(db_module, pending_id):
    if pending_id is None:
        return
    with db_module.conn() as connection:
        connection.execute(
            "DELETE FROM pending_scores WHERE id=?", (pending_id,)
        )


def import_scores(items, db_module=db):
    """Import results and return inserted/duplicate/error counts.

    A pending row is acknowledged only after the central sink accepts either a
    new event or a repeat observation. Invalid/failed results remain pending
    so they can be repaired and retried.
    """
    summary = {"inserted": 0, "duplicates": 0, "errors": 0}
    for item in items:
        try:
            quote = item.get("cope_quote") or item.get("quote_context", "")[:500]
            if not str(quote or "").strip():
                raise ValueError("missing cope quote/context")
            outcome = db_module.add_cope_entry(
                figure_id=item["figure_id"],
                quote=quote,
                source_url=item.get("source_url", ""),
                source_title=item.get("source_title", ""),
                cope_score=item["cope_score"],
                cope_type=item.get("cope_type", "unknown"),
                analysis_md=item.get("analysis", ""),
                model=item.get("model", "claude-sonnet"),
                observed_at=item.get("observed_at") or item.get("published_at"),
                channel=item.get("channel", "offline_import"),
            )
            if not isinstance(outcome, dict):
                raise RuntimeError("central event sink returned no outcome")
            if outcome.get("inserted"):
                accepted_kind = "inserted"
            elif outcome.get("reason") == "duplicate_event":
                accepted_kind = "duplicates"
            else:
                raise ValueError(
                    f"event rejected: {outcome.get('reason', 'unknown')}"
                )
            _delete_pending(db_module, item.get("pending_id"))
            summary[accepted_kind] += 1
        except Exception as exc:
            print(
                f"Error processing {item.get('figure_id', '<missing>')}: {exc}",
                file=sys.stderr,
            )
            summary["errors"] += 1
    return summary


def main(argv=None):
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--db", help="Override COPECHECK_UK_DB for this import"
    )
    args = parser.parse_args(argv)
    if args.db:
        db.DB_PATH = args.db
    scored = json.load(sys.stdin)
    if not isinstance(scored, list):
        raise SystemExit("input must be a JSON list")
    print(json.dumps(import_scores(scored), sort_keys=True))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
```
