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:
simonandClaude Opus 5.5 committed 2026-11-20 14:35:27 +01:00
1 parent 5640ed653b
commit b761517386
22 files changed
+483 -16

No files matched your search

+13
View File
@@ -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).';
+14
View File
@@ -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]
+30
View File
@@ -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:
+16 -1
View File
@@ -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:
+9 -4
View File
@@ -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:
+4 -1
View File
@@ -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,),
+175
View File
@@ -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)
+30
View File
@@ -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"
+1
View File
@@ -29,6 +29,7 @@ app_user ──< report ──< report_reference (→ claim, report, person, org
| `organization` | `kind`: party, parliamentary_group, parliament, government, ministry, state_government, municipality, public_body, company, ngo, media, lobby, court, authority, eu_institution, other. `parent_id` for hierarchies. |
| `identifier` | `(entity_type, entity_id, scheme, value)`, unique per (entity_type, scheme, value). |
| `alias` | alternative names (with/without titles, short names, party abbreviations) used by the resolver and the linker. |
| `image_credit` | author, licence and Commons file page for a third-party image, keyed by its URL, which sits in `person.photo_url` / `organization.logo_url`. No row means an official photo (Parliament, EP); those are never replaced by Commons images. |
| `social_account` | person *or* organisation, `platform`, `url`, `verified` (official source) and `source_slug`. |
### Identifier schemes
+1
View File
@@ -69,6 +69,7 @@ Status: ✅ implemented (adapter name in `code`) · 🟡 planned · ⛔ delibera
| Source | Data | Access | Terms | Status |
|---|---|---|---|---|
| Wikidata | positions incl. Landtage and mayors, party membership, careers, birth dates, **social-media handles**, ids | SPARQL | CC0 | ✅ `wikidata.politicians` |
| Wikimedia Commons | portraits (Wikidata P18) for people without an official photo; party and company logos (P154), matched by Wikidata id, Firmenbuch number (P5285) or ZVR number (P6279) only | SPARQL + Commons API (imageinfo/extmetadata) | free licence per file; author and licence shown next to the image | ✅ `wikimedia.images` (weekly; Parliament/EP photos take precedence) |
| GDELT DOC 2.0 | article metadata for politicians' names, attributed to the original outlets | API, ≤ 1 request / 5 s | free | ✅ `gdelt.coverage` (supplement; thin for Austrian outlets) |
| HowTheyVote.eu | EP roll-call votes | CSV dump on GitHub (robots.txt blocks its download path), API | ODbL 1.0 (share-alike) | ⛔ not needed: `europarl.votes` takes the same votes from the EP under CC BY 4.0 |
| OpenSanctions | PEP cross-references | bulk JSON | CC BY-NC 4.0 | 🟡 non-commercial only |
+13 -2
View File
@@ -47,8 +47,8 @@
"visitors": "Politrack verwendet keine Werbung, kein Tracking und keine Skripte, Schriften oder Einbettungen von Dritten. Beim Abruf fallen technisch notwendige Zugriffsdaten an (IP-Adresse, Zeitpunkt, aufgerufene Seite), die nur so lange gespeichert werden, wie es für den sicheren Betrieb nötig ist.",
"cookiesHeading": "Cookies",
"cookies": "Wir speichern nur deine eigenen Einstellungen in Cookies: Quellen- und Themenfilter sowie das Farbschema. Sie dienen keiner Nachverfolgung.",
"imagesHeading": "Porträts",
"images": "Porträts laden wir über unseren eigenen Server, sodass deine IP-Adresse nicht an das Parlament oder andere Quellen übermittelt wird. Links zu externen Quellen öffnest du selbst; dort gelten die Bestimmungen der jeweiligen Betreiber.",
"imagesHeading": "Porträts und Logos",
"images": "Porträts und Logos laden wir über unseren eigenen Server, sodass deine IP-Adresse nicht an das Parlament, Wikimedia Commons oder andere Quellen übermittelt wird. Links zu externen Quellen öffnest du selbst; dort gelten die Bestimmungen der jeweiligen Betreiber.",
"subjectsHeading": "Daten über Politikerinnen und Politiker",
"subjects": "Politrack verarbeitet personenbezogene Daten ausschließlich zur öffentlichen Rolle von Personen: Funktionen, Abstimmungen, öffentliche Aussagen und Auftritte, gemeldete Nebentätigkeiten, Parteispenden und öffentlich bekannte Verfahren. Private Spender werden nur so genannt, wie es die amtliche Veröffentlichung vorsieht.",
"basisHeading": "Rechtsgrundlage",
@@ -735,5 +735,16 @@
"errorNotYours": "Diesen Bericht kannst du nicht bearbeiten.",
"errorInvalid": "Nicht gespeichert: {detail}",
"errorUnknown": "Nicht gespeichert – bitte später noch einmal versuchen."
},
"Images": {
"official": {
"parlament": "Foto: Parlament Österreich",
"europarl": "Foto: Europäisches Parlament"
},
"commons": "Bild: {credit}",
"commonsNoCredit": "Bild: Wikimedia Commons",
"license": "Lizenz",
"source": "Quelle",
"logoAlt": "Logo von {name}"
}
}
+13 -2
View File
@@ -622,8 +622,8 @@
"visitors": "Politrack uses no advertising, no tracking and no third-party scripts, fonts or embeds. Serving a page produces technically necessary access data (IP address, time, page requested), kept only as long as needed to run the site securely.",
"cookiesHeading": "Cookies",
"cookies": "Cookies only store your own settings: source and topic filters and the colour scheme. They are not used for tracking.",
"imagesHeading": "Portraits",
"images": "Portraits are loaded through our own server, so your IP address is not passed to the parliament or other sources. External source links are yours to open; the operators' own terms apply there.",
"imagesHeading": "Portraits and logos",
"images": "Portraits and logos are loaded through our own server, so your IP address is not passed on to Parliament, Wikimedia Commons or other sources. Links to external sources are opened by you; the respective operator's terms apply there.",
"subjectsHeading": "Data about politicians",
"subjects": "Politrack processes personal data only about people's public role: offices, votes, public statements and appearances, declared side jobs, party donations and publicly known proceedings. Private donors are named only as the official publication names them.",
"basisHeading": "Legal basis",
@@ -735,5 +735,16 @@
"errorNotYours": "You can't edit this report.",
"errorInvalid": "Not saved: {detail}",
"errorUnknown": "Not saved – please try again later."
},
"Images": {
"official": {
"parlament": "Photo: Austrian Parliament",
"europarl": "Photo: European Parliament"
},
"commons": "Image: {credit}",
"commonsNoCredit": "Image: Wikimedia Commons",
"license": "Licence",
"source": "Source",
"logoAlt": "Logo of {name}"
}
}
@@ -7,6 +7,7 @@ import {ExternalLink} from '@/components/ExternalLink';
import {MoneyTable} from '@/components/MoneyTable';
import {Notice} from '@/components/Notice';
import {Breadcrumbs, SectionHead} from '@/components/PageHeader';
import {ImageCredit, Logo} from '@/components/ImageCredit';
import {Link, redirect} from '@/i18n/navigation';
import {api, NotFoundError, type Counterparty, type OrganizationDetail} from '@/lib/api';
import {formatMoneyCompact, formatNumber} from '@/lib/format';
@@ -83,6 +84,15 @@ export default async function OrganizationPage({params}: Props) {
</p>
) : null}
</div>
{org.logo_url && (
<figure className="page-header-logo">
<Logo name={org.name} src={org.logo_url} size="lg" />
<figcaption>
<ImageCredit url={org.logo_url} credit={org.logo_credit} license={org.logo_license}
licenseUrl={org.logo_license_url} pageUrl={org.logo_page_url} />
</figcaption>
</figure>
)}
</header>
<div className="layout-aside">
+7 -1
View File
@@ -2,6 +2,7 @@ import type {Metadata} from 'next';
import {getTranslations, setRequestLocale} from 'next-intl/server';
import {countActive, Field, FilterBar} from '@/components/FilterBar';
import {EmptyState} from '@/components/Notice';
import {Logo} from '@/components/ImageCredit';
import {PageHeader} from '@/components/PageHeader';
import {Pagination} from '@/components/Pagination';
import {Link} from '@/i18n/navigation';
@@ -59,7 +60,12 @@ export default async function OrganizationsPage({params, searchParams}: Props) {
<tbody>
{orgs.map((org) => (
<tr key={org.slug}>
<td data-label={t('name')}><Link href={`/organisationen/${org.slug}`}>{org.name}</Link></td>
<td data-label={t('name')}>
<span className="org-name">
<Logo name={org.name} src={org.logo_url} size="sm" />
<Link href={`/organisationen/${org.slug}`}>{org.name}</Link>
</span>
</td>
<td data-label={t('kindLabel')}><span className="badge">{t(`kind.${org.kind}` as 'kind.other')}</span></td>
<td data-label={t('paid')} className="num">{amount(org.paid)}</td>
<td data-label={t('received')} className="num">{amount(org.received)}</td>
@@ -5,6 +5,7 @@ import {ProportionBar, StatGrid} from '@/components/charts';
import {ClaimList} from '@/components/ClaimList';
import {Notice} from '@/components/Notice';
import {Breadcrumbs, SectionHead} from '@/components/PageHeader';
import {ImageCredit, Logo} from '@/components/ImageCredit';
import {SocialFeed} from '@/components/SocialFeed';
import {VoteLegend, VoteList} from '@/components/VoteList';
import {Link} from '@/i18n/navigation';
@@ -62,6 +63,15 @@ export default async function PartyPage({params}: Props) {
<h1>{party.short_name ?? party.name}</h1>
{party.short_name && <p className="lede">{party.name}</p>}
</div>
{party.logo_url && (
<figure className="page-header-logo">
<Logo name={party.name} src={party.logo_url} size="lg" />
<figcaption>
<ImageCredit url={party.logo_url} credit={party.logo_credit} license={party.logo_license}
licenseUrl={party.logo_license_url} pageUrl={party.logo_page_url} />
</figcaption>
</figure>
)}
</header>
<StatGrid
+2
View File
@@ -1,6 +1,7 @@
import type {Metadata} from 'next';
import {getTranslations, setRequestLocale} from 'next-intl/server';
import {PageHeader} from '@/components/PageHeader';
import {Logo} from '@/components/ImageCredit';
import {Link} from '@/i18n/navigation';
import {api} from '@/lib/api';
import {partyStyle} from '@/lib/format';
@@ -26,6 +27,7 @@ export default async function PartiesPage({params}: {params: Promise<{locale: st
{parties.map((party) => (
<li key={party.slug}>
<Link href={`/parteien/${party.slug}`} className="card-link party-card" style={partyStyle(party.color)}>
<Logo name={party.name} src={party.logo_url} size="sm" />
<span className="card-link-title">{party.short_name ?? party.name}</span>
{party.short_name && <span className="muted small">{party.name}</span>}
<span className="small">
@@ -2,6 +2,7 @@ import type {Metadata} from 'next';
import {notFound} from 'next/navigation';
import {getTranslations, setRequestLocale} from 'next-intl/server';
import {Avatar} from '@/components/Avatar';
import {ImageCredit} from '@/components/ImageCredit';
import {PartyTag, platformName, StatusBadge} from '@/components/badges';
import {StatGrid, type Stat} from '@/components/charts';
import {ClaimList} from '@/components/ClaimList';
@@ -89,7 +90,13 @@ export default async function PersonPage({params, searchParams}: Props) {
<article>
<Breadcrumbs items={[{label: tp('title'), href: '/personen'}, {label: person.full_name}]} />
<header className="profile-head">
<figure className="profile-photo">
<Avatar name={person.full_name} src={person.photo_url} size="lg" />
<figcaption>
<ImageCredit url={person.photo_url} credit={person.photo_credit} license={person.photo_license}
licenseUrl={person.photo_license_url} pageUrl={person.photo_page_url} />
</figcaption>
</figure>
<div>
<div className="cluster">
<StatusBadge status={person.status} verified={person.status_verified} />
+2 -2
View File
@@ -1,8 +1,8 @@
// Image proxy for portraits, so that visitors' IP addresses don't reach the publishers.
// Image proxy for portraits and logos, so that visitors' IP addresses don't reach the publishers.
// Only raster images from the hosts below: anything else would turn this into an open proxy.
import type {NextRequest} from 'next/server';
const ALLOWED_HOSTS = new Set(['www.parlament.gv.at', 'www.europarl.europa.eu']);
const ALLOWED_HOSTS = new Set(['www.parlament.gv.at', 'www.europarl.europa.eu', 'upload.wikimedia.org']);
const IMAGE_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp', 'image/gif']);
const MAX_BYTES = 5 * 1024 * 1024;
const MAX_REDIRECTS = 3;
+6 -3
View File
@@ -1,13 +1,16 @@
import {initials} from '@/lib/format';
/** Third-party images (portraits, logos) go through our own image proxy (app/api/img), so that visitors' IP
* addresses don't reach the publishers. */
export const proxied = (src: string) => `/api/img?u=${encodeURIComponent(src)}`;
/**
* Portrait or initials. Portraits go through our own image proxy (app/api/img), so that visitors' IP addresses
* don't reach third parties. Decorative (alt=""), because the name is always printed next to it.
* Portrait or initials. Decorative (alt=""), because the name is always printed next to it.
*/
export function Avatar({name, src, size = 'md'}: {name: string; src?: string | null; size?: 'md' | 'lg'}) {
const className = size === 'lg' ? 'avatar avatar--lg' : 'avatar';
if (src) {
return <img src={`/api/img?u=${encodeURIComponent(src)}`} alt="" className={className} loading="lazy" decoding="async" />;
return <img src={proxied(src)} alt="" className={className} loading="lazy" decoding="async" />;
}
return <span className={className} aria-hidden="true">{initials(name)}</span>;
}
+51
View File
@@ -0,0 +1,51 @@
import {getTranslations} from 'next-intl/server';
import {proxied} from '@/components/Avatar';
/** Organization or party logo on a light tile (logos are drawn for light backgrounds, also in dark mode). */
export async function Logo({name, src, size = 'md'}: {name: string; src?: string | null; size?: 'sm' | 'md' | 'lg'}) {
if (!src) return null;
const t = await getTranslations('Images');
return (
<span className={`logo-tile logo-tile--${size}`}>
<img src={proxied(src)} alt={t('logoAlt', {name})} loading="lazy" decoding="async" />
</span>
);
}
export type ImageCreditData = {
url?: string | null;
credit?: string | null;
license?: string | null;
licenseUrl?: string | null;
pageUrl?: string | null;
};
function hostOf(url: string): string {
try {
return new URL(url).hostname;
} catch {
return '';
}
}
/** Attribution under a portrait or logo: author and licence for Commons files, the publisher for official photos. */
export async function ImageCredit({url, credit, license, licenseUrl, pageUrl}: ImageCreditData) {
if (!url) return null;
const t = await getTranslations('Images');
const host = hostOf(url);
if (host === 'www.parlament.gv.at') return <p className="image-credit">{t('official.parlament')}</p>;
if (host === 'www.europarl.europa.eu') return <p className="image-credit">{t('official.europarl')}</p>;
if (host !== 'upload.wikimedia.org') return null;
const label = credit ? t('commons', {credit}) : t('commonsNoCredit');
return (
<p className="image-credit">
{pageUrl ? <a href={pageUrl} rel="noopener noreferrer" target="_blank">{label}</a> : label}
{license && (
<>
{' · '}
{licenseUrl ? <a href={licenseUrl} rel="license noopener noreferrer" target="_blank">{license}</a> : license}
</>
)}
</p>
);
}
+14
View File
@@ -223,6 +223,11 @@ export type OrganizationDetail = {
parent_slug: string | null;
parent_name: string | null;
identifiers: Record<string, string> | null;
logo_url: string | null;
logo_credit: string | null;
logo_license: string | null;
logo_license_url: string | null;
logo_page_url: string | null;
money: OrgMoney[];
counterparties: Counterparty[];
people: OrgPerson[];
@@ -233,6 +238,7 @@ export type OrganizationListItem = {
name: string;
short_name: string | null;
kind: string;
logo_url: string | null;
paid: number | null;
received: number | null;
};
@@ -258,6 +264,10 @@ export type PartyDetail = {
short_name: string | null;
color: string | null;
logo_url: string | null;
logo_credit: string | null;
logo_license: string | null;
logo_license_url: string | null;
logo_page_url: string | null;
kind: string;
members: PartyMember[];
former_members: FormerMember[];
@@ -299,6 +309,10 @@ export type PersonDetail = {
birth_date: string | null;
death_date: string | null;
photo_url: string | null;
photo_credit: string | null;
photo_license: string | null;
photo_license_url: string | null;
photo_page_url: string | null;
wikidata_qid: string | null;
parlament_pad: string | null;
ep_id: string | null;
+55
View File
@@ -2448,3 +2448,58 @@ input[type='checkbox'].switch:checked::before {
.report-preview-title {
margin-top: var(--space-4);
}
/* ---------- portraits and logos: credit lines, logo tiles ---------- */
.profile-photo, .page-header-logo {
margin: 0;
display: flex;
flex-direction: column;
gap: var(--space-1);
max-width: 11rem;
}
.image-credit {
margin: 0;
font-size: var(--text-xs, 0.75rem);
line-height: 1.35;
color: var(--ink-3);
overflow-wrap: anywhere;
}
.image-credit a {
color: inherit;
}
/* Logos are designed for light backgrounds, so the tile stays white in dark mode too. */
.logo-tile {
--size: 2rem;
display: inline-grid;
place-items: center;
flex: none;
width: calc(var(--size) * 1.6);
height: var(--size);
padding: 3px;
background: #ffffff;
border: 1px solid var(--line);
border-radius: var(--radius);
}
.logo-tile img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
}
.logo-tile--sm { --size: 1.75rem; }
.logo-tile--lg { --size: 5rem; padding: var(--space-2); }
.party-card .logo-tile {
align-self: flex-start;
}
.org-name {
display: inline-flex;
align-items: center;
gap: var(--space-2);
}