Skip to content

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

Fix lint failures from the ruff, codespell and actionlint upgrades (#5782)

Olga Bulat4c844e0e3fa6
diff --git a/.github/workflows/ci_cd.yml b/.github/workflows/ci_cd.yml
index a14d839f1..91a3b8b26 100644
--- a/.github/workflows/ci_cd.yml
+++ b/.github/workflows/ci_cd.yml
@@ -179,8 +179,6 @@ jobs:
- name: Setup Docker Buildx
uses: docker/setup-buildx-action@v4
- with:
- install: true
- name: Build image `${{ matrix.image }}`
uses: docker/build-push-action@v7
@@ -267,8 +265,6 @@ jobs:
- name: Setup Docker Buildx
uses: docker/setup-buildx-action@v4
- with:
- install: true
- name: Build catalog dev image
uses: docker/build-push-action@v7
@@ -366,8 +362,6 @@ jobs:
- name: Setup Docker Buildx
uses: docker/setup-buildx-action@v4
- with:
- install: true
- name: Build indexer worker dev image
uses: docker/build-push-action@v7
@@ -481,8 +475,6 @@ jobs:
- name: Setup Docker Buildx
uses: docker/setup-buildx-action@v4
- with:
- install: true
- name: Build API dev image
uses: docker/build-push-action@v7
diff --git a/.github/workflows/draft_releases.yml b/.github/workflows/draft_releases.yml
index d64eff2ea..7d0cfef11 100644
--- a/.github/workflows/draft_releases.yml
+++ b/.github/workflows/draft_releases.yml
@@ -52,7 +52,6 @@ jobs:
version: ${{ steps.tag.outputs.date }}
tag: ${{ steps.tag.outputs.git-tag }}
name: ${{ steps.tag.outputs.git-tag }}
- draft: true
commitish: main
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 56747b47a..9d1647985 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -43,9 +43,9 @@ repos:
- id: requirements-txt-fixer
- repo: https://github.com/astral-sh/ruff-pre-commit
- rev: v0.9.9
+ rev: v0.17.5
hooks:
- - id: ruff # replaces Flake8, isort, pydocstyle, pyupgrade
+ - id: ruff-check # replaces Flake8, isort, pydocstyle, pyupgrade
args:
- --fix
- id: ruff-format # replaces Black
@@ -61,12 +61,12 @@ repos:
- id: shfmt-docker
- repo: https://github.com/rhysd/actionlint
- rev: v1.7.7
+ rev: v1.7.12
hooks:
- id: actionlint-docker
- repo: https://github.com/codespell-project/codespell
- rev: v2.4.1
+ rev: v2.4.3
hooks:
- id: codespell
args: [
diff --git a/api/api/models/oauth.py b/api/api/models/oauth.py
index 721a1d4cd..ab9d869d1 100644
--- a/api/api/models/oauth.py
+++ b/api/api/models/oauth.py
@@ -35,7 +35,7 @@ class ThrottledApplication(AbstractApplication):
("enhanced", "enhanced"), # Rate limits for "super" keys, granted on a
# case-by-case basis.
("exempt", "exempt"), # Rate limits used for internal infrastructure to
- # by-pass rate limiting entirely.
+ # bypass rate limiting entirely.
("frontend", "frontend"), # High but finite rate limits for the
# openverse.org frontend, which proxies requests for all its users.
]
diff --git a/api/api/utils/aiohttp.py b/api/api/utils/aiohttp.py
index 43624b01a..d008b22bc 100644
--- a/api/api/utils/aiohttp.py
+++ b/api/api/utils/aiohttp.py
@@ -129,7 +129,7 @@ class LogTiming(aiohttp.TraceConfig):
status = params.response.status
elif isinstance(params.exception, aiohttp.ClientResponseError):
status = params.exception.status
- elif isinstance(params.exception, asyncio.TimeoutError):
+ elif isinstance(params.exception, TimeoutError):
status = self.TIMEOUT_STATUS
else:
status = self.ERROR_STATUS
diff --git a/api/api/utils/check_dead_links/__init__.py b/api/api/utils/check_dead_links/__init__.py
index ab66ea0cd..40d0a26a8 100644
--- a/api/api/utils/check_dead_links/__init__.py
+++ b/api/api/utils/check_dead_links/__init__.py
@@ -88,15 +88,15 @@ async def _head(
) as response:
status = response.status
- except (aiohttp.ClientError, asyncio.TimeoutError) as exception:
+ except (TimeoutError, aiohttp.ClientError) as exception:
# only log non-timeout exceptions. Timeouts are more or less expected
# and we have means of visibility into them (e.g., querying for timings
# that exceed the timeout); they do _not_ need to be in the error log or go to Sentry
- # The timeout exception class aiohttp uses is a subclass of `ClientError` and `asyncio.TimeoutError`,
- # so we have to explicitly check that the error is _not_ an asyncio timeout error, not that it
- # _is_ an aiohttp error. When it is a timeout error, it will be both `asyncio.TimeoutError` and
+ # The timeout exception class aiohttp uses is a subclass of `ClientError` and `TimeoutError`,
+ # so we have to explicitly check that the error is _not_ a timeout error, not that it
+ # _is_ an aiohttp error. When it is a timeout error, it will be both `TimeoutError` and
# `aiohttp.ClientError` because it's a subclass of both
- if not isinstance(exception, asyncio.TimeoutError):
+ if not isinstance(exception, TimeoutError):
if isinstance(exception, _NON_ACTIONABLE_NETWORK_EXCEPTIONS):
log = logger.warning
else:
diff --git a/api/api/utils/image_proxy/extension.py b/api/api/utils/image_proxy/extension.py
index 10dd70f6a..bb45e0b2e 100644
--- a/api/api/utils/image_proxy/extension.py
+++ b/api/api/utils/image_proxy/extension.py
@@ -1,4 +1,3 @@
-import asyncio
import mimetypes
from os.path import splitext
from urllib.parse import urlparse
@@ -37,7 +36,7 @@ _NON_ACTIONABLE_NETWORK_EXCEPTIONS = (
aiohttp.ServerDisconnectedError,
aiohttp.ServerTimeoutError,
aiohttp.ClientOSError,
- asyncio.TimeoutError,
+ TimeoutError,
)
@@ -85,7 +84,7 @@ async def get_image_extension(media_info: MediaInfo) -> str | None:
# timeouts with per-provider granularity, but for now, we just have to
# accept they will happen and are part of the set of non-actionable
# networking errors that we don't need to report as errors to Sentry.
- if not isinstance(exc, asyncio.TimeoutError):
+ if not isinstance(exc, TimeoutError):
if isinstance(exc, _NON_ACTIONABLE_NETWORK_EXCEPTIONS):
log = logger.warning
else:
diff --git a/api/api/views/media_views.py b/api/api/views/media_views.py
index 675334a4e..54349a26c 100644
--- a/api/api/views/media_views.py
+++ b/api/api/views/media_views.py
@@ -1,5 +1,3 @@
-from typing import Union
-
from django.conf import settings
from rest_framework import status
from rest_framework.decorators import action
@@ -31,10 +29,10 @@ from api.utils.throttle import (
logger = structlog.get_logger(__name__)
-MediaListRequestSerializer = Union[
- media_serializers.PaginatedRequestSerializer,
- media_serializers.MediaSearchRequestSerializer,
-]
+MediaListRequestSerializer = (
+ media_serializers.PaginatedRequestSerializer
+ | media_serializers.MediaSearchRequestSerializer
+)
class InvalidSource(APIException):
diff --git a/api/conf/settings/rest_framework.py b/api/conf/settings/rest_framework.py
index f6a401c4b..e1f826774 100644
--- a/api/conf/settings/rest_framework.py
+++ b/api/conf/settings/rest_framework.py
@@ -44,7 +44,7 @@ DEFAULT_THROTTLE_RATES = {
"enhanced_oauth2_client_credentials_burst": "200/min",
"frontend_oauth2_client_credentials_sustained": THROTTLE_FRONTEND_SUSTAINED,
"frontend_oauth2_client_credentials_burst": THROTTLE_FRONTEND_BURST,
- # ``None`` completely by-passes the rate limiting
+ # ``None`` completely bypasses the rate limiting
"exempt_oauth2_client_credentials": None,
}
diff --git a/api/test/unit/controllers/test_search_controller.py b/api/test/unit/controllers/test_search_controller.py
index 5b63d977d..54f2569a5 100644
--- a/api/test/unit/controllers/test_search_controller.py
+++ b/api/test/unit/controllers/test_search_controller.py
@@ -1,7 +1,7 @@
import random
import re
from collections.abc import Callable
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from enum import Enum, auto
from unittest import mock
from unittest.mock import patch
@@ -859,7 +859,7 @@ def test_get_excluded_sources_query_returns_excluded(
else:
for i in range(excluded_count):
ContentSourceFactory.create(
- created_on=datetime.now(tz=timezone.utc),
+ created_on=datetime.now(tz=UTC),
source_identifier=f"source{i + 1}",
source_name=f"Source {i + 1}",
filter_content=True,
diff --git a/api/test/unit/utils/test_aiohttp.py b/api/test/unit/utils/test_aiohttp.py
index 071fe34d7..eeacb58e3 100644
--- a/api/test/unit/utils/test_aiohttp.py
+++ b/api/test/unit/utils/test_aiohttp.py
@@ -1,4 +1,3 @@
-import asyncio
from http.cookies import SimpleCookie
import aiohttp
@@ -205,7 +204,7 @@ def test_log_timing_trace_config_timeout(session_loop):
event_name = "empty_request_ctx_timing_event_test"
with capture_logs() as logs:
- with pytest.raises(asyncio.TimeoutError):
+ with pytest.raises(TimeoutError):
session_loop.run_until_complete(
aiohttp_session.get(
"http://httpbin:8080/delay/4",
diff --git a/api/test/unit/utils/test_image_proxy.py b/api/test/unit/utils/test_image_proxy.py
index e1d10932d..04c26a040 100644
--- a/api/test/unit/utils/test_image_proxy.py
+++ b/api/test/unit/utils/test_image_proxy.py
@@ -1,4 +1,3 @@
-import asyncio
import contextlib
from dataclasses import replace
from urllib.parse import urlencode
@@ -337,7 +336,7 @@ MOCK_CONNECTION_KEY = ConnectionKey(
"aiohttp.client_exceptions.ClientConnectionError",
),
(
- asyncio.TimeoutError("whoops"),
+ TimeoutError("whoops"),
"builtins.TimeoutError",
),
(
diff --git a/api/test/unit/views/test_media_views.py b/api/test/unit/views/test_media_views.py
index f9219d94d..b3e528e34 100644
--- a/api/test/unit/views/test_media_views.py
+++ b/api/test/unit/views/test_media_views.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from unittest.mock import MagicMock, patch
from uuid import uuid4
@@ -60,7 +60,7 @@ def test_get_queryset_source_filtering(api_client, media_type_config, filter_con
media = media_type_config.model_factory.create(source=test_source)
ContentSource.objects.create(
- created_on=datetime.now(tz=timezone.utc),
+ created_on=datetime.now(tz=UTC),
source_identifier=test_source,
source_name="Test Source",
domain_name="https://example.com",
diff --git a/catalog/dags/common/elasticsearch.py b/catalog/dags/common/elasticsearch.py
index 814797c29..b9c326ac1 100644
--- a/catalog/dags/common/elasticsearch.py
+++ b/catalog/dags/common/elasticsearch.py
@@ -1,6 +1,6 @@
import logging
from datetime import timedelta
-from typing import Literal, Union
+from typing import Literal
from airflow.decorators import task, task_group
from airflow.exceptions import AirflowSkipException
@@ -142,7 +142,7 @@ def trigger_and_wait_for_reindex(
query: dict | None = None,
max_docs: int | None = None,
refresh: bool = True,
- slices: Union[int, Literal["auto"]] = "auto",
+ slices: int | Literal["auto"] = "auto",
poke_interval: int = REFRESH_POKE_INTERVAL,
):
@task
@@ -153,7 +153,7 @@ def trigger_and_wait_for_reindex(
query: dict,
requests_per_second: int,
max_docs: int | None,
- slices: Union[int, Literal["auto"]],
+ slices: int | Literal["auto"],
):
es_conn = ElasticsearchPythonHook(hosts=[es_host]).get_conn
source = {"index": source_index}
diff --git a/catalog/dags/common/slack.py b/catalog/dags/common/slack.py
index 90243b0d7..7cf571187 100644
--- a/catalog/dags/common/slack.py
+++ b/catalog/dags/common/slack.py
@@ -53,14 +53,14 @@ import logging
import re
from collections.abc import Callable
from os.path import basename
-from typing import Any
+from typing import Any, NotRequired
from airflow.decorators import task
from airflow.exceptions import AirflowNotFoundException
from airflow.models import DAG, Variable
from airflow.providers.http.hooks.http import HttpHook
from requests import Response
-from typing_extensions import NotRequired, TypedDict
+from typing_extensions import TypedDict
SLACK_NOTIFICATIONS_CONN_ID = "slack_notifications"
diff --git a/catalog/dags/data_refresh/data_refresh_types.py b/catalog/dags/data_refresh/data_refresh_types.py
index 27ce628c4..bf3e9c428 100644
--- a/catalog/dags/data_refresh/data_refresh_types.py
+++ b/catalog/dags/data_refresh/data_refresh_types.py
@@ -8,7 +8,6 @@ This configuration information is used to generate the dynamic Data Refresh dags
import os
from dataclasses import dataclass, field
from datetime import datetime, timedelta
-from typing import Optional
from airflow.models import Variable
@@ -100,7 +99,7 @@ class DataRefreshConfig:
filtered_index_dag_id: str = field(init=False)
media_type: str
table_mapping: TableMapping
- additional_table_mappings: Optional[list[TableMapping]] = None
+ additional_table_mappings: list[TableMapping] | None = None
start_date: datetime = datetime(2020, 1, 1)
schedule: str | None = "0 0 * * 1" # Mondays 00:00 UTC
default_args: dict = field(default_factory=dict)
diff --git a/catalog/dags/providers/provider_api_scripts/europeana.py b/catalog/dags/providers/provider_api_scripts/europeana.py
index 74115b30d..13131f217 100644
--- a/catalog/dags/providers/provider_api_scripts/europeana.py
+++ b/catalog/dags/providers/provider_api_scripts/europeana.py
@@ -12,7 +12,7 @@ Notes: <https://pro.europeana.eu/page/search>
import argparse
import functools
import logging
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
from airflow.models import Variable
@@ -243,7 +243,7 @@ class EuropeanaDataIngester(ProviderDataIngester):
def _get_timestamp_query_param(self, date):
date_obj = datetime.strptime(date, "%Y-%m-%d")
- utc_date = date_obj.replace(tzinfo=timezone.utc)
+ utc_date = date_obj.replace(tzinfo=UTC)
start_timestamp = utc_date.isoformat()
end_timestamp = (utc_date + timedelta(days=1)).isoformat()
diff --git a/catalog/dags/providers/provider_api_scripts/freesound.py b/catalog/dags/providers/provider_api_scripts/freesound.py
index 244a89ce5..2008602e0 100644
--- a/catalog/dags/providers/provider_api_scripts/freesound.py
+++ b/catalog/dags/providers/provider_api_scripts/freesound.py
@@ -71,8 +71,9 @@ class FreesoundDataIngester(ProviderDataIngester):
HTTPError,
max_time=60 * 2,
# Raise all other errors
- giveup=lambda e: e.response.status_code
- not in FreesoundDataIngester.flaky_error_codes,
+ giveup=lambda e: (
+ e.response.status_code not in FreesoundDataIngester.flaky_error_codes
+ ),
)(ProviderDataIngester.get_response_json)
def get_next_query_params(self, prev_query_params: dict | None) -> dict:
diff --git a/catalog/dags/providers/provider_api_scripts/time_delineated_provider_data_ingester.py b/catalog/dags/providers/provider_api_scripts/time_delineated_provider_data_ingester.py
index 1cf508e0e..8559eb7d4 100644
--- a/catalog/dags/providers/provider_api_scripts/time_delineated_provider_data_ingester.py
+++ b/catalog/dags/providers/provider_api_scripts/time_delineated_provider_data_ingester.py
@@ -1,6 +1,6 @@
import logging
from abc import abstractmethod
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
from providers.provider_api_scripts.provider_data_ingester import ProviderDataIngester
@@ -135,7 +135,7 @@ class TimeDelineatedProviderDataIngester(ProviderDataIngester):
"""
pairs_list: list[tuple[datetime, datetime]] = []
# Get UTC timestamps for the start and end of the ingestion date
- start_ts = datetime.strptime(self.date, "%Y-%m-%d").replace(tzinfo=timezone.utc)
+ start_ts = datetime.strptime(self.date, "%Y-%m-%d").replace(tzinfo=UTC)
end_ts = start_ts + timedelta(days=1)
record_count = self._get_record_count(start_ts, end_ts, **kwargs)
diff --git a/catalog/dags/providers/provider_api_scripts/wikimedia_commons.py b/catalog/dags/providers/provider_api_scripts/wikimedia_commons.py
index d398d271b..a545566bf 100644
--- a/catalog/dags/providers/provider_api_scripts/wikimedia_commons.py
+++ b/catalog/dags/providers/provider_api_scripts/wikimedia_commons.py
@@ -109,7 +109,7 @@ entirely and eschew the popularity data for these items.
import argparse
import logging
from copy import deepcopy
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
from types import MappingProxyType
import lxml.html as html
@@ -646,7 +646,7 @@ class WikimediaCommonsDataIngester(ProviderDataIngester):
@staticmethod
def derive_timestamp_pair(date):
date_obj = datetime.strptime(date, "%Y-%m-%d")
- utc_date = date_obj.replace(tzinfo=timezone.utc)
+ utc_date = date_obj.replace(tzinfo=UTC)
start_timestamp = str(int(utc_date.timestamp()))
end_timestamp = str(int((utc_date + timedelta(days=1)).timestamp()))
logger.info(
diff --git a/catalog/dags/providers/provider_workflows.py b/catalog/dags/providers/provider_workflows.py
index 0c1f54858..98e2d8852 100644
--- a/catalog/dags/providers/provider_workflows.py
+++ b/catalog/dags/providers/provider_workflows.py
@@ -4,9 +4,10 @@ import re
from collections.abc import Callable, Sequence
from dataclasses import dataclass, field
from datetime import datetime, timedelta
+from typing import NotRequired
from airflow.models import Variable
-from typing_extensions import NotRequired, TypedDict
+from typing_extensions import TypedDict
from providers.provider_api_scripts.auckland_museum import AucklandMuseumDataIngester
from providers.provider_api_scripts.brooklyn_museum import BrooklynMuseumDataIngester
diff --git a/catalog/docs/provider_data_ingester_faq.md b/catalog/docs/provider_data_ingester_faq.md
index 64a9ea541..41e959140 100644
--- a/catalog/docs/provider_data_ingester_faq.md
+++ b/catalog/docs/provider_data_ingester_faq.md
@@ -57,7 +57,7 @@ def get_record_data(self, data: dict) -> dict | list[dict] | None:
# Get data from the details endpoint
response_json = self.get_response_json(
query_params={"my_params": "foo"},
- endpoint=f"https://foobar.museum.org/api/v1/images/{data.get("uuid")}"
+ endpoint=f"https://foobar.museum.org/api/v1/images/{data.get('uuid')}",
)
...
@@ -96,6 +96,7 @@ def __init__(self, *args, **kwargs):
# Set up our instance variable
self.page_number = None
+
def get_next_query_params(self, prev_query_params: dict | None, **kwargs) -> dict:
# Remember that `get_next_query_params` is called before every request, even
# the first one.
@@ -157,9 +158,7 @@ complex behavior.
```python
# Pseudo code serves as an example
-def get_response_json(
- self, query_params: dict, endpoint: str | None = None, **kwargs
-):
+def get_response_json(self, query_params: dict, endpoint: str | None = None, **kwargs):
batch_json = None
while True:
diff --git a/catalog/tests/dags/providers/provider_api_scripts/test_finnish_museums.py b/catalog/tests/dags/providers/provider_api_scripts/test_finnish_museums.py
index b4d7c097f..2430ae79e 100644
--- a/catalog/tests/dags/providers/provider_api_scripts/test_finnish_museums.py
+++ b/catalog/tests/dags/providers/provider_api_scripts/test_finnish_museums.py
@@ -1,5 +1,5 @@
import logging
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
from unittest.mock import patch
import pytest
@@ -18,9 +18,7 @@ logging.basicConfig(
)
FROZEN_DATE = "2020-04-01"
-FROZEN_UTC_DATE = datetime.strptime(FROZEN_DATE, "%Y-%m-%d").replace(
- tzinfo=timezone.utc
-)
+FROZEN_UTC_DATE = datetime.strptime(FROZEN_DATE, "%Y-%m-%d").replace(tzinfo=UTC)
fm = FinnishMuseumsDataIngester(date=FROZEN_DATE)
image_store = ImageStore(provider=prov.FINNISH_DEFAULT_PROVIDER)
fm.media_stores = {"image": image_store}
diff --git a/catalog/tests/dags/providers/provider_api_scripts/test_rawpixel.py b/catalog/tests/dags/providers/provider_api_scripts/test_rawpixel.py
index 4657ccb1b..6e08dc214 100644
--- a/catalog/tests/dags/providers/provider_api_scripts/test_rawpixel.py
+++ b/catalog/tests/dags/providers/provider_api_scripts/test_rawpixel.py
@@ -291,7 +291,7 @@ def test_get_record_data():
"foreign_identifier": 4032668,
"foreign_landing_url": "https://www.rawpixel.com/image/4032668/photo-image-background-nature-mountain", # noqa
"height": 5515,
- "url": "https://images.rawpixel.com/editor_1024/cHJpdmF0ZS9sci9pbWFnZXMvd2Vic2l0ZS8yMDIyLTA1L2ZsNDY0NDU5OTQ2MjQtaW1hZ2Uta3UyY21zcjUuanBn.jpg", # noqa,
+ "url": "https://images.rawpixel.com/editor_1024/cHJpdmF0ZS9sci9pbWFnZXMvd2Vic2l0ZS8yMDIyLTA1L2ZsNDY0NDU5OTQ2MjQtaW1hZ2Uta3UyY21zcjUuanBn.jpg", # noqa
"thumbnail_url": "https://images.rawpixel.com/image_600/cHJpdmF0ZS9sci9pbWFnZXMvd2Vic2l0ZS8yMDIyLTA1L2ZsNDY0NDU5OTQ2MjQtaW1hZ2Uta3UyY21zcjUuanBn.jpg", # noqa
"license_info": LicenseInfo(
license="cc0",
diff --git a/catalog/tests/dags/providers/provider_api_scripts/test_time_delineated_provider_data_ingester.py b/catalog/tests/dags/providers/provider_api_scripts/test_time_delineated_provider_data_ingester.py
index 7e441c2b2..22fd2ba2d 100644
--- a/catalog/tests/dags/providers/provider_api_scripts/test_time_delineated_provider_data_ingester.py
+++ b/catalog/tests/dags/providers/provider_api_scripts/test_time_delineated_provider_data_ingester.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
from itertools import repeat
from unittest.mock import MagicMock, call, patch
@@ -77,8 +77,8 @@ def test_get_timestamp_pairs_returns_full_day_when_few_records_found():
# timestamp pair representing the whole day
expected_pairs_list = [
(
- datetime(2020, 4, 1, 0, 0, tzinfo=timezone.utc),
- datetime(2020, 4, 2, 0, 0, tzinfo=timezone.utc),
+ datetime(2020, 4, 1, 0, 0, tzinfo=UTC),
+ datetime(2020, 4, 2, 0, 0, tzinfo=UTC),
)
]
@@ -159,7 +159,7 @@ def test_ingest_records_calls_super_for_each_ts_pair():
patch.object(ingester, "_get_timestamp_pairs") as ts_mock,
):
# Make some mock timestamp pairs
- start = datetime(2020, 4, 1, 11, 0, tzinfo=timezone.utc)
+ start = datetime(2020, 4, 1, 11, 0, tzinfo=UTC)
ts_0 = (start, start + timedelta(hours=1))
ts_1 = (start + timedelta(hours=1), start + timedelta(hours=2))
ts_2 = (start + timedelta(hours=2), start + timedelta(hours=3))
@@ -192,8 +192,8 @@ def test_ingest_records_raises_error_if_the_total_count_has_been_exceeded():
):
ts_mock.return_value = [
(
- datetime(2020, 4, 1, 11, 0, tzinfo=timezone.utc),
- datetime(2020, 4, 1, 12, 0, tzinfo=timezone.utc),
+ datetime(2020, 4, 1, 11, 0, tzinfo=UTC),
+ datetime(2020, 4, 1, 12, 0, tzinfo=UTC),
),
]
@@ -240,8 +240,8 @@ def test_ingest_records_does_not_raise_when_should_raise_error_is_false():
):
ts_mock.return_value = [
(
- datetime(2020, 4, 1, 11, 0, tzinfo=timezone.utc),
- datetime(2020, 4, 1, 12, 0, tzinfo=timezone.utc),
+ datetime(2020, 4, 1, 11, 0, tzinfo=UTC),
+ datetime(2020, 4, 1, 12, 0, tzinfo=UTC),
),
]
diff --git a/catalog/tests/utilities/dag_doc_gen/test_dag_doc_generation.py b/catalog/tests/utilities/dag_doc_gen/test_dag_doc_generation.py
index 0e2144068..177f10827 100644
--- a/catalog/tests/utilities/dag_doc_gen/test_dag_doc_generation.py
+++ b/catalog/tests/utilities/dag_doc_gen/test_dag_doc_generation.py
@@ -5,11 +5,11 @@ import pytest
from tests.dags.providers.provider_api_scripts.resources.provider_data_ingester.mock_provider_data_ingester import (
MockProviderDataIngester,
)
-
-from providers.provider_workflows import ProviderWorkflow
from utilities.dag_doc_gen import dag_doc_generation
from utilities.dag_doc_gen.dag_doc_generation import DagInfo
+from providers.provider_workflows import ProviderWorkflow
+
class DagMock(NamedTuple):
# schedule_interval used here because the Dag model does not actually have a
diff --git a/catalog/tests/utilities/media_props_gen/test_column_parser.py b/catalog/tests/utilities/media_props_gen/test_column_parser.py
index a53eb4726..1ad9afb63 100644
--- a/catalog/tests/utilities/media_props_gen/test_column_parser.py
+++ b/catalog/tests/utilities/media_props_gen/test_column_parser.py
@@ -1,5 +1,4 @@
import pytest
-
from utilities.media_props_gen.helpers.column_parser import (
COLUMN_DEFINITIONS,
Column,
diff --git a/catalog/tests/utilities/media_props_gen/test_db.py b/catalog/tests/utilities/media_props_gen/test_db.py
index fbf29a329..f77fe3415 100644
--- a/catalog/tests/utilities/media_props_gen/test_db.py
+++ b/catalog/tests/utilities/media_props_gen/test_db.py
@@ -1,5 +1,4 @@
import pytest
-
from utilities.media_props_gen.helpers.db import (
FieldSqlInfo,
get_table_description_matches,
diff --git a/catalog/tests/utilities/media_props_gen/test_generate_media_properties.py b/catalog/tests/utilities/media_props_gen/test_generate_media_properties.py
index f99961758..27d1d4c37 100644
--- a/catalog/tests/utilities/media_props_gen/test_generate_media_properties.py
+++ b/catalog/tests/utilities/media_props_gen/test_generate_media_properties.py
@@ -1,7 +1,6 @@
from unittest.mock import patch
import pytest
-
from utilities.media_props_gen.generate_media_properties import (
generate_db_props_string,
generate_markdown_doc,
diff --git a/catalog/tests/utilities/media_props_gen/test_md.py b/catalog/tests/utilities/media_props_gen/test_md.py
index c9b3c4643..3e09d40f3 100644
--- a/catalog/tests/utilities/media_props_gen/test_md.py
+++ b/catalog/tests/utilities/media_props_gen/test_md.py
@@ -1,5 +1,4 @@
import pytest
-
from utilities.media_props_gen.helpers.md import Md
diff --git a/documentation/_ext/link_issues.py b/documentation/_ext/link_issues.py
index 4c1f45dc6..35ca91f14 100644
--- a/documentation/_ext/link_issues.py
+++ b/documentation/_ext/link_issues.py
@@ -172,7 +172,7 @@ def is_issuetracker_env(
def lookup_issue(
app: Sphinx, tracker_config: TrackerConfig, issue_id: str
-) -> t.Optional[Issue]:
+) -> Issue | None:
"""
Lookup the given issue.
The issue is first looked up in an internal cache. If it is not found, the
@@ -230,7 +230,7 @@ def make_issue_reference(issue: Issue, content_node: nodes.inline) -> nodes.refe
def resolve_issue_reference(
app: Sphinx, env: BuildEnvironment, node: PendingIssueXRef, contnode: nodes.inline
-) -> t.Optional[nodes.reference]:
+) -> nodes.reference | None:
"""
Resolve an issue reference and turn it into a real reference to the
corresponding issue.
@@ -284,7 +284,7 @@ HEADERS = {
} | ({"Authorization": f"Bearer {GITHUB_TOKEN}"} if GITHUB_TOKEN else {})
-def get(app: Sphinx, url: str) -> t.Optional[requests.Response]:
+def get(app: Sphinx, url: str) -> requests.Response | None:
"""
Get a response from the given ``url``.
``url`` is a string containing the URL to request via GET. ``app`` is the
@@ -305,7 +305,7 @@ def get(app: Sphinx, url: str) -> t.Optional[requests.Response]:
def lookup_github_issue(
app: Sphinx, tracker_config: TrackerConfig, issue_id: str
-) -> t.Optional[Issue]:
+) -> Issue | None:
check_project_with_username(tracker_config)
env = app.env
diff --git a/documentation/general/logging.md b/documentation/general/logging.md
index 51353806e..67f5edfa5 100644
--- a/documentation/general/logging.md
+++ b/documentation/general/logging.md
@@ -11,6 +11,7 @@ We follow these guidelines when writing logs from the API.
```python
import structlog
+
logger = structlog.get_logger(__name__)
```
diff --git a/documentation/packages/python/openverse_attribution/index.md b/documentation/packages/python/openverse_attribution/index.md
index 61b4f7294..d0326842a 100644
--- a/documentation/packages/python/openverse_attribution/index.md
+++ b/documentation/packages/python/openverse_attribution/index.md
@@ -32,18 +32,18 @@ license.
from openverse_attribution.license import License
lic = License("by")
-lic.url() # 'https://creativecommons.org/licenses/by/4.0/'
-lic.name("2.0") # 'CC BY 2.0'
-lic.is_deprecated # False
-lic.is_pd # False
-lic.is_cc # True
+lic.url() # 'https://creativecommons.org/licenses/by/4.0/'
+lic.name("2.0") # 'CC BY 2.0'
+lic.is_deprecated # False
+lic.is_pd # False
+lic.is_cc # True
mark = License("pdm")
-mark.url() # 'https://creativecommons.org/publicdomain/mark/1.0/'
-mark.name("2.0") # 'Public Domain Mark 1.0'
+mark.url() # 'https://creativecommons.org/publicdomain/mark/1.0/'
+mark.name("2.0") # 'Public Domain Mark 1.0'
mark.is_deprecated # False
-mark.is_pd # True
-mark.is_cc # False
+mark.is_pd # True
+mark.is_cc # False
```
## Attribution
@@ -63,9 +63,9 @@ passing `False` to the `license_url` param.
from openverse_attribution.attribution import get_attribution_text
get_attribution_text(
- "cc0",
- title="Wheat Field with Cypresses",
- creator="Vincent van Gogh",
+ "cc0",
+ title="Wheat Field with Cypresses",
+ creator="Vincent van Gogh",
)
# '"Wheat Field with Cypresses" by Vincent van Gogh is marked with CC0 1.0.
# To view the terms, visit https://creativecommons.org/publicdomain/zero/1.0/.'
diff --git a/documentation/projects/proposals/document_all_media_properties/20230426-implementation_plan_documenting_media_properties.md b/documentation/projects/proposals/document_all_media_properties/20230426-implementation_plan_documenting_media_properties.md
index 6cc8e03b5..8046f649a 100644
--- a/documentation/projects/proposals/document_all_media_properties/20230426-implementation_plan_documenting_media_properties.md
+++ b/documentation/projects/proposals/document_all_media_properties/20230426-implementation_plan_documenting_media_properties.md
@@ -130,12 +130,12 @@ information into this dictionary in the API portion of this project.
```python
media_properties = {
- "title": {
- "sql_properties": {
- "type": "character varying",
- "sql_constraints": "(5000)",
- },
- }
+ "title": {
+ "sql_properties": {
+ "type": "character varying",
+ "sql_constraints": "(5000)",
+ },
+ }
}
```
diff --git a/documentation/projects/proposals/rekognition_data/20240530-implementation_plan_augment_catalog_with_rekognition_tags.md b/documentation/projects/proposals/rekognition_data/20240530-implementation_plan_augment_catalog_with_rekognition_tags.md
index 655f0eac7..d34633189 100644
--- a/documentation/projects/proposals/rekognition_data/20240530-implementation_plan_augment_catalog_with_rekognition_tags.md
+++ b/documentation/projects/proposals/rekognition_data/20240530-implementation_plan_augment_catalog_with_rekognition_tags.md
@@ -714,16 +714,16 @@ df = pd.read_json("/home/madison/misc/aws_rekognition_subset.txt", lines=True)
# Extract the labels from each row into mini-dataframes
recs = []
for _, row in df.iterrows():
- iid = row.image_uuid
- try:
- # Normalize the labels into a table, then get only the name and confidence values
- # Skip the record if it doesn't have labels
- tags = pd.json_normalize(row.response["Labels"])[["Name", "Confidence"]]
- except KeyError:
- continue
- # Add the image ID as an index
- tags["image_uuid"] = iid
- recs.append(tags)
+ iid = row.image_uuid
+ try:
+ # Normalize the labels into a table, then get only the name and confidence values
+ # Skip the record if it doesn't have labels
+ tags = pd.json_normalize(row.response["Labels"])[["Name", "Confidence"]]
+ except KeyError:
+ continue
+ # Add the image ID as an index
+ tags["image_uuid"] = iid
+ recs.append(tags)
# Concatenate all dataframes together
# This results in the columns: image_uuid, name, confidence
diff --git a/documentation/projects/proposals/trust_and_safety/content_report_moderation/20240122-implementation_plan_moderation_metrics.md b/documentation/projects/proposals/trust_and_safety/content_report_moderation/20240122-implementation_plan_moderation_metrics.md
index 4769f5d49..8b2672d82 100644
--- a/documentation/projects/proposals/trust_and_safety/content_report_moderation/20240122-implementation_plan_moderation_metrics.md
+++ b/documentation/projects/proposals/trust_and_safety/content_report_moderation/20240122-implementation_plan_moderation_metrics.md
@@ -285,12 +285,20 @@ reports_in_range = Report.objects.filter(created_at__gte=n_days_ago)
# accuracy of reports
# ===================
total_reports = reports_in_range.count()
-confirmed_reports = reports_in_range.filter(decision__action__in=['marked_sensitive', 'deindexed_sensitive', 'deindexed_copyright']).count()
+confirmed_reports = reports_in_range.filter(
+ decision__action__in=[
+ "marked_sensitive",
+ "deindexed_sensitive",
+ "deindexed_copyright",
+ ]
+).count()
report_accuracy = (confirmed_reports / total_reports) * 100 if total_reports else 0
# duplication in reports
# ======================
-duplicate_reports = reports_in_range.filter(decision__action='deduplicated_reports').count()
+duplicate_reports = reports_in_range.filter(
+ decision__action="deduplicated_reports"
+).count()
report_duplication = (duplicate_reports / total_reports) * 100 if total_reports else 0
```
@@ -310,15 +318,17 @@ reports_in_range = Report.objects.filter(created_at__gte=n_days_ago)
# time to decision
# ================
time_differences = reports_in_range.annotate(
- decision_time=Avg(F('decision__created_at') - F('created_at'))
-).values_list('decision_time', flat=True)
-average_decision_time = sum(time_differences, timedelta()) / len(time_differences) if time_differences else timedelta()
+ decision_time=Avg(F("decision__created_at") - F("created_at"))
+).values_list("decision_time", flat=True)
+average_decision_time = (
+ sum(time_differences, timedelta()) / len(time_differences)
+ if time_differences
+ else timedelta()
+)
p99_decision_time = reports_in_range.annotate(
- decision_time=F('decision__created_at') - F('created_at')
-).aggregate(
- percentile_99=Percentile('decision_time', 0.99)
-)['percentile_99']
+ decision_time=F("decision__created_at") - F("created_at")
+).aggregate(percentile_99=Percentile("decision_time", 0.99))["percentile_99"]
```
#### Lists
@@ -341,9 +351,21 @@ reports_in_range = Report.objects.filter(created_at__gte=n_days_ago)
# leaderboards
# ============
-most_reported_media = reports_in_range.values('media_id').annotate(report_count=Count('id')).order_by('-report_count')[:10]
-most_reported_creator = reports_in_range.values('media__creator').annotate(report_count=Count('id')).order_by('-report_count')[:10]
-most_reported_source = reports_in_range.values('media__source').annotate(report_count=Count('id')).order_by('-report_count')[:10]
+most_reported_media = (
+ reports_in_range.values("media_id")
+ .annotate(report_count=Count("id"))
+ .order_by("-report_count")[:10]
+)
+most_reported_creator = (
+ reports_in_range.values("media__creator")
+ .annotate(report_count=Count("id"))
+ .order_by("-report_count")[:10]
+)
+most_reported_source = (
+ reports_in_range.values("media__source")
+ .annotate(report_count=Count("id"))
+ .order_by("-report_count")[:10]
+)
```
### Surface in Django Admin
@@ -370,6 +392,7 @@ admin site and finally create custom filters to operate on the in-memory list.
```python
from collections import Counter
+
class Creator(models.Model):
# fields to uniquely identify a creator
name = models.CharField(max_length=100)
@@ -378,34 +401,43 @@ class Creator(models.Model):
class Meta:
managed = False
+
class CreatorAdmin(admin.ModelAdmin):
- list_display = ('name', 'provider', 'report_count')
- list_filter = ('provider',)
+ list_display = ("name", "provider", "report_count")
+ list_filter = ("provider",)
def report_count(self, obj):
- return Report.objects.filter(media_provider=obj.provider).filter(media__creator=obj.name).count()
+ return (
+ Report.objects.filter(media_provider=obj.provider)
+ .filter(media__creator=obj.name)
+ .count()
+ )
def get_queryset(self, request):
# Convert creators from report models into `Creator` models
creators = Counter()
- for media_id in Report.objects.values('media_obj_id', flat=True):
+ for media_id in Report.objects.values("media_obj_id", flat=True):
try:
- media = Media.objects.get(identifier=media_id)
- creators[(media.creator, media.provider)] += 1
+ media = Media.objects.get(identifier=media_id)
+ creators[(media.creator, media.provider)] += 1
except Media.DoesNotExist:
- pass
- return [Creator(name=creator[0], provider=creator[1]) for (creator, _) in creators.most_common(len(c))]
+ pass
+ return [
+ Creator(name=creator[0], provider=creator[1])
+ for (creator, _) in creators.most_common(len(c))
+ ]
+
class CustomFilter(admin.SimpleListFilter):
- title = 'Filter Title'
- parameter_name = 'parameter'
+ title = "Filter Title"
+ parameter_name = "parameter"
def lookups(self, request, model_admin):
# Return a list of tuples (value, verbose_value) for the filter.
# For example, in the provider filter, these can be a list of providers for that media type.
return (
- ('option_one', 'Option 1'),
- ('option_two', 'Option 2'),
+ ("option_one", "Option 1"),
+ ("option_two", "Option 2"),
)
def queryset(self, request, queryset):
@@ -422,6 +454,7 @@ class ImageProxy(Image):
class Meta:
proxy = True
+
class AudioProxy(Audio):
class Meta:
proxy = True
diff --git a/documentation/projects/proposals/trust_and_safety/detecting_sensitive_textual_content/20230330-implementation_plan_filtering_and_designating_results_with_sensitive_textual_content.md b/documentation/projects/proposals/trust_and_safety/detecting_sensitive_textual_content/20230330-implementation_plan_filtering_and_designating_results_with_sensitive_textual_content.md
index 2d23c30eb..ed984619c 100644
--- a/documentation/projects/proposals/trust_and_safety/detecting_sensitive_textual_content/20230330-implementation_plan_filtering_and_designating_results_with_sensitive_textual_content.md
+++ b/documentation/projects/proposals/trust_and_safety/detecting_sensitive_textual_content/20230330-implementation_plan_filtering_and_designating_results_with_sensitive_textual_content.md
@@ -205,7 +205,7 @@ this:
```py
def create_and_populate_filtered_index(
- self, model_name: str, index_suffix: Optional[str], **_
+ self, model_name: str, index_suffix: Optional[str], **_
):
# Rely on the alias to always created the filtered index from the up-to-date origin
source_index = f"{model_name}"
@@ -426,6 +426,7 @@ that the media serialisers can reference them to derive the sensitive field:
```py
sensitivity = serializers.SerializerMethodField()
+
def get_sensitivity(self, obj):
result = []
if obj["identifier"] in self.context["user_reported_sensitive_content_ids"]:
@@ -469,14 +470,14 @@ writing this document).
```py
origin_index_results = [
- {id: 1, mature: false}, # no sensitive text
- {id: 2, mature: true}, # no sensitive text
- {id: 3, mature: false}, # has sensitive text
- {id: 4, mature: true}, # has sensitive text
+ {id: 1, mature: false}, # no sensitive text
+ {id: 2, mature: true}, # no sensitive text
+ {id: 3, mature: false}, # has sensitive text
+ {id: 4, mature: true}, # has sensitive text
]
filtered_index_results = [
- {id: 1, mature: false}, # no sensitive text
+ {id: 1, mature: false}, # no sensitive text
]
sensitive_result_ids = origin_index_result_ids - filtered_index_result_ids
@@ -519,20 +520,24 @@ textual content:
```py
origin_index_results = [
- {id: 1, mature: false}, # no sensitive text
- {id: 2, mature: true}, # no sensitive text
- {id: 3, mature: false}, # has sensitive text
- {id: 4, mature: true}, # has sensitive text
+ {id: 1, mature: false}, # no sensitive text
+ {id: 2, mature: true}, # no sensitive text
+ {id: 3, mature: false}, # has sensitive text
+ {id: 4, mature: true}, # has sensitive text
]
filtered_index_results = [
- {id: 1, mature: false}, # no sensitive text
+ {id: 1, mature: false}, # no sensitive text
]
sensitive_result_ids = origin_index_result_ids - filtered_index_result_ids
# => [1, 2, 3, 4] - [1] = [2, 3, 4]
-sensitive_results = [r for r in origin_index_results if r["_id"] in sensitive_result_ids and not r["mature"]]
+sensitive_results = [
+ r
+ for r in origin_index_results
+ if r["_id"] in sensitive_result_ids and not r["mature"]
+]
# => [3]
```
diff --git a/pyproject.toml b/pyproject.toml
index c92895f00..87634441c 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -7,8 +7,10 @@ exclude-file = ".codespell/ignore_lines.txt"
ignore-words = ".codespell/ignore_words.txt"
[tool.ruff.lint]
-# Default for `select` is ["E4", "E7", "E9", "F"]
+# Pin the base rule set explicitly so that Ruff upgrades that change
+# the default selection do not silently enable new rules.
# All additional rules must be added using `extend-select`.
+select = ["E4", "E7", "E9", "F"]
extend-select = [
"UP", # pyupgrade, https://docs.astral.sh/ruff/rules/#pyupgrade-up
"D", # pydocstyle, https://docs.astral.sh/ruff/rules/#pydocstyle-d