Files
f1-circuits/tools/commons_candidates.py
T
jschoubben ab9e141cdf Add a tool that lists the Commons photos a poster may use
The posters take an aerial photo per layout and a car photo per season only from Wikimedia
Commons files under CC0, public domain, CC BY or CC BY-SA (docs/posters.md, "Picking photos").
The tool reads each file's licence, author, credit, date and quality marks from the API, keeps
only aerial photos dated within a layout's years, ranks quality marks, size and landscape first,
and keeps Commons' rules: a descriptive User-Agent, one request at a time, at most five a second.

Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh
2026-11-27 14:57:55 +01:00

489 lines
23 KiB
Python

#!/usr/bin/env python3
"""Lists Wikimedia Commons photos the posters may use, for the picker page to show (docs/posters.md, "Picking photos").
For every layout in circuits/circuits.json: aerial photos of its circuit, dated within the layout's years. For every
season 1950-2026: the photos in "<year> Formula One season cars". Only CC0, public domain, CC BY and CC BY-SA; each
file's licence, author, credit, date and quality marks are read from the Action API's imageinfo extmetadata, 50
files a call. Commons' quality marks rank first, then size, then landscape.
It writes examples/data/candidates.json:
{"about": {...},
"layouts": {"<country>/<city>/<circuit>/<layout>": [candidate, ...]},
"seasons": {"<year>": [candidate, ...]}}
A search hit counts as an aerial photo only when its title or a category says so, or two search words found it: a
word in its description alone matched hundreds of race photos taken from the ground. A candidate holds the fields of a
pick (file, licence, author, credit, date) and what the picker shows beside them (thumb, page, width, height, marks,
restrictions, found). A layout's key is its path under circuits/ without an extension, the key circuits/photos.json
uses; a season's is its year.
Commons' rules, kept here: a descriptive User-Agent with the app's address and no person's; one API request at a
time and at most five a second (a request starts at least REQUEST_GAP after the one before); a 429 or a maxlag
answer waits its Retry-After; no image is downloaded, only thumbnail addresses written for the page. A call that
still fails after its retries stops the run, and nothing is written: a partial list is never kept.
Standard library only. Run from the repository root:
python3 tools/commons_candidates.py # every layout and season, writes the file
python3 tools/commons_candidates.py --only belgium/spa --seasons 2018-2019 --out - # a part, to stdout
"""
from __future__ import annotations
import argparse
import datetime as dt
import html
import json
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
CIRCUITS = ROOT / "circuits" / "circuits.json"
OUT = ROOT / "examples" / "data" / "candidates.json"
USER_AGENT = "f1-circuits-picker/1.0 (+https://f1-circuits.zurag.be)"
COMMONS = "https://commons.wikimedia.org/w/api.php"
WIKIDATA = "https://www.wikidata.org/w/api.php"
ENWIKI = "https://en.wikipedia.org/w/api.php"
REQUEST_GAP = 0.25 # seconds between request starts: at most four a second, under Commons' five
RETRIES = 4
THUMB_WIDTH = 500 # one of Commons' standard thumbnail widths
FIRST_SEASON, LAST_SEASON = 1950, 2026
THIS_YEAR = dt.date.today().year
# One word per query: an OR matched unrelated files worldwide (the licence research, 11.1).
# "SkySat" is read in titles only: as a word it stems to "sky" and matches race photos.
AERIAL_WORDS = ["aerial", "luchtfoto", "Luftbild", "aérienne", "aerea", "drone", "intitle:SkySat"]
MARKED = "incategory:Quality_images|Featured_pictures_on_Wikimedia_Commons|Valued_images_sorted_by_promotion_date"
MARK_WEIGHT = {"poty": 5, "potd": 4, "featured": 3, "valued": 2, "quality": 1}
# A search word may sit in a file's description only ("aérienne" alone matched hundreds of race photos taken from
# the ground), so a search hit counts as aerial when its title or a category says so, or two words found it.
AERIAL_SAYS = re.compile(
r"aerial|luchtfoto|luchtopname|overzicht|luftbild|luftaufnahme|a[ée]rienne|a[ée]re[ao]|drone|\bdji\b|skysat|satellite|"
r"bird.?s.?eye|vogelvlucht|from above|from the air|from (an )?(aircraft|airplane|plane|helicopter)|orthophoto|overview",
re.I)
PHOTO_MIME = {"image/jpeg", "image/tiff", "image/webp"} # maps and drawings come as SVG, PNG or GIF
NOT_A_PHOTO = re.compile(r"\bmaps?\b|\bdiagrams?\b|\blogos?\b|\bplans?\b|\bschemes?\b", re.I)
SEASON_KEEP = 40 # the best of a season's hundreds of files
LAYOUT_KEEP = 40
EXTMETA = ("LicenseShortName|License|LicenseUrl|UsageTerms|Artist|Credit|Attribution|AttributionRequired|"
"Restrictions|DateTimeOriginal|Assessments|Categories")
# The licences a pick may carry, by Commons' machine-readable code (extmetadata License).
FREE = re.compile(r"^(cc0|pd([-a-z0-9]*)?|cc-by-\d[\d.,]*([-a-z]+)?|cc-by-sa-\d[\d.,]*([-a-z]+)?)$", re.I)
class Fetcher:
"""One request at a time, paced, retried; the only way this tool reaches Wikimedia."""
def __init__(self) -> None:
self.last = 0.0
self.count = 0
def get(self, endpoint: str, params: dict) -> dict:
params = {"format": "json", "formatversion": "2", "maxlag": "5", **params}
url = endpoint + "?" + urllib.parse.urlencode(params)
wait = 2.0
for attempt in range(RETRIES + 1):
gap = self.last + REQUEST_GAP - time.monotonic()
if gap > 0:
time.sleep(gap)
self.last = time.monotonic()
self.count += 1
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Accept": "application/json"})
try:
with urllib.request.urlopen(req, timeout=90) as res:
body = json.load(res)
except urllib.error.HTTPError as e:
if attempt < RETRIES and (e.code == 429 or e.code >= 500):
time.sleep(_retry_after(e.headers.get("Retry-After"), wait))
wait *= 2
continue
raise SystemExit(f"commons_candidates: HTTP {e.code} for {url}") from e
except (urllib.error.URLError, TimeoutError) as e:
if attempt < RETRIES:
time.sleep(wait)
wait *= 2
continue
raise SystemExit(f"commons_candidates: no answer for {url}: {e}") from e
err = body.get("error")
if err and err.get("code") == "maxlag" and attempt < RETRIES:
time.sleep(max(5.0, wait))
wait *= 2
continue
if err:
raise SystemExit(f"commons_candidates: the API refused {url}: {err.get('code')}: {err.get('info')}")
return body
raise SystemExit(f"commons_candidates: gave up on {url}")
def _retry_after(value: str | None, default: float) -> float:
try:
return max(1.0, float(value))
except (TypeError, ValueError):
return default
# ---------------------------------------------------------------- reading a file's metadata
def plain(value: str) -> str:
"""Text of an extmetadata value: tags removed, entities decoded, whitespace folded."""
text = re.sub(r"<br\s*/?>", " ", value or "", flags=re.I)
text = re.sub(r"<[^>]+>", "", text)
return re.sub(r"\s+", " ", html.unescape(text)).strip()
MONTHS = {m: i for i, m in enumerate(
["january", "february", "march", "april", "may", "june", "july", "august", "september", "october",
"november", "december"], 1)}
MONTH_RE = "(" + "|".join(MONTHS) + ")"
def photo_date(raw: str) -> str | None:
"""When the photo was taken, as YYYY, YYYY-MM or YYYY-MM-DD; None when the value does not say (an upload date,
a decade, a range). Forms seen on Commons are in the licence research, 11.3."""
if not raw:
return None
qs = re.search(r"QS:P\d*,\+(\d{4})-(\d{2})-(\d{2})T[^/]*/(\d+)", raw)
if qs:
year, month, day, precision = qs.group(1), qs.group(2), qs.group(3), int(qs.group(4))
if precision >= 11 and day != "00":
return f"{year}-{month}-{day}"
if precision == 10 and month != "00":
return f"{year}-{month}"
return year if precision == 9 else None
attr = re.search(r'datetime="(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?', raw)
if attr:
return "-".join(p for p in attr.groups() if p)
text = plain(raw).lower()
if "upload" in text or re.search(r"\d{4}s\b", text) or re.search(r"\bbetween\b|\bor\b", text):
return None
m = re.search(r"\b(\d{4})[-:](\d{2})[-:](\d{2})\b", text)
if m and m.group(2) != "00":
return f"{m.group(1)}-{m.group(2)}" + (f"-{m.group(3)}" if m.group(3) != "00" else "")
m = re.search(r"\b(\d{1,2})(?:st|nd|rd|th)? " + MONTH_RE + r",? (\d{4})\b", text)
if m:
return f"{m.group(3)}-{MONTHS[m.group(2)]:02d}-{int(m.group(1)):02d}"
m = re.search(MONTH_RE + r" (\d{1,2}),? (\d{4})\b", text)
if m:
return f"{m.group(3)}-{MONTHS[m.group(1)]:02d}-{int(m.group(2)):02d}"
m = re.search(MONTH_RE + r",? (\d{4})\b", text)
if m:
return f"{m.group(2)}-{MONTHS[m.group(1)]:02d}"
m = re.search(r"\b(\d{4})-(\d{2})\b", text)
if m and 1 <= int(m.group(2)) <= 12:
return f"{m.group(1)}-{m.group(2)}"
years = set(re.findall(r"\b(1[89]\d{2}|20\d{2})\b", text))
if len(years) == 1: # "1983", "circa 1983", "07-06-1954" (day and month order unknown: the year only)
return years.pop()
return None
def licence_code(short: str) -> str:
"""Commons' machine code from a short licence name, for a file whose License field is empty."""
s = short.strip().lower()
if s in ("public domain", "pd"):
return "pd"
if s == "cc0":
return "cc0"
return re.sub(r"\s+", "-", s.replace("cc by", "cc-by"))
def candidate(page: dict, found: str) -> tuple[dict | None, str]:
"""A candidate from one page of an imageinfo answer, or None with the reason it is not one."""
info = (page.get("imageinfo") or [None])[0]
if not info:
return None, "no imageinfo"
meta = {k: (v or {}).get("value", "") for k, v in (info.get("extmetadata") or {}).items()}
if info.get("mime") not in PHOTO_MIME:
return None, f"not a photo ({info.get('mime')})"
short = plain(meta.get("LicenseShortName", ""))
code = plain(meta.get("License", "")) or licence_code(short)
if not FREE.match(code):
return None, f"licence {code or short or 'unknown'}"
title = page["title"].removeprefix("File:")
author = plain(meta.get("Attribution", "")) or plain(meta.get("Artist", "")) or plain(meta.get("Credit", ""))
author = author or "unknown author"
width, height = int(info.get("width") or 0), int(info.get("height") or 0)
marks = [m for m in plain(meta.get("Assessments", "")).split("|") if m]
thumb = (info.get("thumburl") or info.get("url") or "").split("?utm_")[0]
return {
"file": title,
"licence": short or code,
"author": author,
"credit": f"Photo: {author}, {short or code}, via Wikimedia Commons",
"date": photo_date(meta.get("DateTimeOriginal", "")),
"marks": marks,
"width": width,
"height": height,
"thumb": thumb,
"page": info.get("descriptionurl") or f"https://commons.wikimedia.org/wiki/File:{urllib.parse.quote(title)}",
"licence_url": plain(meta.get("LicenseUrl", "")) or None,
"restrictions": [r for r in plain(meta.get("Restrictions", "")).split("|") if r],
"categories": [c for c in plain(meta.get("Categories", "")).split("|") if c],
"found": [found],
}, ""
def rank_key(c: dict) -> tuple:
"""Commons' quality marks first, then size (tall enough for a 1500-px poster), then landscape, then pixels."""
score = sum(MARK_WEIGHT.get(m, 0) for m in c["marks"])
return (-score, -(c["height"] >= 1500), -(c["width"] > c["height"]), -(c["width"] * c["height"]), c["file"])
# ---------------------------------------------------------------- asking Commons
IMAGEINFO = {
"prop": "imageinfo",
"iiprop": "extmetadata|size|url|mime",
"iiurlwidth": str(THUMB_WIDTH),
"iiextmetadatafilter": EXTMETA,
"iiextmetadatalanguage": "en",
}
def pages_of(fetch: Fetcher, params: dict) -> list[dict]:
"""Every page of one generator answer, its imageinfo complete: a heavy batch may be cut, and is then continued."""
body = fetch.get(COMMONS, {"action": "query", **IMAGEINFO, **params})
pages = {p["pageid"]: p for p in body.get("query", {}).get("pages", []) if "pageid" in p}
cont = body.get("continue", {})
while "iicontinue" in cont:
more = fetch.get(COMMONS, {"action": "query", **IMAGEINFO, **params, **cont})
for p in more.get("query", {}).get("pages", []):
if "pageid" in p and p.get("imageinfo"):
pages.setdefault(p["pageid"], p)["imageinfo"] = p["imageinfo"]
cont = more.get("continue", {})
return list(pages.values())
def search(fetch: Fetcher, query: str, pages: int = 1) -> list[dict]:
"""Files matching a CirrusSearch query, in its order, 50 a call, with their metadata."""
out: list[dict] = []
offset = 0
for _ in range(pages):
params = {"generator": "search", "gsrnamespace": "6", "gsrlimit": "50", "gsrsearch": query,
"gsroffset": str(offset)}
body_pages = pages_of(fetch, params)
out.extend(sorted(body_pages, key=lambda p: p.get("index", 0)))
if len(body_pages) < 50:
break
offset += 50
return out
def files(fetch: Fetcher, titles: list[str]) -> list[dict]:
out: list[dict] = []
for i in range(0, len(titles), 50):
out.extend(pages_of(fetch, {"titles": "|".join(f"File:{t}" for t in titles[i:i + 50])}))
return out
def category_files(fetch: Fetcher, category: str) -> list[dict]:
return pages_of(fetch, {"generator": "categorymembers", "gcmtitle": f"Category:{category}",
"gcmtype": "file", "gcmlimit": "50"})
def wikidata(fetch: Fetcher, titles: list[str]) -> dict[str, dict]:
"""For each English Wikipedia title: its Commons category (P373) and its aerial view (P8592). A title is resolved
on Wikipedia first, its redirects followed: a third of circuits.json's links are redirects."""
item: dict[str, str] = {}
for i in range(0, len(titles), 50):
batch = titles[i:i + 50]
body = fetch.get(ENWIKI, {"action": "query", "titles": "|".join(batch), "redirects": "1",
"prop": "pageprops", "ppprop": "wikibase_item"})
q = body.get("query", {})
moved = {n["from"]: n["to"] for n in q.get("normalized", [])}
moved.update({r["from"]: r["to"] for r in q.get("redirects", [])})
found = {p["title"]: (p.get("pageprops") or {}).get("wikibase_item") for p in q.get("pages", [])}
for title in batch:
final, seen = title, set()
while final in moved and final not in seen:
seen.add(final)
final = moved[final]
if found.get(final):
item[title] = found[final]
out: dict[str, dict] = {}
ids = sorted(set(item.values()))
claims_of: dict[str, dict] = {}
for i in range(0, len(ids), 50):
body = fetch.get(WIKIDATA, {"action": "wbgetentities", "ids": "|".join(ids[i:i + 50]), "props": "claims"})
for qid, entity in body.get("entities", {}).items():
claims_of[qid] = entity.get("claims", {})
for title, qid in item.items():
claims = claims_of.get(qid, {})
value = lambda p: [c["mainsnak"]["datavalue"]["value"] for c in claims.get(p, []) # noqa: E731
if c.get("mainsnak", {}).get("datavalue")]
out[title] = {"id": qid, "category": (value("P373") or [None])[0], "aerial": value("P8592")}
return out
# ---------------------------------------------------------------- the circuits and seasons
def layouts(circuits: dict):
"""(circuit key, circuit, [(layout key, first year, last year)]) per circuit, in the file's order."""
for country, cv in circuits.items():
for city, lv in cv["localities"].items():
for slug, circuit in lv["circuits"].items():
rows = []
for layout in circuit["layouts"]:
first, _, last = layout.partition("-")
end = THIS_YEAR if layout.endswith("-") else int(last or first)
rows.append((f"{country}/{city}/{slug}/{layout}", int(first), end))
yield f"{country}/{city}/{slug}", circuit, rows
def wiki_title(circuit: dict) -> str | None:
url = (circuit.get("urls") or {}).get("wikipedia") or ""
if "/wiki/" not in url:
return None
return urllib.parse.unquote(url.split("/wiki/", 1)[1]).split("#")[0].replace("_", " ")
def gather_circuit(fetch: Fetcher, key: str, circuit: dict, wd: dict, skipped: dict) -> list[dict]:
"""Every aerial-photo candidate of one circuit, before the layouts' years are applied."""
found: dict[str, dict] = {}
def take(pages: list[dict], how: str, check_photo: bool = True) -> None:
for page in pages:
c, why = candidate(page, how)
if not c:
skipped[why] = skipped.get(why, 0) + 1
continue
if check_photo and any(NOT_A_PHOTO.search(cat) for cat in c["categories"]):
why = "in a maps, plans or logos category"
skipped[why] = skipped.get(why, 0) + 1
continue
if c["file"] in found:
if how not in found[c["file"]]["found"]:
found[c["file"]]["found"].append(how)
else:
found[c["file"]] = c
entry = wd.get(wiki_title(circuit) or "", {})
if entry.get("aerial"):
take(files(fetch, entry["aerial"]), "Wikidata aerial view (P8592)", check_photo=False)
category = entry.get("category")
if category:
take(category_files(fetch, f"Aerial photographs of {category}"), f"Category:Aerial photographs of {category}")
for word in AERIAL_WORDS:
take(search(fetch, f'deepcat:"{category}" {word}'), f"search: {word}")
else:
for word in AERIAL_WORDS:
take(search(fetch, f'"{circuit["name"]}" {word}'), f"search (no Commons category): {word}")
kept = [c for c in found.values() if says_aerial(c)]
if len(kept) < len(found):
why = "found by one search word only, and no aerial word in its title or categories"
skipped[why] = skipped.get(why, 0) + len(found) - len(kept)
return kept
def says_aerial(c: dict) -> bool:
"""An aerial photo by what Commons says of it: Wikidata's or the category's pick, an aerial word in its title or a
category, or two search words that found it."""
if any(not how.startswith("search") for how in c["found"]):
return True
if AERIAL_SAYS.search(c["file"]) or any(AERIAL_SAYS.search(cat) for cat in c["categories"]):
return True
return len(c["found"]) >= 2
def in_years(c: dict, first: int, last: int) -> bool:
return bool(c["date"]) and first <= int(c["date"][:4]) <= last
def public(c: dict) -> dict:
"""A candidate as the file keeps it: the categories were only for the filter."""
return {k: v for k, v in c.items() if k != "categories"}
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("--only", action="append", default=[],
help="only layouts whose key starts with this (country, country/city, …); may repeat")
ap.add_argument("--seasons", default=f"{FIRST_SEASON}-{LAST_SEASON}",
help="a year, a range such as 2018-2019, or 'none' (default: %(default)s)")
ap.add_argument("--no-layouts", action="store_true", help="list the seasons only")
ap.add_argument("--out", default=str(OUT), help="the file to write, or - for stdout (default: %(default)s)")
args = ap.parse_args()
fetch = Fetcher()
started = dt.datetime.now(dt.timezone.utc)
circuits = json.loads(CIRCUITS.read_text(encoding="utf-8"))
skipped: dict[str, int] = {}
out_layouts: dict[str, list[dict]] = {}
undated: dict[str, int] = {}
chosen = [] if args.no_layouts else [
(k, c, rows) for k, c, rows in layouts(circuits) if not args.only or any(k.startswith(o) for o in args.only)]
wd = wikidata(fetch, sorted({t for _, c, _ in chosen if (t := wiki_title(c))})) if chosen else {}
for n, (key, circuit, rows) in enumerate(chosen, 1):
cands = gather_circuit(fetch, key, circuit, wd, skipped)
undated[key] = sum(1 for c in cands if not c["date"])
for layout_key, first, last in rows:
fits = sorted((c for c in cands if in_years(c, first, last)), key=rank_key)
out_layouts[layout_key] = [public(c) for c in fits[:LAYOUT_KEEP]]
got = sum(1 for k, _, _ in rows if out_layouts[k])
print(f"[{n}/{len(chosen)}] {key}: {len(cands)} licensed photo(s), {undated[key]} undated; "
f"{got} of {len(rows)} layout(s) have a candidate ({fetch.count} requests)", file=sys.stderr)
if args.seasons == "none":
years: list[int] = []
else:
first, _, last = args.seasons.partition("-")
years = list(range(int(first), int(last or first) + 1))
out_seasons: dict[str, list[dict]] = {}
for year in years:
cat = f"{year} Formula One season cars"
found: dict[str, dict] = {}
for query, pages, how in ((f'deepcat:"{cat}" {MARKED}', 1, "marked"), (f'deepcat:"{cat}"', 2, f"Category:{cat}")):
for page in search(fetch, query, pages):
c, why = candidate(page, how)
if not c:
skipped[why] = skipped.get(why, 0) + 1
elif c["file"] not in found:
found[c["file"]] = c
out_seasons[str(year)] = [public(c) for c in sorted(found.values(), key=rank_key)[:SEASON_KEEP]]
print(f"season {year}: {len(found)} licensed photo(s), kept {len(out_seasons[str(year)])} "
f"({fetch.count} requests)", file=sys.stderr)
result = {
"about": {
"made": started.isoformat(timespec="seconds"),
"by": "tools/commons_candidates.py",
"requests": fetch.count,
"layouts": f"aerial photos of the circuit dated within the layout's years, at most {LAYOUT_KEEP} each",
"seasons": f"photos in '<year> Formula One season cars', at most {SEASON_KEEP} each",
"licences": "CC0, public domain, CC BY and CC BY-SA only",
"ranked": "Commons' quality marks, then size (at least 1500 px high), then landscape, then pixels",
"undated_per_circuit": undated,
"skipped": dict(sorted(skipped.items(), key=lambda kv: -kv[1])),
"check": "every candidate is checked by eye before it is picked: a search also finds ground photos and maps",
},
"layouts": out_layouts,
"seasons": out_seasons,
}
text = json.dumps(result, ensure_ascii=False, indent=1) + "\n"
if args.out == "-":
sys.stdout.write(text)
else:
path = Path(args.out)
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(".tmp")
tmp.write_text(text, encoding="utf-8")
tmp.replace(path)
with_l = sum(1 for v in out_layouts.values() if v)
with_s = sum(1 for v in out_seasons.values() if v)
print(f"{with_l} of {len(out_layouts)} layouts and {with_s} of {len(out_seasons)} seasons have a candidate; "
f"{len(out_layouts) - with_l} layouts have none ({fetch.count} requests)", file=sys.stderr)
return 0
if __name__ == "__main__":
sys.exit(main())