Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Refactor Wikimedia Commons to use ProviderDataIngester (#614)
Staci Cooper18decf9b70f4
diff --git a/openverse_catalog/dags/common/storage/audio.py b/openverse_catalog/dags/common/storage/audio.pyindex e30e708e7..40980e0f3 100644--- a/openverse_catalog/dags/common/storage/audio.py+++ b/openverse_catalog/dags/common/storage/audio.py@@ -65,6 +65,7 @@ class AudioStore(MediaStore):alt_files: Optional[Dict] = None,source: Optional[str] = None,ingestion_type: Optional[str] = None,+ **kwargs,):"""Add information for a single audio to the AudioStore.diff --git a/openverse_catalog/dags/common/storage/image.py b/openverse_catalog/dags/common/storage/image.pyindex c8c67ea57..fafff07c3 100644--- a/openverse_catalog/dags/common/storage/image.py+++ b/openverse_catalog/dags/common/storage/image.py@@ -56,6 +56,7 @@ class ImageStore(MediaStore):watermarked: Optional[str] = "f",source: Optional[str] = None,ingestion_type: Optional[str] = None,+ **kwargs,):"""Add information for a single image to the ImageStore.diff --git a/openverse_catalog/dags/providers/provider_api_scripts/provider_data_ingester.py b/openverse_catalog/dags/providers/provider_api_scripts/provider_data_ingester.pyindex 89b079407..cba1848bd 100644--- a/openverse_catalog/dags/providers/provider_api_scripts/provider_data_ingester.py+++ b/openverse_catalog/dags/providers/provider_api_scripts/provider_data_ingester.py@@ -315,7 +315,9 @@ class ProviderDataIngester(ABC):return batch, should_continue- def get_response_json(self, query_params: dict, endpoint: str | None = None):+ def get_response_json(+ self, query_params: dict, endpoint: str | None = None, **kwargs+ ):"""Make the actual API requests needed to ingest a batch. This can be overriddenin order to support APIs that require multiple requests, for example.@@ -325,6 +327,7 @@ class ProviderDataIngester(ABC):self.retries,query_params,headers=self.headers,+ **kwargs,)def get_should_continue(self, response_json):diff --git a/openverse_catalog/dags/providers/provider_api_scripts/wikimedia_commons.py b/openverse_catalog/dags/providers/provider_api_scripts/wikimedia_commons.pyindex cba2cb3e6..d73c9f289 100644--- a/openverse_catalog/dags/providers/provider_api_scripts/wikimedia_commons.py+++ b/openverse_catalog/dags/providers/provider_api_scripts/wikimedia_commons.py@@ -15,15 +15,12 @@ import loggingfrom copy import deepcopyfrom datetime import datetime, timedelta, timezonefrom typing import Optional-from urllib.parse import urlparseimport lxml.html as htmlfrom common.constants import AUDIO, IMAGEfrom common.licenses import get_license_infofrom common.loader import provider_details as prov-from common.requester import DelayedRequester-from common.storage.audio import AudioStore-from common.storage.image import ImageStore+from providers.provider_api_scripts.provider_data_ingester import ProviderDataIngesterlogger = logging.getLogger(__name__)@@ -31,440 +28,431 @@ logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s: %(message)s", level=logging.INFO)-LIMIT = 250# The 10000 is a bit arbitrary, but needs to be larger than the mean# number of uses per file (globally) in the response_json, or we will# fail without a continuation token. The largest example seen so far# had a little over 1000 usesMEAN_GLOBAL_USAGE_LIMIT = 10000-DELAY = 1HOST = "commons.wikimedia.org"-ENDPOINT = f"https://{HOST}/w/api.php"-PROVIDER = prov.WIKIMEDIA_DEFAULT_PROVIDER-AUDIO_PROVIDER = prov.WIKIMEDIA_AUDIO_PROVIDER-DEFAULT_REQUEST_HEADERS = {"User-Agent": prov.UA_STRING}-DEFAULT_QUERY_PARAMS = {- "action": "query",- "generator": "allimages",- "gaisort": "timestamp",- "gaidir": "newer",- "gailimit": LIMIT,- "prop": "imageinfo|globalusage",- "iiprop": "url|user|dimensions|extmetadata|mediatype|size|metadata",- "gulimit": LIMIT,- "gunamespace": 0,- "format": "json",-}PAGES_PATH = ["query", "pages"]+IMAGE_MEDIATYPES = {"BITMAP", "DRAWING"}AUDIO_MEDIATYPES = {"AUDIO"}# Other types available in the API are OFFICE for pdfs and VIDEO-delayed_requester = DelayedRequester(DELAY)-audio_store = AudioStore(provider=AUDIO_PROVIDER)-image_store = ImageStore(provider=PROVIDER)---def main(date):- """- This script pulls the data for a given date from the Wikimedia- Commons API, and writes it into a .TSV file to be eventually read- into our DB.-- Required Arguments:-- date: Date String in the form YYYY-MM-DD. This is the date for- which running the script will pull data.- """-- logger.info(f"Processing Wikimedia Commons API for date: {date}")-- continue_token = {}- total_audio = 0- total_images = 0- start_timestamp, end_timestamp = _derive_timestamp_pair(date)-- while True:- media_batch, continue_token = _get_media_batch(- start_timestamp, end_timestamp, continue_token=continue_token- )- logger.info(f"Continue Token: {continue_token}")- image_pages = _get_image_pages(media_batch)- if image_pages:- _process_image_pages(image_pages)- total_images = image_store.total_items- total_audio = audio_store.total_items- logger.info(f"Total: {total_images} images and {total_audio} audio so far")- if not continue_token:- break-- audio_store.commit()- image_store.commit()- logger.info(f"Total images: {image_store.total_items}")- logger.info(f"Total audios: {audio_store.total_items}")- logger.info("Terminated!")---def _derive_timestamp_pair(date):- date_obj = datetime.strptime(date, "%Y-%m-%d")- utc_date = date_obj.replace(tzinfo=timezone.utc)- start_timestamp = str(int(utc_date.timestamp()))- end_timestamp = str(int((utc_date + timedelta(days=1)).timestamp()))- return start_timestamp, end_timestamp---def _get_media_batch(start_timestamp, end_timestamp, continue_token=None, retries=5):- if continue_token is None:- continue_token = {}- query_params = _build_query_params(- start_timestamp, end_timestamp, continue_token=continue_token- )- image_batch = None- new_continue_token = None- for _ in range(MEAN_GLOBAL_USAGE_LIMIT):- response_json = delayed_requester.get_response_json(- ENDPOINT,- retries=retries,- query_params=query_params,- headers=DEFAULT_REQUEST_HEADERS,- timeout=60,- )-- if response_json is None:- break- else:- new_continue_token = response_json.pop("continue", {})- logger.debug(f"new_continue_token: {new_continue_token}")- query_params.update(new_continue_token)- image_batch = _merge_response_jsons(image_batch, response_json)-- if "batchcomplete" in response_json:- logger.debug("Found batchcomplete")- break-- return image_batch, new_continue_token---def _get_image_pages(image_batch):- image_pages = None-- if image_batch is not None:- image_pages = image_batch.get("query", {}).get("pages")-- if image_pages is None:- logger.warning(f"No pages in the image_batch: {image_batch}")- else:- logger.info(f"Got {len(image_pages)} pages")-- return image_pages---def _process_image_pages(image_pages):- for i in image_pages.values():- _process_media_data(i)---def _build_query_params(- start_date,- end_date,- continue_token=None,- default_query_params=None,-):- if continue_token is None:- continue_token = {}- if default_query_params is None:- default_query_params = DEFAULT_QUERY_PARAMS- query_params = default_query_params.copy()- query_params.update(- gaistart=start_date,- gaiend=end_date,- )- query_params.update(continue_token)- return query_params---def _merge_response_jsons(left_json, right_json):- # Note that we will keep the continue value from the right json in- # the merged output! This is because we assume the right json is- # the later one in the sequence of responses.- if left_json is None:- return right_json-- left_pages = _get_image_pages(left_json)- right_pages = _get_image_pages(right_json)-- if (- left_pages is None- or right_pages is None- or left_pages.keys() != right_pages.keys()- ):- logger.warning("Cannot merge responses with different pages!")- merged_json = None- else:- merged_json = deepcopy(left_json)- merged_json.update(right_json)- merged_pages = _get_image_pages(merged_json)- merged_pages.update(- {k: _merge_image_pages(left_pages[k], right_pages[k]) for k in left_pages}- )-- return merged_json---def _merge_image_pages(left_page, right_page):- merged_page = deepcopy(left_page)- merged_globalusage = left_page.get("globalusage", []) + right_page.get(- "globalusage", []- )- merged_page.update(right_page)- merged_page["globalusage"] = merged_globalusage-- return merged_page---def _extract_file_type(media_info):- filetype = media_info.get("url", "").split(".")[-1]- return None if filetype == "" else filetype--def _process_media_data(media_data):- foreign_id = media_data.get("pageid")- logger.debug(f"Processing page ID: {foreign_id}")- media_info = _get_image_info_dict(media_data)- valid_mediatype = _check_mediatype(media_info)- if not valid_mediatype:- return None- license_info = _get_license_info(media_info)- if license_info.url is None:- return None- media_url = media_info.get("url")- if media_url is None:- return None- creator, creator_url = _extract_creator_info(media_info)- title = _extract_title(media_info)- filesize = media_info.get("size", 0) # in bytes- filetype = _extract_file_type(media_info)- parsed_data = {- "media_url": media_url,- "foreign_landing_url": media_info.get("descriptionshorturl"),- "foreign_identifier": foreign_id,- "license_info": license_info,- "creator": creator,- "creator_url": creator_url,- "title": title,- "filetype": filetype,- "filesize": filesize,- }-- funcs = {- IMAGE: _add_image,- AUDIO: _add_audio,+class WikimediaCommonsDataIngester(ProviderDataIngester):+ providers = {+ "image": prov.WIKIMEDIA_DEFAULT_PROVIDER,+ "audio": prov.WIKIMEDIA_AUDIO_PROVIDER,}- funcs[valid_mediatype](parsed_data, media_data, media_info)---def _get_value_by_name(key_value_list: list, prop_name: str):- prop_list = [- key_value_pair- for key_value_pair in key_value_list- if key_value_pair["name"] == prop_name- ]- if prop_list:- return prop_list[0].get("value")-+ endpoint = f"https://{HOST}/w/api.php"+ headers = {"User-Agent": prov.UA_STRING}++ # The batch_limit applies to the number of pages received by the API, rather+ # than the number of individual records. This means that for Wikimedia Commons+ # setting a global `ingestion_limit` will still limit the number of records, but+ # the exact limit may not be respected.+ batch_limit = 250++ def __init__(self, conf: dict = None, date: str | None = None):+ self.start_timestamp, self.end_timestamp = self.derive_timestamp_pair(date)+ self.continue_token = {}++ super().__init__(conf, date)++ def get_next_query_params(self, prev_query_params, **kwargs):+ return {+ "action": "query",+ "generator": "allimages",+ "gaisort": "timestamp",+ "gaidir": "newer",+ "gailimit": self.batch_limit,+ "prop": "imageinfo|globalusage",+ "iiprop": "url|user|dimensions|extmetadata|mediatype|size|metadata",+ "gulimit": self.batch_limit,+ "gunamespace": 0,+ "format": "json",+ "gaistart": self.start_timestamp,+ "gaiend": self.end_timestamp,+ **self.continue_token,+ }++ def get_media_type(self, record):+ """Get the media_type of a parsed Record"""+ return record["media_type"]++ def get_response_json(self, query_params):+ """+ Overrides the parent function to make multiple requests until+ we see "batchcomplete", rather than a single request to the+ endpoint. This ensures that global usage data used for calculating+ popularity is tabulated correctly.+ """+ batch_json = None++ for _ in range(MEAN_GLOBAL_USAGE_LIMIT):+ response_json = super().get_response_json(+ query_params,+ timeout=60,+ )++ if response_json is None:+ break+ else:+ # Update continue token for the next request+ self.continue_token = response_json.pop("continue", {})+ query_params.update(self.continue_token)+ logger.info(f"New continue token: {self.continue_token}")++ # Merge this response into the batch+ batch_json = self.merge_response_jsons(batch_json, response_json)++ if "batchcomplete" in response_json:+ logger.info("Found batchcomplete")+ break+ return batch_json++ def get_should_continue(self, response_json):+ # Should not continue if continue_token is Falsy+ return self.continue_token++ def get_batch_data(self, response_json):+ image_pages = self.get_media_pages(response_json)+ if image_pages is not None:+ return image_pages.values()+ return None-def _get_value_by_names(key_value_list: list, prop_names: list):- """Gets the first available value for one of the `prop_names`- property names"""- for prop_name in prop_names:- if val := _get_value_by_name(key_value_list, prop_name):- return val+ def get_media_pages(self, response_json):+ if response_json is not None:+ image_pages = response_json.get("query", {}).get("pages")+ if image_pages is not None:+ logger.info(f"Got {len(image_pages)} pages")+ return image_pages+ logger.warning(f"No pages in the image batch: {response_json}")+ return None-def _parse_audio_file_data(parsed_data: dict, file_metadata: list) -> dict:- streams = _get_value_by_name(file_metadata, "streams")- try:+ def get_record_data(self, record):+ foreign_id = record.get("pageid")+ logger.debug(f"Processing page ID: {foreign_id}")++ media_info = self.extract_media_info_dict(record)++ valid_media_type = self.extract_media_type(media_info)+ if not valid_media_type:+ # Do not process unsupported media types, like Video+ return None++ license_info = self.extract_license_info(media_info)+ if license_info.url is None:+ return None++ media_url = media_info.get("url")+ if media_url is None:+ return None++ creator, creator_url = self.extract_creator_info(media_info)+ title = self.extract_title(media_info)+ filesize = media_info.get("size", 0) # in bytes+ filetype = self.extract_file_type(media_info)+ meta_data = self.create_meta_data_dict(record)++ record_data = {+ "media_url": media_url,+ "foreign_landing_url": media_info.get("descriptionshorturl"),+ "foreign_identifier": foreign_id,+ "license_info": license_info,+ "creator": creator,+ "creator_url": creator_url,+ "title": title,+ "filetype": filetype,+ "filesize": filesize,+ "meta_data": meta_data,+ "media_type": valid_media_type,+ }++ # Extend record_data with media-type specific fields+ funcs = {+ IMAGE: self.get_image_record_data,+ AUDIO: self.get_audio_record_data,+ }+ return funcs[valid_media_type](record_data, media_info)++ def get_image_record_data(self, record_data, media_info):+ """Extend record_data with image-specific fields"""+ record_data["image_url"] = record_data.pop("media_url")+ if record_data["filetype"] == "svg":+ record_data["category"] = "illustration"++ return {+ **record_data,+ "width": media_info.get("width"),+ "height": media_info.get("height"),+ }++ def get_audio_record_data(self, record_data, media_info):+ """Extend record_data with audio-specific fields"""+ record_data["audio_url"] = record_data.pop("media_url")++ duration = int(float(media_info.get("duration", 0)) * 1000)+ record_data["duration"] = duration+ record_data["category"] = self.extract_audio_category(record_data)++ file_metadata = self.parse_audio_file_meta_data(media_info)+ if sample_rate := self.get_value_by_names(+ file_metadata, ["audio_sample_rate", "sample_rate"]+ ):+ record_data["sample_rate"] = sample_rate+ if bit_rate := self.get_value_by_names(+ file_metadata, ["bitrate_nominal", "bitrate"]+ ):+ record_data["bit_rate"] = bit_rate if bit_rate <= 2147483647 else None+ if channels := self.get_value_by_names(+ file_metadata, ["audio_channels", "channels"]+ ):+ record_data["meta_data"]["channels"] = channels++ return record_data++ def parse_audio_file_meta_data(self, media_info):+ """Parse out audio file metadata"""+ metadata = media_info.get("metadata", [])++ streams = self.get_value_by_name(metadata, "streams")if not streams:- audio = _get_value_by_name(file_metadata, "audio")- streams = _get_value_by_name(audio, "streams")- streams_data = [stream["value"] for stream in streams][0]- file_data = _get_value_by_name(streams_data, "header")- if not file_data:- file_data = streams_data- except (IndexError, TypeError):- file_data = []- if sample_rate := _get_value_by_names(- file_data, ["audio_sample_rate", "sample_rate"]- ):- parsed_data["sample_rate"] = sample_rate- if bit_rate := _get_value_by_names(file_data, ["bitrate_nominal", "bitrate"]):- parsed_data["bit_rate"] = bit_rate if bit_rate <= 2147483647 else None- if channels := _get_value_by_names(file_data, ["audio_channels", "channels"]):- parsed_data["meta_data"]["channels"] = channels- return parsed_data---def _extract_audio_category(parsed_data):- """Set category to "pronunciation" for any audio with- pronunciation of a word or a phrase"""- for category in parsed_data["meta_data"].get("categories", []):- if "pronunciation" in category.lower():- return "pronunciation"---def _add_audio(parsed_data, media_data, media_info):- # Converting duration into milliseconds- duration = int(float(media_info.get("duration", 0)) * 1000)- parsed_data["audio_url"] = parsed_data.pop("media_url")- parsed_data["duration"] = duration- parsed_data["meta_data"] = _create_meta_data_dict(media_data)- if not parsed_data.get("category"):- parsed_data["category"] = _extract_audio_category(parsed_data)- file_metadata: list = media_info.get("metadata", [])- parsed_data = _parse_audio_file_data(parsed_data, file_metadata)- audio_store.add_item(**parsed_data)---def _add_image(parsed_data, media_data, media_info):- parsed_data["meta_data"] = _create_meta_data_dict(media_data)- parsed_data["width"] = media_info.get("width")- parsed_data["height"] = media_info.get("height")- parsed_data["image_url"] = parsed_data.pop("media_url")- if parsed_data["filetype"] == "svg":- parsed_data["category"] = "illustration"- image_store.add_item(**parsed_data)---def _get_image_info_dict(media_data):- media_info_list = media_data.get("imageinfo")- if media_info_list:- media_info = media_info_list[0]- else:- media_info = {}- return media_info---def _check_mediatype(media_info):- item_mediatype = media_info.get("mediatype")- if item_mediatype in IMAGE_MEDIATYPES:- return IMAGE- elif item_mediatype in AUDIO_MEDIATYPES:- return AUDIO- else:- logger.debug(- f"Incorrect mediatype: {item_mediatype} not in "+ audio = self.get_value_by_name(metadata, "audio")+ streams = self.get_value_by_name(audio, "streams")++ if streams:+ streams_data = streams[0].get("value", [])+ file_data = self.get_value_by_name(streams_data, "header")+ # Fall back to streams_data+ return file_data or streams_data++ return []++ @staticmethod+ def extract_media_info_dict(media_data):+ media_info_list = media_data.get("imageinfo")+ if media_info_list:+ media_info = media_info_list[0]+ else:+ media_info = {}+ return media_info++ @staticmethod+ def get_value_by_name(key_value_list: list, prop_name: str):+ """Gets the first value for the given `prop_name` in a list of+ key value pairs."""+ if key_value_list is None:+ key_value_list = []++ prop_list = [+ key_value_pair+ for key_value_pair in key_value_list+ if key_value_pair["name"] == prop_name+ ]+ if prop_list:+ return prop_list[0].get("value")++ @staticmethod+ def get_value_by_names(key_value_list: list, prop_names: list):+ """Gets the first available value for one of the `prop_names`+ property names"""+ for prop_name in prop_names:+ if val := WikimediaCommonsDataIngester.get_value_by_name(+ key_value_list, prop_name+ ):+ return val++ @staticmethod+ def extract_media_type(media_info):+ media_type = media_info.get("mediatype")++ if media_type in IMAGE_MEDIATYPES:+ return IMAGE+ elif media_type in AUDIO_MEDIATYPES:+ return AUDIO++ logger.info(+ f"Incorrect mediatype: {media_type} not in "f"valid mediatypes ({IMAGE_MEDIATYPES}, {AUDIO_MEDIATYPES})")return None+ @staticmethod+ def extract_audio_category(parsed_data):+ """Set category to "pronunciation" for any audio with+ pronunciation of a word or a phrase"""+ for category in parsed_data["meta_data"].get("categories", []):+ if "pronunciation" in category.lower():+ return "pronunciation"++ @staticmethod+ def extract_ext_value(media_info: dict, ext_key: str) -> Optional[str]:+ return media_info.get("extmetadata", {}).get(ext_key, {}).get("value")++ @staticmethod+ def extract_title(media_info):+ # Titles often have 'File:filename.jpg' form+ # We remove the 'File:' and extension from title+ title = WikimediaCommonsDataIngester.extract_ext_value(media_info, "ObjectName")+ if title is None:+ title = media_info.get("title")+ if title.startswith("File:"):+ title = title.replace("File:", "", 1)+ last_dot_position = title.rfind(".")+ if last_dot_position > 0:+ possible_extension = title[last_dot_position:]+ if possible_extension.lower() in {".png", ".jpg", ".jpeg", ".ogg", ".wav"}:+ title = title[:last_dot_position]+ return title++ @staticmethod+ def extract_date_info(media_info):+ date_originally_created = WikimediaCommonsDataIngester.extract_ext_value(+ media_info, "DateTimeOriginal"+ )+ last_modified_at_source = WikimediaCommonsDataIngester.extract_ext_value(+ media_info, "DateTime"+ )+ return date_originally_created, last_modified_at_source-def _extract_title(media_info):- # Titles often have 'File:filename.jpg' form- # We remove the 'File:' and extension from title- title = _get_ext_value(media_info, "ObjectName")- if title is None:- title = media_info.get("title")- if title.startswith("File:"):- title = title.replace("File:", "", 1)- last_dot_position = title.rfind(".")- if last_dot_position > 0:- possible_extension = title[last_dot_position:]- if possible_extension.lower() in {".png", ".jpg", ".jpeg", ".ogg", ".wav"}:- title = title[:last_dot_position]- return title---def _extract_date_info(media_info):- date_originally_created = _get_ext_value(media_info, "DateTimeOriginal")- last_modified_at_source = _get_ext_value(media_info, "DateTime")- return date_originally_created, last_modified_at_source---def _extract_creator_info(media_info):- artist_string = _get_ext_value(media_info, "Artist")-- if not artist_string:- return None, None-- artist_elem = html.fromstring(artist_string)- # We take all text to replicate what is shown on Wikimedia Commons- artist_text = "".join(artist_elem.xpath("//text()")).strip()- url_list = list(artist_elem.iterlinks())- artist_url = _cleanse_url(url_list[0][2]) if url_list else None- return artist_text, artist_url+ @staticmethod+ def extract_creator_info(media_info):+ artist_string = WikimediaCommonsDataIngester.extract_ext_value(+ media_info, "Artist"+ )+ if not artist_string:+ return None, None++ artist_elem = html.fromstring(artist_string)+ # We take all text to replicate what is shown on Wikimedia Commons+ artist_text = "".join(artist_elem.xpath("//text()")).strip()+ url_list = list(artist_elem.iterlinks())+ artist_url = url_list[0][2] if url_list else None+ return artist_text, artist_url++ @staticmethod+ def extract_category_info(media_info):+ categories_string = (+ WikimediaCommonsDataIngester.extract_ext_value(media_info, "Categories")+ or ""+ )-def _extract_category_info(media_info):- categories_string = _get_ext_value(media_info, "Categories") or ""+ categories_list = categories_string.split("|")+ return categories_list- categories_list = categories_string.split("|")- return categories_list+ @staticmethod+ def extract_file_type(media_info):+ filetype = media_info.get("url", "").split(".")[-1]+ return None if filetype == "" else filetype+ @staticmethod+ def extract_license_info(media_info):+ license_url = (+ WikimediaCommonsDataIngester.extract_ext_value(media_info, "LicenseUrl")+ or ""+ )+ # TODO Add public domain items+ # if license_url == "":+ # license_name = extract_ext_value(media_info, "LicenseShortName") or ""+ # if license_name.lower() in {"public_domain", "pdm-owner"}:+ # pass++ license_info = get_license_info(license_url=license_url.strip())+ return license_info++ @staticmethod+ def extract_geo_data(media_data):+ geo_properties = {+ "latitude": "GPSLatitude",+ "longitude": "GPSLongitude",+ "map_datum": "GPSMapDatum",+ }+ geo_data = {}+ for (key, value) in geo_properties.items():+ key_value = media_data.get(value, {}).get("value")+ if key_value:+ geo_data[key] = key_value+ return geo_data++ def create_meta_data_dict(self, media_data):+ global_usage_length = len(media_data.get("globalusage", []))+ media_info = self.extract_media_info_dict(media_data)+ date_originally_created, last_modified_at_source = self.extract_date_info(+ media_info+ )+ categories_list = self.extract_category_info(media_info)+ description = self.extract_ext_value(media_info, "ImageDescription")+ meta_data = {+ "global_usage_count": global_usage_length,+ "date_originally_created": date_originally_created,+ "last_modified_at_source": last_modified_at_source,+ "categories": categories_list,+ **self.extract_geo_data(media_data),+ }+ if description:+ description_text = " ".join(+ html.fromstring(description).xpath("//text()")+ ).strip()+ meta_data["description"] = description_text+ return meta_data++ def merge_response_jsons(self, left_json, right_json):+ # Note that we will keep the continue value from the right json in+ # the merged output! This is because we assume the right json is+ # the later one in the sequence of responses.+ if left_json is None:+ return right_json++ left_pages = self.get_media_pages(left_json)+ right_pages = self.get_media_pages(right_json)++ if (+ left_pages is None+ or right_pages is None+ or left_pages.keys() != right_pages.keys()+ ):+ logger.warning("Cannot merge responses with different pages!")+ merged_json = None+ else:+ merged_json = deepcopy(left_json)+ merged_json.update(right_json)+ merged_pages = self.get_media_pages(merged_json)+ merged_pages.update(+ {+ k: self.merge_media_pages(left_pages[k], right_pages[k])+ for k in left_pages+ }+ )++ return merged_json++ def merge_media_pages(self, left_page, right_page):+ merged_page = deepcopy(left_page)+ merged_globalusage = left_page.get("globalusage", []) + right_page.get(+ "globalusage", []+ )+ merged_page.update(right_page)+ merged_page["globalusage"] = merged_globalusage-def _get_license_info(media_info):- license_url = _get_ext_value(media_info, "LicenseUrl") or ""- # TODO Add public domain items- # if license_url == "":- # license_name = _get_ext_value(media_info, "LicenseShortName") or ""- # if license_name.lower() in {"public_domain", "pdm-owner"}:- # pass+ return merged_page- license_info = get_license_info(license_url=license_url.strip())- return license_info+ def derive_timestamp_pair(self, date):+ date_obj = datetime.strptime(date, "%Y-%m-%d")+ utc_date = date_obj.replace(tzinfo=timezone.utc)+ start_timestamp = str(int(utc_date.timestamp()))+ end_timestamp = str(int((utc_date + timedelta(days=1)).timestamp()))+ return start_timestamp, end_timestamp-def _get_geo_data(media_data):- geo_properties = {- "latitude": "GPSLatitude",- "longitude": "GPSLongitude",- "map_datum": "GPSMapDatum",- }- geo_data = {}- for (key, value) in geo_properties.items():- key_value = media_data.get(value, {}).get("value")- if key_value:- geo_data[key] = key_value- return geo_data---def _create_meta_data_dict(media_data):- meta_data = {}- global_usage_length = len(media_data.get("globalusage", []))- media_info = _get_image_info_dict(media_data)- date_originally_created, last_modified_at_source = _extract_date_info(media_info)- categories_list = _extract_category_info(media_info)- description = _get_ext_value(media_info, "ImageDescription")- if description:- description_text = " ".join(- html.fromstring(description).xpath("//text()")- ).strip()- meta_data["description"] = description_text- meta_data["global_usage_count"] = global_usage_length- meta_data["date_originally_created"] = date_originally_created- meta_data["last_modified_at_source"] = last_modified_at_source- meta_data["categories"] = categories_list- meta_data.update(_get_geo_data(media_data))- return meta_data---def _cleanse_url(url_string):- """- Check to make sure that a url is valid, and prepend a protocol if needed- """-- parse_result = urlparse(url_string)-- if parse_result.netloc == HOST:- parse_result = urlparse(url_string, scheme="https")- elif not parse_result.scheme:- parse_result = urlparse(url_string, scheme="http")-- if parse_result.netloc or parse_result.path:- return parse_result.geturl()---def _get_ext_value(media_info: dict, ext_key: str) -> Optional[str]:- return media_info.get("extmetadata", {}).get(ext_key, {}).get("value")+def main(date):+ logger.info(f"Begin: Wikimedia Commons data ingestion for {date}")+ ingester = WikimediaCommonsDataIngester(date)+ ingester.ingest_records()if __name__ == "__main__":diff --git a/openverse_catalog/dags/providers/provider_workflows.py b/openverse_catalog/dags/providers/provider_workflows.pyindex 0c3dde214..0a38eb01b 100644--- a/openverse_catalog/dags/providers/provider_workflows.py+++ b/openverse_catalog/dags/providers/provider_workflows.py@@ -11,6 +11,9 @@ from providers.provider_api_scripts.museum_victoria import VictoriaDataIngesterfrom providers.provider_api_scripts.provider_data_ingester import ProviderDataIngesterfrom providers.provider_api_scripts.science_museum import ScienceMuseumDataIngesterfrom providers.provider_api_scripts.stocksnap import StockSnapDataIngester+from providers.provider_api_scripts.wikimedia_commons import (+ WikimediaCommonsDataIngester,+)@dataclass@@ -188,6 +191,7 @@ PROVIDER_WORKFLOWS = [),ProviderWorkflow(provider_script="wikimedia_commons",+ ingester_class=WikimediaCommonsDataIngester,start_date=datetime(2020, 11, 1),schedule_string="@daily",dated=True,diff --git a/tests/dags/providers/provider_api_scripts/resources/wikimedia/audio_filedata_ogg.json b/tests/dags/providers/provider_api_scripts/resources/wikimedia/audio_filedata_ogg.jsonindex 7be63b51d..d064ffb32 100644--- a/tests/dags/providers/provider_api_scripts/resources/wikimedia/audio_filedata_ogg.json+++ b/tests/dags/providers/provider_api_scripts/resources/wikimedia/audio_filedata_ogg.json@@ -1,98 +1,108 @@-[- {- "name": "version",- "value": 2- },- {- "name": "streams",- "value": [- {- "name": 996071589,- "value": [- {- "name": "serial",- "value": 996071589- },- {- "name": "group",- "value": 0- },- {- "name": "type",- "value": "Vorbis"- },- {- "name": "vendor",- "value": "Lavf58.45.100"- },- {- "name": "length",- "value": 123.768- },- {- "name": "size",- "value": 1235274- },- {- "name": "header",- "value": [- {- "name": "vorbis_version",- "value": 0- },- {- "name": "audio_channels",- "value": 2- },- {- "name": "audio_sample_rate",- "value": 48000- },- {- "name": "bitrate_maximum",- "value": 0- },- {- "name": "bitrate_nominal",- "value": 112000- },- {- "name": "bitrate_minimum",- "value": 0- },- {- "name": "blocksize_0",- "value": 8- },- {- "name": "blocksize_1",- "value": 11- },- {- "name": "framing_flag",- "value": 0- }- ]- },- {- "name": "comments",- "value": [- {- "name": "encoder",- "value": "Lavc58.91.100 libvorbis"- }- ]- }- ]- }- ]- },- {- "name": "length",- "value": 123.768- },- {- "name": "offset",- "value": null- }-]+{+ "descriptionshorturl": "https://commons.wikimedia.org/w/index.php?curid=120786580",+ "descriptionurl": "https://commons.wikimedia.org/wiki/File:Nl-Javaanse_herten.ogg",+ "duration": 2.9,+ "height": 0,+ "metadata": [+ {+ "name": "version",+ "value": 2+ },+ {+ "name": "streams",+ "value": [+ {+ "name": 996071589,+ "value": [+ {+ "name": "serial",+ "value": 996071589+ },+ {+ "name": "group",+ "value": 0+ },+ {+ "name": "type",+ "value": "Vorbis"+ },+ {+ "name": "vendor",+ "value": "Lavf58.45.100"+ },+ {+ "name": "length",+ "value": 123.768+ },+ {+ "name": "size",+ "value": 1235274+ },+ {+ "name": "header",+ "value": [+ {+ "name": "vorbis_version",+ "value": 0+ },+ {+ "name": "audio_channels",+ "value": 2+ },+ {+ "name": "audio_sample_rate",+ "value": 48000+ },+ {+ "name": "bitrate_maximum",+ "value": 0+ },+ {+ "name": "bitrate_nominal",+ "value": 112000+ },+ {+ "name": "bitrate_minimum",+ "value": 0+ },+ {+ "name": "blocksize_0",+ "value": 8+ },+ {+ "name": "blocksize_1",+ "value": 11+ },+ {+ "name": "framing_flag",+ "value": 0+ }+ ]+ },+ {+ "name": "comments",+ "value": [+ {+ "name": "encoder",+ "value": "Lavc58.91.100 libvorbis"+ }+ ]+ }+ ]+ }+ ]+ },+ {+ "name": "length",+ "value": 123.768+ },+ {+ "name": "offset",+ "value": null+ }+ ],+ "size": 26706,+ "url": "https://upload.wikimedia.org/wikipedia/commons/4/4e/Nl-Javaanse_herten.ogg",+ "user": "Marcel coenders",+ "width": 0+}diff --git a/tests/dags/providers/provider_api_scripts/resources/wikimedia/audio_filedata_wav.json b/tests/dags/providers/provider_api_scripts/resources/wikimedia/audio_filedata_wav.jsonindex ef4f72270..507407b40 100644--- a/tests/dags/providers/provider_api_scripts/resources/wikimedia/audio_filedata_wav.json+++ b/tests/dags/providers/provider_api_scripts/resources/wikimedia/audio_filedata_wav.json@@ -1,272 +1,282 @@-[- {- "name": "GETID3_VERSION",- "value": "1.9.20-202006061653"- },- {- "name": "filesize",- "value": 101164- },- {- "name": "avdataoffset",- "value": 44- },- {- "name": "avdataend",- "value": 101164- },- {- "name": "fileformat",- "value": "wav"- },- {- "name": "audio",- "value": [- {- "name": "dataformat",- "value": "wav"- },- {- "name": "bitrate_mode",- "value": "cbr"- },- {- "name": "wformattag",- "value": 1- },- {- "name": "streams",- "value": [- {- "name": 0,- "value": [- {- "name": "codec",- "value": "Pulse Code Modulation (PCM)"- },- {- "name": "channels",- "value": 1- },- {- "name": "sample_rate",- "value": 48000- },- {- "name": "bitrate",- "value": 768000- },- {- "name": "bits_per_sample",- "value": 16- },- {- "name": "wformattag",- "value": 1- },- {- "name": "bitrate_mode",- "value": "cbr"- },- {- "name": "lossless",- "value": true- },- {- "name": "dataformat",- "value": "wav"- },- {- "name": "compression_ratio",- "value": 1- }- ]- }- ]- },- {- "name": "codec",- "value": "Pulse Code Modulation (PCM)"- },- {- "name": "channels",- "value": 1- },- {- "name": "sample_rate",- "value": 48000- },- {- "name": "bitrate",- "value": 768000- },- {- "name": "bits_per_sample",- "value": 16- },- {- "name": "lossless",- "value": true- },- {- "name": "channelmode",- "value": "mono"- },- {- "name": "compression_ratio",- "value": 1- }- ]- },- {- "name": "warning",- "value": [- {- "name": 0,- "value": "Expecting \"RIFF|JUNK|IDVX\" at 101168, found \"\ufffd\ufffd\ufffd\ufffd\" (00 00 00 00 ) - skipping rest of file"- }- ]- },- {- "name": "encoding",- "value": "UTF-8"- },- {- "name": "mime_type",- "value": "audio/wav"- },- {- "name": "riff",- "value": [- {- "name": "raw",- "value": [- {- "name": "fmt ",- "value": [- {- "name": "wFormatTag",- "value": 1- },- {- "name": "nChannels",- "value": 1- },- {- "name": "nSamplesPerSec",- "value": 48000- },- {- "name": "nAvgBytesPerSec",- "value": 96000- },- {- "name": "nBlockAlign",- "value": 2- },- {- "name": "wBitsPerSample",- "value": 16- }- ]- }- ]- },- {- "name": "audio",- "value": [- {- "name": 0,- "value": [- {- "name": "codec",- "value": "Pulse Code Modulation (PCM)"- },- {- "name": "channels",- "value": 1- },- {- "name": "sample_rate",- "value": 48000- },- {- "name": "bitrate",- "value": 768000- },- {- "name": "bits_per_sample",- "value": 16- }- ]- }- ]- },- {- "name": "header_size",- "value": 101152- },- {- "name": "WAVE",- "value": [- {- "name": "fmt ",- "value": [- {- "name": 0,- "value": [- {- "name": "offset",- "value": 12- },- {- "name": "size",- "value": 16- },- {- "name": "data",- "value": "\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffdw\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd"- }- ]- }- ]- },- {- "name": "data",- "value": [- {- "name": 0,- "value": [- {- "name": "offset",- "value": 36- },- {- "name": "size",- "value": 101120- }- ]- }- ]- }- ]- }- ]- },- {- "name": "playtime_seconds",- "value": 1.0533333333333332- },- {- "name": "bitrate",- "value": 768000- },- {- "name": "playtime_string",- "value": "0:01"- },- {- "name": "version",- "value": 2- }-]+{+ "descriptionshorturl": "https://commons.wikimedia.org/w/index.php?curid=120786580",+ "descriptionurl": "https://commons.wikimedia.org/wiki/File:Nl-Javaanse_herten.ogg",+ "duration": 2.9,+ "height": 0,+ "metadata": [+ {+ "name": "GETID3_VERSION",+ "value": "1.9.20-202006061653"+ },+ {+ "name": "filesize",+ "value": 101164+ },+ {+ "name": "avdataoffset",+ "value": 44+ },+ {+ "name": "avdataend",+ "value": 101164+ },+ {+ "name": "fileformat",+ "value": "wav"+ },+ {+ "name": "audio",+ "value": [+ {+ "name": "dataformat",+ "value": "wav"+ },+ {+ "name": "bitrate_mode",+ "value": "cbr"+ },+ {+ "name": "wformattag",+ "value": 1+ },+ {+ "name": "streams",+ "value": [+ {+ "name": 0,+ "value": [+ {+ "name": "codec",+ "value": "Pulse Code Modulation (PCM)"+ },+ {+ "name": "channels",+ "value": 1+ },+ {+ "name": "sample_rate",+ "value": 48000+ },+ {+ "name": "bitrate",+ "value": 768000+ },+ {+ "name": "bits_per_sample",+ "value": 16+ },+ {+ "name": "wformattag",+ "value": 1+ },+ {+ "name": "bitrate_mode",+ "value": "cbr"+ },+ {+ "name": "lossless",+ "value": true+ },+ {+ "name": "dataformat",+ "value": "wav"+ },+ {+ "name": "compression_ratio",+ "value": 1+ }+ ]+ }+ ]+ },+ {+ "name": "codec",+ "value": "Pulse Code Modulation (PCM)"+ },+ {+ "name": "channels",+ "value": 1+ },+ {+ "name": "sample_rate",+ "value": 48000+ },+ {+ "name": "bitrate",+ "value": 768000+ },+ {+ "name": "bits_per_sample",+ "value": 16+ },+ {+ "name": "lossless",+ "value": true+ },+ {+ "name": "channelmode",+ "value": "mono"+ },+ {+ "name": "compression_ratio",+ "value": 1+ }+ ]+ },+ {+ "name": "warning",+ "value": [+ {+ "name": 0,+ "value": "Expecting \"RIFF|JUNK|IDVX\" at 101168, found \"\ufffd\ufffd\ufffd\ufffd\" (00 00 00 00 ) - skipping rest of file"+ }+ ]+ },+ {+ "name": "encoding",+ "value": "UTF-8"+ },+ {+ "name": "mime_type",+ "value": "audio/wav"+ },+ {+ "name": "riff",+ "value": [+ {+ "name": "raw",+ "value": [+ {+ "name": "fmt ",+ "value": [+ {+ "name": "wFormatTag",+ "value": 1+ },+ {+ "name": "nChannels",+ "value": 1+ },+ {+ "name": "nSamplesPerSec",+ "value": 48000+ },+ {+ "name": "nAvgBytesPerSec",+ "value": 96000+ },+ {+ "name": "nBlockAlign",+ "value": 2+ },+ {+ "name": "wBitsPerSample",+ "value": 16+ }+ ]+ }+ ]+ },+ {+ "name": "audio",+ "value": [+ {+ "name": 0,+ "value": [+ {+ "name": "codec",+ "value": "Pulse Code Modulation (PCM)"+ },+ {+ "name": "channels",+ "value": 1+ },+ {+ "name": "sample_rate",+ "value": 48000+ },+ {+ "name": "bitrate",+ "value": 768000+ },+ {+ "name": "bits_per_sample",+ "value": 16+ }+ ]+ }+ ]+ },+ {+ "name": "header_size",+ "value": 101152+ },+ {+ "name": "WAVE",+ "value": [+ {+ "name": "fmt ",+ "value": [+ {+ "name": 0,+ "value": [+ {+ "name": "offset",+ "value": 12+ },+ {+ "name": "size",+ "value": 16+ },+ {+ "name": "data",+ "value": "\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffdw\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd"+ }+ ]+ }+ ]+ },+ {+ "name": "data",+ "value": [+ {+ "name": 0,+ "value": [+ {+ "name": "offset",+ "value": 36+ },+ {+ "name": "size",+ "value": 101120+ }+ ]+ }+ ]+ }+ ]+ }+ ]+ },+ {+ "name": "playtime_seconds",+ "value": 1.0533333333333332+ },+ {+ "name": "bitrate",+ "value": 768000+ },+ {+ "name": "playtime_string",+ "value": "0:01"+ },+ {+ "name": "version",+ "value": 2+ }+ ],+ "size": 26706,+ "url": "https://upload.wikimedia.org/wikipedia/commons/4/4e/Nl-Javaanse_herten.ogg",+ "user": "Marcel coenders",+ "width": 0+}diff --git a/tests/dags/providers/provider_api_scripts/test_wikimedia_commons.py b/tests/dags/providers/provider_api_scripts/test_wikimedia_commons.pyindex 82440989a..9d97cce3d 100644--- a/tests/dags/providers/provider_api_scripts/test_wikimedia_commons.py+++ b/tests/dags/providers/provider_api_scripts/test_wikimedia_commons.py@@ -1,11 +1,13 @@import jsonimport loggingfrom pathlib import Path-from unittest.mock import call, patch+from unittest.mock import patchfrom common.constants import IMAGEfrom common.licenses import get_license_info-from providers.provider_api_scripts import wikimedia_commons as wmc+from providers.provider_api_scripts.wikimedia_commons import (+ WikimediaCommonsDataIngester,+)RESOURCES = Path(__file__).parent.resolve() / "resources/wikimedia"@@ -15,59 +17,64 @@ logging.basicConfig(level=logging.DEBUG,)+wmc = WikimediaCommonsDataIngester(date="2018-01-15")+def test_derive_timestamp_pair():# Note that the timestamps are derived as if input was in UTC.- actual_start_ts, actual_end_ts = wmc._derive_timestamp_pair("2018-01-15")+ actual_start_ts, actual_end_ts = wmc.derive_timestamp_pair("2018-01-15")assert actual_start_ts == "1515974400"assert actual_end_ts == "1516060800"-def test_get_image_pages_returns_correctly_with_continue():+def test_get_media_pages_returns_correctly_with_continue():with open(RESOURCES / "response_small_with_continue.json") as f:resp_dict = json.load(f)expect_result = {"84798633": {"pageid": 84798633, "title": "File:Ambassade1.jpg"}}- actual_result = wmc._get_image_pages(resp_dict)+ actual_result = wmc.get_media_pages(resp_dict)assert actual_result == expect_result-def test_get_image_pages_returns_correctly_with_none_json():- expect_result = None- actual_result = wmc._get_image_pages(None)- assert actual_result == expect_result+def test_get_batch_data_returns_correctly_with_pages():+ with open(RESOURCES / "response_small_with_continue.json") as f:+ resp_dict = json.load(f)+ expect_result = [+ {"pageid": 84798633, "title": "File:Ambassade1.jpg"},+ ]+ actual_result = wmc.get_batch_data(resp_dict)+ assert list(actual_result) == expect_result-def test_get_image_pages_returns_correctly_with_no_pages():++def test_get_batch_data_returns_correctly_with_none_json():expect_result = None- actual_result = wmc._get_image_pages({"batch_complete": ""})+ actual_result = wmc.get_batch_data(None)assert actual_result == expect_result-def test_build_query_params_adds_start_and_end():- actual_qp = wmc._build_query_params("abc", "def", default_query_params={})- assert actual_qp["gaistart"] == "abc"- assert actual_qp["gaiend"] == "def"+def test_get_batch_data_returns_correctly_with_no_pages():+ expect_result = None+ actual_result = wmc.get_batch_data({"batch_complete": ""})+ assert actual_result == expect_result-def test_build_query_params_leaves_other_keys():- actual_qp = wmc._build_query_params(- "abc", "def", default_query_params={"test": "value"}- )- assert actual_qp["test"] == "value"+def test_get_next_query_params_adds_start_and_end():+ actual_qp = wmc.get_next_query_params(prev_query_params={})+ assert actual_qp["gaistart"] == wmc.start_timestamp+ assert actual_qp["gaiend"] == wmc.end_timestamp-def test_build_query_params_adds_continue():- actual_qp = wmc._build_query_params(- "abc",- "def",- {"continuetoken": "next.jpg"},- default_query_params={"test": "value"},+def test_get_next_query_params_adds_continue():+ wmc.continue_token = {"gaicontinue": "200|next.jpg", "continue": "gaicontinue||"}+ actual_qp = wmc.get_next_query_params(+ prev_query_params={},)- assert actual_qp["continuetoken"] == "next.jpg"+ assert actual_qp["gaicontinue"] == "200|next.jpg"+ assert actual_qp["continue"] == "gaicontinue||"-def test_get_image_batch(monkeypatch):+def test_get_response_json(monkeypatch):with open(RESOURCES / "continuation/wmc_pretty1.json") as f:first_response = json.load(f)with open(RESOURCES / "continuation/wmc_pretty2.json") as f:@@ -78,52 +85,44 @@ def test_get_image_batch(monkeypatch):def mock_get_response_json(endpoint, retries, query_params, **kwargs):continue_one = "Edvard_Munch_-_Night_in_Nice_(1891).jpg|nowiki|1281339"continue_two = "Niedercunnersdorf_Gartenweg_12.JPG|dewiki|9849507"+ logging.info(f"Testing with: {query_params}")if "continue" not in query_params:return first_response- elif query_params["gucontinue"] == continue_one:+ elif query_params.get("gucontinue") == continue_one:return second_response- elif query_params["gucontinue"] == continue_two:+ elif query_params.get("gucontinue") == continue_two:return third_responseelse:return Nonewith open(RESOURCES / "continuation/wmc_pretty123.json") as f:expect_image_batch = json.load(f)- expect_image_batch.pop("continue")- expect_continue_token = {- "gaicontinue": (- "20151031230201|Lancelot_'Capability'_BROWN_-_Wilderness_House_"- "Moat_Lane_Hampton_Court_Palace_Hampton_Court_London_KT8_9AR.jpg"- ),- "continue": "gaicontinue||",- }+ expect_continue_token = expect_image_batch.pop("continue")monkeypatch.setattr(wmc.delayed_requester, "get_response_json", mock_get_response_json)- actual_image_batch, actual_continue_token = wmc._get_media_batch(- "2019-01-01", "2019-01-02"- )+ wmc.continue_token = {}+ actual_image_batch = wmc.get_response_json(wmc.get_next_query_params({}))assert actual_image_batch == expect_image_batch- assert actual_continue_token == expect_continue_token+ assert wmc.continue_token == expect_continue_token-def test_get_image_batch_returns_correctly_without_continue(monkeypatch):+def test_get_response_json_returns_correctly_without_continue(monkeypatch):with open(RESOURCES / "response_small_missing_continue.json") as f:resp_dict = json.load(f)+ wmc.continue_token = {}with patch.object(wmc.delayed_requester, "get_response_json", return_value=resp_dict) as mock_response_json:- actual_result, actual_continue = wmc._get_media_batch(- "2019-01-01", "2019-01-02", retries=2- )+ actual_result = wmc.get_response_json(wmc.get_next_query_params({}))expect_result = resp_dictexpect_continue = {}mock_response_json.assert_called_once()- assert actual_continue == expect_continue+ assert wmc.continue_token == expect_continueassert actual_result == expect_result@@ -135,73 +134,73 @@ def test_merge_response_jsons():with open(RESOURCES / "continuation/wmc_pretty1plus2.json") as f:expect_merged_response = json.load(f)- actual_merged_response = wmc._merge_response_jsons(+ actual_merged_response = wmc.merge_response_jsons(left_response,right_response,)assert actual_merged_response == expect_merged_response-def test_merge_image_pages_left_only_with_gu():+def test_merge_media_pages_left_only_with_gu():with open(RESOURCES / "continuation/page_44672185_left.json") as f:left_page = json.load(f)with open(RESOURCES / "continuation/page_44672185_right.json") as f:right_page = json.load(f)- actual_merged_page = wmc._merge_image_pages(left_page, right_page)+ actual_merged_page = wmc.merge_media_pages(left_page, right_page)assert actual_merged_page == left_page-def test_merge_image_pages_left_only_with_gu_backwards():+def test_merge_media_pages_left_only_with_gu_backwards():with open(RESOURCES / "continuation/page_44672185_left.json") as f:left_page = json.load(f)with open(RESOURCES / "continuation/page_44672185_right.json") as f:right_page = json.load(f)- actual_merged_page = wmc._merge_image_pages(right_page, left_page)+ actual_merged_page = wmc.merge_media_pages(right_page, left_page)assert actual_merged_page == left_page-def test_merge_image_pages_neither_have_gu():+def test_merge_media_pages_neither_have_gu():with open(RESOURCES / "continuation/page_44672210_left.json") as f:left_page = json.load(f)with open(RESOURCES / "continuation/page_44672210_right.json") as f:right_page = json.load(f)- actual_merged_page = wmc._merge_image_pages(left_page, right_page)+ actual_merged_page = wmc.merge_media_pages(left_page, right_page)assert actual_merged_page == left_page-def test_merge_image_pages_neigher_have_gu_backwards():+def test_merge_media_pages_neigher_have_gu_backwards():with open(RESOURCES / "continuation/page_44672210_left.json") as f:left_page = json.load(f)with open(RESOURCES / "continuation/page_44672210_right.json") as f:right_page = json.load(f)- actual_merged_page = wmc._merge_image_pages(right_page, left_page)+ actual_merged_page = wmc.merge_media_pages(right_page, left_page)assert actual_merged_page == left_page-def test_merge_image_pages_both_have_gu():+def test_merge_media_pages_both_have_gu():with open(RESOURCES / "continuation/page_44672212_left.json") as f:left_page = json.load(f)with open(RESOURCES / "continuation/page_44672212_right.json") as f:right_page = json.load(f)with open(RESOURCES / "continuation/page_44672212_merged.json") as f:expect_merged_page = json.load(f)- actual_merged_page = wmc._merge_image_pages(left_page, right_page)+ actual_merged_page = wmc.merge_media_pages(left_page, right_page)assert actual_merged_page == expect_merged_pagedef test_extract_title_gets_cleaned_title():image_info = {"extmetadata": {"ObjectName": {"value": "File:filename.jpg"}}}- actual_title = wmc._extract_title(image_info)+ actual_title = wmc.extract_title(image_info)expected_title = "filename"assert actual_title == expected_titleimage_info["title"] = "filename.jpeg"- actual_title = wmc._extract_title(image_info)+ actual_title = wmc.extract_title(image_info)expected_title = "filename"assert actual_title == expected_title-def test_process_media_data_handles_example_dict():+def test_get_record_data_handles_example_dict():"""Converts sample json data to correct image metadata,and calls `add_item` once for a valid image.@@ -209,30 +208,29 @@ def test_process_media_data_handles_example_dict():with open(RESOURCES / "image_data_example.json") as f:media_data = json.load(f)- with patch.object(wmc.image_store, "add_item", return_value=1) as mock_add:- wmc._process_media_data(media_data)+ record_data = wmc.get_record_data(media_data)+expected_license_info = get_license_info(license_url="https://creativecommons.org/licenses/by-sa/4.0")- assert mock_add.call_count == 1- assert mock_add.call_args == call(- foreign_landing_url=(+ assert record_data == {+ "foreign_landing_url": ("https://commons.wikimedia.org/w/index.php?curid=81754323"),- foreign_identifier=81754323,- image_url=(+ "foreign_identifier": 81754323,+ "image_url": ("https://upload.wikimedia.org/wikipedia/commons/2/25/20120925_""PlozevetBretagne_LoneTree_DSC07971_PtrQs.jpg"),- license_info=expected_license_info,- width=5514,- height=3102,- creator="PtrQs",- creator_url="https://commons.wikimedia.org/wiki/User:PtrQs",- title="20120925 PlozevetBretagne LoneTree DSC07971 PtrQs",- filetype="jpg",- filesize=11863148,- meta_data={+ "license_info": expected_license_info,+ "width": 5514,+ "height": 3102,+ "creator": "PtrQs",+ "creator_url": "//commons.wikimedia.org/wiki/User:PtrQs",+ "title": "20120925 PlozevetBretagne LoneTree DSC07971 PtrQs",+ "filetype": "jpg",+ "filesize": 11863148,+ "meta_data": {"description": "SONY DSC","global_usage_count": 0,"date_originally_created": "2012-09-25 16:23:02",@@ -246,67 +244,50 @@ def test_process_media_data_handles_example_dict():"Trees in Finist\u00e8re",],},- )---def test_process_media_data_adds_example_dict():- """- `_process_media_data` calls `ImageStore.add_item` with valid arguments,- and doesn't pass unexpected arguments. Saves the item to the `ImageStore`.- """- with open(RESOURCES / "image_data_example.json") as f:- media_data = json.load(f)- wmc._process_media_data(media_data)- assert wmc.image_store.total_items == 1+ "media_type": "image",+ }-def test_process_media_data_throws_out_invalid_mediatype(monkeypatch):+def test_get_record_data_throws_out_invalid_mediatype(monkeypatch):media_data = {"mediatype": "INVALID"}+ data = wmc.get_record_data(media_data)+ assert data is None- def mock_check_mediatype(image_info):- return False- monkeypatch.setattr(wmc, "_check_mediatype", mock_check_mediatype)- with patch.object(wmc.image_store, "add_item", return_value=1) as mock_add:- wmc._process_media_data(media_data)-- mock_add.assert_not_called()---def test_get_image_info_dict():+def test_extract_media_info_dict():with open(RESOURCES / "image_data_example.json") as f:media_data = json.load(f)with open(RESOURCES / "image_info_from_example_data.json") as f:expect_image_info = json.load(f)- actual_image_info = wmc._get_image_info_dict(media_data)+ actual_image_info = wmc.extract_media_info_dict(media_data)assert actual_image_info == expect_image_info-def test_check_mediatype_with_valid_image_info():+def test_extract_mediatype_with_valid_image_info():with open(RESOURCES / "image_info_from_example_data.json") as f:image_info = json.load(f)- valid_mediatype = wmc._check_mediatype(image_info)+ valid_mediatype = wmc.extract_media_type(image_info)assert valid_mediatype == IMAGE-def test_check_mediatype_with_invalid_mediatype_in_image_info():+def test_extract_mediatype_with_invalid_mediatype_in_image_info():with open(RESOURCES / "image_info_from_example_data.json") as f:image_info = json.load(f)- image_info.update(mediatype="INVALIDTYPE")+ image_info["mediatype"] = "INVALIDTYPE"- valid_mediatype = wmc._check_mediatype(image_info)+ valid_mediatype = wmc.extract_media_type(image_info)assert valid_mediatype is Nonedef test_extract_creator_info_handles_plaintext():with open(RESOURCES / "image_info_artist_string.json") as f:image_info = json.load(f)- actual_creator, actual_creator_url = wmc._extract_creator_info(image_info)+ actual_creator, actual_creator_url = wmc.extract_creator_info(image_info)expect_creator = "Artist Name"expect_creator_url = Noneassert expect_creator == actual_creator@@ -316,7 +297,7 @@ def test_extract_creator_info_handles_plaintext():def test_extract_creator_info_handles_well_formed_link():with open(RESOURCES / "image_info_artist_link.json") as f:image_info = json.load(f)- actual_creator, actual_creator_url = wmc._extract_creator_info(image_info)+ actual_creator, actual_creator_url = wmc.extract_creator_info(image_info)expect_creator = "link text"expect_creator_url = "https://test.com/linkspot"assert expect_creator == actual_creator@@ -326,7 +307,7 @@ def test_extract_creator_info_handles_well_formed_link():def test_extract_creator_info_handles_div_with_no_link():with open(RESOURCES / "image_info_artist_div.json") as f:image_info = json.load(f)- actual_creator, actual_creator_url = wmc._extract_creator_info(image_info)+ actual_creator, actual_creator_url = wmc.extract_creator_info(image_info)expect_creator = "Jona Lendering"expect_creator_url = Noneassert expect_creator == actual_creator@@ -336,10 +317,10 @@ def test_extract_creator_info_handles_div_with_no_link():def test_extract_creator_info_handles_internal_wc_link():with open(RESOURCES / "image_info_artist_internal_link.json") as f:image_info = json.load(f)- actual_creator, actual_creator_url = wmc._extract_creator_info(image_info)+ actual_creator, actual_creator_url = wmc.extract_creator_info(image_info)expect_creator = "NotaRealUser"expect_creator_url = (- "https://commons.wikimedia.org/w/index.php?title=User:NotaRealUser&"+ "//commons.wikimedia.org/w/index.php?title=User:NotaRealUser&""action=edit&redlink=1")assert expect_creator == actual_creator@@ -349,27 +330,27 @@ def test_extract_creator_info_handles_internal_wc_link():def test_extract_creator_info_handles_link_as_partial_text():with open(RESOURCES / "image_info_artist_partial_link.json") as f:image_info = json.load(f)- actual_creator, actual_creator_url = wmc._extract_creator_info(image_info)+ actual_creator, actual_creator_url = wmc.extract_creator_info(image_info)expect_creator = "Jeff & Brian from Eastbourne"expect_creator_url = "https://www.flickr.com/people/16707908@N07"assert expect_creator == actual_creatorassert expect_creator_url == actual_creator_url-def test_get_license_info_finds_license_url():+def test_extract_license_info_finds_license_url():with open(RESOURCES / "image_info_from_example_data.json") as f:image_info = json.load(f)expect_license_url = "https://creativecommons.org/licenses/by-sa/4.0/"- actual_license_url = wmc._get_license_info(image_info).url+ actual_license_url = wmc.extract_license_info(image_info).urlassert actual_license_url == expect_license_url-def test_get_license_url_handles_missing_license_url():+def test_extract_license_url_handles_missing_license_url():with open(RESOURCES / "image_info_artist_partial_link.json") as f:image_info = json.load(f)expect_license_url = None- actual_license_url = wmc._get_license_info(image_info).url+ actual_license_url = wmc.extract_license_info(image_info).urlassert actual_license_url == expect_license_url@@ -380,14 +361,14 @@ def test_create_meta_data_scrapes_text_from_html_description():"Identificatie Titel(s): Allegorie op kunstenaar Francesco Mazzoli, ""bekend als Parmigianino")- actual_description = wmc._create_meta_data_dict(media_data)["description"]+ actual_description = wmc.create_meta_data_dict(media_data)["description"]assert actual_description == expect_descriptiondef test_create_meta_data_tallies_global_usage_count():with open(RESOURCES / "continuation/page_44672185_left.json") as f:media_data = json.load(f)- actual_gu = wmc._create_meta_data_dict(media_data)["global_usage_count"]+ actual_gu = wmc.create_meta_data_dict(media_data)["global_usage_count"]expect_gu = 3assert actual_gu == expect_gu@@ -395,61 +376,71 @@ def test_create_meta_data_tallies_global_usage_count():def test_create_meta_data_tallies_zero_global_usage_count():with open(RESOURCES / "continuation/page_44672185_right.json") as f:media_data = json.load(f)- actual_gu = wmc._create_meta_data_dict(media_data)["global_usage_count"]+ actual_gu = wmc.create_meta_data_dict(media_data)["global_usage_count"]expect_gu = 0assert actual_gu == expect_gu-def test_parse_audio_file_data_parses_ogg_streams():+def test_get_audio_record_data_parses_ogg_streams():with open(RESOURCES / "audio_filedata_ogg.json") as f:file_metadata = json.load(f)- original_data = {"meta_data": {}}- actual_parsed_data = wmc._parse_audio_file_data(original_data, file_metadata)+ original_data = {"media_url": "myurl.com", "meta_data": {}}+ actual_parsed_data = wmc.get_audio_record_data(original_data, file_metadata)expected_parsed_data = {+ "audio_url": "myurl.com","bit_rate": 112000,"sample_rate": 48000,"meta_data": {"channels": 2},}- assert actual_parsed_data == expected_parsed_data+ assert actual_parsed_data.items() >= expected_parsed_data.items()-def test_parse_audio_file_data_parses_wav_audio_data():+def test_get_audio_record_data_parses_wav_audio_data():with open(RESOURCES / "audio_filedata_wav.json") as f:file_metadata = json.load(f)- original_data = {"meta_data": {}}- actual_parsed_data = wmc._parse_audio_file_data(original_data, file_metadata)+ original_data = {"media_url": "myurl.com", "meta_data": {}}+ actual_parsed_data = wmc.get_audio_record_data(original_data, file_metadata)expected_parsed_data = {+ "audio_url": "myurl.com","bit_rate": 768000,"sample_rate": 48000,"meta_data": {"channels": 1},}- assert actual_parsed_data == expected_parsed_data+ assert actual_parsed_data.items() >= expected_parsed_data.items()-def test_parse_audio_file_data_parses_wav_audio_data_missing_streams():+def test_get_audio_record_data_parses_wav_audio_data_missing_streams():with open(RESOURCES / "audio_filedata_wav.json") as f:file_metadata = json.load(f)+ original_data = {"media_url": "myurl.com", "meta_data": {}}# Remove any actual audio metadata- file_metadata = file_metadata[:5] + file_metadata[6:]- original_data = {"meta_data": {}}- actual_parsed_data = wmc._parse_audio_file_data(original_data, file_metadata)-+ file_metadata["metadata"] = (+ file_metadata["metadata"][:5] + file_metadata["metadata"][6:]+ )+ actual_parsed_data = wmc.get_audio_record_data(original_data, file_metadata)+ expected_parsed_data = {+ "audio_url": "myurl.com",+ "meta_data": {},+ }# No data is available, so nothing should be added- assert actual_parsed_data == original_data+ assert actual_parsed_data.items() >= expected_parsed_data.items()-def test_parse_audio_file_data_parses_wav_invalid_bit_rate():+def test_get_audio_record_data_parses_wav_invalid_bit_rate():with open(RESOURCES / "audio_filedata_wav.json") as f:file_metadata = json.load(f)+ original_data = {"media_url": "myurl.com", "meta_data": {}}# Set the bit rate higher than the int max- file_metadata[5]["value"][3]["value"][0]["value"][3]["value"] = 4294967294- original_data = {"meta_data": {}}+ file_metadata["metadata"][5]["value"][3]["value"][0]["value"][3][+ "value"+ ] = 4294967294expected_parsed_data = {+ "audio_url": "myurl.com","bit_rate": None,"sample_rate": 48000,"meta_data": {"channels": 1},}- actual_parsed_data = wmc._parse_audio_file_data(original_data, file_metadata)- assert actual_parsed_data == expected_parsed_data+ actual_parsed_data = wmc.get_audio_record_data(original_data, file_metadata)+ assert actual_parsed_data.items() >= expected_parsed_data.items()