Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Handle Science Museum errors with batches larger than 50 pages (#905)
Staci Cooper4a6e1b9c6b16
diff --git a/DAGs.md b/DAGs.mdindex a5759a2be..3e0a57d78 100644--- a/DAGs.md+++ b/DAGs.md@@ -77,7 +77,7 @@ The following are DAGs grouped by their primary tag:| `nypl_workflow` | `@monthly` | `False` | image || [`phylopic_workflow`](#phylopic_workflow) | `@daily` | `True` | image || [`rawpixel_workflow`](#rawpixel_workflow) | `@monthly` | `False` | image |-| `science_museum_workflow` | `@monthly` | `False` | image |+| [`science_museum_workflow`](#science_museum_workflow) | `@monthly` | `False` | image || [`smithsonian_workflow`](#smithsonian_workflow) | `@weekly` | `False` | image || `smk_workflow` | `@monthly` | `False` | image || [`stocksnap_workflow`](#stocksnap_workflow) | `@monthly` | `False` | image |@@ -123,6 +123,7 @@ The following is documentation associated with each DAG (where available):1. [`recreate_audio_popularity_calculation`](#recreate_audio_popularity_calculation)1. [`recreate_image_popularity_calculation`](#recreate_image_popularity_calculation)1. [`report_pending_reported_media`](#report_pending_reported_media)+ 1. [`science_museum_workflow`](#science_museum_workflow)1. [`smithsonian_workflow`](#smithsonian_workflow)1. [`stocksnap_workflow`](#stocksnap_workflow)1. [`wikimedia_commons_workflow`](#wikimedia_commons_workflow)@@ -560,6 +561,20 @@ taken. If a record has been reported multiple times, it only needs to bereviewed once and so is only counted once in the reporting by this DAG.+## `science_museum_workflow`+++Content Provider: Science Museum++ETL Process: Use the API to identify all CC-licensed images.++Output: TSV file containing the image, the respective+ meta-data.++Notes: https://github.com/TheScienceMuseum/collectionsonline/wiki/Collections-Online-API # noqa+ Rate limited, no specific rate given.++## `smithsonian_workflow`diff --git a/openverse_catalog/dags/providers/factory_utils.py b/openverse_catalog/dags/providers/factory_utils.pyindex ae8ecd335..ea2ac8354 100644--- a/openverse_catalog/dags/providers/factory_utils.py+++ b/openverse_catalog/dags/providers/factory_utils.py@@ -37,7 +37,7 @@ def generate_tsv_filenames(f"Initializing ProviderIngester {ingester_class.__name__} in"f"order to generate store filenames.")- ingester = ingester_class(dag_run.conf, *args)+ ingester = ingester_class(dag_run.conf, dag_run.dag_id, *args)stores = ingester.media_stores# Push the media store output paths to XComs.@@ -75,7 +75,7 @@ def pull_media_wrapper(# Initialize the ProviderDataIngester class, which will initialize the# media stores and DelayedRequester.logger.info(f"Initializing ProviderIngester {ingester_class.__name__}")- ingester = ingester_class(dag_run.conf, *args)+ ingester = ingester_class(dag_run.conf, dag_run.dag_id, *args)stores = ingester.media_storesfor store, tsv_filename in zip(stores.values(), tsv_filenames):diff --git a/openverse_catalog/dags/providers/provider_api_scripts/provider_data_ingester.py b/openverse_catalog/dags/providers/provider_api_scripts/provider_data_ingester.pyindex 84031cad6..5b3560072 100644--- a/openverse_catalog/dags/providers/provider_api_scripts/provider_data_ingester.py+++ b/openverse_catalog/dags/providers/provider_api_scripts/provider_data_ingester.py@@ -93,10 +93,12 @@ class ProviderDataIngester(ABC):"""pass- def __init__(self, conf: dict = None, date: str = None):+ def __init__(self, conf: dict = None, dag_id: str = None, date: str = None):"""Optional Arguments:+conf: The configuration dict for the running DagRun+ dag_id: The id of the running provider DAGdate: Date String in the form YYYY-MM-DD. This is the date forwhich running the script will pull data"""@@ -122,6 +124,7 @@ class ProviderDataIngester(ABC):)self.media_stores = self._init_media_stores()self.date = date+ self.dag_id = dag_id or ""# dag_run configuration optionsconf = conf or {}diff --git a/openverse_catalog/dags/providers/provider_api_scripts/science_museum.py b/openverse_catalog/dags/providers/provider_api_scripts/science_museum.pyindex 5a2f465e2..a99ee9940 100644--- a/openverse_catalog/dags/providers/provider_api_scripts/science_museum.py+++ b/openverse_catalog/dags/providers/provider_api_scripts/science_museum.py@@ -1,6 +1,19 @@+"""+Content Provider: Science Museum++ETL Process: Use the API to identify all CC-licensed images.++Output: TSV file containing the image, the respective+ meta-data.++Notes: https://github.com/TheScienceMuseum/collectionsonline/wiki/Collections-Online-API # noqa+ Rate limited, no specific rate given.+"""import loggingimport re+from datetime import date+from common import slackfrom common.licenses import get_license_infofrom common.loader import provider_details as provfrom providers.provider_api_scripts.provider_data_ingester import ProviderDataIngester@@ -12,21 +25,6 @@ LIMIT = 100CC0_LICENSE = get_license_info(license_="cc0", license_version="1.0")-YEAR_RANGES = [- (0, 1500),- (1500, 1750),- (1750, 1825),- (1825, 1850),- (1850, 1875),- (1875, 1900),- (1900, 1915),- (1915, 1940),- (1940, 1965),- (1965, 1990),- (1990, 2020),- (2020, 2023),-]-class ScienceMuseumDataIngester(ProviderDataIngester):providers = {"image": prov.SCIENCE_DEFAULT_PROVIDER}@@ -40,31 +38,59 @@ class ScienceMuseumDataIngester(ProviderDataIngester):# instance variable to prevent duplicate recordsself.RECORD_IDS = set()+ # track page number as instance variable so we can more+ # easily detect when the page limit is reached+ self.page_number = 0++ @staticmethod+ def _get_year_ranges(final_year: int) -> list[tuple[int, int]]:+ """+ The Science Museum API currently raises a 400 when attempting to access+ any page number higher than 50+ (https://github.com/TheScienceMuseum/collectionsonline/issues/1470).++ To avoid this, we ingest data for small ranges of years at a time,+ in order to split the data into batches less than 50 pages each.+ Because more recent data is more numerous, the length of the year+ ranges decreases as they get closer to the current day.+ """+ # Start with some very large ranges for old data+ year_ranges = [+ (0, 1500),+ (1500, 1750),+ ]+ # Add a range for every 25 years between 1750 and 1875+ year_ranges.extend([(x, x + 25) for x in range(1750, 1875, 25)])+ # Add a range for every 10 years between 1875 and 'next year'+ # relative to when the DAG is being run.+ year_ranges.extend(+ [(x, min(x + 10, final_year)) for x in range(1875, final_year, 10)]+ )+ return year_ranges+def ingest_records(self, **kwargs):- for year_range in YEAR_RANGES:+ next_year = date.today().year + 1+ for year_range in self._get_year_ranges(next_year):logger.info(f"==Starting on year range: {year_range}==")super().ingest_records(year_range=year_range)def get_next_query_params(self, prev_query_params, **kwargs):from_, to_ = kwargs["year_range"]if not prev_query_params:- # Return default query params on the first request- return {- "has_image": 1,- "image_license": "CC",- "page[size]": LIMIT,- "page[number]": 0,- "date[from]": from_,- "date[to]": to_,- }+ # Reset the page number to 0+ self.page_number = 0else:- # Increment `skip` by the batch limit.- return {- **prev_query_params,- "date[from]": from_,- "date[to]": to_,- "page[number]": prev_query_params["page[number]"] + 1,- }+ # Increment the page number+ self.page_number += 1++ return {+ "has_image": 1,+ "image_license": "CC",+ "page[size]": LIMIT,+ "page[number]": self.page_number,+ "date[from]": from_,+ "date[to]": to_,+ }def get_media_type(self, record):# This provider only supports Images.@@ -224,11 +250,29 @@ class ScienceMuseumDataIngester(ProviderDataIngester):return Nonedef get_should_continue(self, response_json) -> bool:- return response_json.get("links", {}).get("next") is not None+ next_page_url = response_json.get("links", {}).get("next")++ # No more data left to process+ if next_page_url is None:+ return False++ # Special case where we must halt ingestion early to prevent+ # external API errors caused by accessing a page number higher+ # than 50.+ if self.page_number == 50:+ current_url = response_json.get("links", {}).get("self")+ message = (+ f"Request {current_url} contains more than 50 pages of"+ " data and cannot be fully ingested. Reduce the size of"+ " the year range in order to complete ingestion."+ )+ slack.send_alert(message, dag_id=self.dag_id)+ return False++ return Truedef main():- logger.info("Begin: Science Museum data ingestion")ingester = ScienceMuseumDataIngester()ingester.ingest_records()diff --git a/openverse_catalog/dags/providers/provider_api_scripts/wikimedia_commons.py b/openverse_catalog/dags/providers/provider_api_scripts/wikimedia_commons.pyindex b9eea7e84..dd9aa7d88 100644--- a/openverse_catalog/dags/providers/provider_api_scripts/wikimedia_commons.py+++ b/openverse_catalog/dags/providers/provider_api_scripts/wikimedia_commons.py@@ -54,11 +54,11 @@ class WikimediaCommonsDataIngester(ProviderDataIngester):# the exact limit may not be respected.batch_limit = 250- def __init__(self, conf: dict = None, date: str | None = None):- self.start_timestamp, self.end_timestamp = self.derive_timestamp_pair(date)- self.continue_token = {}+ def __init__(self, *args, **kwargs):+ super().__init__(*args, **kwargs)- super().__init__(conf, date)+ self.start_timestamp, self.end_timestamp = self.derive_timestamp_pair(self.date)+ self.continue_token = {}def get_next_query_params(self, prev_query_params, **kwargs):return {diff --git a/tests/dags/providers/provider_api_scripts/test_science_museum.py b/tests/dags/providers/provider_api_scripts/test_science_museum.pyindex dd5a23b24..486f568d6 100644--- a/tests/dags/providers/provider_api_scripts/test_science_museum.py+++ b/tests/dags/providers/provider_api_scripts/test_science_museum.py@@ -67,6 +67,26 @@ default_params = {}+def test_get_year_ranges():+ # Expected list when using 1923 as the final year+ expected_list = [+ (0, 1500),+ (1500, 1750),+ (1750, 1775),+ (1775, 1800),+ (1800, 1825),+ (1825, 1850),+ (1850, 1875),+ (1875, 1885),+ (1885, 1895),+ (1895, 1905),+ (1905, 1915),+ (1915, 1923),+ ]+ actual_list = sm._get_year_ranges(1923)+ assert actual_list == expected_list++def test_get_query_param_default():actual_param = sm.get_next_query_params({}, **{"year_range": (0, 1500)})expected_param = default_params | {@@ -79,6 +99,8 @@ def test_get_query_param_default():def test_get_query_param_offset_page_number():+ sm = ScienceMuseumDataIngester()+ sm.page_number = 10actual_param = sm.get_next_query_params(default_params | {"page[number]": 10}, **{"year_range": (1500, 2000)})@@ -329,10 +351,36 @@ def test_handle_obj_data_none(object_data):assert actual_images is None-def test_get_should_continue():- response_json = {"links": {"next": ""}}-- assert sm.get_should_continue(response_json) is True+ "next_url, page_number, should_continue, should_alert",+ [+ # Happy path, should continue+ (+ "https://collection.sciencemuseumgroup.org.uk/search/date[from]/1875/date[to]/1900/images/image_license?page[size]=100&page[number]=20",+ 20,+ True,+ False,+ ),+ # Don't continue when next_url is None, regardless of page number+ (None, 20, False, False),+ (None, 50, False, False),+ # Don't continue and DO alert when page number is 50 and there is a next_url+ (+ "https://collection.sciencemuseumgroup.org.uk/search/date[from]/1875/date[to]/1900/images/image_license?page[size]=100&page[number]=50",+ 50,+ False,+ True,+ ),+ ],+)+def test_get_should_continue(next_url, page_number, should_continue, should_alert):+ response_json = {"links": {"next": next_url}}+ sm = ScienceMuseumDataIngester()+ sm.page_number = page_number++ with patch("common.slack.send_alert") as send_alert_mock:+ assert sm.get_should_continue(response_json) == should_continue+ assert send_alert_mock.called == should_alertdef test_get_should_continue_last_page():diff --git a/tests/dags/providers/test_factory_utils.py b/tests/dags/providers/test_factory_utils.pyindex 1c3646636..754dd6a41 100644--- a/tests/dags/providers/test_factory_utils.py+++ b/tests/dags/providers/test_factory_utils.py@@ -32,7 +32,7 @@ def internal_func_mock():fdi = FakeDataIngester()-def _set_up_ingester(mock_conf, mock_func, value):+def _set_up_ingester(mock_conf, mock_dag_id, mock_func, value):"""Set up ingest records as a proxy for calling the mock function, then returnthe instance. This is necessary because the args are only handed in during