Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Refactor Jamendo to use the ProviderDataIngester (#741)
Staci Cooperdb47359a7d9d
diff --git a/openverse_catalog/dags/providers/provider_api_scripts/jamendo.py b/openverse_catalog/dags/providers/provider_api_scripts/jamendo.pyindex e4c76b9e9..0379708e6 100644--- a/openverse_catalog/dags/providers/provider_api_scripts/jamendo.py+++ b/openverse_catalog/dags/providers/provider_api_scripts/jamendo.py@@ -16,328 +16,217 @@ Notes: https://api.jamendo.com/v3.0/tracks/channels: 1/2"""import logging-from functools import lru_cachefrom typing import Optionalfrom urllib.parse import parse_qs, urlencode, urlsplitimport commonfrom airflow.models import Variable+from common import constantsfrom common.licenses import get_license_infofrom common.loader import provider_details as prov-from common.requester import DelayedRequester-from common.storage.audio import AudioStorefrom common.urls import rewrite_redirected_url+from providers.provider_api_scripts.provider_data_ingester import ProviderDataIngester-logging.basicConfig(- format="%(asctime)s - %(name)s - %(levelname)s: %(message)s", level=logging.INFO-)logger = logging.getLogger(__name__)logging.getLogger(common.urls.__name__).setLevel(logging.WARNING)-LIMIT = 200 # number of items per page in API response-DELAY = 1 # in seconds-RETRIES = 3--HOST = "jamendo.com"-ENDPOINT = f"https://api.{HOST}/v3.0/tracks"-PROVIDER = prov.JAMENDO_DEFAULT_PROVIDER-APP_KEY = Variable.get("API_KEY_JAMENDO", "not_set")--HEADERS = {- "Accept": "application/json",-}-DEFAULT_QUERY_PARAMS = {- # jsonpretty can have invalid characters in json:- # \u0009 tab breaks the json- "format": "json",- "client_id": APP_KEY,- "include": "musicinfo licenses stats lyrics",- "imagesize": 200,- "limit": LIMIT,- "audioformat": "mp32",-}--delayed_requester = DelayedRequester(DELAY)-audio_store = AudioStore(provider=PROVIDER)--def main():- """- This script pulls the data for a given date from the Jamendo,- and writes it into a .TSV file to be eventually read- into our DB.- """-- logger.info("Begin: Jamendo script")- audio_count = _get_items()- audio_store.commit()- logger.info(f"Total audio pulled: {audio_count}")- logger.info("Terminated!")---def _get_query_params(- offset,- default_query_params=None,-):- if default_query_params is None:- default_query_params = DEFAULT_QUERY_PARAMS- query_params = default_query_params.copy()- query_params["offset"] = offset- return query_params---def _get_items():- item_count = 0- should_continue = True- offset = 0- while should_continue:- query_params = _get_query_params(offset=offset)- batch_data = _get_batch_json(query_params=query_params)- if isinstance(batch_data, list) and len(batch_data) > 0:- item_count = _process_item_batch(batch_data)- offset += LIMIT+class JamendoDataIngester(ProviderDataIngester):+ providers = {"audio": prov.JAMENDO_DEFAULT_PROVIDER}+ endpoint = "https://api.jamendo.com/v3.0/tracks"+ batch_limit = 200+ headers = {"Accept": "application/json"}++ def get_media_type(self, record):+ return constants.AUDIO++ def get_next_query_params(self, prev_query_params, **kwargs):+ if not prev_query_params:+ # On first request, build default params.+ return {+ "format": "json",+ "client_id": Variable.get("API_KEY_JAMENDO"),+ "include": "musicinfo licenses stats lyrics",+ "imagesize": 200,+ "limit": self.batch_limit,+ "audioformat": "mp32",+ "offset": 0,+ }else:- should_continue = False- return item_count---def _get_batch_json(- endpoint=ENDPOINT, headers=None, retries=RETRIES, query_params=None-):- if headers is None:- headers = HEADERS- response_json = delayed_requester.get_response_json(- endpoint, retries, query_params, headers=headers- )- if response_json is None:- return None- else:- return response_json.get("results")---def _process_item_batch(items_batch):- for item in items_batch:- item_meta_data = _extract_audio_data(item)- if item_meta_data is None:- continue- audio_store.add_item(**item_meta_data)- return audio_store.total_items---def _extract_audio_data(media_data):- try:- foreign_landing_url = media_data["shareurl"]- except (TypeError, KeyError, AttributeError):- return None- audio_url, duration = _get_audio_info(media_data)- if audio_url is None:- return None- item_license = _get_license(media_data)- if item_license is None:- return None- foreign_identifier = _get_foreign_identifier(media_data)- title = _get_title(media_data)- creator, creator_url = _get_creator_data(media_data)- thumbnail = _get_thumbnail_url(media_data)- metadata = _get_metadata(media_data)- tags = _get_tags(media_data)- # Jamendo has only music- category = "music"- # We request mp32 (VBR) files- filetype = "mp32"- genres = _get_genres(media_data)- (- set_foreign_id,- audio_set,- position,- url,- set_thumbnail,- ) = _get_audio_set_info(media_data)- return {- "title": title,- "creator": creator,- "creator_url": creator_url,- "foreign_identifier": foreign_identifier,- "foreign_landing_url": foreign_landing_url,- "audio_url": audio_url,- "duration": duration,- "filetype": filetype,- "thumbnail_url": thumbnail,- "license_info": item_license,- "meta_data": metadata,- "raw_tags": tags,- "category": category,- "genres": genres,- "set_foreign_id": set_foreign_id,- "audio_set": audio_set,- "set_position": position,- "set_url": url,- "set_thumbnail": set_thumbnail,- }---def _get_foreign_identifier(media_data):- try:- return media_data["id"]- except (TypeError, IndexError, KeyError):+ # Increment `offset` by the batch limit.+ return {+ **prev_query_params,+ "offset": prev_query_params["offset"] + self.batch_limit,+ }++ def get_batch_data(self, response_json):+ if response_json:+ return response_json.get("results")return None--def _remove_param_from_url(url: str, param: str) -> str:- """- Remove a parameter from a provided URL.- """- parsed_url = urlsplit(url)- query = parse_qs(parsed_url.query)- query.pop(param, None)- return parsed_url._replace(query=urlencode(query, doseq=True)).geturl()---def _get_audio_info(media_data: dict) -> tuple[Optional[str], Optional[int]]:- """Parse audio URL & audio duration- Also remove the "from" parameter from an audio URL. Audio URLs have a "from" param- which seems to encapsulate information about the calling application.- Example from the API:- https://prod-1.storage.jamendo.com/?trackid=1532771&format=mp31&from=app-devsite- This information looks like an API key or secret when returned, so we remove it- since it's not necessary for serving the audio files.- >>> base_url = "https://prod-1.storage.jamendo.com/"- >>> url = f"{base_url}?trackid=1532771&format=mp31&from=app-devsite"- >>> _remove_param_from_url(url, "from")- 'https://prod-1.storage.jamendo.com/?trackid=1532771&format=mp31'- :return: Tuple with main audio file information:- - audio_url- - duration (in milliseconds)- """- if (audio_url := media_data.get("audio")) is None:- return None, None- audio_url = _remove_param_from_url(audio_url, "from")- duration = media_data.get("duration")- if duration:- duration = int(duration) * 1000- return audio_url, duration---def _remove_trackid(thumbnail_url: Optional[str]) -> Optional[str]:- """- ``audio_set`` data is used to create a separate database table in the API.- To make sure that any given ``audio_set`` appears in that table only once,- all the fields for that ``audio_set`` need to have the same values. In- Jamendo, the ``audio_set`` thumbnail has a ``trackid`` query parameter,- which breaks this rule.-- This function removes the ``trackid`` query parameter from the URL to make- all thumbnail values identical for an audio set.- >>> base_url = "https://usercontent.jamendo.com"- >>> url = f"{base_url}?type=album&id=119&width=200&trackid=732"- >>> _remove_trackid(url)- 'https://usercontent.jamendo.com?type=album&id=119&width=200'- """- if thumbnail_url is None:- return- return _remove_param_from_url(thumbnail_url, "trackid")---def _get_audio_set_info(media_data):- url = None- base_url = "https://www.jamendo.com/album/"- audio_set = media_data.get("album_name")- position = media_data.get("position")- thumbnail = _remove_trackid(media_data.get("album_image"))- set_id = media_data.get("album_id")- if set_id and audio_set:- set_slug = (- audio_set.lower().replace(" ", "-").replace("/", "-").replace("--", "")- )- url = _cleanse_url(f"{base_url}{set_id}/{set_slug}")- return set_id, audio_set, position, url, thumbnail---def _get_thumbnail_url(media_data):- return media_data.get("image")---def _get_creator_data(item):- base_url = "https://www.jamendo.com/artist/"- creator_name = item.get("artist_name")- if creator_name is None:- return None, None- creator_id = item.get("artist_id")- creator_idstr = item.get("artist_idstr")- if creator_id is not None and creator_idstr is not None:- creator_url = f"{base_url}{creator_id}/{creator_idstr}"- else:- creator_url = None- return creator_name.strip(), creator_url---def _get_title(item):- return item.get("name")---def _get_metadata(item):- metadata = {}- lyrics = item.get("lyrics")- if lyrics:- metadata["lyrics"] = lyrics- downloads_count = item.get("stats", {}).get("rate_download_total", 0)- listens_count = item.get("stats", {}).get("rate_listened_total", 0)- playlists_count = item.get("stats", {}).get("rate_playlisted_total", 0)- release_date = item.get("releasedate")- if release_date is not None:- metadata["release_date"] = release_date- metadata["downloads"] = downloads_count- metadata["listens"] = listens_count- metadata["playlists"] = playlists_count- return metadata---def _get_tags(item):- # vocal/instrumental- # genre- # instruments- tags = []- musicinfo = item.get("musicinfo")- if musicinfo:- music_type = musicinfo.get("vocalinstrumental")- if music_type:+ @staticmethod+ def _remove_param_from_url(url: str, param: str) -> str:+ """+ Remove a parameter from a provided URL.+ """+ parsed_url = urlsplit(url)+ query = parse_qs(parsed_url.query)+ query.pop(param, None)+ return parsed_url._replace(query=urlencode(query, doseq=True)).geturl()++ def _remove_trackid(self, thumbnail_url: Optional[str]) -> Optional[str]:+ """+ ``audio_set`` data is used to create a separate database table in the API.+ To make sure that any given ``audio_set`` appears in that table only once,+ all the fields for that ``audio_set`` need to have the same values. In+ Jamendo, the ``audio_set`` thumbnail has a ``trackid`` query parameter,+ which breaks this rule.+ This function removes the ``trackid`` query parameter from the URL to make+ all thumbnail values identical for an audio set.+ >>> base_url = "https://usercontent.jamendo.com"+ >>> url = f"{base_url}?type=album&id=119&width=200&trackid=732"+ >>> _remove_trackid(url)+ 'https://usercontent.jamendo.com?type=album&id=119&width=200'+ """+ if thumbnail_url is None:+ return None+ return self._remove_param_from_url(thumbnail_url, "trackid")++ def _get_audio_url(self, data):+ """+ Parses out audio URL, and removes the "from" parameter. Audio URLs have a "from"+ param which seems to encapsulate information about the calling application.+ Example from the API:+ https://prod-1.storage.jamendo.com/?trackid=1532771&format=mp31&from=app-devsite+ This information looks like an API key or secret when returned, so we remove it+ since it's not necessary for serving the audio files.+ >>> base_url = "https://prod-1.storage.jamendo.com/"+ >>> url = f"{base_url}?trackid=1532771&format=mp31&from=app-devsite"+ >>> _remove_param_from_url(url, "from")+ 'https://prod-1.storage.jamendo.com/?trackid=1532771&format=mp31'+ :return: Tuple with main audio file information:+ - audio_url+ - duration (in milliseconds)+ """+ if (audio_url := data.get("audio")) is None:+ return None+ return self._remove_param_from_url(audio_url, "from")++ @staticmethod+ def _get_creator_data(data):+ base_url = "https://www.jamendo.com/artist/"+ if (creator_name := data.get("artist_name")) is None:+ return None, None++ creator_id = data.get("artist_id")+ creator_idstr = data.get("artist_idstr")+ if creator_id is not None and creator_idstr is not None:+ creator_url = f"{base_url}{creator_id}/{creator_idstr}"+ else:+ creator_url = None++ return creator_name.strip(), creator_url++ @staticmethod+ def _get_metadata(data):+ stats = data.get("stats", {})+ metadata = {+ "lyrics": data.get("lyrics") or None,+ "release_date": data.get("releasedate"),+ "downloads": stats.get("rate_download_total", 0),+ "listens": stats.get("rate_listened_total", 0),+ "playlists": stats.get("rate_playlisted_total", 0),+ }+ return {k: v for k, v in metadata.items() if v is not None}++ @staticmethod+ def _get_tags(data):+ tags = []++ musicinfo = data.get("musicinfo", {})+ if music_type := musicinfo.get("vocalinstrumental"):tags.append(music_type)- music_gender = musicinfo.get("gender")- if music_gender:+ if music_gender := musicinfo.get("gender"):tags.append(music_gender)- music_speed = musicinfo.get("speed")- if music_speed:+ if music_speed := musicinfo.get("speed"):tags.append(f"speed_{music_speed}")+for tag_name in ["instruments", "vartags"]:tag_value = musicinfo.get("tags", {}).get(tag_name)if tag_value:- tag_value = [_ for _ in tag_value if _ != "undefined"]- tags.extend(tag_value)- return tags---def _get_genres(item):- genres = item.get("musicinfo", {}).get("tags", {}).get("genres", None)- return genres+ tags.extend([tag for tag in tag_value if tag != "undefined"])++ return tags++ def get_record_data(self, data):+ if (foreign_identifier := data.get("id")) is None:+ return None++ if (foreign_landing_url := data.get("shareurl")) is None:+ return None++ if (audio_url := self._get_audio_url(data)) is None:+ return None++ license_url = data.get("license_ccurl")+ license_info = get_license_info(license_url=license_url)+ if license_info.license is None:+ return None++ duration = data.get("duration")+ if duration:+ duration = int(duration) * 1000+ title = data.get("name")+ thumbnail = data.get("image")+ genres = data.get("musicinfo", {}).get("tags", {}).get("genres")+ creator, creator_url = self._get_creator_data(data)+ metadata = self._get_metadata(data)+ tags = self._get_tags(data)+ # Jamendo only has music+ category = "music"+ # We request only mp32 (VBR) files+ filetype = "mp32"++ # Audio Set data+ set_url = None+ base_url = "https://www.jamendo.com/album/"+ audio_set = data.get("album_name")+ set_position = data.get("position")+ set_thumbnail = self._remove_trackid(data.get("album_image"))+ set_id = data.get("album_id")+ if set_id and audio_set:+ set_slug = (+ audio_set.lower().replace(" ", "-").replace("/", "-").replace("--", "")+ )+ set_url = rewrite_redirected_url(f"{base_url}{set_id}/{set_slug}")+ return {+ "title": title,+ "creator": creator,+ "creator_url": creator_url,+ "foreign_identifier": foreign_identifier,+ "foreign_landing_url": foreign_landing_url,+ "audio_url": audio_url,+ "duration": duration,+ "filetype": filetype,+ "thumbnail_url": thumbnail,+ "license_info": license_info,+ "meta_data": metadata,+ "raw_tags": tags,+ "category": category,+ "genres": genres,+ "set_foreign_id": set_id,+ "audio_set": audio_set,+ "set_position": set_position,+ "set_url": set_url,+ "set_thumbnail": set_thumbnail,+ }-def _get_license(item):- item_license_url = item.get("license_ccurl")- item_license = get_license_info(license_url=item_license_url)- if item_license.license is None:- return None- return item_license---@lru_cache(maxsize=1024)-def _cleanse_url(url_string):- """- Check to make sure that a url is valid, and prepend a protocol if needed- Used to create correct album url by getting a redirect for urls- with special characters, eg `/album/139/nés-funky`- """- return rewrite_redirected_url(url_string)+def main():+ logger.info("Begin: Jamendo data ingestion.")+ ingester = JamendoDataIngester()+ ingester.ingest_records()if __name__ == "__main__":diff --git a/openverse_catalog/dags/providers/provider_workflows.py b/openverse_catalog/dags/providers/provider_workflows.pyindex 9542b514c..415c25b31 100644--- a/openverse_catalog/dags/providers/provider_workflows.py+++ b/openverse_catalog/dags/providers/provider_workflows.py@@ -7,6 +7,7 @@ from providers.provider_api_scripts.brooklyn_museum import BrooklynMuseumDataIngfrom providers.provider_api_scripts.cleveland_museum import ClevelandDataIngesterfrom providers.provider_api_scripts.finnish_museums import FinnishMuseumsDataIngesterfrom providers.provider_api_scripts.inaturalist import INaturalistDataIngester+from providers.provider_api_scripts.jamendo import JamendoDataIngesterfrom providers.provider_api_scripts.metropolitan_museum import MetMuseumDataIngesterfrom providers.provider_api_scripts.museum_victoria import VictoriaDataIngesterfrom providers.provider_api_scripts.provider_data_ingester import ProviderDataIngester@@ -153,6 +154,7 @@ PROVIDER_WORKFLOWS = [),ProviderWorkflow(provider_script="jamendo",+ ingestion_callable=JamendoDataIngester,media_types=("audio",),),ProviderWorkflow(diff --git a/tests/dags/providers/provider_api_scripts/resources/jamendo/last_page.json b/tests/dags/providers/provider_api_scripts/resources/jamendo/last_page.jsondeleted file mode 100644index 286416d97..000000000--- a/tests/dags/providers/provider_api_scripts/resources/jamendo/last_page.json+++ /dev/null@@ -1,48 +0,0 @@-{- "album_id": "119",- "album_image": "https://usercontent.jamendo.com?type=album&id=119&width=200&trackid=732",- "album_name": "Opera I",- "artist_id": "92",- "artist_idstr": "haeresis",- "artist_name": "Haeresis",- "audio": "https://mp3d.jamendo.com/?trackid=732&format=mp32&from=WftSCtIfbfXP90c1jNqsfw%3D%3D%7CNzgGctbCMB1xAW8bJE5uEw%3D%3D",- "audiodownload": "https://mp3d.jamendo.com/download/track/732/mp32/",- "audiodownload_allowed": true,- "duration": 144,- "id": "732",- "image": "https://usercontent.jamendo.com?type=album&id=119&width=200&trackid=732",- "license_ccurl": "http://creativecommons.org/licenses/by-nc/2.0/",- "licenses": {- "ccnc": "true",- "ccnd": "false",- "ccsa": "false",- "probackground": "false",- "prolicensing": "false"- },- "lyrics": "",- "musicinfo": {- "speed": "medium",- "tags": {- "genres": [],- "instruments": [],- "vartags": []- },- "vocalinstrumental": "instrumental"- },- "name": "Thoughtful",- "position": 6,- "prourl": "",- "releasedate": "2005-04-12",- "shareurl": "https://www.jamendo.com/track/732",- "shorturl": "https://jamen.do/t/732",- "stats": {- "avgnote": 0,- "dislikes": 0,- "favorited": 66,- "likes": 0,- "notes": 0,- "playlisted": 92,- "rate_downloads_total": 2826,- "rate_listened_total": 5616- }-}diff --git a/tests/dags/providers/provider_api_scripts/resources/jamendo/page1.json b/tests/dags/providers/provider_api_scripts/resources/jamendo/page1.jsondeleted file mode 100644index c2119e704..000000000--- a/tests/dags/providers/provider_api_scripts/resources/jamendo/page1.json+++ /dev/null@@ -1,201 +0,0 @@-[- {- "album_id": "119",- "album_image": "https://usercontent.jamendo.com?type=album&id=119&width=200&trackid=730",- "album_name": "Opera I",- "artist_id": "92",- "artist_idstr": "haeresis",- "artist_name": "Haeresis",- "audio": "https://mp3d.jamendo.com/?trackid=730&format=mp32&from=3qvpQaRnh2Xki6EPtPKE9Q%3D%3D%7CwO7vlB7s%2F4Ax3zxnu5b7oA%3D%3D",- "audiodownload": "https://mp3d.jamendo.com/download/track/730/mp32/",- "audiodownload_allowed": true,- "duration": 136,- "id": "730",- "image": "https://usercontent.jamendo.com?type=album&id=119&width=200&trackid=730",- "license_ccurl": "http://creativecommons.org/licenses/by-nc/2.0/",- "licenses": {- "ccnc": "true",- "ccnd": "false",- "ccsa": "false",- "probackground": "false",- "prolicensing": "false"- },- "lyrics": "",- "musicinfo": {- "speed": "medium",- "tags": {- "genres": [],- "instruments": [],- "vartags": []- },- "vocalinstrumental": "instrumental"- },- "name": "Giants",- "position": 4,- "prourl": "",- "releasedate": "2005-04-12",- "shareurl": "https://www.jamendo.com/track/730",- "shorturl": "https://jamen.do/t/730",- "stats": {- "avgnote": 0,- "dislikes": 0,- "favorited": 66,- "likes": 0,- "notes": 0,- "playlisted": 89,- "rate_downloads_total": 4668,- "rate_listened_total": 5694- }- },- {- "album_id": "119",- "album_image": "https://usercontent.jamendo.com?type=album&id=119&width=200&trackid=731",- "album_name": "Opera I",- "artist_id": "92",- "artist_idstr": "haeresis",- "artist_name": "Haeresis",- "audio": "https://mp3d.jamendo.com/?trackid=731&format=mp32&from=SrzQ0HI5HB2acTFp8Erxhw%3D%3D%7C04BHE7pblSM64LS6NT2yMw%3D%3D",- "audiodownload": "https://mp3d.jamendo.com/download/track/731/mp32/",- "audiodownload_allowed": true,- "duration": 202,- "id": "731",- "image": "https://usercontent.jamendo.com?type=album&id=119&width=200&trackid=731",- "license_ccurl": "http://creativecommons.org/licenses/by-nc/2.0/",- "licenses": {- "ccnc": "true",- "ccnd": "false",- "ccsa": "false",- "probackground": "false",- "prolicensing": "false"- },- "lyrics": "",- "musicinfo": {- "speed": "medium",- "tags": {- "genres": [],- "instruments": [],- "vartags": []- },- "vocalinstrumental": "instrumental"- },- "name": "Through the storm",- "position": 5,- "prourl": "",- "releasedate": "2005-04-12",- "shareurl": "https://www.jamendo.com/track/731",- "shorturl": "https://jamen.do/t/731",- "stats": {- "avgnote": 0,- "dislikes": 0,- "favorited": 66,- "likes": 0,- "notes": 0,- "playlisted": 92,- "rate_downloads_total": 4438,- "rate_listened_total": 5625- }- },- {- "album_id": "119",- "album_image": "https://usercontent.jamendo.com?type=album&id=119&width=200&trackid=732",- "album_name": "Opera I",- "artist_id": "92",- "artist_idstr": "haeresis",- "artist_name": "Haeresis",- "audio": "https://mp3d.jamendo.com/?trackid=732&format=mp32&from=WftSCtIfbfXP90c1jNqsfw%3D%3D%7CNzgGctbCMB1xAW8bJE5uEw%3D%3D",- "audiodownload": "https://mp3d.jamendo.com/download/track/732/mp32/",- "audiodownload_allowed": true,- "duration": 144,- "id": "732",- "image": "https://usercontent.jamendo.com?type=album&id=119&width=200&trackid=732",- "license_ccurl": "http://creativecommons.org/licenses/by-nc/2.0/",- "licenses": {- "ccnc": "true",- "ccnd": "false",- "ccsa": "false",- "probackground": "false",- "prolicensing": "false"- },- "lyrics": "",- "musicinfo": {- "speed": "medium",- "tags": {- "genres": [],- "instruments": [],- "vartags": []- },- "vocalinstrumental": "instrumental"- },- "name": "Thoughtful",- "position": 6,- "prourl": "",- "releasedate": "2005-04-12",- "shareurl": "https://www.jamendo.com/track/732",- "shorturl": "https://jamen.do/t/732",- "stats": {- "avgnote": 0,- "dislikes": 0,- "favorited": 66,- "likes": 0,- "notes": 0,- "playlisted": 92,- "rate_downloads_total": 2826,- "rate_listened_total": 5616- }- },- {- "album_id": "36",- "album_image": "https://usercontent.jamendo.com?type=album&id=36&width=200&trackid=287",- "album_name": "Adversit\u00e9",- "artist_id": "17",- "artist_idstr": "alchimie",- "artist_name": "Alchimie",- "audio": "https://mp3d.jamendo.com/?trackid=287&format=mp32&from=zfuzxtKcdaSAup2RiA3CLA%3D%3D%7C3sOlsOWdqT2UOTSYkAetgQ%3D%3D",- "audiodownload": "https://mp3d.jamendo.com/download/track/287/mp32/",- "audiodownload_allowed": true,- "duration": 197,- "id": "287",- "image": "https://usercontent.jamendo.com?type=album&id=36&width=200&trackid=287",- "license_ccurl": "http://creativecommons.org/licenses/by-nc-sa/2.0/",- "licenses": {- "cc": "true",- "ccnc": "true",- "ccnd": "false",- "ccsa": "true",- "probackground": "false",- "prolicensing": "false"- },- "lyrics": "",- "musicinfo": {- "gender": "male",- "speed": "medium",- "tags": {- "genres": [- "pop",- "rock"- ],- "instruments": [],- "vartags": [- "engage"- ]- },- "vocalinstrumental": "vocal"- },- "name": "Port\u00e9es Disparues (Femmes sans visage)",- "position": 3,- "prourl": "",- "releasedate": "2005-03-24",- "shareurl": "https://www.jamendo.com/track/287",- "shorturl": "https://jamen.do/t/287",- "stats": {- "avgnote": 0,- "dislikes": 0,- "favorited": 104,- "likes": 0,- "notes": 0,- "playlisted": 158,- "rate_downloads_total": 9092,- "rate_listened_total": 6469- }- }-]diff --git a/tests/dags/providers/provider_api_scripts/resources/jamendo/page2.json b/tests/dags/providers/provider_api_scripts/resources/jamendo/page2.jsondeleted file mode 100644index 215c07f08..000000000--- a/tests/dags/providers/provider_api_scripts/resources/jamendo/page2.json+++ /dev/null@@ -1,50 +0,0 @@-[- {- "album_id": "119",- "album_image": "https://usercontent.jamendo.com?type=album&id=119&width=200&trackid=732",- "album_name": "Opera I",- "artist_id": "92",- "artist_idstr": "haeresis",- "artist_name": "Haeresis",- "audio": "https://mp3d.jamendo.com/?trackid=732&format=mp32&from=WftSCtIfbfXP90c1jNqsfw%3D%3D%7CNzgGctbCMB1xAW8bJE5uEw%3D%3D",- "audiodownload": "https://mp3d.jamendo.com/download/track/732/mp32/",- "audiodownload_allowed": true,- "duration": 144,- "id": "732",- "image": "https://usercontent.jamendo.com?type=album&id=119&width=200&trackid=732",- "license_ccurl": "http://creativecommons.org/licenses/by-nc/2.0/",- "licenses": {- "ccnc": "true",- "ccnd": "false",- "ccsa": "false",- "probackground": "false",- "prolicensing": "false"- },- "lyrics": "",- "musicinfo": {- "speed": "medium",- "tags": {- "genres": [],- "instruments": [],- "vartags": []- },- "vocalinstrumental": "instrumental"- },- "name": "Thoughtful",- "position": 6,- "prourl": "",- "releasedate": "2005-04-12",- "shareurl": "https://www.jamendo.com/track/732",- "shorturl": "https://jamen.do/t/732",- "stats": {- "avgnote": 0,- "dislikes": 0,- "favorited": 66,- "likes": 0,- "notes": 0,- "playlisted": 92,- "rate_downloads_total": 2826,- "rate_listened_total": 5616- }- }-]diff --git a/tests/dags/providers/provider_api_scripts/test_jamendo.py b/tests/dags/providers/provider_api_scripts/test_jamendo.pyindex a51f96ecd..5e23c1a9e 100644--- a/tests/dags/providers/provider_api_scripts/test_jamendo.py+++ b/tests/dags/providers/provider_api_scripts/test_jamendo.py@@ -1,29 +1,34 @@import json-import loggingfrom pathlib import Pathfrom unittest.mock import patchimport pytestfrom common.licenses import LicenseInfo-from providers.provider_api_scripts import jamendo+from providers.provider_api_scripts.jamendo import JamendoDataIngesterRESOURCES = Path(__file__).parent.resolve() / "resources/jamendo"-logging.basicConfig(- format="%(asctime)s - %(name)s - %(levelname)s: %(message)s",- level=logging.DEBUG,-)-@pytest.fixture(autouse=True)-def cleanse_url():- with patch("providers.provider_api_scripts.jamendo._cleanse_url") as mock_cleanse:+def rewrite_redirected_url():+ with (+ patch(+ "providers.provider_api_scripts.jamendo.rewrite_redirected_url"+ ) as class_mock,+ patch("common.urls.rewrite_redirected_url") as module_mock,+ ):# Prevent calling out to Jamendo & speed up tests- mock_cleanse.side_effect = lambda x: x+ # We need to patch it in both namespaces because `rewrite_redirected_url` is used+ # directly in the JamendoDataIngester, as well as by `get_license_info`.+ class_mock.side_effect = lambda x: x+ module_mock.side_effect = lambda x: xyield+jamendo = JamendoDataIngester()++@pytest.mark.parametrize("url, param, expected",[@@ -41,168 +46,27 @@ def test_remove_param_from_url(url, param, expected):assert actual == expected-def test_get_image_pages_returns_correctly_with_none_json():- expect_result = None- with patch.object(- jamendo.delayed_requester, "get_response_json", return_value=None- ):- actual_result = jamendo._get_batch_json()- assert actual_result == expect_result---def test_get_image_pages_returns_correctly_with_no_results():- expect_result = None- with patch.object(jamendo.delayed_requester, "get_response_json", return_value={}):- actual_result = jamendo._get_batch_json()- assert actual_result == expect_result[email protected]("json", [None, {}]) # No results+def test_get_batch_data_returns_correctly(json):+ assert jamendo.get_batch_data(json) is None-def test_get_query_params_adds_offset():- actual_qp = jamendo._get_query_params(offset=200)+def test_get_next_query_params_adds_offset():+ actual_qp = jamendo.get_next_query_params({"offset": 0})assert actual_qp["offset"] == 200-def test_get_query_params_leaves_other_keys():- actual_qp = jamendo._get_query_params(- offset=200, default_query_params={"test": "value"}- )+def test_get_next_query_params_leaves_other_keys():+ actual_qp = jamendo.get_next_query_params({"offset": 200, "test": "value"})assert actual_qp["test"] == "value"assert len(actual_qp.keys()) == 2-def test_get_items():- with open(RESOURCES / "page1.json") as f:- first_response = json.load(f)- with patch.object(jamendo, "_get_batch_json", side_effect=[first_response, []]):- expected_image_count = 4- actual_image_count = jamendo._get_items()- assert expected_image_count == actual_image_count---def test_process_item_batch_handles_example_batch():- with open(RESOURCES / "audio_data_example.json") as f:- items_batch = [json.load(f)]- with patch.object(jamendo.audio_store, "add_item", return_value=1) as mock_add:- jamendo._process_item_batch(items_batch)- mock_add.assert_called_once()- _, actual_call_args = mock_add.call_args_list[0]- expected_call_args = {- "audio_set": "Opera I",- "audio_url": "https://mp3d.jamendo.com/?trackid=732&format=mp32",- "category": "music",- "creator": "Haeresis",- "creator_url": "https://www.jamendo.com/artist/92/haeresis",- "duration": 144000,- "filetype": "mp32",- "foreign_identifier": "732",- "foreign_landing_url": "https://www.jamendo.com/track/732",- "genres": [],- "license_info": LicenseInfo(- license="by-nc",- version="2.0",- url="https://creativecommons.org/licenses/by-nc/2.0/",- raw_url="http://creativecommons.org/licenses/by-nc/2.0/",- ),- "meta_data": {- "downloads": 0,- "listens": 5616,- "playlists": 0,- "release_date": "2005-04-12",- },- "raw_tags": ["instrumental", "speed_medium"],- "set_foreign_id": "119",- "set_position": 6,- "set_thumbnail": "https://usercontent.jamendo.com?type=album&id=119&width=200",- "set_url": "https://www.jamendo.com/album/119/opera-i",- "thumbnail_url": "https://usercontent.jamendo.com?type=album&id=119&width=200&trackid=732",- "title": "Thoughtful",- }- assert actual_call_args == expected_call_args---def test_extract_audio_data_returns_none_when_media_data_none():- actual_image_info = jamendo._extract_audio_data(None)- expected_image_info = None- assert actual_image_info is expected_image_info---def test_extract_audio_data_returns_none_when_no_foreign_id():- with open(RESOURCES / "audio_data_example.json") as f:- audio_data = json.load(f)- audio_data.pop("shareurl", None)- actual_image_info = jamendo._extract_audio_data(audio_data)- expected_image_info = None- assert actual_image_info is expected_image_info---def test_extract_audio_data_returns_none_when_no_audio_url():- with open(RESOURCES / "audio_data_example.json") as f:- audio_data = json.load(f)- audio_data.pop("audio", None)- actual_audio_info = jamendo._extract_audio_data(audio_data)- assert actual_audio_info is None---def test_extract_audio_data_returns_none_when_no_license():- with open(RESOURCES / "audio_data_example.json") as f:- audio_data = json.load(f)- audio_data.pop("license_ccurl", None)- actual_audio_info = jamendo._extract_audio_data(audio_data)- assert actual_audio_info is None---def test_get_audio_set_info():- with open(RESOURCES / "audio_data_example.json") as f:- audio_data = json.load(f)- actual_audio_set_info = jamendo._get_audio_set_info(audio_data)- expected_audio_set_info = (- "119",- "Opera I",- 6,- "https://www.jamendo.com/album/119/opera-i",- "https://usercontent.jamendo.com?type=album&id=119&width=200",- )- assert actual_audio_set_info == expected_audio_set_info---def test_get_creator_data():- with open(RESOURCES / "audio_data_example.json") as f:- audio_data = json.load(f)- actual_creator, actual_creator_url = jamendo._get_creator_data(audio_data)- expected_creator = "Haeresis"- expected_creator_url = "https://www.jamendo.com/artist/92/haeresis"-- assert actual_creator == expected_creator- assert actual_creator_url == expected_creator_url---def test_get_creator_data_handles_no_url():+def test_get_record_data():with open(RESOURCES / "audio_data_example.json") as f:- audio_data = json.load(f)- audio_data.pop("artist_idstr", None)- expected_creator = "Haeresis"-- actual_creator, actual_creator_url = jamendo._get_creator_data(audio_data)- assert actual_creator == expected_creator- assert actual_creator_url is None---def test_get_creator_data_returns_none_when_no_artist():- with open(RESOURCES / "audio_data_example.json") as f:- audio_data = json.load(f)- audio_data.pop("artist_name", None)- actual_creator, actual_creator_url = jamendo._get_creator_data(audio_data)-- assert actual_creator is None- assert actual_creator_url is None---def test_extract_audio_data_handles_example_dict():- with open(RESOURCES / "audio_data_example.json") as f:- audio_data = json.load(f)-- actual_image_info = jamendo._extract_audio_data(audio_data)- expected_image_info = {+ item_data = json.load(f)+ actual = jamendo.get_record_data(item_data)+ expected = {"audio_set": "Opera I","audio_url": "https://mp3d.jamendo.com/?trackid=732&format=mp32","category": "music",@@ -216,7 +80,7 @@ def test_extract_audio_data_handles_example_dict():"license_info": LicenseInfo(license="by-nc",version="2.0",- url="https://creativecommons.org/licenses/by-nc/2.0/",+ url="https://creativecommons.org/licenses/by-nc/2.0",raw_url="http://creativecommons.org/licenses/by-nc/2.0/",),"meta_data": {@@ -233,7 +97,43 @@ def test_extract_audio_data_handles_example_dict():"thumbnail_url": "https://usercontent.jamendo.com?type=album&id=119&width=200&trackid=732","title": "Thoughtful",}- assert actual_image_info == expected_image_info+ assert actual == expected+++ "required_field",+ [+ "shareurl", # foreign identifier+ "audio", # audio url+ "license_ccurl", # license+ ],+)+def test_get_record_data_returns_none_when_required_data_is_null(required_field):+ with open(RESOURCES / "audio_data_example.json") as f:+ audio_data = json.load(f)+ audio_data.pop(required_field, None)+ assert jamendo.get_record_data(audio_data) is None+++def test_get_record_data_handles_no_creator_url():+ with open(RESOURCES / "audio_data_example.json") as f:+ audio_data = json.load(f)+ audio_data.pop("artist_idstr", None)+ expected_creator = "Haeresis"++ actual_data = jamendo.get_record_data(audio_data)+ assert actual_data.get("creator") == expected_creator+ assert actual_data.get("creator_url") is None+++def test_get_record_data_handles_no_artist():+ with open(RESOURCES / "audio_data_example.json") as f:+ audio_data = json.load(f)+ audio_data.pop("artist_name", None)+ actual_data = jamendo.get_record_data(audio_data)++ assert actual_data.get("creator") is None+ assert actual_data.get("creator_url") is Nonedef test_get_tags():