animl-lite 3.3.2__tar.gz → 3.3.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. {animl_lite-3.3.2 → animl_lite-3.3.4}/PKG-INFO +4 -3
  2. {animl_lite-3.3.2 → animl_lite-3.3.4}/README.md +1 -1
  3. {animl_lite-3.3.2 → animl_lite-3.3.4}/pyproject.toml +4 -3
  4. {animl_lite-3.3.2 → animl_lite-3.3.4}/src/animl/__init__.py +1 -1
  5. {animl_lite-3.3.2 → animl_lite-3.3.4}/src/animl/classification.py +4 -0
  6. {animl_lite-3.3.2 → animl_lite-3.3.4}/src/animl/generator.py +0 -3
  7. {animl_lite-3.3.2 → animl_lite-3.3.4}/src/animl/utils/general.py +3 -2
  8. {animl_lite-3.3.2 → animl_lite-3.3.4}/src/animl_lite.egg-info/PKG-INFO +4 -3
  9. {animl_lite-3.3.2 → animl_lite-3.3.4}/src/animl_lite.egg-info/SOURCES.txt +4 -1
  10. {animl_lite-3.3.2 → animl_lite-3.3.4}/src/animl_lite.egg-info/requires.txt +2 -1
  11. animl_lite-3.3.4/tests/test_classification.py +209 -0
  12. animl_lite-3.3.4/tests/test_detection.py +238 -0
  13. {animl_lite-3.3.2 → animl_lite-3.3.4}/tests/test_file_management.py +39 -18
  14. animl_lite-3.3.4/tests/test_video_processing.py +260 -0
  15. {animl_lite-3.3.2 → animl_lite-3.3.4}/LICENSE +0 -0
  16. {animl_lite-3.3.2 → animl_lite-3.3.4}/setup.cfg +0 -0
  17. {animl_lite-3.3.2 → animl_lite-3.3.4}/src/animl/__main__.py +0 -0
  18. {animl_lite-3.3.2 → animl_lite-3.3.4}/src/animl/detection.py +0 -0
  19. {animl_lite-3.3.2 → animl_lite-3.3.4}/src/animl/export.py +0 -0
  20. {animl_lite-3.3.2 → animl_lite-3.3.4}/src/animl/file_management.py +0 -0
  21. {animl_lite-3.3.2 → animl_lite-3.3.4}/src/animl/pipeline.py +0 -0
  22. {animl_lite-3.3.2 → animl_lite-3.3.4}/src/animl/reid/__init__.py +0 -0
  23. {animl_lite-3.3.2 → animl_lite-3.3.4}/src/animl/reid/distance.py +0 -0
  24. {animl_lite-3.3.2 → animl_lite-3.3.4}/src/animl/reid/inference.py +0 -0
  25. {animl_lite-3.3.2 → animl_lite-3.3.4}/src/animl/utils/__init__.py +0 -0
  26. {animl_lite-3.3.2 → animl_lite-3.3.4}/src/animl/utils/animlr.py +0 -0
  27. {animl_lite-3.3.2 → animl_lite-3.3.4}/src/animl/utils/visualization.py +0 -0
  28. {animl_lite-3.3.2 → animl_lite-3.3.4}/src/animl/video_processing.py +0 -0
  29. {animl_lite-3.3.2 → animl_lite-3.3.4}/src/animl_lite.egg-info/dependency_links.txt +0 -0
  30. {animl_lite-3.3.2 → animl_lite-3.3.4}/src/animl_lite.egg-info/top_level.txt +0 -0
  31. {animl_lite-3.3.2 → animl_lite-3.3.4}/tests/test_export.py +0 -0
  32. {animl_lite-3.3.2 → animl_lite-3.3.4}/tests/test_pipeline.py +0 -0
  33. {animl_lite-3.3.2 → animl_lite-3.3.4}/tests/test_reid_distance.py +0 -0
  34. {animl_lite-3.3.2 → animl_lite-3.3.4}/tests/test_utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: animl-lite
3
- Version: 3.3.2
3
+ Version: 3.3.4
4
4
  Summary: Tools for classifying camera trap images
5
5
  Author-email: Kyra Swanson <tswanson@sdzwa.org>
6
6
  Project-URL: Homepage, https://github.com/conservationtechlab/animl-py
@@ -14,12 +14,13 @@ Requires-Dist: pillow>=12.3.0
14
14
  Requires-Dist: pyexiftool>=0.5.6
15
15
  Requires-Dist: pyyaml>=6.0.3
16
16
  Requires-Dist: opencv-python>=4.12.0.88
17
+ Requires-Dist: onnxruntime==1.22.0
17
18
  Requires-Dist: tqdm>=4.66.5
18
19
  Provides-Extra: gpu
19
- Requires-Dist: onnxruntime-gpu==1.20.0; extra == "gpu"
20
+ Requires-Dist: onnxruntime-gpu==1.22.0; extra == "gpu"
20
21
  Dynamic: license-file
21
22
 
22
- # animl-py 3.3.2
23
+ # animl-py 3.3.4
23
24
  AniML comprises a variety of machine learning tools for analyzing ecological data. This Python package includes a set of functions to classify subjects within camera trap field data and can handle both images and videos.
