Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Add flickr sub provider auditing dag (#1034)
Staci Mullinsebb2e520cc4b
diff --git a/DAGs.md b/DAGs.mdindex 143328497..e5eefc851 100644--- a/DAGs.md+++ b/DAGs.md@@ -39,12 +39,13 @@ The following are DAGs grouped by their primary tag:## Maintenance-| DAG ID | Schedule Interval |-| --------------------------------------------- | ----------------- |-| [`airflow_log_cleanup`](#airflow_log_cleanup) | `@weekly` |-| [`check_silenced_dags`](#check_silenced_dags) | `@weekly` |-| [`pr_review_reminders`](#pr_review_reminders) | `0 0 * * 1-5` |-| [`rotate_db_snapshots`](#rotate_db_snapshots) | `0 0 * * 6` |+| DAG ID | Schedule Interval |+| --------------------------------------------------------------------------- | ----------------- |+| [`airflow_log_cleanup`](#airflow_log_cleanup) | `@weekly` |+| [`check_silenced_dags`](#check_silenced_dags) | `@weekly` |+| [`flickr_audit_sub_provider_workflow`](#flickr_audit_sub_provider_workflow) | `@monthly` |+| [`pr_review_reminders`](#pr_review_reminders) | `0 0 * * 1-5` |+| [`rotate_db_snapshots`](#rotate_db_snapshots) | `0 0 * * 6` |## Oauth@@ -98,6 +99,7 @@ The following is documentation associated with each DAG (where available):1. [`europeana_reingestion_workflow`](#europeana_reingestion_workflow)1. [`europeana_workflow`](#europeana_workflow)1. [`finnish_museums_workflow`](#finnish_museums_workflow)+1. [`flickr_audit_sub_provider_workflow`](#flickr_audit_sub_provider_workflow)1. [`flickr_reingestion_workflow`](#flickr_reingestion_workflow)1. [`flickr_workflow`](#flickr_workflow)1. [`freesound_workflow`](#freesound_workflow)@@ -239,6 +241,14 @@ script is a dated DAG that ingests all records that were last updated in theprevious day. Because of this, it is not necessary to run a separate reingestionDAG, as updated data will be processed during regular ingestion.+## `flickr_audit_sub_provider_workflow`++### Flickr Sub Provider Audit++Check the list of member institutions of the Flickr Commons for institutions+that have cc-licensed images and are not already configured as sub-providers for+the Flickr DAG. Report suggestions for new sub-providers to Slack.+## `flickr_reingestion_workflow`Content Provider: Flickrdiff --git a/openverse_catalog/dags/common/loader/provider_details.py b/openverse_catalog/dags/common/loader/provider_details.pyindex 76a7f624e..c219fa21a 100644--- a/openverse_catalog/dags/common/loader/provider_details.py+++ b/openverse_catalog/dags/common/loader/provider_details.py@@ -56,6 +56,10 @@ FLICKR_SUB_PROVIDERS = {"bio_diversity": {"61021753@N02"}, # BioDivLibrary"spacex": {"130608600@N05"}, # Official SpaceX Photos"woc_tech": {"136629440@N06"}, # WOCinTech Chat+ "valence_romans": {"150408343@N02"}, # Valence Romans Agglomeration Media Library+ "east_riding": {"138361426@N08"}, # East Riding Archives+ "archief_alkmaar": {"98304311@N03"}, # Regionaal Archief Alkmaar Commons+ "bib_gulbenkian": {"26577438@N06"}, # Gulbenkian Art Library}FLICKR_PHOTO_URL_BASE = "https://www.flickr.com/photos/"diff --git a/openverse_catalog/dags/maintenance/flickr_audit_sub_provider_workflow.py b/openverse_catalog/dags/maintenance/flickr_audit_sub_provider_workflow.pynew file mode 100644index 000000000..3f6d906b0--- /dev/null+++ b/openverse_catalog/dags/maintenance/flickr_audit_sub_provider_workflow.py@@ -0,0 +1,168 @@+"""+# Flickr Sub Provider Audit++Check the list of member institutions of the Flickr Commons for institutions that+have cc-licensed images and are not already configured as sub-providers for the Flickr+DAG. Report suggestions for new sub-providers to Slack.+"""++import logging++from airflow import DAG+from airflow.exceptions import AirflowSkipException+from airflow.models import Variable+from airflow.operators.python import PythonOperator+from common.constants import DAG_DEFAULT_ARGS+from common.loader import provider_details as prov+from common.requester import DelayedRequester+from common.slack import send_alert+from providers.provider_api_scripts.flickr import LICENSE_INFO+++logger = logging.getLogger(__name__)++DAG_ID = "flickr_audit_sub_provider_workflow"+MAX_ACTIVE = 1+++class FlickrSubProviderAuditor:++ endpoint = "https://www.flickr.com/services/rest"+ retries = 2++ # Institutions with fewer than this number of cc-licensed images will not be+ # recommended as a new sub provider.+ minimum_image_count = 300++ # NSIDs in this list should not be reported for consideration for+ # becoming a sub-provider.+ nsids_to_skip = [+ # TODO: Currently contains graphic medical imagery. Reconsider once+ # content safety progress is made.+ "61270229@N05",+ ]++ def __init__(self):+ self.api_key = Variable.get("API_KEY_FLICKR")+ self.requester = DelayedRequester(headers={"Accept": "application/json"})+ self.base_params = {+ "api_key": self.api_key,+ "format": "json",+ "nojsoncallback": 1,+ }+ # Get the list of institutions that are already configured for Flickr+ self.current_institutions = set().union(*prov.FLICKR_SUB_PROVIDERS.values())++ def get_institutions(self):+ response_json = self.requester.get_response_json(+ self.endpoint,+ self.retries,+ query_params={+ "method": "flickr.commons.getInstitutions",+ **self.base_params,+ },+ )+ if response_json:+ return response_json.get("institutions", {}).get("institution", [])++ return None++ def get_cc_image_count(self, name, nsid):+ """Return the number of cc licensed images for this institution."""++ # The Flickr API is consistently returning a count of '0' when querying for+ # images matching multiple license types from a particular user. It gives more+ # accurate results when you query for one license at a time, however, so we have+ # to make separate requests for each license type.+ logger.info(f"Checking records for {name}")++ count = 0+ for license in LICENSE_INFO.keys():+ response_json = self.requester.get_response_json(+ self.endpoint,+ self.retries,+ query_params={+ "method": "flickr.photos.search",+ "media": "photos",+ "license": license,+ "user_id": nsid,+ "safe_search": 1,+ **self.base_params,+ },+ )++ if response_json:+ sub_total = response_json.get("photos", {}).get("total", 0)+ if sub_total > 0:+ logger.info(f"Found {sub_total} records for license type {license}")+ count += sub_total++ logger.info(f"TOTAL COUNT for {name}: {count}")+ return count++ def get_new_institutions_with_cc_licensed_images(self):+ new_institutions_with_cc_images = []++ # Get the full list of Flickr commons institutions from the API+ institutions = self.get_institutions()++ for institution in institutions:+ name = institution.get("name", {}).get("_content")+ nsid = institution.get("nsid")++ if not name or not nsid:+ continue++ # Skip institutions that are already configured as sub-providers+ if nsid in self.current_institutions:+ continue++ # Skip institutions that have been added to the nsids_to_skip list+ if nsid in self.nsids_to_skip:+ continue++ # Skip institutions that do not have enough cc-licensed images. Many+ # institutions have "no known copyright restrictions", but no cc+ # license. See https://www.flickr.com/commons/usage+ cc_count = self.get_cc_image_count(name, nsid)+ if cc_count < self.minimum_image_count:+ continue++ # Otherwise, consider this institution for addition as a+ # sub-provider.+ new_institutions_with_cc_images.append((name, nsid, cc_count))++ return new_institutions_with_cc_images+++def audit_flickr_sub_providers():+ auditor = FlickrSubProviderAuditor()++ potential_sub_providers = auditor.get_new_institutions_with_cc_licensed_images()+ if not potential_sub_providers:+ raise AirflowSkipException("No new potential sub-providers were identified.")++ message = "Consider adding the following sub-providers for Flickr:"+ for (name, nsid, cc_count) in potential_sub_providers:+ message += "\n"+ message += f"{name}: {nsid} _({cc_count} cc-licensed images)_"++ send_alert(message, dag_id=DAG_ID, username="Flickr SubProvider Suggestions")+ return message+++dag = DAG(+ dag_id=DAG_ID,+ default_args=DAG_DEFAULT_ARGS,+ max_active_runs=MAX_ACTIVE,+ catchup=False,+ schedule="@monthly",+ doc_md=__doc__,+ tags=["maintenance"],+)++with dag:+ PythonOperator(+ task_id="audit_flickr_sub_providers",+ python_callable=audit_flickr_sub_providers,+ )diff --git a/tests/dags/maintenance/test_flickr_audit_sub_provider.py b/tests/dags/maintenance/test_flickr_audit_sub_provider.pynew file mode 100644index 000000000..8a7cdc2ab--- /dev/null+++ b/tests/dags/maintenance/test_flickr_audit_sub_provider.py@@ -0,0 +1,129 @@+from unittest import mock++import pytest+from airflow.exceptions import AirflowSkipException+from maintenance.flickr_audit_sub_provider_workflow import (+ FlickrSubProviderAuditor,+ audit_flickr_sub_providers,+)+++auditor = FlickrSubProviderAuditor()+++ "response_json, expected_institutions",+ (+ (None, None),+ ({"foo": "bar"}, []),+ ({"institutions": {}}, []),+ ({"institutions": {"institution": [{"foo": "bar"}]}}, [{"foo": "bar"}]),+ ),+)+def test_get_institutions(response_json, expected_institutions):+ requester = auditor.requester+ with mock.patch.object(requester, "get_response_json", return_value=response_json):+ assert auditor.get_institutions() == expected_institutions+++ "response_json, expected_total_count",+ (+ (None, 0),+ ({}, 0),+ ({"photos": {}}, 0),+ ({"photos": {"total": 0}}, 0),+ # 1 record for each license, 8 total records+ ({"photos": {"total": 1}}, 8),+ ),+)+def test_check_for_licensed_images(response_json, expected_total_count):+ requester = auditor.requester+ with mock.patch.object(requester, "get_response_json", return_value=response_json):+ assert auditor.get_cc_image_count("name", "nsid") == expected_total_count+++def test_get_new_institutions():+ mock_already_configured_institutions = [+ "24662369@N07", # Matches 'Already configured' institution+ "35067687@N04", # Additional test value+ ]+ mock_nsids_to_skip = [+ "61270229@N05",+ ]++ mock_institutions_from_api = [+ # Institutions that should be skipped+ # No name+ {"nsid": "150408343@N02"},+ {"name": {}, "nsid": "150408343@N02"},+ # No nsid+ {"name": {"_content": "Missing NSID"}},+ # Nsid in skip list+ {"name": {"_content": "Skipped NSID"}, "nsid": "61270229@N05"},+ # Already configured in sub-providers+ {"name": {"_content": "Already configured"}, "nsid": "24662369@N07"},+ # This one is mocked to return no CC-licensed images+ {"name": {"_content": "No CC images"}, "nsid": "138361426@N08"},+ # This one is mocked to return only a small number of CC-licensed images+ {"name": {"_content": "Not enough CC images"}, "nsid": "142575440@N02"},+ # Institutions that should be marked for consideration+ # This one is mocked to return CC-licensed_images+ {"name": {"_content": "Institution to consider"}, "nsid": "35128489@N07"},+ ]++ def mock_get_cc_image_count(name, nsid):+ # Mock counts for a few institutions such that they are skipped+ if name == "No CC images":+ return 0 # No cc-licensed images+ if name == "Not enough CC images":+ return 1 # Less than the minimum required number of images++ # All others have enough cc-licensed images+ return 1000++ with (+ mock.patch.object(+ auditor, "get_institutions", return_value=mock_institutions_from_api+ ),+ mock.patch.object(auditor, "get_cc_image_count", new=mock_get_cc_image_count),+ ):+ auditor.current_institutions = mock_already_configured_institutions+ auditor.nsids_to_skip = mock_nsids_to_skip++ actual_institutions = auditor.get_new_institutions_with_cc_licensed_images()+ assert actual_institutions == [+ ("Institution to consider", "35128489@N07", 1000)+ ]+++ "potential_sub_providers, message",+ (+ # No suggested sub-providers+ pytest.param(+ [],+ "",+ marks=pytest.mark.raises(exception=AirflowSkipException),+ ),+ (+ [("NavyMedicine", "61270229@N05", 1000)],+ "NavyMedicine: 61270229@N05 _(1000 cc-licensed images)_",+ ),+ (+ [+ ("NavyMedicine", "61270229@N05", 1000),+ ("East Riding Archives", "138361426@N08", 2000),+ ],+ "NavyMedicine: 61270229@N05 _(1000 cc-licensed images)_\n"+ "East Riding Archives: 138361426@N08 _(2000 cc-licensed images)_",+ ),+ ),+)+def test_audit_flickr_sub_providers(potential_sub_providers, message):+ with mock.patch(+ "maintenance.flickr_audit_sub_provider_workflow.FlickrSubProviderAuditor.get_new_institutions_with_cc_licensed_images",+ return_value=potential_sub_providers,+ ):+ actual_message = audit_flickr_sub_providers()+ assert message in actual_message