---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\"Monthly update script for EU CopeCheck — fetches Eurostat data and re-scores all countries. Usage: python3 monthly_update.py # Fetch data + re-score all python3 monthly_update.py --fetch-only."
resource: "https://eu.copecheck.com"
tags: ["copecheck", "eu", "source-file", "py"]
timestamp: "2026-05-08T08:02:14Z"
site: "eu"
source_path: "copecheck-eu/monthly_update.py"
---

# !/usr/bin/env python3

Source path: `copecheck-eu/monthly_update.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-05-08T08:02:14Z`

```py
#!/usr/bin/env python3
"""Monthly update script for EU CopeCheck — fetches Eurostat data and re-scores all countries.

Usage:
    python3 monthly_update.py              # Fetch data + re-score all
    python3 monthly_update.py --fetch-only # Only fetch data, no re-scoring
    python3 monthly_update.py --score-only # Only re-score (using existing data)
"""
import os
import sys
import time
import logging
import argparse

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

import db
import scorer
import eu_data_fetcher

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s [%(name)s] %(message)s",
    handlers=[
        logging.StreamHandler(),
        logging.FileHandler(os.path.join(os.path.dirname(os.path.abspath(__file__)), "monthly_update.log"))
    ]
)
log = logging.getLogger("monthly_update")


def fetch_data():
    """Fetch all Eurostat data."""
    log.info("=" * 60)
    log.info("PHASE 1: Fetching Eurostat data")
    log.info("=" * 60)
    total = eu_data_fetcher.fetch_all()
    log.info("Fetched %d total records from Eurostat", total)
    return total


def rescore_all_countries():
    """Re-score all 27 EU countries using live Eurostat data."""
    log.info("=" * 60)
    log.info("PHASE 2: Re-scoring all EU countries with live data")
    log.info("=" * 60)

    # Archive current scores before re-scoring
    db.archive_current_scores()
    log.info("Archived current scores to history")

    countries = db.get_all_countries(order_by="id ASC")
    scored = 0
    failed = 0

    for i, country in enumerate(countries, 1):
        code = country['code']
        name = country['name']
        log.info("[%d/%d] Scoring %s (%s)...", i, len(countries), name, code)

        # Get Eurostat summary for this country
        eurostat_summary = eu_data_fetcher.get_country_summary(code)
        log.info("  Eurostat data: %d lines", len(eurostat_summary.split('\n')))

        try:
            result = scorer.score_country(country, eurostat_data=eurostat_summary)
            if result:
                db.update_country_scores(country['id'], result)
                log.info("  Scored: cope=%s, screwed=%s (model: %s)",
                         result.get('overall_score', '?'), result.get('screwed_score', '?'),
                         result.get('ai_model', '?'))
                scored += 1
            else:
                log.warning("  FAILED: No result returned")
                failed += 1
        except Exception as e:
            log.exception("  FAILED: %s", e)
            failed += 1

        # Rate limit between API calls
        if i < len(countries):
            time.sleep(3)

    log.info("=" * 60)
    log.info("Scoring complete: %d scored, %d failed", scored, failed)
    log.info("=" * 60)
    return scored, failed


def main():
    parser = argparse.ArgumentParser(description="EU CopeCheck monthly update")
    parser.add_argument("--fetch-only", action="store_true", help="Only fetch Eurostat data")
    parser.add_argument("--score-only", action="store_true", help="Only re-score countries")
    args = parser.parse_args()

    db.init_db()

    if args.fetch_only:
        fetch_data()
    elif args.score_only:
        rescore_all_countries()
    else:
        fetch_data()
        log.info("Waiting 5s before re-scoring...")
        time.sleep(5)
        rescore_all_countries()

    log.info("Monthly update complete!")


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