images: portraits and logos from Wikimedia Commons with author and licence
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>
This commit is contained in:
1 parent
5640ed653b
commit
b761517386
22 files changed
+484
-17
No files matched your search
@@ -0,0 +1,13 @@
|
||||
-- Portraits and logos from Wikimedia Commons (via Wikidata P18 / P154). The image itself sits in person.photo_url or
|
||||
-- organization.logo_url; official photos (Parliament, European Parliament) take precedence and are never replaced.
|
||||
-- The licence data is keyed by the image URL, so the credit always belongs to the image that is actually shown.
|
||||
CREATE TABLE image_credit (
|
||||
url TEXT PRIMARY KEY,
|
||||
page_url TEXT, -- file description page on Commons
|
||||
credit TEXT, -- author / attribution as plain text
|
||||
license TEXT, -- short name, e.g. "CC BY-SA 4.0"
|
||||
license_url TEXT,
|
||||
source_slug TEXT NOT NULL,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
COMMENT ON TABLE image_credit IS 'Licence and attribution for third-party images in person.photo_url / organization.logo_url (Wikimedia Commons). No row = official photo of the source (Parliament, EP).';
|
||||
@@ -163,6 +163,10 @@ class PersonDetail(Model):
|
||||
birth_date: date | None = None
|
||||
death_date: date | None = None
|
||||
photo_url: str | None = None
|
||||
photo_credit: str | None = None
|
||||
photo_license: str | None = None
|
||||
photo_license_url: str | None = None
|
||||
photo_page_url: str | None = None
|
||||
wikidata_qid: str | None = None
|
||||
parlament_pad: str | None = None
|
||||
ep_id: str | None = None
|
||||
@@ -264,6 +268,10 @@ class PartyDetail(Model):
|
||||
short_name: str | None = None
|
||||
color: str | None = None
|
||||
logo_url: str | None = None
|
||||
logo_credit: str | None = None
|
||||
logo_license: str | None = None
|
||||
logo_license_url: str | None = None
|
||||
logo_page_url: str | None = None
|
||||
kind: str
|
||||
members: list[PartyMember]
|
||||
former_members: list[FormerMember]
|
||||
@@ -279,6 +287,7 @@ class OrganizationListItem(Model):
|
||||
name: str
|
||||
short_name: str | None = None
|
||||
kind: str
|
||||
logo_url: str | None = None
|
||||
paid: float | None = None
|
||||
received: float | None = None
|
||||
|
||||
@@ -317,6 +326,11 @@ class OrganizationDetail(Model):
|
||||
parent_slug: str | None = None
|
||||
parent_name: str | None = None
|
||||
identifiers: dict[str, str] | None = None
|
||||
logo_url: str | None = None
|
||||
logo_credit: str | None = None
|
||||
logo_license: str | None = None
|
||||
logo_license_url: str | None = None
|
||||
logo_page_url: str | None = None
|
||||
money: list[OrgMoney]
|
||||
counterparties: list[Counterparty]
|
||||
people: list[OrgPerson]
|
||||
|
||||
@@ -25,6 +25,7 @@ from politrack.core.records import (
|
||||
Document,
|
||||
Event,
|
||||
Evidence,
|
||||
Image,
|
||||
Legal,
|
||||
Money,
|
||||
OrgRecord,
|
||||
@@ -82,6 +83,8 @@ class Loader:
|
||||
return self.post_removed(record)
|
||||
if isinstance(record, ArchiveCopy):
|
||||
return self.archive_copy(record)
|
||||
if isinstance(record, Image):
|
||||
return self.image(record)
|
||||
raise TypeError(f"unknown record type {type(record).__name__}")
|
||||
|
||||
# -- documents --------------------------------------------------------------------
|
||||
@@ -244,6 +247,33 @@ class Loader:
|
||||
self.ctx.stats["social_accounts"] += 1
|
||||
return row["id"]
|
||||
|
||||
def image(self, rec: Image) -> int | None:
|
||||
"""Portrait or logo from Commons: only where no official image exists (or a Commons one is replaced)."""
|
||||
third_party = "(col IS NULL OR col LIKE 'https://upload.wikimedia.org/%%')"
|
||||
if rec.role == "photo":
|
||||
entity_id = self.resolver.person(rec.person)
|
||||
table, col = "person", "photo_url"
|
||||
else:
|
||||
entity_id = self.resolver.org(rec.org, create=False)
|
||||
table, col = "organization", "logo_url"
|
||||
if entity_id is None:
|
||||
self.ctx.stats["images_unresolved"] += 1
|
||||
return None
|
||||
self.conn.execute(
|
||||
"""INSERT INTO image_credit (url, page_url, credit, license, license_url, source_slug)
|
||||
VALUES (%s, %s, %s, %s, %s, %s)
|
||||
ON CONFLICT (url) DO UPDATE SET page_url = EXCLUDED.page_url, credit = EXCLUDED.credit,
|
||||
license = EXCLUDED.license, license_url = EXCLUDED.license_url, updated_at = now()""",
|
||||
(rec.url, rec.page_url, rec.credit, rec.license, rec.license_url, self.ctx.spec.slug),
|
||||
)
|
||||
updated = self.conn.execute(
|
||||
f"UPDATE {table} SET {col} = %s WHERE id = %s AND {third_party.replace('col', col)} "
|
||||
f"AND {col} IS DISTINCT FROM %s",
|
||||
(rec.url, entity_id, rec.url),
|
||||
).rowcount
|
||||
self.ctx.stats["images_set" if updated else "images_kept"] += 1
|
||||
return entity_id
|
||||
|
||||
# -- standalone facets ------------------------------------------------------------
|
||||
|
||||
def vote_event(self, rec: VoteEvent) -> int:
|
||||
|
||||
@@ -121,6 +121,20 @@ class SocialAccount:
|
||||
verified: bool = False # True only for official sources (parliament profile, official website)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Image:
|
||||
"""A portrait (person) or logo (organization) from a freely licensed source, with its attribution. Fills the
|
||||
entity's photo_url / logo_url only if it has no official image."""
|
||||
url: str # the image (thumbnail) shown on the site
|
||||
role: Literal["photo", "logo"]
|
||||
page_url: str | None = None # description page with the full licence information
|
||||
credit: str | None = None
|
||||
license: str | None = None
|
||||
license_url: str | None = None
|
||||
person: PersonRef | None = None
|
||||
org: OrgRef | None = None
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------
|
||||
# Facets (structured payload of a claim)
|
||||
# --------------------------------------------------------------------------------------------
|
||||
@@ -273,7 +287,8 @@ class ArchiveCopy:
|
||||
archive_url: str
|
||||
|
||||
|
||||
Record = Union[PersonRecord, OrgRecord, SocialAccount, VoteEvent, Event, Claim, Document, PostRemoved, ArchiveCopy]
|
||||
Record = Union[PersonRecord, OrgRecord, SocialAccount, VoteEvent, Event, Claim, Document, PostRemoved, ArchiveCopy,
|
||||
Image]
|
||||
|
||||
|
||||
def to_jsonable(obj: Any) -> Any:
|
||||
|
||||
@@ -30,7 +30,9 @@ def list_parties(conn: Connection) -> list[dict]:
|
||||
|
||||
def get_party(conn: Connection, slug: str) -> dict | None:
|
||||
party = conn.execute(
|
||||
"SELECT id, slug, name, short_name, color, logo_url, kind FROM organization WHERE slug = %s", (slug,)
|
||||
"""SELECT o.id, o.slug, o.name, o.short_name, o.color, o.logo_url, o.kind, ic.credit AS logo_credit,
|
||||
ic.license AS logo_license, ic.license_url AS logo_license_url, ic.page_url AS logo_page_url
|
||||
FROM organization o LEFT JOIN image_credit ic ON ic.url = o.logo_url WHERE o.slug = %s""", (slug,)
|
||||
).fetchone()
|
||||
if not party:
|
||||
return None
|
||||
@@ -105,7 +107,7 @@ def list_organizations(conn: Connection, *, q: str | None = None, kind: str | No
|
||||
offset: int = 0) -> list[dict]:
|
||||
return conn.execute(
|
||||
"""
|
||||
SELECT o.slug, o.name, o.short_name, o.kind,
|
||||
SELECT o.slug, o.name, o.short_name, o.kind, o.logo_url,
|
||||
(SELECT sum(amount) FROM money_flow WHERE payer_org_id = o.id) AS paid,
|
||||
(SELECT sum(amount) FROM money_flow WHERE payee_org_id = o.id) AS received
|
||||
FROM organization o
|
||||
@@ -125,8 +127,11 @@ def get_organization(conn: Connection, slug: str) -> dict | None:
|
||||
org = conn.execute(
|
||||
"""SELECT o.id, o.slug, o.name, o.short_name, o.kind, parent.slug AS parent_slug, parent.name AS parent_name,
|
||||
(SELECT jsonb_object_agg(i.scheme, i.value) FROM identifier i
|
||||
WHERE i.entity_type = 'organization' AND i.entity_id = o.id) AS identifiers
|
||||
FROM organization o LEFT JOIN organization parent ON parent.id = o.parent_id WHERE o.slug = %s""",
|
||||
WHERE i.entity_type = 'organization' AND i.entity_id = o.id) AS identifiers,
|
||||
o.logo_url, ic.credit AS logo_credit, ic.license AS logo_license, ic.license_url AS logo_license_url,
|
||||
ic.page_url AS logo_page_url
|
||||
FROM organization o LEFT JOIN organization parent ON parent.id = o.parent_id
|
||||
LEFT JOIN image_credit ic ON ic.url = o.logo_url WHERE o.slug = %s""",
|
||||
(slug,),
|
||||
).fetchone()
|
||||
if not org:
|
||||
|
||||
@@ -40,8 +40,11 @@ def get_person(conn: Connection, slug: str) -> dict | None:
|
||||
"""
|
||||
SELECT p.id, p.slug, p.full_name, p.given_name, p.family_name, p.honorific_prefix, p.birth_date, p.death_date,
|
||||
p.photo_url, pi.wikidata_qid, pi.parlament_pad, pi.ep_id, p.summary_de, p.summary_en, ps.status,
|
||||
ps.verified AS status_verified, ps.last_office_end
|
||||
ps.verified AS status_verified, ps.last_office_end,
|
||||
ic.credit AS photo_credit, ic.license AS photo_license, ic.license_url AS photo_license_url,
|
||||
ic.page_url AS photo_page_url
|
||||
FROM person p JOIN person_status ps ON ps.person_id = p.id JOIN person_identifier pi ON pi.person_id = p.id
|
||||
LEFT JOIN image_credit ic ON ic.url = p.photo_url
|
||||
WHERE p.slug = %s
|
||||
""",
|
||||
(slug,),
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
"""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)
|
||||
@@ -247,3 +247,33 @@ def test_orf_fee_report_is_orf_income_not_a_payment_to_a_medium():
|
||||
assert claim.facet.payer_name == "Programmentgelt gemäß § 31 Abs. 1 ORF-G" and claim.facet.category == "orf_fee"
|
||||
assert claim.summary_de == ("Österreichischer Rundfunk: Einnahmen aus Programmentgelt gemäß § 31 Abs. 1 ORF-G, "
|
||||
"176.200.000,00 € (2023-Q3)")
|
||||
|
||||
|
||||
def test_written_question_addressee_is_not_an_asker():
|
||||
from politrack.sources.parlament.items import ParlamentItems, question_answerers
|
||||
|
||||
rows = [
|
||||
{"ITYP": "J", "Nummer": "1495/J", "Betreff": "Thema - beantwortet durch 1479/AB (SPÖ)",
|
||||
"Personen": '["2337","35520"]', "Datum": "07.08.2018"},
|
||||
{"ITYP": "J", "Nummer": "1600/J", "Betreff": "Offen", "Personen": '["2337","35520"]', "Datum": "01.09.2018"},
|
||||
{"ITYP": "AB", "Nummer": "1479/AB", "Betreff": "Thema", "Personen": '["35520"]', "Datum": "07.10.2018"},
|
||||
]
|
||||
answerers = question_answerers(rows)
|
||||
adapter = ParlamentItems.__new__(ParlamentItems)
|
||||
askers = [c.person.ids["parlament"] for c in adapter.question_claims(rows[0], "/gegenstand/XXVI/J/1495", answerers)]
|
||||
assert askers == ["2337"]
|
||||
unanswered = [c.person.ids["parlament"] for c in adapter.question_claims(rows[1], "/gegenstand/XXVI/J/1600", answerers)]
|
||||
assert unanswered == ["2337"]
|
||||
answer = [c.person.ids["parlament"] for c in adapter.question_claims(rows[2], "/gegenstand/XXVI/AB/1479", answerers)]
|
||||
assert answer == ["35520"]
|
||||
|
||||
|
||||
def test_commons_register_ids_and_titles():
|
||||
from politrack.sources.wikimedia import file_title, register_id
|
||||
|
||||
assert register_id("firmenbuch", "520909 v") == "520909v"
|
||||
assert register_id("firmenbuch", "FN 58358x") == "58358x"
|
||||
assert register_id("firmenbuch", "HRB 704943") is None
|
||||
assert register_id("zvr", "ZVR 0303258961") == "303258961"
|
||||
assert file_title("http://commons.wikimedia.org/wiki/Special:FilePath/B%C3%B6sendorfer_logo.svg") == \
|
||||
"File:Bösendorfer logo.svg"
|
||||
Reference in new issue
Block a user