depicts/depicts/commons.py

44 lines
1.2 KiB
Python

"""Wikimedia Commons API call."""
from . import mediawiki, utils
from .type import CallParams
commons_url = "https://commons.wikimedia.org/w/api.php"
page_size = 50
def image_detail(
filenames: list[str] | str,
thumbheight: int | None = None,
thumbwidth: int | None = None,
) -> dict[str, dict[str, str]]:
"""Get image detail from Wikimedia Commons."""
if not isinstance(filenames, list):
filenames = [filenames]
if not filenames:
return {}
params: CallParams = {
"action": "query",
"prop": "imageinfo",
"iiprop": "url",
}
if thumbheight is not None:
params["iiurlheight"] = thumbheight
if thumbwidth is not None:
params["iiurlwidth"] = thumbwidth
images = {}
for cur in utils.chunk(filenames, page_size):
call_params = params.copy()
call_params["titles"] = "|".join(f"File:{f}" for f in cur)
r = mediawiki.api_post(call_params, api_url=commons_url)
for image in r.json()["query"]["pages"]:
filename = utils.drop_start(image["title"], "File:")
images[filename] = image["imageinfo"][0] if "imageinfo" in image else None
return images