videopython 0.60.0__tar.gz → 0.61.0__tar.gz

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.
Files changed (94) hide show
  1. {videopython-0.60.0 → videopython-0.61.0}/PKG-INFO +3 -4
  2. {videopython-0.60.0 → videopython-0.61.0}/pyproject.toml +5 -8
  3. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/_revisions.py +7 -6
  4. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/dubbing/models.py +2 -25
  5. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/understanding/audio.py +130 -71
  6. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/video_analysis/models.py +6 -63
  7. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/base/__init__.py +1 -1
  8. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/base/description.py +27 -195
  9. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/base/transcription.py +53 -96
  10. {videopython-0.60.0 → videopython-0.61.0}/.gitignore +0 -0
  11. {videopython-0.60.0 → videopython-0.61.0}/LICENSE +0 -0
  12. {videopython-0.60.0 → videopython-0.61.0}/README.md +0 -0
  13. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/__init__.py +0 -0
  14. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/_exceptions.py +0 -0
  15. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/_ffmpeg.py +0 -0
  16. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/__init__.py +0 -0
  17. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/_device.py +0 -0
  18. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/_ollama.py +0 -0
  19. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/_optional.py +0 -0
  20. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/_predictor.py +0 -0
  21. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/auto_edit/__init__.py +0 -0
  22. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/auto_edit/backend.py +0 -0
  23. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/auto_edit/catalog.py +0 -0
  24. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/auto_edit/editor.py +0 -0
  25. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/auto_edit/local.py +0 -0
  26. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/auto_edit/models.py +0 -0
  27. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/auto_edit/resolve.py +0 -0
  28. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/dubbing/__init__.py +0 -0
  29. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/dubbing/_tts_backend.py +0 -0
  30. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/dubbing/audio_ops.py +0 -0
  31. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/dubbing/config.py +0 -0
  32. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/dubbing/dubber.py +0 -0
  33. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/dubbing/pipeline.py +0 -0
  34. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/dubbing/quality.py +0 -0
  35. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/dubbing/remux.py +0 -0
  36. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/dubbing/separation.py +0 -0
  37. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/dubbing/timing.py +0 -0
  38. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/dubbing/translation.py +0 -0
  39. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/dubbing/voice_sample.py +0 -0
  40. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/effects.py +0 -0
  41. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/errors.py +0 -0
  42. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/generation/__init__.py +0 -0
  43. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/generation/audio.py +0 -0
  44. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/generation/image.py +0 -0
  45. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/generation/video.py +0 -0
  46. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/keyframe.py +0 -0
  47. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/ops.py +0 -0
  48. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/transforms.py +0 -0
  49. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/understanding/__init__.py +0 -0
  50. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/understanding/_detector.py +0 -0
  51. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/understanding/classification.py +0 -0
  52. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/understanding/faces.py +0 -0
  53. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/understanding/image.py +0 -0
  54. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/understanding/objects.py +0 -0
  55. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/understanding/temporal.py +0 -0
  56. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/video_analysis/__init__.py +0 -0
  57. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/video_analysis/analyzer.py +0 -0
  58. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/video_analysis/detectors.py +0 -0
  59. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/video_analysis/sampling.py +0 -0
  60. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/ai/video_analysis/source_metadata.py +0 -0
  61. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/audio/__init__.py +0 -0
  62. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/audio/analysis.py +0 -0
  63. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/audio/audio.py +0 -0
  64. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/base/_dimensions.py +0 -0
  65. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/base/_video_io.py +0 -0
  66. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/base/draw_detections.py +0 -0
  67. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/base/fonts/Anton-OFL.txt +0 -0
  68. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/base/fonts/Anton-Regular.ttf +0 -0
  69. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/base/fonts/BebasNeue-OFL.txt +0 -0
  70. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/base/fonts/BebasNeue-Regular.ttf +0 -0
  71. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/base/fonts/DejaVuSans.ttf +0 -0
  72. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/base/fonts/LICENSE_DEJAVU +0 -0
  73. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/base/fonts/Lato-Bold.ttf +0 -0
  74. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/base/fonts/Lato-OFL.txt +0 -0
  75. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/base/fonts/Poppins-Bold.ttf +0 -0
  76. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/base/fonts/Poppins-OFL.txt +0 -0
  77. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/base/fonts/__init__.py +0 -0
  78. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/base/video.py +0 -0
  79. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/editing/__init__.py +0 -0
  80. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/editing/_ass.py +0 -0
  81. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/editing/_easing.py +0 -0
  82. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/editing/_schema.py +0 -0
  83. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/editing/audio_ops.py +0 -0
  84. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/editing/effects.py +0 -0
  85. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/editing/errors.py +0 -0
  86. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/editing/operation.py +0 -0
  87. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/editing/streaming.py +0 -0
  88. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/editing/transcription_overlay.py +0 -0
  89. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/editing/transforms.py +0 -0
  90. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/editing/video_edit.py +0 -0
  91. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/mcp/__init__.py +0 -0
  92. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/mcp/_models.py +0 -0
  93. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/mcp/server.py +0 -0
  94. {videopython-0.60.0 → videopython-0.61.0}/src/videopython/py.typed +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: videopython
