animl-lite 3.1.0__py3-none-any.whl

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.
animl/__init__.py ADDED
@@ -0,0 +1,68 @@
1
+ __version__ = '3.1.0'
2
+ from animl import classification
3
+ from animl import detection
4
+ from animl import export
5
+ from animl import file_management
6
+ from animl import generator
7
+ from animl import pipeline
8
+ from animl import reid
9
+ from animl import split
10
+ from animl import utils
11
+ from animl import video_processing
12
+
13
+ from animl.classification import (SDZWA_CLASSIFIER_SIZE, classify,
14
+ load_class_list, load_classifier,
15
+ sequence_classification,
16
+ single_classification,)
17
+ from animl.detection import (MEGADETECTORv5_SIZE, convert_onnx_detections,
18
+ detect, load_detector, parse_detections,)
19
+ from animl.export import (export_coco, export_folders, export_megadetector,
20
+ export_timelapse, remove_link,
21
+ update_labels_from_folders,)
22
+ from animl.file_management import (IMAGE_EXTENSIONS, VALID_EXTENSIONS,
23
+ VIDEO_EXTENSIONS, WorkingDirectory,
24
+ active_times, build_file_manifest,
25
+ check_file, load_data, load_json, save_data,
26
+ save_detection_checkpoint, save_json,)
27
+ from animl.generator import (Letterbox, ManifestGenerator, Normalize,
28
+ manifest_dataloader, pil_to_numpy_array,)
29
+ from animl.pipeline import (from_config, from_paths,)
30
+ from animl.reid import (compute_batched_distance_matrix,
31
+ compute_distance_matrix, cosine_distance, distance,
32
+ euclidean_squared_distance, extract_miew_embeddings,
33
+ inference, load_miew, remove_diagonal,)
34
+ from animl.split import (get_animals, get_empty, train_val_test,)
35
+ from animl.utils import (MD_COLORS, MD_LABELS, clip_coords,
36
+ convert_minxywh_to_absxyxy, general, get_device,
37
+ letterbox, normalize_boxes, plot_all_bounding_boxes,
38
+ plot_box, plot_from_file, scale_letterbox, softmax,
39
+ tensor_to_onnx, visualization, xyn2xy, xywh2xyxy,
40
+ xywhc2xyxy, xywhn2xyxy, xyxy2xywh, xyxyc2xywh,
41
+ xyxyc2xywhn,)
42
+ from animl.video_processing import (count_frames, extract_frames,
43
+ get_frame_as_image,)
44
+
45
+ __all__ = ['IMAGE_EXTENSIONS', 'Letterbox', 'MD_COLORS', 'MD_LABELS',
46
+ 'MEGADETECTORv5_SIZE', 'ManifestGenerator', 'Normalize',
47
+ 'SDZWA_CLASSIFIER_SIZE', 'VALID_EXTENSIONS', 'VIDEO_EXTENSIONS',
48
+ 'WorkingDirectory', 'active_times', 'build_file_manifest',
49
+ 'check_file', 'classification', 'classify', 'clip_coords',
50
+ 'compute_batched_distance_matrix', 'compute_distance_matrix',
51
+ 'convert_minxywh_to_absxyxy', 'convert_onnx_detections',
52
+ 'cosine_distance', 'count_frames', 'detect', 'detection',
53
+ 'distance', 'euclidean_squared_distance', 'export', 'export_coco',
54
+ 'export_folders', 'export_megadetector', 'export_timelapse',
55
+ 'extract_frames', 'extract_miew_embeddings', 'file_management',
56
+ 'from_config', 'from_paths', 'general', 'generator', 'get_animals',
57
+ 'get_device', 'get_empty', 'get_frame_as_image', 'inference',
58
+ 'letterbox', 'load_class_list', 'load_classifier', 'load_data',
59
+ 'load_detector', 'load_json', 'load_miew', 'manifest_dataloader',
60
+ 'normalize_boxes', 'parse_detections', 'pil_to_numpy_array',
61
+ 'pipeline', 'plot_all_bounding_boxes', 'plot_box', 'plot_from_file',
62
+ 'reid', 'remove_diagonal', 'remove_link', 'save_data',
63
+ 'save_detection_checkpoint', 'save_json', 'scale_letterbox',
64
+ 'sequence_classification', 'single_classification', 'softmax',
65
+ 'split', 'tensor_to_onnx', 'train_val_test',
66
+ 'update_labels_from_folders', 'utils', 'video_processing',
67
+ 'visualization', 'xyn2xy', 'xywh2xyxy', 'xywhc2xyxy', 'xywhn2xyxy',
68
+ 'xyxy2xywh', 'xyxyc2xywh', 'xyxyc2xywhn']
animl/__main__.py ADDED
@@ -0,0 +1,70 @@
1
+ '''
2
+ Main script.
3
+
4
+ Runs full animl workflow on a given directory.
5
+ User must provide MegaDetector, Classifier, and Class list files,
6
+ otherwise will pull MDv5 and the CTL Southwest v2 models by default.
7
+
8
+ Usage example
9
+ > python -m animl /home/usr/animl-py/examples/Southwest/
10
+
11
+ OR
12
+
13
+ > python -m animl /image/dir megadetector.pt classifier.pt class_file.csv
14
+
15
+ Paths to model files must be edited to local machine.
16
+
17
+ @ Kyra Swanson, 2023
18
+ '''
19
+ import time
20
+ import argparse
21
+ from pathlib import Path
22
+
23
+ from animl import pipeline
24
+ import animl.models.download as models
25
+
26
+ # Start timer
27
+ start_time = time.time()
28
+
29
+ # IF RUN FROM COMMAND LINE
30
+ parser = argparse.ArgumentParser(description='Folder locations for the main script')
31
+ home = Path.cwd() / 'models'
32
+ # Create and parse arguements
33
+ parser.add_argument('imagedir_config', type=str,
34
+ help='Path to Image Directory or Config File')
35
+ parser.add_argument('--detector', type=str, nargs='?',
36
+ help='Path to MD model',
37
+ default=Path(home / 'md_v5a.0.0.pt'))
38
+ parser.add_argument('--classifier', type=str, nargs='?',
39
+ help='Path to Class model',
40
+ default=Path(home / 'sdzwa_southwest_v3.pt'))
41
+ parser.add_argument('--classlist', type=str, nargs='?',
42
+ help='Path to class list',
43
+ default=Path(home / 'sdzwa_southwest_v3_classes.csv'))
44
+ args = parser.parse_args()
45
+
46
+ # first argument is config file
47
+ if Path(args.imagedir_config).is_file():
48
+ pipeline.from_config(args.imagedir_config)
49
+
50
+ # first argument is a directory
51
+ else:
52
+ if not Path(args.detector).is_file():
53
+ prompt = "MegaDetector not found, would you like to download? y/n: "
54
+ if input(prompt).lower() == "y":
55
+ models.download_model(models.MEGADETECTOR['MDV5a'], out_dir=home)
56
+
57
+ if not Path(args.classifier).is_file():
58
+ prompt = "Classifier not found, would you like to download Southwest_v3? y/n: "
59
+ if input(prompt).lower() == "y":
60
+ models.download_model(models.CLASSIFIER['SDZWA_Southwest_v3'], out_dir=home)
61
+
62
+ if not Path(args.classlist).is_file():
63
+ prompt = "Class list not found, would you like to download Southwest_v3? y/n: "
64
+ if input(prompt).lower() == "y":
65
+ models.download_model(models.CLASS_LIST['SDZWA_Southwest_v3'], out_dir=home)
66
+
67
+ # Call the main function
68
+ pipeline.from_paths(args.imagedir_config, args.detector, args.classifier, args.classlist)
69
+
70
+ print(f"Pipeline took {time.time() - start_time:.2f} seconds")
@@ -0,0 +1,363 @@
1
+ '''
2
+ Tools for Saving, Loading, and Using Species Classifiers
3
+
4
+ @ Kyra Swanson 2023
5
+ '''
6
+ import json
7
+ from typing import Optional, Union
8
+ import pandas as pd
9
+ import numpy as np
10
+ from pathlib import Path
11
+ from time import time
12
+ from tqdm import tqdm
13
+ import onnxruntime
14
+
15
+ from animl import generator, file_management
16
+ from animl.utils.general import get_device, softmax
17
+
18
+
19
+ SDZWA_CLASSIFIER_SIZE = 299
20
+
21
+
22
+ def load_classifier(model_path: str,
23
+ classes: Union[int, str, Path, pd.DataFrame] = None):
24
+ '''
25
+ Creates a model instance and loads the latest model state weights.
26
+
27
+ Args:
28
+ model_path (str): file or directory path to model weights
29
+ classes (int | str | Path | pd.DataFrame): number of classes, path to associated class list, or pd.DataFrame of class list
30
+ device (str): specify to run on cpu or gpu
31
+ architecture (str): expected model architecture
32
+
33
+ Returns:
34
+ model: model object of given architecture with loaded weights
35
+ class_list: list of class names
36
+ '''
37
+ class_list = None
38
+ model_path = Path(model_path)
39
+ # check to make sure GPU is available if chosen
40
+ providers = get_device()
41
+
42
+ print(f'Loading model at {model_path}')
43
+ model = onnxruntime.InferenceSession(model_path, providers=providers)
44
+ model.framework = "onnx"
45
+
46
+ # get number of classes
47
+ if isinstance(classes, str) or isinstance(classes, Path):
48
+ class_list = load_class_list(classes)
49
+ elif isinstance(classes, pd.DataFrame):
50
+ class_list = classes
51
+ else:
52
+ class_list = None
53
+ # try to load class dict from metadata
54
+ props = model.get_modelmeta().custom_metadata_map
55
+ if "class_dict" in props:
56
+ print("Loaded class_dict from ONNX metadata.")
57
+ class_dict = json.loads(props["class_dict"])
58
+ class_list = [class_dict[str(i)] for i in range(len(class_dict))]
59
+ class_list = pd.DataFrame({'class': class_list})
60
+
61
+ # no need to return epoch
62
+ return model, class_list
63
+
64
+
65
+ def load_class_list(classlist_file):
66
+ """
67
+ Return classlist file as pd.DataFrame.
68
+
69
+ Args:
70
+ classlist_file (str): file path to class list
71
+
72
+ Returns:
73
+ pd.DataFrame of class list
74
+ """
75
+ if not Path(classlist_file).is_file():
76
+ raise FileNotFoundError(f"Class list file not found at {classlist_file}")
77
+ return pd.read_csv(classlist_file)
78
+
79
+
80
+ def classify(model,
81
+ detections,
82
+ resize_width: int = 480,
83
+ resize_height: int = 480,
84
+ file_col: str = 'filepath',
85
+ crop: bool = True,
86
+ normalize: bool = True,
87
+ out_file: Optional[str] = None):
88
+ """
89
+ Predict species using classifier model.
90
+
91
+ Args:
92
+ model: preloaded classifier model
93
+ detections (mult): dataframe of (animal) detections, list of filepaths or filepath str
94
+ resize_width (int): image width input size
95
+ resize_height (int): image height input size
96
+ file_col (str): column name containing file paths
97
+ crop (bool): use bbox to crop images before feeding into model
98
+ normalize (bool): normalize the tensor before inference
99
+ batch_size (int): data generator batch size
100
+ num_workers (int): number of cores
101
+ device (str): specify to run model on cpu or gpu, default to cpu
102
+ out_file (str): path to save prediction results to
103
+
104
+ Returns:
105
+ detections (pd.DataFrame): MD detections with classifier prediction and confidence
106
+ """
107
+ if file_management.check_file(out_file, output_type="Classification results"):
108
+ return file_management.load_data(out_file).to_numpy()
109
+
110
+ # initialize lists
111
+ raw_output = []
112
+
113
+ # Manifest
114
+ if isinstance(detections, pd.DataFrame):
115
+ if file_col not in detections.columns:
116
+ raise ValueError(f"file_col {file_col} not found in manifest columns")
117
+ # no frame column, assume all images and set to 0
118
+ if 'frame' not in detections.columns:
119
+ print("Warning: 'frame' column not found in manifest columns. Defaulting to 0 assuming images.")
120
+ detections['frame'] = 0
121
+
122
+ dataset = generator.manifest_dataloader(detections, file_col=file_col, crop=crop,
123
+ resize_width=resize_width, resize_height=resize_height,
124
+ normalize=normalize)
125
+ # Single File
126
+ elif isinstance(detections, str):
127
+ detections = pd.DataFrame({file_col: detections, 'frame': 0}, index=[0])
128
+ dataset = generator.manifest_dataloader(detections, file_col=file_col, crop=False,
129
+ resize_width=resize_width, resize_height=resize_height,
130
+ normalize=normalize)
131
+ # List of Files
132
+ elif isinstance(detections, list):
133
+ detections = pd.DataFrame({file_col: detections, 'frame': 0}, index=range(len(detections)))
134
+ dataset = generator.manifest_dataloader(detections, file_col=file_col, crop=False,
135
+ resize_width=resize_width, resize_height=resize_height,
136
+ normalize=normalize)
137
+ else:
138
+ raise AssertionError("Input must be a data frame of crops, single file path or vector of file paths.")
139
+
140
+ # Predict
141
+ start_time = time()
142
+ for _, batch in tqdm(enumerate(dataset), total=len(detections)):
143
+ image = batch[0]
144
+ output = model.run(None, {model.get_inputs()[0].name: image})[0]
145
+ raw_output.extend(softmax(output))
146
+
147
+ raw_output = np.vstack(raw_output)
148
+
149
+ if out_file:
150
+ file_management.save_data(pd.DataFrame(raw_output), out_file)
151
+
152
+ print(f"\nFinished classification. Total images processed: {len(raw_output)} at {round(len(raw_output)/(time() - start_time), 1)} img/s.")
153
+
154
+ return raw_output
155
+
156
+
157
+ def single_classification(animals: pd.DataFrame,
158
+ empty: Optional[pd.DataFrame],
159
+ predictions_raw: np.array,
160
+ class_list: pd.DataFrame):
161
+ """
162
+ Get maximum likelihood prediction from softmaxed logits.
163
+
164
+ Args:
165
+ animals (pd.DataFrame): animal detections from manifest
166
+ predictions_raw (np.array): softmaxed logits from classify()
167
+ class_list (pd.DataFrame): class list associated with model
168
+
169
+ Returns:
170
+ animals dataframe with "prediction" label an "confidence" columns
171
+ """
172
+ class_list = pd.Series(class_list)
173
+
174
+ if not animals.empty:
175
+ files = animals.groupby('filepath')
176
+ updated_files = []
177
+ for f, file in files:
178
+ preds = predictions_raw[file.index]
179
+ preds = np.mean(preds, axis=0)
180
+ file["prediction"] = class_list[np.argmax(preds)]
181
+ file["confidence"] = np.max(file["conf"]) * np.max(preds)
182
+ updated_files.append(file)
183
+
184
+ animals = pd.concat(updated_files, ignore_index=True)
185
+
186
+ manifest = pd.concat([animals if not animals.empty else None, empty if not empty.empty else None]).reset_index(drop=True)
187
+
188
+ # remove empties from videos
189
+ files = manifest.groupby('filepath')
190
+ for f, file in files:
191
+ if file['extension'].iloc[0] in file_management.VIDEO_EXTENSIONS:
192
+ predictions = file['prediction'].unique()
193
+ if 'empty' in predictions and len(predictions) > 1:
194
+ real_prediction = predictions[predictions != 'empty'][0]
195
+ manifest.loc[manifest['filepath'] == f, 'prediction'] = real_prediction
196
+
197
+ return manifest
198
+
199
+
200
+ def sequence_classification(animals: pd.DataFrame,
201
+ empty: Optional[pd.DataFrame],
202
+ predictions_raw: np.array,
203
+ class_list: pd.DataFrame,
204
+ station_col: str,
205
+ empty_class: str = "",
206
+ sort_columns: list[str] = None,
207
+ file_col: str = "filepath",
208
+ maxdiff: int = 60):
209
+ """
210
+ Applies class labels to images based on sequential information.
211
+
212
+ This function applies image classifications at a sequence level by leveraging information from
213
+ multiple images. A sequence is defined as all images at the same camera and station where the
214
+ time between consecutive images is <=maxdiff. This can improve classification accuracy, but
215
+ assumes that only one species is present in each sequence. If you regularly expect multiple
216
+ species to occur in an image or sequence don't use this function.
217
+
218
+ Args:
219
+ animals (pd.DataFrame): Sub-selection of all images that contain animals
220
+ empty (Optional) (pd.DataFrame): Sub-selection of all images that do not contain animals
221
+ predictions_raw (Numpy Array of Numpy Arrays): Logits of all entries in "animals"
222
+ class_list (pd.DataFrame): class list associated with classifier model
223
+ station_col (str): The name of the station column
224
+ empty_class (str) (Optional): the name of class_list 'empty' label
225
+ sort_columns (List of Strings): Defines sorting order for the DataFrame
226
+ file_col (str): The name of the filepath column
227
+ maxdiff (int): Maximum time difference in seconds between any two images in a sequence
228
+
229
+ Returns:
230
+ final_df (pd.DataFrame): Sequence classified data from both animals and empty
231
+
232
+ Raises:
233
+ Exception: If 'sort_columns' is not a list or is empty
234
+ Exception: If 'station_col' is not a string or is empty
235
+ Exception: If 'empty' is defined and is not a pandas DataFrame
236
+ Exception: If maxdiff is defined and is not a positive number
237
+ """
238
+ if not isinstance(station_col, str) or station_col == '':
239
+ raise Exception("'station_col' must be a non-empty string")
240
+
241
+ # Sanity check to verify that empty is a Pandas DataFrame, if defined
242
+ if empty is not None and not isinstance(animals, pd.DataFrame):
243
+ raise Exception("'empty' must be a DataFrame")
244
+
245
+ # Sanity check to verify that maxdiff is a positive number
246
+ if not isinstance(maxdiff, (int, float)) or maxdiff < 0:
247
+ raise Exception("'maxdiff' must be a number >= 0")
248
+
249
+ if not {file_col}.issubset(animals.columns):
250
+ raise ValueError(f"DataFrame must contain '{file_col}' column.")
251
+
252
+ if "conf" not in animals.columns:
253
+ animals["conf"] = 1
254
+
255
+ if empty_class > "":
256
+ empty_col = class_list[class_list == empty_class].index[0]
257
+ else:
258
+ empty_col = None
259
+
260
+ if empty is not None or not empty.empty:
261
+ empty["ID"] = range(0, empty.shape[0])
262
+ predempty = empty.pivot(index="ID", columns="prediction", values="confidence")
263
+ # Replace NaN with 0
264
+ predempty = predempty.fillna(0)
265
+ predempty = pd.concat([pd.DataFrame(np.zeros((empty.shape[0], len(class_list)))), predempty], axis=1)
266
+
267
+ if empty_class > "":
268
+ if 'empty' in predempty.columns:
269
+ predempty[empty_col] = predempty["empty"]
270
+ predempty = predempty.drop("empty", axis=1)
271
+ class_list = pd.concat([class_list,
272
+ pd.Series([x for x in empty["prediction"].unique() if x != "empty"])], ignore_index=True)
273
+
274
+ else:
275
+ class_list = pd.concat([class_list, pd.Series(empty["prediction"].unique())], ignore_index=True)
276
+ empty_col = predempty.columns.get_loc("empty")
277
+
278
+ # placeholders
279
+ animals["prediction"] = list(class_list[np.argmax(predictions_raw, axis=1)])
280
+ animals["confidence"] = animals["conf"].mul(np.max(predictions_raw, axis=1))
281
+
282
+ empty["conf"] = 1
283
+ animals_merged = pd.concat([animals, empty.iloc[:, :-1]]).reset_index(drop=True) # dont add ID column
284
+ predictions = np.hstack((predictions_raw,
285
+ np.zeros((predictions_raw.shape[0], len(predempty.columns) - predictions_raw.shape[1]))))
286
+ # concat
287
+ predictions = np.vstack((predictions, np.array(predempty)))
288
+
289
+ if sort_columns is None:
290
+ sort_columns = [station_col, "datetime"]
291
+
292
+ animals_merged['filemodifydate'] = pd.to_datetime(animals_merged['filemodifydate'], format="%Y-%m-%d %H:%M:%S")
293
+
294
+ sort = animals_merged.sort_values(by=sort_columns).index
295
+ animals_sort = animals_merged.loc[sort].reset_index(drop=True)
296
+ predsort = predictions[sort]
297
+
298
+ conf_placeholder = np.zeros(len(animals_sort))
299
+ predict_placeholder = np.empty(len(animals_sort), dtype='U30')
300
+ sequence_placeholder = np.zeros(len(animals_sort))
301
+
302
+ i = 0
303
+ s = 0
304
+ while i < len(animals_sort):
305
+ rows = [i]
306
+ last_index = i+1
307
+
308
+ while (last_index < len(animals_sort) and not pd.isna(animals_sort.loc[i, "datetime"]) and
309
+ not pd.isna(animals_sort.loc[last_index, "datetime"]) and
310
+ animals_sort.loc[last_index, station_col] == animals_sort.loc[i, station_col] and
311
+ (animals_sort.loc[last_index, "filemodifydate"] - animals_sort.loc[i, "filemodifydate"]).total_seconds() <= maxdiff):
312
+ rows.append(last_index)
313
+ last_index += 1
314
+
315
+ rows = np.array(rows)
316
+
317
+ # multiple detections in sequence
318
+ if len(rows) > 1:
319
+ predclass = np.argmax(predsort[rows], axis=1)
320
+
321
+ # no empties
322
+ if empty_col is None or empty_col not in predclass:
323
+ predsort_confidence = predsort[rows] * np.reshape(animals_sort.loc[rows, 'conf'].values, (-1, 1))
324
+ predbest = np.mean(predsort_confidence, axis=0)
325
+ conf_placeholder[rows] = np.max(predsort_confidence[:, np.argmax(predbest)])
326
+ predict_placeholder[rows] = class_list[np.argmax(predbest)]
327
+
328
+ else:
329
+ mask = pd.DataFrame((predclass == empty_col))
330
+ filtered_animals = animals_sort.loc[rows, file_col].reset_index(drop=True)
331
+ sum_values = mask.groupby(filtered_animals).sum()
332
+ count_values = mask.groupby(filtered_animals).count()
333
+
334
+ sel_all_empty = count_values == sum_values
335
+ sel_mixed = np.where(filtered_animals.isin(sel_all_empty[~sel_all_empty[0]].index))[0]
336
+ sel_no_empties = np.where(filtered_animals.isin(sel_all_empty[~sel_all_empty[0]].index) & (predclass != empty_col))[0]
337
+
338
+ if len(sel_mixed) > 0 and len(sel_no_empties) > 0:
339
+ predsort_confidence = predsort[rows[sel_no_empties]] * np.reshape(animals_sort.loc[rows[sel_no_empties], 'conf'].values, (-1, 1))
340
+ predbest = np.mean(predsort_confidence, axis=0)
341
+ conf_placeholder[rows[sel_mixed]] = np.max(predsort_confidence[:, np.argmax(predbest)])
342
+ predict_placeholder[rows[sel_mixed]] = class_list[np.argmax(predbest)]
343
+
344
+ for file in sel_all_empty[sel_all_empty[0]].index:
345
+ empty_row = np.where(animals_sort[file_col] == file)
346
+ predsort_confidence = predsort[empty_row] * np.reshape(animals_sort.loc[empty_row, 'conf'].values, (-1, 1))
347
+ predbest = np.mean(predsort_confidence, axis=0)
348
+ conf_placeholder[empty_row] = np.max(predsort_confidence[:, np.argmax(predbest)])
349
+ predict_placeholder[empty_row] = class_list[np.argmax(predbest)]
350
+ # single row in sequence
351
+ else:
352
+ predbest = predsort[rows]
353
+ conf_placeholder[rows] = np.max(predbest * animals_sort.loc[rows, 'conf'].values)
354
+ predict_placeholder[rows] = class_list[np.argmax(predbest)]
355
+
356
+ i = last_index
357
+ s += 1
358
+
359
+ animals_sort['confidence'] = conf_placeholder
360
+ animals_sort['prediction'] = predict_placeholder
361
+ animals_sort['sequence'] = sequence_placeholder
362
+
363
+ return animals_sort