Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions .github/workflows/pre-commit.yaml
Copy link
Contributor

@kevinconka kevinconka Jan 21, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cool! I did not think of using pre-commit to do all the linting and formatting checks

Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# .github/workflows/pre-commit.yml
name: Pre-commit

on:
pull_request:
branches: ['**']
push:
branches: ['**']

jobs:
pre-commit:
runs-on: ubuntu-latest

steps:
- name: Checkout Repository
uses: actions/checkout@v4

- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.12'

- uses: pre-commit/action@v3.0.0
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@ jobs:
steps:
- name: Checkout Repository
uses: actions/checkout@v4

- name: Install uv
uses: astral-sh/setup-uv@v6

- name: Sync dependencies
run: uv sync --all-extras

- name: Run tests
run: uv run pytest
4 changes: 2 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -182,9 +182,9 @@ cython_debug/
.abstra/

# Visual Studio Code
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
# and can be added to the global gitignore or merged into this file. However, if you prefer,
# and can be added to the global gitignore or merged into this file. However, if you prefer,
# you could uncomment the following to ignore the entire vscode folder
# .vscode/

Expand Down
24 changes: 24 additions & 0 deletions .pre-commit-config.yaml
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

very nice 😎

Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
repos:
# housekeeping 🧹
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
args: ['--maxkb=500']

# make code pretty 💄
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.3.0
hooks:
- id: ruff
args: [ --fix ]
- id: ruff-format

