Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Generate Wikimedia thumbnail URLs on the fly (#4736)
sarayourfriendbfa84f532e3a
diff --git a/api/api/utils/image_proxy/__init__.py b/api/api/utils/image_proxy/__init__.pyindex 1061cd2a9..a8b47ea41 100644--- a/api/api/utils/image_proxy/__init__.py+++ b/api/api/utils/image_proxy/__init__.py@@ -20,6 +20,7 @@ from api.utils.image_proxy.dataclasses import MediaInfo, RequestConfigfrom api.utils.image_proxy.exception import UpstreamThumbnailExceptionfrom api.utils.image_proxy.extension import get_image_extensionfrom api.utils.image_proxy.photon import get_photon_request_params+from api.utils.image_proxy.wikimedia import get_wikimedia_thumbnail_urlfrom api.utils.tallies import get_monthly_timestamp@@ -42,7 +43,7 @@ THUMBNAIL_STRATEGY = Literal["photon_proxy", "original"]def get_request_params_for_extension(ext: str,headers: dict[str, str],- image_url: str,+ media_info: MediaInfo,parsed_image_url: urlparse,request_config: RequestConfig,) -> tuple[str, dict[str, str], dict[str, str]]:@@ -52,6 +53,29 @@ def get_request_params_for_extension(request params, if the file can be cached and returned as is (SVG), we do that,otherwise we raise UnsupportedMediaType exception."""++ if media_info.media_provider == "wikimedia":+ # Wikimedia supports all file types with their own thumbnail+ # endpoints; we still request the thumbnail through to Site Accelerator to offload repeated+ # requests from Wikimedia's servers. Site Accelerator essentially acts as a cache,+ # because we'll rely on Wikimedia to resize and compress the image as needed.+ thumbnail_url = get_wikimedia_thumbnail_url(+ media_info,+ parsed_image_url,+ request_config,+ )+ if thumbnail_url is not None:+ return get_photon_request_params(+ thumbnail_url,+ # Because Wikimedia's thumbnails are configurable for compression+ # and size, we can skip both operations in Site Accelerator+ is_full_size=True,+ is_compressed=False,+ headers=headers,+ )+ # else, `get_wikimedia_thumbnail_url` was unable to create a thumbnail URL+ # for this wikimedia image, so fallback to the default routine+if ext in PHOTON_TYPES:return get_photon_request_params(parsed_image_url,@@ -60,7 +84,7 @@ def get_request_params_for_extension(headers,)elif ext in ORIGINAL_TYPES:- return image_url, {}, headers+ return media_info.image_url, {}, headersraise UnsupportedMediaType(f"Image extension {ext} is not supported by the thumbnail proxy.")@@ -215,7 +239,7 @@ async def get(upstream_url, params, headers = get_request_params_for_extension(image_extension,headers,- image_url,+ media_info,parsed_image_url,request_config,)diff --git a/api/api/utils/image_proxy/dataclasses.py b/api/api/utils/image_proxy/dataclasses.pyindex f15fb1f85..14a45a9a1 100644--- a/api/api/utils/image_proxy/dataclasses.py+++ b/api/api/utils/image_proxy/dataclasses.py@@ -7,6 +7,7 @@ class MediaInfo:media_provider: strmedia_identifier: UUIDimage_url: str+ width: int | None = None@dataclassdiff --git a/api/api/utils/image_proxy/wikimedia.py b/api/api/utils/image_proxy/wikimedia.pynew file mode 100644index 000000000..9962df54d--- /dev/null+++ b/api/api/utils/image_proxy/wikimedia.py@@ -0,0 +1,49 @@+import re+from math import inf+from urllib.parse import ParseResult++from django.conf import settings++from api.utils.image_proxy.dataclasses import MediaInfo, RequestConfig+++# e.g.:+# https://upload.wikimedia.org/wikipedia/commons/9/9e/Color_icon_yellow.svg+# https://upload.wikimedia.org/wikipedia/commons/f/f3/Open_book_01.svg+# The length of the hashes is constant+# For each example, the thumbnail URL is:+# https://upload.wikimedia.org/wikipedia/commons/thumb/9/9e/Color_icon_yellow.svg/<WIDTH>px-Color_icon_yellow.svg.jpg+# https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Open_book_01.svg/<WIDTH>px-Open_book_01.svg.jpg+# A regex is slightly more reliable for this in case for some reason wikipedia/commons is not a constant prefix+# or the filename somehow has an additional `/` in it (though that does not appear to be possible)+WIKIMEDIA_PATH_PARSE = re.compile(+ r"^(?P<path_prefix>.*?)(?P<hash>/[a-z0-9]{1}/[a-z0-9]{2}/)(?P<filename>.*)$"+)+++def get_wikimedia_thumbnail_url(+ media_info: MediaInfo, url: ParseResult, request_config: RequestConfig+) -> ParseResult | None:+ path_match = WIKIMEDIA_PATH_PARSE.match(url.path)+ if path_match is None:+ return None++ groups = path_match.groupdict()++ if request_config.is_full_size:+ width = media_info.width or settings.THUMBNAIL_WIDTH_PX+ else:+ # If not full size, prevent Wikimedia from upscaling the image by using the smaller of+ # the default thumbnail size or media_info.width+ # Wikimedia _requires_ sending a width, so there's no other fallback than the default thumbnail size+ width = min(settings.THUMBNAIL_WIDTH_PX, media_info.width or inf)++ params = f"{width}px"++ if request_config.is_compressed:+ params = f"lossy-{params}"++ # always retrieve a PNG, and Site Accelerator will convert it as necessary based on the accept headers+ return url._replace(+ path=f"{groups['path_prefix']}/thumb{groups['hash']}{groups['filename']}/{params}-{groups['filename']}.png"+ )diff --git a/api/api/views/image_views.py b/api/api/views/image_views.pyindex c99b189ed..974a4292b 100644--- a/api/api/views/image_views.py+++ b/api/api/views/image_views.py@@ -110,6 +110,7 @@ class ImageViewSet(MediaViewSet):media_identifier=image.identifier,media_provider=image.provider,image_url=image_url,+ width=image.width,)@thumbnail_docsdiff --git a/api/conf/settings/thumbnails.py b/api/conf/settings/thumbnails.pyindex 31d5f4ed8..7e22acf89 100644--- a/api/conf/settings/thumbnails.py+++ b/api/conf/settings/thumbnails.py@@ -15,7 +15,7 @@ PHOTON_ENDPOINT = config("PHOTON_ENDPOINT", default="https://i0.wp.com/")# they're just passed through to Photon's API# Keeping them as strings makes the tests slightly less verbose (for not needing# to cast them in assertions to match the parsed param types)-THUMBNAIL_WIDTH_PX = config("THUMBNAIL_WIDTH_PX", default="600")+THUMBNAIL_WIDTH_PX = config("THUMBNAIL_WIDTH_PX", default="600", cast=int)THUMBNAIL_QUALITY = config("THUMBNAIL_JPG_QUALITY", default="80")# The length of time to cache repeated thumbnail failures@@ -37,3 +37,8 @@ THUMBNAIL_UPSTREAM_TIMEOUT = config("THUMBNAIL_UPSTREAM_TIMEOUT", default=4, casTHUMBNAIL_EXTENSION_REQUEST_TIMEOUT = config("THUMBNAIL_EXTENSION_REQUEST_TIMEOUT", default=4, cast=int)++# Use Wikimedia's thumbnail endpoint when requesting thumbnails from Site Accelerator (formerly Photon)+USE_WIKIMEDIA_THUMBNAIL_ENDPOINT = config(+ "USE_WIKIMEDIA_THUMBNAIL_ENDPOINT", default=True, cast=bool+)diff --git a/api/test/factory/models/image.py b/api/test/factory/models/image.pyindex 63c59d7c2..5a147ce54 100644--- a/api/test/factory/models/image.py+++ b/api/test/factory/models/image.py@@ -2,6 +2,7 @@ import factoryfrom factory.django import DjangoModelFactoryfrom api.models.image import DeletedImage, Image, ImageReport, SensitiveImage+from test.factory.faker import Fakerfrom test.factory.models.media import MediaFactory, MediaReportFactory@@ -25,6 +26,9 @@ class ImageFactory(MediaFactory):class Meta:model = Image+ width = Faker("random_element", elements=(100, 1200, 2500))+ height = Faker("random_element", elements=(100, 1200, 2500))+class ImageReportFactory(MediaReportFactory):class Meta:diff --git a/api/test/factory/models/media.py b/api/test/factory/models/media.pyindex 41242782f..f586e14d9 100644--- a/api/test/factory/models/media.py+++ b/api/test/factory/models/media.py@@ -53,7 +53,7 @@ class MediaFactory(DjangoModelFactory):"""The foreign identifier isn't necessarily a UUID but for test purposes it's fine if it looks like one"""license = Faker("random_element", elements=ALL_LICENSES)- provider = Faker("random_element", elements=("wikimedia", "flickr"))+ provider = Faker("random_element", elements=("flickr", "stocksnap"))foreign_landing_url = Faker("globally_unique_url")url = Faker("globally_unique_url")diff --git a/api/test/unit/utils/test_image_proxy.py b/api/test/unit/utils/test_image_proxy.pyindex 19bbbd265..1020796c9 100644--- a/api/test/unit/utils/test_image_proxy.py+++ b/api/test/unit/utils/test_image_proxy.py@@ -34,6 +34,12 @@ TEST_IMAGE_URL = PHOTON_URL_FOR_TEST_IMAGE.replace(settings.PHOTON_ENDPOINT, "htTEST_MEDIA_IDENTIFIER = uuid4()TEST_MEDIA_PROVIDER = "foo"+# pook assets the params are passed matching type, so `'600' != 600`+# this is a bug in pook, but we need to handle it here anyway+# otherwise we would need to adjust the runtime code to account for+# this testing oddity+THUMBNAIL_WIDTH_PARAM = str(settings.THUMBNAIL_WIDTH_PX)+TEST_MEDIA_INFO = MediaInfo(media_identifier=TEST_MEDIA_IDENTIFIER,media_provider=TEST_MEDIA_PROVIDER,@@ -84,7 +90,7 @@ def test_get_successful_no_auth_key_default_args(mock_image_data):pook.get(PHOTON_URL_FOR_TEST_IMAGE).params({- "w": settings.THUMBNAIL_WIDTH_PX,+ "w": THUMBNAIL_WIDTH_PARAM,"quality": settings.THUMBNAIL_QUALITY,})@@ -126,7 +132,7 @@ def test_get_successful_with_auth_key_default_args(mock_image_data, auth_key):pook.get(PHOTON_URL_FOR_TEST_IMAGE).params({- "w": settings.THUMBNAIL_WIDTH_PX,+ "w": THUMBNAIL_WIDTH_PARAM,"quality": settings.THUMBNAIL_QUALITY,})@@ -149,7 +155,7 @@ def test_get_successful_no_auth_key_not_compressed(mock_image_data):pook.get(PHOTON_URL_FOR_TEST_IMAGE).params({- "w": settings.THUMBNAIL_WIDTH_PX,+ "w": THUMBNAIL_WIDTH_PARAM,}).header("User-Agent", UA_HEADER)@@ -210,7 +216,7 @@ def test_get_successful_no_auth_key_png_only(mock_image_data):pook.get(PHOTON_URL_FOR_TEST_IMAGE).params({- "w": settings.THUMBNAIL_WIDTH_PX,+ "w": THUMBNAIL_WIDTH_PARAM,"quality": settings.THUMBNAIL_QUALITY,})@@ -233,7 +239,7 @@ def test_get_successful_forward_query_params(mock_image_data):pook.get(PHOTON_URL_FOR_TEST_IMAGE).params({- "w": settings.THUMBNAIL_WIDTH_PX,+ "w": THUMBNAIL_WIDTH_PARAM,"quality": settings.THUMBNAIL_QUALITY,"q": params,}@@ -275,7 +281,7 @@ def test_get_successful_records_response_code(pook.get(PHOTON_URL_FOR_TEST_IMAGE).params({- "w": settings.THUMBNAIL_WIDTH_PX,+ "w": THUMBNAIL_WIDTH_PARAM,"quality": settings.THUMBNAIL_QUALITY,})@@ -430,7 +436,7 @@ def test_caches_failures_if_cache_surpasses_tolerance(mock_image_data, settings,pook.get(PHOTON_URL_FOR_TEST_IMAGE).params({- "w": settings.THUMBNAIL_WIDTH_PX,+ "w": THUMBNAIL_WIDTH_PARAM,"quality": settings.THUMBNAIL_QUALITY,})@@ -512,7 +518,7 @@ def test_get_successful_https_image_url_sends_ssl_parameter(mock_image_data):pook.get(PHOTON_URL_FOR_TEST_IMAGE).params({- "w": settings.THUMBNAIL_WIDTH_PX,+ "w": THUMBNAIL_WIDTH_PARAM,"quality": settings.THUMBNAIL_QUALITY,"ssl": "true",}@@ -640,3 +646,249 @@ def test_photon_get_saves_image_type_to_cache("Redis connect failed, cannot cache image extension.",])++[email protected](start_active=False)+def test_wikimedia_thumbnail_default_params_small_image():+ image_url = (+ "https://upload.wikimedia.org/wikipedia/commons/9/9e/Color_icon_yellow.svg"+ )+ width = settings.THUMBNAIL_WIDTH_PX - 1+ image = ImageFactory.create(url=image_url, provider="wikimedia", width=width)+ # It uses the image width to prevent wikimedia's thumbnail service upscaling the image+ expected_thumbnail_url_path = f"upload.wikimedia.org/wikipedia/commons/thumb/9/9e/Color_icon_yellow.svg/lossy-{width}px-Color_icon_yellow.svg.png"++ pook.on()+ (+ pook.get(settings.PHOTON_ENDPOINT + expected_thumbnail_url_path)+ .params(+ {+ "ssl": "true",+ }+ )+ .header("User-Agent", UA_HEADER)+ .header("Accept", "image/*")+ .reply(200)+ .body(MOCK_BODY)+ )++ photon_get(+ MediaInfo(+ media_identifier=image.identifier,+ media_provider=image.provider,+ image_url=image_url,+ width=image.width,+ )+ )++[email protected](start_active=False)+def test_wikimedia_thumbnail_default_params_large_image():+ image_url = (+ "https://upload.wikimedia.org/wikipedia/commons/9/9e/Color_icon_yellow.svg"+ )+ width = settings.THUMBNAIL_WIDTH_PX + 1+ image = ImageFactory.create(url=image_url, provider="wikimedia", width=width)+ # Uses the default thumbnail setting because that value is smaller than the width of the image+ expected_thumbnail_url_path = f"upload.wikimedia.org/wikipedia/commons/thumb/9/9e/Color_icon_yellow.svg/lossy-{settings.THUMBNAIL_WIDTH_PX}px-Color_icon_yellow.svg.png"++ pook.on()+ (+ pook.get(settings.PHOTON_ENDPOINT + expected_thumbnail_url_path)+ .params(+ {+ "ssl": "true",+ }+ )+ .header("User-Agent", UA_HEADER)+ .header("Accept", "image/*")+ .reply(200)+ .body(MOCK_BODY)+ )++ photon_get(+ MediaInfo(+ media_identifier=image.identifier,+ media_provider=image.provider,+ image_url=image_url,+ width=image.width,+ )+ )++[email protected](start_active=False)+def test_wikimedia_thumbnail_default_params_unknown_width():+ image_url = (+ "https://upload.wikimedia.org/wikipedia/commons/9/9e/Color_icon_yellow.svg"+ )+ image = ImageFactory.create(url=image_url, provider="wikimedia")+ # Uses the default thumbnail setting because the actual image size is unknown+ expected_thumbnail_url_path = f"upload.wikimedia.org/wikipedia/commons/thumb/9/9e/Color_icon_yellow.svg/lossy-{settings.THUMBNAIL_WIDTH_PX}px-Color_icon_yellow.svg.png"++ pook.on()+ (+ pook.get(settings.PHOTON_ENDPOINT + expected_thumbnail_url_path)+ .params(+ {+ "ssl": "true",+ }+ )+ .header("User-Agent", UA_HEADER)+ .header("Accept", "image/*")+ .reply(200)+ .body(MOCK_BODY)+ )++ photon_get(+ MediaInfo(+ media_identifier=image.identifier,+ media_provider=image.provider,+ image_url=image_url,+ width=None,+ )+ )++[email protected](start_active=False)+def test_wikimedia_thumbnail_full_size_params():+ image_url = (+ "https://upload.wikimedia.org/wikipedia/commons/9/9e/Color_icon_yellow.svg"+ )+ image = ImageFactory.create(url=image_url, provider="wikimedia")+ expected_thumbnail_url_path = f"upload.wikimedia.org/wikipedia/commons/thumb/9/9e/Color_icon_yellow.svg/lossy-{image.width}px-Color_icon_yellow.svg.png"++ pook.on()+ (+ pook.get(settings.PHOTON_ENDPOINT + expected_thumbnail_url_path)+ .params(+ {+ "ssl": "true",+ }+ )+ .header("User-Agent", UA_HEADER)+ .header("Accept", "image/*")+ .reply(200)+ .body(MOCK_BODY)+ )++ photon_get(+ MediaInfo(+ media_identifier=image.identifier,+ media_provider=image.provider,+ image_url=image_url,+ width=image.width,+ ),+ request_config=RequestConfig(is_full_size=True),+ )++[email protected](start_active=False)+def test_wikimedia_thumbnail_uncompressed_params():+ image_url = (+ "https://upload.wikimedia.org/wikipedia/commons/9/9e/Color_icon_yellow.svg"+ )+ # ensure image width is larger than the default so we can reliably assert it is _not_ pulling the full-size image+ # if width is smaller than the default, even if we request full size, it will always use the images actual width+ # to prevent wikimedia's thumbnail service from upscaling the image, which it will do if the requested width is+ # larger than the actual width of the image+ width = settings.THUMBNAIL_WIDTH_PX + 1+ image = ImageFactory.create(url=image_url, provider="wikimedia", width=width)+ expected_thumbnail_url_path = f"upload.wikimedia.org/wikipedia/commons/thumb/9/9e/Color_icon_yellow.svg/{settings.THUMBNAIL_WIDTH_PX}px-Color_icon_yellow.svg.png"++ pook.on()+ (+ pook.get(settings.PHOTON_ENDPOINT + expected_thumbnail_url_path)+ .params(+ {+ "ssl": "true",+ }+ )+ .header("User-Agent", UA_HEADER)+ .header("Accept", "image/*")+ .reply(200)+ .body(MOCK_BODY)+ )++ photon_get(+ MediaInfo(+ media_identifier=image.identifier,+ media_provider=image.provider,+ image_url=image_url,+ width=image.width,+ ),+ request_config=RequestConfig(is_compressed=False),+ )++[email protected](start_active=False)+def test_wikimedia_thumbnail_uncompressed_full_size_params():+ image_url = (+ "https://upload.wikimedia.org/wikipedia/commons/9/9e/Color_icon_yellow.svg"+ )+ image = ImageFactory.create(url=image_url, provider="wikimedia")+ expected_thumbnail_url_path = f"upload.wikimedia.org/wikipedia/commons/thumb/9/9e/Color_icon_yellow.svg/{image.width}px-Color_icon_yellow.svg.png"++ pook.on()+ (+ pook.get(settings.PHOTON_ENDPOINT + expected_thumbnail_url_path)+ .params(+ {+ "ssl": "true",+ }+ )+ .header("User-Agent", UA_HEADER)+ .header("Accept", "image/*")+ .reply(200)+ .body(MOCK_BODY)+ )++ photon_get(+ MediaInfo(+ media_identifier=image.identifier,+ media_provider=image.provider,+ image_url=image_url,+ width=image.width,+ ),+ request_config=RequestConfig(is_compressed=False, is_full_size=True),+ )++[email protected](start_active=False)+def test_wikimedia_thumbnail_unknown_url_format():+ image_url = "https://upload.wikimedia.org/path_prefix/Color_icon_yellow.jpg"+ image = ImageFactory.create(url=image_url, provider="wikimedia")+ expected_thumbnail_url_path = (+ "upload.wikimedia.org/path_prefix/Color_icon_yellow.jpg"+ )++ pook.on()+ (+ pook.get(settings.PHOTON_ENDPOINT + expected_thumbnail_url_path)+ .params(+ {+ "ssl": "true",+ "w": THUMBNAIL_WIDTH_PARAM,+ "quality": settings.THUMBNAIL_QUALITY,+ }+ )+ .header("User-Agent", UA_HEADER)+ .header("Accept", "image/*")+ .reply(200)+ .body(MOCK_BODY)+ )++ photon_get(+ MediaInfo(+ media_identifier=image.identifier,+ media_provider=image.provider,+ image_url=image_url,+ width=image.width,+ ),+ )diff --git a/api/test/unit/views/test_image_views.py b/api/test/unit/views/test_image_views.pyindex dd3e8dd66..daa5e2db5 100644--- a/api/test/unit/views/test_image_views.py+++ b/api/test/unit/views/test_image_views.py@@ -43,6 +43,7 @@ def test_thumbnail_uses_upstream_thumb_for_smk():thumb_url = "http://iip.smk.dk/thumb.jpg" if smk_has_thumb else Noneimage = ImageFactory.create(+ provider="smk",url="http://iip.smk.dk/image.jpg",thumbnail=thumb_url,)