---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\"Monthly rescore: archive current scores then rescore all countries via MiniMax.\"\"\" import sys import os import time import json import re import requests from datetime import datetime from."
resource: "https://countries.copecheck.com"
tags: ["copecheck", "countries", "source-file", "py"]
timestamp: "2026-04-29T14:49:51Z"
site: "countries"
source_path: "copecheck-countries/monthly_rescore.py"
---

# !/usr/bin/env python3

Source path: `copecheck-countries/monthly_rescore.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-04-29T14:49:51Z`

```py
#!/usr/bin/env python3
"""Monthly rescore: archive current scores then rescore all countries via MiniMax."""

import sys
import os
import time
import json
import re
import requests
from datetime import datetime
from dotenv import load_dotenv

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
load_dotenv(os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env'))

from db import init_db, init_history, archive_current_scores, get_leaderboard, upsert_country

[redacted secret-like line]
MINIMAX_URL = 'https://api.minimax.io/v1/chat/completions'
MINIMAX_MODEL = 'minimax-m2.7'


def score_one(country):
    """Score a single country with MiniMax."""
    prompt = f"""You are the Countries CopeCheck Oracle. Score "{country['name']}" on AI/automation cope.

Current leader: {country.get('leader_name', 'Unknown')} ({country.get('leader_title', 'Leader')})
Economy type: {country.get('economy_type', 'Mixed')}
Key sectors: {country.get('key_sectors', 'Various')}

Score these dimensions (0-100 each, higher = worse):
1. PREPAREDNESS (how unprepared for AI displacement)
2. LEADER COPE (denial/deflection level)
3. EXPOSURE (economic vulnerability to automation)
4. SCREWED SCORE (how objectively screwed regardless of preparation)
5. OVERALL COPE = (preparedness*0.35 + leader_cope*0.30 + exposure*0.35)

Return ONLY valid JSON:
{{
    "preparedness_score": number,
    "leader_cope_score": number,
    "exposure_score": number,
    "screwed_score": number,
    "overall_score": number,
    "description": "1-2 sardonic sentences",
    "leader_name": "name",
    "leader_title": "title",
    "leader_quotes": ["quote1", "quote2"],
    "policy_summary": "2-3 sentences on actual AI policy",
    "key_sectors": "comma,separated",
    "economy_type": "type"
}}"""

    resp = requests.post(
        MINIMAX_URL,
        headers={
[redacted secret-like line]
            'Content-Type': 'application/json'
        },
        json={
            'model': MINIMAX_MODEL,
            'messages': [{'role': 'user', 'content': prompt}],
            'temperature': 0.7,
[redacted secret-like line]
        },
        timeout=60
    )
    resp.raise_for_status()
    data = resp.json()
    content = data['choices'][0]['message']['content']
    # Strip think tags
    content = re.sub(r'<think>.*?</think>', '', content, flags=re.DOTALL).strip()
    # Extract JSON
    match = re.search(r'\{[\s\S]*\}', content)
    if not match:
        raise ValueError(f"No JSON in response for {country['name']}")
    return json.loads(match.group())


def main():
[redacted secret-like line]
[redacted secret-like line]
        sys.exit(1)

    init_db()
    init_history()

    # Archive current scores
    month = datetime.utcnow().strftime('%Y-%m')
    n = archive_current_scores(month)
    print(f"Archived {n} countries for {month}")

    # Get all system countries and rescore
    countries = get_leaderboard()
    print(f"\nRescoring {len(countries)} countries...")

    success = 0
    failed = []
    for c in countries:
        try:
            print(f"  Scoring {c['name']}...", end=' ', flush=True)
            result = score_one(c)

            # Update the country with new scores
            update = {
                'name': c['name'],
                'code': c.get('code'),
                'flag': c.get('flag'),
                'leader_name': result.get('leader_name', c.get('leader_name')),
                'leader_title': result.get('leader_title', c.get('leader_title')),
                'economy_type': result.get('economy_type', c.get('economy_type')),
                'gdp_usd': c.get('gdp_usd'),
                'key_sectors': result.get('key_sectors', c.get('key_sectors')),
                'description': result.get('description', c.get('description')),
                'preparedness_score': result['preparedness_score'],
                'leader_cope_score': result['leader_cope_score'],
                'exposure_score': result['exposure_score'],
                'overall_score': result['overall_score'],
                'screwed_score': result['screwed_score'],
                'leader_quotes': result.get('leader_quotes', []),
                'policy_summary': result.get('policy_summary', c.get('policy_summary')),
                'submitted_by': 'system'
            }
            upsert_country(update)
            print(f"overall={result['overall_score']}, screwed={result['screwed_score']}")
            success += 1
            time.sleep(1)  # rate limit courtesy
        except Exception as e:
            print(f"FAILED: {e}")
            failed.append(c['name'])

    print(f"\nDone: {success} scored, {len(failed)} failed")
    if failed:
        print(f"Failed: {', '.join(failed)}")


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