|
33 | 33 | open_pose_file, |
34 | 34 | ) |
35 | 35 |
|
| 36 | +from . import pose_attribute_cache |
36 | 37 | from .feature_manager import FeatureManager |
37 | 38 | from .parallel_workers import ( |
38 | 39 | BinaryFeatureLoadJobSpec, |
|
61 | 62 | from jabs.core.utils.process_pool_manager import ProcessPoolManager |
62 | 63 |
|
63 | 64 |
|
| 65 | +def _is_int(value: object) -> bool: |
| 66 | + """Return True for a genuine int (JSON bools are ints in Python; reject them).""" |
| 67 | + return isinstance(value, int) and not isinstance(value, bool) |
| 68 | + |
| 69 | + |
| 70 | +def _is_str_list(value: object) -> bool: |
| 71 | + """Return True for a list whose every element is a string.""" |
| 72 | + return isinstance(value, list) and all(isinstance(item, str) for item in value) |
| 73 | + |
| 74 | + |
| 75 | +# Pose-derived fields cached per video, mapped to a predicate validating the |
| 76 | +# cached value's type (matching the corresponding VideoScanResult field). An |
| 77 | +# entry is trusted only when it carries a matching token and pose filename plus |
| 78 | +# every field present with the expected type; a parseable-but-malformed entry |
| 79 | +# (e.g. a hand-edited or corrupted cache) is treated as a miss and rescanned. |
| 80 | +_POSE_CACHE_FIELD_VALIDATORS: dict[str, Callable[[object], bool]] = { |
| 81 | + "hdf5_frame_count": _is_int, |
| 82 | + "identity_count": _is_int, |
| 83 | + "static_objects": _is_str_list, |
| 84 | + "lixit_keypoints": _is_int, |
| 85 | + "has_cm_per_pixel": lambda value: isinstance(value, bool), |
| 86 | +} |
| 87 | + |
| 88 | + |
| 89 | +def _pose_cache_entry_matches(entry: object, token: str, pose_file: str) -> bool: |
| 90 | + """Return True when a cache entry is usable for a video's current pose file. |
| 91 | +
|
| 92 | + Validates field types as well as presence so a parseable-but-malformed entry |
| 93 | + is treated as a miss (triggering a rescan) rather than reconstructed into |
| 94 | + wrong metadata or a reconstruction-time error. |
| 95 | + """ |
| 96 | + return ( |
| 97 | + isinstance(entry, dict) |
| 98 | + and entry.get("token") == token |
| 99 | + and entry.get("pose_file") == pose_file |
| 100 | + and all( |
| 101 | + field in entry and validator(entry[field]) |
| 102 | + for field, validator in _POSE_CACHE_FIELD_VALIDATORS.items() |
| 103 | + ) |
| 104 | + ) |
| 105 | + |
| 106 | + |
| 107 | +def _scan_result_from_pose_cache(video: str, entry: dict) -> VideoScanResult: |
| 108 | + """Reconstruct a VideoScanResult from a cached entry. |
| 109 | +
|
| 110 | + ``video_frame_count`` is left ``None``: video frame counts are validated on |
| 111 | + demand rather than at load, so they are never cached. |
| 112 | + """ |
| 113 | + return VideoScanResult( |
| 114 | + video=video, |
| 115 | + hdf5_frame_count=entry["hdf5_frame_count"], |
| 116 | + video_frame_count=None, |
| 117 | + identity_count=entry["identity_count"], |
| 118 | + static_objects=list(entry["static_objects"]), |
| 119 | + lixit_keypoints=entry["lixit_keypoints"], |
| 120 | + has_cm_per_pixel=entry["has_cm_per_pixel"], |
| 121 | + ) |
| 122 | + |
| 123 | + |
| 124 | +def _pose_cache_entry(result: VideoScanResult, pose_file: str, token: str) -> dict: |
| 125 | + """Build a cache entry from a fresh scan result.""" |
| 126 | + return { |
| 127 | + "token": token, |
| 128 | + "pose_file": pose_file, |
| 129 | + "hdf5_frame_count": result["hdf5_frame_count"], |
| 130 | + "identity_count": result["identity_count"], |
| 131 | + "static_objects": list(result["static_objects"]), |
| 132 | + "lixit_keypoints": result["lixit_keypoints"], |
| 133 | + "has_cm_per_pixel": result["has_cm_per_pixel"], |
| 134 | + } |
| 135 | + |
| 136 | + |
64 | 137 | class Project: |
65 | 138 | """Represents a JABS project, managing data, settings, and operations for a project directory. |
66 | 139 |
|
@@ -215,18 +288,99 @@ def _run_video_scan( |
215 | 288 | if not jobs: |
216 | 289 | return {} |
217 | 290 |
|
| 291 | + # The opt-in up-front check reads video frame counts, which are not |
| 292 | + # cached, so it always performs a full scan. |
| 293 | + if enable_video_check: |
| 294 | + return self._scan_jobs(jobs, process_pool) |
| 295 | + |
| 296 | + return self._run_cached_video_scan(jobs, process_pool) |
| 297 | + |
| 298 | + @staticmethod |
| 299 | + def _scan_jobs( |
| 300 | + jobs: list[VideoScanJobSpec], |
| 301 | + process_pool: "ProcessPoolManager | None", |
| 302 | + ) -> dict[str, VideoScanResult]: |
| 303 | + """Run scan jobs in parallel when a pool is available, else sequentially. |
| 304 | +
|
| 305 | + Args: |
| 306 | + jobs: Scan jobs to execute. |
| 307 | + process_pool: Optional shared pool; when ``None`` the jobs run |
| 308 | + sequentially in the calling process. |
| 309 | +
|
| 310 | + Returns: |
| 311 | + Mapping from video filename to its scan result. |
| 312 | + """ |
218 | 313 | if process_pool is not None: |
219 | 314 | future_to_video = { |
220 | 315 | process_pool.submit(scan_video_metadata, job): job["video"] for job in jobs |
221 | 316 | } |
222 | 317 | results: dict[str, VideoScanResult] = {} |
223 | 318 | for future in as_completed(future_to_video): |
224 | | - result: VideoScanResult = future.result() |
| 319 | + try: |
| 320 | + result: VideoScanResult = future.result() |
| 321 | + except Exception: |
| 322 | + logger.error( |
| 323 | + "Failed to scan pose metadata for %s", |
| 324 | + future_to_video[future], |
| 325 | + exc_info=True, |
| 326 | + ) |
| 327 | + raise |
225 | 328 | results[result["video"]] = result |
226 | 329 | return results |
227 | 330 |
|
228 | 331 | return {job["video"]: scan_video_metadata(job) for job in jobs} |
229 | 332 |
|
| 333 | + def _run_cached_video_scan( |
| 334 | + self, |
| 335 | + jobs: list[VideoScanJobSpec], |
| 336 | + process_pool: "ProcessPoolManager | None", |
| 337 | + ) -> dict[str, VideoScanResult]: |
| 338 | + """Scan only new/changed pose files, reusing cached attributes otherwise. |
| 339 | +
|
| 340 | + Pose attributes are intrinsic to the pose file, so an entry whose cached |
| 341 | + ``stat`` token still matches is reused without opening the file. Only |
| 342 | + videos with a missing or stale entry are scanned; the cache is then |
| 343 | + rewritten when anything changed (a rescan happened, or the set of videos |
| 344 | + differs from what was cached). |
| 345 | +
|
| 346 | + Args: |
| 347 | + jobs: Scan jobs for every video with a locatable pose file. |
| 348 | + process_pool: Optional shared pool for parallelizing the scan of the |
| 349 | + uncached videos. |
| 350 | +
|
| 351 | + Returns: |
| 352 | + Mapping from video filename to its scan result. |
| 353 | + """ |
| 354 | + cache_path = self._paths.pose_attribute_cache_file |
| 355 | + cached = pose_attribute_cache.load(cache_path) |
| 356 | + |
| 357 | + results: dict[str, VideoScanResult] = {} |
| 358 | + tokens: dict[str, str] = {} |
| 359 | + to_scan: list[VideoScanJobSpec] = [] |
| 360 | + for job in jobs: |
| 361 | + video = job["video"] |
| 362 | + token = pose_attribute_cache.pose_token(job["pose_path"]) |
| 363 | + tokens[video] = token |
| 364 | + entry = cached.get(video) |
| 365 | + if _pose_cache_entry_matches(entry, token, job["pose_path"].name): |
| 366 | + results[video] = _scan_result_from_pose_cache(video, entry) |
| 367 | + else: |
| 368 | + to_scan.append(job) |
| 369 | + |
| 370 | + if to_scan: |
| 371 | + results.update(self._scan_jobs(to_scan, process_pool)) |
| 372 | + |
| 373 | + updated = { |
| 374 | + job["video"]: _pose_cache_entry( |
| 375 | + results[job["video"]], job["pose_path"].name, tokens[job["video"]] |
| 376 | + ) |
| 377 | + for job in jobs |
| 378 | + } |
| 379 | + if to_scan or set(updated) != set(cached): |
| 380 | + pose_attribute_cache.save(cache_path, updated) |
| 381 | + |
| 382 | + return results |
| 383 | + |
230 | 384 | def _validate_pose_files(self): |
231 | 385 | """Ensure all videos have corresponding pose files.""" |
232 | 386 | err = False |
|
0 commit comments