Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Add `filetype` to Phylopic script (#547)
Olga Bulataacab7bbe0b3
diff --git a/openverse_catalog/dags/providers/provider_api_scripts/phylopic.py b/openverse_catalog/dags/providers/provider_api_scripts/phylopic.pyindex 1f908e755..a3dc32e1d 100644--- a/openverse_catalog/dags/providers/provider_api_scripts/phylopic.py+++ b/openverse_catalog/dags/providers/provider_api_scripts/phylopic.py@@ -13,6 +13,7 @@ Notes: http://phylopic.org/api/import argparseimport loggingfrom datetime import date, timedelta+from typing import Dictfrom common.licenses import get_license_infofrom common.requester import DelayedRequester@@ -83,15 +84,22 @@ def main(date_start: str = "all", date_end: str = None):def _add_data_to_buffer(**kwargs):endpoint = _create_endpoint_for_IDs(**kwargs)IDs = _get_image_IDs(endpoint)+ if IDs is None:+ returnfor id_ in IDs:- if id_ is not None:- details = _get_meta_data(id_)- if details is not None:- image_store.add_item(**details)+ item_data = _get_object_json(id_)+ if item_data:+ _process_item(item_data)-def _get_total_images():+def _process_item(item_data: Dict) -> None:+ details = _get_meta_data(item_data)+ if details is not None:+ image_store.add_item(**details)+++def _get_total_images() -> int:# Get the total number of PhyloPic imagestotal = 0endpoint = "http://phylopic.org/api/a/image/count"@@ -124,7 +132,7 @@ def _create_endpoint_for_IDs(**kwargs):return endpoint-def _get_image_IDs(_endpoint):+def _get_image_IDs(_endpoint) -> list | None:result = delayed_requester.get_response_json(_endpoint, retries=2)image_IDs = []@@ -132,32 +140,35 @@ def _get_image_IDs(_endpoint):data = list(result.get("result"))if len(data) > 0:- for i in range(len(data)):- image_IDs.append(data[i].get("uid"))+ for item in data:+ image_IDs.append(item.get("uid"))if not image_IDs:logger.warning("No content available!")- return [None]+ return Nonereturn image_IDs-def _get_meta_data(_uuid):+def _get_object_json(_uuid: str) -> Dict | None:logger.info(f"Processing UUID: {_uuid}")- base_url = "http://phylopic.org"- meta_data = {}endpoint = (f"http://phylopic.org/api/a/image/{_uuid}?options=credit+""licenseURL+pngFiles+submitted+submitter+taxa+canonicalName""+string+firstName+lastName")+ result = Nonerequest = delayed_requester.get_response_json(endpoint, retries=2)if request and request.get("success") is True:result = request["result"]- else:- return None+ return result++def _get_meta_data(result: Dict) -> Dict:+ base_url = "http://phylopic.org"+ meta_data = {}+ _uuid = result.get("uid")license_url = result.get("licenseURL")meta_data["taxa"], title = _get_taxa_details(result)@@ -178,8 +189,8 @@ def _get_meta_data(_uuid):"foreign_landing_url": foreign_url,"image_url": img_url,"license_info": get_license_info(license_url=license_url),- "width": str(width),- "height": str(height),+ "width": width,+ "height": height,"creator": creator,"title": title,"meta_data": meta_data,@@ -222,27 +233,26 @@ def _get_taxa_details(result):def _get_image_info(result, _uuid):base_url = "http://phylopic.org"- img_url = ""- width = ""- height = ""+ img_url = None+ width = None+ height = Noneimage_info = result.get("pngFiles")- img = []if image_info:- img = list(filter(lambda x: (int(str(x.get("width", "0"))) >= 257), image_info))- img = sorted(img, key=lambda x: x["width"], reverse=True)-- if len(img) > 0:- img_url = img[0].get("url")- img_url = f"{base_url}{img_url}"- width = img[0].get("width")- height = img[0].get("height")-- if img_url == "":- logging.warning(f"Image not detected in url: {base_url}/image/{_uuid}")- return None, None, None- else:- return img_url, width, height+ images = list(+ filter(lambda x: (int(str(x.get("width", "0"))) >= 257), image_info)+ )+ if len(images) > 0:+ image = sorted(images, key=lambda x: x["width"], reverse=True)[0]+ img_url = image.get("url")+ if not img_url:+ logging.warning(f"Image not detected in url: {base_url}/image/{_uuid}")+ else:+ img_url = f"{base_url}{img_url}"+ width = image.get("width")+ height = image.get("height")++ return img_url, width, heightdef _compute_date_range(date_start: str, days: int = DEFAULT_PROCESS_DAYS) -> str:diff --git a/tests/dags/providers/provider_api_scripts/test_phylopic.py b/tests/dags/providers/provider_api_scripts/test_phylopic.pyindex e73d0d577..a569381ce 100644--- a/tests/dags/providers/provider_api_scripts/test_phylopic.py+++ b/tests/dags/providers/provider_api_scripts/test_phylopic.py@@ -1,7 +1,7 @@import jsonimport logging-import osfrom functools import partial+from pathlib import Pathfrom unittest.mock import patchimport pytest@@ -9,9 +9,7 @@ from common.licenses import get_license_infofrom providers.provider_api_scripts import phylopic as pp-RESOURCES = os.path.join(- os.path.abspath(os.path.dirname(__file__)), "resources/phylopic"-)+RESOURCES = Path(__file__).parent / "resources/phylopic"logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s: %(message)s",@@ -19,6 +17,16 @@ logging.basicConfig()+def image_data():+ yield get_json("correct_meta_data_example.json")+++def get_json(filename):+ with open(RESOURCES / filename) as f:+ return json.load(f)++def test_get_total_images_giving_zero():with patch.object(pp.delayed_requester, "get_response_json", return_value=None):img_count = pp._get_total_images()@@ -26,8 +34,7 @@ def test_get_total_images_giving_zero():def test_get_total_images_correct():- with open(os.path.join(RESOURCES, "total_images_example.json")) as f:- r = json.load(f)+ r = get_json("total_images_example.json")with patch.object(pp.delayed_requester, "get_response_json", return_value=r):img_count = pp._get_total_images()assert img_count == 10@@ -61,13 +68,12 @@ def test_create_endpoint_for_IDs(data, expected):def test_get_image_IDs_for_no_content():with patch.object(pp.delayed_requester, "get_response_json", return_value=None):image_ids = pp._get_image_IDs("")- expect_image_ids = [None]+ expect_image_ids = Noneassert image_ids == expect_image_idsdef test_get_img_IDs_correct():- with open(os.path.join(RESOURCES, "image_ids_example.json")) as f:- r = json.load(f)+ r = get_json("image_ids_example.json")with patch.object(pp.delayed_requester, "get_response_json", return_value=r):actual_img_ids = pp._get_image_IDs("")expect_img_ids = [@@ -79,16 +85,9 @@ def test_get_img_IDs_correct():def test_get_meta_data_with_no_img_url():- with open(os.path.join(RESOURCES, "no_image_url_example.json")) as f:- r = json.load(f)+ r = get_json("no_image_url_example.json")with patch.object(pp.delayed_requester, "get_response_json", return_value=r):- meta_data = pp._get_meta_data("")- assert meta_data is None---def test_get_meta_data_for_none_response():- with patch.object(pp.delayed_requester, "get_response_json", return_value=None):- meta_data = pp._get_meta_data("")+ meta_data = pp._get_meta_data({})assert meta_data is None@@ -97,39 +96,11 @@ cc0_license = get_license_info()-def test_get_meta_data_correct():- with open(os.path.join(RESOURCES, "correct_meta_data_example.json")) as f:- r = json.load(f)- with patch.object(pp.delayed_requester, "get_response_json", return_value=r):- actual_meta_data = pp._get_meta_data("e9df48fe-68ea-419e-b9df-441e0b208335")- expect_meta_data = {- "foreign_identifier": "e9df48fe-68ea-419e-b9df-441e0b208335",- "image_url": (- "http://phylopic.org/assets/images/submissions/e9df48fe-68ea-"- "419e-b9df-441e0b208335.1024.png"- ),- "foreign_landing_url": "http://phylopic.org/image/e9df48fe-68ea-419e-b9df-441e0b208335",- "width": "847",- "height": "1024",- "license_info": cc0_license,- "creator": "Jonathan Wells",- "title": "Chondrus crispus NODC Taxonomic Code, database (version 8.0) 1996",- "meta_data": {- "taxa": [- "Chondrus crispus NODC Taxonomic Code, database (version 8.0) 1996"- ],- "credit_line": "Jonathan Wells",- "pub_date": "2020-02-26 11:59:53",- },- }- assert actual_meta_data == expect_meta_data---def test_get_creator_details():- with open(os.path.join(RESOURCES, "correct_meta_data_example.json")) as f:- r = json.load(f)- with patch.object(pp.delayed_requester, "get_response_json", return_value=r):- result = r["result"]+def test_get_creator_details(image_data):+ with patch.object(+ pp.delayed_requester, "get_response_json", return_value=image_data+ ):+ result = image_data["result"]actual_creator_details = pp._get_creator_details(result)expect_creator_details = ("Jonathan Wells",@@ -139,11 +110,11 @@ def test_get_creator_details():assert actual_creator_details == expect_creator_details-def test_get_taxa_details():- with open(os.path.join(RESOURCES, "correct_meta_data_example.json")) as f:- r = json.load(f)- with patch.object(pp.delayed_requester, "get_response_json", return_value=r):- result = r["result"]+def test_get_taxa_details(image_data):+ with patch.object(+ pp.delayed_requester, "get_response_json", return_value=image_data+ ):+ result = image_data["result"]actual_taxa = pp._get_taxa_details(result)expect_taxa = (["Chondrus crispus NODC Taxonomic Code, database (version 8.0) 1996"],@@ -152,11 +123,11 @@ def test_get_taxa_details():assert actual_taxa == expect_taxa-def test_get_image_info():- with open(os.path.join(RESOURCES, "correct_meta_data_example.json")) as f:- r = json.load(f)- with patch.object(pp.delayed_requester, "get_response_json", return_value=r):- result = r["result"]+def test_get_image_info(image_data):+ with patch.object(+ pp.delayed_requester, "get_response_json", return_value=image_data+ ):+ result = image_data["result"]actual_img_info = pp._get_image_info(result, "e9df48fe-68ea-419e-b9df-441e0b208335")@@ -171,9 +142,39 @@ def test_get_image_info():assert actual_img_info == expect_img_info+def test_process_item(image_data):+ image_uuid = "e9df48fe-68ea-419e-b9df-441e0b208335"+ with patch.object(pp.image_store, "save_item") as mock_save:+ item_data = image_data["result"]+ pp._process_item(item_data)+ actual_image = mock_save.call_args[0][0]+ expected_image = {+ "foreign_identifier": image_uuid,+ "foreign_landing_url": f"http://phylopic.org/image/{image_uuid}",+ "url": "http://phylopic.org/assets/images/submissions/e9df48fe-68ea-419e-b9df-441e0b208335.1024.png",+ "width": 847,+ "height": 1024,+ "filetype": "png",+ "creator": "Jonathan Wells",+ "license_": "cc0",+ "license_version": "1.0",+ "title": "Chondrus crispus NODC Taxonomic Code, database (version 8.0) 1996",+ "meta_data": {+ "taxa": [+ "Chondrus crispus NODC Taxonomic Code, database (version 8.0) 1996"+ ],+ "credit_line": "Jonathan Wells",+ "pub_date": "2020-02-26 11:59:53",+ "license_url": "https://creativecommons.org/publicdomain/zero/1.0/",+ "raw_license_url": "http://creativecommons.org/publicdomain/zero/1.0/",+ },+ }+ for key, value in expected_image.items():+ assert getattr(actual_image, key) == value++def test_get_image_info_with_no_img_url():- with open(os.path.join(RESOURCES, "no_image_url_example.json")) as f:- r = json.load(f)+ r = get_json("no_image_url_example.json")with patch.object(pp.delayed_requester, "get_response_json", return_value=r):result = r["result"]actual_img_info = list(