Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Add iNaturalist.org metadata (#549)
rwidomee474f2cbf6f
diff --git a/DAGs.md b/DAGs.mdindex fc48f9777..727b0565e 100644--- a/DAGs.md+++ b/DAGs.md@@ -81,6 +81,7 @@ The following are DAGs grouped by their primary tag:| `finnish_museums_workflow` | `@monthly` | `False` | image || [`flickr_workflow`](#flickr_workflow) | `@daily` | `True` | image || [`freesound_workflow`](#freesound_workflow) | `@monthly` | `False` | audio |+| [`inaturalist_workflow`](#inaturalist_workflow) | `@monthly` | `False` | image || [`jamendo_workflow`](#jamendo_workflow) | `@monthly` | `False` | audio || [`metropolitan_museum_workflow`](#metropolitan_museum_workflow) | `@daily` | `True` | image || `museum_victoria_workflow` | `@monthly` | `False` | image |@@ -117,6 +118,7 @@ The following is documentation associated with each DAG (where available):1. [`flickr_workflow`](#flickr_workflow)1. [`freesound_workflow`](#freesound_workflow)1. [`image_data_refresh`](#image_data_refresh)+ 1. [`inaturalist_workflow`](#inaturalist_workflow)1. [`jamendo_workflow`](#jamendo_workflow)1. [`metropolitan_museum_workflow`](#metropolitan_museum_workflow)1. [`oauth2_authorization`](#oauth2_authorization)@@ -292,6 +294,30 @@ https://github.com/WordPress/openverse-catalog/issues/353)https://github.com/WordPress/openverse-catalog/issues/453)+## `inaturalist_workflow`+++Provider: iNaturalist++Output: TSV file containing the media metadata.++Notes: [The iNaturalist API is not intended for data scraping.]+ (https://api.inaturalist.org/v1/docs/)++ [But there is a full dump intended for sharing on S3.]+ (https://github.com/inaturalist/inaturalist-open-data/tree/documentation/Metadata)++ Because these are very large normalized tables, as opposed to more document+ oriented API responses, we found that bringing the data into postgres first+ was the most effective approach. [More detail in slack here.]+ (https://wordpress.slack.com/archives/C02012JB00N/p1653145643080479?thread_ts=1653082292.714469&cid=C02012JB00N)++ We use the table structure defined [here,]+ (https://github.com/inaturalist/inaturalist-open-data/blob/main/Metadata/structure.sql)+ except for adding ancestry tags to the taxa table.+++## `jamendo_workflow`diff --git a/docker-compose.override.yml b/docker-compose.override.ymlindex caca2b483..5087335fb 100644--- a/docker-compose.override.yml+++ b/docker-compose.override.yml@@ -28,7 +28,7 @@ services:MINIO_ROOT_PASSWORD: ${AWS_SECRET_KEY}# Comma separated list of buckets to create on startupBUCKETS_TO_CREATE: ${OPENVERSE_BUCKET},openverse-airflow-logs,commonsmapper-v2,commonsmapper- # Create the buckets on every container startup+ # Create empty buckets on every container startup# Note: $0 is included in the exec because "/bin/bash -c" swallows the first# argument, so it must be re-added at the beginning of the exec callentrypoint: >-@@ -46,6 +46,36 @@ services:timeout: 20sretries: 3+ load_to_s3:+ image: minio/mc:latest+ env_file:+ - .env+ depends_on:+ - s3+ volumes:+ # Buckets for testing provider data imported from s3 are subdirectories under+ # /tests/s3-data/+ - ./tests/s3-data:/data:rw+ # Loop through subdirectories mounted to the volume and load them to s3/minio.+ # This takes care of filesystem delays on some local dev environments that may make+ # minio miss files included directly in the minio volume.+ # More info here: https://stackoverflow.com/questions/72867045+ # This does *not* allow for testing permissions issues that may come up in real AWS.+ # And, if you remove files from /tests/s3-data, you will need to use `just down -v`+ # and `just up` or `just recreate` to see the minio bucket without those files.+ entrypoint: >+ /bin/sh -c "+ /usr/bin/mc config host add s3 http://s3:5000 ${AWS_ACCESS_KEY} ${AWS_SECRET_KEY};+ cd /data;+ for b in */ ; do+ echo \"Loading bucket $$b\"+ /usr/bin/mc mb --ignore-existing s3/$$b+ /usr/bin/mc cp --r $$b s3/$$b+ /usr/bin/mc ls s3/$$b;+ done ;+ exit 0;+ "+# Dev changes for the webserver containerwebserver:depends_on:diff --git a/docker/local_postgres/0002_aws_s3_mock.sql b/docker/local_postgres/0002_aws_s3_mock.sqlindex a461769f4..16ae8d5b0 100644--- a/docker/local_postgres/0002_aws_s3_mock.sql+++ b/docker/local_postgres/0002_aws_s3_mock.sql@@ -13,6 +13,7 @@ LANGUAGE plpython3uAS $$import osimport boto3+ from datetime import datetime as dts3_obj = boto3.resource('s3',aws_access_key_id=os.getenv('AWS_ACCESS_KEY', 'test_key'),@@ -20,15 +21,19 @@ AS $$region_name=region,endpoint_url=os.getenv('S3_LOCAL_ENDPOINT', 'http://s3:5000')).Object(bucket, file_path)- temp_location = '/tmp/postgres_loading.tsv'+ temp_location = f"/tmp/pg_load_{dt.now().timestamp()}_{file_path.split('/')[-1]}"s3_obj.download_file(temp_location)+ if file_path[-3:]=='.gz':+ copy_from = f"PROGRAM 'gzip -dc {temp_location}'"+ else:+ copy_from = plpy.quote_literal(temp_location)with open(temp_location) as f:columns = '({})'.format(column_list) if column_list else ''res = plpy.execute('COPY {} {} FROM {} {};'.format(table_name,columns,- plpy.quote_literal(temp_location),+ copy_from,options))diff --git a/justfile b/justfileindex 57bf3dbce..b6473db1e 100644--- a/justfile+++ b/justfile@@ -67,8 +67,12 @@ deploy:lint:pre-commit run --all-files+# Load any dependencies necessary for actions on the stack without running the webserver+_deps:+ @just up "postgres s3 load_to_s3"+# Mount the tests directory and run a particular command-@_mount-tests command: (up "postgres s3")+@_mount-tests command: _deps# The test directory is mounted into the container only during testingdocker-compose {{ DOCKER_FILES }} run \-v {{ justfile_directory() }}/tests:/usr/local/airflow/tests/ \@@ -90,7 +94,7 @@ shell: updocker-compose {{ DOCKER_FILES }} exec {{ SERVICE }} /bin/bash# Launch an IPython REPL using the webserver image-ipython: (up "postgres s3")+ipython: _depsdocker-compose {{ DOCKER_FILES }} run \--rm \-w /usr/local/airflow/openverse_catalog/dags \@@ -99,7 +103,7 @@ ipython: (up "postgres s3")/usr/local/airflow/.local/bin/ipython# Run a given command using the webserver image-run *args: (up "postgres s3")+run *args: _depsdocker-compose {{ DOCKER_FILES }} run --rm {{ SERVICE }} {{ args }}# Launch a pgcli shell on the postgres container (defaults to openledger) use "airflow" for airflow metastorediff --git a/openverse_catalog/dags/common/loader/provider_details.py b/openverse_catalog/dags/common/loader/provider_details.pyindex aa5dcdb61..a54c57ca4 100644--- a/openverse_catalog/dags/common/loader/provider_details.py+++ b/openverse_catalog/dags/common/loader/provider_details.py@@ -31,6 +31,7 @@ JAMENDO_DEFAULT_PROVIDER = "jamendo"STOCKSNAP_DEFAULT_PROVIDER = "stocksnap"WORDPRESS_DEFAULT_PROVIDER = "wordpress"FREESOUND_DEFAULT_PROVIDER = "freesound"+INATURALIST_DEFAULT_PROVIDER = "inaturalist"# Finnish parametersFINNISH_SUB_PROVIDERS = {@@ -130,6 +131,7 @@ DEFAULT_IMAGE_CATEGORY = {"deviantart": ImageCategory.DIGITIZED_ARTWORK.value,"digitaltmuseum": ImageCategory.DIGITIZED_ARTWORK.value,"floraon": ImageCategory.PHOTOGRAPH.value,+ "inaturalist": ImageCategory.PHOTOGRAPH.value,"mccordmuseum": ImageCategory.DIGITIZED_ARTWORK.value,"met": ImageCategory.DIGITIZED_ARTWORK.value,"museumsvictoria": ImageCategory.DIGITIZED_ARTWORK.value,diff --git a/openverse_catalog/dags/providers/provider_api_scripts/inaturalist.py b/openverse_catalog/dags/providers/provider_api_scripts/inaturalist.pynew file mode 100644index 000000000..439d6cf8f--- /dev/null+++ b/openverse_catalog/dags/providers/provider_api_scripts/inaturalist.py@@ -0,0 +1,166 @@+"""+Provider: iNaturalist++Output: TSV file containing the media metadata.++Notes: [The iNaturalist API is not intended for data scraping.]+ (https://api.inaturalist.org/v1/docs/)++ [But there is a full dump intended for sharing on S3.]+ (https://github.com/inaturalist/inaturalist-open-data/tree/documentation/Metadata)++ Because these are very large normalized tables, as opposed to more document+ oriented API responses, we found that bringing the data into postgres first+ was the most effective approach. [More detail in slack here.]+ (https://wordpress.slack.com/archives/C02012JB00N/p1653145643080479?thread_ts=1653082292.714469&cid=C02012JB00N)++ We use the table structure defined [here,]+ (https://github.com/inaturalist/inaturalist-open-data/blob/main/Metadata/structure.sql)+ except for adding ancestry tags to the taxa table.+"""++import os+from pathlib import Path+from typing import Dict++import pendulum+from airflow.exceptions import AirflowSkipException+from airflow.operators.python import PythonOperator+from airflow.providers.amazon.aws.hooks.s3 import S3Hook+from airflow.providers.postgres.hooks.postgres import PostgresHook+from airflow.providers.postgres.operators.postgres import PostgresOperator+from airflow.utils.task_group import TaskGroup+from common.constants import POSTGRES_CONN_ID+from common.licenses import LicenseInfo, get_license_info+from common.loader import provider_details as prov+from providers.provider_api_scripts.provider_data_ingester import ProviderDataIngester+++AWS_CONN_ID = os.getenv("AWS_CONN_ID", "test_conn_id")+PROVIDER = prov.INATURALIST_DEFAULT_PROVIDER+SCRIPT_DIR = Path(__file__).parents[1] / "provider_csv_load_scripts/inaturalist"+SOURCE_FILE_NAMES = ["photos", "observations", "taxa", "observers"]+++class INaturalistDataIngester(ProviderDataIngester):++ providers = {"image": prov.INATURALIST_DEFAULT_PROVIDER}++ def __init__(self, *kwargs):+ super(INaturalistDataIngester, self).__init__()+ self.pg = PostgresHook(POSTGRES_CONN_ID)++ # adjustments to buffer limits. TO DO: try to integrate this with the dev+ # environment logic in the base class, rather than just over-writing it.+ # See https://github.com/WordPress/openverse-catalog/issues/682+ self.media_stores["image"].buffer_length = 10_000+ self.batch_limit = 10_000+ self.sql_template = (SCRIPT_DIR / "export_to_json.template.sql").read_text()++ def get_next_query_params(self, prev_query_params=None, **kwargs):+ if prev_query_params is None:+ return {"offset_num": 0}+ else:+ next_offset = prev_query_params["offset_num"] + self.batch_limit+ return {"offset_num": next_offset}++ def get_response_json(self, query_params: Dict):+ """+ Call the SQL to pull json from Postgres, where the raw data has been loaded.+ """+ sql_string = self.sql_template.format(+ batch_limit=self.batch_limit, offset_num=query_params["offset_num"]+ )+ sql_result = self.pg.get_records(sql_string)+ # Postgres returns a list of tuples, even if it's one tuple with one item.+ return sql_result[0][0]++ def get_batch_data(self, response_json):+ if response_json:+ return response_json+ return None++ def get_record_data(self, data):+ if data.get("foreign_identifier") is None:+ # TO DO: maybe raise an error here or after a certain number of these?+ # more info in https://github.com/WordPress/openverse-catalog/issues/684+ return None+ license_url = data.get("license_url")+ license_info = get_license_info(license_url=license_url)+ if license_info == LicenseInfo(None, None, None, None):+ return None+ record_data = {k: data[k] for k in data.keys() if k != "license_url"}+ record_data["license_info"] = license_info+ return record_data++ def get_media_type(self, record):+ # This provider only supports Images via S3, though they have some audio files+ # on site and in the API.+ return "image"++ def endpoint(self):+ raise NotImplementedError("Normalized TSV files from AWS S3 means no endpoint.")++ @staticmethod+ def compare_update_dates(+ last_success: pendulum.DateTime | None, s3_keys: list, aws_conn_id=AWS_CONN_ID+ ):+ # if it was never run, assume the data is new+ if last_success is None:+ return+ s3 = S3Hook(aws_conn_id=aws_conn_id)+ s3_client = s3.get_client_type()+ for key in s3_keys:+ # this will error out if the files don't exist, and bubble up as an+ # informative failure+ last_modified = s3_client.head_object(+ Bucket="inaturalist-open-data", Key=key+ )["LastModified"]+ # if any file has been updated, let's pull them all+ if last_success < last_modified:+ return+ # If no files have been updated, skip the DAG+ raise AirflowSkipException("Nothing new to ingest")++ @staticmethod+ def create_preingestion_tasks():++ with TaskGroup(group_id="preingestion_tasks") as preingestion_tasks:++ check_for_file_updates = PythonOperator(+ task_id="check_for_file_updates",+ python_callable=INaturalistDataIngester.compare_update_dates,+ op_kwargs={+ "last_success": "{{ prev_start_date_success }}",+ "s3_keys": [+ f"{file_name}.csv.gz" for file_name in SOURCE_FILE_NAMES+ ],+ },+ )++ create_inaturalist_schema = PostgresOperator(+ task_id="create_inaturalist_schema",+ postgres_conn_id=POSTGRES_CONN_ID,+ sql=(SCRIPT_DIR / "create_schema.sql").read_text(),+ )++ with TaskGroup(group_id="load_source_files") as load_source_files:+ for source_name in SOURCE_FILE_NAMES:+ PostgresOperator(+ task_id=f"load_{source_name}",+ postgres_conn_id=POSTGRES_CONN_ID,+ sql=(SCRIPT_DIR / f"{source_name}.sql").read_text(),+ ),++ (check_for_file_updates >> create_inaturalist_schema >> load_source_files)++ return preingestion_tasks++ @staticmethod+ def create_postingestion_tasks():+ drop_inaturalist_schema = PostgresOperator(+ task_id="drop_inaturalist_schema",+ postgres_conn_id=POSTGRES_CONN_ID,+ sql="DROP SCHEMA IF EXISTS inaturalist CASCADE",+ )+ return drop_inaturalist_schemadiff --git a/openverse_catalog/dags/providers/provider_csv_load_scripts/inaturalist/create_schema.sql b/openverse_catalog/dags/providers/provider_csv_load_scripts/inaturalist/create_schema.sqlnew file mode 100644index 000000000..8c4d1287f--- /dev/null+++ b/openverse_catalog/dags/providers/provider_csv_load_scripts/inaturalist/create_schema.sql@@ -0,0 +1,4 @@+CREATE SCHEMA IF NOT EXISTS inaturalist;+COMMIT;+SELECT schema_name+FROM information_schema.schemata WHERE schema_name = 'inaturalist';diff --git a/openverse_catalog/dags/providers/provider_csv_load_scripts/inaturalist/export_to_json.template.sql b/openverse_catalog/dags/providers/provider_csv_load_scripts/inaturalist/export_to_json.template.sqlnew file mode 100644index 000000000..d7cfef2f0--- /dev/null+++ b/openverse_catalog/dags/providers/provider_csv_load_scripts/inaturalist/export_to_json.template.sql@@ -0,0 +1,87 @@+/*+-------------------------------------------------------------------------------+EXPORT TO JSON+-------------------------------------------------------------------------------++ ** Please note: This SQL will not run as is! You must replace offset_num and+ batch_limit with integers representing the records you want to retrieve.++Joining two very large normalized tables is difficult, in any data manipulation system.+PHOTOS has on the order of 120 million records, and OBSERVATIONS has on the order of+70 million records. We have to join them to get at the taxa (species) information for+any given photo. Taxa are the only descriptive text we have for inaturalist photos.++The postgres query optimizer is smart enough to use limit and offset to make this like+joining multiple small-ish tables to a single large one which is not so difficult. The+ORDER BY requires a sort on each call, but the index on INATURALIST.PHOTOS.PHOTO_ID+makes that manageable. (More info on limit / offset and query optimization at+https://www.postgresql.org/docs/current/queries-limit.html)++This query calls for 100 records at a time to match the pace of the python ingester.++Alternative approaches considered:+- Let python do the pagination using a cursor: Joining the two full tables in one step+ requires working through 120 million * 70 million possible combinations, and when+ tested with the full dataset after 13 minutes the local machine was physically hot and+ had not yet returned a single record.+- Use database pagination instead of limit/offset: This would have avoided the need to+ sort / index, but might have introduced data quality risks (if postgres moved+ things around while the job was running) and some pages appeared empty which required+ more complicated python logic for retries. More on this approach at:+ https://www.citusdata.com/blog/2016/03/30/five-ways-to-paginate/++Everything on iNaturalist is holding at version 4, except CC0 which is version 1.0.+License versions below are hard-coded from inaturalist+https://github.com/inaturalist/inaturalist/blob/d338ba76d82af83d8ad0107563015364a101568c/app/models/shared/license_module.rb#L5+*/++select json_agg(records)+from (+ SELECT+ INATURALIST.PHOTOS.PHOTO_ID as foreign_identifier,+ INATURALIST.PHOTOS.WIDTH,+ INATURALIST.PHOTOS.HEIGHT,+ INATURALIST.TAXA.NAME as title,+ array_to_json(INATURALIST.TAXA.ancestor_names) as raw_tags,+ LOWER(INATURALIST.PHOTOS.EXTENSION) as filetype,+ (CASE+ WHEN INATURALIST.PHOTOS.LICENSE = 'CC-BY-NC-SA'+ THEN 'http://creativecommons.org/licenses/by-nc-sa/4.0/'+ WHEN INATURALIST.PHOTOS.LICENSE = 'CC-BY-NC'+ THEN 'http://creativecommons.org/licenses/by-nc/4.0/'+ WHEN INATURALIST.PHOTOS.LICENSE = 'CC-BY-NC-ND'+ THEN 'http://creativecommons.org/licenses/by-nc-nd/4.0/'+ WHEN INATURALIST.PHOTOS.LICENSE = 'CC-BY'+ THEN 'http://creativecommons.org/licenses/by/4.0/'+ WHEN INATURALIST.PHOTOS.LICENSE = 'CC-BY-SA'+ THEN 'http://creativecommons.org/licenses/by-sa/4.0/'+ WHEN INATURALIST.PHOTOS.LICENSE = 'CC-BY-ND'+ THEN 'http://creativecommons.org/licenses/by-nd/4.0/'+ WHEN INATURALIST.PHOTOS.LICENSE = 'PD'+ THEN 'http://en.wikipedia.org/wiki/Public_domain'+ WHEN INATURALIST.PHOTOS.LICENSE = 'CC0'+ THEN 'http://creativecommons.org/publicdomain/zero/1.0/'+ END) as license_url,+ 'https://www.inaturalist.org/photos/' || INATURALIST.PHOTOS.PHOTO_ID+ as foreign_landing_url,+ 'https://inaturalist-open-data.s3.amazonaws.com/photos/'+ || INATURALIST.PHOTOS.PHOTO_ID || '/medium.' || INATURALIST.PHOTOS.EXTENSION+ as image_url,+ COALESCE(INATURALIST.OBSERVERS.LOGIN, INATURALIST.PHOTOS.OBSERVER_ID::text)+ as creator,+ 'https://www.inaturalist.org/users/' || INATURALIST.PHOTOS.OBSERVER_ID+ as creator_url+ FROM INATURALIST.PHOTOS+ INNER JOIN+ INATURALIST.OBSERVATIONS ON+ INATURALIST.PHOTOS.OBSERVATION_UUID = INATURALIST.OBSERVATIONS.OBSERVATION_UUID+ INNER JOIN+ INATURALIST.OBSERVERS ON+ INATURALIST.PHOTOS.OBSERVER_ID = INATURALIST.OBSERVERS.OBSERVER_ID+ INNER JOIN+ INATURALIST.TAXA ON+ INATURALIST.OBSERVATIONS.TAXON_ID = INATURALIST.TAXA.TAXON_ID+ ORDER BY PHOTO_ID+ LIMIT {batch_limit}+ OFFSET {offset_num}+) as records;diff --git a/openverse_catalog/dags/providers/provider_csv_load_scripts/inaturalist/observations.sql b/openverse_catalog/dags/providers/provider_csv_load_scripts/inaturalist/observations.sqlnew file mode 100644index 000000000..09e87b81d--- /dev/null+++ b/openverse_catalog/dags/providers/provider_csv_load_scripts/inaturalist/observations.sql@@ -0,0 +1,38 @@+/*+-------------------------------------------------------------------------------+OBSERVATIONS+-------------------------------------------------------------------------------+-- ~400,000 observations do not have a taxon_id that is in the taxa table.+-- Their photos are not included in the final transformed view on the+ assumption that photos are not useful to us without a title or tags++Taking DDL from+https://github.com/inaturalist/inaturalist-open-data/blob/main/Metadata/structure.sql+*/++DROP TABLE IF EXISTS inaturalist.observations;+COMMIT;++CREATE TABLE inaturalist.observations (+ observation_uuid uuid,+ observer_id integer,+ latitude numeric(15, 10),+ longitude numeric(15, 10),+ positional_accuracy integer,+ taxon_id integer,+ quality_grade character varying(255),+ observed_on date+);+COMMIT;++SELECT aws_s3.table_import_from_s3('inaturalist.observations',+ '',+ '(FORMAT ''csv'', DELIMITER E''\t'', HEADER, QUOTE E''\b'')',+ 'inaturalist-open-data',+ 'observations.csv.gz',+ 'us-east-1');++ALTER TABLE inaturalist.observations ADD PRIMARY KEY (observation_uuid);+COMMIT;++SELECT count(*) FROM inaturalist.observations;diff --git a/openverse_catalog/dags/providers/provider_csv_load_scripts/inaturalist/observers.sql b/openverse_catalog/dags/providers/provider_csv_load_scripts/inaturalist/observers.sqlnew file mode 100644index 000000000..52672fdba--- /dev/null+++ b/openverse_catalog/dags/providers/provider_csv_load_scripts/inaturalist/observers.sql@@ -0,0 +1,30 @@+/*+-------------------------------------------------------------------------------+OBSERVERS+-------------------------------------------------------------------------------++Taking DDL from+https://github.com/inaturalist/inaturalist-open-data/blob/main/Metadata/structure.sql+*/++DROP TABLE IF EXISTS inaturalist.observers;+COMMIT;++CREATE TABLE inaturalist.observers (+ observer_id integer,+ login character varying(255),+ name character varying(255)+);+COMMIT;++SELECT aws_s3.table_import_from_s3('inaturalist.observers',+ '',+ '(FORMAT ''csv'', DELIMITER E''\t'', HEADER, QUOTE E''\b'')',+ 'inaturalist-open-data',+ 'observers.csv.gz',+ 'us-east-1');++ALTER TABLE inaturalist.observers ADD PRIMARY KEY (observer_id);+COMMIT;++SELECT count(*) FROM inaturalist.observers;diff --git a/openverse_catalog/dags/providers/provider_csv_load_scripts/inaturalist/photos.sql b/openverse_catalog/dags/providers/provider_csv_load_scripts/inaturalist/photos.sqlnew file mode 100644index 000000000..d53a17346--- /dev/null+++ b/openverse_catalog/dags/providers/provider_csv_load_scripts/inaturalist/photos.sql@@ -0,0 +1,44 @@+/*+-------------------------------------------------------------------------------+PHOTOS+-------------------------------------------------------------------------------+-- despite the 2022-05-30 data set having complete observer IDs, we do not use an FK+ constraint on observer_id in order to save load time+-- photo_id is not unique. There are ~130,000 duplicate photo_ids (~0.1% of photos).+ Both records are saved to the TSV and only one is loaded back into to postgres.+-- TO DO: See https://github.com/WordPress/openverse-catalog/issues/685 for more on+ handling duplicate photo ids.++Taking DDL from+https://github.com/inaturalist/inaturalist-open-data/blob/main/Metadata/structure.sql+*/++DROP TABLE IF EXISTS inaturalist.photos CASCADE;+COMMIT;++CREATE TABLE inaturalist.photos (+ photo_uuid uuid NOT NULL,+ photo_id integer NOT NULL,+ observation_uuid uuid NOT NULL,+ observer_id integer,+ extension character varying(5),+ license character varying(255),+ width smallint,+ height smallint,+ position smallint+);+COMMIT;++SELECT aws_s3.table_import_from_s3('inaturalist.photos',+ '',+ '(FORMAT ''csv'', DELIMITER E''\t'', HEADER, QUOTE E''\b'')',+ 'inaturalist-open-data',+ 'photos.csv.gz',+ 'us-east-1');++-- Not unique, because photo id isn't unique, and it will take too long to check.+-- btree because that is the only one that will support limit/offset without sorting.+-- more here: https://www.postgresql.org/docs/current/indexes-ordering.html+CREATE INDEX ON INATURALIST.PHOTOS USING btree (PHOTO_ID);++SELECT count(*) FROM inaturalist.photos;diff --git a/openverse_catalog/dags/providers/provider_csv_load_scripts/inaturalist/taxa.sql b/openverse_catalog/dags/providers/provider_csv_load_scripts/inaturalist/taxa.sqlnew file mode 100644index 000000000..347508b91--- /dev/null+++ b/openverse_catalog/dags/providers/provider_csv_load_scripts/inaturalist/taxa.sql@@ -0,0 +1,53 @@+/*+-------------------------------------------------------------------------------+TAXA+-------------------------------------------------------------------------------++Taking DDL from+https://github.com/inaturalist/inaturalist-open-data/blob/main/Metadata/structure.sql+Plus adding a field for ancestry tags.+*/++DROP TABLE IF EXISTS inaturalist.taxa;+COMMIT;++CREATE TABLE inaturalist.taxa (+ taxon_id integer,+ ancestry character varying(255),+ rank_level double precision,+ rank character varying(255),+ name character varying(255),+ active boolean,+ ancestor_names varchar[]+);+COMMIT;++SELECT aws_s3.table_import_from_s3('inaturalist.taxa',+ 'taxon_id, ancestry, rank_level, rank, name, active',+ '(FORMAT ''csv'', DELIMITER E''\t'', HEADER, QUOTE E''\b'')',+ 'inaturalist-open-data',+ 'taxa.csv.gz',+ 'us-east-1');++ALTER TABLE inaturalist.taxa ADD PRIMARY KEY (taxon_id);+COMMIT;++WITH aggregated AS+(+ select+ child.taxon_id,+ array_agg(ancestors.name) as ancestor_names+ from+ inaturalist.taxa ancestors,+ inaturalist.taxa child+ where ancestors.taxon_id = ANY (string_to_array(child.ancestry, '/')::int[])+ and ancestors.rank not in ('stateofmatter','epifamily','zoosection')+ group by child.taxon_id+)+UPDATE inaturalist.taxa+SET ancestor_names = aggregated.ancestor_names+from aggregated+where taxa.taxon_id = aggregated.taxon_id;+COMMIT;++SELECT count(*) FROM inaturalist.taxa;diff --git a/openverse_catalog/dags/providers/provider_dag_factory.py b/openverse_catalog/dags/providers/provider_dag_factory.pyindex 28cafc4ef..80d020641 100644--- a/openverse_catalog/dags/providers/provider_dag_factory.py+++ b/openverse_catalog/dags/providers/provider_dag_factory.py@@ -107,6 +107,8 @@ def create_provider_api_workflow(load_timeout: timedelta = timedelta(hours=1),doc_md: Optional[str] = "",media_types: Sequence[str] = ("image",),+ create_preingestion_tasks: Optional[Callable] = None,+ create_postingestion_tasks: Optional[Callable] = None,):"""This factory method instantiates a DAG that will run the given@@ -150,6 +152,10 @@ def create_provider_api_workflow(doc_md: string which should be used for the DAG's documentation markdownmedia_types: list describing the media type(s) that this provider handles(e.g. `["audio"]`, `["image", "audio"]`, etc.)+ create_preingestion_tasks and create_postingestion_tasks: callable which creates a+ task or task group to be run before or after (respectively) the+ rest of the provider workflow. Loading and dropping temporary+ tables is one example."""default_args = {**DAG_DEFAULT_ARGS, **(default_args or {})}media_type_name = "mixed" if len(media_types) > 1 else media_types[0]@@ -286,6 +292,14 @@ def create_provider_api_workflow(generate_filenames >> pull_data >> load_tasks >> report_load_completion+ if create_preingestion_tasks:+ preingestion_tasks = create_preingestion_tasks()+ preingestion_tasks >> pull_data++ if create_postingestion_tasks:+ postingestion_tasks = create_postingestion_tasks()+ pull_data >> postingestion_tasks+return dagdiff --git a/openverse_catalog/dags/providers/provider_workflow_dag_factory.py b/openverse_catalog/dags/providers/provider_workflow_dag_factory.pyindex ab61910b6..5ebdba20d 100644--- a/openverse_catalog/dags/providers/provider_workflow_dag_factory.py+++ b/openverse_catalog/dags/providers/provider_workflow_dag_factory.py@@ -33,4 +33,6 @@ for provider_workflow in PROVIDER_WORKFLOWS:provider_workflow.load_timeout,provider_script.__doc__,provider_workflow.media_types,+ provider_workflow.preingestion_task_creator,+ provider_workflow.postingestion_task_creator,)diff --git a/openverse_catalog/dags/providers/provider_workflows.py b/openverse_catalog/dags/providers/provider_workflows.pyindex fd0740796..5aaaf7a3f 100644--- a/openverse_catalog/dags/providers/provider_workflows.py+++ b/openverse_catalog/dags/providers/provider_workflows.py@@ -4,6 +4,7 @@ from typing import Dict, Optional, Sequence, Typefrom providers.provider_api_scripts.cleveland_museum import ClevelandDataIngesterfrom providers.provider_api_scripts.finnish_museums import FinnishMuseumsDataIngester+from providers.provider_api_scripts.inaturalist import INaturalistDataIngesterfrom providers.provider_api_scripts.museum_victoria import VictoriaDataIngesterfrom providers.provider_api_scripts.provider_data_ingester import ProviderDataIngesterfrom providers.provider_api_scripts.science_museum import ScienceMuseumDataIngester@@ -54,6 +55,12 @@ class ProviderWorkflow:doc_md: string which should be used for the DAG's documentation markdownmedia_types: list describing the media type(s) that this provider handles(e.g. `["audio"]`, `["image", "audio"]`, etc.)+ preingestion_task_creator: callable that returns an airflow task or task group to+ to run any necessary pre-ingestion tasks, such as loading bulk+ data from S3+ postingestion_task_creator: callable that returns an airflow task or task group to+ to run any necessary post-ingestion tasks, such as dropping data+ loaded during pre-ingestion"""provider_script: str@@ -70,6 +77,8 @@ class ProviderWorkflow:load_timeout: timedelta = timedelta(hours=1)doc_md: str = ""media_types: Sequence[str] = ("image",)+ preingestion_task_creator: Optional[callable] = None+ postingestion_task_creator: Optional[callable] = Nonedef __post_init__(self):if not self.dag_id:@@ -106,6 +115,13 @@ PROVIDER_WORKFLOWS = [schedule_string="@daily",dated=True,),+ ProviderWorkflow(+ provider_script="inaturalist",+ ingester_class=INaturalistDataIngester,+ preingestion_task_creator=INaturalistDataIngester.create_preingestion_tasks,+ postingestion_task_creator=INaturalistDataIngester.create_postingestion_tasks,+ schedule_string="@monthly",+ ),ProviderWorkflow(provider_script="freesound",media_types=("audio",),diff --git a/tests/dags/providers/provider_api_scripts/resources/inaturalist/full_db_response.txt b/tests/dags/providers/provider_api_scripts/resources/inaturalist/full_db_response.txtnew file mode 100644index 000000000..66e613bd5--- /dev/null+++ b/tests/dags/providers/provider_api_scripts/resources/inaturalist/full_db_response.txt@@ -0,0 +1 @@+[([{'foreign_identifier': 10314159, 'width': 1530, 'height': 2048, 'title': 'Trifolium hybridum', 'raw_tags': ['Fabaceae', 'Fabales', 'Magnoliopsida', 'Angiospermae', 'Plantae', 'Trifolium', 'Tracheophyta', 'Faboideae', 'Trifolieae'], 'filetype': 'jpg', 'license_url': 'http://creativecommons.org/licenses/by-nc/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/10314159', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/10314159/medium.jpg', 'creator': 'akjenny', 'creator_url': 'https://www.inaturalist.org/users/615549'}, {'foreign_identifier': 20314159, 'width': 2048, 'height': 1955, 'title': 'Lonicera sempervirens', 'raw_tags': ['Magnoliopsida', 'Angiospermae', 'Plantae', 'Dipsacales', 'Caprifoliaceae', 'Lonicera', 'Tracheophyta', 'Caprifolioideae', 'Caprifolium'], 'filetype': 'jpeg', 'license_url': 'http://creativecommons.org/licenses/by-nc/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/20314159', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/20314159/medium.jpeg', 'creator': 'drshawntdash', 'creator_url': 'https://www.inaturalist.org/users/11861'}, {'foreign_identifier': 30314159, 'width': 2048, 'height': 1360, 'title': 'Ladona julia', 'raw_tags': ['Animalia', 'Arthropoda', 'Insecta', 'Odonata', 'Libellulidae', 'Anisoptera', 'Ladona', 'Pterygota', 'Hexapoda', 'Libelluloidea'], 'filetype': 'jpeg', 'license_url': 'http://creativecommons.org/licenses/by-nc/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/30314159', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/30314159/medium.jpeg', 'creator': 'parzudak', 'creator_url': 'https://www.inaturalist.org/users/813200'}, {'foreign_identifier': 40314159, 'width': 1024, 'height': 683, 'title': 'Leucochrysum stipitatum', 'raw_tags': ['Magnoliopsida', 'Angiospermae', 'Plantae', 'Asteraceae', 'Asterales', 'Leucochrysum', 'Tracheophyta', 'Gnaphalieae', 'Asteroideae'], 'filetype': 'jpeg', 'license_url': 'http://creativecommons.org/licenses/by-nc-sa/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/40314159', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/40314159/medium.jpeg', 'creator': 'kenw', 'creator_url': 'https://www.inaturalist.org/users/1623'}, {'foreign_identifier': 60314159, 'width': 1536, 'height': 2048, 'title': 'Arion ater', 'raw_tags': ['Animalia', 'Gastropoda', 'Mollusca', 'Stylommatophora', 'Arionidae', 'Arion', 'Arionoidea', 'Arion', 'Heterobranchia', 'Euthyneura', 'Tectipleura', 'Eupulmonata', 'Helicina', 'Arionoidei'], 'filetype': 'jpeg', 'license_url': 'http://creativecommons.org/licenses/by-nc/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/60314159', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/60314159/medium.jpeg', 'creator': 'max_hof_mann', 'creator_url': 'https://www.inaturalist.org/users/775177'}, {'foreign_identifier': 80314159, 'width': 1536, 'height': 2048, 'title': 'Insecta', 'raw_tags': ['Animalia', 'Arthropoda', 'Hexapoda'], 'filetype': 'jpg', 'license_url': 'http://creativecommons.org/licenses/by-nc/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/80314159', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/80314159/medium.jpg', 'creator': 'sheilacro', 'creator_url': 'https://www.inaturalist.org/users/3225310'}, {'foreign_identifier': 90314159, 'width': 1350, 'height': 900, 'title': 'Herpetogramma', 'raw_tags': ['Animalia', 'Arthropoda', 'Lepidoptera', 'Insecta', 'Pyraloidea', 'Crambidae', 'Spilomelinae', 'Pterygota', 'Hexapoda', 'Herpetogrammatini'], 'filetype': 'jpeg', 'license_url': 'http://creativecommons.org/licenses/by-nc-nd/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/90314159', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/90314159/medium.jpeg', 'creator': 'natureguy', 'creator_url': 'https://www.inaturalist.org/users/134993'}, {'foreign_identifier': 110314159, 'width': 2048, 'height': 1365, 'title': 'Cladonia', 'raw_tags': ['Fungi', 'Ascomycota', 'Lecanorales', 'Cladoniaceae', 'Lecanoromycetes', 'Pezizomycotina', 'Lecanoromycetidae'], 'filetype': 'jpeg', 'license_url': 'http://creativecommons.org/licenses/by-nc/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/110314159', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/110314159/medium.jpeg', 'creator': 'sichonik', 'creator_url': 'https://www.inaturalist.org/users/3892316'}, {'foreign_identifier': 120314159, 'width': 792, 'height': 653, 'title': 'Sarcophagidae', 'raw_tags': ['Animalia', 'Arthropoda', 'Insecta', 'Diptera', 'Brachycera', 'Pterygota', 'Calyptratae', 'Oestroidea', 'Hexapoda', 'Cyclorrhapha'], 'filetype': 'jpg', 'license_url': 'http://creativecommons.org/licenses/by/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/120314159', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/120314159/medium.jpg', 'creator': 'zealouswizard', 'creator_url': 'https://www.inaturalist.org/users/3234999'}, {'foreign_identifier': 130314159, 'width': 1024, 'height': 2048, 'title': 'Senecio vernalis', 'raw_tags': ['Magnoliopsida', 'Angiospermae', 'Plantae', 'Asteraceae', 'Asterales', 'Senecio', 'Tracheophyta', 'Senecioneae', 'Asteroideae', 'Senecioninae'], 'filetype': 'jpeg', 'license_url': 'http://creativecommons.org/licenses/by/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/130314159', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/130314159/medium.jpeg', 'creator': 'solokultas', 'creator_url': 'https://www.inaturalist.org/users/1198134'}, {'foreign_identifier': 150314159, 'width': 1536, 'height': 2048, 'title': 'Matricaria discoidea', 'raw_tags': ['Magnoliopsida', 'Angiospermae', 'Plantae', 'Asteraceae', 'Asterales', 'Matricaria', 'Tracheophyta', 'Anthemideae', 'Asteroideae', 'Matricariinae'], 'filetype': 'jpeg', 'license_url': 'http://creativecommons.org/licenses/by-nc/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/150314159', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/150314159/medium.jpeg', 'creator': 'tularosatabulator', 'creator_url': 'https://www.inaturalist.org/users/3586703'}, {'foreign_identifier': 160314159, 'width': 1536, 'height': 2048, 'title': 'Sciurus granatensis', 'raw_tags': ['Animalia', 'Chordata', 'Mammalia', 'Rodentia', 'Sciuridae', 'Sciurus', 'Sciuromorpha', 'Sciurinae', 'Sciurini', 'Vertebrata', 'Theria', 'Placentalia', 'Euarchontoglires'], 'filetype': 'jpg', 'license_url': 'http://creativecommons.org/licenses/by-nc/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/160314159', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/160314159/medium.jpg', 'creator': 'mp_velez87', 'creator_url': 'https://www.inaturalist.org/users/5040484'}, {'foreign_identifier': 170314159, 'width': 1536, 'height': 2048, 'title': 'Bacopa monnieri', 'raw_tags': ['Magnoliopsida', 'Angiospermae', 'Plantae', 'Lamiales', 'Plantaginaceae', 'Bacopa', 'Tracheophyta', 'Gratioleae'], 'filetype': 'jpg', 'license_url': 'http://creativecommons.org/licenses/by-nc/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/170314159', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/170314159/medium.jpg', 'creator': 'calebhelsel', 'creator_url': 'https://www.inaturalist.org/users/3314770'}, {'foreign_identifier': 190995604, 'width': 2048, 'height': 1536, 'title': 'Arenaria interpres', 'raw_tags': ['Animalia', 'Chordata', 'Aves', 'Scolopacidae', 'Arenaria', 'Charadriiformes', 'Vertebrata'], 'filetype': 'jpeg', 'license_url': 'http://creativecommons.org/licenses/by-nc/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/190995604', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/190995604/medium.jpeg', 'creator': 'raymie', 'creator_url': 'https://www.inaturalist.org/users/765334'}, {'foreign_identifier': 190995604, 'width': 2048, 'height': 1536, 'title': 'Dreissena polymorpha', 'raw_tags': ['Animalia', 'Mollusca', 'Bivalvia', 'Myida', 'Dreissenidae', 'Dreissena', 'Euheterodonta', 'Imparidentia', 'Dreissenoidea', 'Autobranchia', 'Heteroconchia', 'Dreisseninae'], 'filetype': 'jpeg', 'license_url': 'http://creativecommons.org/licenses/by-nc/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/190995604', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/190995604/medium.jpeg', 'creator': 'raymie', 'creator_url': 'https://www.inaturalist.org/users/765334'}, {'foreign_identifier': 190995656, 'width': 2048, 'height': 1536, 'title': 'Dreissena polymorpha', 'raw_tags': ['Animalia', 'Mollusca', 'Bivalvia', 'Myida', 'Dreissenidae', 'Dreissena', 'Euheterodonta', 'Imparidentia', 'Dreissenoidea', 'Autobranchia', 'Heteroconchia', 'Dreisseninae'], 'filetype': 'jpeg', 'license_url': 'http://creativecommons.org/licenses/by-nc/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/190995656', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/190995656/medium.jpeg', 'creator': 'raymie', 'creator_url': 'https://www.inaturalist.org/users/765334'}, {'foreign_identifier': 190995656, 'width': 2048, 'height': 1536, 'title': 'Arenaria interpres', 'raw_tags': ['Animalia', 'Chordata', 'Aves', 'Scolopacidae', 'Arenaria', 'Charadriiformes', 'Vertebrata'], 'filetype': 'jpeg', 'license_url': 'http://creativecommons.org/licenses/by-nc/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/190995656', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/190995656/medium.jpeg', 'creator': 'raymie', 'creator_url': 'https://www.inaturalist.org/users/765334'}, {'foreign_identifier': 191001500, 'width': 2048, 'height': 1536, 'title': 'Pachypsylla venusta', 'raw_tags': ['Animalia', 'Arthropoda', 'Insecta', 'Hemiptera', 'Psylloidea', 'Pterygota', 'Pachypsylla', 'Sternorrhyncha', 'Hexapoda', 'Aphalaridae', 'Pachypsyllinae'], 'filetype': 'jpeg', 'license_url': 'http://creativecommons.org/licenses/by-nc/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/191001500', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/191001500/medium.jpeg', 'creator': 'cosmiccat', 'creator_url': 'https://www.inaturalist.org/users/34728'}, {'foreign_identifier': 191001500, 'width': 2048, 'height': 1536, 'title': 'Celtis laevigata', 'raw_tags': ['Magnoliopsida', 'Angiospermae', 'Plantae', 'Rosales', 'Cannabaceae', 'Celtis', 'Tracheophyta'], 'filetype': 'jpeg', 'license_url': 'http://creativecommons.org/licenses/by-nc/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/191001500', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/191001500/medium.jpeg', 'creator': 'cosmiccat', 'creator_url': 'https://www.inaturalist.org/users/34728'}, {'foreign_identifier': 191012628, 'width': 1152, 'height': 2048, 'title': 'Pseudacris fouquettei', 'raw_tags': ['Animalia', 'Chordata', 'Amphibia', 'Anura', 'Hylidae', 'Pseudacris', 'Vertebrata', 'Acridinae'], 'filetype': 'jpg', 'license_url': 'http://creativecommons.org/licenses/by-nc/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/191012628', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/191012628/medium.jpg', 'creator': 'kaptainkory', 'creator_url': 'https://www.inaturalist.org/users/22614'}, {'foreign_identifier': 191012628, 'width': 1152, 'height': 2048, 'title': 'Pseudacris crucifer', 'raw_tags': ['Animalia', 'Chordata', 'Amphibia', 'Anura', 'Hylidae', 'Pseudacris', 'Vertebrata', 'Acridinae'], 'filetype': 'jpg', 'license_url': 'http://creativecommons.org/licenses/by-nc/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/191012628', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/191012628/medium.jpg', 'creator': 'kaptainkory', 'creator_url': 'https://www.inaturalist.org/users/22614'}, {'foreign_identifier': 191015484, 'width': 2048, 'height': 1684, 'title': 'Lantana camara', 'raw_tags': ['Magnoliopsida', 'Angiospermae', 'Plantae', 'Lamiales', 'Verbenaceae', 'Lantana', 'Tracheophyta', 'Lantaneae'], 'filetype': 'jpeg', 'license_url': 'http://creativecommons.org/licenses/by-nc/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/191015484', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/191015484/medium.jpeg', 'creator': 'bushboy', 'creator_url': 'https://www.inaturalist.org/users/662724'}, {'foreign_identifier': 191015484, 'width': 2048, 'height': 1684, 'title': 'Aporiina', 'raw_tags': ['Animalia', 'Arthropoda', 'Lepidoptera', 'Insecta', 'Papilionoidea', 'Pieridae', 'Pterygota', 'Pierinae', 'Pierini', 'Hexapoda'], 'filetype': 'jpeg', 'license_url': 'http://creativecommons.org/licenses/by-nc/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/191015484', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/191015484/medium.jpeg', 'creator': 'bushboy', 'creator_url': 'https://www.inaturalist.org/users/662724'}, {'foreign_identifier': 191015547, 'width': 2048, 'height': 1536, 'title': 'Aporiina', 'raw_tags': ['Animalia', 'Arthropoda', 'Lepidoptera', 'Insecta', 'Papilionoidea', 'Pieridae', 'Pterygota', 'Pierinae', 'Pierini', 'Hexapoda'], 'filetype': 'jpeg', 'license_url': 'http://creativecommons.org/licenses/by-nc/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/191015547', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/191015547/medium.jpeg', 'creator': 'bushboy', 'creator_url': 'https://www.inaturalist.org/users/662724'}, {'foreign_identifier': 191015547, 'width': 2048, 'height': 1536, 'title': 'Lantana camara', 'raw_tags': ['Magnoliopsida', 'Angiospermae', 'Plantae', 'Lamiales', 'Verbenaceae', 'Lantana', 'Tracheophyta', 'Lantaneae'], 'filetype': 'jpeg', 'license_url': 'http://creativecommons.org/licenses/by-nc/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/191015547', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/191015547/medium.jpeg', 'creator': 'bushboy', 'creator_url': 'https://www.inaturalist.org/users/662724'}, {'foreign_identifier': 191016506, 'width': 2048, 'height': 1536, 'title': 'Gambusia holbrooki', 'raw_tags': ['Animalia', 'Chordata', 'Actinopterygii', 'Cyprinodontiformes', 'Poeciliidae', 'Gambusia', 'Vertebrata', 'Poeciliinae', 'Cyprinodontoidei'], 'filetype': 'jpeg', 'license_url': 'http://creativecommons.org/licenses/by-nc/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/191016506', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/191016506/medium.jpeg', 'creator': 'kingmush', 'creator_url': 'https://www.inaturalist.org/users/3453019'}, {'foreign_identifier': 191016506, 'width': 2048, 'height': 1536, 'title': 'Panicum repens', 'raw_tags': ['Angiospermae', 'Plantae', 'Poales', 'Liliopsida', 'Poaceae', 'Panicum', 'Tracheophyta', 'Paniceae', 'Panicoideae', 'Panicinae'], 'filetype': 'jpeg', 'license_url': 'http://creativecommons.org/licenses/by-nc/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/191016506', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/191016506/medium.jpeg', 'creator': 'kingmush', 'creator_url': 'https://www.inaturalist.org/users/3453019'}, {'foreign_identifier': 191018870, 'width': 1363, 'height': 2048, 'title': 'Toxicodendron diversilobum', 'raw_tags': ['Magnoliopsida', 'Angiospermae', 'Plantae', 'Sapindales', 'Anacardiaceae', 'Toxicodendron', 'Tracheophyta', 'Anacardioideae'], 'filetype': 'jpg', 'license_url': 'http://creativecommons.org/licenses/by-nc/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/191018870', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/191018870/medium.jpg', 'creator': 'tiwane', 'creator_url': 'https://www.inaturalist.org/users/28'}, {'foreign_identifier': 191018870, 'width': 1363, 'height': 2048, 'title': 'Pedicularis densiflora', 'raw_tags': ['Magnoliopsida', 'Angiospermae', 'Plantae', 'Orobanchaceae', 'Lamiales', 'Pedicularis', 'Tracheophyta', 'Pedicularideae'], 'filetype': 'jpg', 'license_url': 'http://creativecommons.org/licenses/by-nc/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/191018870', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/191018870/medium.jpg', 'creator': 'tiwane', 'creator_url': 'https://www.inaturalist.org/users/28'}, {'foreign_identifier': 191018903, 'width': 818, 'height': 741, 'title': 'Ranunculus occidentalis', 'raw_tags': ['Magnoliopsida', 'Angiospermae', 'Plantae', 'Ranunculus', 'Ranunculaceae', 'Ranunculales', 'Tracheophyta', 'Ranunculoideae', 'Ranunculeae'], 'filetype': 'jpg', 'license_url': 'http://creativecommons.org/licenses/by-nc/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/191018903', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/191018903/medium.jpg', 'creator': 'tiwane', 'creator_url': 'https://www.inaturalist.org/users/28'}, {'foreign_identifier': 191018903, 'width': 818, 'height': 741, 'title': 'Andrena', 'raw_tags': ['Animalia', 'Arthropoda', 'Insecta', 'Hymenoptera', 'Apoidea', 'Andrenidae', 'Apocrita', 'Pterygota', 'Aculeata', 'Hexapoda', 'Andreninae', 'Andrenini'], 'filetype': 'jpg', 'license_url': 'http://creativecommons.org/licenses/by-nc/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/191018903', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/191018903/medium.jpg', 'creator': 'tiwane', 'creator_url': 'https://www.inaturalist.org/users/28'}, {'foreign_identifier': 191019692, 'width': 1800, 'height': 1200, 'title': 'Mareca americana', 'raw_tags': ['Animalia', 'Chordata', 'Aves', 'Anseriformes', 'Anatidae', 'Vertebrata', 'Mareca'], 'filetype': 'png', 'license_url': 'http://creativecommons.org/licenses/by-nc/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/191019692', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/191019692/medium.png', 'creator': 'dabee', 'creator_url': 'https://www.inaturalist.org/users/4024764'}, {'foreign_identifier': 191019692, 'width': 1800, 'height': 1200, 'title': 'Anas platyrhynchos', 'raw_tags': ['Animalia', 'Chordata', 'Aves', 'Anseriformes', 'Anatidae', 'Anas', 'Vertebrata'], 'filetype': 'png', 'license_url': 'http://creativecommons.org/licenses/by-nc/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/191019692', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/191019692/medium.png', 'creator': 'dabee', 'creator_url': 'https://www.inaturalist.org/users/4024764'}, {'foreign_identifier': 200352737, 'width': 1536, 'height': 2048, 'title': 'Plantae', 'raw_tags': None, 'filetype': 'jpg', 'license_url': 'http://creativecommons.org/licenses/by-nc/4.0/', 'foreign_landing_url': 'https://www.inaturalist.org/photos/200352737', 'image_url': 'https://inaturalist-open-data.s3.amazonaws.com/photos/200352737/medium.jpg', 'creator': 'sikstro1', 'creator_url': 'https://www.inaturalist.org/users/2019940'}],)]diff --git a/tests/dags/providers/provider_api_scripts/resources/inaturalist/pull_sample_records.py b/tests/dags/providers/provider_api_scripts/resources/inaturalist/pull_sample_records.pynew file mode 100644index 000000000..afa56adae--- /dev/null+++ b/tests/dags/providers/provider_api_scripts/resources/inaturalist/pull_sample_records.py@@ -0,0 +1,196 @@+"""+Some hacky code to pull sample data from large TSV files from inaturalist.++First download the full datasets from aws s3://inaturalist-open-data/, and adjust+RAW_DATA to fit where you saved them.+Assumes that large files are saved outside of the Openverse repo to take pressure off+git and linting.+"""+++import csv+import gzip+import os+from datetime import datetime as dt+from pathlib import Path++import pandas as pd+++# Because this is unlikely to be reused, I didn't want to change the git ignore+BASE_DIR = Path(__file__).parents[7]+DATA_FOR_TESTING = BASE_DIR / "openverse-catalog/tests/s3-data/inaturalist-open-data"+RAW_DATA = BASE_DIR / "inaturalist-june-22"+MID_SIZE_FILE_PATH = BASE_DIR / "inaturalist-june-22/mid-sized"+SMALL_FILE_PATH = BASE_DIR / "inaturalist-june-22/small"+++# This is just something I used in ipython to move things around+def move_files(from_dir, to_dir, copy=False):+ for file_name in os.listdir(from_dir):+ if file_name[-7:] == ".csv.gz":+ if copy:+ print(f"Copying {file_name} from {from_dir} to {to_dir}...")+ os.system(f"cp {from_dir}/{file_name} {to_dir}/{file_name}")+ else:+ print(f"Moving {file_name} from {from_dir} to {to_dir}...")+ os.rename(f"{from_dir}/{file_name}", f"{to_dir}/{file_name}")+++def pull_sample_records(+ file_name,+ id_name,+ id_list,+ is_unique=True,+ every_nth_record=None,+ output_path=MID_SIZE_FILE_PATH,+ input_path=RAW_DATA,+):+ """+ Reads through a full gzip file and keeps just the selected ID records++ This is not wildly efficient for large ID lists and large files.+ """+ # can we read the stuff? (should assert that id_name is a valid field name, but...)+ assert len(id_list) > 0+ assert len(id_list) < 10000+ working_input_file = input_path / file_name+ assert os.path.exists(working_input_file)+ output_file_name = output_path / file_name+ # read in the selected records+ sample_records = []+ remaining_ids = id_list.copy()+ print(+ "Starting to read",+ working_input_file,+ "at",+ dt.now().strftime("%d/%m/%Y %H:%M:%S"),+ )+ with gzip.open(working_input_file, "rt") as in_file:+ records = csv.DictReader(in_file, delimiter="\t")+ lines_read = 0+ keep_random = False+ for record in records:+ if every_nth_record:+ keep_random = lines_read % every_nth_record == 0+ if (record[id_name] in remaining_ids) or keep_random:+ sample_records += [record]+ if is_unique:+ remaining_ids.remove(record[id_name])+ lines_read += 1+ if lines_read % 10**7 == 0:+ print(+ "Read line number",+ lines_read,+ "at",+ dt.now().strftime("%d/%m/%Y %H:%M:%S"),+ )+ # write them to the sample output file+ sample_df = pd.DataFrame(sample_records)+ with gzip.open(output_file_name, "wt") as out_file:+ sample_df.to_csv(out_file, sep="\t", header=True, index=False)+ print(len(sample_df), "sample records saved in", output_file_name)+ return output_file_name+++def get_sample_id_list(sample_file, joined_on):+ """+ sample_file: from a table that you have already drawn sample records+ a file object so that you can handle if it's compressed or not, set+ up to read text+ joined_on: the string name of the field they have in common+ """+ records = csv.DictReader(sample_file, delimiter="\t")+ sample_values = set()+ for record in records:+ sample_values.add(record[joined_on])+ return list(sample_values)+++if __name__ == "__main__":++ # PHOTOS+ photo_ids = [+ str(i)+ for i in [+ 20314159,+ 10314159,+ 30314159,+ 40314159,+ 60314159,+ 80314159,+ 90314159,+ 110314159,+ 120314159,+ 130314159,+ 150314159,+ 160314159,+ 170314159,+ 191019692,+ 191018903,+ 191018870,+ 191016506,+ 191015547,+ 191015484,+ 191012628,+ 191001500,+ 190995656,+ 190995604,+ 191028942,+ 191028931,+ 191024617,+ 200352737,+ ]+ ]+ pull_sample_records(+ file_name="photos.csv.gz",+ id_name="photo_id",+ id_list=photo_ids,+ is_unique=False,+ every_nth_record=None,+ output_path=DATA_FOR_TESTING,+ )++ # ASSOCIATED OBSERVATIONS+ with gzip.open(f"{DATA_FOR_TESTING}/photos.csv.gz", "rt") as photo_output:+ sample_observations = get_sample_id_list(photo_output, "observation_uuid")+ pull_sample_records(+ "observations.csv.gz",+ "observation_uuid",+ sample_observations,+ False,+ None,+ DATA_FOR_TESTING,+ )++ # ASSOCIATED OBSERVERS+ with gzip.open(f"{DATA_FOR_TESTING}/photos.csv.gz", "rt") as photo_output:+ sample_observers = get_sample_id_list(photo_output, "observer_id")+ pull_sample_records(+ "observers.csv.gz",+ "observer_id",+ sample_observers,+ False,+ None,+ DATA_FOR_TESTING,+ )++ # ASSOCIATED TAXA (including ancestry for photo tags)+ with gzip.open(+ f"{DATA_FOR_TESTING}/observations.csv.gz", "rt"+ ) as observation_output:+ sample_taxa = get_sample_id_list(observation_output, "taxon_id")+ sample_taxa_with_ancestors = set(sample_taxa)+ with gzip.open(f"{RAW_DATA}/taxa.csv.gz", "rt") as all_taxa:+ records = csv.DictReader(all_taxa, delimiter="\t")+ for t in records:+ if t["taxon_id"] in sample_taxa:+ sample_taxa_with_ancestors.update(t["ancestry"].split("/"))+ pull_sample_records(+ "taxa.csv.gz",+ "taxon_id",+ list(sample_taxa_with_ancestors),+ False,+ None,+ DATA_FOR_TESTING,+ )diff --git a/tests/dags/providers/provider_api_scripts/test_inaturalist.py b/tests/dags/providers/provider_api_scripts/test_inaturalist.pynew file mode 100644index 000000000..f6bc39887--- /dev/null+++ b/tests/dags/providers/provider_api_scripts/test_inaturalist.py@@ -0,0 +1,130 @@+from ast import literal_eval+from pathlib import Path++import pytest+from airflow.providers.postgres.hooks.postgres import PostgresHook+from common.constants import POSTGRES_CONN_ID+from common.licenses import get_license_info+from providers.provider_api_scripts import inaturalist+++# Sample data included in the tests below covers the following weird cases:+# - 3 of the photo records link to unclassified observations, so they have no title or+# tags and we don't load them.+# - 10 of the remaining photo ids appear on multiple records, load one per photo_id.+# - One of the photos has a taxon without any ancestors in the source table.+# To really get at data quality issues, it's worth loading bigger sample files to minio+# and running the dag in airflow locally.+++INAT = inaturalist.INaturalistDataIngester()+PG = PostgresHook(POSTGRES_CONN_ID)+SQL_SCRIPT_DIR = (+ Path(__file__).parents[4]+ / "openverse_catalog/dags/providers/provider_csv_load_scripts/inaturalist"+)+RESOURCE_DIR = Path(__file__).parent / "resources/inaturalist"+# postgres always returns a list of tuples, which is not a valid json format+FULL_DB_RESPONSE = literal_eval((RESOURCE_DIR / "full_db_response.txt").read_text())+# in this case, it's a list containing a single tuple with a single value that is a+# valid json array of records for processing as if they came from a regular API.+JSON_RESPONSE = FULL_DB_RESPONSE[0][0]+RECORD0 = JSON_RESPONSE[0]+++# Based on the small sample files in /tests/s3-data/inaturalist-open-data and on+# minio in the test environment+# Just checking raw record counts, assume that the contents load correctly as only+# taxa has any logic outside literally loading the table using postgres existing+# copy command.+ "file_name, expected",+ [+ ("create_schema.sql", [("inaturalist",)]),+ ("photos.sql", [(37,)]),+ ("observations.sql", [(32,)]),+ ("taxa.sql", [(183,)]),+ ("observers.sql", [(23,)]),+ ],+)+def test_load_data(file_name, expected):+ sql_string = (SQL_SCRIPT_DIR / file_name).read_text()+ actual = PG.get_records(sql_string)+ assert actual == expected+++def test_get_next_query_params_no_prior():+ expected = {"offset_num": 0}+ actual = INAT.get_next_query_params()+ assert expected == actual+++def test_get_next_query_params_prior_0():+ expected = {"offset_num": INAT.batch_limit}+ actual = INAT.get_next_query_params({"offset_num": 0})+ assert expected == actual++[email protected]("value", [None, {}])+def test_get_batch_data_returns_none(value):+ actual = INAT.get_batch_data(value)+ assert actual is None+++def test_get_response_json():+ expected = JSON_RESPONSE+ actual = INAT.get_response_json({"offset_num": 0})+ assert actual == expected+++def test_get_batch_data_full_response():+ actual = INAT.get_batch_data(JSON_RESPONSE)+ assert isinstance(actual, list)+ assert len(actual) == 34+ assert isinstance(actual[0], dict)+ assert actual[0] == RECORD0++[email protected]("field", ["license_url", "foreign_identifier"])+def test_get_record_data_missing_necessarly_fields(field):+ expected = None+ record = RECORD0.copy()+ record.pop(field)+ actual = INAT.get_record_data(record)+ assert actual == expected+++def test_get_record_data_full_response():+ expected = {+ "foreign_identifier": 10314159,+ "filetype": "jpg",+ "license_info": get_license_info(+ license_url="http://creativecommons.org/licenses/by-nc/4.0/"+ ),+ "width": 1530,+ "height": 2048,+ "foreign_landing_url": "https://www.inaturalist.org/photos/10314159",+ "image_url": "https://inaturalist-open-data.s3.amazonaws.com/photos/10314159/medium.jpg",+ "creator": "akjenny",+ "creator_url": "https://www.inaturalist.org/users/615549",+ "title": "Trifolium hybridum",+ "raw_tags": [+ "Fabaceae",+ "Fabales",+ "Magnoliopsida",+ "Angiospermae",+ "Plantae",+ "Trifolium",+ "Tracheophyta",+ "Faboideae",+ "Trifolieae",+ ],+ }+ actual = INAT.get_record_data(RECORD0)+ assert actual == expected+++def test_get_media_type():+ expected = "image"+ actual = INAT.get_media_type(INAT.get_record_data(RECORD0))+ assert actual == expecteddiff --git a/tests/s3-data/inaturalist-open-data/observations.csv.gz b/tests/s3-data/inaturalist-open-data/observations.csv.gznew file mode 100644index 000000000..a2be65fd0Binary files /dev/null and b/tests/s3-data/inaturalist-open-data/observations.csv.gz differdiff --git a/tests/s3-data/inaturalist-open-data/observers.csv.gz b/tests/s3-data/inaturalist-open-data/observers.csv.gznew file mode 100644index 000000000..afa1071c3Binary files /dev/null and b/tests/s3-data/inaturalist-open-data/observers.csv.gz differdiff --git a/tests/s3-data/inaturalist-open-data/photos.csv.gz b/tests/s3-data/inaturalist-open-data/photos.csv.gznew file mode 100644index 000000000..b4d34cc6dBinary files /dev/null and b/tests/s3-data/inaturalist-open-data/photos.csv.gz differdiff --git a/tests/s3-data/inaturalist-open-data/taxa.csv.gz b/tests/s3-data/inaturalist-open-data/taxa.csv.gznew file mode 100644index 000000000..6e071cdc6Binary files /dev/null and b/tests/s3-data/inaturalist-open-data/taxa.csv.gz differ