Skip to content

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

Change PhyloPic date range & schedule interval (#423)

Madison Swain-Bowden7cccf88879c0
diff --git a/openverse_catalog/dags/providers/phylopic_workflow.py b/openverse_catalog/dags/providers/phylopic_workflow.py
index 616eaaf73..879dcb7a8 100644
--- a/openverse_catalog/dags/providers/phylopic_workflow.py
+++ b/openverse_catalog/dags/providers/phylopic_workflow.py
@@ -13,6 +13,6 @@ globals()[DAG_ID] = create_provider_api_workflow(
phylopic.main,
start_date=datetime(1970, 1, 1),
max_active_tasks=1,
- schedule_string="@daily",
+ schedule_string="@weekly",
dated=True,
)
diff --git a/openverse_catalog/dags/providers/provider_api_scripts/phylopic.py b/openverse_catalog/dags/providers/provider_api_scripts/phylopic.py
index 2e3d6cdab..9bc7b4b8e 100644
--- a/openverse_catalog/dags/providers/provider_api_scripts/phylopic.py
+++ b/openverse_catalog/dags/providers/provider_api_scripts/phylopic.py
@@ -12,6 +12,7 @@ Notes: http://phylopic.org/api/
import argparse
import logging
+from datetime import date, timedelta
from common.licenses import get_license_info
from common.requester import DelayedRequester
@@ -28,12 +29,14 @@ HOST = "phylopic.org"
ENDPOINT = f"http://{HOST}/api/a"
PROVIDER = "phylopic"
LIMIT = 5
+# Default number of days to process if date_end is not defined
+DEFAULT_PROCESS_DAYS = 7
delayed_requester = DelayedRequester(DELAY)
image_store = ImageStore(provider=PROVIDER)
-def main(date="all"):
+def main(date_start: str = "all", date_end: str = None):
"""
This script pulls the data for a given date from the PhyloPic
API, and writes it into a .TSV file to be eventually read
@@ -41,15 +44,18 @@ def main(date="all"):
Required Arguments:
- date: Date String in the form YYYY-MM-DD. This is the date for
- which running the script will pull data.
+ date_start: Date String in the form YYYY-MM-DD. This date defines the beginning
+ of the range that the script will pull data from.
+ date_end: Date String in the form YYYY-MM-DD. Similar to `date_start`, this
+ defines the end of the range of data pulled. Defaults to
+ DEFAULT_PROCESS_DAYS (7) if undefined.
"""
offset = 0
logger.info("Begin: PhyloPic API requests")
- if date == "all":
+ if date_start == "all":
logger.info("Processing all images")
param = {"offset": offset}
@@ -62,8 +68,11 @@ def main(date="all"):
param = {"offset": offset}
else:
- param = {"date": date}
- logger.info(f"Processing date: {date}")
+ if date_end is None:
+ date_end = _compute_date_range(date_start)
+ param = {"date_start": date_start, "date_end": date_end}
+
+ logger.info(f"Processing from {date_start} to {date_end}")
_add_data_to_buffer(**param)
image_store.commit()
@@ -71,16 +80,16 @@ def main(date="all"):
logger.info("Terminated!")
-def _add_data_to_buffer(**args):
- endpoint = _create_endpoint_for_IDs(**args)
+def _add_data_to_buffer(**kwargs):
+ endpoint = _create_endpoint_for_IDs(**kwargs)
IDs = _get_image_IDs(endpoint)
for id_ in IDs:
if id_ is not None:
details = _get_meta_data(id_)
if details is not None:
- args = _create_args(details, id_)
- image_store.add_item(**args)
+ kwargs = _create_args(details, id_)
+ image_store.add_item(**kwargs)
def _create_args(details, id_):
@@ -111,18 +120,24 @@ def _get_total_images():
return total
-def _create_endpoint_for_IDs(**args):
+def _create_endpoint_for_IDs(**kwargs):
limit = LIMIT
- if args.get("date"):
- # Get a list of objects uploaded/updated on a given date.
- date = args["date"]
- endpoint = f"http://phylopic.org/api/a/image/list/modified/{date}"
+ if ((date_start := kwargs.get("date_start")) is not None) and (
+ (date_end := kwargs.get("date_end")) is not None
+ ):
+ # Get a list of objects uploaded/updated from a given date to another date
+ # http://phylopic.org/api/#method-image-time-range
+ endpoint = (
+ f"http://phylopic.org/api/a/image/list/modified/{date_start}/{date_end}"
+ )
- else:
+ elif (offset := kwargs.get("offset")) is not None:
# Get all images and limit the results for each request.
- offset = args["offset"]
endpoint = f"http://phylopic.org/api/a/image/list/{offset}/{limit}"
+
+ else:
+ raise ValueError("No valid selection criteria found!")
return endpoint
@@ -255,14 +270,30 @@ def _get_image_info(result, _uuid):
return img_url, width, height, thumbnail
+def _compute_date_range(date_start: str, days: int = DEFAULT_PROCESS_DAYS) -> str:
+ """
+ Given an ISO formatted date string and a number of days, compute the
+ ISO string that represents the start date plus the days provided.
+ """
+ date_end = date.fromisoformat(date_start) + timedelta(days=days)
+ return date_end.isoformat()
+
+
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="PhyloPic API Job", add_help=True)
parser.add_argument(
- "--date",
+ "--date-start",
default="all",
- help="Identify all images" " from a particular date (YYYY-MM-DD).",
+ help="Identify all images starting from a particular date (YYYY-MM-DD).",
+ )
+ parser.add_argument(
+ "--date-end",
+ default=None,
+ help="Used in conjunction with --date-start, identify all images ending on "
+ f"a particular date (YYYY-MM-DD), defaults to {DEFAULT_PROCESS_DAYS} "
+ "if not defined.",
)
- date = parser.parse_args().date
+ args = parser.parse_args()
- main(date)
+ main(args.date_start, args.date_end)
diff --git a/tests/dags/providers/provider_api_scripts/test_phylopic.py b/tests/dags/providers/provider_api_scripts/test_phylopic.py
index 0ef0d49ec..5b4e03d0d 100644
--- a/tests/dags/providers/provider_api_scripts/test_phylopic.py
+++ b/tests/dags/providers/provider_api_scripts/test_phylopic.py
@@ -1,8 +1,10 @@
import json
import logging
import os
+from functools import partial
from unittest.mock import patch
+import pytest
from common.licenses import LicenseInfo
from providers.provider_api_scripts import phylopic as pp
@@ -31,16 +33,29 @@ def test_get_total_images_correct():
assert img_count == 10
-def test_create_endpoint_for_IDs_by_date():
- actual_endpoint = pp._create_endpoint_for_IDs(**{"date": "2020-02-10"})
- expect_endpoint = str("http://phylopic.org/api" "/a/image/list/modified/2020-02-10")
- assert actual_endpoint == expect_endpoint
+invalid_endpoint = partial(pytest.param, marks=pytest.mark.raises(exception=ValueError))
-def test_create_endpoint_for_IDs_all():
- actual_endpoint = pp._create_endpoint_for_IDs(**{"offset": 0})
- expect_endpoint = "http://phylopic.org/api/a/image/list/0/5"
- assert actual_endpoint == expect_endpoint
+ "data, expected",
+ [
+ # Happy paths
+ (
+ {"date_start": "2020-02-10", "date_end": "2020-02-11"},
+ "http://phylopic.org/api/a/image/list/modified/2020-02-10/2020-02-11",
+ ),
+ ({"offset": 0}, "http://phylopic.org/api/a/image/list/0/5"),
+ # Missing/None parameters
+ invalid_endpoint({}, None),
+ invalid_endpoint({"offset": None}, None),
+ invalid_endpoint({"date_start": None}, None),
+ invalid_endpoint({"date_start": None, "date_end": None}, None),
+ invalid_endpoint({"date_start": "2020-02-10", "date_end": None}, None),
+ ],
+)
+def test_create_endpoint_for_IDs(data, expected):
+ actual = pp._create_endpoint_for_IDs(**data)
+ assert actual == expected
def test_get_image_IDs_for_no_content():
@@ -252,3 +267,16 @@ def test_create_args():
}
assert actual_args == expect_args
assert len(actual_args) == 10
+
+
+ "date_start, days, expected",
+ [
+ ("2022-01-10", 10, "2022-01-20"),
+ ("2022-02-28", 7, "2022-03-07"),
+ ("2022-02-28", -7, "2022-02-21"),
+ ],
+)
+def test_compute_date_range(date_start, days, expected):
+ actual = pp._compute_date_range(date_start, days)
+ assert actual == expected