---
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. Fixed version: uses v1 endpoint, 'square' size, correct response parsing.\"\"\" import json import os import sqlite3."
resource: "https://uk.copecheck.com"
tags: ["copecheck", "uk", "source-file", "py"]
timestamp: "2026-04-25T08:07:20Z"
site: "uk"
source_path: "copecheck-uk/generate_uk_portraits_v2.py"
---

# !/usr/bin/env python3

Source path: `copecheck-uk/generate_uk_portraits_v2.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-04-25T08:07:20Z`

```py
#!/usr/bin/env python3
"""Generate AI portrait images for all UK CopeCheck figures via Straico API.
Fixed version: uses v1 endpoint, 'square' size, correct response parsing."""

import json
import os
import sqlite3
import sys
import time
import requests

[redacted secret-like line]
STRAICO_URL = "https://api.straico.com/v1/image/generation"
PHOTOS_DIR = os.path.expanduser("~/infra/copecheck-uk/static/photos")
DB_PATH = os.path.expanduser("~/infra/copecheck-uk/data/copecheck_uk.db")
MODEL = "openai/dall-e-3"

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


def generate_portrait(figure):
    """Generate a portrait for a single figure via Straico API."""
    name = figure["name"]
    role = figure["role"]
    fig_id = figure["id"]
    outfile = os.path.join(PHOTOS_DIR, f"{fig_id}.png")

    if os.path.exists(outfile) and os.path.getsize(outfile) > 10000 and "--force" not in sys.argv:
        print(f"  SKIP {fig_id} (already exists, {os.path.getsize(outfile)//1024}KB)")
        return "skip"

    prompt = (
        f"Dark, stylised editorial portrait illustration of {name}, {role}. "
        f"Dramatic chiaroscuro lighting, deep black background, slightly desaturated colors. "
        f"Sharp-focused face with intense expression. Modern digital art style with painterly textures. "
        f"Professional headshot composition, shoulders and head visible. "
        f"High contrast, moody atmosphere, editorial magazine quality."
    )

    print(f"  Generating portrait for {name}...")
    try:
        resp = requests.post(
            STRAICO_URL,
            headers={
[redacted secret-like line]
                "Content-Type": "application/json",
            },
            json={
                "model": MODEL,
                "description": prompt,
                "size": "square",
                "variations": 1,
            },
            timeout=120,
        )
        if resp.status_code not in (200, 201):
            print(f"  ERROR: API returned {resp.status_code}: {resp.text[:300]}")
            return "fail"

        data = resp.json()
        images = data.get("data", {}).get("images", [])
        if not images:
            print(f"  ERROR: No images in response: {json.dumps(data)[:300]}")
            return "fail"

        image_url = images[0]
        coins = data.get("data", {}).get("price", {}).get("total", "?")
        print(f"  Downloading image ({coins} coins)...")

        img_resp = requests.get(image_url, timeout=60)
        if img_resp.status_code == 200:
            with open(outfile, "wb") as f:
                f.write(img_resp.content)
            print(f"  OK: {outfile} ({len(img_resp.content)//1024}KB)")
            return "ok"
        else:
            print(f"  ERROR: Download failed {img_resp.status_code}")
            return "fail"
    except Exception as e:
        print(f"  ERROR: {e}")
        return "fail"


def update_db():
    """Update photo_url in the database for all figures."""
    conn = sqlite3.connect(DB_PATH)
    c = conn.cursor()
    updated = 0
    for fig in FIGURES:
        photo_path = f"/static/photos/{fig['id']}.png"
        full_path = os.path.join(PHOTOS_DIR, f"{fig['id']}.png")
        if os.path.exists(full_path) and os.path.getsize(full_path) > 10000:
            c.execute("UPDATE figures SET photo_url = ? WHERE id = ?", (photo_path, fig["id"]))
            updated += 1
    conn.commit()
    conn.close()
    print(f"\nUpdated {updated} photo_url entries in database")


def main():
    # Parse batch argument: --batch 1-3 means figures index 0,1,2
    batch_start = 0
    batch_end = len(FIGURES)
    for i, arg in enumerate(sys.argv):
        if arg == "--batch" and i + 1 < len(sys.argv):
            parts = sys.argv[i + 1].split("-")
            batch_start = int(parts[0]) - 1
            batch_end = int(parts[1]) if len(parts) > 1 else batch_start + 1
        if arg == "--update-db":
            update_db()
            return

    os.makedirs(PHOTOS_DIR, exist_ok=True)
    figures_batch = FIGURES[batch_start:batch_end]
    print(f"Processing {len(figures_batch)} figures (batch {batch_start+1}-{batch_end}) using {MODEL}...")

    results = {"ok": [], "fail": [], "skip": []}
    for i, fig in enumerate(figures_batch):
        print(f"\n[{batch_start+i+1}/{len(FIGURES)}] {fig['name']} ({fig['role']})")
        status = generate_portrait(fig)
        results[status].append(fig["id"])
        if status != "skip" and i < len(figures_batch) - 1:
            print("  Waiting 5s...")
            time.sleep(5)

    print(f"\n{'='*60}")
    print(f"RESULTS: {len(results['ok'])} ok, {len(results['fail'])} fail, {len(results['skip'])} skip")
    if results["ok"]:
        print(f"  OK:   {', '.join(results['ok'])}")
    if results["fail"]:
        print(f"  FAIL: {', '.join(results['fail'])}")
    if results["skip"]:
        print(f"  SKIP: {', '.join(results['skip'])}")
    print(f"{'='*60}")


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