New adapter wikimedia.images: Wikidata P18 for people without an official photo, P154 logos for parties and organisations matched by Wikidata id, Firmenbuch (P5285) or ZVR number (P6279). Licence data from the Commons file page goes into image_credit (keyed by image URL); official Parliament/EP photos are never replaced. Web: logos on party cards, party, organisation and organisation-list pages, credit lines under portraits and logos, image proxy allows upload.wikimedia.org. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
176 lines
8.1 KiB
Python
176 lines
8.1 KiB
Python
"""Portraits and logos from Wikimedia Commons, found through Wikidata.
|
|
|
|
Persons: Wikidata P18 (image) for everyone with a Wikidata id and no official photo (Parliament and European
|
|
Parliament photos always take precedence; the loader never replaces them).
|
|
Organizations: Wikidata P154 (logo image), matched through the Wikidata id, the Firmenbuch number (P5285) or the
|
|
ZVR number (P6279). Matching is by identifier only, never by name.
|
|
|
|
Every image comes with its author and licence from the Commons file page (extmetadata); the site shows that credit
|
|
next to the image. Commons only hosts freely licensed files; logos can still be protected trademarks, which is fine
|
|
for identifying the organization.
|
|
|
|
Flow: SPARQL (Wikidata ids -> file names) -> Commons API imageinfo in batches of 50 (thumbnail URL + licence).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import re
|
|
from collections.abc import Iterator
|
|
from typing import Any
|
|
from urllib.parse import unquote
|
|
|
|
from psycopg import Connection
|
|
|
|
from politrack.core import Adapter, Request, Response, RunContext, SourceSpec, register
|
|
from politrack.core.records import Image, OrgRef, PersonRef
|
|
from politrack.sources.wikidata import SPARQL, sparql
|
|
from politrack.text import html_to_text
|
|
|
|
COMMONS_API = "https://commons.wikimedia.org/w/api.php"
|
|
THUMB_WIDTH = 330 # one of Wikimedia's standard thumbnail steps (cached at the edge)
|
|
BATCH = 300
|
|
FILE_BATCH = 50
|
|
|
|
SPEC = SourceSpec(
|
|
slug="wikimedia-commons",
|
|
name="Wikimedia Commons (Porträts und Logos)",
|
|
kind="aggregator",
|
|
homepage="https://commons.wikimedia.org",
|
|
license="Freie Lizenzen je Datei (CC BY, CC BY-SA, gemeinfrei); Urheber und Lizenz werden angezeigt",
|
|
access="api",
|
|
trust=60,
|
|
min_interval=1.0,
|
|
robots_exempt=(SPARQL, COMMONS_API),
|
|
tos_notes="Wikidata SPARQL and the Commons MediaWiki API with a descriptive User-Agent, sequential requests "
|
|
"(API etiquette; robots.txt disallows /w/ for crawlers, not API clients). Images are shown through the "
|
|
"site's image proxy with author and licence of each file.",
|
|
)
|
|
|
|
PERSON_QUERY = """
|
|
SELECT ?item ?img WHERE { VALUES ?item { %(items)s } ?item wdt:P18 ?img . }
|
|
"""
|
|
ORG_QUERY = """
|
|
SELECT ?item ?img WHERE { VALUES ?item { %(items)s } ?item wdt:P154 ?img . }
|
|
"""
|
|
# Logos of all items with an Austrian register number; the loader keeps those whose number we know.
|
|
REGISTER_QUERY = """
|
|
SELECT ?item ?id ?img WHERE { ?item wdt:%(prop)s ?id ; wdt:P154 ?img . }
|
|
"""
|
|
REGISTERS = {"firmenbuch": "P5285", "zvr": "P6279"}
|
|
|
|
|
|
def register_id(scheme: str, value: str) -> str | None:
|
|
"""Wikidata's register number in our identifier format: Firmenbuch '520909 v' / 'FN 58358x' -> '520909v',
|
|
ZVR digits only."""
|
|
value = value.strip().lower()
|
|
if scheme == "firmenbuch":
|
|
value = re.sub(r"^fn\s*", "", value).replace(" ", "")
|
|
return value.lstrip("0") if re.fullmatch(r"\d+[a-z]", value) else None
|
|
value = re.sub(r"\D", "", value)
|
|
return value.lstrip("0") or None
|
|
|
|
|
|
def file_title(commons_url: str) -> str:
|
|
"""http://commons.wikimedia.org/wiki/Special:FilePath/Foo%20bar.jpg -> 'File:Foo bar.jpg'"""
|
|
name = unquote(commons_url.rsplit("/", 1)[-1]).replace("_", " ")
|
|
return f"File:{name}"
|
|
|
|
|
|
def item_qid(binding: dict) -> str:
|
|
return binding["item"]["value"].rsplit("/", 1)[-1]
|
|
|
|
|
|
def wikidata_ids(conn: Connection, entity_type: str, where: str) -> list[str]:
|
|
rows = conn.execute(
|
|
f"""SELECT DISTINCT i.value FROM identifier i WHERE i.entity_type = %s AND i.scheme = 'wikidata'
|
|
AND i.value ~ '^Q[0-9]+$' AND {where} ORDER BY i.value""", (entity_type,)).fetchall()
|
|
return [r["value"] for r in rows]
|
|
|
|
|
|
def plain(meta: dict, key: str, limit: int = 200) -> str | None:
|
|
value = html_to_text((meta.get(key) or {}).get("value") or "").strip()
|
|
return value[:limit] if value else None
|
|
|
|
|
|
@register
|
|
class CommonsImages(Adapter):
|
|
spec = SPEC
|
|
name = "wikimedia.images"
|
|
description = "Portraits (Wikidata P18) and logos (P154) from Wikimedia Commons, with author and licence"
|
|
schedule = "30 5 * * 0"
|
|
queue = "scrape"
|
|
|
|
def start(self, ctx: RunContext) -> Iterator[Request]:
|
|
if ctx.conn is None:
|
|
return
|
|
persons = wikidata_ids(ctx.conn, "person", """EXISTS (SELECT 1 FROM person p WHERE p.id = i.entity_id
|
|
AND (p.photo_url IS NULL OR p.photo_url LIKE 'https://upload.wikimedia.org/%%'))""")
|
|
orgs = wikidata_ids(ctx.conn, "organization", "TRUE")
|
|
ctx.stats["persons_checked"], ctx.stats["orgs_checked"] = len(persons), len(orgs)
|
|
for i in range(0, len(persons), BATCH):
|
|
items = " ".join(f"wd:{q}" for q in persons[i:i + BATCH])
|
|
yield sparql(PERSON_QUERY % {"items": items}, kind="person_images")
|
|
for i in range(0, len(orgs), BATCH):
|
|
items = " ".join(f"wd:{q}" for q in orgs[i:i + BATCH])
|
|
yield sparql(ORG_QUERY % {"items": items}, kind="org_logos")
|
|
for scheme, prop in REGISTERS.items():
|
|
yield sparql(REGISTER_QUERY % {"prop": prop}, kind="register_logos", meta={"scheme": scheme})
|
|
|
|
def parse(self, ctx: RunContext, response: Response) -> Iterator[Any]:
|
|
kind = response.request.kind
|
|
if kind == "files":
|
|
yield from self.parse_files(ctx, response)
|
|
return
|
|
bindings = json.loads(response.text, strict=False)["results"]["bindings"]
|
|
targets: dict[str, list[dict]] = {}
|
|
seen: set[str] = set()
|
|
for b in sorted(bindings, key=lambda b: (item_qid(b), b["img"]["value"])):
|
|
qid = item_qid(b)
|
|
if qid in seen: # several images: the first one (stable order)
|
|
continue
|
|
seen.add(qid)
|
|
if kind == "person_images":
|
|
target = {"role": "photo", "ids": {"wikidata": qid}}
|
|
elif kind == "org_logos":
|
|
target = {"role": "logo", "ids": {"wikidata": qid}}
|
|
else:
|
|
scheme = response.meta["scheme"]
|
|
value = register_id(scheme, b["id"]["value"])
|
|
if not value:
|
|
continue
|
|
target = {"role": "logo", "ids": {scheme: value, "wikidata": qid}}
|
|
targets.setdefault(file_title(b["img"]["value"]), []).append(target)
|
|
titles = sorted(targets)
|
|
for i in range(0, len(titles), FILE_BATCH):
|
|
chunk = titles[i:i + FILE_BATCH]
|
|
yield Request(
|
|
url=COMMONS_API, kind="files", conditional=False,
|
|
params={"action": "query", "prop": "imageinfo", "iiprop": "url|extmetadata",
|
|
"iiurlwidth": THUMB_WIDTH, "iiextmetadatafilter": "Artist|Credit|LicenseShortName|LicenseUrl",
|
|
"titles": "|".join(chunk), "format": "json", "formatversion": 2},
|
|
meta={"targets": {t: targets[t] for t in chunk}},
|
|
)
|
|
|
|
def parse_files(self, ctx: RunContext, response: Response) -> Iterator[Image]:
|
|
query = response.json().get("query") or {}
|
|
renamed = {n["to"]: n["from"] for n in query.get("normalized") or []}
|
|
targets = response.meta.get("targets") or {}
|
|
for page in query.get("pages") or []:
|
|
info = (page.get("imageinfo") or [None])[0]
|
|
wanted = targets.get(renamed.get(page.get("title"), page.get("title")))
|
|
if not info or not wanted:
|
|
ctx.stats["files_missing"] += 1
|
|
continue
|
|
url = info.get("thumburl") or info.get("url")
|
|
if not url or not url.startswith("https://upload.wikimedia.org/"):
|
|
continue
|
|
meta = info.get("extmetadata") or {}
|
|
credit = plain(meta, "Artist") or plain(meta, "Credit")
|
|
for target in wanted:
|
|
person = PersonRef(ids=target["ids"]) if target["role"] == "photo" else None
|
|
org = OrgRef(ids=target["ids"], create=False) if target["role"] == "logo" else None
|
|
yield Image(url=url, role=target["role"], page_url=info.get("descriptionurl"), credit=credit,
|
|
license=plain(meta, "LicenseShortName", 80), license_url=plain(meta, "LicenseUrl", 300),
|
|
person=person, org=org)
|