3
- Version: 0.60.0
3
+ Version: 0.61.0
4
4
  Summary: LLM-friendly Python video editing with JSON plans, local AI, and MCP tools.
5
5
  Project-URL: Homepage, https://videopython.com
6
6
  Project-URL: Repository, https://github.com/bartwojtowicz/videopython/
@@ -28,11 +28,11 @@ Provides-Extra: ai
28
28
  Requires-Dist: accelerate>=0.29.2; extra == 'ai'
29
29
  Requires-Dist: demucs>=4.0.0; extra == 'ai'
30
30
  Requires-Dist: diffusers>=0.35.0; extra == 'ai'
31
+ Requires-Dist: faster-whisper>=1.2.1; extra == 'ai'
31
32
  Requires-Dist: ftfy>=6.1; extra == 'ai'
32
33
  Requires-Dist: imagehash>=4.3; extra == 'ai'
33
34
  Requires-Dist: numba>=0.62; extra == 'ai'
34
35
  Requires-Dist: ollama>=0.5.0; extra == 'ai'
35
- Requires-Dist: openai-whisper>=20240930; extra == 'ai'
36
36
  Requires-Dist: pyannote-audio>=4.0.0; extra == 'ai'
37
37
  Requires-Dist: pyloudnorm>=0.1.1; extra == 'ai'
38
38
  Requires-Dist: silero-vad>=5.1; extra == 'ai'
@@ -44,11 +44,10 @@ Requires-Dist: transformers>=5.2.0; extra == 'ai'
44
44
  Requires-Dist: transnetv2-pytorch>=1.0.5; extra == 'ai'
45
45
  Requires-Dist: videopython-chatterbox>=0.1.7.post1; extra == 'ai'
46
46
  Provides-Extra: mcp
47
+ Requires-Dist: faster-whisper>=1.2.1; extra == 'mcp'
47
48
  Requires-Dist: imagehash>=4.3; extra == 'mcp'
48
49
  Requires-Dist: mcp<2,>=1.27; extra == 'mcp'
49
- Requires-Dist: numba>=0.62; extra == 'mcp'
50
50
  Requires-Dist: ollama>=0.5.0; extra == 'mcp'
51
- Requires-Dist: openai-whisper>=20240930; extra == 'mcp'
52
51
  Requires-Dist: torch>=2.8.0; extra == 'mcp'
53
52
  Requires-Dist: torchvision>=0.23.0; extra == 'mcp'
54
53
  Requires-Dist: transformers>=5.2.0; extra == 'mcp'
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "videopython"
3
- version = "0.60.0"
3
+ version = "0.61.0"
4
4
  description = "LLM-friendly Python video editing with JSON plans, local AI, and MCP tools."
