---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\"Generate AI portrait images for all UK CopeCheck figures via Straico API.\"\"\" import json import os import sys import time import requests [redacted secret-like line] PHOTOS_DIR =."
resource: "https://uk.copecheck.com"
tags: ["copecheck", "uk", "source-file", "py"]
timestamp: "2026-04-25T07:45:08Z"
site: "uk"
source_path: "copecheck-uk/generate_uk_portraits.py"
---

# !/usr/bin/env python3

Source path: `copecheck-uk/generate_uk_portraits.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-04-25T07:45:08Z`

```py
#!/usr/bin/env python3
"""Generate AI portrait images for all UK CopeCheck figures via Straico API."""

import json
import os
import sys
import time
import requests

[redacted secret-like line]
PHOTOS_DIR = os.path.expanduser("~/infra/copecheck-uk/static/photos")

FIGURES = [
    {"id": "starmer",       "name": "Keir Starmer",        "role": "Prime Minister",              "party": "Labour",         "type": "politician"},
    {"id": "farage",        "name": "Nigel Farage",         "role": "Leader of Reform UK",         "party": "Reform UK",      "type": "politician"},
    {"id": "badenoch",      "name": "Kemi Badenoch",        "role": "Leader of the Opposition",    "party": "Conservative",   "type": "politician"},
    {"id": "reeves",        "name": "Rachel Reeves",        "role": "Chancellor of the Exchequer", "party": "Labour",         "type": "politician"},
[redacted secret-like line]
    {"id": "davey",         "name": "Ed Davey",             "role": "Leader of the Liberal Democrats", "party": "Liberal Democrats", "type": "politician"},
    {"id": "tice",          "name": "Richard Tice",         "role": "Deputy Leader of Reform UK",  "party": "Reform UK",      "type": "politician"},
    {"id": "jenrick",       "name": "Robert Jenrick",       "role": "Reform UK Shadow Chancellor", "party": "Reform UK",      "type": "politician"},
    {"id": "swinney",       "name": "John Swinney",         "role": "First Minister of Scotland",  "party": "SNP",            "type": "politician"},
    {"id": "ap_iorwerth",   "name": "Rhun ap Iorwerth",     "role": "Leader of Plaid Cymru",       "party": "Plaid Cymru",    "type": "politician"},
    {"id": "polanski",      "name": "Zack Polanski",        "role": "Leader of the Green Party",   "party": "Green Party",    "type": "politician"},
    {"id": "dyson",         "name": "James Dyson",          "role": "Founder of Dyson",            "party": "",               "type": "business"},
    {"id": "ratcliffe",     "name": "Jim Ratcliffe",        "role": "Founder and Chairman of INEOS", "party": "",             "type": "business"},
    {"id": "newton_smith",  "name": "Rain Newton-Smith",    "role": "Chief Executive of CBI",      "party": "",               "type": "business"},
    {"id": "martin",        "name": "Tim Martin",           "role": "Founder and Chairman of JD Wetherspoon", "party": "",    "type": "business"},
    {"id": "sunak",         "name": "Rishi Sunak",          "role": "Former Prime Minister",       "party": "Conservative",   "type": "politician"},
    {"id": "corbyn",        "name": "Jeremy Corbyn",        "role": "Independent MP",              "party": "Independent",    "type": "politician"},
]

def generate_portrait(figure):
    """Generate a portrait for a single figure via Straico API."""
    name = figure["name"]
    role = figure["role"]
    fig_type = "politician" if figure["type"] == "politician" else "business figure"
    party = figure.get("party", "")

    description = f"UK {fig_type}"
    if party:
        description += f", {party}"

    prompt = (
        f"Professional editorial portrait illustration of {name}, {role}. "
        f"Dark moody background, dramatic lighting, political figure style. "
        f"Semi-realistic digital art, dark navy and red color accent. {description}"
    )

    print(f"  Generating portrait for {name}...")
    print(f"  Prompt: {prompt[:100]}...")

    try:
        resp = requests.post(
            "https://api.straico.com/v0/image/generation",
            headers={
[redacted secret-like line]
                "Content-Type": "application/json",
            },
            json={
                "model": "openai/dall-e-3",
                "description": prompt,
                "size": "1024x1024",
                "variations": 1,
            },
            timeout=120,
        )
        resp.raise_for_status()
        data = resp.json()
        images = data.get("data", [])
        if images:
            img = images[0]
            if isinstance(img, str):
                return img
            elif isinstance(img, dict):
                return img.get("url") or img.get("image")
        print(f"  WARNING: No images returned for {name}")
        print(f"  Response: {json.dumps(data)[:500]}")
        return None
    except Exception as e:
        print(f"  ERROR generating portrait for {name}: {e}")
        return None


def download_image(url, save_path):
    """Download an image from URL to local path."""
    try:
        resp = requests.get(url, timeout=30)
        resp.raise_for_status()
        with open(save_path, "wb") as f:
            f.write(resp.content)
        size_kb = os.path.getsize(save_path) / 1024
        print(f"  Saved: {save_path} ({size_kb:.0f} KB)")
        return True
    except Exception as e:
        print(f"  ERROR downloading image: {e}")
        return False


def main():
    os.makedirs(PHOTOS_DIR, exist_ok=True)

    # Check which figures already have portraits
    existing = set()
    for f in os.listdir(PHOTOS_DIR):
        if f.endswith(".png"):
            existing.add(f.replace(".png", ""))

    results = {"success": [], "failed": [], "skipped": []}

    for i, fig in enumerate(FIGURES, 1):
        fig_id = fig["id"]
        save_path = os.path.join(PHOTOS_DIR, f"{fig_id}.png")

        if fig_id in existing and "--force" not in sys.argv:
            print(f"[{i}/17] SKIP {fig['name']} (already exists)")
            results["skipped"].append(fig_id)
            continue

        print(f"\n[{i}/17] {fig['name']} ({fig['role']})")

        image_url = generate_portrait(fig)
        if not image_url:
            results["failed"].append(fig_id)
            continue

        if download_image(image_url, save_path):
            results["success"].append(fig_id)
        else:
            results["failed"].append(fig_id)

        # Rate limiting - wait between API calls
        if i < len(FIGURES):
            print("  Waiting 3s before next request...")
            time.sleep(3)

    print("\n" + "=" * 60)
    print(f"RESULTS: {len(results['success'])} success, {len(results['failed'])} failed, {len(results['skipped'])} skipped")
    if results["success"]:
        print(f"  Success: {', '.join(results['success'])}")
    if results["failed"]:
        print(f"  Failed:  {', '.join(results['failed'])}")
    if results["skipped"]:
        print(f"  Skipped: {', '.join(results['skipped'])}")
    print("=" * 60)


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