simba-uw-tf-dev 4.7.2__py3-none-any.whl → 4.7.5__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.

Potentially problematic release.


This version of simba-uw-tf-dev might be problematic. Click here for more details.

Files changed (35) hide show
  1. simba/SimBA.py +13 -4
  2. simba/assets/icons/left_arrow_green.png +0 -0
  3. simba/assets/icons/left_arrow_red.png +0 -0
  4. simba/assets/icons/right_arrow_green.png +0 -0
  5. simba/assets/icons/right_arrow_red.png +0 -0
  6. simba/assets/lookups/yolo_schematics/yolo_mitra.csv +1 -1
  7. simba/mixins/geometry_mixin.py +357 -302
  8. simba/mixins/image_mixin.py +129 -4
  9. simba/model/yolo_fit.py +22 -15
  10. simba/model/yolo_pose_inference.py +7 -2
  11. simba/outlier_tools/skip_outlier_correction.py +2 -2
  12. simba/plotting/heat_mapper_clf_mp.py +45 -23
  13. simba/plotting/plot_clf_results.py +2 -1
  14. simba/plotting/plot_clf_results_mp.py +456 -455
  15. simba/roi_tools/roi_utils.py +2 -2
  16. simba/sandbox/convert_h264_to_mp4_lossless.py +129 -0
  17. simba/sandbox/extract_and_convert_videos.py +257 -0
  18. simba/sandbox/remove_end_of_video.py +80 -0
  19. simba/sandbox/video_timelaps.py +291 -0
  20. simba/ui/import_pose_frame.py +13 -13
  21. simba/ui/pop_ups/clf_plot_pop_up.py +1 -1
  22. simba/ui/pop_ups/run_machine_models_popup.py +2 -2
  23. simba/ui/pop_ups/video_processing_pop_up.py +3638 -3469
  24. simba/ui/tkinter_functions.py +3 -1
  25. simba/ui/video_timelaps.py +454 -0
  26. simba/utils/lookups.py +67 -1
  27. simba/utils/read_write.py +10 -3
  28. simba/video_processors/batch_process_create_ffmpeg_commands.py +0 -1
  29. simba/video_processors/video_processing.py +5385 -5264
  30. {simba_uw_tf_dev-4.7.2.dist-info → simba_uw_tf_dev-4.7.5.dist-info}/METADATA +1 -1
  31. {simba_uw_tf_dev-4.7.2.dist-info → simba_uw_tf_dev-4.7.5.dist-info}/RECORD +35 -26
  32. {simba_uw_tf_dev-4.7.2.dist-info → simba_uw_tf_dev-4.7.5.dist-info}/LICENSE +0 -0
  33. {simba_uw_tf_dev-4.7.2.dist-info → simba_uw_tf_dev-4.7.5.dist-info}/WHEEL +0 -0
  34. {simba_uw_tf_dev-4.7.2.dist-info → simba_uw_tf_dev-4.7.5.dist-info}/entry_points.txt +0 -0
  35. {simba_uw_tf_dev-4.7.2.dist-info → simba_uw_tf_dev-4.7.5.dist-info}/top_level.txt +0 -0
@@ -17,8 +17,8 @@ from PIL import ImageTk
17
17
  from scipy.spatial.distance import cdist
18
18
  from shapely.geometry import Polygon
19
19
 
