Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Filter out duplicates from `raw_tags` in the catalog v2 (#4014)
Krystle Salazar5adc7900873b
diff --git a/catalog/dags/common/storage/audio.py b/catalog/dags/common/storage/audio.pyindex 27653b66e..76771cb0e 100644--- a/catalog/dags/common/storage/audio.py+++ b/catalog/dags/common/storage/audio.py@@ -54,7 +54,7 @@ class AudioStore(MediaStore):creator_url: str | None = None,title: str | None = None,meta_data: dict | str | None = None,- raw_tags: list | str | None = None,+ raw_tags: list | set | None = None,watermarked: bool | None = False,duration: int | None = None,bit_rate: int | None = None,@@ -112,7 +112,7 @@ class AudioStore(MediaStore):in this dictionary, and `license_url` isgiven as an argument, the argument willreplace the one given in the dictionary.- raw_tags: List of tags associated with the audio.+ raw_tags: List or set of tags associated with the audio.watermarked: True only if audio has a watermark.duration: in millisecondsbit_rate: Audio bit rate as int.@@ -138,7 +138,7 @@ class AudioStore(MediaStore):and the `provider` argument in theAudioStore init function is the specificprovider of the audio.- ingestion_type: set programmatically+ ingestion_type: Set programmatically."""if audio_set is None:audio_set_data = Nonediff --git a/catalog/dags/common/storage/image.py b/catalog/dags/common/storage/image.pyindex 40c5f7f9b..45fbd9681 100644--- a/catalog/dags/common/storage/image.py+++ b/catalog/dags/common/storage/image.py@@ -56,7 +56,7 @@ class ImageStore(MediaStore):creator_url: str | None = None,title: str | None = None,meta_data: dict | str | None = None,- raw_tags=None,+ raw_tags: list | set | None = None,category: str | None = None,watermarked: str | None = "f",source: str | None = None,@@ -107,7 +107,7 @@ class ImageStore(MediaStore):in this dictionary, and `license_url` isgiven as an argument, the argument willreplace the one given in the dictionary.- raw_tags: List of tags associated with the image.+ raw_tags: List or set of tags associated with the image.category: The image category, defaults to the defaultcategory for the provider fromcommon/loader/provider_details.py.@@ -120,7 +120,7 @@ class ImageStore(MediaStore):and the `provider` argument in theImageStore init function is the specificprovider of the image.- ingestion_type: Set programmatically+ ingestion_type: Set programmatically."""image_data = {diff --git a/catalog/dags/common/storage/media.py b/catalog/dags/common/storage/media.pyindex 2262141a4..f17c81ff5 100644--- a/catalog/dags/common/storage/media.py+++ b/catalog/dags/common/storage/media.py@@ -11,25 +11,29 @@ from common.storage.tsv_columns import CURRENT_VERSIONlogger = logging.getLogger(__name__)-# Filter out tags that exactly match these terms. All terms should be-# lowercase.-TAG_BLACKLIST = {"no person", "squareformat"}+# Filter out tags that exactly match these terms. All terms should be lowercase.+TAG_DENYLIST = {+ "no person",+ "squareformat",+ "undefined",+}-# Filter out tags that contain the following terms. All entrees should be-# lowercase.-TAG_CONTAINS_BLACKLIST = {- "flickriosapp",- "uploaded",+# Filter out tags that contain the following terms. All entrées should be lowercase.+TAG_CONTAINS_DENYLIST = {":","=",- "cc0","by","by-nc",- "by-nd",- "by-sa","by-nc-nd","by-nc-sa",+ "by-nd",+ "by-sa",+ "cc0",+ "creative commons",+ "flickriosapp","pdm",+ "public domain",+ "uploaded",}COMMON_CRAWL = "commoncrawl"@@ -242,19 +246,17 @@ class MediaStore(metaclass=abc.ABCMeta):return buffer_length@staticmethod- def _tag_blacklisted(tag: str | dict) -> bool:+ def _tag_denylisted(tag: str | dict) -> bool:"""- Determine if the is banned or contains a banned substring.+ Determine if the tag is banned or contains a banned substring.:param tag: the tag to be verified against the blacklist- :return: true if tag is blacklisted, else returns false+ :return: true if tag is deny listed, else returns false."""- if isinstance(tag, dict): # check if the tag is already enriched- tag = tag.get("name")- if tag in TAG_BLACKLIST:+ if tag in TAG_DENYLIST:return True- for blacklisted_substring in TAG_CONTAINS_BLACKLIST:- if blacklisted_substring in tag:+ for denylisted_substring in TAG_CONTAINS_DENYLIST:+ if denylisted_substring in tag:return Truereturn False@@ -274,34 +276,31 @@ class MediaStore(metaclass=abc.ABCMeta):)return enriched_meta_data- def _enrich_tags(self, raw_tags) -> list | None:+ def _enrich_tags(self, raw_tags) -> list[dict] | None:"""- Add provider information to tags.+ Add provider information to tags, sorted for further consistency between runs,+ saving on inserts into the DB later.Args:- raw_tags: List of strings or dictionaries+ raw_tags: List or set of strings.Returns:A list of 'enriched' tags:{"name": "tag_name", "provider": self._PROVIDER}"""- if not isinstance(raw_tags, list):- logger.debug("`tags` is not a list.")+ if not isinstance(raw_tags, (list, set)):+ logger.debug("`raw_tags` is not of an accepted type.")return None- else:- return [- self._format_raw_tag(tag)- for tag in raw_tags- if not self._tag_blacklisted(tag)- ]-- def _format_raw_tag(self, tag):- if isinstance(tag, dict) and tag.get("name") and tag.get("provider"):- logger.debug(f"Tag already enriched: {tag}")- return tag- else:- logger.debug(f"Enriching tag: {tag}")- return {"name": tag, "provider": self.provider}+ raw_tags = sorted(set(raw_tags))++ return [+ self._format_raw_tag(tag)+ for tag in raw_tags+ if not self._tag_denylisted(tag)+ ]++ def _format_raw_tag(self, tag: str) -> dict:+ return {"name": tag, "provider": self.provider}def _validate_filetype(self, filetype: str | None, url: str) -> str | None:"""diff --git a/catalog/dags/providers/provider_api_scripts/flickr.py b/catalog/dags/providers/provider_api_scripts/flickr.pyindex a1cfede82..89a4fa06d 100644--- a/catalog/dags/providers/provider_api_scripts/flickr.py+++ b/catalog/dags/providers/provider_api_scripts/flickr.py@@ -318,9 +318,7 @@ class FlickrDataIngester(TimeDelineatedProviderDataIngester):# arbitrarily large data in the DB.raw_tag_string = image_data.get("tags", "").strip()[:max_tag_string_length]if raw_tag_string:- # We sort for further consistency between runs, saving on- # inserts into the DB later.- raw_tags = sorted(list(set(raw_tag_string.split())))+ raw_tags = raw_tag_string.split()return raw_tags@staticmethoddiff --git a/catalog/tests/dags/common/storage/test_audio.py b/catalog/tests/dags/common/storage/test_audio.pyindex 394e45afa..8a19b999e 100644--- a/catalog/tests/dags/common/storage/test_audio.py+++ b/catalog/tests/dags/common/storage/test_audio.py@@ -160,21 +160,6 @@ def test_AudioStore_produces_correct_total_audios():assert audio_store.total_items == 3-def test_AudioStore_get_audio_enriches_multiple_tags():- audio_store = audio.AudioStore("test_provider")- audio_args = mock_audio_args.copy()- audio_args["raw_tags"] = ["tagone", "tag2", "tag3"]- actual_audio = audio_store._get_audio(- **audio_args,- )-- assert actual_audio.tags == [- {"name": "tagone", "provider": "test_provider"},- {"name": "tag2", "provider": "test_provider"},- {"name": "tag3", "provider": "test_provider"},- ]--@test_media.INT_MAX_PARAMETERIZATIONdef test_AudioStore_get_audio_validates_duration(value, expected):audio_store = audio.AudioStore("test_provider")diff --git a/catalog/tests/dags/common/storage/test_media.py b/catalog/tests/dags/common/storage/test_media.pyindex d1cdfd9d3..6f084512e 100644--- a/catalog/tests/dags/common/storage/test_media.py+++ b/catalog/tests/dags/common/storage/test_media.py@@ -9,7 +9,7 @@ from unittest.mock import patchimport pytestfrom common import urls-from common.licenses import LicenseInfo, get_license_info+from common.licenses import LicenseInfofrom common.loader import provider_details as provfrom common.storage import image, media@@ -511,174 +511,12 @@ def test_MediaStore_add_item_fixes_invalid_license_url():def test_MediaStore_get_image_enriches_singleton_tags():image_store = image.ImageStore("test_provider")-- actual_image = image_store._get_image(- license_info=get_license_info(- license_="by-sa",- license_version="4.0",- license_url="https://license/url",- ),- foreign_landing_url=TEST_FOREIGN_LANDING_URL,- url=TEST_IMAGE_URL,- thumbnail_url=None,- filetype=None,- filesize=None,- foreign_identifier="02",- width=None,- height=None,- creator=None,- creator_url=None,- title=None,- meta_data=None,- raw_tags=["lone"],- category=None,- watermarked=None,- source=None,- ingestion_type=None,- )+ image_data = TEST_IMAGE_DICT | TEST_REQUIRED_FIELDS | {"raw_tags": ["lone"]}+ actual_image = image_store._get_image(**image_data)assert actual_image.tags == [{"name": "lone", "provider": "test_provider"}]-def test_MediaStore_get_image_tag_blacklist():- raw_tags = [- "cc0",- "valid",- "garbage:=metacrap",- "uploaded:by=flickrmobile",- {"name": "uploaded:by=instagram", "provider": "test_provider"},- ]-- image_store = image.ImageStore("test_provider")-- actual_image = image_store._get_image(- license_info=get_license_info(- license_="by",- license_version="4.0",- ),- foreign_landing_url=TEST_FOREIGN_LANDING_URL,- url=TEST_IMAGE_URL,- meta_data=None,- raw_tags=raw_tags,- category=None,- foreign_identifier="02",- thumbnail_url=None,- filetype=None,- filesize=None,- width=None,- height=None,- creator=None,- creator_url=None,- title=None,- watermarked=None,- ingestion_type=None,- )-- assert actual_image.tags == [{"name": "valid", "provider": "test_provider"}]---def test_MediaStore_get_image_enriches_multiple_tags():- image_store = image.ImageStore("test_provider")- actual_image = image_store._get_image(- license_info=get_license_info(- license_url="https://license/url",- license_="by",- license_version="4.0",- ),- foreign_landing_url=TEST_FOREIGN_LANDING_URL,- url=TEST_IMAGE_URL,- thumbnail_url=None,- filetype=None,- filesize=None,- foreign_identifier="02",- width=None,- height=None,- creator=None,- creator_url=None,- title=None,- meta_data=None,- raw_tags=["tagone", "tag2", "tag3"],- category=None,- watermarked=None,- source=None,- ingestion_type=None,- )-- assert actual_image.tags == [- {"name": "tagone", "provider": "test_provider"},- {"name": "tag2", "provider": "test_provider"},- {"name": "tag3", "provider": "test_provider"},- ]---def test_MediaStore_get_image_leaves_preenriched_tags(setup_env):- image_store = image.ImageStore("test_provider")- tags = [- {"name": "tagone", "provider": "test_provider"},- {"name": "tag2", "provider": "test_provider"},- {"name": "tag3", "provider": "test_provider"},- ]-- actual_image = image_store._get_image(- license_info=get_license_info(- license_url="https://license/url",- license_="by",- license_version="4.0",- ),- foreign_landing_url=TEST_FOREIGN_LANDING_URL,- url=TEST_IMAGE_URL,- thumbnail_url=None,- filetype=None,- filesize=None,- foreign_identifier="02",- width=None,- height=None,- creator=None,- creator_url=None,- title=None,- meta_data=None,- raw_tags=tags,- category=None,- watermarked=None,- source=None,- ingestion_type=None,- )-- assert actual_image.tags == tags---def test_MediaStore_get_image_nones_nonlist_tags():- image_store = image.ImageStore("test_provider")- tags = "notalist"-- actual_image = image_store._get_image(- license_info=get_license_info(- license_url="https://license/url",- license_="by",- license_version="4.0",- ),- foreign_landing_url=TEST_FOREIGN_LANDING_URL,- url=TEST_IMAGE_URL,- thumbnail_url=None,- filetype=None,- filesize=None,- foreign_identifier="02",- width=None,- height=None,- creator=None,- creator_url=None,- title=None,- meta_data=None,- raw_tags=tags,- category=None,- watermarked=None,- source=None,- ingestion_type=None,- )-- assert actual_image.tags is None--# Extracts `jpg` extension from the url.# Converts `jpeg` to `jpg` to use the standard extension.# Extracts `tif` extension, and converts it to the standard, `tiff`.@@ -709,6 +547,55 @@ def test_MediaStore_validates_filetype(filetype, url, expected_filetype):assert cleaned_data["filetype"] == expected_filetype+ "raw_tags, expected_tags",+ [+ pytest.param(+ ["lone"],+ [{"name": "lone", "provider": "test_provider"}],+ id="enriches singleton tag",+ ),+ pytest.param(+ ["tagone", "tag2", "tag3"],+ [+ {"name": "tag2", "provider": "test_provider"},+ {"name": "tag3", "provider": "test_provider"},+ {"name": "tagone", "provider": "test_provider"},+ ],+ id="sort and enriches multiple tags",+ ),+ pytest.param(+ ["cc0", "valid", "garbage:=metacrap", "uploaded:by=flickrmobile"],+ [{"name": "valid", "provider": "test_provider"}],+ id="exclude tags by the denylist",+ ),+ pytest.param("notalist", None, id="nonlist tags should be None"),+ pytest.param(+ {"tag2", "tagone"},+ [+ {"name": "tag2", "provider": "test_provider"},+ {"name": "tagone", "provider": "test_provider"},+ ],+ id="accepts set of tags",+ ),+ pytest.param(+ ["tag2", "tagone", "tag2"],+ [+ {"name": "tag2", "provider": "test_provider"},+ {"name": "tagone", "provider": "test_provider"},+ ],+ id="remove duplicates",+ ),+ ],+)+def test_MediaStore_get_image_tag_denylist(raw_tags, expected_tags):+ image_store = image.ImageStore("test_provider")+ image_data = TEST_IMAGE_DICT | TEST_REQUIRED_FIELDS | {"raw_tags": raw_tags}+ actual_image = image_store._get_image(**image_data)++ assert actual_image.tags == expected_tags++@INT_MAX_PARAMETERIZATIONdef test_MediaStore_validate_integer(value, expected):image_store = image.MockImageStore("test_provider")diff --git a/catalog/tests/dags/providers/provider_api_scripts/resources/flickr/image_data_long_tags_string.json b/catalog/tests/dags/providers/provider_api_scripts/resources/flickr/image_data_long_tags_string.jsondeleted file mode 100644index 5b8dc7926..000000000--- a/catalog/tests/dags/providers/provider_api_scripts/resources/flickr/image_data_long_tags_string.json+++ /dev/null@@ -1,5 +0,0 @@-{- "id": "456",- "tags": "tag1 tag2 tag3 tag3 tag4 tag5 tag6 tag7",- "width_l": 1024-}diff --git a/catalog/tests/dags/providers/provider_api_scripts/resources/flickr/image_data_varying_tags_whitespace.json b/catalog/tests/dags/providers/provider_api_scripts/resources/flickr/image_data_varying_tags_whitespace.jsondeleted file mode 100644index f9b35f73f..000000000--- a/catalog/tests/dags/providers/provider_api_scripts/resources/flickr/image_data_varying_tags_whitespace.json+++ /dev/null@@ -1,5 +0,0 @@-{- "id": "456",- "tags": "tag1 tag2 tag3 tag3 ",- "width_l": 1024-}diff --git a/catalog/tests/dags/providers/provider_api_scripts/test_flickr.py b/catalog/tests/dags/providers/provider_api_scripts/test_flickr.pyindex 2b84a816b..7f3d644f9 100644--- a/catalog/tests/dags/providers/provider_api_scripts/test_flickr.py+++ b/catalog/tests/dags/providers/provider_api_scripts/test_flickr.py@@ -161,12 +161,12 @@ def test_get_record_data():"title": "Surveying Ruperts Reef @reeflifesurvey #lapofaus #marineexplorer","meta_data": expect_meta_data,"raw_tags": [- "australia",- "marine",- "marineexplorer",- "nature","scuba",+ "nature",+ "marine","underwater",+ "australia",+ "marineexplorer",],"source": flickr.provider_string,"category": "photograph",@@ -301,15 +301,13 @@ def test_create_meta_data(image_data, expected_meta_data):[# Happy path, handles whitespace(- _get_resource_json("image_data_varying_tags_whitespace.json"),- ["tag1", "tag2", "tag3"],+ {"tags": "tag1 tag2 tag3 tag3 "},+ ["tag1", "tag2", "tag3", "tag3"],),- # Sorts tags- (_get_resource_json("image_data_unsorted_tags.json"), ["tag1", "tag2", "tag3"]),# Truncates long tags(- _get_resource_json("image_data_long_tags_string.json"),- ["tag1", "tag2", "tag3", "tag4", "tag5", "tag6"],+ {"tags": "tag1 tag2 tag3 tag3 tag4 tag5 tag6 tag7"},+ ["tag1", "tag2", "tag3", "tag3", "tag4", "tag5", "tag6"],),# Returns None when no tags key({"id": "aslkjb"}, None),@@ -354,9 +352,9 @@ def test_get_record_data_with_sub_provider():"capecanaveral","commercialcrewprogram","gophertortoise",- "kennedyspacecenter",- "nasa","spacex",+ "nasa",+ "kennedyspacecenter",],"source": "nasa","category": None,