-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathslp.py
More file actions
2005 lines (1698 loc) · 72.6 KB
/
Copy pathslp.py
File metadata and controls
2005 lines (1698 loc) · 72.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""This module handles direct I/O operations for working with .slp files.
Format version history:
- 1.0: Initial format
- 1.1: Changed coordinate system from top-left pixel at (0, 0) to center at (0, 0)
- 1.2: Added tracking_score field to instances
- 1.3: Added explicit handling for tracking_score
- 1.4: Added channel_order attribute to embedded video datasets to track RGB vs BGR
"""
from __future__ import annotations
import sys
from enum import Enum, IntEnum
from pathlib import Path
from typing import TYPE_CHECKING, Optional, Union
import h5py
import imageio.v3 as iio
import numpy as np
import simplejson as json
from tqdm import tqdm
from sleap_io.io.skeleton import SkeletonSLPDecoder, SkeletonSLPEncoder
from sleap_io.io.utils import (
is_file_accessible,
read_hdf5_attrs,
read_hdf5_dataset,
sanitize_filename,
)
from sleap_io.io.video_reading import (
HDF5Video,
ImageVideo,
MediaVideo,
TiffVideo,
VideoBackend,
)
from sleap_io.model.camera import (
Camera,
CameraGroup,
FrameGroup,
InstanceGroup,
RecordingSession,
)
from sleap_io.model.instance import Instance, PredictedInstance, Track
from sleap_io.model.labeled_frame import LabeledFrame
from sleap_io.model.labels import Labels
from sleap_io.model.skeleton import Skeleton
from sleap_io.model.suggestions import SuggestionFrame
from sleap_io.model.video import Video
if TYPE_CHECKING:
from sleap_io.model.labels_set import LabelsSet
try:
import cv2
except ImportError:
pass
class VideoReferenceMode(Enum):
"""How to handle video references when saving."""
EMBED = "embed" # Embed frames in the file
RESTORE_ORIGINAL = "restore_original" # Use original video if available
PRESERVE_SOURCE = "preserve_source" # Keep reference to source file (.pkg.slp)
class InstanceType(IntEnum):
"""Enumeration of instance types to integers."""
USER = 0
PREDICTED = 1
def make_video(
labels_path: str,
video_json: dict,
open_backend: bool = True,
) -> Video:
"""Create a `Video` object from a JSON dictionary.
Args:
labels_path: A string path to the SLEAP labels file.
video_json: A dictionary containing the video metadata.
open_backend: If `True` (the default), attempt to open the video backend for
I/O. If `False`, the backend will not be opened (useful for reading metadata
when the video files are not available).
"""
backend_metadata = video_json["backend"]
video_path = backend_metadata["filename"]
# Marker for embedded videos.
source_video = None
is_embedded = False
if video_path == ".":
video_path = labels_path
is_embedded = True
# Basic path resolution.
video_path = Path(sanitize_filename(video_path))
original_video = None
if is_embedded:
# Try to recover the source video and original video from HDF5 attrs.
with h5py.File(labels_path, "r") as f:
dataset = backend_metadata["dataset"]
if dataset.endswith("/video"):
dataset = dataset[:-6]
# Load source_video metadata
if dataset in f and "source_video" in f[dataset]:
source_video_json = json.loads(
f[f"{dataset}/source_video"].attrs["json"]
)
source_video = make_video(
labels_path,
source_video_json,
open_backend=open_backend,
)
# Load original_video metadata
if f"{dataset}/original_video" in f:
original_video_json = json.loads(
f[f"{dataset}/original_video"].attrs["json"]
)
original_video = make_video(
labels_path,
original_video_json,
open_backend=False, # Original videos are often not available
)
else:
# For non-embedded videos, check if metadata is in videos_json
if "source_video" in video_json:
source_video = make_video(
labels_path,
video_json["source_video"],
open_backend=open_backend,
)
if "original_video" in video_json:
original_video = make_video(
labels_path,
video_json["original_video"],
open_backend=False, # Original videos are often not available
)
backend = None
if open_backend:
try:
if not is_file_accessible(video_path):
# Check for the same filename in the same directory as the labels file.
candidate_video_path = Path(labels_path).parent / video_path.name
if is_file_accessible(candidate_video_path):
video_path = candidate_video_path
else:
# TODO (TP): Expand capabilities of path resolution to support more
# complex path finding strategies.
pass
except (OSError, PermissionError, FileNotFoundError):
pass
# Convert video path to string.
video_path = video_path.as_posix()
if "filenames" in backend_metadata:
# This is an ImageVideo.
# TODO: Path resolution.
video_path = backend_metadata["filenames"]
video_path = [Path(sanitize_filename(p)) for p in video_path]
try:
grayscale = None
if "grayscale" in backend_metadata:
grayscale = backend_metadata["grayscale"]
elif "shape" in backend_metadata:
grayscale = backend_metadata["shape"][-1] == 1
backend = VideoBackend.from_filename(
video_path,
dataset=backend_metadata.get("dataset", None),
grayscale=grayscale,
input_format=backend_metadata.get("input_format", None),
format=backend_metadata.get("format", None),
)
except Exception:
backend = None
return Video(
filename=video_path,
backend=backend,
backend_metadata=backend_metadata,
source_video=source_video,
original_video=original_video,
open_backend=open_backend,
)
def read_videos(labels_path: str, open_backend: bool = True) -> list[Video]:
"""Read `Video` dataset in a SLEAP labels file.
Args:
labels_path: A string path to the SLEAP labels file.
open_backend: If `True` (the default), attempt to open the video backend for
I/O. If `False`, the backend will not be opened (useful for reading metadata
when the video files are not available).
Returns:
A list of `Video` objects.
"""
videos = []
videos_metadata = read_hdf5_dataset(labels_path, "videos_json")
for video_data in videos_metadata:
video_json = json.loads(video_data)
video = make_video(labels_path, video_json, open_backend=open_backend)
videos.append(video)
return videos
def video_to_dict(video: Video, labels_path: Optional[str] = None) -> dict:
"""Convert a `Video` object to a JSON-compatible dictionary.
Args:
video: A `Video` object to convert.
labels_path: Path to the labels file being written. Used to determine if the
video should use a self-reference (".") or external reference.
Returns:
A dictionary containing the video metadata.
"""
video_filename = sanitize_filename(video.filename)
result = {"filename": video_filename}
# Add backend metadata
if video.backend is None:
result["backend"] = video.backend_metadata
elif type(video.backend) is MediaVideo:
result["backend"] = {
"type": "MediaVideo",
"shape": video.shape,
"filename": video_filename,
"grayscale": video.grayscale,
"bgr": True,
"dataset": "",
"input_format": "",
}
elif type(video.backend) is HDF5Video:
# Determine if we should use self-reference or external reference
use_self_reference = (
video.backend.has_embedded_images
and labels_path is not None
and Path(sanitize_filename(video.filename)).resolve()
== Path(sanitize_filename(labels_path)).resolve()
)
result["backend"] = {
"type": "HDF5Video",
"shape": video.shape,
"filename": ("." if use_self_reference else video_filename),
"dataset": video.backend.dataset,
"input_format": video.backend.input_format,
"convert_range": False,
"has_embedded_images": video.backend.has_embedded_images,
"grayscale": video.grayscale,
}
elif type(video.backend) is ImageVideo:
if video.shape is not None:
height, width, channels = video.shape[1:4]
else:
height, width, channels = None, None, 3
result["backend"] = {
"type": "ImageVideo",
"shape": video.shape,
"filename": sanitize_filename(video.backend.filename[0]),
"filenames": sanitize_filename(video.backend.filename),
"height_": height,
"width_": width,
"channels_": channels,
"grayscale": video.grayscale,
}
elif type(video.backend) is TiffVideo:
result["backend"] = {
"type": "TiffVideo",
"shape": video.shape,
"filename": video_filename,
"grayscale": video.grayscale,
"keep_open": video.backend.keep_open,
"format": video.backend.format,
}
# Add source_video metadata if present
if hasattr(video, "source_video") and video.source_video is not None:
result["source_video"] = video_to_dict(video.source_video, labels_path)
# Add original_video metadata if present
if hasattr(video, "original_video") and video.original_video is not None:
result["original_video"] = video_to_dict(video.original_video, labels_path)
return result
def prepare_frames_to_embed(
labels_path: str,
labels: Labels,
frames_to_embed: list[tuple[Video, int]],
) -> list[dict]:
"""Prepare frames to embed by gathering all metadata needed for embedding.
Args:
labels_path: A string path to the SLEAP labels file.
labels: A `Labels` object containing the videos.
frames_to_embed: A list of tuples of `(video, frame_idx)` specifying the
frames to embed.
Returns:
A list of dictionaries, each containing metadata for a frame to embed:
- video: The Video object
- frame_idx: The index of the frame to embed
- video_ind: The index of the video in labels.videos
- group: The HDF5 group to store the embedded data in
"""
# First, group frames by video
to_embed_by_video = {}
for video, frame_idx in frames_to_embed:
if video not in to_embed_by_video:
to_embed_by_video[video] = []
to_embed_by_video[video].append(frame_idx)
# Remove duplicates and sort
for video in to_embed_by_video:
to_embed_by_video[video] = sorted(list(set(to_embed_by_video[video])))
# Create a list of frame metadata for embedding
frames_metadata = []
for video, frame_inds in to_embed_by_video.items():
video_ind = labels.videos.index(video)
group = f"video{video_ind}"
for frame_idx in frame_inds:
frames_metadata.append(
{
"video": video,
"frame_idx": frame_idx,
"video_ind": video_ind,
"group": group,
}
)
return frames_metadata
def process_and_embed_frames(
labels_path: str,
frames_metadata: list[dict],
image_format: str = "png",
fixed_length: bool = True,
verbose: bool = True,
plugin: Optional[str] = None,
) -> dict[Video, Video]:
"""Process and embed frames into a SLEAP labels file.
This function loads, encodes, and writes frames to the HDF5 file in a single loop,
making it easier to add progress monitoring.
Args:
labels_path: A string path to the SLEAP labels file.
frames_metadata: A list of dictionaries with frame metadata from
prepare_frames_to_embed.
image_format: The image format to use for embedding. Valid formats are "png"
(the default), "jpg" or "hdf5".
fixed_length: If `True` (the default), the embedded images will be padded to the
length of the largest image. If `False`, the images will be stored as
variable length, which is smaller but may not be supported by all readers.
verbose: If `True` (the default), display a progress bar for the embedding
process.
plugin: Image plugin to use for encoding. One of "opencv" or "imageio".
If None, uses the global default from `get_default_image_plugin()`.
If no global default is set, auto-detects based on available packages.
Returns:
A dictionary mapping original Video objects to their embedded versions.
"""
# Determine which plugin to use for encoding
from sleap_io.io.video_reading import get_default_image_plugin
if plugin is None:
plugin = get_default_image_plugin()
if plugin is None:
# Auto-detect: prefer opencv, fallback to imageio
plugin = "opencv" if "cv2" in sys.modules else "imageio"
# Initialize a dictionary to store data by group
data_by_group = {}
# Process all frames in a single flat loop with progress bar if verbose
frame_iter = (
tqdm(frames_metadata, desc="Embedding frames", disable=not verbose)
if verbose
else frames_metadata
)
for frame_meta in frame_iter:
video = frame_meta["video"]
frame_idx = frame_meta["frame_idx"]
group = frame_meta["group"]
# Initialize group data structure if this is the first frame for this group
if group not in data_by_group:
data_by_group[group] = {
"video": video, # All frames in a group are from the same video
"frame_inds": [],
"imgs_data": [],
"channel_order": None, # Track channel order: "RGB" or "BGR"
}
# Load the frame
frame = video[frame_idx]
# Encode the frame
if image_format == "hdf5":
img_data = frame
channel_order = "RGB" # HDF5 format stores as-is (RGB)
else:
if plugin == "opencv":
img_data = np.squeeze(
cv2.imencode("." + image_format, frame)[1]
).astype("int8")
channel_order = "BGR" # OpenCV encodes in BGR
else: # imageio
if frame.shape[-1] == 1:
frame = frame.squeeze(axis=-1)
img_data = np.frombuffer(
iio.imwrite("<bytes>", frame, extension="." + image_format),
dtype="int8",
)
channel_order = "RGB" # imageio encodes in RGB
# Store channel order (should be consistent for all frames in a group)
if data_by_group[group]["channel_order"] is None:
data_by_group[group]["channel_order"] = channel_order
# Store frame data in the appropriate group
data_by_group[group]["imgs_data"].append(img_data)
data_by_group[group]["frame_inds"].append(frame_idx)
# Write all frame data to the HDF5 file
replaced_videos = {}
with h5py.File(labels_path, "a") as f:
for group, data in data_by_group.items():
video = data["video"]
frame_inds = data["frame_inds"]
imgs_data = data["imgs_data"]
if image_format == "hdf5":
f.create_dataset(
f"{group}/video", data=imgs_data, compression="gzip", chunks=True
)
ds = f[f"{group}/video"]
else:
if fixed_length:
img_bytes_len = 0
for img in imgs_data:
img_bytes_len = max(img_bytes_len, len(img))
ds = f.create_dataset(
f"{group}/video",
shape=(len(imgs_data), img_bytes_len),
dtype="int8",
compression="gzip",
)
for i, img in enumerate(imgs_data):
ds[i, : len(img)] = img
else:
ds = f.create_dataset(
f"{group}/video",
shape=(len(imgs_data),),
dtype=h5py.special_dtype(vlen=np.dtype("int8")),
)
for i, img in enumerate(imgs_data):
ds[i] = img
# Store metadata
ds.attrs["format"] = image_format
ds.attrs["channel_order"] = data["channel_order"]
video_shape = video.shape
(
ds.attrs["frames"],
ds.attrs["height"],
ds.attrs["width"],
ds.attrs["channels"],
) = video_shape
# Store frame indices
f.create_dataset(f"{group}/frame_numbers", data=frame_inds)
# Store source video
if video.source_video is not None:
source_video = video.source_video
else:
source_video = video
# Create embedded video object
embedded_video = Video(
filename=labels_path,
backend=VideoBackend.from_filename(
labels_path,
dataset=f"{group}/video",
grayscale=video.grayscale,
keep_open=False,
),
source_video=source_video,
)
# Store source video metadata
grp = f.require_group(f"{group}/source_video")
grp.attrs["json"] = json.dumps(
video_to_dict(source_video, labels_path), separators=(",", ":")
)
# Store the embedded video for return
replaced_videos[video] = embedded_video
return replaced_videos
def embed_frames(
labels_path: str,
labels: Labels,
embed: list[tuple[Video, int]],
image_format: str = "png",
verbose: bool = True,
plugin: Optional[str] = None,
):
"""Embed frames in a SLEAP labels file.
Args:
labels_path: A string path to the SLEAP labels file.
labels: A `Labels` object to embed in the labels file.
embed: A list of tuples of `(video, frame_idx)` specifying the frames to embed.
image_format: The image format to use for embedding. Valid formats are "png"
(the default), "jpg" or "hdf5".
verbose: If `True` (the default), display a progress bar for the embedding
process.
plugin: Image plugin to use for encoding. One of "opencv" or "imageio".
If None, uses the global default from `get_default_image_plugin()`.
Notes:
This function will embed the frames in the labels file and update the `Videos`
and `Labels` objects in place.
"""
frames_metadata = prepare_frames_to_embed(labels_path, labels, embed)
replaced_videos = process_and_embed_frames(
labels_path,
frames_metadata,
image_format=image_format,
verbose=verbose,
plugin=plugin,
)
if len(replaced_videos) > 0:
labels.replace_videos(video_map=replaced_videos)
def embed_videos(
labels_path: str,
labels: Labels,
embed: bool | str | list[tuple[Video, int]],
verbose: bool = True,
plugin: Optional[str] = None,
):
"""Embed videos in a SLEAP labels file.
Args:
labels_path: A string path to the SLEAP labels file to save.
labels: A `Labels` object to save.
embed: Frames to embed in the saved labels file. One of `None`, `True`,
`"all"`, `"user"`, `"suggestions"`, `"user+suggestions"`, `"source"` or list
of tuples of `(video, frame_idx)`.
If `None` is specified (the default) and the labels contains embedded
frames, those embedded frames will be re-saved to the new file.
If `True` or `"all"`, all labeled frames and suggested frames will be
embedded.
verbose: If `True` (the default), display a progress bar for the embedding
process.
plugin: Image plugin to use for encoding. One of "opencv" or "imageio".
If None, uses the global default from `get_default_image_plugin()`.
If `"source"` is specified, no images will be embedded and the source video
will be restored if available.
This argument is only valid for the SLP backend.
"""
if embed is True:
embed = "all"
if embed == "user":
embed = [(lf.video, lf.frame_idx) for lf in labels.user_labeled_frames]
elif embed == "suggestions":
embed = [(sf.video, sf.frame_idx) for sf in labels.suggestions]
elif embed == "user+suggestions":
embed = [(lf.video, lf.frame_idx) for lf in labels.user_labeled_frames]
embed += [(sf.video, sf.frame_idx) for sf in labels.suggestions]
elif embed == "all":
embed = [(lf.video, lf.frame_idx) for lf in labels]
embed += [(sf.video, sf.frame_idx) for sf in labels.suggestions]
elif embed == "source":
embed = []
elif isinstance(embed, list):
embed = embed
else:
raise ValueError(f"Invalid value for embed: {embed}")
embed_frames(labels_path, labels, embed, verbose=verbose, plugin=plugin)
def write_videos(
labels_path: str,
videos: list[Video],
restore_source: bool = False,
reference_mode: Optional[VideoReferenceMode] = None,
original_videos: list[Video] | None = None,
verbose: bool = True,
):
"""Write video metadata to a SLEAP labels file.
Args:
labels_path: A string path to the SLEAP labels file.
videos: A list of `Video` objects to store the metadata for.
restore_source: Deprecated. Use reference_mode instead. If `True`, restore
source videos if available and will not re-embed the embedded images.
If `False` (the default), will re-embed images that were previously
embedded.
reference_mode: How to handle video references:
- EMBED: Re-embed frames that were previously embedded
- RESTORE_ORIGINAL: Use original video if available
- PRESERVE_SOURCE: Keep reference to source file (e.g., .pkg.slp)
original_videos: Optional list of original video objects before embedding.
Used when reference_mode is EMBED to preserve metadata.
verbose: If `True` (the default), display a progress bar when embedding frames.
"""
# Handle backwards compatibility
if reference_mode is None:
if restore_source:
reference_mode = VideoReferenceMode.RESTORE_ORIGINAL
else:
reference_mode = VideoReferenceMode.EMBED
videos_to_embed = []
videos_to_write = []
# First determine which videos need embedding
for video_ind, video in enumerate(videos):
if type(video.backend) is HDF5Video and video.backend.has_embedded_images:
if reference_mode == VideoReferenceMode.RESTORE_ORIGINAL:
if video.source_video is None:
# No source video available, reference the current embedded video
# file
videos_to_write.append((video_ind, video))
else:
# Use the source video
videos_to_write.append((video_ind, video.source_video))
elif reference_mode == VideoReferenceMode.PRESERVE_SOURCE:
# Keep the reference to the source .pkg.slp file
videos_to_write.append((video_ind, video))
else: # EMBED mode
# If the video has embedded images, check if we need to re-embed them
already_embedded = False
if Path(labels_path).exists():
with h5py.File(labels_path, "r") as f:
already_embedded = f"video{video_ind}/video" in f
if already_embedded:
videos_to_write.append((video_ind, video))
else:
# Collect information for embedding
frames_to_embed = [
(video, frame_idx) for frame_idx in video.backend.source_inds
]
videos_to_embed.append((video_ind, video, frames_to_embed))
else:
videos_to_write.append((video_ind, video))
# Process videos that need embedding
if videos_to_embed:
# Prepare all frames to embed
all_frames_to_embed = []
for video_ind, video, frames in videos_to_embed:
for frame in frames:
all_frames_to_embed.append(frame)
# Create a temporary Labels object for embedding
temp_labels = Labels(
videos=[v for _, v, _ in videos_to_embed], labeled_frames=[]
)
# Prepare and embed all frames in a single process
frames_metadata = prepare_frames_to_embed(
labels_path, temp_labels, all_frames_to_embed
)
replaced_videos = process_and_embed_frames(
labels_path,
frames_metadata,
image_format=[
v.backend.image_format if hasattr(v.backend, "image_format") else "png"
for _, v, _ in videos_to_embed
][0], # Use the first video's format
verbose=verbose,
)
# Add the embedded videos to the list
for video_ind, video, _ in videos_to_embed:
if video in replaced_videos:
videos_to_write.append((video_ind, replaced_videos[video]))
# Write video metadata
video_jsons = []
for video_ind, video in sorted(videos_to_write, key=lambda x: x[0]):
video_json = video_to_dict(video, labels_path)
video_jsons.append(np.bytes_(json.dumps(video_json, separators=(",", ":"))))
with h5py.File(labels_path, "a") as f:
if "videos_json" not in f:
f.create_dataset("videos_json", data=video_jsons, maxshape=(None,))
# Save lineage metadata in a separate pass to ensure video groups exist
with h5py.File(labels_path, "a") as f:
for video_ind, video in enumerate(videos):
dataset = f"video{video_ind}"
# If original_videos is provided (e.g., during embedding), use those
original_video = original_videos[video_ind] if original_videos else video
# Determine what metadata to save based on reference mode and video
# structure
original_to_save = None
source_to_save = None
# Handle original_video metadata
if reference_mode != VideoReferenceMode.RESTORE_ORIGINAL:
if original_video.original_video:
original_to_save = original_video.original_video
elif (
original_video.source_video is not None
and hasattr(original_video.source_video, "original_video")
and original_video.source_video.original_video is not None
):
# If source_video has original_video, use that (it's the true
# original)
original_to_save = original_video.source_video.original_video
elif (
original_video.source_video is not None
and reference_mode == VideoReferenceMode.EMBED
):
# For embed mode, if we only have source_video, that becomes the
# original
original_to_save = original_video.source_video
# Handle source_video metadata
if reference_mode != VideoReferenceMode.PRESERVE_SOURCE:
if reference_mode == VideoReferenceMode.EMBED and original_videos:
# For embed mode, save the original video as source (it's the
# .pkg.slp)
source_to_save = original_video
elif original_video.source_video is not None:
source_to_save = original_video.source_video
# Write metadata as datasets in the video group
if dataset in f:
video_group = f[dataset]
if original_to_save is not None:
# Store original_video metadata as a group (consistent with
# source_video)
original_grp = video_group.require_group("original_video")
original_json = video_to_dict(original_to_save, labels_path)
original_grp.attrs["json"] = json.dumps(
original_json, separators=(",", ":")
)
if source_to_save is not None:
# For EMBED mode with original_videos, we need to overwrite
# source_video
# because embed_videos saves the wrong metadata
if (
reference_mode == VideoReferenceMode.EMBED
and original_videos
and "source_video" in video_group
):
# Remove the existing source_video group
del video_group["source_video"]
if "source_video" not in video_group:
# Create source_video group
source_grp = video_group.require_group("source_video")
source_json = video_to_dict(source_to_save, labels_path)
source_grp.attrs["json"] = json.dumps(
source_json, separators=(",", ":")
)
def read_tracks(labels_path: str) -> list[Track]:
"""Read `Track` dataset in a SLEAP labels file.
Args:
labels_path: A string path to the SLEAP labels file.
Returns:
A list of `Track` objects.
"""
tracks = [json.loads(x) for x in read_hdf5_dataset(labels_path, "tracks_json")]
track_objects = []
for track in tracks:
track_objects.append(Track(name=track[1]))
return track_objects
def write_tracks(labels_path: str, tracks: list[Track]):
"""Write track metadata to a SLEAP labels file.
Args:
labels_path: A string path to the SLEAP labels file.
tracks: A list of `Track` objects to store the metadata for.
"""
# TODO: Add support for track metadata like spawned on frame.
SPAWNED_ON = 0
tracks_json = [
np.bytes_(json.dumps([SPAWNED_ON, track.name], separators=(",", ":")))
for track in tracks
]
with h5py.File(labels_path, "a") as f:
f.create_dataset("tracks_json", data=tracks_json, maxshape=(None,))
def read_suggestions(labels_path: str, videos: list[Video]) -> list[SuggestionFrame]:
"""Read `SuggestionFrame` dataset in a SLEAP labels file.
Args:
labels_path: A string path to the SLEAP labels file.
videos: A list of `Video` objects.
Returns:
A list of `SuggestionFrame` objects.
"""
try:
suggestions = read_hdf5_dataset(labels_path, "suggestions_json")
except KeyError:
return []
suggestions = [json.loads(x) for x in suggestions]
suggestions_objects = []
for suggestion in suggestions:
# Extract metadata (e.g., "group")
metadata = {"group": suggestion.get("group", 0)}
suggestions_objects.append(
SuggestionFrame(
video=videos[int(suggestion["video"])],
frame_idx=suggestion["frame_idx"],
metadata=metadata,
)
)
return suggestions_objects
def write_suggestions(
labels_path: str, suggestions: list[SuggestionFrame], videos: list[Video]
):
"""Write track metadata to a SLEAP labels file.
Args:
labels_path: A string path to the SLEAP labels file.
suggestions: A list of `SuggestionFrame` objects to store the metadata for.
videos: A list of `Video` objects.
"""
suggestions_json = []
for suggestion in suggestions:
# Get group from metadata if available, otherwise use default
group = suggestion.metadata.get("group", 0) if suggestion.metadata else 0
suggestion_dict = {
"video": str(videos.index(suggestion.video)),
"frame_idx": suggestion.frame_idx,
"group": group,
}
suggestion_json = np.bytes_(json.dumps(suggestion_dict, separators=(",", ":")))
suggestions_json.append(suggestion_json)
with h5py.File(labels_path, "a") as f:
f.create_dataset("suggestions_json", data=suggestions_json, maxshape=(None,))
def read_metadata(labels_path: str) -> dict:
"""Read metadata from a SLEAP labels file.
Args:
labels_path: A string path to the SLEAP labels file.
Returns:
A dict containing the metadata from a SLEAP labels file.
"""
md = read_hdf5_attrs(labels_path, "metadata", "json")
return json.loads(md.decode())
def read_skeletons(labels_path: str) -> list[Skeleton]:
"""Read `Skeleton` dataset from a SLEAP labels file.
Args:
labels_path: A string that contains the path to the labels file.
Returns:
A list of `Skeleton` objects.
"""
metadata = read_metadata(labels_path)
# Get node names. This is a superset of all nodes across all skeletons. Note that
# node ordering is specific to each skeleton, so we'll need to fix this afterwards.
node_names = [x["name"] for x in metadata["nodes"]]
# Use the SLP skeleton decoder
decoder = SkeletonSLPDecoder()
return decoder.decode(metadata, node_names)
def serialize_skeletons(skeletons: list[Skeleton]) -> tuple[list[dict], list[dict]]:
"""Serialize a list of `Skeleton` objects to JSON-compatible dicts.
Args:
skeletons: A list of `Skeleton` objects.
Returns:
A tuple of `skeletons_dicts, nodes_dicts`.
`nodes_dicts` is a list of dicts containing the nodes in all the skeletons.
`skeletons_dicts` is a list of dicts containing the skeletons.
Notes:
This function attempts to replicate the serialization of skeletons in legacy
SLEAP which relies on a combination of networkx's graph serialization and our
own metadata used to store nodes and edges independent of the graph structure.
However, because sleap-io does not currently load in the legacy metadata, this
function will not produce byte-level compatible serialization with legacy
formats, even though the ordering and all attributes of nodes and edges should
match up.
"""
# Use the SLP skeleton encoder
encoder = SkeletonSLPEncoder()
return encoder.encode_skeletons(skeletons)
def write_metadata(labels_path: str, labels: Labels):
"""Write metadata to a SLEAP labels file.
This function will write the skeletons and provenance for the labels.
Args:
labels_path: A string path to the SLEAP labels file.
labels: A `Labels` object to store the metadata for.
See also: serialize_skeletons
"""
skeletons_dicts, nodes_dicts = serialize_skeletons(labels.skeletons)
md = {
"version": "2.0.0",
"skeletons": skeletons_dicts,
"nodes": nodes_dicts,
"videos": [],
"tracks": [],
"suggestions": [], # TODO: Handle suggestions metadata.
"negative_anchors": {},
"provenance": labels.provenance,
}
# Custom encoding.
for k in md["provenance"]:
if isinstance(md["provenance"][k], Path):
# Path -> str
md["provenance"][k] = md["provenance"][k].as_posix()
with h5py.File(labels_path, "a") as f:
grp = f.require_group("metadata")
grp.attrs["format_id"] = 1.4
grp.attrs["json"] = np.bytes_(json.dumps(md, separators=(",", ":")))
def read_points(labels_path: str) -> np.ndarray:
"""Read points dataset from a SLEAP labels file.
Args:
labels_path: A string path to the SLEAP labels file.
Returns:
A structured array of point data.
"""
pts = read_hdf5_dataset(labels_path, "points")
return pts
def read_pred_points(labels_path: str) -> np.ndarray:
"""Read predicted points dataset from a SLEAP labels file.