5
5
  authors = [
6
6
  { name = "Bartosz Wójtowicz", email = "bartoszwojtowicz@outlook.com" },
@@ -77,11 +77,9 @@ ai = ["videopython[ai]"]
77
77
  [project.optional-dependencies]
78
78
  ai = [
79
79
  # Speech recognition / diarization (understanding/audio.py)
80
- "openai-whisper>=20240930",
81
- # Floored, not capped: numba declares the numpy cap, and without a floor a
82
- # resolver satisfies a newer numpy by backtracking numba instead, breaking
83
- # `import whisper`. 0.62 is the oldest release for the lower supported
84
- # Python versions; Numba's metadata selects a compatible release on 3.14.
80
+ "faster-whisper>=1.2.1",
81
+ # videopython-chatterbox imports librosa, which imports numba. Keep the resolver
82
+ # from backtracking to a numba release incompatible with the selected NumPy.
85
83
  "numba>=0.62",
86
84
  "pyannote-audio>=4.0.0",
87
85
  "silero-vad>=5.1",
@@ -123,8 +121,7 @@ ai = [
123
121
  # dubbing, diarization, source separation, or TTS. Pin MCP <2 — v2 is breaking.
124
122
  mcp = [
125
123
  "mcp>=1.27,<2",
126
- "openai-whisper>=20240930",
127
- "numba>=0.62",
124
+ "faster-whisper>=1.2.1",
128
125
  "transnetv2-pytorch>=1.0.5",
129
126
  "transformers>=5.2.0",
130
127
  "imagehash>=4.3",
@@ -38,12 +38,6 @@ Usage:
38
38
  # argument. The repo id + revision are resolved internally by the
39
39
  # chatterbox package, so there is nothing for us to pass a ``revision`` to.
40
40
  #
41
- # * openai-whisper CDN models -- ai/understanding/audio.py loads transcription
42
- # weights via ``whisper.load_model(name="turbo", ...)`` (tiny/base/small/
43
- # medium/large/turbo). openai-whisper downloads these from OpenAI's own CDN
44
- # by name, NOT through a HF ``from_pretrained`` repo, so there is no HF
45
- # commit SHA to pin. (The faster-whisper backend, if/when used, WOULD map to
46
- # a HF repo and could be pinned -- this code path does not use it.)
47
41
  # ---------------------------------------------------------------------------
48
42
  """
49
43
 
@@ -54,6 +48,13 @@ from __future__ import annotations
54
48
  # ``pinned(model_id)`` resolves with a plain dict lookup. SHAs captured from
55
49
  # the HuggingFace model API (see module docstring for refresh instructions).
56
50
  MODEL_REVISIONS: dict[str, str] = {
51
+ # CTranslate2 Whisper models (ai/understanding/audio.py: AudioToText).
52
+ "Systran/faster-whisper-tiny": "d90ca5fe260221311c53c58e660288d3deb8d356",
53
+ "Systran/faster-whisper-base": "ebe41f70d5b6dfa9166e2c581c45c9c0cfc57b66",
54
+ "Systran/faster-whisper-small": "536b0662742c02347bc0e980a01041f333bce120",
55
+ "Systran/faster-whisper-medium": "08e178d48790749d25932bbc082711ddcfdfbc4f",
56
+ "Systran/faster-whisper-large-v3": "edaa852ec7e145841d8ffdb056a99866b5f0a478",
57
+ "mobiuslabsgmbh/faster-whisper-large-v3-turbo": "0a363e9161cbc7ed1431c9597a8ceaf0c4f78fcf",
57
58
  # Speaker diarization (ai/understanding/audio.py: PYANNOTE_DIARIZATION_MODEL).
58
59
  # Gated repo (auto-approved); from_pretrained needs an accepted HF token.
59
60
  "pyannote/speaker-diarization-community-1": "3533c8cf8e369892e6b79ff1bf80f7b0286a54ee",
@@ -3,9 +3,8 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  from dataclasses import dataclass
6
- from typing import Annotated, Any
7
6
 
8
- from pydantic import BaseModel, BeforeValidator, ConfigDict, Field, PlainSerializer, model_validator
7
+ from pydantic import BaseModel, ConfigDict, Field, model_validator
9
8
 
10
9
  from videopython.ai.dubbing.quality import TranscriptQuality
11
10
  from videopython.audio import Audio
@@ -39,26 +38,6 @@ class TimingAdjustment:
39
38
  CLEAN_SPEED_TOLERANCE = 0.01
40
39
 
41
40
 
42
- # TranscriptionSegment and Transcription still live in videopython.base as
43
- # plain dataclasses with hand-rolled to_dict/from_dict. Bridge them at
44
- # the field boundary so the dubbing cache wire format stays identical.
45
- def _validate_transcription_segment(value: Any) -> Any:
46
- if value is None or isinstance(value, TranscriptionSegment):
47
- return value
48
- return TranscriptionSegment.from_dict(value)
49
-
50
-
51
- def _serialize_with_to_dict(value: Any) -> Any:
52
- return value.to_dict() if value is not None else None
53
-
54
-
55
- _TranscriptionSegmentField = Annotated[
56
- TranscriptionSegment,
57
- BeforeValidator(_validate_transcription_segment),
58
- PlainSerializer(_serialize_with_to_dict, return_type=dict, when_used="always"),
59
- ]
60
-
61
-
62
41
  class Expressiveness(BaseModel):
63
42
  """Chatterbox ``generate()`` knobs derived from source-segment prosody.
64
43
 
@@ -108,9 +87,7 @@ class TranslatedSegment(BaseModel):
108
87
  end: End time in seconds.
109
88
  """
110
89
 
111
- model_config = ConfigDict(arbitrary_types_allowed=True)
112
-
113
- original_segment: _TranscriptionSegmentField
90
+ original_segment: TranscriptionSegment
114
91
  translated_text: str
115
92
  source_lang: str
116
93
  target_lang: str
@@ -3,6 +3,8 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import logging
6
+ from bisect import bisect_left
7
+ from types import MethodType
6
8
  from typing import Any, Literal
7
9
 
8
10
  from videopython.ai._device import log_device_initialization, select_device
@@ -17,6 +19,38 @@ logger = logging.getLogger(__name__)
17
19
  # Whisper's initial_prompt budget; longer prompts are silently truncated by the decoder.
18
20
  _INITIAL_PROMPT_TOKEN_BUDGET = 224
19
21
  _INITIAL_PROMPT_TEMPLATE = "Transcript may include the following names: {terms}."
22
+ _WHISPER_SAMPLE_RATE = 16_000
23
+ _WHISPER_LANGUAGE_SAMPLES = 30 * _WHISPER_SAMPLE_RATE
24
+ _WHISPER_MODELS = {
25
+ "tiny": "Systran/faster-whisper-tiny",
26
+ "base": "Systran/faster-whisper-base",
27
+ "small": "Systran/faster-whisper-small",
28
+ "medium": "Systran/faster-whisper-medium",
29
+ "large": "Systran/faster-whisper-large-v3",
30
+ "turbo": "mobiuslabsgmbh/faster-whisper-large-v3-turbo",
31
+ }
32
+
33
+
34
+ def _reconstruct_diarization(pipeline: Any, segmentations: Any, hard_clusters: Any, count: Any) -> Any:
35
+ """Reconstruct global clusters without promoting segmentation data to float64."""
36
+ import numpy as np
37
+
38
+ num_chunks, num_frames, _ = segmentations.data.shape
39
+ num_clusters = int(np.max(hard_clusters)) + 1
40
+ clustered_data = np.full(
41
+ (num_chunks, num_frames, num_clusters),
42
+ np.nan,
43
+ dtype=segmentations.data.dtype,
44
+ )
45
+
46
+ for chunk_index, (cluster, (_, segmentation)) in enumerate(zip(hard_clusters, segmentations)):
47
+ for cluster_index in np.unique(cluster):
48
+ if cluster_index == -2:
49
+ continue
50
+ clustered_data[chunk_index, :, cluster_index] = np.max(segmentation[:, cluster == cluster_index], axis=1)
51
+
52
+ clustered_segmentations = type(segmentations)(clustered_data, segmentations.sliding_window)
53
+ return pipeline.to_diarization(clustered_segmentations, count)
20
54
 
21
55
 
22
56
  def _normalize_vocabulary(vocabulary: list[str] | None) -> list[str]:
@@ -50,19 +84,18 @@ def _render_initial_prompt(terms: list[str]) -> str:
50
84
  return _INITIAL_PROMPT_TEMPLATE.format(terms=", ".join(terms))
51
85
 
52
86
 
53
- def _build_initial_prompt(vocabulary: list[str]) -> str | None:
87
+ def _build_initial_prompt(vocabulary: list[str], tokenizer: Any) -> str | None:
54
88
  """Render the prompt and trim tail terms until it fits Whisper's
55
89
  224-token ``initial_prompt`` budget; ``None`` for empty input."""
56
90
  if not vocabulary:
57
91
  return None
58
92
 
59
- from videopython.ai._optional import require
60
-
61
- whisper_tokenizer = require("whisper.tokenizer", feature="AudioToText")
62
-
63
- tokenizer = whisper_tokenizer.get_tokenizer(multilingual=True, task="transcribe")
64
93
  kept = list(vocabulary)
65
- while kept and len(tokenizer.encode(_render_initial_prompt(kept))) > _INITIAL_PROMPT_TOKEN_BUDGET:
94
+ while (
95
+ kept
96
+ and len(tokenizer.encode(_render_initial_prompt(kept), add_special_tokens=False).ids)
97
+ > _INITIAL_PROMPT_TOKEN_BUDGET
98
+ ):
66
99
  kept.pop()
67
100
 
68
101
  if not kept:
@@ -80,26 +113,27 @@ def _attach_confidence_by_overlap(
80
113
  target_segments: list[TranscriptionSegment],
81
114
  source_segments: list[TranscriptionSegment],
82
115
  ) -> None:
83
- """Stamp Whisper confidence (avg_logprob, no_speech_prob, compression_ratio)
84
- onto ``target_segments`` from the ``source_segments`` they overlap most with.
116
+ """Copy confidence from the greatest-overlap source into chronological targets.
85
117
 
86
- Re-attaches per-segment confidence after diarization rebuilds segments
87
- from words and drops the original Whisper-segment metadata. Whisper's
88
- confidence is window-level, not phoneme-level, so overlap-by-time is the
89
- right granularity — re-deriving per-word and re-aggregating wouldn't be
90
- more accurate.
91
-
92
- Mutates ``target_segments`` in place. Segments with no overlap to any
93
- source segment are left untouched (their confidence stays None).
118
+ Both lists must be chronological and non-overlapping within themselves. Ties use
119
+ the earlier source. Targets without an overlap stay unchanged.
94
120
  """
121
+ source_index = 0
95
122
  for tgt in target_segments:
123
+ while source_index < len(source_segments) and source_segments[source_index].end <= tgt.start:
124
+ source_index += 1
125
+
96
126
  best_overlap = 0.0
97
127
  best_src: TranscriptionSegment | None = None
98
- for src in source_segments:
99
- overlap = max(0.0, min(tgt.end, src.end) - max(tgt.start, src.start))
128
+ candidate_index = source_index
129
+ while candidate_index < len(source_segments) and source_segments[candidate_index].start < tgt.end:
130
+ src = source_segments[candidate_index]
131
+ overlap = min(tgt.end, src.end) - max(tgt.start, src.start)
100
132
  if overlap > best_overlap:
101
133
  best_overlap = overlap
102
134
  best_src = src
135
+ candidate_index += 1
136
+
103
137
  if best_src is not None:
104
138
  tgt.avg_logprob = best_src.avg_logprob
105
139
  tgt.no_speech_prob = best_src.no_speech_prob
@@ -109,7 +143,7 @@ def _attach_confidence_by_overlap(
109
143
  class AudioToText(ManagedPredictor):
110
144
  """Transcription service for audio and video using local Whisper models.
111
145
 
112
- Uses openai-whisper for transcription (with word-level timestamps) and
146
+ Uses faster-whisper in float32 for transcription (with word-level timestamps) and
113
147
  pyannote-audio for optional speaker diarization. By default, Silero VAD
114
148
  runs before Whisper to gate language detection on a 30s window built from
115
149
  voiced regions only — fixes Whisper's tendency to lock onto the wrong
@@ -152,6 +186,9 @@ class AudioToText(ManagedPredictor):
152
186
  vocabulary: list[str] | None = None,
153
187
  device: str | None = None,
154
188
  ):
189
+ if model_name not in _WHISPER_MODELS:
190
+ choices = ", ".join(_WHISPER_MODELS)
191
+ raise ValueError(f"Unsupported Whisper model {model_name!r}. Choose one of: {choices}.")
155
192
  self.model_name = model_name
156
193
  self.enable_diarization = enable_diarization
157
194
  self.enable_vad = enable_vad
@@ -170,16 +207,22 @@ class AudioToText(ManagedPredictor):
170
207
  self._vad_model: Any = None
171
208
 
172
209
  def _transcribe_kwargs(self, language: str | None, vocabulary: list[str]) -> dict[str, Any]:
173
- """Kwargs threaded into ``whisper.Whisper.transcribe`` from both call sites.
210
+ """Kwargs threaded into faster-whisper from both call sites.
211
+
174
212
  ``initial_prompt`` is omitted entirely on the no-vocab path."""
175
213
  kwargs: dict[str, Any] = {
176
214
  "word_timestamps": True,
177
215
  "language": language,
216
+ "beam_size": 1,
217
+ "best_of": 5,
218
+ "temperature": [0.0, 0.2, 0.4, 0.6, 0.8, 1.0],
219
+ "compression_ratio_threshold": 2.4,
178
220
  "condition_on_previous_text": self.condition_on_previous_text,
179
221
  "no_speech_threshold": self.no_speech_threshold,
180
- "logprob_threshold": self.logprob_threshold,
222
+ "log_prob_threshold": self.logprob_threshold,
223
+ "vad_filter": False,
181
224
  }
182
- prompt = _build_initial_prompt(vocabulary)
225
+ prompt = _build_initial_prompt(vocabulary, self._model.hf_tokenizer)
183
226
  if prompt is not None:
184
227
  kwargs["initial_prompt"] = prompt
185
228
  return kwargs
@@ -188,12 +231,33 @@ class AudioToText(ManagedPredictor):
188
231
  """Initialize local Whisper model."""
189
232
  from videopython.ai._optional import require
190
233
 
191
- whisper = require("whisper", feature="AudioToText")
234
+ faster_whisper = require("faster_whisper", feature="AudioToText")
235
+ model_id = _WHISPER_MODELS[self.model_name]
236
+ self._model = faster_whisper.WhisperModel(
237
+ model_id,
238
+ revision=pinned(model_id),
239
+ device=self.device,
240
+ compute_type="float32",
241
+ )
192
242
 
193
- # No revision pin: openai-whisper downloads weights by name from OpenAI's
194
- # own CDN, not via a HF from_pretrained repo, so there is no HF commit
195
- # SHA to pin (see videopython.ai._revisions module docstring).
196
- self._model = whisper.load_model(name=self.model_name, device=self.device)
243
+ def _run_whisper(self, audio: Any, language: str | None, vocabulary: list[str]) -> dict[str, Any]:
244
+ segments_source, info = self._model.transcribe(
245
+ audio=audio,
246
+ **self._transcribe_kwargs(language, vocabulary),
247
+ )
248
+ segments = [
249
+ {
250
+ "start": segment.start,
251
+ "end": segment.end,
252
+ "text": segment.text,
253
+ "words": [{"start": word.start, "end": word.end, "word": word.word} for word in segment.words or []],
254
+ "avg_logprob": segment.avg_logprob,
255
+ "no_speech_prob": segment.no_speech_prob,
256
+ "compression_ratio": segment.compression_ratio,
257
+ }
258
+ for segment in segments_source
259
+ ]
260
+ return {"segments": segments, "language": info.language}
197
261
 
198
262
  def _init_diarization(self) -> None:
199
263
  """Initialize pyannote speaker diarization pipeline."""
@@ -206,6 +270,10 @@ class AudioToText(ManagedPredictor):
206
270
  self._diarization_pipeline = Pipeline.from_pretrained(
207
271
  self.PYANNOTE_DIARIZATION_MODEL, revision=pinned(self.PYANNOTE_DIARIZATION_MODEL)
208
272
  )
273
+ if not callable(getattr(self._diarization_pipeline, "reconstruct", None)):
274
+ raise RuntimeError("The pyannote diarization pipeline no longer provides reconstruct().")
275
+ # pyannote otherwise promotes its duration-by-speaker workspace to float64.
276
+ self._diarization_pipeline.reconstruct = MethodType(_reconstruct_diarization, self._diarization_pipeline)
209
277
  self._diarization_pipeline.to(torch.device(self.device))
210
278
 
211
279
  def _init_vad(self) -> None:
@@ -247,42 +315,45 @@ class AudioToText(ManagedPredictor):
247
315
  words: list[TranscriptionWord],
248
316
  diarization_result: Any,
249
317
  ) -> list[TranscriptionWord]:
250
- """Assign speaker labels to words based on diarization segment overlap.
251
-
252
- For each word, finds the diarization segment with the greatest time overlap
253
- and assigns that speaker. Words with no overlapping diarization segment get
254
- the nearest speaker by midpoint distance.
255
- """
318
+ """Assign speakers to chronological words from exclusive diarization tracks."""
256
319
  speaker_segments: list[tuple[float, float, str]] = []
257
- # pyannote-audio 4.x returns DiarizeOutput; use exclusive_speaker_diarization
258
- # (no overlapping turns) for cleaner word assignment.
259
- annotation = getattr(diarization_result, "exclusive_speaker_diarization", diarization_result)
320
+ annotation = diarization_result.exclusive_speaker_diarization
260
321
  for turn, _, speaker in annotation.itertracks(yield_label=True):
261
322
  speaker_segments.append((turn.start, turn.end, speaker))
262
323
 
263
324
  if not speaker_segments:
264
325
  return words
265
326
 
327
+ speaker_segments.sort(key=lambda segment: (segment[0], segment[1]))
328
+ speaker_midpoints = [(start + end) / 2.0 for start, end, _ in speaker_segments]
266
329
  result = []
330
+ segment_index = 0
267
331
  for word in words:
332
+ while segment_index < len(speaker_segments) and speaker_segments[segment_index][1] <= word.start:
333
+ segment_index += 1
334
+
268
335
  best_speaker: str | None = None
269
336
  best_overlap = 0.0
270
-
271
- for seg_start, seg_end, speaker in speaker_segments:
272
- overlap = max(0.0, min(word.end, seg_end) - max(word.start, seg_start))
337
+ candidate_index = segment_index
338
+ while candidate_index < len(speaker_segments) and speaker_segments[candidate_index][0] < word.end:
339
+ seg_start, seg_end, speaker = speaker_segments[candidate_index]
340
+ overlap = min(word.end, seg_end) - max(word.start, seg_start)
273
341
  if overlap > best_overlap:
274
342
  best_overlap = overlap
275
343
  best_speaker = speaker
344
+ candidate_index += 1
276
345
 
277
346
  if best_speaker is None:
278
347
  word_mid = (word.start + word.end) / 2.0
279
- best_dist = float("inf")
280
- for seg_start, seg_end, speaker in speaker_segments:
281
- seg_mid = (seg_start + seg_end) / 2.0
282
- dist = abs(word_mid - seg_mid)
283
- if dist < best_dist:
284
- best_dist = dist
285
- best_speaker = speaker
348
+ nearest_index = bisect_left(speaker_midpoints, word_mid)
349
+ if nearest_index == len(speaker_segments):
350
+ nearest_index -= 1
351
+ elif nearest_index > 0:
352
+ previous_distance = word_mid - speaker_midpoints[nearest_index - 1]
353
+ next_distance = speaker_midpoints[nearest_index] - word_mid
354
+ if previous_distance <= next_distance:
355
+ nearest_index -= 1
356
+ best_speaker = speaker_segments[nearest_index][2]
286
357
 
287
358
  result.append(
288
359
  TranscriptionWord(
@@ -309,7 +380,7 @@ class AudioToText(ManagedPredictor):
309
380
  import numpy as np
310
381
  import torch
311
382
 
312
- all_words: list[TranscriptionWord] = list(transcription.words)
383
+ all_words = sorted(transcription.words, key=lambda word: (word.start, word.end))
313
384
  if not all_words:
314
385
  raise ValueError("Cannot diarize a transcription with no words.")
315
386
 
@@ -325,9 +396,7 @@ class AudioToText(ManagedPredictor):
325
396
  if self._diarization_pipeline is None:
326
397
  self._init_diarization()
327
398
 
328
- import whisper
329
-
330
- audio_mono = audio.to_mono().resample(whisper.audio.SAMPLE_RATE)
399
+ audio_mono = audio.to_mono().resample(_WHISPER_SAMPLE_RATE)
331
400
  waveform = torch.from_numpy(audio_mono.data.astype(np.float32)).unsqueeze(0)
332
401
  diarization_result = self._diarization_pipeline(
333
402
  {"waveform": waveform, "sample_rate": audio_mono.metadata.sample_rate}
@@ -340,7 +409,7 @@ class AudioToText(ManagedPredictor):
340
409
  # combined path -- so re-attach it the same way. Without this, splitting
341
410
  # transcription and diarization into two calls silently loses confidence
342
411
  # that running them as one keeps.
343
- source_segments = transcription.segments
412
+ source_segments = sorted(transcription.segments, key=lambda segment: (segment.start, segment.end))
344
413
  rebuilt = Transcription(words=all_words, language=transcription.language)
345
414
  _attach_confidence_by_overlap(rebuilt.segments, source_segments)
346
415
  return rebuilt
@@ -348,7 +417,7 @@ class AudioToText(ManagedPredictor):
348
417
  def _run_vad(self, audio_mono: Audio) -> list[tuple[float, float]]:
349
418
  """Return voiced spans in seconds using Silero VAD.
350
419
 
351
- Audio must already be mono at ``whisper.audio.SAMPLE_RATE`` (16 kHz),
420
+ Audio must already be mono at 16 kHz,
352
421
  which is one of Silero's two supported rates.
353
422
  """
354
423
  import numpy as np
@@ -374,16 +443,13 @@ class AudioToText(ManagedPredictor):
374
443
  Whisper's auto-detection only inspects the first 30s of input. When
375
444
  the file opens with silence/music/credits, that window contains no
376
445
  speech and detection picks the closest-looking thing (typically
377
- English). Concatenating voiced spans up to 30s and running
378
- ``model.detect_language()`` on the resulting mel fixes this.
446
+ English). Concatenating up to 30 seconds of voiced audio fixes this.
379
447
  """
380
448
  import numpy as np
381
- import torch
382
- import whisper
383
449
 
384
450
  sample_rate = audio_mono.metadata.sample_rate
385
451
  chunks: list[np.ndarray] = []
386
- remaining = whisper.audio.N_SAMPLES
452
+ remaining = _WHISPER_LANGUAGE_SAMPLES
387
453
  for start, end in voiced_spans:
388
454
  if remaining <= 0:
389
455
  break
@@ -391,12 +457,9 @@ class AudioToText(ManagedPredictor):
391
457
  chunks.append(chunk)
392
458
  remaining -= len(chunk)
393
459
 
394
- voiced_audio = np.concatenate(chunks).astype(np.float32) if chunks else np.zeros(0, dtype=np.float32)
395
- padded = whisper.audio.pad_or_trim(torch.from_numpy(voiced_audio))
396
- mel = whisper.audio.log_mel_spectrogram(padded, n_mels=self._model.dims.n_mels).to(self._model.device)
397
-
398
- _, probs = self._model.detect_language(mel)
399
- return max(probs, key=probs.get)
460
+ voiced_audio = np.concatenate(chunks).astype(np.float32)
461
+ language, _, _ = self._model.detect_language(audio=voiced_audio)
462
+ return language
400
463
 
401
464
  def _transcribe_with_diarization(
402
465
  self, audio_mono: Audio, language: str | None, vocabulary: list[str]
@@ -409,7 +472,7 @@ class AudioToText(ManagedPredictor):
409
472
  self._init_diarization()
410
473
 
411
474
  audio_data = audio_mono.data
412
- transcription_result = self._model.transcribe(audio=audio_data, **self._transcribe_kwargs(language, vocabulary))
475
+ transcription_result = self._run_whisper(audio_data, language, vocabulary)
413
476
 
414
477
  waveform = torch.from_numpy(audio_data.astype(np.float32)).unsqueeze(0)
415
478
  diarization_result = self._diarization_pipeline(
@@ -448,12 +511,10 @@ class AudioToText(ManagedPredictor):
448
511
  finds no speech, an empty Transcription is returned without
449
512
  invoking Whisper.
450
513
  """
451
- import whisper
452
-
453
514
  if self._model is None:
454
515
  self._init_local()
455
516
 
456
- audio_mono = audio.to_mono().resample(whisper.audio.SAMPLE_RATE)
517
+ audio_mono = audio.to_mono().resample(_WHISPER_SAMPLE_RATE)
457
518
 
458
519
  language: str | None = None
459
520
  if self.enable_vad:
@@ -465,9 +526,7 @@ class AudioToText(ManagedPredictor):
465
526
  if self.enable_diarization:
466
527
  return self._transcribe_with_diarization(audio_mono, language, vocabulary)
467
528
 
468
- transcription_result = self._model.transcribe(
469
- audio=audio_mono.data, **self._transcribe_kwargs(language, vocabulary)
470
- )
529
+ transcription_result = self._run_whisper(audio_mono.data, language, vocabulary)
471
530
  return self._process_transcription_result(transcription_result)
472
531
 
473
532
  def transcribe(self, media: Audio | Video, vocabulary: list[str] | None = None) -> Transcription:
@@ -3,9 +3,9 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  from pathlib import Path
6
- from typing import Annotated, Any, Literal
6
+ from typing import Any, Literal
7
7
 
8
- from pydantic import BaseModel, BeforeValidator, ConfigDict, Field, PlainSerializer, model_validator
8
+ from pydantic import BaseModel, ConfigDict, Field, model_validator
9
9
 
10
10
  from videopython.base.description import AudioClassification, FaceTrack, SceneDescription
11
11
  from videopython.base.transcription import Transcription
@@ -51,59 +51,6 @@ ALL_ANALYZER_IDS: tuple[_AnalyzerId, ...] = (
51
51
  )
52
52
 
53
53
 
54
- # Nested-type bridges: Transcription, SceneDescription, AudioClassification,
55
- # and FaceTrack still live in videopython.base as plain dataclasses with
56
- # hand-rolled to_dict/from_dict. Until they migrate to BaseModel, we
57
- # interop at the field boundary so the wire format stays identical.
58
- def _build_validator(cls: Any) -> Any:
59
- def _validate(value: Any) -> Any:
60
- if value is None or isinstance(value, cls):
61
- return value
62
- return cls.from_dict(value)
63
-
64
- return _validate
65
-
66
-
67
- def _serialize(value: Any) -> Any:
68
- return value.to_dict() if value is not None else None
69
-
70
-
71
- _TranscriptionField = Annotated[
72
- Transcription,
73
- BeforeValidator(_build_validator(Transcription)),
74
- PlainSerializer(_serialize, return_type=dict, when_used="always"),
75
- ]
76
- _SceneDescriptionField = Annotated[
77
- SceneDescription,
78
- BeforeValidator(_build_validator(SceneDescription)),
79
- PlainSerializer(_serialize, return_type=dict, when_used="always"),
80
- ]
81
- _AudioClassificationField = Annotated[
82
- AudioClassification,
83
- BeforeValidator(_build_validator(AudioClassification)),
84
- PlainSerializer(_serialize, return_type=dict, when_used="always"),
85
- ]
86
-
87
-
88
- def _validate_face_tracks(value: Any) -> Any:
89
- if value is None:
90
- return None
91
- return [item if isinstance(item, FaceTrack) else FaceTrack.from_dict(item) for item in value]
92
-
93
-
94
- def _serialize_face_tracks(value: Any) -> Any:
95
- if value is None:
96
- return None
97
- return [track.to_dict() for track in value]
98
-
99
-
100
- _FaceTracksField = Annotated[
101
- list[FaceTrack],
102
- BeforeValidator(_validate_face_tracks),
103
- PlainSerializer(_serialize_face_tracks, return_type=list, when_used="always"),
104
- ]
105
-
106
-
107
54
  class GeoMetadata(BaseModel):
108
55
  """Optional geolocation metadata attached to a video container."""
109
56
 
@@ -206,9 +153,7 @@ class VideoAnalysisConfig(BaseModel):
206
153
  class AudioAnalysisSection(BaseModel):
207
154
  """Audio understanding outputs."""
208
155
 
209
- model_config = ConfigDict(arbitrary_types_allowed=True)
210
-
211
- transcription: _TranscriptionField | None = None
156
+ transcription: Transcription | None = None
212
157
 
213
158
 
214
159
  class SceneAnalysisSample(BaseModel):
@@ -220,16 +165,14 @@ class SceneAnalysisSample(BaseModel):
220
165
  trajectory internally.
221
166
  """
222
167
 
223
- model_config = ConfigDict(arbitrary_types_allowed=True)
224
-
225
168
  scene_index: int
226
169
  start_second: float
227
170
  end_second: float
228
171
  start_frame: int | None = None
229
172
  end_frame: int | None = None
230
- scene_description: _SceneDescriptionField | None = None
231
- audio_classification: _AudioClassificationField | None = None
232
- faces: _FaceTracksField | None = None
173
+ scene_description: SceneDescription | None = None
174
+ audio_classification: AudioClassification | None = None
175
+ faces: list[FaceTrack] | None = None
233
176
 
234
177
 
235
178
  class SceneAnalysisSection(BaseModel):
@@ -41,7 +41,7 @@ __all__ = [
41
41
  "draw_detections",
42
42
  "DetectionStyle",
43
43
  "class_color",
44
- # Transcription data classes
44
+ # Transcription result models
45
45
  "Transcription",
46
46
  "TranscriptionSegment",
47
47
  "TranscriptionWord",