Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Refactor Metropolitan Museum of Art to use ProviderDataIngester (#674)

rwidom8ac257cde51f
diff --git a/DAGs.md b/DAGs.md
index 727b0565e..bae0c526d 100644
--- a/DAGs.md
+++ b/DAGs.md
@@ -349,8 +349,23 @@ ETL Process: Use the API to identify all CC0 artworks.
Output: TSV file containing the image, their respective
meta-data.
-Notes: https://metmuseum.github.io/
- No rate limit specified.
+Notes: https://metmuseum.github.io/#search
+ "Please limit requests to 80 requests per second." May need to
+ bump up the delay (e.g. to 3 seconds), to avoid of blocking
+ during local development testing.
+
+ Some analysis to improve data quality was conducted using a
+ separate csv file here: https://github.com/metmuseum/openaccess
+
+ Get a list of object IDs:
+ https://collectionapi.metmuseum.org/public/collection/v1/objects?metadataDate=2022-08-10
+ Get a specific object:
+ https://collectionapi.metmuseum.org/public/collection/v1/objects/1027
+ The search functionality requires a specific query (term search)
+ in addition to date and public domain. It seems like it won't
+ connect with just date and license.
+ https://collectionapi.metmuseum.org/public/collection/v1/search?isPublicDomain=true&metadataDate=2022-08-07
+
diff --git a/openverse_catalog/dags/common/loader/provider_details.py b/openverse_catalog/dags/common/loader/provider_details.py
index a54c57ca4..e9e6eab49 100644
--- a/openverse_catalog/dags/common/loader/provider_details.py
+++ b/openverse_catalog/dags/common/loader/provider_details.py
@@ -20,6 +20,7 @@ WIKIMEDIA_DEFAULT_PROVIDER = "wikimedia"
SMITHSONIAN_DEFAULT_PROVIDER = "smithsonian"
BROOKLYN_DEFAULT_PROVIDER = "brooklynmuseum"
CLEVELAND_DEFAULT_PROVIDER = "clevelandmuseum"
+METROPOLITAN_MUSEUM_DEFAULT_PROVIDER = "met"
VICTORIA_DEFAULT_PROVIDER = "museumsvictoria"
NYPL_DEFAULT_PROVIDER = "nypl"
RAWPIXEL_DEFAULT_PROVIDER = "rawpixel"
diff --git a/openverse_catalog/dags/providers/provider_api_scripts/metropolitan_museum.py b/openverse_catalog/dags/providers/provider_api_scripts/metropolitan_museum.py
index bff094b7d..40d83288b 100644
--- a/openverse_catalog/dags/providers/provider_api_scripts/metropolitan_museum.py
+++ b/openverse_catalog/dags/providers/provider_api_scripts/metropolitan_museum.py
@@ -6,138 +6,178 @@ ETL Process: Use the API to identify all CC0 artworks.
Output: TSV file containing the image, their respective
meta-data.
-Notes: https://metmuseum.github.io/
- No rate limit specified.
+Notes: https://metmuseum.github.io/#search
+ "Please limit requests to 80 requests per second." May need to
+ bump up the delay (e.g. to 3 seconds), to avoid of blocking
+ during local development testing.
+
+ Some analysis to improve data quality was conducted using a
+ separate csv file here: https://github.com/metmuseum/openaccess
+
+ Get a list of object IDs:
+ https://collectionapi.metmuseum.org/public/collection/v1/objects?metadataDate=2022-08-10
+ Get a specific object:
+ https://collectionapi.metmuseum.org/public/collection/v1/objects/1027
+ The search functionality requires a specific query (term search)
+ in addition to date and public domain. It seems like it won't
+ connect with just date and license.
+ https://collectionapi.metmuseum.org/public/collection/v1/search?isPublicDomain=true&metadataDate=2022-08-07
+
"""
import argparse
import logging
from common.licenses import get_license_info
-from common.requester import DelayedRequester
-from common.storage.image import ImageStore
-
+from common.loader import provider_details as prov
+from provider_data_ingester import ProviderDataIngester
-DELAY = 1.0 # time delay (in seconds)
-PROVIDER = "met"
-ENDPOINT = "https://collectionapi.metmuseum.org/public/collection/v1/objects"
-DEFAULT_LICENSE_INFO = get_license_info(license_="cc0", license_version="1.0")
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s: %(message)s", level=logging.INFO
)
logger = logging.getLogger(__name__)
-delayed_requester = DelayedRequester(DELAY)
-image_store = ImageStore(provider=PROVIDER)
-
-
-def main(date=None):
- """
- This script pulls the data for a given date from the Metropolitan
- Museum of Art API, and writes it into a .TSV file to be eventually
- read into our DB.
-
- Required Arguments:
-
- date: Date String in the form YYYY-MM-DD. This is the date for
- which running the script will pull data.
- """
-
- logger.info(f"Begin: Met Museum API requests for date: {date}")
- fetch_the_object_id = _get_object_ids(date)
- if fetch_the_object_id:
- logger.info(f"Total object found {fetch_the_object_id[0]}")
- _extract_the_data(fetch_the_object_id[1])
-
- total_images = image_store.commit()
- logger.info(f"Total CC0 images received {total_images}")
-
-
-def _get_object_ids(date, endpoint=ENDPOINT):
- query_params = ""
- if date:
- query_params = {"metadataDate": date}
-
- response = _get_response_json(query_params, endpoint)
-
- if response:
- total_object_ids = response["total"]
- object_ids = response["objectIDs"]
- else:
- logger.warning("No content available")
- return None
- return [total_object_ids, object_ids]
-
-
-def _get_response_json(
- query_params,
- endpoint,
- retries=5,
-):
- response_json = delayed_requester.get_response_json(
- endpoint, query_params=query_params, retries=retries
- )
-
- return response_json
-
-
-def _extract_the_data(object_ids):
- for i in object_ids:
- _get_data_for_image(i)
-
-
-def _get_data_for_image(object_id):
- object_json = _get_and_validate_object_json(object_id)
- if not object_json:
- logger.warning(f"Could not retrieve object_json for object_id: {object_id}")
- return
-
- main_image = object_json.get("primaryImage")
- other_images = object_json.get("additionalImages", [])
- image_list = [main_image] + other_images
-
- meta_data = _create_meta_data(object_json)
-
- for img in image_list:
- foreign_id = _build_foreign_id(object_id, img)
- image_store.add_item(
- foreign_landing_url=object_json.get("objectURL"),
- image_url=img,
- license_info=DEFAULT_LICENSE_INFO,
- foreign_identifier=foreign_id,
- creator=object_json.get("artistDisplayName"),
- title=object_json.get("title"),
- meta_data=meta_data,
+class MetMuseumDataIngester(ProviderDataIngester):
+ providers = {"image": prov.METROPOLITAN_MUSEUM_DEFAULT_PROVIDER}
+ endpoint = "https://collectionapi.metmuseum.org/public/collection/v1/objects"
+ DEFAULT_LICENSE_INFO = get_license_info(license_="cc0", license_version="1.0")
+
+ # adding args for automatically generated parameters from generate_tsv_filenames
+ def __init__(self, conf: dict = None, date: str = None):
+ super(MetMuseumDataIngester, self).__init__(conf=conf, date=date)
+ self.retries = 5
+
+ # Default to empty dict to avoid break in ingest_records. In general, this dag
+ # should not be run without a date, but don't want to completely rule it out.
+ self.query_param = {}
+ if date:
+ self.query_param = {"metadataDate": date}
+
+ # this seems like useful information to track for context on the existing load
+ # metrics, but just adding them to the log in aggregate for now rather than
+ # logging each record individually or doing something fancier in airflow.
+ self.object_ids_retrieved = 0 # total object IDs based on date
+ self.non_cc0_objects = 0 # number checked and ignored because of licensing
+
+ def get_next_query_params(self, prev_query_params=None):
+ return self.query_param
+
+ def get_batch_data(self, response_json):
+ if response_json:
+ self.object_ids_retrieved = response_json["total"]
+ # A single objet d'art may have more than one image (and therefore more
+ # than one record) associated with it, but there are generally on the order
+ # of 10 or fewer records per object.
+ logger.info(f"Total objects found {self.object_ids_retrieved}")
+ return response_json["objectIDs"]
+ else:
+ logger.warning("No content available")
+ return None
+
+ def get_record_data(self, object_id):
+ object_endpoint = f"{self.endpoint}/{object_id}"
+ object_json = self.delayed_requester.get_response_json(
+ object_endpoint, self.retries
)
-
-def _get_and_validate_object_json(object_id, endpoint=ENDPOINT):
- object_endpoint = f"{endpoint}/{object_id}"
- object_json = _get_response_json(None, object_endpoint)
- if not object_json.get("isPublicDomain"):
- logger.warning("CC0 license not detected")
- object_json = None
- return object_json
-
-
-def _build_foreign_id(object_id, image_url):
- unique_identifier = image_url.split("/")[-1].split(".")[0]
- return f"{object_id}-{unique_identifier}"
-
-
-def _create_meta_data(object_json):
- meta_data = {
- "accession_number": object_json.get("accessionNumber"),
- "classification": object_json.get("classification"),
- "culture": object_json.get("culture"),
- "date": object_json.get("objectDate"),
- "medium": object_json.get("medium"),
- "credit_line": object_json.get("creditLine"),
- }
- meta_data = {k: v for k, v in meta_data.items() if v is not None}
- return meta_data
+ if object_json.get("isPublicDomain") is False:
+ self.non_cc0_objects += 1
+ if self.non_cc0_objects % self.batch_limit == 0:
+ logger.info(f"Retrieved {self.non_cc0_objects} non-CC0 objects.")
+ return None
+
+ main_image = object_json.get("primaryImage")
+ other_images = object_json.get("additionalImages", [])
+ image_list = [main_image] + other_images
+
+ meta_data = self._get_meta_data(object_json)
+ raw_tags = self._get_tag_list(object_json)
+ title = self._get_title(object_json)
+ artist = self._get_artist_name(object_json)
+
+ # We aren't currently populating creator_url. In theory we could url encode
+ # f"https://collectionapi.metmuseum.org/public/collection/v1/search?artistOrCulture={artist}"
+ # per API guide here: https://metmuseum.github.io/#search
+ # but it seems fairly buggy (i.e. nonresponsive), at least when tested with
+ # "Chelsea Porcelain Manufactory" and "Minton(s)" and "Jean Pucelle"
+ # Should we use artistWikidata_URL or artistULAN_URL? They're populated approx
+ # 65% of the time.
+
+ return [
+ {
+ "foreign_landing_url": object_json.get("objectURL"),
+ "image_url": img,
+ "license_info": self.DEFAULT_LICENSE_INFO,
+ "foreign_identifier": self._get_foreign_id(object_id, img),
+ "creator": artist,
+ "title": title,
+ "meta_data": meta_data,
+ "raw_tags": raw_tags,
+ }
+ for img in image_list
+ ]
+
+ def get_should_continue(self, response_json):
+ # The met museum search function does not have pagination for the initial list
+ # of object IDs, so after processing the first list, we're done.
+ if response_json:
+ return False
+
+ def _get_foreign_id(self, object_id: int, image_url: str):
+ unique_identifier = image_url.split("/")[-1].split(".")[0]
+ return f"{object_id}-{unique_identifier}"
+
+ def _get_meta_data(self, object_json):
+ if object_json is None:
+ return
+ if object_json.get("accessionNumber"):
+ return {
+ "accession_number": object_json.get("accessionNumber"),
+ }
+
+ def _get_tag_list(self, object_json):
+ if object_json is None:
+ return
+ tag_list = [
+ tag
+ for tag in [
+ object_json.get("department"),
+ object_json.get("medium"),
+ object_json.get("culture"),
+ object_json.get("objectName"),
+ self._get_artist_name(object_json),
+ object_json.get("classification"),
+ object_json.get("objectDate"),
+ object_json.get("creditLine"),
+ object_json.get("period"),
+ ]
+ if tag
+ ]
+ if object_json.get("tags"):
+ tag_list += [tag["term"] for tag in object_json.get("tags")]
+ return tag_list
+
+ def _get_title(self, object_json):
+ if object_json is not None:
+ # Use or to skip false-y (empty) titles: ""
+ return object_json.get("title") or object_json.get("objectName")
+
+ def _get_artist_name(self, object_json):
+ if object_json is None:
+ return
+ return object_json.get("artistDisplayName")
+
+ def get_media_type(self, object_json):
+ # This provider only supports Images.
+ return "image"
+
+
+def main(date: str):
+ logger.info("Begin: Metropolitan Museum data ingestion")
+ ingester = MetMuseumDataIngester(date)
+ ingester.ingest_records()
if __name__ == "__main__":
diff --git a/openverse_catalog/dags/providers/provider_workflows.py b/openverse_catalog/dags/providers/provider_workflows.py
index 0d37a0ab1..6d188b107 100644
--- a/openverse_catalog/dags/providers/provider_workflows.py
+++ b/openverse_catalog/dags/providers/provider_workflows.py
@@ -5,6 +5,7 @@ from typing import Dict, Optional, Sequence, Type
from providers.provider_api_scripts.cleveland_museum import ClevelandDataIngester
from providers.provider_api_scripts.finnish_museums import FinnishMuseumsDataIngester
from providers.provider_api_scripts.inaturalist import INaturalistDataIngester
+from providers.provider_api_scripts.metropolitan_museum import MetMuseumDataIngester
from providers.provider_api_scripts.museum_victoria import VictoriaDataIngester
from providers.provider_api_scripts.provider_data_ingester import ProviderDataIngester
from providers.provider_api_scripts.science_museum import ScienceMuseumDataIngester
@@ -134,6 +135,7 @@ PROVIDER_WORKFLOWS = [
),
ProviderWorkflow(
provider_script="metropolitan_museum",
+ ingester_class=MetMuseumDataIngester,
start_date=datetime(2016, 9, 1),
schedule_string="@daily",
dated=True,
diff --git a/tests/dags/providers/provider_api_scripts/resources/metropolitan_museum_of_art/read_met_csv.py b/tests/dags/providers/provider_api_scripts/resources/metropolitan_museum_of_art/read_met_csv.py
new file mode 100644
index 000000000..7bc90be2e
--- /dev/null
+++ b/tests/dags/providers/provider_api_scripts/resources/metropolitan_museum_of_art/read_met_csv.py
@@ -0,0 +1,162 @@
+"""
+Ad hoc exploratory analysis for identifying test cases for the API workflow.
+To execute this, download MetObjects.csv from here:
+https://github.com/metmuseum/openaccess/blob/master/MetObjects.csv
+"""
+
+from pathlib import Path
+from time import sleep
+
+import pandas as pd
+import requests
+
+
+pd.set_option("display.min_rows", 500)
+pd.set_option("display.width", None)
+
+DIR = Path(__file__).parent
+raw_data_file_name = "MetObjects.csv"
+
+raw_data = pd.read_csv(
+ DIR / raw_data_file_name,
+ header=0,
+ usecols=[
+ "Is Public Domain",
+ "Object ID",
+ "Object Number",
+ "Department",
+ "Object Name",
+ "Title",
+ "Culture",
+ "Artist Display Name",
+ "Medium",
+ "Credit Line",
+ "Classification",
+ "Link Resource",
+ "Tags",
+ "Period",
+ "Object Date",
+ "Artist Wikidata URL",
+ "Artist ULAN URL",
+ ],
+)
+
+# *** object_number is never missing.
+# is_highlight is never missing.
+# is_timeline_work is never missing.
+# gallery_number is missing 85% of values, see 860873
+# *** department is never missing.
+# accessionyear is missing 0% of values, see 854659
+# *** object_name is missing 0% of values, see 854659
+# *** title is missing 10% of values, see 856958
+# *** culture is missing 42% of values, see 860873
+# --> period is missing 71% of values, see 860873
+# dynasty is missing 95% of values, see 860873
+# reign is missing 97% of values, see 860873
+# portfolio is missing 96% of values, see 860873
+# constituent_id is missing 56% of values, see 857718
+# artist_role is missing 57% of values, see 857718
+# artist_prefix is missing 56% of values, see 857718
+# *** artist_display_name is missing 56% of values, see 857718
+# artist_display_bio is missing 57% of values, see 857718
+# artist_suffix is missing 56% of values, see 857718
+# artist_alpha_sort is missing 56% of values, see 857718
+# artist_nationality is missing 56% of values, see 857718
+# artist_begin_date is missing 56% of values, see 857718
+# artist_end_date is missing 56% of values, see 857718
+# artist_gender is missing 86% of values, see 860873
+# artist_ulan_url is missing 64% of values, see 860873
+# artist_wikidata_url is missing 65% of values, see 860873
+# --> object_date is missing 3% of values, see 856790
+# object_begin_date is never missing.
+# object_end_date is never missing.
+# *** medium is missing 0% of values, see 854659
+# dimensions is missing 13% of values, see 856203
+# *** credit_line is missing 0% of values, see 853970
+# geography_type is missing 84% of values, see 860873
+# city is missing 93% of values, see 860873
+# state is missing 99% of values, see 860873
+# county is missing 97% of values, see 860873
+# country is missing 81% of values, see 860873
+# region is missing 92% of values, see 860873
+# subregion is missing 94% of values, see 860873
+# locale is missing 96% of values, see 860873
+# locus is missing 98% of values, see 860873
+# excavation is missing 96% of values, see 860873
+# river is missing 99% of values, see 860873
+# *** classification is missing 13% of values, see 854659
+# rights_and_reproduction is missing 99% of values, see 860873
+# *** link_resource is never missing.
+# object_wikidata_url is missing 93% of values, see 860873
+# metadata_date is always missing.
+# --> repository is never missing, but 1 val: 'Metropolitan Museum of Art, New York, NY'
+# *** tags is missing 41% of values, see 857718
+# tags_aat_url is missing 41% of values, see 857718
+# tags_wikidata_url is missing 41% of values, see 857718
+
+new_column_names = {col: col.lower().replace(" ", "_") for col in raw_data.columns}
+raw_data.rename(columns=new_column_names, inplace=True)
+
+print("--> Column names:", "\n".join(raw_data.columns), sep="\n")
+print("--> Licensing:", raw_data.is_public_domain.value_counts(dropna=False), sep="\n")
+
+raw_data.set_index("object_id", inplace=True)
+raw_data.drop(raw_data[raw_data["is_public_domain"] == 0].index, inplace=True)
+raw_data.drop(["is_public_domain"], axis=1, inplace=True)
+
+raw_data["possible_creator_url"] = raw_data.artist_ulan_url.fillna(
+ raw_data.artist_wikidata_url
+)
+
+total_records = len(raw_data)
+print(f"--> Total CC0 records: {total_records}")
+print("--> Percent populated for different fields...")
+sample_cases = set()
+for c in raw_data.columns:
+ m = raw_data[c].isna().sum()
+ if m == total_records:
+ print(f"{c} is always missing.")
+ elif m > 0:
+ example = max(raw_data[raw_data[c].isna()].index)
+ sample_cases.add(example)
+ print(f"{c} is missing {int(100.0*m/total_records)}% of values, see {example}")
+ else:
+ print(f"{c} is never missing.")
+
+# add existing test cases
+sample_cases = sample_cases.union([45733, 45734, 1027])
+# from https://github.com/WordPress/openverse-catalog/issues/641
+sample_cases = sample_cases.union([855619, 479, 747045, 5915, 4542])
+
+for object_id in sample_cases:
+ print(f"Requesting {object_id}... ", end="")
+ file_name = f"sample_response_{object_id}.json"
+ object_url = (
+ f"https://collectionapi.metmuseum.org/public/collection/v1/objects/{object_id}"
+ )
+ response = requests.get(object_url)
+ if response.json():
+ with open(DIR / file_name, "w") as f:
+ f.write(response.text)
+ print(":) YAY!")
+ else:
+ print(":( no response")
+ sleep(5)
+
+print("handle missing titles...")
+print(
+ raw_data[["title", "object_name", "classification", "artist_display_name"]].query(
+ "not(title == title)"
+ )
+)
+
+print("artist display names...")
+print(
+ raw_data.query(
+ "artist_display_name == 'Unidentified' "
+ + "or artist_display_name == 'Unidentified artist'"
+ ).artist_display_name.value_counts()
+)
+
+print("medium...")
+print(raw_data.medium.value_counts())
diff --git a/tests/dags/providers/provider_api_scripts/resources/metropolitan_museum_of_art/sample_additional_image_data.json b/tests/dags/providers/provider_api_scripts/resources/metropolitan_museum_of_art/sample_additional_image_data.json
index 0abff3fd9..7c6ea7386 100644
--- a/tests/dags/providers/provider_api_scripts/resources/metropolitan_museum_of_art/sample_additional_image_data.json
+++ b/tests/dags/providers/provider_api_scripts/resources/metropolitan_museum_of_art/sample_additional_image_data.json
@@ -1,18 +1,86 @@
-{
- "creator": "Kiyohara Yukinobu",
- "foreign_identifier": "45734-1",
- "foreign_landing_url": "https://www.metmuseum.org/art/collection/search/45734",
- "image_url": "https://images.metmuseum.org/CRDImages/as/original/DP251120.jpg",
- "license_": "cc0",
- "license_version": "1.0",
- "meta_data": {
- "accession_number": "36.100.45",
- "classification": "Paintings",
- "credit_line": "The Howard Mansfield Collection, Purchase, Rogers Fund, 1936",
- "culture": "Japan",
- "date": "late 17th century",
- "medium": "Hanging scroll; ink and color on silk"
+[
+ {
+ "creator": "Kiyohara Yukinobu",
+ "foreign_identifier": "45734-DP251139",
+ "foreign_landing_url": "https://wwwstg.metmuseum.org/art/collection/search/45734",
+ "image_url": "https://images.metmuseum.org/CRDImages/as/original/DP251139.jpg",
+ "license_info": {
+ "license": "cc0",
+ "url": "https://creativecommons.org/publicdomain/zero/1.0/",
+ "version": "1.0"
+ },
+ "meta_data": {
+ "accession_number": "36.100.45"
+ },
+ "raw_tags": [
+ "Asian Art",
+ "Hanging scroll; ink and color on silk",
+ "Japan",
+ "Hanging scroll",
+ "Kiyohara Yukinobu",
+ "Paintings",
+ "late 17th century",
+ "The Howard Mansfield Collection, Purchase, Rogers Fund, 1936",
+ "Edo period (1615\u20131868)",
+ "Birds",
+ "Leaves"
+ ],
+ "title": "Quail and Millet"
},
- "thumbnail_url": "",
- "title": "Quail and Millet"
-}
+ {
+ "creator": "Kiyohara Yukinobu",
+ "foreign_identifier": "45734-DP251138",
+ "foreign_landing_url": "https://wwwstg.metmuseum.org/art/collection/search/45734",
+ "image_url": "https://images.metmuseum.org/CRDImages/as/original/DP251138.jpg",
+ "license_info": {
+ "license": "cc0",
+ "url": "https://creativecommons.org/publicdomain/zero/1.0/",
+ "version": "1.0"
+ },
+ "meta_data": {
+ "accession_number": "36.100.45"
+ },
+ "raw_tags": [
+ "Asian Art",
+ "Hanging scroll; ink and color on silk",
+ "Japan",
+ "Hanging scroll",
+ "Kiyohara Yukinobu",
+ "Paintings",
+ "late 17th century",
+ "The Howard Mansfield Collection, Purchase, Rogers Fund, 1936",
+ "Edo period (1615\u20131868)",
+ "Birds",
+ "Leaves"
+ ],
+ "title": "Quail and Millet"
+ },
+ {
+ "creator": "Kiyohara Yukinobu",
+ "foreign_identifier": "45734-DP251120",
+ "foreign_landing_url": "https://wwwstg.metmuseum.org/art/collection/search/45734",
+ "image_url": "https://images.metmuseum.org/CRDImages/as/original/DP251120.jpg",
+ "license_info": {
+ "license": "cc0",
+ "url": "https://creativecommons.org/publicdomain/zero/1.0/",
+ "version": "1.0"
+ },
+ "meta_data": {
+ "accession_number": "36.100.45"
+ },
+ "raw_tags": [
+ "Asian Art",
+ "Hanging scroll; ink and color on silk",
+ "Japan",
+ "Hanging scroll",
+ "Kiyohara Yukinobu",
+ "Paintings",
+ "late 17th century",
+ "The Howard Mansfield Collection, Purchase, Rogers Fund, 1936",
+ "Edo period (1615\u20131868)",
+ "Birds",
+ "Leaves"
+ ],
+ "title": "Quail and Millet"
+ }
+]
diff --git a/tests/dags/providers/provider_api_scripts/resources/metropolitan_museum_of_art/sample_image_data.json b/tests/dags/providers/provider_api_scripts/resources/metropolitan_museum_of_art/sample_image_data.json
index 1a0573c22..403b2680a 100644
--- a/tests/dags/providers/provider_api_scripts/resources/metropolitan_museum_of_art/sample_image_data.json
+++ b/tests/dags/providers/provider_api_scripts/resources/metropolitan_museum_of_art/sample_image_data.json
@@ -1,16 +1,26 @@
-{
- "creator": "Kiyohara Yukinobu",
- "foreign_identifier": 45734,
- "foreign_landing_url": "https://wwwstg.metmuseum.org/art/collection/search/45734",
- "image_url": "https://images.metmuseum.org/CRDImages/as/original/DP251139.jpg",
- "license": "cc0",
- "license_version": "1.0",
- "meta_data": {
- "accession_number": "36.100.45",
- "classification": "Paintings",
- "credit_line": "The Howard Mansfield Collection, Purchase, Rogers Fund, 1936",
- "culture": "Japan"
- },
- "thumbnail_url": "https://images.metmuseum.org/CRDImages/as/web-large/DP251139.jpg",
- "title": "Quail and Millet"
-}
+[
+ {
+ "creator": "",
+ "foreign_identifier": "47533-79_2_414b_S1_sf",
+ "foreign_landing_url": "https://www.metmuseum.org/art/collection/search/47533",
+ "image_url": "https://images.metmuseum.org/CRDImages/as/original/79_2_414b_S1_sf.jpg",
+ "license_info": {
+ "license": "cc0",
+ "url": "https://creativecommons.org/publicdomain/zero/1.0/",
+ "version": "1.0"
+ },
+ "meta_data": {
+ "accession_number": "79.2.414b"
+ },
+ "raw_tags": [
+ "Asian Art",
+ "Porcelain painted in underglaze blue",
+ "China",
+ "Cover",
+ "Ceramics",
+ "Purchase by subscription, 1879",
+ "Qing dynasty (1644\u20131911), Kangxi period (1662\u20131722)"
+ ],
+ "title": "Cover"
+ }
+]
diff --git a/tests/dags/providers/provider_api_scripts/test_metropolitan_museum.py b/tests/dags/providers/provider_api_scripts/test_metropolitan_museum.py
index 7967770c5..b0d2c503e 100644
--- a/tests/dags/providers/provider_api_scripts/test_metropolitan_museum.py
+++ b/tests/dags/providers/provider_api_scripts/test_metropolitan_museum.py
@@ -6,181 +6,201 @@ from unittest.mock import MagicMock, patch
import pytest
import requests
from common.licenses import LicenseInfo
-from providers.provider_api_scripts import metropolitan_museum as mma
+from providers.provider_api_scripts.metropolitan_museum import MetMuseumDataIngester
-RESOURCES = Path(__file__).parent / "resources/metropolitan_museum_of_art"
-
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s: %(message)s", level=logging.INFO
)
logger = logging.getLogger(__name__)
-CC0 = LicenseInfo(
- "cc0", "1.0", "https://creativecommons.org/publicdomain/zero/1.0/", None
-)
+mma = MetMuseumDataIngester()
+RESOURCES = Path(__file__).parent / "resources/metropolitan_museum_of_art"
-def test_get_object_ids():
- r = requests.Response()
- r.status_code = 200
- r.json = MagicMock(return_value={"total": 4, "objectIDs": [153, 1578, 465, 546]})
- with patch.object(mma.delayed_requester, "get", return_value=r):
- total_objects = mma._get_object_ids("")
- assert total_objects[0] == 4
- assert total_objects[1] == [153, 1578, 465, 546]
-
-
-def test_get_response_json():
- expect_json = {"it": "works"}
- endpoint = "https://abc.com"
- query_params = {"a": "b"}
- retries = 2
- with patch.object(
- mma.delayed_requester, "get_response_json", return_value=expect_json
- ) as mock_get_response_json:
- r_json = mma._get_response_json(query_params, endpoint, retries=retries)
-
- assert r_json == expect_json
- mock_get_response_json.assert_called_once_with(
- endpoint, query_params=query_params, retries=retries
- )
+# abbreviated response without other images 45733
+single_object_response = json.loads(
+ (RESOURCES / "sample_response_without_additional.json").read_text()
+)
+# single expected record if 45733 with no additional images
+single_expected_data = json.loads((RESOURCES / "sample_image_data.json").read_text())
+
+# response for objectid 45734 with 2 additional image urls
+full_object_response = json.loads((RESOURCES / "sample_response.json").read_text())
+# 3 expected image records for objectid 45734
+full_expected_data = json.loads(
+ (RESOURCES / "sample_additional_image_data.json").read_text()
+)
-def test_create_meta_data():
- exact_response = {
- "accessionNumber": "36.100.45",
- "classification": "Paintings",
- "creditLine": "The Howard Mansfield Collection, Purchase, Rogers Fund, 1936",
- "culture": "Japan",
- "objectDate": "late 17th century",
- "medium": "Hanging scroll; ink and color on silk",
- }
- exact_meta_data = {
- "accession_number": "36.100.45",
- "classification": "Paintings",
- "credit_line": "The Howard Mansfield Collection, Purchase, Rogers Fund, 1936",
- "culture": "Japan",
- "date": "late 17th century",
- "medium": "Hanging scroll; ink and color on silk",
- }
- r = requests.Response()
- r.status_code = 200
- r.json = MagicMock(return_value=exact_response)
- with patch.object(mma.delayed_requester, "get", return_value=r):
- response = mma._get_response_json(None, "", retries=2)
- meta_data = mma._create_meta_data(response)
+CC0 = LicenseInfo(
+ "cc0", "1.0", "https://creativecommons.org/publicdomain/zero/1.0/", None
+)
- assert exact_meta_data == meta_data
+ "test_date, expected",
+ [
+ pytest.param("2022-07-01", {"metadataDate": "2022-07-01"}, id="happy_path"),
+ pytest.param(None, {}, id="None"),
+ pytest.param("", {}, id="empty_string"),
+ ],
+)
+def test_get_next_query_params(test_date, expected):
+ ingester = MetMuseumDataIngester(date=test_date)
+ actual = ingester.get_next_query_params()
+ assert actual == expected
+
+
+ "response_json, expected",
+ [
+ pytest.param(
+ {"total": 4, "objectIDs": [153, 1578, 465, 546]},
+ [153, 1578, 465, 546],
+ id="happy_path",
+ ),
+ pytest.param({}, None, id="empty_dict"),
+ pytest.param(None, None, id="None"),
+ ],
+)
+def test_get_batch_data(response_json, expected):
+ actual = mma.get_batch_data(response_json)
+ assert actual == expected
+
+
+ "response_json, expected",
+ [
+ pytest.param(
+ single_object_response,
+ single_expected_data[0].get("meta_data"),
+ id="single_image",
+ ),
+ pytest.param(
+ full_object_response,
+ full_expected_data[0].get("meta_data"),
+ id="full_object",
+ ),
+ pytest.param({}, None, id="empty_dict"),
+ pytest.param(None, None, id="None"),
+ ],
+)
+def test_get_meta_data(response_json, expected):
+ actual = mma._get_meta_data(response_json)
+ assert expected == actual
+
+
+ "response_json, expected",
+ [
+ pytest.param(
+ single_object_response,
+ single_expected_data[0].get("raw_tags"),
+ id="single_image",
+ ),
+ pytest.param(
+ full_object_response,
+ full_expected_data[0].get("raw_tags"),
+ id="full_object",
+ ),
+ pytest.param({}, [], id="empty_dict"),
+ pytest.param(None, None, id="None"),
+ ],
+)
+def test_get_tag_list(response_json, expected):
+ actual = mma._get_tag_list(response_json)
+ assert expected == actual
+
+
+ "response_json, expected",
+ [
+ pytest.param(
+ {"title": "Yes, regular case", "objectName": "Wrong"},
+ "Yes, regular case",
+ id="happy_path",
+ ),
+ pytest.param(
+ {"objectName": "Yes, no title at all"},
+ "Yes, no title at all",
+ id="no_title",
+ ),
+ pytest.param(
+ {"title": "", "objectName": "Yes, empty title"},
+ "Yes, empty title",
+ id="empty_string_title",
+ ),
+ pytest.param({}, None, id="empty_json"),
+ pytest.param(None, None, id="None"),
+ ],
+)
+def test_get_title(response_json, expected):
+ actual = mma._get_title(response_json)
+ assert actual == expected
+
+
+ "response_json, expected",
+ [
+ pytest.param({}, None, id="empty_json"),
+ pytest.param(None, None, id="None"),
+ pytest.param(
+ {"artistDisplayName": "Unidentified flying obj"},
+ "Unidentified flying obj",
+ id="happy_path",
+ ),
+ ],
+)
+def test_get_artist_name(response_json, expected):
+ actual = mma._get_artist_name(response_json)
+ assert actual == expected
-def test_get_data_for_image_with_none_response():
+
+def test_get_record_data_with_none_response():
with patch.object(mma.delayed_requester, "get", return_value=None) as mock_get:
with pytest.raises(Exception):
- assert mma._get_data_for_image(10)
-
+ assert mma.get_record_data(10)
assert mock_get.call_count == 6
-def test_get_data_for_image_with_non_ok():
+def test_get_record_data_with_non_ok():
r = requests.Response()
r.status_code = 504
r.json = MagicMock(return_value={})
with patch.object(mma.delayed_requester, "get", return_value=r) as mock_get:
with pytest.raises(Exception):
- assert mma._get_data_for_image(10)
-
+ assert mma.get_record_data(10)
assert mock_get.call_count == 6
-def test_get_data_for_image_returns_response_json_when_all_ok(monkeypatch):
- with open(RESOURCES / "sample_response_without_additional.json") as f:
- actual_response_json = json.load(f)
-
- def mock_get_response_json(query_params, retries=0):
- return actual_response_json
-
- monkeypatch.setattr(mma, "_get_response_json", mock_get_response_json)
- with open(RESOURCES / "sample_additional_image_data.json") as f:
- image_data = json.load(f)
-
- r = requests.Response()
- r.status_code = 200
- r.json = MagicMock(return_value=image_data)
- with patch.object(
- mma.image_store, "save_item", return_value=image_data
- ) as mock_save:
- mma._get_data_for_image(45733)
-
- actual_image = mock_save.call_args[0][0]
-
- expected_image = {
- "creator": "",
- "foreign_identifier": "45733-79_2_414b_S1_sf",
- "foreign_landing_url": "https://www.metmuseum.org/art/collection/search/47533",
- "url": "https://images.metmuseum.org/CRDImages/as/original/79_2_414b_S1_sf.jpg",
- "license_": CC0.license,
- "license_version": CC0.version,
- "filetype": "jpg",
- "filesize": None,
- "meta_data": {
- "license_url": CC0.url,
- "raw_license_url": CC0.raw_url,
- "accession_number": "79.2.414b",
- "classification": "Ceramics",
- "culture": "China",
- "date": "",
- "medium": "Porcelain painted in underglaze blue",
- "credit_line": "Purchase by subscription, 1879",
- },
- "title": "Cover",
- }
-
- assert mock_save.call_count == 1
- for key, value in expected_image.items():
- assert getattr(actual_image, key) == value
-
-
-def test_get_data_for_image_returns_response_json_with_additional_images(monkeypatch):
- with open(RESOURCES / "sample_response.json") as f:
- actual_response_json = json.load(f)
-
- def mock_get_response_json(query_params, retries=0):
- return actual_response_json
-
- monkeypatch.setattr(mma, "_get_response_json", mock_get_response_json)
- with open(RESOURCES / "sample_additional_image_data.json") as f:
- image_data = json.load(f)
-
- r = requests.Response()
- r.status_code = 200
- r.json = MagicMock(return_value=image_data)
- with patch.object(mma.image_store, "add_item", return_value=image_data) as mock_add:
- mma._get_data_for_image(45734)
-
- mock_add.assert_called_with(
- creator="Kiyohara Yukinobu",
- foreign_identifier="45734-DP251120",
- foreign_landing_url=(
- "https://wwwstg.metmuseum.org/art/collection/search/45734"
- ),
- image_url="https://images.metmuseum.org/CRDImages/as/original/DP251120.jpg",
- license_info=(
- LicenseInfo(
- "cc0", "1.0", "https://creativecommons.org/publicdomain/zero/1.0/", None
- )
+ "response_json, expected",
+ [
+ pytest.param(single_object_response, single_expected_data, id="single_image"),
+ pytest.param(full_object_response, full_expected_data, id="full_object"),
+ pytest.param(
+ json.loads('{"isPublicDomain": false, "otherData": "is here too"}'),
+ None,
+ id="not_cc0",
),
- meta_data={
- "accession_number": "36.100.45",
- "classification": "Paintings",
- "culture": "Japan",
- "date": "late 17th century",
- "medium": "Hanging scroll; ink and color on silk",
- "credit_line": (
- "The Howard Mansfield Collection, Purchase, Rogers Fund, 1936"
- ),
- },
- title="Quail and Millet",
+ ],
+)
+def test_get_record_data_returns_response_json_when_all_ok(
+ response_json, expected, monkeypatch
+):
+ monkeypatch.setattr(
+ mma.delayed_requester, "get_response_json", lambda x, y: response_json
)
-
- assert mock_add.call_count == 3
+ actual = mma.get_record_data(response_json.get("objectID"))
+
+ if expected is None:
+ assert actual is None
+ else:
+ assert len(actual) == len(expected)
+ for actual_result, expected_result in zip(actual, expected):
+ for key, value in expected_result.items():
+ if key == "license_info":
+ assert actual_result.get(key) == CC0
+ else:
+ assert actual_result.get(key) == value