depicts/depicts/commons.py

44 lines
1.2 KiB
Python
Raw Normal View History

2023-10-25 07:54:05 +01:00
"""Wikimedia Commons API call."""
from . import mediawiki, utils
2023-10-25 07:54:05 +01:00
from .type import CallParams
2023-10-25 07:54:05 +01:00
commons_url = "https://commons.wikimedia.org/w/api.php"
2019-10-14 11:08:42 +01:00
page_size = 50
2023-10-25 07:54:05 +01:00
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 {}
2023-10-25 07:54:05 +01:00
params: CallParams = {
"action": "query",
"prop": "imageinfo",
"iiprop": "url",
}
if thumbheight is not None:
2023-10-25 07:54:05 +01:00
params["iiurlheight"] = thumbheight
if thumbwidth is not None:
2023-10-25 07:54:05 +01:00
params["iiurlwidth"] = thumbwidth
images = {}
2019-10-14 11:08:42 +01:00
for cur in utils.chunk(filenames, page_size):
call_params = params.copy()
2023-10-25 07:54:05 +01:00
call_params["titles"] = "|".join(f"File:{f}" for f in cur)
2019-10-14 11:08:42 +01:00
r = mediawiki.api_post(call_params, api_url=commons_url)
2019-10-14 11:08:42 +01:00
2023-10-25 07:54:05 +01:00
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