---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\"Re-extract article bodies for curated rows whose body was truncated. STRICTLY ADDITIVE: the only column ever written is articles.body, and only when the freshly extracted text is longer than."
resource: "https://www.copecheck.com"
tags: ["copecheck", "main", "source-file", "py"]
timestamp: "2026-09-25T22:02:34Z"
site: "main"
source_path: "copecheck/repair_short_bodies.py"
---

# !/usr/bin/env python3

Source path: `copecheck/repair_short_bodies.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-09-25T22:02:34Z`

```py
#!/usr/bin/env python3
"""Re-extract article bodies for curated rows whose body was truncated.

STRICTLY ADDITIVE: the only column ever written is articles.body, and only
when the freshly extracted text is longer than what is already stored and
passes the existing extraction-quality gate. No score, verdict, one_liner,
relevance, index_status, provenance or any other field is touched, and no
row is ever deleted.

Run:  venv/bin/python repair_short_bodies.py [--dry-run] [--limit N]
"""
from __future__ import annotations

import argparse
import json
import logging
import os
import sqlite3
import sys
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timezone
from pathlib import Path

BASE = Path("/home/ben/infra/copecheck")
os.chdir(BASE)
sys.path.insert(0, str(BASE))

import pipeline  # noqa: E402  (home scraper + trafilatura fallback)
from content_quality import extraction_quality_issue  # noqa: E402

DB = Path(os.environ.get("COPECHECK_DB", BASE / "data" / "copecheck.db"))
TS = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
LOG_PATH = BASE / "logs" / f"repair_short_bodies-{TS}.log"
REPORT = BASE / "logs" / f"repair_short_bodies-{TS}.json"
MIN_GOOD = 500
WORKERS = int(os.environ.get("REPAIR_WORKERS", "4"))

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(message)s",
    handlers=[logging.FileHandler(LOG_PATH), logging.StreamHandler(sys.stdout)],
)
log = logging.getLogger("repair")

SELECT = """
SELECT slug, url, COALESCE(body, '') AS body
  FROM articles
 WHERE indexed_source = 'curated'
   AND length(COALESCE(body, '')) < 500
 ORDER BY id
"""

write_lock = threading.Lock()


def extract(url: str) -> tuple[str, str]:
    """Return (text, reason). reason is '' on success."""
    try:
        text = pipeline.fetch_article(url, source="repair:curated") or ""
    except Exception as exc:
        return "", f"fetch_error:{type(exc).__name__}"
    if not text:
        return "", "no_content"
    issue = extraction_quality_issue(text)
    if issue:
        return "", f"quality:{issue}"
    return text, ""


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--dry-run", action="store_true")
    ap.add_argument("--limit", type=int, default=0)
    args = ap.parse_args()

    conn = sqlite3.connect(DB, timeout=60)
    conn.row_factory = sqlite3.Row
    conn.execute("PRAGMA busy_timeout=60000")
    rows = [dict(r) for r in conn.execute(SELECT)]
    if args.limit:
        rows = rows[: args.limit]
    log.info("candidates=%d dry_run=%s workers=%d db=%s", len(rows), args.dry_run, WORKERS, DB)

    stats = {"repaired": 0, "unrecoverable": 0, "no_improvement": 0}
    failures: list[dict] = []
    repaired: list[dict] = []

    def work(row):
        text, reason = extract(row["url"])
        return row, text, reason

    with ThreadPoolExecutor(max_workers=WORKERS) as pool:
        futures = [pool.submit(work, r) for r in rows]
        for n, fut in enumerate(as_completed(futures), 1):
            row, text, reason = fut.result()
            slug, old = row["slug"], row["body"]
            if reason:
                stats["unrecoverable"] += 1
                failures.append({"slug": slug, "url": row["url"], "reason": reason})
                log.info("[%d/%d] UNRECOVERABLE %s (%s)", n, len(rows), slug, reason)
                continue
            if len(text) <= len(old) or len(text) < MIN_GOOD:
                stats["no_improvement"] += 1
                failures.append({
                    "slug": slug, "url": row["url"],
                    "reason": f"no_improvement:new={len(text)},old={len(old)}",
                })
                log.info("[%d/%d] NO-IMPROVEMENT %s new=%d old=%d",
                         n, len(rows), slug, len(text), len(old))
                continue
            if not args.dry_run:
                with write_lock:
                    cur = conn.execute(
                        "UPDATE articles SET body = ? WHERE slug = ?", (text, slug)
                    )
                    conn.commit()
                    if cur.rowcount != 1:
                        log.warning("unexpected rowcount %s for %s", cur.rowcount, slug)
            stats["repaired"] += 1
            repaired.append({"slug": slug, "old_len": len(old), "new_len": len(text)})
            log.info("[%d/%d] REPAIRED %s %d -> %d", n, len(rows), slug, len(old), len(text))

    conn.close()
    report = {
        "timestamp": TS,
        "db": str(DB),
        "dry_run": args.dry_run,
        "candidates": len(rows),
        **stats,
        "repaired_rows": repaired,
        "failures": failures,
    }
    REPORT.write_text(json.dumps(report, indent=2))
    log.info("DONE %s report=%s", stats, REPORT)
    return 0


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