# scanning for leaked secrets ㊙️
- repo: https://github.com/gitleaks/gitleaks
rev: v8.18.2
hooks:
- id: gitleaks
8 changes: 8 additions & 0 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"recommendations": [
"ms-python.python",
"charliermarsh.ruff",
"ms-python.pylint"
],
"unwantedRecommendations": []
}
20 changes: 20 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"[python]": {
"editor.defaultFormatter": "charliermarsh.ruff",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": "explicit",
"source.fixAll.ruff": "explicit"
}
},
"python.testing.pytestArgs": [
"tests"
],
"python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true,
"files.exclude": {
"**/.mypy_cache": true,
"**/.pytest_cache": true,
"**/.ruff_cache": true
}
}
2 changes: 1 addition & 1 deletion ruff.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ select = [ # https://docs.astral.sh/ruff/rules/
"W", # PyCodeStyle Warnings
"ANN", # flake8-annotations
"B", # flake8-bugbear
"TC", # flake8-type-checking
"TCH", # flake8-type-checking
"PTH", # flake8-use-pathlib
"NPY", # NumPy specific rules
"TID", # flake8-tidy-imports
Expand Down
10 changes: 5 additions & 5 deletions src/seaclips/collate.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
# Licensed under the Apache License 2.0. See LICENSE file.

from dataclasses import dataclass
from typing import Any
from typing import Any, Union

import numpy as np
import torch
Expand Down Expand Up @@ -39,7 +39,7 @@ class SeaClipsBatch:
image_infos: List of image metadata dictionaries
annotations: List of lists of annotation dictionaries
video_infos: List of video metadata dictionaries
reference_frames: (optional) BatchedReferenceFrames instance for reference frames
reference_frames: (optional) BatchedReferenceFrames instance for ref frames
"""

images: torch.Tensor
Expand All @@ -60,7 +60,7 @@ def seaclips_collate_fn(batch: list[SeaClipsSample]) -> SeaClipsBatch:
batch: List of samples from SeaClipsDataset.__getitem__

Returns:
SeaClipsBatch: Batched data structure containing images, annotations, and metadata.
SeaClipsBatch: Batched data structure containing images, annotations & metadata.

Example:
>>> from torch.utils.data import DataLoader
Expand Down Expand Up @@ -161,7 +161,7 @@ def _collate_reference_frames(


def _get_image_tensor(
image: Any, target_size: tuple[int, int] | None = None
image: Union[Image.Image, torch.Tensor], target_size: tuple[int, int] | None = None
) -> torch.Tensor:
if isinstance(image, Image.Image):
image_array = np.array(image)
Expand All @@ -175,7 +175,7 @@ def _get_image_tensor(
return image_tensor

# --- 2. Pad to fixed size ---
C, H, W = image_tensor.shape
_, H, W = image_tensor.shape
target_h, target_w = target_size

if target_h < H or target_w < W:
Expand Down
14 changes: 8 additions & 6 deletions src/seaclips/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,14 +91,14 @@ def _load_metadata(self) -> None:
self.videos_idx = {}
return

with open(self.config.annotation_path, encoding="utf-8") as f:
with open(self.config.annotation_path, encoding="utf-8") as f: # noqa: PTH123
data = json.load(f)

self.videos_data = data["videos"]
self.videos_idx = {vid["id"]: vid for vid in self.videos_data}

def _build_video_frame_index(self) -> None:
"""Build index mapping video_id to sorted list of (frame_id, image_id, idx) tuples."""
"""Build index mapping video_id -> sorted list w (frame_id,image_id,idx)."""
self.video_frames_idx = {}

for idx, img_id in enumerate(self.image_ids):
Expand Down Expand Up @@ -138,7 +138,8 @@ def __getitem__(self, idx: int) -> SeaClipsSample:
- image_info: Image metadata (id, video_id, frame_id, etc.)
- annotations: List of annotation dictionaries with parsed fields
- video_info: Video metadata for this frame
- reference_frames: List of ReferenceFrame if load_reference_frames=True else None.
- reference_frames: List of ReferenceFrame if load_reference_frames=True
else None.
"""
if idx >= len(self):
raise IndexError(
Expand Down Expand Up @@ -198,7 +199,8 @@ def _get_reference_frames(

if current_pos is None:
raise ValueError(
f"Current index {current_idx} not found in video frames for video_id {video_id}"
f"Current index {current_idx} not found in video \
frames for video_id {video_id}"
)

for offset in self.config.ref_frame_range:
Expand All @@ -207,7 +209,7 @@ def _get_reference_frames(
# Check if reference frame exists
if not (0 <= ref_pos < len(video_frames)):
ref_pos = current_pos # Use current frame if out of bounds
offset = 0
offset = 0 # noqa: PLW2901

_, ref_img_id, _ = video_frames[ref_pos]

Expand Down Expand Up @@ -300,7 +302,7 @@ def filter_by_metadata(
"""Filter images by metadata attributes.

Args:
weather: Filter by weather condition ("sunny", "overcast", "cloudy", "rainy")
weather: Filter by weather ("sunny", "overcast", "cloudy", "rainy")
sea_state: Filter by sea state ("smooth", "wavy")
camera_sensor: Filter by camera sensor type ("e-CAM", "Axis", "FLIR")
water_reflections: Filter by water reflections presence ("yes", "no")
Expand Down
10 changes: 5 additions & 5 deletions src/seaclips/visualization.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@

import random

import matplotlib.patches as patches
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import patches
from matplotlib.figure import Figure
from PIL import Image

Expand Down Expand Up @@ -145,7 +145,7 @@ def show_sample(

return fig

def show_sample_with_references(
def show_sample_with_references( # noqa: PLR0914
self,
idx: int,
show_labels: bool = True,
Expand Down Expand Up @@ -218,7 +218,7 @@ def show_sample_with_references(
spine.set_linewidth(3)
spine.set_visible(True)

for idx in range(n_frames, len(axes)):
for idx in range(n_frames, len(axes)): # noqa: PLR1704
axes[idx].axis("off")

video_info = self.dataset.videos_idx[sample.video_info["id"]]
Expand Down Expand Up @@ -266,7 +266,7 @@ def show_video_sequence(
axes = np.array([axes])
axes = axes.flatten()

for idx, (frame, ax) in enumerate(zip(frames_to_show, axes)):
for _, (frame, ax) in enumerate(zip(frames_to_show, axes)):
image = frame.image
annotations = frame.annotations
img_info = frame.image_info
Expand Down Expand Up @@ -330,7 +330,7 @@ def show_grid(
return fig


def show_sample(dataset: SeaClipsDataset, idx: int, **kwargs) -> Figure:
def show_sample(dataset: SeaClipsDataset, idx: int, **kwargs) -> Figure: # noqa: ANN003
"""Convenience function to visualize a sample.

Args:
Expand Down
3 changes: 1 addition & 2 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

import pytest
from PIL import Image

from seaclips.dataset import ReferenceFrame, SeaClipsSample


Expand Down Expand Up @@ -107,7 +106,7 @@ def dataset_root(tmp_path, sample_coco_data):
img.save(split_dir / f"{i:06d}.png")

annotation_file = tmp_path / f"seaclips-{split}.json"
with open(annotation_file, "w", encoding="utf-8") as f:
with open(annotation_file, "w", encoding="utf-8") as f: # noqa: PTH123
json.dump(sample_coco_data, f)

return tmp_path
Expand Down
2 changes: 0 additions & 2 deletions tests/test_collate.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
"""Tests for collate functions."""

import pytest
import torch

from seaclips.collate import seaclips_collate_fn


Expand Down
1 change: 0 additions & 1 deletion tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
from pathlib import Path

import pytest

from seaclips.config import SeaClipsConfig


Expand Down
1 change: 0 additions & 1 deletion tests/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

import pytest
from PIL import Image

from seaclips.config import SeaClipsConfig
from seaclips.dataset import SeaClipsDataset

Expand Down