20
- from simba.utils.checks import (check_file_exist_and_readable, check_instance,
21
- check_int, check_str, check_valid_array,
20
+ from simba.utils.checks import (check_file_exist_and_readable, check_int,
21
+ check_str, check_valid_array,
22
22
  check_valid_dataframe, check_valid_tuple,
23
23
  check_video_and_data_frm_count_align)
24
24
  from simba.utils.enums import (ROI_SETTINGS, ConfigKey, Formats, Keys, Options,
@@ -0,0 +1,129 @@
1
+ """
2
+ Convert .h264 files to lossless MP4 format using FFmpeg.
3
+
4
+ This script converts H.264 raw video files to MP4 container format using
5
+ lossless encoding (copy codec) to preserve quality.
6
+ """
7
+ import os
8
+ import subprocess
9
+ import glob
10
+ from pathlib import Path
11
+ from typing import List, Union
12
+
13
+ def check_ffmpeg_available() -> bool:
14
+ """Check if FFmpeg is available in the system."""
15
+ try:
16
+ subprocess.run(['ffmpeg', '-version'],
17
+ stdout=subprocess.PIPE,
18
+ stderr=subprocess.PIPE,
19
+ check=True)
20
+ return True
21
+ except (subprocess.CalledProcessError, FileNotFoundError):
22
+ return False
23
+
24
+ def convert_h264_to_mp4_lossless(input_path: Union[str, Path],
25
+ output_path: Union[str, Path] = None) -> bool:
26
+ """
27
+ Convert a single .h264 file to lossless MP4.
28
+
29
+ :param Union[str, Path] input_path: Path to input .h264 file
30
+ :param Union[str, Path] output_path: Optional output path. If None, creates output in same directory with .mp4 extension
31
+ :return: True if conversion successful, False otherwise
32
+ """
33
+ input_path = Path(input_path)
34
+
35
+ if not input_path.exists():
36
+ print(f"[ERROR] File not found: {input_path}")
37
+ return False
38
+
39
+ if output_path is None:
40
+ output_path = input_path.with_suffix('.mp4')
41
+ else:
42
+ output_path = Path(output_path)
43
+
44
+ if output_path.exists():
45
+ print(f"[SKIP] Output file already exists: {output_path}")
46
+ return False
47
+
48
+ # FFmpeg command for lossless conversion (copy codec, no re-encoding)
49
+ # -c:v copy: Copy video stream without re-encoding (lossless)
50
+ # -c:a copy: Copy audio stream if present (lossless)
51
+ # -movflags +faststart: Optimize for web streaming (optional)
52
+ cmd = [
53
+ 'ffmpeg',
54
+ '-i', str(input_path),
55
+ '-c:v', 'copy', # Copy video codec (lossless)
56
+ '-c:a', 'copy', # Copy audio codec if present (lossless)
57
+ '-y', # Overwrite output file if exists
58
+ str(output_path)
59
+ ]
60
+
61
+ try:
62
+ print(f"Converting {input_path.name} -> {output_path.name}...")
63
+ result = subprocess.run(
64
+ cmd,
65
+ stdout=subprocess.PIPE,
66
+ stderr=subprocess.PIPE,
67
+ check=True,
68
+ text=True
69
+ )
70
+ print(f" [OK] Successfully converted {input_path.name}")
71
+ return True
72
+ except subprocess.CalledProcessError as e:
73
+ print(f" [ERROR] FFmpeg error for {input_path.name}: {e.stderr}")
74
+ return False
75
+ except Exception as e:
76
+ print(f" [ERROR] Unexpected error for {input_path.name}: {e}")
77
+ return False
78
+
79
+ def convert_all_h264_files(directory: str,
80
+ pattern: str = None) -> None:
81
+ """
82
+ Convert all .h264 files in a directory to MP4.
83
+
84
+ :param str directory: Directory containing .h264 files
85
+ :param str pattern: Optional pattern to match in filename (e.g., '4.03.001_6_2026_01_16_09_15_00_000')
86
+ """
87
+ dir_path = Path(directory)
88
+
89
+ if not dir_path.exists():
90
+ print(f"[ERROR] Directory does not exist: {directory}")
91
+ return
92
+
93
+ if not check_ffmpeg_available():
94
+ print("[ERROR] FFmpeg is not available. Please install FFmpeg.")
95
+ return
96
+
97
+ # Find all .h264 files
98
+ h264_files = list(dir_path.glob('*.h264'))
99
+
100
+ if pattern:
101
+ h264_files = [f for f in h264_files if pattern in f.name]
102
+
103
+ if not h264_files:
104
+ pattern_msg = f" matching pattern '{pattern}'" if pattern else ""
105
+ print(f"No .h264 files found{pattern_msg} in {directory}")
106
+ return
107
+
108
+ print(f"Found {len(h264_files)} .h264 file(s) to convert...")
109
+
110
+ successful = 0
111
+ failed = 0
112
+
113
+ for h264_file in sorted(h264_files):
114
+ if convert_h264_to_mp4_lossless(h264_file):
115
+ successful += 1
116
+ else:
117
+ failed += 1
118
+
119
+ print(f"\nConversion complete!")
120
+ print(f" Successful: {successful}")
121
+ print(f" Failed: {failed}")
122
+ print(f" Total: {len(h264_files)}")
123
+
124
+ if __name__ == "__main__":
125
+ # Convert all .h264 files in the directory
126
+ directory = r"E:\lp_videos_tar"
127
+ pattern = None # Convert all .h264 files, not just matching a pattern
128
+
129
+ convert_all_h264_files(directory, pattern=pattern)
@@ -0,0 +1,257 @@
1
+ """
2
+ Extract tar files and convert all videos to lossless MP4 format.
3
+
4
+ This script:
5
+ 1. Extracts all .tar, .tar.gz, and .tgz files in a directory
6
+ 2. Finds all video files (various formats)
7
+ 3. Converts them to lossless MP4 using FFmpeg stream copy
8
+ """
9
+ import os
10
+ import tarfile
11
+ import glob
12
+ import subprocess
13
+ from pathlib import Path
14
+ from typing import List, Set
15
+
16
+ # Common video file extensions
17
+ VIDEO_EXTENSIONS = {'.h264', '.avi', '.mov', '.mkv', '.flv', '.m4v', '.mp4',
18
+ '.webm', '.wmv', '.mpg', '.mpeg', '.ts', '.mts', '.m2ts'}
19
+
20
+ def check_ffmpeg_available() -> bool:
21
+ """Check if FFmpeg is available in the system."""
22
+ try:
23
+ subprocess.run(['ffmpeg', '-version'],
24
+ stdout=subprocess.PIPE,
25
+ stderr=subprocess.PIPE,
26
+ check=True)
27
+ return True
28
+ except (subprocess.CalledProcessError, FileNotFoundError):
29
+ return False
30
+
31
+ def extract_tar_files(directory_path: str, output_dir: str = None) -> List[Path]:
32
+ """
33
+ Extracts all .tar, .tar.gz, and .tgz files in a given directory.
34
+
35
+ Args:
36
+ directory_path (str): The path to the directory containing the tar files.
37
+ output_dir (str, optional): The directory where to extract the contents.
38
+ If None, extracts to the same directory as the tar file.
39
+ Defaults to None.
40
+ Returns:
41
+ List[Path]: List of directories where files were extracted
42
+ """
43
+ if output_dir is None:
44
+ output_dir = directory_path
45
+
46
+ dir_path = Path(directory_path)
47
+ output_path = Path(output_dir)
48
+ output_path.mkdir(parents=True, exist_ok=True)
49
+
50
+ tar_files = []
51
+ for ext in ['*.tar', '*.tar.gz', '*.tgz']:
52
+ tar_files.extend(dir_path.glob(ext))
53
+
54
+ if not tar_files:
55
+ print(f"No tar file(s) found in {directory_path}")
56
+ return []
57
+
58
+ print(f"Found {len(tar_files)} tar file(s) to extract...")
59
+
60
+ extracted_dirs = []
61
+ for tar_file_path in tar_files:
62
+ tar_file = Path(tar_file_path)
63
+ print(f"Extracting {tar_file.name}...")
64
+ try:
65
+ # Extract to a subdirectory named after the tar file (without extension)
66
+ extract_dir = output_path / tar_file.stem
67
+ extract_dir.mkdir(parents=True, exist_ok=True)
68
+
69
+ with tarfile.open(tar_file_path, 'r:*') as f:
70
+ if hasattr(tarfile, 'data_filter'): # Python 3.12+
71
+ f.extractall(path=extract_dir, filter='data')
72
+ else:
73
+ f.extractall(path=extract_dir)
74
+ print(f" [OK] Extracted {tar_file.name} to {extract_dir}")
75
+ extracted_dirs.append(extract_dir)
76
+ except tarfile.ReadError as e:
77
+ print(f" [ERROR] Error extracting {tar_file.name}: {e} (Not a valid tar file or corrupted)")
78
+ except Exception as e:
79
+ print(f" [ERROR] Error extracting {tar_file.name}: {e}")
80
+
81
+ print("\nExtraction complete!")
82
+ return extracted_dirs
83
+
84
+ def find_video_files(directory: Path, recursive: bool = True) -> List[Path]:
85
+ """
86
+ Find all video files in a directory.
87
+
88
+ Args:
89
+ directory: Directory to search
90
+ recursive: If True, search recursively in subdirectories
91
+
92
+ Returns:
93
+ List of video file paths
94
+ """
95
+ video_files = []
96
+
97
+ if recursive:
98
+ for ext in VIDEO_EXTENSIONS:
99
+ video_files.extend(directory.rglob(f'*{ext}'))
100
+ else:
101
+ for ext in VIDEO_EXTENSIONS:
102
+ video_files.extend(directory.glob(f'*{ext}'))
103
+
104
+ return sorted(video_files)
105
+
106
+ def convert_video_to_mp4_lossless(input_path: Path, output_path: Path = None) -> bool:
107
+ """
108
+ Convert a video file to lossless MP4 using FFmpeg stream copy.
109
+
110
+ Args:
111
+ input_path: Path to input video file
112
+ output_path: Optional output path. If None, creates output in same directory with .mp4 extension
113
+
114
+ Returns:
115
+ True if conversion successful, False otherwise
116
+ """
117
+ if not input_path.exists():
118
+ print(f"[ERROR] File not found: {input_path}")
119
+ return False
120
+
121
+ if output_path is None:
122
+ output_path = input_path.with_suffix('.mp4')
123
+ else:
124
+ output_path = Path(output_path)
125
+
126
+ # Skip if already MP4
127
+ if input_path.suffix.lower() == '.mp4':
128
+ print(f"[SKIP] File is already MP4: {input_path.name}")
129
+ return False
130
+
131
+ if output_path.exists():
132
+ print(f"[SKIP] Output file already exists: {output_path.name}")
133
+ return False
134
+
135
+ # FFmpeg command for lossless conversion (stream copy)
136
+ # -c:v copy: Copy video stream without re-encoding (lossless)
137
+ # -c:a copy: Copy audio stream if present (lossless)
138
+ # -y: Overwrite output file if exists
139
+ cmd = [
140
+ 'ffmpeg',
141
+ '-i', str(input_path),
142
+ '-c:v', 'copy', # Copy video codec (lossless)
143
+ '-c:a', 'copy', # Copy audio codec if present (lossless)
144
+ '-y',
145
+ str(output_path)
146
+ ]
147
+
148
+ try:
149
+ print(f"Converting {input_path.name} -> {output_path.name}...")
150
+ result = subprocess.run(
151
+ cmd,
152
+ stdout=subprocess.PIPE,
153
+ stderr=subprocess.PIPE,
154
+ check=True,
155
+ text=True
156
+ )
157
+ print(f" [OK] Successfully converted {input_path.name}")
158
+ return True
159
+ except subprocess.CalledProcessError as e:
160
+ print(f" [ERROR] FFmpeg error for {input_path.name}")
161
+ # Print first few lines of stderr for debugging
162
+ stderr_lines = e.stderr.split('\n')[:5]
163
+ for line in stderr_lines:
164
+ if line.strip():
165
+ print(f" {line}")
166
+ return False
167
+ except Exception as e:
168
+ print(f" [ERROR] Unexpected error for {input_path.name}: {e}")
169
+ return False
170
+
171
+ def extract_and_convert_videos(directory_path: str,
172
+ extract_to_subdirs: bool = True,
173
+ convert_recursive: bool = True) -> None:
174
+ """
175
+ Extract all tar files and convert all videos to lossless MP4.
176
+
177
+ Args:
178
+ directory_path: Directory containing tar files
179
+ extract_to_subdirs: If True, extract each tar to its own subdirectory
180
+ convert_recursive: If True, search for videos recursively in extracted directories
181
+ """
182
+ dir_path = Path(directory_path)
183
+
184
+ if not dir_path.exists():
185
+ print(f"[ERROR] Directory does not exist: {directory_path}")
186
+ return
187
+
188
+ if not check_ffmpeg_available():
189
+ print("[ERROR] FFmpeg is not available. Please install FFmpeg.")
190
+ return
191
+
192
+ # Step 1: Extract tar files
193
+ print("=" * 60)
194
+ print("STEP 1: Extracting tar files...")
195
+ print("=" * 60)
196
+ extracted_dirs = extract_tar_files(directory_path,
197
+ output_dir=directory_path if extract_to_subdirs else None)
198
+
199
+ # Step 2: Find all video files
200
+ print("\n" + "=" * 60)
201
+ print("STEP 2: Finding video files...")
202
+ print("=" * 60)
203
+
204
+ # Search in extracted directories and the main directory
205
+ search_dirs = extracted_dirs if extracted_dirs else [dir_path]
206
+ all_video_files = []
207
+
208
+ for search_dir in search_dirs:
209
+ videos = find_video_files(search_dir, recursive=convert_recursive)
210
+ all_video_files.extend(videos)
211
+ if videos:
212
+ print(f"Found {len(videos)} video file(s) in {search_dir}")
213
+
214
+ # Also search in main directory if we extracted to subdirs
215
+ if extract_to_subdirs and dir_path not in search_dirs:
216
+ videos = find_video_files(dir_path, recursive=False)
217
+ all_video_files.extend(videos)
218
+ if videos:
219
+ print(f"Found {len(videos)} video file(s) in {dir_path}")
220
+
221
+ if not all_video_files:
222
+ print("No video files found to convert.")
223
+ return
224
+
225
+ print(f"\nTotal video files found: {len(all_video_files)}")
226
+
227
+ # Step 3: Convert videos to MP4
228
+ print("\n" + "=" * 60)
229
+ print("STEP 3: Converting videos to lossless MP4...")
230
+ print("=" * 60)
231
+
232
+ successful = 0
233
+ failed = 0
234
+ skipped = 0
235
+
236
+ for video_file in all_video_files:
237
+ result = convert_video_to_mp4_lossless(video_file)
238
+ if result is True:
239
+ successful += 1
240
+ elif result is False and video_file.suffix.lower() == '.mp4':
241
+ skipped += 1
242
+ else:
243
+ failed += 1
244
+
245
+ print("\n" + "=" * 60)
246
+ print("Conversion complete!")
247
+ print("=" * 60)
248
+ print(f" Successful: {successful}")
249
+ print(f" Failed: {failed}")
250
+ print(f" Skipped (already MP4): {skipped}")
251
+ print(f" Total: {len(all_video_files)}")
252
+
253
+ if __name__ == "__main__":
254
+ target_directory = r"E:\new_tars"
255
+ extract_and_convert_videos(target_directory,
256
+ extract_to_subdirs=True,
257
+ convert_recursive=True)
@@ -0,0 +1,80 @@
1
+ """
2
+ Function to remove N seconds from the end of a video file.
3
+
4
+ Similar to simba.video_processors.video_processing.remove_beginning_of_video
5
+ but removes from the end instead of the beginning.
6
+ """
7
+
8
+ import os
9
+ import subprocess
10
+ from typing import Union, Optional
11
+
12
+ from simba.utils.checks import (
13
+ check_ffmpeg_available,
14
+ check_file_exist_and_readable,
15
+ check_int,
16
+ check_if_dir_exists,
17
+ check_nvidea_gpu_available
18
+ )
19
+ from simba.utils.errors import FFMPEGCodecGPUError, InvalidInputError
20
+ from simba.utils.printing import SimbaTimer, stdout_success
21
+ from simba.utils.read_write import get_fn_ext, get_video_meta_data
22
+ from simba.utils.lookups import quality_pct_to_crf
23
+
24
+
25
+ def remove_end_of_video(file_path: Union[str, os.PathLike],
26
+ time: int,
27
+ quality: int = 60,
28
+ save_path: Optional[Union[str, os.PathLike]] = None,
29
+ gpu: Optional[bool] = False) -> None:
30
+ """
31
+ Remove N seconds from the end of a video file.
32
+
33
+ :param Union[str, os.PathLike] file_path: Path to video file
34
+ :param int time: Number of seconds to remove from the end of the video.
35
+ :param int quality: Video quality percentage (1-100). Higher values = higher quality. Default 60.
36
+ :param Optional[Union[str, os.PathLike]] save_path: Optional save location for the shortened video. If None, then the new video is saved in the same directory as the input video with the ``_shortened`` suffix.
37
+ :param Optional[bool] gpu: If True, use NVIDEA GPU codecs. Default False.
38
+ :returns: None. If save_path is not passed, the result is stored in the same directory as the input file with the ``_shorten.mp4`` suffix.
39
+
40
+ .. note::
41
+ Codec is automatically selected: libx264 for CPU encoding (ignored if gpu=True).
42
+
43
+ :example:
44
+ >>> _ = remove_end_of_video(file_path='project_folder/videos/Video_1.avi', time=10)
45
+ >>> remove_end_of_video(file_path=f'/Users/simon/Desktop/imgs_4/test/blahhhh.mp4', save_path='/Users/simon/Desktop/imgs_4/test/CUT.mp4', time=3)
46
+ """
47
+
48
+ check_ffmpeg_available(raise_error=True)
49
+ if gpu and not check_nvidea_gpu_available():
50
+ raise FFMPEGCodecGPUError(msg="No GPU found (as evaluated by nvidea-smi returning None)", source=remove_end_of_video.__name__)
51
+ timer = SimbaTimer(start=True)
52
+ check_file_exist_and_readable(file_path=file_path)
53
+ video_meta_data = get_video_meta_data(video_path=file_path)
54
+ check_int(name="Cut time", value=time, min_value=1)
55
+ check_int(name=f'{remove_end_of_video.__name__} quality', value=quality, min_value=1, max_value=100, raise_error=True)
56
+ quality_crf = quality_pct_to_crf(pct=int(quality))
57
+ time = int(time)
58
+ dir, file_name, ext = get_fn_ext(filepath=file_path)
59
+ if video_meta_data['video_length_s'] <= time:
60
+ raise InvalidInputError(msg=f"The cut time {time}s is invalid for video {file_name} with length {video_meta_data['video_length_s']}s", source=remove_end_of_video.__name__)
61
+ if save_path is None:
62
+ save_name = os.path.join(dir, f"{file_name}_shorten.mp4")
63
+ else:
64
+ check_if_dir_exists(in_dir=os.path.dirname(save_path), source=f'{remove_end_of_video.__name__} save_path', create_if_not_exist=True)
65
+ save_name = save_path
66
+ duration = video_meta_data['video_length_s'] - time
67
+ if gpu:
68
+ cmd = f'ffmpeg -hwaccel auto -c:v h264_cuvid -i "{file_path}" -t {duration} -rc vbr -cq {quality_crf} -c:v h264_nvenc -c:a aac "{save_name}" -loglevel error -stats -hide_banner -y'
69
+ else:
70
+ cmd = f'ffmpeg -i "{file_path}" -t {duration} -c:v libx264 -crf {quality_crf} -c:a aac "{save_name}" -loglevel error -stats -hide_banner -y'
71
+ print(f"Removing final {time}s from {file_name}... ")
72
+ subprocess.call(cmd, shell=True, stdout=subprocess.PIPE)
73
+ timer.stop_timer()
74
+ stdout_success(msg=f"SIMBA COMPLETE: Video converted! {save_name} generated!", elapsed_time=timer.elapsed_time_str, source=remove_end_of_video.__name__)
75
+
76
+
77
+ if __name__ == "__main__":
78
+ # Example usage
79
+ # remove_end_of_video(file_path='path/to/video.mp4', time=10)
80
+ pass