Skip to content

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

Wikimedia: re-attempt large batches with reduced parameter selection (#1008)

Madison Swain-Bowdenc476f923c1ac
diff --git a/DAGs.md b/DAGs.md
index 76d2836b6..6979a3230 100644
--- a/DAGs.md
+++ b/DAGs.md
@@ -574,23 +574,241 @@ is undocumented.
## `wikimedia_commons_workflow`
-Content Provider: Wikimedia Commons
+**Content Provider:** Wikimedia Commons
+
+**ETL Process:** Use the API to identify all CC-licensed images.
+
+**Output:** TSV file containing the image, the respective meta-data.
+
+### Notes
+
+Rate limit of no more than 200 requests/second, and we are required to set a
+unique User-Agent field
+([docs](https://www.mediawiki.org/wiki/Wikimedia_REST_API#Terms_and_conditions)).
+
+Wikimedia Commons uses an implementation of the
+[MediaWiki API](https://www.mediawiki.org/wiki/API:Main_page). This API is
+incredibly complex in the level of configuration you can provide when querying,
+and as such it can also be quite abstruse. The most straightforward docs can be
+found on the
+[Wikimedia website directly](https://commons.wikimedia.org/w/api.php?action=help&modules=query),
+as these show all the parameters available. Specifications on queries can also
+be found on the [query page](https://www.mediawiki.org/wiki/API:Query).
+
+Different kinds of queries can be made against the API using "modules", we use
+the [allimages module](https://www.mediawiki.org/wiki/API:Allimages), which lets
+us search for images in a given time range (see `"generator": "allimages"` in
+the query params).
+
+Many queries will return results in batches, with the API supplying a "continue"
+token. This token is used on subsequent calls to tell the API where to start the
+next set of results from; it functions as a page offset
+([docs](https://www.mediawiki.org/wiki/API:Query#Continuing_queries)).
+
+We can also specify what kinds of information we want for the query. Wikimedia
+has a massive amount of data on it, so it only returns what we ask for. The
+fields that are returned are defined by the
+[properties](https://www.mediawiki.org/wiki/API:Properties) or "props"
+parameter. Sub-properties can also be defined, with the parameter name of the
+sub-property determined by an abbreviation of the higher-level property. For
+instance, if our property is "imageinfo" and we want to set sub-property values,
+we would define those in "iiprops".
+
+The data within a property is paginated as well, Wikimedia will handle iteration
+through the property sub-pages using the "continue" token
+([see here for more details](https://www.mediawiki.org/wiki/API:Properties#Additional_notes)).
+
+Depending on the kind of property data that's being returned, it's possible for
+the API to iterate extensively on a specific media item. What Wikimedia is
+iterating over in these cases can be gleaned from the "continue" token. Those
+tokens take the form of, as I understand it,
+"<primary-iterator>||<next-iteration-prop>", paired with an "<XX>continue" value
+for the property being iterated over. For example, if we're were iterating over
+a set of image properties, the token might look like:
-ETL Process: Use the API to identify all CC-licensed images.
-
-Output: TSV file containing the image, the respective meta-data.
+```
+{
+ "iicontinue": "The_Railway_Chronicle_1844.pdf|20221209222801",
+ "gaicontinue": "20221209222614|NTUL-0527100_英國產業革命史略.pdf",
+ "continue": "gaicontinue||globalusage",
+}
+```
-Notes: https://commons.wikimedia.org/wiki/API:Main_page No rate limit specified.
+In this case, we're iterating over the "global all images" generator
+(gaicontinue) as our primary iterator, with the "image properties" (iicontinue)
+as the secondary continue iterator. The "globalusage" property would be the next
+property to iterate over. It's also possible for multiple sub-properties to be
+iterated over simultaneously, in which case the "continue" token would not have
+a secondary value (e.g. `gaicontinue||`).
+
+In most runs, the "continue" key will be `gaicontinue||` after the first
+request, which means that we have more than one batch to iterate over for the
+primary iterator. Some days will have fewer images than the batch limit but
+still have multiple batches of content on the secondary iterator, which means
+the "continue" key may not have a primary iteration component (e.g.
+`||globalusage`). This token can also be seen when the first request has more
+data in the secondary iterator, before we've processed any data on the primary
+iterator.
+
+Occasionally, the ingester will come across a piece of media that has many
+results for the property it's iterating over. An example of this can include an
+item being on many pages, this it would have many "global usage" results. In
+order to process the entire batch, we have to iterate over _all_ of the returned
+results; Wikimedia does not provide a mechanism to "skip to the end" of a batch.
+On numerous occasions, this iteration has been so extensive that the pull media
+task has hit the task's timeout. To avoid this, we limit the number of
+iterations we make for parsing through a sub-property's data. If we hit the
+limit, we re-issue the original query _without_ requesting properties that
+returned large amounts of data. Unfortunately, this means that we will **not**
+have that property's data for these items the second time around (e.g.
+popularity data if we needed to skip global usage). In the case of popularity,
+especially since the problem with these images is that they're so popular, we
+want to preserve that information where possible! So we cache the popularity
+data from previous iterations and use it in subsequent ones if we come across
+the same item again.
+
+Below are some specific references to various properties, with examples for
+cases where they might exceed the limit. Technically, it's feasible for almost
+any property to exceed the limit, but these are the ones that we've seen in
+practice.
+
+#### `imageinfo`
+
+[Docs](https://commons.wikimedia.org/w/api.php?action=help&modules=query%2Bimageinfo)
+
+[Example where metadata has hundreds of data points](https://commons.wikimedia.org/wiki/File:The_Railway_Chronicle_1844.pdf#metadata)
+(see "Metadata" table, which may need to be expanded).
+
+For these requests, we can remove the `metadata` property from the `iiprops`
+parameter to avoid this issue on subsequent iterations.
+
+#### `globalusage`
+
+[Docs](https://commons.wikimedia.org/w/api.php?action=help&modules=query%2Bglobalusage)
+
+[Example where an image is used on almost every wiki](https://commons.wikimedia.org/w/index.php?curid=4298234).
+
+For these requests, we can remove the `globalusage` property from the `prop`
+parameter entirely and eschew the popularity data for these items.
## `wikimedia_reingestion_workflow`
-Content Provider: Wikimedia Commons
+**Content Provider:** Wikimedia Commons
+
+**ETL Process:** Use the API to identify all CC-licensed images.
+
+**Output:** TSV file containing the image, the respective meta-data.
+
+### Notes
+
+Rate limit of no more than 200 requests/second, and we are required to set a
+unique User-Agent field
+([docs](https://www.mediawiki.org/wiki/Wikimedia_REST_API#Terms_and_conditions)).
+
+Wikimedia Commons uses an implementation of the
+[MediaWiki API](https://www.mediawiki.org/wiki/API:Main_page). This API is
+incredibly complex in the level of configuration you can provide when querying,
+and as such it can also be quite abstruse. The most straightforward docs can be
+found on the
+[Wikimedia website directly](https://commons.wikimedia.org/w/api.php?action=help&modules=query),
+as these show all the parameters available. Specifications on queries can also
+be found on the [query page](https://www.mediawiki.org/wiki/API:Query).
+
+Different kinds of queries can be made against the API using "modules", we use
+the [allimages module](https://www.mediawiki.org/wiki/API:Allimages), which lets
+us search for images in a given time range (see `"generator": "allimages"` in
+the query params).
+
+Many queries will return results in batches, with the API supplying a "continue"
+token. This token is used on subsequent calls to tell the API where to start the
+next set of results from; it functions as a page offset
+([docs](https://www.mediawiki.org/wiki/API:Query#Continuing_queries)).
+
+We can also specify what kinds of information we want for the query. Wikimedia
+has a massive amount of data on it, so it only returns what we ask for. The
+fields that are returned are defined by the
+[properties](https://www.mediawiki.org/wiki/API:Properties) or "props"
+parameter. Sub-properties can also be defined, with the parameter name of the
+sub-property determined by an abbreviation of the higher-level property. For
+instance, if our property is "imageinfo" and we want to set sub-property values,
+we would define those in "iiprops".
+
+The data within a property is paginated as well, Wikimedia will handle iteration
+through the property sub-pages using the "continue" token
+([see here for more details](https://www.mediawiki.org/wiki/API:Properties#Additional_notes)).
+
+Depending on the kind of property data that's being returned, it's possible for
+the API to iterate extensively on a specific media item. What Wikimedia is
+iterating over in these cases can be gleaned from the "continue" token. Those
+tokens take the form of, as I understand it,
+"<primary-iterator>||<next-iteration-prop>", paired with an "<XX>continue" value
+for the property being iterated over. For example, if we're were iterating over
+a set of image properties, the token might look like:
-ETL Process: Use the API to identify all CC-licensed images.
-
-Output: TSV file containing the image, the respective meta-data.
+```
+{
+ "iicontinue": "The_Railway_Chronicle_1844.pdf|20221209222801",
+ "gaicontinue": "20221209222614|NTUL-0527100_英國產業革命史略.pdf",
+ "continue": "gaicontinue||globalusage",
+}
+```
-Notes: https://commons.wikimedia.org/wiki/API:Main_page No rate limit specified.
+In this case, we're iterating over the "global all images" generator
+(gaicontinue) as our primary iterator, with the "image properties" (iicontinue)
+as the secondary continue iterator. The "globalusage" property would be the next
+property to iterate over. It's also possible for multiple sub-properties to be
+iterated over simultaneously, in which case the "continue" token would not have
+a secondary value (e.g. `gaicontinue||`).
+
+In most runs, the "continue" key will be `gaicontinue||` after the first
+request, which means that we have more than one batch to iterate over for the
+primary iterator. Some days will have fewer images than the batch limit but
+still have multiple batches of content on the secondary iterator, which means
+the "continue" key may not have a primary iteration component (e.g.
+`||globalusage`). This token can also be seen when the first request has more
+data in the secondary iterator, before we've processed any data on the primary
+iterator.
+
+Occasionally, the ingester will come across a piece of media that has many
+results for the property it's iterating over. An example of this can include an
+item being on many pages, this it would have many "global usage" results. In
+order to process the entire batch, we have to iterate over _all_ of the returned
+results; Wikimedia does not provide a mechanism to "skip to the end" of a batch.
+On numerous occasions, this iteration has been so extensive that the pull media
+task has hit the task's timeout. To avoid this, we limit the number of
+iterations we make for parsing through a sub-property's data. If we hit the
+limit, we re-issue the original query _without_ requesting properties that
+returned large amounts of data. Unfortunately, this means that we will **not**
+have that property's data for these items the second time around (e.g.
+popularity data if we needed to skip global usage). In the case of popularity,
+especially since the problem with these images is that they're so popular, we
+want to preserve that information where possible! So we cache the popularity
+data from previous iterations and use it in subsequent ones if we come across
+the same item again.
+
+Below are some specific references to various properties, with examples for
+cases where they might exceed the limit. Technically, it's feasible for almost
+any property to exceed the limit, but these are the ones that we've seen in
+practice.
+
+#### `imageinfo`
+
+[Docs](https://commons.wikimedia.org/w/api.php?action=help&modules=query%2Bimageinfo)
+
+[Example where metadata has hundreds of data points](https://commons.wikimedia.org/wiki/File:The_Railway_Chronicle_1844.pdf#metadata)
+(see "Metadata" table, which may need to be expanded).
+
+For these requests, we can remove the `metadata` property from the `iiprops`
+parameter to avoid this issue on subsequent iterations.
+
+#### `globalusage`
+
+[Docs](https://commons.wikimedia.org/w/api.php?action=help&modules=query%2Bglobalusage)
+
+[Example where an image is used on almost every wiki](https://commons.wikimedia.org/w/index.php?curid=4298234).
+
+For these requests, we can remove the `globalusage` property from the `prop`
+parameter entirely and eschew the popularity data for these items.
## `wordpress_workflow`
diff --git a/openverse_catalog/dags/common/operators/__init__.py b/openverse_catalog/dags/common/operators/__init__.py
deleted file mode 100644
index e69de29bb..000000000
diff --git a/openverse_catalog/dags/providers/provider_api_scripts/wikimedia_commons.py b/openverse_catalog/dags/providers/provider_api_scripts/wikimedia_commons.py
index 6a60400bf..662dd2a7d 100644
--- a/openverse_catalog/dags/providers/provider_api_scripts/wikimedia_commons.py
+++ b/openverse_catalog/dags/providers/provider_api_scripts/wikimedia_commons.py
@@ -1,19 +1,116 @@
"""
-Content Provider: Wikimedia Commons
+**Content Provider:** Wikimedia Commons
-ETL Process: Use the API to identify all CC-licensed images.
+**ETL Process:** Use the API to identify all CC-licensed images.
-Output: TSV file containing the image, the respective
+**Output:** TSV file containing the image, the respective
meta-data.
-Notes: https://commons.wikimedia.org/wiki/API:Main_page
- No rate limit specified.
-"""
+### Notes
+
+Rate limit of no more than 200 requests/second, and we are required to set a unique
+User-Agent field ([docs](https://www.mediawiki.org/wiki/Wikimedia_REST_API#Terms_and_conditions)).
+
+Wikimedia Commons uses an implementation of the
+[MediaWiki API](https://www.mediawiki.org/wiki/API:Main_page). This API is incredibly
+complex in the level of configuration you can provide when querying, and as such it can
+also be quite abstruse. The most straightforward docs can be found on the
+[Wikimedia website directly](https://commons.wikimedia.org/w/api.php?action=help&modules=query),
+as these show all the parameters available. Specifications on queries can also be found
+on the [query page](https://www.mediawiki.org/wiki/API:Query).
+
+Different kinds of queries can be made against the API using "modules", we use the
+[allimages module](https://www.mediawiki.org/wiki/API:Allimages), which lets us search
+for images in a given time range (see `"generator": "allimages"` in the query params).
+
+Many queries will return results in batches, with the API supplying a "continue" token.
+This token is used on subsequent calls to tell the API where to start the next set of
+results from; it functions as a page offset ([docs](https://www.mediawiki.org/wiki/API:Query#Continuing_queries)).
+
+We can also specify what kinds of information we want for the query. Wikimedia has a
+massive amount of data on it, so it only returns what we ask for. The fields that are
+returned are defined by the [properties](https://www.mediawiki.org/wiki/API:Properties)
+or "props" parameter. Sub-properties can also be defined, with the parameter name of
+the sub-property determined by an abbreviation of the higher-level property. For
+instance, if our property is "imageinfo" and we want to set sub-property values, we
+would define those in "iiprops".
+
+The data within a property is paginated as well, Wikimedia will handle iteration through
+the property sub-pages using the "continue" token
+([see here for more details](https://www.mediawiki.org/wiki/API:Properties#Additional_notes)).
+
+Depending on the kind of property data that's being returned, it's possible for the API
+to iterate extensively on a specific media item. What Wikimedia is iterating over in
+these cases can be gleaned from the "continue" token. Those tokens take the form of,
+as I understand it, "<primary-iterator>||<next-iteration-prop>", paired with an
+"<XX>continue" value for the property being iterated over. For example, if we're
+were iterating over a set of image properties, the token might look like:
+
+```
+{
+ "iicontinue": "The_Railway_Chronicle_1844.pdf|20221209222801",
+ "gaicontinue": "20221209222614|NTUL-0527100_英國產業革命史略.pdf",
+ "continue": "gaicontinue||globalusage",
+}
+```
+
+In this case, we're iterating over the "global all images" generator (gaicontinue) as
+our primary iterator, with the "image properties" (iicontinue) as the secondary continue
+iterator. The "globalusage" property would be the next property to iterate over. It's
+also possible for multiple sub-properties to be iterated over simultaneously, in which
+case the "continue" token would not have a secondary value (e.g. `gaicontinue||`).
+
+In most runs, the "continue" key will be `gaicontinue||` after the first request, which
+means that we have more than one batch to iterate over for the primary iterator. Some
+days will have fewer images than the batch limit but still have multiple batches of
+content on the secondary iterator, which means the "continue" key may not have a primary
+iteration component (e.g. `||globalusage`). This token can also be seen when the first
+request has more data in the secondary iterator, before we've processed any data on
+the primary iterator.
+
+Occasionally, the ingester will come across a piece of media that has many results for
+the property it's iterating over. An example of this can include an item being on many
+pages, this it would have many "global usage" results. In order to process the entire
+batch, we have to iterate over *all* of the returned results; Wikimedia does not provide
+a mechanism to "skip to the end" of a batch. On numerous occasions, this iteration has
+been so extensive that the pull media task has hit the task's timeout. To avoid this,
+we limit the number of iterations we make for parsing through a sub-property's data. If
+we hit the limit, we re-issue the original query *without* requesting properties that
+returned large amounts of data. Unfortunately, this means that we will
+**not** have that property's data for these items the second time around (e.g.
+popularity data if we needed to skip global usage). In the case of popularity,
+especially since the problem with these images is that they're so popular, we want to
+preserve that information where possible! So we cache the popularity data from
+previous iterations and use it in subsequent ones if we come across the same
+item again.
+
+Below are some specific references to various properties, with examples for cases where
+they might exceed the limit. Technically, it's feasible for almost any property to
+exceed the limit, but these are the ones that we've seen in practice.
+
+#### `imageinfo`
+[Docs](https://commons.wikimedia.org/w/api.php?action=help&modules=query%2Bimageinfo)
+
+[Example where metadata has hundreds of data points](https://commons.wikimedia.org/wiki/File:The_Railway_Chronicle_1844.pdf#metadata)
+(see "Metadata" table, which may need to be expanded).
+
+For these requests, we can remove the `metadata` property from the `iiprops` parameter
+to avoid this issue on subsequent iterations.
+
+#### `globalusage`
+[Docs](https://commons.wikimedia.org/w/api.php?action=help&modules=query%2Bglobalusage)
+
+[Example where an image is used on almost every wiki](https://commons.wikimedia.org/w/index.php?curid=4298234).
+
+For these requests, we can remove the `globalusage` property from the `prop` parameter
+entirely and eschew the popularity data for these items.
+""" # noqa: E501
import argparse
import logging
from copy import deepcopy
from datetime import datetime, timedelta, timezone
+from types import MappingProxyType
import lxml.html as html
from common.constants import AUDIO, IMAGE
@@ -23,21 +120,6 @@ from providers.provider_api_scripts.provider_data_ingester import ProviderDataIn
logger = logging.getLogger(__name__)
-logging.basicConfig(
- format="%(asctime)s - %(name)s - %(levelname)s: %(message)s", level=logging.INFO
-)
-
-# 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 uses
-MEAN_GLOBAL_USAGE_LIMIT = 10000
-HOST = "commons.wikimedia.org"
-PAGES_PATH = ["query", "pages"]
-
-IMAGE_MEDIATYPES = {"BITMAP", "DRAWING"}
-AUDIO_MEDIATYPES = {"AUDIO"}
-# Other types available in the API are OFFICE for pdfs and VIDEO
class WikimediaCommonsDataIngester(ProviderDataIngester):
@@ -45,35 +127,91 @@ class WikimediaCommonsDataIngester(ProviderDataIngester):
"image": prov.WIKIMEDIA_DEFAULT_PROVIDER,
"audio": prov.WIKIMEDIA_AUDIO_PROVIDER,
}
- endpoint = f"https://{HOST}/w/api.php"
+ host = "commons.wikimedia.org"
+ endpoint = f"https://{host}/w/api.php"
headers = {"User-Agent": prov.UA_STRING}
+ # 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 uses
+ mean_global_usage_limit = 10000
+ # Total number of attempts to retrieve global usage pages for a given batch.
+ # These can be very large, so we need to limit the number of attempts otherwise
+ # the DAG will hit the timeout when it comes across these items.
+ # See: https://github.com/WordPress/openverse-catalog/issues/725
+ max_page_iteration_before_give_up = 100
+
+ image_mediatypes = {"BITMAP", "DRAWING"}
+ audio_mediatypes = {"AUDIO"}
+ # Other types available in the API are OFFICE for pdfs and VIDEO
+
# 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
+ class ReturnProps:
+ """Different sets of properties to return from the API."""
+
+ # All normal media info, plus popularity info by global usage
+ query_all = "imageinfo|globalusage"
+ # Just media info, used where there's too much global usage data to parse
+ query_no_popularity = "imageinfo"
+
+ # All media info we care about
+ media_all = "url|user|dimensions|extmetadata|mediatype|size|metadata"
+ # Everything minus the metadata, which is only necessary for audio and can
+ # balloon for PDFs which are considered images by Wikimedia
+ media_no_metadata = "url|user|dimensions|extmetadata|mediatype|size"
+
+ # MappingProxy effectively provides a frozen dictionary, since this is defined
+ # at the class level and technically mutable.
+ default_props = MappingProxyType(
+ {
+ "prop": ReturnProps.query_all,
+ "iiprop": ReturnProps.media_all,
+ }
+ )
+
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.start_timestamp, self.end_timestamp = self.derive_timestamp_pair(self.date)
self.continue_token = {}
+ self.current_props = self.default_props.copy()
+ self.popularity_cache: dict[str, int] = {}
def get_next_query_params(self, prev_query_params, **kwargs):
+ # NOTE: If more sub-properties are added here, an additional contingency for
+ # iterating over that property's "continue" token will need to be added
+ # to the `adjust_parameters_for_next_iteration` function, otherwise the
+ # ingestion could get stuck in an infinite loop.
return {
+ # The type of action being taken for the API request
"action": "query",
+ # What "generator" to use for returning results, in this case "allimages"
"generator": "allimages",
+ # How to sort the "global all images" (gai) results
"gaisort": "timestamp",
+ # How to order the results
"gaidir": "newer",
+ # The number of "all images" results to return per request
"gailimit": self.batch_limit,
- "prop": "imageinfo|globalusage",
- "iiprop": "url|user|dimensions|extmetadata|mediatype|size|metadata",
+ # The number of "global usage" results to return per request
"gulimit": self.batch_limit,
+ # What namespace to search in, 0 is the main namespace
+ # https://www.mediawiki.org/wiki/Help:Namespaces
"gunamespace": 0,
"format": "json",
+ # The timestamp to start the search from
"gaistart": self.start_timestamp,
+ # The timestamp to end the search at
"gaiend": self.end_timestamp,
+ # The current properties to use for the request
+ **self.current_props,
+ # The current continue token to use for the request provided by Wikimedia
**self.continue_token,
}
@@ -81,7 +219,7 @@ class WikimediaCommonsDataIngester(ProviderDataIngester):
"""Get the media_type of a parsed Record"""
return record["media_type"]
- def get_response_json(self, query_params):
+ def get_response_json(self, query_params, **kwargs):
"""
Get the response data from the API.
@@ -89,28 +227,51 @@ class WikimediaCommonsDataIngester(ProviderDataIngester):
we see "batchcomplete", rather than a single request to the
endpoint. This ensures that global usage data used for calculating
popularity is tabulated correctly.
+
+ This also dynamically adjust the query parameters based on the response sizes
+ for a given continue token. For more information see the DAG description.
"""
batch_json = None
+ gaicontinue = None
+ iteration_count = 0
- for _ in range(MEAN_GLOBAL_USAGE_LIMIT):
+ for _ in range(self.mean_global_usage_limit):
response_json = super().get_response_json(
query_params,
timeout=60,
)
- if response_json is None:
- break
+ # Update continue token for the next request
+ self.continue_token = response_json.pop("continue", {})
+ query_params.update(self.continue_token)
+ logger.info(f"Continue token for next iteration: {self.continue_token}")
+
+ current_gaicontinue = self.continue_token.get("gaicontinue")
+ logger.debug(f"{current_gaicontinue=}")
+ if current_gaicontinue == gaicontinue:
+ # gaicontinue token can be None if all available results fit within
+ # the batch limit, so we don't need to make an exception if it's None
+ iteration_count += 1
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}")
+ # Reset the iteration count if the continue token has changed
+ iteration_count = 0
+ gaicontinue = current_gaicontinue
+
+ if iteration_count >= self.max_page_iteration_before_give_up:
+ logger.warning(
+ f"Hit iteration count limit for '{gaicontinue}', "
+ "re-attempting with a bare token"
+ )
+ self.adjust_parameters_for_next_iteration(gaicontinue)
+ break
- # Merge this response into the batch
- batch_json = self.merge_response_jsons(batch_json, response_json)
+ # 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")
+ # Reset the search props for the next batch
+ self.current_props = self.default_props.copy()
break
return batch_json
@@ -124,7 +285,8 @@ class WikimediaCommonsDataIngester(ProviderDataIngester):
return image_pages.values()
return None
- def get_media_pages(self, response_json):
+ @staticmethod
+ def get_media_pages(response_json):
if response_json is not None:
image_pages = response_json.get("query", {}).get("pages")
if image_pages is not None:
@@ -136,7 +298,6 @@ class WikimediaCommonsDataIngester(ProviderDataIngester):
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)
@@ -180,7 +341,8 @@ class WikimediaCommonsDataIngester(ProviderDataIngester):
}
return funcs[valid_media_type](record_data, media_info)
- def get_image_record_data(self, record_data, media_info):
+ @staticmethod
+ def get_image_record_data(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":
@@ -233,6 +395,29 @@ class WikimediaCommonsDataIngester(ProviderDataIngester):
return []
+ def adjust_parameters_for_next_iteration(self, gaicontinue: str | None) -> None:
+ """
+ Adjust the parameters for the next iteration. This removes properties based
+ on what continue token is being iterated over, using heuristics determined by
+ observation from the values that caused the overage.
+ """
+ if "gucontinue" in self.continue_token:
+ # Exclude global usage info (i.e. popularity) from the query
+ self.current_props["prop"] = self.ReturnProps.query_no_popularity
+ if "iicontinue" in self.continue_token:
+ # Exclude metadata from the query
+ self.current_props["iiprop"] = self.ReturnProps.media_no_metadata
+
+ # In order to appropriately adjust the continue token, we need to preserve the
+ # primary iterator (if there is one) and reset the secondary iterator.
+ current_continue = self.continue_token.get("continue", "||")
+ reset_continue = current_continue.split("||")[0]
+
+ self.continue_token = {
+ "gaicontinue": gaicontinue,
+ "continue": f"{reset_continue}||",
+ }
+
@staticmethod
def extract_media_info_dict(media_data):
media_info_list = media_data.get("imageinfo")
@@ -268,15 +453,17 @@ class WikimediaCommonsDataIngester(ProviderDataIngester):
@staticmethod
def extract_media_type(media_info):
media_type = media_info.get("mediatype")
+ image_mediatypes = WikimediaCommonsDataIngester.image_mediatypes
+ audio_mediatypes = WikimediaCommonsDataIngester.audio_mediatypes
- if media_type in IMAGE_MEDIATYPES:
+ if media_type in image_mediatypes:
return IMAGE
- elif media_type in AUDIO_MEDIATYPES:
+ elif media_type in audio_mediatypes:
return AUDIO
logger.info(
- f"Incorrect mediatype: {media_type} not in "
- f"valid mediatypes ({IMAGE_MEDIATYPES}, {AUDIO_MEDIATYPES})"
+ f"Ignoring mediatype: {media_type} not in "
+ f"valid mediatypes ({image_mediatypes}, {audio_mediatypes})"
)
return None
@@ -382,8 +569,27 @@ class WikimediaCommonsDataIngester(ProviderDataIngester):
geo_data[key] = key_value
return geo_data
+ def extract_global_usage(self, media_data) -> int:
+ """
+ Extract the global usage count from the media data.
+ The global usage count serves as a proxy for popularity data, since it
+ represents how many pages across all available wikis a media item is used on.
+ This uses a cache to record previous values for a given foreign ID, because
+ it is possible that we might encounter a media item several times based on the
+ querying method used (see "props" above). Not all results will have the same
+ (if any) usage data, so we want to record and cache the highest value. Most
+ items have no global usage data, so we only cache items that have a value.
+ """
+ global_usage_count = len(media_data.get("globalusage", []))
+ foreign_id = media_data["pageid"]
+ cached_usage_count = self.popularity_cache.get(foreign_id, 0)
+ max_usage_count = max(global_usage_count, cached_usage_count)
+ # Only cache if it's greater than zero, otherwise it'll just take up space
+ if max_usage_count > 0:
+ self.popularity_cache[foreign_id] = max_usage_count
+ return max_usage_count
+
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
@@ -391,7 +597,7 @@ class WikimediaCommonsDataIngester(ProviderDataIngester):
categories_list = self.extract_category_info(media_info)
description = self.extract_ext_value(media_info, "ImageDescription")
meta_data = {
- "global_usage_count": global_usage_length,
+ "global_usage_count": self.extract_global_usage(media_data),
"date_originally_created": date_originally_created,
"last_modified_at_source": last_modified_at_source,
"categories": categories_list,
@@ -434,7 +640,8 @@ class WikimediaCommonsDataIngester(ProviderDataIngester):
return merged_json
- def merge_media_pages(self, left_page, right_page):
+ @staticmethod
+ def merge_media_pages(left_page, right_page):
merged_page = deepcopy(left_page)
merged_globalusage = left_page.get("globalusage", []) + right_page.get(
"globalusage", []
@@ -444,17 +651,21 @@ class WikimediaCommonsDataIngester(ProviderDataIngester):
return merged_page
- def derive_timestamp_pair(self, date):
+ @staticmethod
+ 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()))
+ logger.info(
+ f"Start timestamp: {start_timestamp}, end timestamp: {end_timestamp}"
+ )
return start_timestamp, end_timestamp
def main(date):
logger.info(f"Begin: Wikimedia Commons data ingestion for {date}")
- ingester = WikimediaCommonsDataIngester(date)
+ ingester = WikimediaCommonsDataIngester(date=date)
ingester.ingest_records()
@@ -464,7 +675,7 @@ if __name__ == "__main__":
add_help=True,
)
parser.add_argument(
- "--date", help="Identify images uploaded on a date (format: YYYY-MM-DD)."
+ "--date", help="Identify media uploaded on a date (format: YYYY-MM-DD)."
)
args = parser.parse_args()
if args.date:
diff --git a/tests/dags/providers/provider_api_scripts/resources/wikimedia/continuation/wmc_continue_max_iter.json b/tests/dags/providers/provider_api_scripts/resources/wikimedia/continuation/wmc_continue_max_iter.json
new file mode 100644
index 000000000..3f8f983a2
--- /dev/null
+++ b/tests/dags/providers/provider_api_scripts/resources/wikimedia/continuation/wmc_continue_max_iter.json
@@ -0,0 +1,942 @@
+{
+ "continue": {
+ "continue": "gaicontinue||imageinfo",
+ "gucontinue": "Edvard_Munch_-_Night_in_Nice_(1891).jpg|nowiki|1281339",
+ "gaicontinue": "Edvard_Munch_-_Night_in_Nice_(1891).jpg|nowiki|1281339"
+ },
+ "query": {
+ "pages": {
+ "18263872": {
+ "globalusage": [],
+ "imageinfo": [
+ {
+ "descriptionshorturl": "https://commons.wikimedia.org/w/index.php?curid=18263872",
+ "descriptionurl": "https://commons.wikimedia.org/wiki/File:Minchinmavida_Volcano.jpg",
+ "extmetadata": {
+ "Artist": {
+ "source": "commons-desc-page",
+ "value": "The original uploader was <a href=\"https://en.wikipedia.org/wiki/it:User:Elvezio\" class=\"extiw\" title=\"w:it:User:Elvezio\">Elvezio</a> at <a href=\"https://en.wikipedia.org/wiki/it:\" class=\"extiw\" title=\"w:it:\">Italian Wikipedia</a>."
+ },
+ "Assessments": {
+ "hidden": "",
+ "source": "commons-categories",
+ "value": ""
+ },
+ "AttributionRequired": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "false"
+ },
+ "Categories": {
+ "hidden": "",
+ "source": "commons-categories",
+ "value": "2009 Chait\u00e9n eruptions|Ash fall on glaciers|Lahars in Chile|Michinmahuida|PD NASA|Satellite pictures of volcanoes in Chile|Sediment input|Volcanic ash in Chile"
+ },
+ "CommonsMetadataExtension": {
+ "hidden": "",
+ "source": "extension",
+ "value": 1.2
+ },
+ "Copyrighted": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "False"
+ },
+ "Credit": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "Transferred from <span class=\"plainlinks\"><a class=\"external text\" href=\"https://it.wikipedia.org\">it.wikipedia</a></span> to Commons by <a href=\"//commons.wikimedia.org/wiki/User:Baroc\" title=\"User:Baroc\">Baroc</a> using <a href=\"https://tools.wmflabs.org/commonshelper/\" class=\"extiw\" title=\"toollabs:commonshelper/\">CommonsHelper</a>."
+ },
+ "DateTime": {
+ "hidden": "",
+ "source": "mediawiki-metadata",
+ "value": "2015-10-31 23:00:49"
+ },
+ "DateTimeOriginal": {
+ "source": "commons-desc-page",
+ "value": "2009-03-17"
+ },
+ "ImageDescription": {
+ "source": "commons-desc-page",
+ "value": "<a href=\"https://it.wikipedia.org/wiki/Vulcano_Minchinmavida\" class=\"extiw\" title=\"it:Vulcano Minchinmavida\">Vulcano Minchinmavida</a> <a href=\"https://it.wikipedia.org/wiki/Cile\" class=\"extiw\" title=\"it:Cile\">Cile</a>"
+ },
+ "License": {
+ "hidden": "",
+ "source": "commons-templates",
+ "value": "pd"
+ },
+ "LicenseShortName": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "Public domain"
+ },
+ "ObjectName": {
+ "hidden": "",
+ "source": "mediawiki-metadata",
+ "value": "Minchinmavida Volcano"
+ },
+ "Restrictions": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": ""
+ },
+ "UsageTerms": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "Public domain"
+ }
+ },
+ "height": 1440,
+ "size": 1117410,
+ "url": "https://upload.wikimedia.org/wikipedia/commons/f/fb/Minchinmavida_Volcano.jpg",
+ "user": "SteinsplitterBot",
+ "width": 1440
+ }
+ ],
+ "imagerepository": "local",
+ "ns": 6,
+ "pageid": 18263872,
+ "title": "File:Minchinmavida Volcano.jpg"
+ },
+ "44672185": {
+ "globalusage": [
+ {
+ "title": "Heydelberq",
+ "url": "https://az.wikipedia.org/wiki/Heydelberq",
+ "wiki": "az.wikipedia.org"
+ },
+ {
+ "title": "Heidelberg",
+ "url": "https://en.wikipedia.org/wiki/Heidelberg",
+ "wiki": "en.wikipedia.org"
+ },
+ {
+ "title": "Heidelberg",
+ "url": "https://vi.wikipedia.org/wiki/Heidelberg",
+ "wiki": "vi.wikipedia.org"
+ }
+ ],
+ "imageinfo": [
+ {
+ "descriptionshorturl": "https://commons.wikimedia.org/w/index.php?curid=44672185",
+ "descriptionurl": "https://commons.wikimedia.org/wiki/File:2002-04-02_Hauptstra%C3%9Fe,_Heidelberg_IMG_0404.jpg",
+ "extmetadata": {
+ "Artist": {
+ "source": "commons-desc-page",
+ "value": "<a href=\"//commons.wikimedia.org/wiki/User:Hasenl%C3%A4ufer\" title=\"User:Hasenl\u00e4ufer\">Eckhard Henkel</a>"
+ },
+ "Assessments": {
+ "hidden": "",
+ "source": "commons-categories",
+ "value": ""
+ },
+ "Attribution": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "Photo: Eckhard Henkel / <a rel=\"nofollow\" class=\"external text\" href=\"http:////commons.wikimedia.org/wiki/File:2002-04-02_Hauptstra%C3%9Fe,_Heidelberg_IMG_0404.jpg\">Wikimedia Commons</a> / <a rel=\"nofollow\" class=\"external text\" href=\"https://creativecommons.org/licenses/by-sa/3.0/de/deed.en\">CC BY-SA 3.0 DE</a>"
+ },
+ "AttributionRequired": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "true"
+ },
+ "Categories": {
+ "hidden": "",
+ "source": "commons-categories",
+ "value": "Files by Hasenl\u00e4ufer|Hauptstra\u00dfe (Heidelberg)|Media with locations|Pages with maps|Photographs taken on 2002-04-02"
+ },
+ "CommonsMetadataExtension": {
+ "hidden": "",
+ "source": "extension",
+ "value": 1.2
+ },
+ "Copyrighted": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "True"
+ },
+ "Credit": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "<span class=\"int-own-work\" lang=\"en\">Own work</span>"
+ },
+ "DateTime": {
+ "hidden": "",
+ "source": "mediawiki-metadata",
+ "value": "2015-10-31 23:00:22"
+ },
+ "DateTimeOriginal": {
+ "source": "commons-desc-page",
+ "value": "2002-04-02"
+ },
+ "GPSLatitude": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "49.411580"
+ },
+ "GPSLongitude": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "8.705512"
+ },
+ "GPSMapDatum": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "WGS-84"
+ },
+ "ImageDescription": {
+ "source": "commons-desc-page",
+ "value": "Blick in die <a href=\"https://de.wikipedia.org/wiki/Hauptstra%C3%9Fe_(Heidelberg)\" class=\"extiw\" title=\"de:Hauptstra\u00dfe (Heidelberg)\">Hauptstra\u00dfe</a> in Richtung Westen, etwas westlich des Universit\u00e4tsplatzes, <a href=\"https://de.wikipedia.org/wiki/Heidelberg\" class=\"extiw\" title=\"de:Heidelberg\">Heidelberg</a>"
+ },
+ "License": {
+ "hidden": "",
+ "source": "commons-templates",
+ "value": "cc-by-sa-3.0-de"
+ },
+ "LicenseShortName": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "CC BY-SA 3.0 de"
+ },
+ "LicenseUrl": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "https://creativecommons.org/licenses/by-sa/3.0/de/deed.en"
+ },
+ "ObjectName": {
+ "hidden": "",
+ "source": "mediawiki-metadata",
+ "value": "2002-04-02 Hauptstra\u00dfe, Heidelberg IMG 0404"
+ },
+ "Permission": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "This image is <b>not <a href=\"https://en.wikipedia.org/wiki/Public_domain\" class=\"extiw\" title=\"en:Public domain\">public domain</a></b>. Please respect the copyright protection. It may only be used according to the rules mentioned here. This specifically <b>excludes use in social media</b>, if applicable terms of the licenses listed here not appropriate."
+ },
+ "Restrictions": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": ""
+ },
+ "UsageTerms": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "Creative Commons Attribution-Share Alike 3.0 de"
+ }
+ },
+ "height": 1172,
+ "size": 816636,
+ "url": "https://upload.wikimedia.org/wikipedia/commons/e/e9/2002-04-02_Hauptstra%C3%9Fe%2C_Heidelberg_IMG_0404.jpg",
+ "user": "Hasenl\u00e4ufer",
+ "width": 1563
+ }
+ ],
+ "imagerepository": "local",
+ "ns": 6,
+ "pageid": 44672185,
+ "title": "File:2002-04-02 Hauptstra\u00dfe, Heidelberg IMG 0404.jpg"
+ },
+ "44672190": {
+ "globalusage": [],
+ "imageinfo": [
+ {
+ "descriptionshorturl": "https://commons.wikimedia.org/w/index.php?curid=44672190",
+ "descriptionurl": "https://commons.wikimedia.org/wiki/File:Niedercunnersdorf_M%C3%BChlgrabenweg_5_(1).JPG",
+ "extmetadata": {
+ "Artist": {
+ "source": "commons-desc-page",
+ "value": "<a href=\"//commons.wikimedia.org/wiki/User:BTLmovies\" title=\"User:BTLmovies\">Pascal Seibt</a>"
+ },
+ "Assessments": {
+ "hidden": "",
+ "source": "commons-categories",
+ "value": ""
+ },
+ "AttributionRequired": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "true"
+ },
+ "Categories": {
+ "hidden": "",
+ "source": "commons-categories",
+ "value": "Niedercunnersdorf M\u00fchlgrabenweg 5|Self-published work|Supported by Wikimedia Deutschland|Umgebinde Online 2015"
+ },
+ "CommonsMetadataExtension": {
+ "hidden": "",
+ "source": "extension",
+ "value": 1.2
+ },
+ "Copyrighted": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "True"
+ },
+ "Credit": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "<span class=\"int-own-work\" lang=\"en\">Own work</span>"
+ },
+ "DateTime": {
+ "hidden": "",
+ "source": "mediawiki-metadata",
+ "value": "2015-10-31 23:00:32"
+ },
+ "DateTimeOriginal": {
+ "source": "commons-desc-page",
+ "value": "2015-09-12 13:51:49"
+ },
+ "ImageDescription": {
+ "source": "commons-desc-page",
+ "value": "Niedercunnersdorf M\u00fchlgrabenweg 5"
+ },
+ "License": {
+ "hidden": "",
+ "source": "commons-templates",
+ "value": "cc-by-sa-4.0"
+ },
+ "LicenseShortName": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "CC BY-SA 4.0"
+ },
+ "LicenseUrl": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "https://creativecommons.org/licenses/by-sa/4.0"
+ },
+ "ObjectName": {
+ "hidden": "",
+ "source": "mediawiki-metadata",
+ "value": "Niedercunnersdorf M\u00fchlgrabenweg 5 (1)"
+ },
+ "Restrictions": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": ""
+ },
+ "UsageTerms": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "Creative Commons Attribution-Share Alike 4.0"
+ }
+ },
+ "height": 3864,
+ "size": 7938894,
+ "url": "https://upload.wikimedia.org/wikipedia/commons/8/80/Niedercunnersdorf_M%C3%BChlgrabenweg_5_%281%29.JPG",
+ "user": "BTLmovies",
+ "width": 5152
+ }
+ ],
+ "imagerepository": "local",
+ "ns": 6,
+ "pageid": 44672190,
+ "title": "File:Niedercunnersdorf M\u00fchlgrabenweg 5 (1).JPG"
+ },
+ "44672194": {
+ "globalusage": [],
+ "imageinfo": [
+ {
+ "descriptionshorturl": "https://commons.wikimedia.org/w/index.php?curid=44672194",
+ "descriptionurl": "https://commons.wikimedia.org/wiki/File:Niedercunnersdorf_Gartenweg_12.JPG",
+ "extmetadata": {
+ "Artist": {
+ "source": "commons-desc-page",
+ "value": "<a href=\"//commons.wikimedia.org/wiki/User:BTLmovies\" title=\"User:BTLmovies\">Pascal Seibt</a>"
+ },
+ "Assessments": {
+ "hidden": "",
+ "source": "commons-categories",
+ "value": ""
+ },
+ "AttributionRequired": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "true"
+ },
+ "Categories": {
+ "hidden": "",
+ "source": "commons-categories",
+ "value": "Cultural heritage monuments in Kottmar|Self-published work|Supported by Wikimedia Deutschland|Umgebinde Online 2015|Umgebinde in Niedercunnersdorf"
+ },
+ "CommonsMetadataExtension": {
+ "hidden": "",
+ "source": "extension",
+ "value": 1.2
+ },
+ "Copyrighted": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "True"
+ },
+ "Credit": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "<span class=\"int-own-work\" lang=\"en\">Own work</span>"
+ },
+ "DateTime": {
+ "hidden": "",
+ "source": "mediawiki-metadata",
+ "value": "2015-10-31 23:00:35"
+ },
+ "DateTimeOriginal": {
+ "source": "commons-desc-page",
+ "value": "2015-09-12 11:42:12"
+ },
+ "ImageDescription": {
+ "source": "commons-desc-page",
+ "value": "Niedercunnersdorf Gartenweg 12"
+ },
+ "License": {
+ "hidden": "",
+ "source": "commons-templates",
+ "value": "cc-by-sa-4.0"
+ },
+ "LicenseShortName": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "CC BY-SA 4.0"
+ },
+ "LicenseUrl": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "https://creativecommons.org/licenses/by-sa/4.0"
+ },
+ "ObjectName": {
+ "hidden": "",
+ "source": "mediawiki-metadata",
+ "value": "Niedercunnersdorf Gartenweg 12"
+ },
+ "Restrictions": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": ""
+ },
+ "UsageTerms": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "Creative Commons Attribution-Share Alike 4.0"
+ }
+ },
+ "height": 3000,
+ "size": 5815855,
+ "url": "https://upload.wikimedia.org/wikipedia/commons/3/37/Niedercunnersdorf_Gartenweg_12.JPG",
+ "user": "BTLmovies",
+ "width": 4000
+ }
+ ],
+ "imagerepository": "local",
+ "ns": 6,
+ "pageid": 44672194,
+ "title": "File:Niedercunnersdorf Gartenweg 12.JPG"
+ },
+ "44672195": {
+ "globalusage": [],
+ "imageinfo": [
+ {
+ "descriptionshorturl": "https://commons.wikimedia.org/w/index.php?curid=44672195",
+ "descriptionurl": "https://commons.wikimedia.org/wiki/File:Niedercunnersdorf_Gartenweg_25.JPG",
+ "extmetadata": {
+ "Artist": {
+ "source": "commons-desc-page",
+ "value": "<a href=\"//commons.wikimedia.org/wiki/User:BTLmovies\" title=\"User:BTLmovies\">Pascal Seibt</a>"
+ },
+ "Assessments": {
+ "hidden": "",
+ "source": "commons-categories",
+ "value": ""
+ },
+ "AttributionRequired": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "true"
+ },
+ "Categories": {
+ "hidden": "",
+ "source": "commons-categories",
+ "value": "Cultural heritage monuments in Kottmar|Self-published work|Supported by Wikimedia Deutschland|Umgebinde Online 2015|Umgebinde in Niedercunnersdorf"
+ },
+ "CommonsMetadataExtension": {
+ "hidden": "",
+ "source": "extension",
+ "value": 1.2
+ },
+ "Copyrighted": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "True"
+ },
+ "Credit": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "<span class=\"int-own-work\" lang=\"en\">Own work</span>"
+ },
+ "DateTime": {
+ "hidden": "",
+ "source": "mediawiki-metadata",
+ "value": "2015-10-31 23:00:35"
+ },
+ "DateTimeOriginal": {
+ "source": "commons-desc-page",
+ "value": "2015-09-12 10:14:54"
+ },
+ "ImageDescription": {
+ "source": "commons-desc-page",
+ "value": "Niedercunnersdorf Gartenweg 25"
+ },
+ "License": {
+ "hidden": "",
+ "source": "commons-templates",
+ "value": "cc-by-sa-4.0"
+ },
+ "LicenseShortName": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "CC BY-SA 4.0"
+ },
+ "LicenseUrl": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "https://creativecommons.org/licenses/by-sa/4.0"
+ },
+ "ObjectName": {
+ "hidden": "",
+ "source": "mediawiki-metadata",
+ "value": "Niedercunnersdorf Gartenweg 25"
+ },
+ "Restrictions": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": ""
+ },
+ "UsageTerms": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "Creative Commons Attribution-Share Alike 4.0"
+ }
+ },
+ "height": 3000,
+ "size": 5941935,
+ "url": "https://upload.wikimedia.org/wikipedia/commons/1/19/Niedercunnersdorf_Gartenweg_25.JPG",
+ "user": "BTLmovies",
+ "width": 4000
+ }
+ ],
+ "imagerepository": "local",
+ "ns": 6,
+ "pageid": 44672195,
+ "title": "File:Niedercunnersdorf Gartenweg 25.JPG"
+ },
+ "44672196": {
+ "globalusage": [],
+ "imageinfo": [
+ {
+ "descriptionshorturl": "https://commons.wikimedia.org/w/index.php?curid=44672196",
+ "descriptionurl": "https://commons.wikimedia.org/wiki/File:Niedercunnersdorf_NiedereHauptstra%C3%9Fe_66.JPG",
+ "extmetadata": {
+ "Artist": {
+ "source": "commons-desc-page",
+ "value": "<a href=\"//commons.wikimedia.org/wiki/User:BTLmovies\" title=\"User:BTLmovies\">Pascal Seibt</a>"
+ },
+ "Assessments": {
+ "hidden": "",
+ "source": "commons-categories",
+ "value": ""
+ },
+ "AttributionRequired": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "true"
+ },
+ "Categories": {
+ "hidden": "",
+ "source": "commons-categories",
+ "value": "Cultural heritage monuments in Kottmar|Self-published work|Supported by Wikimedia Deutschland|Umgebinde Online 2015|Umgebinde in Niedercunnersdorf"
+ },
+ "CommonsMetadataExtension": {
+ "hidden": "",
+ "source": "extension",
+ "value": 1.2
+ },
+ "Copyrighted": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "True"
+ },
+ "Credit": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "<span class=\"int-own-work\" lang=\"en\">Own work</span>"
+ },
+ "DateTime": {
+ "hidden": "",
+ "source": "mediawiki-metadata",
+ "value": "2015-10-31 23:00:36"
+ },
+ "DateTimeOriginal": {
+ "source": "commons-desc-page",
+ "value": "2015-09-12 11:11:40"
+ },
+ "ImageDescription": {
+ "source": "commons-desc-page",
+ "value": "Niedercunnersdorf NiedereHauptstra\u00dfe 66"
+ },
+ "License": {
+ "hidden": "",
+ "source": "commons-templates",
+ "value": "cc-by-sa-4.0"
+ },
+ "LicenseShortName": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "CC BY-SA 4.0"
+ },
+ "LicenseUrl": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "https://creativecommons.org/licenses/by-sa/4.0"
+ },
+ "ObjectName": {
+ "hidden": "",
+ "source": "mediawiki-metadata",
+ "value": "Niedercunnersdorf NiedereHauptstra\u00dfe 66"
+ },
+ "Restrictions": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": ""
+ },
+ "UsageTerms": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "Creative Commons Attribution-Share Alike 4.0"
+ }
+ },
+ "height": 3000,
+ "size": 5800771,
+ "url": "https://upload.wikimedia.org/wikipedia/commons/1/1a/Niedercunnersdorf_NiedereHauptstra%C3%9Fe_66.JPG",
+ "user": "BTLmovies",
+ "width": 4000
+ }
+ ],
+ "imagerepository": "local",
+ "ns": 6,
+ "pageid": 44672196,
+ "title": "File:Niedercunnersdorf NiedereHauptstra\u00dfe 66.JPG"
+ },
+ "44672207": {
+ "globalusage": [],
+ "imageinfo": [
+ {
+ "descriptionshorturl": "https://commons.wikimedia.org/w/index.php?curid=44672207",
+ "descriptionurl": "https://commons.wikimedia.org/wiki/File:Niedercunnersdorf_WillhelmTempelPlatz_11.JPG",
+ "extmetadata": {
+ "Artist": {
+ "source": "commons-desc-page",
+ "value": "<a href=\"//commons.wikimedia.org/wiki/User:BTLmovies\" title=\"User:BTLmovies\">Pascal Seibt</a>"
+ },
+ "Assessments": {
+ "hidden": "",
+ "source": "commons-categories",
+ "value": ""
+ },
+ "AttributionRequired": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "true"
+ },
+ "Categories": {
+ "hidden": "",
+ "source": "commons-categories",
+ "value": "Cultural heritage monuments in Kottmar|Self-published work|Supported by Wikimedia Deutschland|Umgebinde Online 2015|Umgebinde in Niedercunnersdorf"
+ },
+ "CommonsMetadataExtension": {
+ "hidden": "",
+ "source": "extension",
+ "value": 1.2
+ },
+ "Copyrighted": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "True"
+ },
+ "Credit": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "<span class=\"int-own-work\" lang=\"en\">Own work</span>"
+ },
+ "DateTime": {
+ "hidden": "",
+ "source": "mediawiki-metadata",
+ "value": "2015-10-31 23:00:40"
+ },
+ "DateTimeOriginal": {
+ "source": "commons-desc-page",
+ "value": "2015-09-12 10:59:25"
+ },
+ "ImageDescription": {
+ "source": "commons-desc-page",
+ "value": "Niedercunnersdorf WillhelmTempelPlatz 11"
+ },
+ "License": {
+ "hidden": "",
+ "source": "commons-templates",
+ "value": "cc-by-sa-4.0"
+ },
+ "LicenseShortName": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "CC BY-SA 4.0"
+ },
+ "LicenseUrl": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "https://creativecommons.org/licenses/by-sa/4.0"
+ },
+ "ObjectName": {
+ "hidden": "",
+ "source": "mediawiki-metadata",
+ "value": "Niedercunnersdorf WillhelmTempelPlatz 11"
+ },
+ "Restrictions": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": ""
+ },
+ "UsageTerms": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "Creative Commons Attribution-Share Alike 4.0"
+ }
+ },
+ "height": 3000,
+ "size": 5421958,
+ "url": "https://upload.wikimedia.org/wikipedia/commons/b/b0/Niedercunnersdorf_WillhelmTempelPlatz_11.JPG",
+ "user": "BTLmovies",
+ "width": 4000
+ }
+ ],
+ "imagerepository": "local",
+ "ns": 6,
+ "pageid": 44672207,
+ "title": "File:Niedercunnersdorf WillhelmTempelPlatz 11.JPG"
+ },
+ "44672210": {
+ "globalusage": [],
+ "imageinfo": [
+ {
+ "descriptionshorturl": "https://commons.wikimedia.org/w/index.php?curid=44672210",
+ "descriptionurl": "https://commons.wikimedia.org/wiki/File:A_catalogue_of_the_recent_sea-urchins_(Echinoidea)_in_the_collection_of_the_British_Museum_(Natural_History)_BHL8403911.jpg",
+ "extmetadata": {
+ "Artist": {
+ "source": "commons-desc-page",
+ "value": "British Museum (Natural History).; Clark, Hubert Lyman"
+ },
+ "Assessments": {
+ "hidden": "",
+ "source": "commons-categories",
+ "value": ""
+ },
+ "AttributionRequired": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "false"
+ },
+ "Categories": {
+ "hidden": "",
+ "source": "commons-categories",
+ "value": "A catalogue of the recent sea-urchins (Echinoidea) in the collection of the British Museum (Natural History)|CC-PD-Mark|Files from the Biodiversity Heritage Library|Images uploaded by F\u00e6|PD-old-70-expired|PD-scan (PD-old-70-expired)"
+ },
+ "CommonsMetadataExtension": {
+ "hidden": "",
+ "source": "extension",
+ "value": 1.2
+ },
+ "Copyrighted": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "False"
+ },
+ "Credit": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "<a rel=\"nofollow\" class=\"external free\" href=\"https://www.biodiversitylibrary.org/pageimage/8403911\">https://www.biodiversitylibrary.org/pageimage/8403911</a>"
+ },
+ "DateTime": {
+ "hidden": "",
+ "source": "mediawiki-metadata",
+ "value": "2015-10-31 23:00:44"
+ },
+ "DateTimeOriginal": {
+ "source": "commons-desc-page",
+ "value": "1925"
+ },
+ "ImageDescription": {
+ "source": "commons-desc-page",
+ "value": "A catalogue of the recent sea-urchins (Echinoidea) in the collection of the British Museum (Natural History) / by Hubert Lyman Clark ; [with a preface by C. Tate Regan]."
+ },
+ "License": {
+ "hidden": "",
+ "source": "commons-templates",
+ "value": "pd"
+ },
+ "LicenseShortName": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "Public domain"
+ },
+ "ObjectName": {
+ "hidden": "",
+ "source": "mediawiki-metadata",
+ "value": "A catalogue of the recent sea-urchins (Echinoidea) in the collection of the British Museum (Natural History) BHL8403911"
+ },
+ "Restrictions": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": ""
+ },
+ "UsageTerms": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "Public domain"
+ }
+ },
+ "height": 2766,
+ "size": 287144,
+ "url": "https://upload.wikimedia.org/wikipedia/commons/c/c1/A_catalogue_of_the_recent_sea-urchins_%28Echinoidea%29_in_the_collection_of_the_British_Museum_%28Natural_History%29_BHL8403911.jpg",
+ "user": "F\u00e6",
+ "width": 1670
+ }
+ ],
+ "imagerepository": "local",
+ "ns": 6,
+ "pageid": 44672210,
+ "title": "File:A catalogue of the recent sea-urchins (Echinoidea) in the collection of the British Museum (Natural History) BHL8403911.jpg"
+ },
+ "44672212": {
+ "globalusage": [
+ {
+ "title": "V\u00e6rker_af_Edvard_Munch",
+ "url": "https://da.wikipedia.org/wiki/V%C3%A6rker_af_Edvard_Munch",
+ "wiki": "da.wikipedia.org"
+ },
+ {
+ "title": "Liste_der_Gem\u00e4lde_von_Edvard_Munch",
+ "url": "https://de.wikipedia.org/wiki/Liste_der_Gem%C3%A4lde_von_Edvard_Munch",
+ "wiki": "de.wikipedia.org"
+ },
+ {
+ "title": "Benutzer:Magnus_Manske/listeria_test2",
+ "url": "https://de.wikipedia.org/wiki/Benutzer:Magnus_Manske/listeria_test2",
+ "wiki": "de.wikipedia.org"
+ },
+ {
+ "title": "List_of_paintings_by_Edvard_Munch",
+ "url": "https://en.wikipedia.org/wiki/List_of_paintings_by_Edvard_Munch",
+ "wiki": "en.wikipedia.org"
+ },
+ {
+ "title": "Liste_des_tableaux_d'Edvard_Munch",
+ "url": "https://fr.wikipedia.org/wiki/Liste_des_tableaux_d%27Edvard_Munch",
+ "wiki": "fr.wikipedia.org"
+ },
+ {
+ "title": "\u0537\u0564\u057e\u0561\u0580\u0564_\u0544\u0578\u0582\u0576\u056f\u056b_\u0576\u056f\u0561\u0580\u0576\u0565\u0580\u056b_\u0581\u0561\u0576\u056f",
+ "url": "https://hy.wikipedia.org/wiki/%D4%B7%D5%A4%D5%BE%D5%A1%D6%80%D5%A4_%D5%84%D5%B8%D6%82%D5%B6%D5%AF%D5%AB_%D5%B6%D5%AF%D5%A1%D6%80%D5%B6%D5%A5%D6%80%D5%AB_%D6%81%D5%A1%D5%B6%D5%AF",
+ "wiki": "hy.wikipedia.org"
+ },
+ {
+ "title": "\u30a8\u30c9\u30f4\u30a1\u30eb\u30c9\u30fb\u30e0\u30f3\u30af",
+ "url": "https://ja.wikipedia.org/wiki/%E3%82%A8%E3%83%89%E3%83%B4%E3%82%A1%E3%83%AB%E3%83%89%E3%83%BB%E3%83%A0%E3%83%B3%E3%82%AF",
+ "wiki": "ja.wikipedia.org"
+ }
+ ],
+ "imageinfo": [
+ {
+ "descriptionshorturl": "https://commons.wikimedia.org/w/index.php?curid=44672212",
+ "descriptionurl": "https://commons.wikimedia.org/wiki/File:Edvard_Munch_-_Night_in_Nice_(1891).jpg",
+ "extmetadata": {
+ "Artist": {
+ "source": "commons-desc-page",
+ "value": "<bdi><a href=\"https://en.wikipedia.org/wiki/en:Edvard_Munch\" class=\"extiw\" title=\"w:en:Edvard Munch\">Edvard Munch</a>\n</bdi>"
+ },
+ "Assessments": {
+ "hidden": "",
+ "source": "commons-categories",
+ "value": ""
+ },
+ "AttributionRequired": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "false"
+ },
+ "Categories": {
+ "hidden": "",
+ "source": "commons-categories",
+ "value": "1890s paintings by Edvard Munch|1891 paintings from France|1891 paintings in Norway|Artworks with Wikidata item|Artworks with known accession number|CC-PD-Mark|Nice in art|PD-Art (PD-old-auto-expired)|PD-old-75-expired|Paintings by Edvard Munch in the Nasjonalmuseet for kunst, arkitektur og design"
+ },
+ "CommonsMetadataExtension": {
+ "hidden": "",
+ "source": "extension",
+ "value": 1.2
+ },
+ "Copyrighted": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "False"
+ },
+ "Credit": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "<a rel=\"nofollow\" class=\"external free\" href=\"http://samling.nasjonalmuseet.no/no/object/NG.M.00394\">http://samling.nasjonalmuseet.no/no/object/NG.M.00394</a> Nasjonalmuseet"
+ },
+ "DateTime": {
+ "hidden": "",
+ "source": "mediawiki-metadata",
+ "value": "2015-10-31 23:00:53"
+ },
+ "DateTimeOriginal": {
+ "source": "commons-desc-page",
+ "value": "1891<div style=\"display: none;\">date QS:P,+1891-00-00T00:00:00Z/9</div>"
+ },
+ "License": {
+ "hidden": "",
+ "source": "commons-templates",
+ "value": "pd"
+ },
+ "LicenseShortName": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "Public domain"
+ },
+ "ObjectName": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "<div class=\"fn\">\n<span style=\"font-weight:bold\"><span dir=\"ltr\" lang=\"en\"><i>Night in Nice</i></span></span><div style=\"display: none;\">label QS:Len,\"Night in Nice\"</div>\n</div>"
+ },
+ "Restrictions": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": ""
+ },
+ "UsageTerms": {
+ "hidden": "",
+ "source": "commons-desc-page",
+ "value": "Public domain"
+ }
+ },
+ "height": 714,
+ "size": 171366,
+ "url": "https://upload.wikimedia.org/wikipedia/commons/4/45/Edvard_Munch_-_Night_in_Nice_%281891%29.jpg",
+ "user": "4ing",
+ "width": 803
+ }
+ ],
+ "imagerepository": "local",
+ "ns": 6,
+ "pageid": 44672212,
+ "title": "File:Edvard Munch - Night in Nice (1891).jpg"
+ }
+ }
+ }
+}
diff --git a/tests/dags/providers/provider_api_scripts/test_wikimedia_commons.py b/tests/dags/providers/provider_api_scripts/test_wikimedia_commons.py
index 9d97cce3d..3d61c748e 100644
--- a/tests/dags/providers/provider_api_scripts/test_wikimedia_commons.py
+++ b/tests/dags/providers/provider_api_scripts/test_wikimedia_commons.py
@@ -1,8 +1,9 @@
import json
import logging
from pathlib import Path
-from unittest.mock import patch
+from unittest.mock import Mock, patch
+import pytest
from common.constants import IMAGE
from common.licenses import get_license_info
from providers.provider_api_scripts.wikimedia_commons import (
@@ -17,17 +18,23 @@ logging.basicConfig(
level=logging.DEBUG,
)
-wmc = WikimediaCommonsDataIngester(date="2018-01-15")
+def wmc() -> WikimediaCommonsDataIngester:
+ return WikimediaCommonsDataIngester(date="2018-01-15")
-def test_derive_timestamp_pair():
+
+RP = WikimediaCommonsDataIngester.ReturnProps
+
+
+def test_derive_timestamp_pair(wmc):
# 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")
assert actual_start_ts == "1515974400"
assert actual_end_ts == "1516060800"
-def test_get_media_pages_returns_correctly_with_continue():
+def test_get_media_pages_returns_correctly_with_continue(wmc):
with open(RESOURCES / "response_small_with_continue.json") as f:
resp_dict = json.load(f)
@@ -36,7 +43,7 @@ def test_get_media_pages_returns_correctly_with_continue():
assert actual_result == expect_result
-def test_get_batch_data_returns_correctly_with_pages():
+def test_get_batch_data_returns_correctly_with_pages(wmc):
with open(RESOURCES / "response_small_with_continue.json") as f:
resp_dict = json.load(f)
@@ -47,25 +54,25 @@ def test_get_batch_data_returns_correctly_with_pages():
assert list(actual_result) == expect_result
-def test_get_batch_data_returns_correctly_with_none_json():
+def test_get_batch_data_returns_correctly_with_none_json(wmc):
expect_result = None
actual_result = wmc.get_batch_data(None)
assert actual_result == expect_result
-def test_get_batch_data_returns_correctly_with_no_pages():
+def test_get_batch_data_returns_correctly_with_no_pages(wmc):
expect_result = None
actual_result = wmc.get_batch_data({"batch_complete": ""})
assert actual_result == expect_result
-def test_get_next_query_params_adds_start_and_end():
+def test_get_next_query_params_adds_start_and_end(wmc):
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_get_next_query_params_adds_continue():
+def test_get_next_query_params_adds_continue(wmc):
wmc.continue_token = {"gaicontinue": "200|next.jpg", "continue": "gaicontinue||"}
actual_qp = wmc.get_next_query_params(
prev_query_params={},
@@ -74,7 +81,25 @@ def test_get_next_query_params_adds_continue():
assert actual_qp["continue"] == "gaicontinue||"
-def test_get_response_json(monkeypatch):
+ "query_prop",
+ [RP.query_all, RP.query_no_popularity],
+)
+ "media_prop",
+ [RP.media_all, RP.media_no_metadata],
+)
+def test_get_next_query_params_adds_props(query_prop, media_prop, wmc):
+ wmc.current_props = {
+ "prop": query_prop,
+ "iiprop": media_prop,
+ }
+ actual_qp = wmc.get_next_query_params(prev_query_params={})
+ assert actual_qp["prop"] == query_prop
+ assert actual_qp["iiprop"] == media_prop
+
+
+def test_get_response_json(monkeypatch, wmc):
with open(RESOURCES / "continuation/wmc_pretty1.json") as f:
first_response = json.load(f)
with open(RESOURCES / "continuation/wmc_pretty2.json") as f:
@@ -108,7 +133,7 @@ def test_get_response_json(monkeypatch):
assert wmc.continue_token == expect_continue_token
-def test_get_response_json_returns_correctly_without_continue(monkeypatch):
+def test_get_response_json_returns_correctly_without_continue(monkeypatch, wmc):
with open(RESOURCES / "response_small_missing_continue.json") as f:
resp_dict = json.load(f)
@@ -126,7 +151,53 @@ def test_get_response_json_returns_correctly_without_continue(monkeypatch):
assert actual_result == expect_result
-def test_merge_response_jsons():
+def test_get_response_json_breaks_on_max_iterations(monkeypatch, wmc):
+ with open(RESOURCES / "continuation/wmc_continue_max_iter.json") as f:
+ response = json.load(f)
+ wmc.max_page_iteration_before_give_up = 10
+ wmc.delayed_requester._DELAY = 0.01
+
+ def mock_get_response_json(endpoint, retries, query_params, **kwargs):
+ return response.copy()
+
+ get_response_mock = Mock(side_effect=mock_get_response_json)
+
+ monkeypatch.setattr(wmc.delayed_requester, "get_response_json", get_response_mock)
+ wmc.continue_token = {}
+ actual = wmc.get_response_json(wmc.get_next_query_params({}))
+ expected = response.copy()
+ expected.pop("continue")
+ assert actual == expected
+ # This should call exactly (max iterations + 1) times
+ assert get_response_mock.call_count == wmc.max_page_iteration_before_give_up + 1
+ # The props should NOT be the default at this point
+ assert wmc.current_props != wmc.default_props
+
+
+def test_get_response_json_props_reset_on_batchcomplete(monkeypatch, wmc):
+ with open(RESOURCES / "continuation/wmc_pretty_nocontinue.json") as f:
+ response = json.load(f)
+ wmc.max_page_iteration_before_give_up = 10
+ wmc.delayed_requester._DELAY = 0.01
+
+ def mock_get_response_json(endpoint, retries, query_params, **kwargs):
+ return response.copy()
+
+ get_response_mock = Mock(side_effect=mock_get_response_json)
+
+ monkeypatch.setattr(wmc.delayed_requester, "get_response_json", get_response_mock)
+ wmc.continue_token = {}
+ # Force a change to the props
+ wmc.current_props["prop"] = "foo"
+
+ actual = wmc.get_response_json(wmc.get_next_query_params({}))
+ expected = response.copy()
+ assert actual == expected
+ # The props should be reset to the default
+ assert wmc.current_props == wmc.default_props
+
+
+def test_merge_response_jsons(wmc):
with open(RESOURCES / "continuation/wmc_pretty1.json") as f:
left_response = json.load(f)
with open(RESOURCES / "continuation/wmc_pretty2.json") as f:
@@ -141,7 +212,7 @@ def test_merge_response_jsons():
assert actual_merged_response == expect_merged_response
-def test_merge_media_pages_left_only_with_gu():
+def test_merge_media_pages_left_only_with_gu(wmc):
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:
@@ -150,7 +221,7 @@ def test_merge_media_pages_left_only_with_gu():
assert actual_merged_page == left_page
-def test_merge_media_pages_left_only_with_gu_backwards():
+def test_merge_media_pages_left_only_with_gu_backwards(wmc):
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:
@@ -159,7 +230,7 @@ def test_merge_media_pages_left_only_with_gu_backwards():
assert actual_merged_page == left_page
-def test_merge_media_pages_neither_have_gu():
+def test_merge_media_pages_neither_have_gu(wmc):
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:
@@ -168,7 +239,7 @@ def test_merge_media_pages_neither_have_gu():
assert actual_merged_page == left_page
-def test_merge_media_pages_neigher_have_gu_backwards():
+def test_merge_media_pages_neigher_have_gu_backwards(wmc):
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:
@@ -177,7 +248,7 @@ def test_merge_media_pages_neigher_have_gu_backwards():
assert actual_merged_page == left_page
-def test_merge_media_pages_both_have_gu():
+def test_merge_media_pages_both_have_gu(wmc):
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:
@@ -188,7 +259,7 @@ def test_merge_media_pages_both_have_gu():
assert actual_merged_page == expect_merged_page
-def test_extract_title_gets_cleaned_title():
+def test_extract_title_gets_cleaned_title(wmc):
image_info = {"extmetadata": {"ObjectName": {"value": "File:filename.jpg"}}}
actual_title = wmc.extract_title(image_info)
expected_title = "filename"
@@ -200,7 +271,7 @@ def test_extract_title_gets_cleaned_title():
assert actual_title == expected_title
-def test_get_record_data_handles_example_dict():
+def test_get_record_data_handles_example_dict(wmc):
"""
Converts sample json data to correct image metadata,
and calls `add_item` once for a valid image.
@@ -248,13 +319,13 @@ def test_get_record_data_handles_example_dict():
}
-def test_get_record_data_throws_out_invalid_mediatype(monkeypatch):
+def test_get_record_data_throws_out_invalid_mediatype(monkeypatch, wmc):
media_data = {"mediatype": "INVALID"}
data = wmc.get_record_data(media_data)
assert data is None
-def test_extract_media_info_dict():
+def test_extract_media_info_dict(wmc):
with open(RESOURCES / "image_data_example.json") as f:
media_data = json.load(f)
@@ -266,7 +337,7 @@ def test_extract_media_info_dict():
assert actual_image_info == expect_image_info
-def test_extract_mediatype_with_valid_image_info():
+def test_extract_mediatype_with_valid_image_info(wmc):
with open(RESOURCES / "image_info_from_example_data.json") as f:
image_info = json.load(f)
@@ -274,7 +345,7 @@ def test_extract_mediatype_with_valid_image_info():
assert valid_mediatype == IMAGE
-def test_extract_mediatype_with_invalid_mediatype_in_image_info():
+def test_extract_mediatype_with_invalid_mediatype_in_image_info(wmc):
with open(RESOURCES / "image_info_from_example_data.json") as f:
image_info = json.load(f)
@@ -284,7 +355,7 @@ def test_extract_mediatype_with_invalid_mediatype_in_image_info():
assert valid_mediatype is None
-def test_extract_creator_info_handles_plaintext():
+def test_extract_creator_info_handles_plaintext(wmc):
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)
@@ -294,7 +365,7 @@ def test_extract_creator_info_handles_plaintext():
assert expect_creator_url == actual_creator_url
-def test_extract_creator_info_handles_well_formed_link():
+def test_extract_creator_info_handles_well_formed_link(wmc):
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)
@@ -304,7 +375,7 @@ def test_extract_creator_info_handles_well_formed_link():
assert expect_creator_url == actual_creator_url
-def test_extract_creator_info_handles_div_with_no_link():
+def test_extract_creator_info_handles_div_with_no_link(wmc):
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)
@@ -314,7 +385,7 @@ def test_extract_creator_info_handles_div_with_no_link():
assert expect_creator_url == actual_creator_url
-def test_extract_creator_info_handles_internal_wc_link():
+def test_extract_creator_info_handles_internal_wc_link(wmc):
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)
@@ -327,7 +398,7 @@ def test_extract_creator_info_handles_internal_wc_link():
assert expect_creator_url == actual_creator_url
-def test_extract_creator_info_handles_link_as_partial_text():
+def test_extract_creator_info_handles_link_as_partial_text(wmc):
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)
@@ -337,7 +408,7 @@ def test_extract_creator_info_handles_link_as_partial_text():
assert expect_creator_url == actual_creator_url
-def test_extract_license_info_finds_license_url():
+def test_extract_license_info_finds_license_url(wmc):
with open(RESOURCES / "image_info_from_example_data.json") as f:
image_info = json.load(f)
@@ -346,7 +417,7 @@ def test_extract_license_info_finds_license_url():
assert actual_license_url == expect_license_url
-def test_extract_license_url_handles_missing_license_url():
+def test_extract_license_url_handles_missing_license_url(wmc):
with open(RESOURCES / "image_info_artist_partial_link.json") as f:
image_info = json.load(f)
expect_license_url = None
@@ -354,7 +425,7 @@ def test_extract_license_url_handles_missing_license_url():
assert actual_license_url == expect_license_url
-def test_create_meta_data_scrapes_text_from_html_description():
+def test_create_meta_data_scrapes_text_from_html_description(wmc):
with open(RESOURCES / "image_data_html_description.json") as f:
media_data = json.load(f)
expect_description = (
@@ -365,7 +436,7 @@ def test_create_meta_data_scrapes_text_from_html_description():
assert actual_description == expect_description
-def test_create_meta_data_tallies_global_usage_count():
+def test_create_meta_data_tallies_global_usage_count(wmc):
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"]
@@ -373,7 +444,17 @@ def test_create_meta_data_tallies_global_usage_count():
assert actual_gu == expect_gu
-def test_create_meta_data_tallies_zero_global_usage_count():
+def test_create_meta_data_tallies_global_usage_count_keeps_higher_value(wmc):
+ with open(RESOURCES / "continuation/page_44672185_left.json") as f:
+ media_data = json.load(f)
+ expect_gu = 10
+ # Prep the cache with a higher value
+ wmc.popularity_cache = {44672185: expect_gu}
+ actual_gu = wmc.create_meta_data_dict(media_data)["global_usage_count"]
+ assert actual_gu == expect_gu
+
+
+def test_create_meta_data_tallies_zero_global_usage_count(wmc):
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"]
@@ -381,7 +462,7 @@ def test_create_meta_data_tallies_zero_global_usage_count():
assert actual_gu == expect_gu
-def test_get_audio_record_data_parses_ogg_streams():
+def test_get_audio_record_data_parses_ogg_streams(wmc):
with open(RESOURCES / "audio_filedata_ogg.json") as f:
file_metadata = json.load(f)
original_data = {"media_url": "myurl.com", "meta_data": {}}
@@ -396,7 +477,7 @@ def test_get_audio_record_data_parses_ogg_streams():
assert actual_parsed_data.items() >= expected_parsed_data.items()
-def test_get_audio_record_data_parses_wav_audio_data():
+def test_get_audio_record_data_parses_wav_audio_data(wmc):
with open(RESOURCES / "audio_filedata_wav.json") as f:
file_metadata = json.load(f)
original_data = {"media_url": "myurl.com", "meta_data": {}}
@@ -411,7 +492,7 @@ def test_get_audio_record_data_parses_wav_audio_data():
assert actual_parsed_data.items() >= expected_parsed_data.items()
-def test_get_audio_record_data_parses_wav_audio_data_missing_streams():
+def test_get_audio_record_data_parses_wav_audio_data_missing_streams(wmc):
with open(RESOURCES / "audio_filedata_wav.json") as f:
file_metadata = json.load(f)
original_data = {"media_url": "myurl.com", "meta_data": {}}
@@ -428,7 +509,7 @@ def test_get_audio_record_data_parses_wav_audio_data_missing_streams():
assert actual_parsed_data.items() >= expected_parsed_data.items()
-def test_get_audio_record_data_parses_wav_invalid_bit_rate():
+def test_get_audio_record_data_parses_wav_invalid_bit_rate(wmc):
with open(RESOURCES / "audio_filedata_wav.json") as f:
file_metadata = json.load(f)
original_data = {"media_url": "myurl.com", "meta_data": {}}
@@ -444,3 +525,53 @@ def test_get_audio_record_data_parses_wav_invalid_bit_rate():
}
actual_parsed_data = wmc.get_audio_record_data(original_data, file_metadata)
assert actual_parsed_data.items() >= expected_parsed_data.items()
+
+
+ "continue_token, expected_props, expected_continue",
+ [
+ ({}, WikimediaCommonsDataIngester.default_props.copy(), "||"),
+ # iicontinue
+ (
+ {
+ "iicontinue": "The_Railway_Chronicle_1844.pdf|20221209222801",
+ "gaicontinue": "20221209222614|NTUL-0527100_英國產業革命史略.pdf",
+ "continue": "gaicontinue||globalusage",
+ },
+ {"prop": RP.query_all, "iiprop": RP.media_no_metadata},
+ "gaicontinue||",
+ ),
+ # gucontinue
+ (
+ {
+ "gucontinue": "Samuel_van_Hoogstraten.jpg|wikidatawiki|28903920",
+ "gaicontinue": "Portland_Street_night_December_2022_Px3_03.jpg",
+ "continue": "gaicontinue||imageinfo",
+ },
+ {"prop": RP.query_no_popularity, "iiprop": RP.media_all},
+ "gaicontinue||",
+ ),
+ # both
+ (
+ {
+ "iicontinue": "The_Railway_Chronicle_1844.pdf|20221209222801",
+ "gucontinue": "Lahore_Satellite_view.jpg|enwiki|125315",
+ "gaicontinue": "20221209222614|NTUL-0527100_英國產業革命史略.pdf",
+ "continue": "gaicontinue||",
+ },
+ {"prop": RP.query_no_popularity, "iiprop": RP.media_no_metadata},
+ "gaicontinue||",
+ ),
+ ],
+)
+def test_adjust_parameters_for_next_iteration(
+ continue_token, expected_props, expected_continue, wmc
+):
+ wmc.continue_token = continue_token
+ gaicontinue = "example||gaicontinue"
+ wmc.adjust_parameters_for_next_iteration(gaicontinue)
+ assert wmc.continue_token == {
+ "continue": expected_continue,
+ "gaicontinue": gaicontinue,
+ }
+ assert wmc.current_props == expected_props