facescope 0.2.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.
facescope/analysis.py ADDED
@@ -0,0 +1,777 @@
1
+ """Offline CPU cut detection, face detection, coordinate inversion, and shot-local tracking."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import math
7
+ import os
8
+ import pickle
9
+ import shutil
10
+ import tempfile
11
+ from collections.abc import Callable, Generator, Iterable, Sequence
12
+ from contextlib import closing
13
+ from dataclasses import dataclass
14
+ from fractions import Fraction
15
+ from itertools import pairwise
16
+ from pathlib import Path
17
+ from typing import Final, Protocol, cast
18
+
19
+ import cv2
20
+ import numpy as np
21
+ from numpy.typing import NDArray
22
+ from scenedetect import AdaptiveDetector, FrameTimecode # pyright: ignore[reportMissingTypeStubs]
23
+
24
+ from facescope._limits import check_media_raster
25
+ from facescope._media import media_pipe
26
+ from facescope.errors import AnalysisError
27
+ from facescope.inspection import InspectedSource
28
+ from facescope.plan import SourceGeometry
29
+ from facescope.planner import FaceObservation
30
+ from facescope.progress import ExecutionControl, ProgressEvent, ProgressStage
31
+
32
+ YUNET_MODEL_FILENAME: Final[str] = "face_detection_yunet_2023mar.onnx"
33
+ YUNET_MODEL_SHA256: Final[str] = "8f2383e4dd3cfbb4553ea8718107fc0423210dc964f9f4280604804ed2552fa4"
34
+ YUNET_MODEL_PROVENANCE: Final[str] = (
35
+ "https://media.githubusercontent.com/media/opencv/opencv_zoo/"
36
+ "f12e12798e8314f7c074a6656816c048dcc95b7a/models/face_detection_yunet/"
37
+ "face_detection_yunet_2023mar.onnx"
38
+ )
39
+
40
+
41
+ @dataclass(frozen=True, slots=True)
42
+ class AnalysisTransform:
43
+ """Invertible mapping between display coordinates and resized/padded analysis canvas."""
44
+
45
+ canvas_width: int
46
+ canvas_height: int
47
+ resized_width: int
48
+ resized_height: int
49
+ pad_x: int
50
+ pad_y: int
51
+ display_width: Fraction
52
+ display_height: Fraction
53
+ display_left: Fraction = Fraction(0)
54
+
55
+
56
+ type _BoxEvidence = tuple[Fraction, Fraction, Fraction, Fraction, Fraction]
57
+ type _DisplayEyes = tuple[tuple[Fraction, Fraction], tuple[Fraction, Fraction]]
58
+ type _DisplayDetection = (
59
+ _BoxEvidence | tuple[Fraction, Fraction, Fraction, Fraction, Fraction, _DisplayEyes]
60
+ )
61
+
62
+
63
+ @dataclass(frozen=True, slots=True)
64
+ class RawDetection:
65
+ """Single detection emitted in analysis-canvas pixel coordinates."""
66
+
67
+ left: float | Fraction
68
+ top: float | Fraction
69
+ right: float | Fraction
70
+ bottom: float | Fraction
71
+ confidence: float | Fraction
72
+ eyes: (
73
+ tuple[tuple[float | Fraction, float | Fraction], tuple[float | Fraction, float | Fraction]]
74
+ | None
75
+ ) = None
76
+
77
+
78
+ @dataclass(frozen=True, slots=True)
79
+ class TrackingConfig:
80
+ """Deterministic shot-local face association settings."""
81
+
82
+ min_confidence: Fraction = Fraction(1, 2)
83
+ min_iou: Fraction = Fraction(1, 5)
84
+ max_gap: int = 8
85
+
86
+
87
+ class FaceDetector(Protocol):
88
+ """Protocol for CPU face detectors operating on BGR analysis-canvas images."""
89
+
90
+ @property
91
+ def input_size(self) -> tuple[int, int]: ...
92
+
93
+ def detect(self, canvas_bgr: NDArray[np.uint8]) -> Sequence[RawDetection]: ...
94
+
95
+
96
+ class CutDetector(Protocol):
97
+ """Protocol for shot detectors consuming a one-pass, read-only stream of canvases."""
98
+
99
+ def detect_cuts(
100
+ self,
101
+ frames_bgr: Iterable[NDArray[np.uint8]],
102
+ *,
103
+ frame_rate: Fraction,
104
+ frame_count: int,
105
+ ) -> tuple[tuple[int, int], ...]: ...
106
+
107
+
108
+ def make_analysis_transform(
109
+ source_geometry: SourceGeometry,
110
+ *,
111
+ canvas_size: tuple[int, int] | None = None,
112
+ target_height: int = 360,
113
+ ) -> AnalysisTransform:
114
+ """Build an aspect-preserving resize/letterbox transform for display-space imagery."""
115
+ disp_w = source_geometry.active_display_width
116
+ disp_h = source_geometry.display_height
117
+ if canvas_size is None:
118
+ if target_height <= 0:
119
+ raise AnalysisError(f"target_height must be > 0, got {target_height}")
120
+ canvas_w = max(2, 2 * round(target_height * float(source_geometry.active_dar) / 2))
121
+ canvas_h = target_height
122
+ return AnalysisTransform(
123
+ canvas_width=canvas_w,
124
+ canvas_height=canvas_h,
125
+ resized_width=canvas_w,
126
+ resized_height=canvas_h,
127
+ pad_x=0,
128
+ pad_y=0,
129
+ display_width=disp_w,
130
+ display_height=disp_h,
131
+ display_left=source_geometry.active_left,
132
+ )
133
+
134
+ canvas_w, canvas_h = canvas_size
135
+ if canvas_w <= 0 or canvas_h <= 0:
136
+ raise AnalysisError(f"canvas_size dimensions must be > 0, got {canvas_size}")
137
+ scale = min(Fraction(canvas_w, 1) / disp_w, Fraction(canvas_h, 1) / disp_h)
138
+ resized_w = max(1, min(canvas_w, round(float(disp_w * scale))))
139
+ resized_h = max(1, min(canvas_h, round(float(disp_h * scale))))
140
+ pad_x = (canvas_w - resized_w) // 2
141
+ pad_y = (canvas_h - resized_h) // 2
142
+ return AnalysisTransform(
143
+ canvas_width=canvas_w,
144
+ canvas_height=canvas_h,
145
+ resized_width=resized_w,
146
+ resized_height=resized_h,
147
+ pad_x=pad_x,
148
+ pad_y=pad_y,
149
+ display_width=disp_w,
150
+ display_height=disp_h,
151
+ display_left=source_geometry.active_left,
152
+ )
153
+
154
+
155
+ def prepare_canvas(frame_bgr: NDArray[np.uint8], transform: AnalysisTransform) -> NDArray[np.uint8]:
156
+ """Resize a stored BGR frame to square-pixel display geometry and pad onto the canvas."""
157
+ src_h, src_w = frame_bgr.shape[:2]
158
+ interp = (
159
+ cv2.INTER_AREA
160
+ if transform.resized_width <= src_w and transform.resized_height <= src_h
161
+ else cv2.INTER_LINEAR
162
+ )
163
+ resized = cast(
164
+ NDArray[np.uint8],
165
+ cv2.resize(
166
+ frame_bgr,
167
+ (transform.resized_width, transform.resized_height),
168
+ interpolation=interp,
169
+ ),
170
+ )
171
+ if (
172
+ transform.pad_x == 0
173
+ and transform.pad_y == 0
174
+ and transform.resized_width == transform.canvas_width
175
+ and transform.resized_height == transform.canvas_height
176
+ ):
177
+ return resized
178
+
179
+ canvas = np.zeros((transform.canvas_height, transform.canvas_width, 3), dtype=np.uint8)
180
+ y0, x0 = transform.pad_y, transform.pad_x
181
+ canvas[y0 : y0 + transform.resized_height, x0 : x0 + transform.resized_width] = resized
182
+ return canvas
183
+
184
+
185
+ def _to_exact_rational(value: float | Fraction) -> Fraction:
186
+ if isinstance(value, Fraction):
187
+ return value
188
+ return Fraction(value).limit_denominator(10_000)
189
+
190
+
191
+ def invert_canvas_box(
192
+ detection: RawDetection,
193
+ transform: AnalysisTransform,
194
+ ) -> _BoxEvidence | None:
195
+ """Invert a canvas-space box back into clamped display coordinates and rational confidence."""
196
+ c_left = _to_exact_rational(detection.left)
197
+ c_top = _to_exact_rational(detection.top)
198
+ c_right = _to_exact_rational(detection.right)
199
+ c_bottom = _to_exact_rational(detection.bottom)
200
+ conf = _to_exact_rational(detection.confidence)
201
+ if conf <= 0:
202
+ return None
203
+ conf = min(Fraction(1, 1), conf)
204
+
205
+ scale_x = transform.display_width / Fraction(transform.resized_width, 1)
206
+ scale_y = transform.display_height / Fraction(transform.resized_height, 1)
207
+
208
+ d_left = (c_left - transform.pad_x) * scale_x
209
+ d_top = (c_top - transform.pad_y) * scale_y
210
+ d_right = (c_right - transform.pad_x) * scale_x
211
+ d_bottom = (c_bottom - transform.pad_y) * scale_y
212
+
213
+ clamped_left = max(Fraction(0, 1), min(transform.display_width, d_left))
214
+ clamped_top = max(Fraction(0, 1), min(transform.display_height, d_top))
215
+ clamped_right = max(Fraction(0, 1), min(transform.display_width, d_right))
216
+ clamped_bottom = max(Fraction(0, 1), min(transform.display_height, d_bottom))
217
+ if clamped_left >= clamped_right or clamped_top >= clamped_bottom:
218
+ return None
219
+ return (
220
+ clamped_left + transform.display_left,
221
+ clamped_top,
222
+ clamped_right + transform.display_left,
223
+ clamped_bottom,
224
+ conf,
225
+ )
226
+
227
+
228
+ def _eye_pair(value: object) -> tuple[object, object] | None:
229
+ if isinstance(value, tuple) and len(cast(tuple[object, ...], value)) == 2:
230
+ return cast(tuple[object, object], value)
231
+ return None
232
+
233
+
234
+ def _invert_canvas_eye(
235
+ point: object, transform: AnalysisTransform
236
+ ) -> tuple[Fraction, Fraction] | None:
237
+ values = _eye_pair(point)
238
+ if values is None:
239
+ return None
240
+ x, y = values
241
+ if not isinstance(x, (int, float, Fraction)) or not isinstance(y, (int, float, Fraction)):
242
+ return None
243
+ if isinstance(x, bool) or isinstance(y, bool):
244
+ return None
245
+ if (isinstance(x, float) and not math.isfinite(x)) or (
246
+ isinstance(y, float) and not math.isfinite(y)
247
+ ):
248
+ return None
249
+ if not (transform.pad_x <= x < transform.pad_x + transform.resized_width):
250
+ return None
251
+ if not (transform.pad_y <= y < transform.pad_y + transform.resized_height):
252
+ return None
253
+ display_x = (
254
+ (_to_exact_rational(x) - transform.pad_x)
255
+ * transform.display_width
256
+ / transform.resized_width
257
+ )
258
+ display_y = (
259
+ (_to_exact_rational(y) - transform.pad_y)
260
+ * transform.display_height
261
+ / transform.resized_height
262
+ )
263
+ return display_x + transform.display_left, display_y
264
+
265
+
266
+ def _invert_canvas_eyes(
267
+ eyes: object, transform: AnalysisTransform, box: _BoxEvidence
268
+ ) -> _DisplayEyes | None:
269
+ values = _eye_pair(eyes)
270
+ if values is None:
271
+ return None
272
+ first = _invert_canvas_eye(values[0], transform)
273
+ second = _invert_canvas_eye(values[1], transform)
274
+ if first is None or second is None or first[0] == second[0]:
275
+ return None
276
+ left, top, right, bottom, _ = box
277
+ if not all(
278
+ left <= x < right and top <= y <= top + (bottom - top) * 2 / 3 for x, y in (first, second)
279
+ ):
280
+ return None
281
+ return first, second
282
+
283
+
284
+ def verify_model_file(
285
+ model_path: str | os.PathLike[str],
286
+ *,
287
+ expected_sha256: str | None = YUNET_MODEL_SHA256,
288
+ ) -> Path:
289
+ """Verify a locally provisioned analysis weight file exists and matches its SHA-256."""
290
+ path = Path(model_path)
291
+ if not path.is_file():
292
+ raise AnalysisError(
293
+ f"Missing local face model weights at {path}; download {YUNET_MODEL_FILENAME} "
294
+ f"from {YUNET_MODEL_PROVENANCE} (MIT license) offline before analysis."
295
+ )
296
+ if expected_sha256 is not None:
297
+ with path.open("rb") as handle:
298
+ actual = hashlib.file_digest(handle, "sha256").hexdigest()
299
+ if actual != expected_sha256:
300
+ raise AnalysisError(
301
+ f"Model weights SHA-256 mismatch at {path}: "
302
+ f"expected {expected_sha256}, got {actual}"
303
+ )
304
+ return path
305
+
306
+
307
+ class YuNetFaceDetector:
308
+ """CPU OpenCV FaceDetectorYN wrapper with no global state leakage."""
309
+
310
+ def __init__(
311
+ self,
312
+ model_path: str | os.PathLike[str],
313
+ input_size: tuple[int, int],
314
+ *,
315
+ score_threshold: float = 0.5,
316
+ nms_threshold: float = 0.3,
317
+ top_k: int = 5000,
318
+ expected_sha256: str | None = YUNET_MODEL_SHA256,
319
+ ) -> None:
320
+ verified = verify_model_file(model_path, expected_sha256=expected_sha256)
321
+ w, h = input_size
322
+ if w <= 0 or h <= 0:
323
+ raise AnalysisError(f"YuNet input_size must be positive, got {input_size}")
324
+ self._input_size = (w, h)
325
+
326
+ prev_level = cv2.utils.logging.getLogLevel()
327
+ cv2.utils.logging.setLogLevel(cv2.utils.logging.LOG_LEVEL_ERROR)
328
+ try:
329
+ self._detector = cv2.FaceDetectorYN.create(
330
+ str(verified),
331
+ "",
332
+ (w, h),
333
+ score_threshold,
334
+ nms_threshold,
335
+ top_k,
336
+ )
337
+ except cv2.error as exc:
338
+ raise AnalysisError(
339
+ f"Failed to initialize YuNet detector from {verified}: {exc}"
340
+ ) from exc
341
+ finally:
342
+ cv2.utils.logging.setLogLevel(prev_level)
343
+
344
+ @property
345
+ def input_size(self) -> tuple[int, int]:
346
+ """Expected (width, height) of BGR canvas inputs."""
347
+ return self._input_size
348
+
349
+ def detect(self, canvas_bgr: NDArray[np.uint8]) -> list[RawDetection]:
350
+ """Detect faces on one BGR canvas matching input_size."""
351
+ expected_h, expected_w = self._input_size[1], self._input_size[0]
352
+ if canvas_bgr.shape[:2] != (expected_h, expected_w):
353
+ raise AnalysisError(
354
+ f"Canvas shape {canvas_bgr.shape[:2]} does not match detector "
355
+ f"{(expected_h, expected_w)}"
356
+ )
357
+ try:
358
+ rows_obj = cast(object, self._detector.detect(canvas_bgr)[1])
359
+ except cv2.error as exc:
360
+ raise AnalysisError(f"YuNet inference failed: {exc}") from exc
361
+ if rows_obj is None:
362
+ return []
363
+ values = np.asarray(rows_obj, dtype=float)
364
+ detections: list[RawDetection] = []
365
+ for row in values:
366
+ x, y, w, h, conf = (
367
+ float(row[0]),
368
+ float(row[1]),
369
+ float(row[2]),
370
+ float(row[3]),
371
+ float(row[14]),
372
+ )
373
+ if w <= 0 or h <= 0 or conf <= 0:
374
+ continue
375
+ detections.append(
376
+ RawDetection(
377
+ left=x,
378
+ top=y,
379
+ right=x + w,
380
+ bottom=y + h,
381
+ confidence=min(1.0, conf),
382
+ eyes=((float(row[4]), float(row[5])), (float(row[6]), float(row[7]))),
383
+ )
384
+ )
385
+ return detections
386
+
387
+
388
+ class AdaptiveCutDetector:
389
+ """Presentation-ordered PySceneDetect AdaptiveDetector wrapper."""
390
+
391
+ def __init__(
392
+ self,
393
+ *,
394
+ adaptive_threshold: float = 3.0,
395
+ min_scene_len: int = 15,
396
+ window_width: int = 2,
397
+ min_content_val: float = 15.0,
398
+ ) -> None:
399
+ self._adaptive_threshold = adaptive_threshold
400
+ self._min_scene_len = min_scene_len
401
+ self._window_width = window_width
402
+ self._min_content_val = min_content_val
403
+
404
+ def detect_cuts(
405
+ self,
406
+ frames_bgr: Iterable[NDArray[np.uint8]],
407
+ *,
408
+ frame_rate: Fraction,
409
+ frame_count: int,
410
+ ) -> tuple[tuple[int, int], ...]:
411
+ """Partition [0, frame_count) into contiguous shot ranges in presentation order."""
412
+ if frame_count <= 0:
413
+ raise AnalysisError(f"frame_count must be > 0, got {frame_count}")
414
+ fps = float(frame_rate)
415
+ detector = AdaptiveDetector(
416
+ adaptive_threshold=self._adaptive_threshold,
417
+ min_scene_len=self._min_scene_len,
418
+ window_width=self._window_width,
419
+ min_content_val=self._min_content_val,
420
+ )
421
+ raw_cuts: list[int] = []
422
+ seen = 0
423
+ for idx, frame in enumerate(frames_bgr):
424
+ seen += 1
425
+ cuts = detector.process_frame(FrameTimecode(idx, fps), frame)
426
+ raw_cuts.extend(c.frame_num for c in cuts)
427
+ if seen != frame_count:
428
+ raise AnalysisError(f"Cut detector received {seen} frames, expected {frame_count}")
429
+ post = detector.post_process(FrameTimecode(frame_count, fps))
430
+ raw_cuts.extend(c.frame_num for c in post)
431
+
432
+ boundaries = sorted({c for c in raw_cuts if 0 < c < frame_count})
433
+ points = [0, *boundaries, frame_count]
434
+ return tuple((start, end) for start, end in pairwise(points))
435
+
436
+
437
+ def _box_iou(
438
+ a: tuple[Fraction, Fraction, Fraction, Fraction],
439
+ b: tuple[Fraction, Fraction, Fraction, Fraction],
440
+ ) -> Fraction:
441
+ inter_w = min(a[2], b[2]) - max(a[0], b[0])
442
+ inter_h = min(a[3], b[3]) - max(a[1], b[1])
443
+ if inter_w <= 0 or inter_h <= 0:
444
+ return Fraction(0, 1)
445
+ inter = inter_w * inter_h
446
+ area_a = (a[2] - a[0]) * (a[3] - a[1])
447
+ area_b = (b[2] - b[0]) * (b[3] - b[1])
448
+ union = area_a + area_b - inter
449
+ return inter / union if union > 0 else Fraction(0, 1)
450
+
451
+
452
+ def _associate_tracks(
453
+ frames: Iterable[tuple[int, Sequence[_DisplayDetection]]],
454
+ cfg: TrackingConfig,
455
+ check: Callable[[], None] | None,
456
+ ) -> list[FaceObservation]:
457
+ observations: list[FaceObservation] = []
458
+ next_track_id = 0
459
+ open_tracks: dict[int, tuple[int, tuple[Fraction, Fraction, Fraction, Fraction]]] = {}
460
+ for frame_idx, frame_detections in frames:
461
+ if check is not None and frame_idx % 128 == 0:
462
+ check()
463
+ open_tracks = {
464
+ tid: state
465
+ for tid, state in open_tracks.items()
466
+ if frame_idx - state[0] <= cfg.max_gap + 1
467
+ }
468
+ dets = [det for det in frame_detections if det[4] >= cfg.min_confidence]
469
+ if not dets:
470
+ continue
471
+
472
+ pairs: list[tuple[Fraction, int, int]] = []
473
+ for tid, (_, last_box) in open_tracks.items():
474
+ for d_idx, det in enumerate(dets):
475
+ iou = _box_iou(last_box, det[:4])
476
+ if iou >= cfg.min_iou:
477
+ pairs.append((iou, tid, d_idx))
478
+ pairs.sort(key=lambda item: (-item[0], item[1], item[2]))
479
+
480
+ matched_tracks: set[int] = set()
481
+ matched_dets: set[int] = set()
482
+ for _, tid, d_idx in pairs:
483
+ if tid in matched_tracks or d_idx in matched_dets:
484
+ continue
485
+ matched_tracks.add(tid)
486
+ matched_dets.add(d_idx)
487
+ det = dets[d_idx]
488
+ open_tracks[tid] = (frame_idx, det[:4])
489
+ observations.append(
490
+ FaceObservation(
491
+ frame_index=frame_idx,
492
+ track_id=tid,
493
+ left=det[0],
494
+ top=det[1],
495
+ right=det[2],
496
+ bottom=det[3],
497
+ confidence=det[4],
498
+ eyes=det[5] if len(det) == 6 else None,
499
+ )
500
+ )
501
+
502
+ for d_idx, det in enumerate(dets):
503
+ if d_idx in matched_dets:
504
+ continue
505
+ tid = next_track_id
506
+ next_track_id += 1
507
+ open_tracks[tid] = (frame_idx, det[:4])
508
+ observations.append(
509
+ FaceObservation(
510
+ frame_index=frame_idx,
511
+ track_id=tid,
512
+ left=det[0],
513
+ top=det[1],
514
+ right=det[2],
515
+ bottom=det[3],
516
+ confidence=det[4],
517
+ eyes=det[5] if len(det) == 6 else None,
518
+ )
519
+ )
520
+ return observations
521
+
522
+
523
+ def associate_shot_tracks(
524
+ shot_ranges: Sequence[tuple[int, int]],
525
+ frame_detections: Sequence[Sequence[_DisplayDetection]],
526
+ *,
527
+ config: TrackingConfig | None = None,
528
+ check: Callable[[], None] | None = None,
529
+ ) -> list[FaceObservation]:
530
+ """Associate per-frame display detections into strictly shot-local tracks."""
531
+ cfg = TrackingConfig() if config is None else config
532
+ observations: list[FaceObservation] = []
533
+ for start, end in shot_ranges:
534
+ frames = ((idx, frame_detections[idx]) for idx in range(start, end))
535
+ observations.extend(_associate_tracks(frames, cfg, check))
536
+ return observations
537
+
538
+
539
+ def iter_decoded_bgr_frames(
540
+ inspected: InspectedSource, *, check: Callable[[], None] | None = None
541
+ ) -> Generator[NDArray[np.uint8]]:
542
+ """Stream exact presentation-ordered BGR24 frames from an inspected MKV stream."""
543
+ ffmpeg_bin = shutil.which("ffmpeg")
544
+ if ffmpeg_bin is None:
545
+ raise AnalysisError("Missing required tool 'ffmpeg' on PATH; install FFmpeg first.")
546
+
547
+ width = inspected.source_geometry.stored_width
548
+ height = inspected.source_geometry.stored_height
549
+ expected_frames = inspected.source_geometry.frame_count
550
+ frame_bytes = width * height * 3
551
+ cmd = [
552
+ ffmpeg_bin,
553
+ "-hide_banner",
554
+ "-loglevel",
555
+ "error",
556
+ "-nostdin",
557
+ "-i",
558
+ str(inspected.path),
559
+ "-map",
560
+ f"0:{inspected.stream_identity.stream_index}",
561
+ "-fps_mode",
562
+ "passthrough",
563
+ "-f",
564
+ "rawvideo",
565
+ "-pix_fmt",
566
+ "bgr24",
567
+ "-",
568
+ ]
569
+ with media_pipe(
570
+ cmd, mode="read", error=AnalysisError, stage="FFmpeg decode", check=check
571
+ ) as pipe:
572
+ for index in range(expected_frames):
573
+ chunk = pipe.read(frame_bytes)
574
+ if len(chunk) != frame_bytes:
575
+ raise AnalysisError(
576
+ f"Short picture decode at frame {index}/{expected_frames}: "
577
+ f"expected {frame_bytes} bytes, got {len(chunk)}"
578
+ )
579
+ yield np.frombuffer(chunk, dtype=np.uint8).reshape((height, width, 3)).copy()
580
+ if pipe.read(1):
581
+ raise AnalysisError(f"Picture decode exceeds expected {expected_frames} frames")
582
+
583
+
584
+ def _iter_analyzed_shots(
585
+ inspected: InspectedSource,
586
+ *,
587
+ face_detector: FaceDetector | None = None,
588
+ model_path: str | os.PathLike[str] | None = None,
589
+ cut_detector: CutDetector | None = None,
590
+ canvas_size: tuple[int, int] | None = None,
591
+ tracking_config: TrackingConfig | None = None,
592
+ expected_model_sha256: str | None = YUNET_MODEL_SHA256,
593
+ control: ExecutionControl | None = None,
594
+ analysis_window: int | None = None,
595
+ ) -> Generator[tuple[int, int, list[FaceObservation]]]:
596
+ """Decode a standalone file into the shared bounded shot analyzer."""
597
+ check = None if control is None or control.cancel is None else control.check
598
+ with closing(iter_decoded_bgr_frames(inspected, check=check)) as frames:
599
+ yield from analyze_frame_shots(
600
+ frames,
601
+ geometry=inspected.source_geometry,
602
+ frame_rate=inspected.frame_rate,
603
+ face_detector=face_detector,
604
+ model_path=model_path,
605
+ cut_detector=cut_detector,
606
+ canvas_size=canvas_size,
607
+ tracking_config=tracking_config,
608
+ expected_model_sha256=expected_model_sha256,
609
+ control=control,
610
+ analysis_window=analysis_window,
611
+ )
612
+
613
+
614
+ def analyze_frame_shots(
615
+ frames: Iterable[NDArray[np.uint8]],
616
+ *,
617
+ geometry: SourceGeometry,
618
+ frame_rate: Fraction,
619
+ face_detector: FaceDetector | None = None,
620
+ model_path: str | os.PathLike[str] | None = None,
621
+ cut_detector: CutDetector | None = None,
622
+ canvas_size: tuple[int, int] | None = None,
623
+ tracking_config: TrackingConfig | None = None,
624
+ expected_model_sha256: str | None = YUNET_MODEL_SHA256,
625
+ control: ExecutionControl | None = None,
626
+ analysis_window: int | None = None,
627
+ ) -> Generator[tuple[int, int, list[FaceObservation]]]:
628
+ """Spool detections during the cut pass, then associate one real shot at a time."""
629
+ if face_detector is not None:
630
+ effective_canvas = face_detector.input_size
631
+ transform = make_analysis_transform(geometry, canvas_size=effective_canvas)
632
+ detector: FaceDetector = face_detector
633
+ else:
634
+ if model_path is None:
635
+ raise AnalysisError(
636
+ f"No face_detector or model_path provided; supply local {YUNET_MODEL_FILENAME} "
637
+ f"from {YUNET_MODEL_PROVENANCE}"
638
+ )
639
+ transform = make_analysis_transform(geometry, canvas_size=canvas_size)
640
+ check_media_raster(
641
+ transform.canvas_width,
642
+ transform.canvas_height,
643
+ label="Analysis canvas",
644
+ error=AnalysisError,
645
+ )
646
+ detector = YuNetFaceDetector(
647
+ model_path,
648
+ (transform.canvas_width, transform.canvas_height),
649
+ expected_sha256=expected_model_sha256,
650
+ )
651
+
652
+ if face_detector is not None:
653
+ check_media_raster(
654
+ transform.canvas_width,
655
+ transform.canvas_height,
656
+ label="Analysis canvas",
657
+ error=AnalysisError,
658
+ )
659
+ c_detector: CutDetector = AdaptiveCutDetector() if cut_detector is None else cut_detector
660
+ count = geometry.frame_count
661
+ check = None if control is None or control.cancel is None else control.check
662
+ cfg = TrackingConfig() if tracking_config is None else tracking_config
663
+ left, right = geometry.active_columns
664
+ shape = (geometry.stored_height, geometry.stored_width, 3)
665
+ feed_complete = False
666
+ with tempfile.TemporaryFile() as spool:
667
+
668
+ def detect_and_yield() -> Generator[NDArray[np.uint8]]:
669
+ nonlocal feed_complete
670
+ seen = 0
671
+ for idx, frame in enumerate(frames):
672
+ if idx >= count:
673
+ raise AnalysisError(f"Frame feed exceeds declared count {count}")
674
+ if (
675
+ not isinstance(cast(object, frame), np.ndarray)
676
+ or frame.dtype != np.uint8
677
+ or frame.shape != shape
678
+ ):
679
+ raise AnalysisError(f"Frame {idx} must be a uint8 BGR array of shape {shape}")
680
+ seen += 1
681
+ canvas = prepare_canvas(frame[:, left:right], transform)
682
+ inverted: list[_DisplayDetection] = []
683
+ for raw in detector.detect(canvas):
684
+ box = invert_canvas_box(raw, transform)
685
+ if box is not None:
686
+ eyes = _invert_canvas_eyes(raw.eyes, transform, box)
687
+ inverted.append(box if eyes is None else (*box, eyes))
688
+ # This unlinked file is created and populated here, never from external data.
689
+ data = pickle.dumps(inverted, protocol=pickle.HIGHEST_PROTOCOL)
690
+ try:
691
+ if len(data) > 1024 * 1024 or spool.tell() + len(data) > 4 * 1024**3:
692
+ raise AnalysisError("Detection spill limit exceeded")
693
+ spool.write(data)
694
+ except OSError as exc:
695
+ raise AnalysisError(f"Could not write detection spill: {exc}") from exc
696
+ if control is not None:
697
+ control.report(ProgressEvent(ProgressStage.PLANNING, idx + 1, count))
698
+ yield canvas
699
+ if seen != count:
700
+ raise AnalysisError(f"Frame feed declared {count} frames but yielded {seen}")
701
+ feed_complete = True
702
+
703
+ with closing(detect_and_yield()) as canvases:
704
+ shot_ranges = c_detector.detect_cuts(canvases, frame_rate=frame_rate, frame_count=count)
705
+ # Custom cutters may return before consuming any frames.
706
+ for _ in canvases:
707
+ pass
708
+
709
+ if not feed_complete:
710
+ raise AnalysisError("Cut detector did not permit validation of the complete frame feed")
711
+ expected = 0
712
+ for start, end in shot_ranges:
713
+ if (
714
+ type(start) is not int
715
+ or type(end) is not int
716
+ or start != expected
717
+ or not start < end <= count
718
+ ):
719
+ raise AnalysisError(
720
+ "Cut detector ranges must partition the decoded frame inventory"
721
+ )
722
+ expected = end
723
+ if expected != count:
724
+ raise AnalysisError("Cut detector ranges must partition the decoded frame inventory")
725
+ spool.seek(0)
726
+
727
+ def shot_frames(start: int, end: int) -> Generator[tuple[int, list[_DisplayDetection]]]:
728
+ length = end - start
729
+ summarize = analysis_window is not None and length > analysis_window
730
+ bins = min(128, analysis_window or 128)
731
+ last_bin = -1
732
+ for index in range(start, end):
733
+ if check is not None and index % 128 == 0:
734
+ check()
735
+ dets = cast(list[_DisplayDetection], pickle.load(spool))
736
+ if summarize:
737
+ bucket = (index - start) * bins // length
738
+ if bucket == last_bin or not any(det[4] >= cfg.min_confidence for det in dets):
739
+ continue
740
+ last_bin = bucket
741
+ yield index, dets
742
+
743
+ for start, end in shot_ranges:
744
+ if check is not None:
745
+ check()
746
+ yield start, end, _associate_tracks(shot_frames(start, end), cfg, check)
747
+
748
+
749
+ def analyze_video(
750
+ inspected: InspectedSource,
751
+ *,
752
+ face_detector: FaceDetector | None = None,
753
+ model_path: str | os.PathLike[str] | None = None,
754
+ cut_detector: CutDetector | None = None,
755
+ canvas_size: tuple[int, int] | None = None,
756
+ tracking_config: TrackingConfig | None = None,
757
+ expected_model_sha256: str | None = YUNET_MODEL_SHA256,
758
+ control: ExecutionControl | None = None,
759
+ ) -> tuple[tuple[tuple[int, int], ...], list[FaceObservation]]:
760
+ """Run presentation-ordered cut detection, face detection, and shot-local tracking."""
761
+ ranges: list[tuple[int, int]] = []
762
+ observations: list[FaceObservation] = []
763
+ shots = _iter_analyzed_shots(
764
+ inspected,
765
+ face_detector=face_detector,
766
+ model_path=model_path,
767
+ cut_detector=cut_detector,
768
+ canvas_size=canvas_size,
769
+ tracking_config=tracking_config,
770
+ expected_model_sha256=expected_model_sha256,
771
+ control=control,
772
+ )
773
+ with closing(shots):
774
+ for start, end, shot_observations in shots:
775
+ ranges.append((start, end))
776
+ observations.extend(shot_observations)
777
+ return tuple(ranges), observations