24
25
  This package is also available in R: [animl](https://github.com/conservationtechlab/animl)
25
26
 
@@ -1,4 +1,4 @@
1
- # animl-py 3.3.2
1
+ # animl-py 3.3.4
2
2
  AniML comprises a variety of machine learning tools for analyzing ecological data. This Python package includes a set of functions to classify subjects within camera trap field data and can handle both images and videos.
3
3
  This package is also available in R: [animl](https://github.com/conservationtechlab/animl)
4
4
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "animl-lite"
3
- version = "3.3.2"
3
+ version = "3.3.4"
4
4
  description = "Tools for classifying camera trap images"
5
5
 
6
6
  readme = "README.md"
@@ -13,15 +13,16 @@ requires-python = ">=3.12,<3.14"
13
13
  dependencies = [
14
14
  "numpy>=2.0.2",
15
15
  "pandas>=2.2.2,<3.0.0",
16
- "pillow>=12.3.0",
16
+ "pillow>=12.3.0",
17
17
  "pyexiftool>=0.5.6",
18
18
  "pyyaml>=6.0.3",
19
19
  "opencv-python>=4.12.0.88",
20
+ "onnxruntime==1.22.0",
20
21
  "tqdm>=4.66.5",
21
22
  ]
22
23
  [project.optional-dependencies]
23
24
  gpu = [
24
- "onnxruntime-gpu==1.20.0",
25
+ "onnxruntime-gpu==1.22.0",
25
26
  ]
26
27
 
27
28
  [project.urls] # Optional
@@ -1,4 +1,4 @@
1
- __version__ = '3.3.2'
1
+ __version__ = '3.3.4'
2
2
 
3
3
  from animl import classification
4
4
  from animl import detection
@@ -33,6 +33,10 @@ def load_classifier(model_path: str,
33
33
  '''
34
34
  class_list = None
35
35
  model_path = Path(model_path)
36
+
37
+ if not model_path.exists():
38
+ raise FileNotFoundError(f"Model file not found at {model_path}")
39
+
36
40
  # check to make sure GPU is available if chosen
37
41
  providers = get_onnx_device(user_set=device)
38
42
 
@@ -8,8 +8,6 @@ so the module can be used without requiring PyTorch at runtime.
8
8
  Images are returned as numpy arrays (C, H, W) with dtype float32 and
9
9
  values scaled to [0, 1]. Batching is provided by a simple Python generator.
10
10
  """
11
- from venv import logger
12
-
13
11
  import cv2
14
12
  import numpy as np
15
13
  from typing import Tuple, Optional, Sequence, Generator
@@ -19,7 +17,6 @@ from PIL import Image, ImageFile, ImageOps
19
17
  from collections import deque
20
18
  import threading
21
19
  import queue
22
- from concurrent.futures import ThreadPoolExecutor
23
20
 
24
21
  from animl.file_management import IMAGE_EXTENSIONS, VIDEO_EXTENSIONS
25
22
  from animl.utils.general import SDZWA_CLASSIFIER_SIZE
@@ -54,8 +54,9 @@ def get_onnx_device(user_set=None, quiet=False):
54
54
  if user_set is not None and user_set in ['cuda', 'cuda:0', 'cuda:1', 'cuda:2', 'cuda:3']:
55
55
  if not quiet:
56
56
  print('Warning: CUDA device specified but not available, using CPU instead.')
57
- providers = ['CPUExecutionProvider']
58
-
57
+ # CoreML/MPS not compatible at this time
58
+ providers = ['CPUExecutionProvider']
59
+
59
60
  return providers
60
61
 
61
62
  # ==============================================================================
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: animl-lite
3
- Version: 3.3.2
3
+ Version: 3.3.4
4
4
  Summary: Tools for classifying camera trap images
5
5
  Author-email: Kyra Swanson <tswanson@sdzwa.org>
6
6
  Project-URL: Homepage, https://github.com/conservationtechlab/animl-py
@@ -14,12 +14,13 @@ Requires-Dist: pillow>=12.3.0
14
14
  Requires-Dist: pyexiftool>=0.5.6
15
15
  Requires-Dist: pyyaml>=6.0.3
16
16
  Requires-Dist: opencv-python>=4.12.0.88
17
+ Requires-Dist: onnxruntime==1.22.0
17
18
  Requires-Dist: tqdm>=4.66.5
18
19
  Provides-Extra: gpu
19
- Requires-Dist: onnxruntime-gpu==1.20.0; extra == "gpu"
20
+ Requires-Dist: onnxruntime-gpu==1.22.0; extra == "gpu"
20
21
  Dynamic: license-file
21
22
 
22
- # animl-py 3.3.2
23
+ # animl-py 3.3.4
23
24
  AniML comprises a variety of machine learning tools for analyzing ecological data. This Python package includes a set of functions to classify subjects within camera trap field data and can handle both images and videos.
24
25
  This package is also available in R: [animl](https://github.com/conservationtechlab/animl)
25
26
 
@@ -22,8 +22,11 @@ src/animl_lite.egg-info/SOURCES.txt
22
22
  src/animl_lite.egg-info/dependency_links.txt
23
23
  src/animl_lite.egg-info/requires.txt
24
24
  src/animl_lite.egg-info/top_level.txt
25
+ tests/test_classification.py
26
+ tests/test_detection.py
25
27
  tests/test_export.py
26
28
  tests/test_file_management.py
27
29
  tests/test_pipeline.py
28
30
  tests/test_reid_distance.py
29
- tests/test_utils.py
31
+ tests/test_utils.py
32
+ tests/test_video_processing.py
@@ -4,7 +4,8 @@ pillow>=12.3.0
4
4
  pyexiftool>=0.5.6
5
5
  pyyaml>=6.0.3
6
6
  opencv-python>=4.12.0.88
7
+ onnxruntime==1.22.0
7
8
  tqdm>=4.66.5
8
9
 
9
10
  [gpu]
10
- onnxruntime-gpu==1.20.0
11
+ onnxruntime-gpu==1.22.0
@@ -0,0 +1,209 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+ import pytest
8
+
9
+ from animl.classification import (
10
+ classify,
11
+ load_class_list,
12
+ load_classifier,
13
+ single_classification,
14
+ )
15
+
16
+
17
+ # ---------------------------------------------------------------------------
18
+ # Fixtures
19
+ # ---------------------------------------------------------------------------
20
+
21
+ @pytest.fixture
22
+ def class_list_file(tmp_path: Path) -> Path:
23
+ f = tmp_path / "classes.csv"
24
+ f.write_text("class\njaguar\nocelot\npuma\n")
25
+ return f
26
+
27
+
28
+ @pytest.fixture
29
+ def class_list_df() -> pd.DataFrame:
30
+ return pd.DataFrame({"class": ["jaguar", "ocelot", "puma"]})
31
+
32
+
33
+ @pytest.fixture
34
+ def animals_df(tmp_path: Path) -> pd.DataFrame:
35
+ from PIL import Image
36
+
37
+ img = tmp_path / "animal.jpg"
38
+ Image.new("RGB", (299, 299), color=(100, 50, 10)).save(img)
39
+ return pd.DataFrame(
40
+ {
41
+ "filepath": [str(img)],
42
+ "frame": [0],
43
+ "conf": [0.9],
44
+ "category": [1],
45
+ "category_label": ["animal"],
46
+ "max_detection_conf": [0.9],
47
+ "bbox_x": [0.1],
48
+ "bbox_y": [0.1],
49
+ "bbox_w": [0.5],
50
+ "bbox_h": [0.5],
51
+ }
52
+ )
53
+
54
+
55
+ @pytest.fixture
56
+ def empty_df() -> pd.DataFrame:
57
+ return pd.DataFrame(
58
+ {
59
+ "filepath": ["empty.jpg"],
60
+ "frame": [0],
61
+ "conf": [None],
62
+ "category": [0],
63
+ "category_label": ["empty"],
64
+ "max_detection_conf": [None],
65
+ "prediction": ["empty"],
66
+ "confidence": [1.0],
67
+ }
68
+ )
69
+
70
+
71
+ @pytest.fixture
72
+ def real_classifier_model() -> Path:
73
+ """
74
+ Use an existing real ONNX model file for testing.
75
+ Point this to your actual model location.
76
+ """
77
+ # Option 1: Copy from a known location in your repo/test data
78
+ real_model_path = Path(__file__).parent / "fixtures" / "sdzwa_southwest_v3.onnx"
79
+
80
+ if real_model_path.exists():
81
+ return real_model_path
82
+
83
+ pytest.skip("Real classifier model not found")
84
+
85
+
86
+ # ---------------------------------------------------------------------------
87
+ # load_class_list
88
+ # ---------------------------------------------------------------------------
89
+
90
+ def test_load_class_list_returns_dataframe(class_list_file: Path):
91
+ df = load_class_list(str(class_list_file))
92
+ assert isinstance(df, pd.DataFrame)
93
+ assert "class" in df.columns
94
+ assert len(df) == 3
95
+
96
+
97
+ def test_load_class_list_raises_for_missing_file(tmp_path: Path):
98
+ with pytest.raises(FileNotFoundError):
99
+ load_class_list(str(tmp_path / "nonexistent.csv"))
100
+
101
+
102
+ # ---------------------------------------------------------------------------
103
+ # load_classifier
104
+ # ---------------------------------------------------------------------------
105
+
106
+ def test_load_classifier_raises_for_missing_model(tmp_path: Path):
107
+ with pytest.raises(Exception):
108
+ load_classifier(str(tmp_path / "nonexistent.onnx"))
109
+
110
+
111
+ def test_load_classifier_returns_model_and_class_list(real_classifier_model: Path, class_list_file: Path):
112
+ model, class_list = load_classifier(str(real_classifier_model), classes=class_list_file)
113
+ assert model is not None
114
+ assert model.model_type == "classifier"
115
+ assert class_list is not None
116
+
117
+
118
+ def test_load_classifier_accepts_dataframe_classes(real_classifier_model: Path, class_list_df: pd.DataFrame):
119
+ model, class_list = load_classifier(str(real_classifier_model), classes=class_list_df)
120
+ assert class_list is not None
121
+
122
+
123
+ def test_load_classifier_no_classes_returns_none_class_list(real_classifier_model: Path):
124
+ model, class_list = load_classifier(str(real_classifier_model))
125
+ # class list is should load from onnx model
126
+ assert class_list is not None
127
+
128
+
129
+ # ---------------------------------------------------------------------------
130
+ # classify
131
+ # ---------------------------------------------------------------------------
132
+
133
+ def test_classify_returns_numpy_array(real_classifier_model: Path, animals_df: pd.DataFrame):
134
+ model, _ = load_classifier(str(real_classifier_model))
135
+ result = classify(model, animals_df, resize_width=299, resize_height=299, crop=False)
136
+ assert isinstance(result, np.ndarray)
137
+
138
+
139
+ def test_classify_raises_on_invalid_input(real_classifier_model: Path):
140
+ model, _ = load_classifier(str(real_classifier_model))
141
+ with pytest.raises(AssertionError):
142
+ classify(model, 12345)
143
+
144
+
145
+ def test_classify_accepts_string_filepath(real_classifier_model: Path, animals_df: pd.DataFrame):
146
+ model, _ = load_classifier(str(real_classifier_model))
147
+ filepath = animals_df["filepath"].iloc[0]
148
+ result = classify(model, filepath, resize_width=299, resize_height=299)
149
+ assert isinstance(result, np.ndarray)
150
+
151
+
152
+ def test_classify_accepts_list_of_filepaths(real_classifier_model: Path, animals_df: pd.DataFrame):
153
+ model, _ = load_classifier(str(real_classifier_model))
154
+ result = classify(model, animals_df, resize_width=299, resize_height=299)
155
+ assert isinstance(result, np.ndarray)
156
+
157
+
158
+ def test_classify_saves_to_file(real_classifier_model: Path, tmp_path: Path, animals_df: pd.DataFrame):
159
+ model, _ = load_classifier(str(real_classifier_model))
160
+ out = tmp_path / "classifications.csv"
161
+ classify(model, animals_df, resize_width=299, resize_height=299, crop=False, out_file=str(out))
162
+ assert out.exists()
163
+
164
+
165
+ def test_classify_raises_on_missing_file_col(real_classifier_model: Path):
166
+ model, _ = load_classifier(str(real_classifier_model))
167
+ df = pd.DataFrame({"other_col": ["img.jpg"]})
168
+ with pytest.raises(ValueError):
169
+ classify(model, df, file_col="filepath")
170
+
171
+
172
+ # ---------------------------------------------------------------------------
173
+ # single_classification
174
+ # ---------------------------------------------------------------------------
175
+
176
+ def test_single_classification_adds_prediction_column(animals_df: pd.DataFrame):
177
+ predictions_raw = np.array([[0.1, 0.8, 0.1]])
178
+ class_list = ["jaguar", "ocelot", "puma"]
179
+ result = single_classification(animals_df, None, predictions_raw, class_list)
180
+ assert "prediction" in result.columns
181
+ assert "confidence" in result.columns
182
+ assert result["prediction"].iloc[0] == "ocelot"
183
+
184
+
185
+ def test_single_classification_includes_empty(animals_df: pd.DataFrame, empty_df: pd.DataFrame):
186
+ predictions_raw = np.array([[0.1, 0.8, 0.1]])
187
+ class_list = ["jaguar", "ocelot", "puma"]
188
+ result = single_classification(animals_df, empty_df, predictions_raw, class_list)
189
+ assert len(result) == 2
190
+ assert "empty" in result["prediction"].values
191
+
192
+
193
+ def test_single_classification_best_returns_one_per_file(animals_df: pd.DataFrame):
194
+ predictions_raw = np.array([[0.1, 0.8, 0.1]])
195
+ class_list = ["jaguar", "ocelot", "puma"]
196
+ result = single_classification(animals_df, None, predictions_raw, class_list, best=True)
197
+ assert len(result) == 1
198
+
199
+
200
+ def test_single_classification_empty_animals_still_returns(empty_df: pd.DataFrame):
201
+ animals = pd.DataFrame(
202
+ columns=["filepath", "frame", "conf", "category", "category_label",
203
+ "max_detection_conf", "bbox_x", "bbox_y", "bbox_w", "bbox_h"]
204
+ )
205
+ predictions_raw = np.zeros((0, 3))
206
+ class_list = ["jaguar", "ocelot", "puma"]
207
+ result = single_classification(animals, empty_df, predictions_raw, class_list)
208
+ assert isinstance(result, pd.DataFrame)
209
+ assert not result.empty
@@ -0,0 +1,238 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+ from typing import Optional
5
+
6
+ import numpy as np
7
+ import pandas as pd
8
+ import pytest
9
+
10
+ from animl.detection import (
11
+ _convert_detections,
12
+ get_animals,
13
+ get_empty,
14
+ load_detector,
15
+ parse_detections,
16
+ )
17
+
18
+
19
+ # ---------------------------------------------------------------------------
20
+ # Helpers / fixtures
21
+ # ---------------------------------------------------------------------------
22
+
23
+ @pytest.fixture
24
+ def sample_detections_with_animal() -> list[dict]:
25
+ return [
26
+ {
27
+ "filepath": "img_a.jpg",
28
+ "frame": 0,
29
+ "max_detection_conf": 0.9,
30
+ "category": 1,
31
+ "category_label": "animal",
32
+ "detections": [
33
+ {
34
+ "category": 1,
35
+ "category_label": "animal",
36
+ "conf": 0.9,
37
+ "bbox_x": 0.1,
38
+ "bbox_y": 0.2,
39
+ "bbox_w": 0.3,
40
+ "bbox_h": 0.4,
41
+ }
42
+ ],
43
+ }
44
+ ]
45
+
46
+
47
+ @pytest.fixture
48
+ def sample_detections_empty() -> list[dict]:
49
+ return [
50
+ {
51
+ "filepath": "img_b.jpg",
52
+ "frame": 0,
53
+ "max_detection_conf": None,
54
+ "category": 0,
55
+ "category_label": "empty",
56
+ "detections": [],
57
+ }
58
+ ]
59
+
60
+
61
+ @pytest.fixture
62
+ def mixed_detections(
63
+ sample_detections_with_animal, sample_detections_empty
64
+ ) -> list[dict]:
65
+ return sample_detections_with_animal + sample_detections_empty
66
+
67
+
68
+ @pytest.fixture
69
+ def real_detector_model() -> Path:
70
+ """
71
+ Use an existing real ONNX model file for testing.
72
+ Point this to your actual model location.
73
+ """
74
+ # Option 1: Copy from a known location in your repo/test data
75
+ real_model_path = Path(__file__).parent / "fixtures" / "md_v1000.0.0-sorrel.onnx"
76
+
77
+ if real_model_path.exists():
78
+ return real_model_path
79
+
80
+ pytest.skip("Real detector model not found")
81
+
82
+
83
+
84
+
85
+ # ---------------------------------------------------------------------------
86
+ # load_detector
87
+ # ---------------------------------------------------------------------------
88
+
89
+ def test_load_detector_raises_for_missing_file(tmp_path: Path):
90
+ with pytest.raises(FileNotFoundError):
91
+ load_detector(str(tmp_path / "nonexistent.onnx"))
92
+
93
+
94
+ def test_load_detector_returns_model_with_type(real_detector_model: Path):
95
+ model = load_detector(str(real_detector_model), model_type="megadetector")
96
+ assert model.model_type == "megadetector"
97
+
98
+
99
+ def test_load_detector_sets_custom_model_type(real_detector_model: Path):
100
+ model = load_detector(str(real_detector_model), model_type="yolo")
101
+ assert model.model_type == "yolo"
102
+
103
+
104
+ # ---------------------------------------------------------------------------
105
+ # parse_detections
106
+ # ---------------------------------------------------------------------------
107
+
108
+ def test_parse_detections_returns_dataframe(sample_detections_with_animal):
109
+ df = parse_detections(sample_detections_with_animal)
110
+ assert isinstance(df, pd.DataFrame)
111
+ assert not df.empty
112
+
113
+
114
+ def test_parse_detections_contains_expected_columns(sample_detections_with_animal):
115
+ df = parse_detections(sample_detections_with_animal)
116
+ for col in ("filepath", "frame", "category", "conf", "bbox_x", "bbox_y", "bbox_w", "bbox_h"):
117
+ assert col in df.columns, f"Missing column: {col}"
118
+
119
+
120
+ def test_parse_detections_empty_detections(sample_detections_empty):
121
+ df = parse_detections(sample_detections_empty)
122
+ assert isinstance(df, pd.DataFrame)
123
+ assert len(df) == 1
124
+ assert df.iloc[0]["category_label"] == "empty"
125
+
126
+
127
+ def test_parse_detections_raises_on_empty_list():
128
+ with pytest.raises(AssertionError):
129
+ parse_detections([])
130
+
131
+
132
+ def test_parse_detections_raises_on_non_list():
133
+ with pytest.raises(TypeError):
134
+ parse_detections({"not": "a list"})
135
+
136
+
137
+ def test_parse_detections_threshold_filters(sample_detections_with_animal):
138
+ df = parse_detections(sample_detections_with_animal, threshold=0.95)
139
+ # The only detection has conf=0.9, which is below the threshold of 0.95,
140
+ # so it should be filtered out leaving no animal rows with a non-null conf.
141
+ assert df.empty
142
+
143
+
144
+ def test_parse_detections_merges_manifest(sample_detections_with_animal, tmp_path: Path):
145
+ manifest = pd.DataFrame(
146
+ {"filepath": ["img_a.jpg"], "frame": [0], "station": ["s1"]}
147
+ )
148
+ df = parse_detections(sample_detections_with_animal, manifest=manifest)
149
+ assert "station" in df.columns
150
+
151
+
152
+ def test_parse_detections_raises_invalid_manifest_col(sample_detections_with_animal):
153
+ manifest = pd.DataFrame({"other_col": ["img_a.jpg"]})
154
+ with pytest.raises(ValueError):
155
+ parse_detections(sample_detections_with_animal, manifest=manifest, file_col="filepath")
156
+
157
+
158
+ def test_parse_detections_saves_to_file(tmp_path: Path, sample_detections_with_animal):
159
+ out = tmp_path / "detections.csv"
160
+ df = parse_detections(sample_detections_with_animal, out_file=str(out))
161
+ assert out.exists()
162
+ assert isinstance(df, pd.DataFrame)
163
+
164
+
165
+ # ---------------------------------------------------------------------------
166
+ # get_animals / get_empty
167
+ # ---------------------------------------------------------------------------
168
+
169
+ @pytest.fixture
170
+ def manifest_with_mixed_categories() -> pd.DataFrame:
171
+ return pd.DataFrame(
172
+ {
173
+ "filepath": ["a.jpg", "b.jpg", "c.jpg"],
174
+ "frame": [0, 0, 0],
175
+ "category": [1, 0, 2],
176
+ "conf": [0.9, 1, 0.8],
177
+ "category_label": ["animal", "empty", "vehicle"],
178
+ }
179
+ )
180
+
181
+
182
+ def test_get_animals_returns_only_animals(manifest_with_mixed_categories):
183
+ animals = get_animals(manifest_with_mixed_categories)
184
+ assert not animals.empty
185
+ assert all(animals["category_label"] == "animal")
186
+
187
+
188
+ def test_get_animals_returns_empty_df_when_no_animals():
189
+ manifest = pd.DataFrame(
190
+ {"category_label": ["empty", "vehicle"], "filepath": ["a.jpg", "b.jpg"]}
191
+ )
192
+ animals = get_animals(manifest)
193
+ assert animals.empty
194
+
195
+
196
+ def test_get_animals_uses_category_when_no_label_col():
197
+ manifest = pd.DataFrame(
198
+ {"category": [1, 0, 1], "filepath": ["a.jpg", "b.jpg", "c.jpg"]}
199
+ )
200
+ animals = get_animals(manifest)
201
+ assert len(animals) == 2
202
+
203
+
204
+ def test_get_empty_returns_non_animals(manifest_with_mixed_categories):
205
+ others = get_empty(manifest_with_mixed_categories)
206
+ assert not others.empty
207
+ assert all(others["category_label"] != "animal")
208
+
209
+
210
+ def test_get_empty_returns_empty_df_when_all_animals():
211
+ manifest = pd.DataFrame(
212
+ {
213
+ "category": [1, 1],
214
+ "category_label": ["animal", "animal"],
215
+ "filepath": ["a.jpg", "b.jpg"],
216
+ }
217
+ )
218
+ others = get_empty(manifest)
219
+ assert others.empty
220
+
221
+
222
+ # ---------------------------------------------------------------------------
223
+ # _convert_detections (internal helper)
224
+ # ---------------------------------------------------------------------------
225
+
226
+ def test_convert_detections_no_detection_produces_empty_result():
227
+ # Simulate a batch with one image that has zero predictions above threshold.
228
+ image_tensor = np.zeros((1, 3, 32, 32), dtype=np.float32)
229
+ image_paths = ["img.jpg"]
230
+ image_frames = [0]
231
+ image_sizes = np.array([[32, 32]])
232
+ # pred with no detections (empty rows)
233
+ predictions = [np.zeros((0, 6), dtype=np.float32)]
234
+ batch = (image_tensor, image_paths, image_frames, image_sizes)
235
+ results = _convert_detections(predictions, batch, letterbox=False)
236
+ assert len(results) == 1
237
+ assert results[0]["detections"] == []
238
+ assert results[0]["filepath"] == "img.jpg"
@@ -6,7 +6,7 @@ import pandas as pd
6
6
  import pytest
7
7
 
8
8
  from animl import file_management
9
- from animl.generator import ManifestGenerator, manifest_dataloader
9
+ from animl.generator import ManifestGenerator
10
10
 
11
11
 
12
12
  def test_valid_extensions_contains_expected_types():
@@ -218,50 +218,71 @@ def test_sequence_calculation_input_validation(station_col, maxdiff, exc):
218
218
  file_management.sequence_calculation(manifest, station_col=station_col, maxdiff=maxdiff)
219
219
 
220
220
 
221
- def test_manifest_generator_len_and_item(tmp_path: Path):
221
+ def test_manifest_generator_len_and_batches(tmp_path: Path):
222
+ """Test that ManifestGenerator correctly reports batch count and yields batches."""
222
223
  img = tmp_path / "img.jpg"
223
224
  from PIL import Image
224
225
 
225
226
  Image.new("RGB", (20, 10), color=(100, 50, 10)).save(img)
226
227
  df = pd.DataFrame({"filepath": [str(img)]})
227
- gen = ManifestGenerator(df, crop=False, resize_height=16, resize_width=16)
228
+ gen = ManifestGenerator(df, crop=False, resize_height=16, resize_width=16, batch_size=1)
229
+
230
+ # __len__ returns number of batches
228
231
  assert len(gen) == 1
229
- item = gen[0]
230
- assert item is not None
231
- img_arr, path, frame, hw = item
232
- assert img_arr.shape == (3, 16, 16)
233
- assert path == str(img)
234
- assert frame == 0
235
- assert hw.tolist() == [10, 20]
232
+
233
+ # Iterate and get first batch
234
+ batch = next(iter(gen))
235
+ assert batch is not None
236
+
237
+ batch_images, batch_filepaths, batch_frames, batch_hw = batch
238
+ assert batch_images.shape == (1, 3, 16, 16) # (B, C, H, W)
239
+ assert batch_filepaths == [str(img)]
240
+ assert batch_frames[0] == 0
241
+ assert batch_hw[0].tolist() == [10, 20] # [height, width]
236
242
 
237
243
 
238
244
  def test_manifest_generator_requires_bbox_when_crop_true(tmp_path: Path):
245
+ """Test that cropping without bbox columns disables cropping instead of raising."""
239
246
  img = tmp_path / "img.jpg"
240
247
  from PIL import Image
241
248
 
242
249
  Image.new("RGB", (20, 10), color=(0, 0, 0)).save(img)
243
250
  df = pd.DataFrame({"filepath": [str(img)]})
244
- with pytest.raises(ValueError):
245
- ManifestGenerator(df, crop=True)
251
+
252
+ # Should not raise; instead it disables cropping and prints a message
253
+ gen = ManifestGenerator(df, crop=True)
254
+ assert gen.crop is False
246
255
 
247
256
 
248
257
  def test_manifest_generator_invalid_crop_coord(tmp_path: Path):
258
+ """Test that invalid crop_coord raises ValueError."""
249
259
  img = tmp_path / "img.jpg"
250
260
  from PIL import Image
251
261
 
252
262
  Image.new("RGB", (20, 10), color=(0, 0, 0)).save(img)
253
- df = pd.DataFrame({"filepath": [str(img)], "bbox_x": [0], "bbox_y": [0], "bbox_w": [1], "bbox_h": [1]})
254
- with pytest.raises(ValueError):
263
+ df = pd.DataFrame({
264
+ "filepath": [str(img)],
265
+ "bbox_x": [0],
266
+ "bbox_y": [0],
267
+ "bbox_w": [1],
268
+ "bbox_h": [1]
269
+ })
270
+
271
+ with pytest.raises(ValueError, match="crop_coord must be 'relative' or 'absolute'"):
255
272
  ManifestGenerator(df, crop=True, crop_coord="bad")
256
273
 
257
274
 
258
275
  def test_manifest_dataloader_yields_batches(tmp_path: Path):
276
+ """Test that ManifestGenerator yields properly formatted batches."""
259
277
  img = tmp_path / "img.jpg"
260
278
  from PIL import Image
261
279
 
262
280
  Image.new("RGB", (20, 10), color=(0, 0, 0)).save(img)
263
281
  df = pd.DataFrame({"filepath": [str(img)]})
264
- loader = manifest_dataloader(df, crop=False, resize_height=8, resize_width=8)
265
- batch = next(loader)
266
- assert batch[0].shape == (1, 3, 8, 8)
267
- assert batch[1] == [str(img)]
282
+ loader = ManifestGenerator(df, crop=False, resize_height=8, resize_width=8, batch_size=1)
283
+
284
+ batch = next(iter(loader))
285
+ batch_images, batch_filepaths, batch_frames, batch_hw = batch
286
+
287
+ assert batch_images.shape == (1, 3, 8, 8) # (B, C, H, W)
288
+ assert batch_filepaths == [str(img)]
@@ -0,0 +1,260 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+ from unittest.mock import MagicMock, patch
5
+
6
+ import cv2
7
+ import numpy as np
8
+ import pandas as pd
9
+ import pytest
10
+
11
+ from animl import file_management
12
+ from animl.video_processing import (
13
+ _count_frames,
14
+ extract_frames,
15
+ get_images,
16
+ get_videos,
17
+ )
18
+
19
+
20
+ # ---------------------------------------------------------------------------
21
+ # Fixtures
22
+ # ---------------------------------------------------------------------------
23
+
24
+ @pytest.fixture
25
+ def mixed_manifest(tmp_path: Path) -> pd.DataFrame:
26
+ img = tmp_path / "photo.jpg"
27
+ vid = tmp_path / "clip.mp4"
28
+ img.write_bytes(b"fake-image")
29
+ vid.write_bytes(b"fake-video")
30
+ return pd.DataFrame({"filepath": [str(img), str(vid)]})
31
+
32
+
33
+ @pytest.fixture
34
+ def image_manifest(tmp_path: Path) -> pd.DataFrame:
35
+ img = tmp_path / "photo.jpg"
36
+ img.write_bytes(b"fake-image")
37
+ return pd.DataFrame({"filepath": [str(img)]})
38
+
39
+
40
+ @pytest.fixture
41
+ def video_manifest(tmp_path: Path) -> pd.DataFrame:
42
+ vid = tmp_path / "clip.mp4"
43
+ vid.write_bytes(b"fake-video")
44
+ return pd.DataFrame({"filepath": [str(vid)]})
45
+
46
+
47
+ # ---------------------------------------------------------------------------
48
+ # get_images / get_videos
49
+ # ---------------------------------------------------------------------------
50
+
51
+ def test_get_images_returns_only_images(mixed_manifest: pd.DataFrame):
52
+ images = get_images(mixed_manifest)
53
+ assert not images.empty
54
+ assert all(
55
+ Path(p).suffix.lower() in file_management.IMAGE_EXTENSIONS
56
+ for p in images["filepath"]
57
+ )
58
+
59
+
60
+ def test_get_images_assigns_frame_zero(image_manifest: pd.DataFrame):
61
+ images = get_images(image_manifest)
62
+ assert list(images["frame"]) == [0]
63
+
64
+
65
+ def test_get_videos_returns_only_videos(mixed_manifest: pd.DataFrame):
66
+ videos = get_videos(mixed_manifest)
67
+ assert not videos.empty
68
+ assert all(
69
+ Path(p).suffix.lower() in file_management.VIDEO_EXTENSIONS
70
+ for p in videos["filepath"]
71
+ )
72
+
73
+
74
+ def test_get_images_empty_when_no_images(video_manifest: pd.DataFrame):
75
+ images = get_images(video_manifest)
76
+ assert images.empty
77
+
78
+
79
+ def test_get_videos_empty_when_no_videos(image_manifest: pd.DataFrame):
80
+ videos = get_videos(image_manifest)
81
+ assert videos.empty
82
+
83
+
84
+ # ---------------------------------------------------------------------------
85
+ # extract_frames
86
+ # ---------------------------------------------------------------------------
87
+
88
+ def test_extract_frames_raises_without_fps_and_frames(mixed_manifest: pd.DataFrame):
89
+ with pytest.raises(AssertionError):
90
+ extract_frames(mixed_manifest, frames=None, fps=None)
91
+
92
+
93
+ def test_extract_frames_raises_missing_file_col(mixed_manifest: pd.DataFrame):
94
+ with pytest.raises(ValueError):
95
+ extract_frames(mixed_manifest, frames=3, file_col="nonexistent_col")
96
+
97
+
98
+ def test_extract_frames_images_only_returns_manifest(image_manifest: pd.DataFrame):
99
+ result = extract_frames(image_manifest, frames=3)
100
+ assert isinstance(result, pd.DataFrame)
101
+ assert "filepath" in result.columns
102
+ assert "frame" in result.columns
103
+ assert list(result["frame"]) == [0]
104
+
105
+
106
+ def test_extract_frames_includes_videos(video_manifest: pd.DataFrame):
107
+ result = extract_frames(video_manifest, frames=3, parallel=False)
108
+ assert isinstance(result, pd.DataFrame)
109
+ assert "frame" in result.columns
110
+
111
+
112
+ def test_extract_frames_saves_to_file(tmp_path: Path, image_manifest: pd.DataFrame):
113
+ out = tmp_path / "frames.csv"
114
+ result = extract_frames(image_manifest, frames=1, out_file=str(out))
115
+ assert out.exists()
116
+ assert isinstance(result, pd.DataFrame)
117
+
118
+
119
+ # ---------------------------------------------------------------------------
120
+ # _count_frames
121
+ # ---------------------------------------------------------------------------
122
+
123
+ def test_count_frames_missing_file_raises(tmp_path: Path):
124
+ with pytest.raises(FileNotFoundError):
125
+ _count_frames(str(tmp_path / "nonexistent.mp4"), frames=5)
126
+
127
+
128
+ def test_count_frames_invalid_file_returns_none(tmp_path: Path):
129
+ """Test that _count_frames returns None for invalid/corrupted video files."""
130
+ vid = tmp_path / "clip.mp4"
131
+ vid.write_bytes(b"fake")
132
+ result = _count_frames(str(vid), frames=3)
133
+ assert result is None
134
+
135
+
136
+ def test_count_frames_with_fps_invalid_file_returns_none(tmp_path: Path):
137
+ """Test that _count_frames returns None for invalid files even with fps parameter."""
138
+ vid = tmp_path / "clip.mp4"
139
+ vid.write_bytes(b"fake")
140
+ result = _count_frames(str(vid), fps=2)
141
+ assert result is None
142
+
143
+
144
+ def test_count_frames_with_frames_parameter_returns_list(tmp_path: Path):
145
+ """Test that _count_frames returns a list of frame pairs when using frames parameter."""
146
+ vid = tmp_path / "clip.mp4"
147
+ vid.write_bytes(b"fake")
148
+
149
+ mock_cap = MagicMock()
150
+ mock_cap.isOpened.return_value = True
151
+ mock_cap.get.side_effect = lambda prop: {
152
+ cv2.CAP_PROP_FRAME_COUNT: 100.0,
153
+ }.get(prop, 30.0)
154
+
155
+ with patch("cv2.VideoCapture", return_value=mock_cap):
156
+ result = _count_frames(str(vid), frames=3)
157
+
158
+ assert result is not None
159
+ assert isinstance(result, list)
160
+ assert len(result) == 3
161
+ for pair in result:
162
+ assert len(pair) == 2
163
+ assert pair[0] == str(vid)
164
+ assert isinstance(pair[1], int)
165
+
166
+
167
+ def test_count_frames_with_fps_parameter_returns_list(tmp_path: Path):
168
+ """Test that _count_frames returns a list of frame pairs when using fps parameter."""
169
+ vid = tmp_path / "clip.mp4"
170
+ vid.write_bytes(b"fake")
171
+
172
+ mock_cap = MagicMock()
173
+ mock_cap.isOpened.return_value = True
174
+ mock_cap.get.side_effect = lambda prop: {
175
+ cv2.CAP_PROP_FRAME_COUNT: 300.0, # 10 seconds at 30 fps
176
+ cv2.CAP_PROP_FPS: 30.0,
177
+ }.get(prop, 30.0)
178
+
179
+ with patch("cv2.VideoCapture", return_value=mock_cap):
180
+ result = _count_frames(str(vid), fps=2)
181
+
182
+ assert result is not None
183
+ assert isinstance(result, list)
184
+ assert len(result) > 0
185
+ for pair in result:
186
+ assert len(pair) == 2
187
+ assert pair[0] == str(vid)
188
+ assert isinstance(pair[1], int)
189
+
190
+
191
+ def test_count_frames_corrupted_video_returns_none(tmp_path: Path):
192
+ """Test that _count_frames returns None when VideoCapture fails to open."""
193
+ vid = tmp_path / "corrupted.mp4"
194
+ vid.write_bytes(b"fake")
195
+
196
+ mock_cap = MagicMock()
197
+ mock_cap.isOpened.return_value = False
198
+
199
+ with patch("cv2.VideoCapture", return_value=mock_cap):
200
+ result = _count_frames(str(vid), frames=5)
201
+
202
+ assert result is None
203
+
204
+
205
+ def test_count_frames_zero_frame_count_returns_none(tmp_path: Path):
206
+ """Test that _count_frames returns None when frame count is 0."""
207
+ vid = tmp_path / "empty.mp4"
208
+ vid.write_bytes(b"fake")
209
+
210
+ mock_cap = MagicMock()
211
+ mock_cap.isOpened.return_value = True
212
+ mock_cap.get.side_effect = lambda prop: {
213
+ cv2.CAP_PROP_FRAME_COUNT: 0.0, # No frames
214
+ }.get(prop, 30.0)
215
+
216
+ with patch("cv2.VideoCapture", return_value=mock_cap):
217
+ result = _count_frames(str(vid), frames=5)
218
+
219
+ assert result is None
220
+
221
+
222
+ def test_count_frames_fps_zero_falls_back_to_default(tmp_path: Path):
223
+ """Test that _count_frames handles fps=0 by falling back to ffmpeg or default."""
224
+ vid = tmp_path / "clip.mp4"
225
+ vid.write_bytes(b"fake")
226
+
227
+ mock_cap = MagicMock()
228
+ mock_cap.isOpened.return_value = True
229
+ mock_cap.get.side_effect = lambda prop: {
230
+ cv2.CAP_PROP_FRAME_COUNT: 300.0,
231
+ cv2.CAP_PROP_FPS: 0.0, # fps detection fails
232
+ }.get(prop, 0.0)
233
+
234
+ with patch("cv2.VideoCapture", return_value=mock_cap):
235
+ with patch("animl.video_processing.get_fps_from_ffmpeg", return_value=None):
236
+ result = _count_frames(str(vid), fps=2)
237
+
238
+ assert result is not None
239
+ assert isinstance(result, list)
240
+
241
+
242
+ def test_count_frames_frame_indices_within_bounds(tmp_path: Path):
243
+ """Test that returned frame indices are within the valid range."""
244
+ vid = tmp_path / "clip.mp4"
245
+ vid.write_bytes(b"fake")
246
+
247
+ frame_count = 100
248
+ mock_cap = MagicMock()
249
+ mock_cap.isOpened.return_value = True
250
+ mock_cap.get.side_effect = lambda prop: {
251
+ cv2.CAP_PROP_FRAME_COUNT: float(frame_count),
252
+ }.get(prop, 30.0)
253
+
254
+ with patch("cv2.VideoCapture", return_value=mock_cap):
255
+ result = _count_frames(str(vid), frames=5)
256
+
257
+ assert result is not None
258
+ for pair in result:
259
+ frame_idx = pair[1]
260
+ assert 0 <= frame_idx < frame_count
File without changes
File without changes