videopython 0.61.0__tar.gz → 0.61.2__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 (101) hide show
  1. {videopython-0.61.0 → videopython-0.61.2}/PKG-INFO +3 -3
  2. {videopython-0.61.0 → videopython-0.61.2}/pyproject.toml +7 -5
  3. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/_ollama.py +26 -2
  4. videopython-0.61.2/src/videopython/ai/_text_chunks.py +32 -0
  5. videopython-0.61.2/src/videopython/ai/dubbing/_phrases.py +95 -0
  6. videopython-0.61.2/src/videopython/ai/dubbing/_synthesis.py +29 -0
  7. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/dubbing/models.py +18 -33
  8. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/dubbing/pipeline.py +49 -11
  9. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/dubbing/remux.py +7 -8
  10. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/dubbing/timing.py +72 -41
  11. videopython-0.61.2/src/videopython/ai/dubbing/translation.py +271 -0
  12. videopython-0.61.2/src/videopython/ai/generation/_speech_graphs.py +115 -0
  13. videopython-0.61.2/src/videopython/ai/generation/_speech_tokens.py +35 -0
  14. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/generation/audio.py +60 -10
  15. videopython-0.61.2/src/videopython/ai/understanding/_pyannote_patches.py +186 -0
  16. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/understanding/audio.py +2 -27
  17. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/audio/audio.py +20 -6
  18. videopython-0.61.0/src/videopython/ai/dubbing/translation.py +0 -328
  19. {videopython-0.61.0 → videopython-0.61.2}/.gitignore +0 -0
  20. {videopython-0.61.0 → videopython-0.61.2}/LICENSE +0 -0
  21. {videopython-0.61.0 → videopython-0.61.2}/README.md +0 -0
  22. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/__init__.py +0 -0
  23. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/_exceptions.py +0 -0
  24. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/_ffmpeg.py +0 -0
  25. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/__init__.py +0 -0
  26. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/_device.py +0 -0
  27. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/_optional.py +0 -0
  28. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/_predictor.py +0 -0
  29. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/_revisions.py +0 -0
  30. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/auto_edit/__init__.py +0 -0
  31. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/auto_edit/backend.py +0 -0
  32. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/auto_edit/catalog.py +0 -0
  33. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/auto_edit/editor.py +0 -0
  34. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/auto_edit/local.py +0 -0
  35. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/auto_edit/models.py +0 -0
  36. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/auto_edit/resolve.py +0 -0
  37. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/dubbing/__init__.py +0 -0
  38. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/dubbing/_tts_backend.py +0 -0
  39. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/dubbing/audio_ops.py +0 -0
  40. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/dubbing/config.py +0 -0
  41. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/dubbing/dubber.py +0 -0
  42. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/dubbing/quality.py +0 -0
  43. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/dubbing/separation.py +0 -0
  44. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/dubbing/voice_sample.py +0 -0
  45. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/effects.py +0 -0
  46. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/errors.py +0 -0
  47. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/generation/__init__.py +0 -0
  48. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/generation/image.py +0 -0
  49. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/generation/video.py +0 -0
  50. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/keyframe.py +0 -0
  51. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/ops.py +0 -0
  52. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/transforms.py +0 -0
  53. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/understanding/__init__.py +0 -0
  54. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/understanding/_detector.py +0 -0
  55. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/understanding/classification.py +0 -0
  56. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/understanding/faces.py +0 -0
  57. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/understanding/image.py +0 -0
  58. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/understanding/objects.py +0 -0
  59. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/understanding/temporal.py +0 -0
  60. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/video_analysis/__init__.py +0 -0
  61. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/video_analysis/analyzer.py +0 -0
  62. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/video_analysis/detectors.py +0 -0
  63. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/video_analysis/models.py +0 -0
  64. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/video_analysis/sampling.py +0 -0
  65. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/ai/video_analysis/source_metadata.py +0 -0
  66. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/audio/__init__.py +0 -0
  67. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/audio/analysis.py +0 -0
  68. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/base/__init__.py +0 -0
  69. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/base/_dimensions.py +0 -0
  70. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/base/_video_io.py +0 -0
  71. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/base/description.py +0 -0
  72. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/base/draw_detections.py +0 -0
  73. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/base/fonts/Anton-OFL.txt +0 -0
  74. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/base/fonts/Anton-Regular.ttf +0 -0
  75. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/base/fonts/BebasNeue-OFL.txt +0 -0
  76. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/base/fonts/BebasNeue-Regular.ttf +0 -0
  77. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/base/fonts/DejaVuSans.ttf +0 -0
  78. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/base/fonts/LICENSE_DEJAVU +0 -0
  79. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/base/fonts/Lato-Bold.ttf +0 -0
  80. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/base/fonts/Lato-OFL.txt +0 -0
  81. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/base/fonts/Poppins-Bold.ttf +0 -0
  82. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/base/fonts/Poppins-OFL.txt +0 -0
  83. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/base/fonts/__init__.py +0 -0
  84. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/base/transcription.py +0 -0
  85. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/base/video.py +0 -0
  86. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/editing/__init__.py +0 -0
  87. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/editing/_ass.py +0 -0
  88. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/editing/_easing.py +0 -0
  89. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/editing/_schema.py +0 -0
  90. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/editing/audio_ops.py +0 -0
  91. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/editing/effects.py +0 -0
  92. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/editing/errors.py +0 -0
  93. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/editing/operation.py +0 -0
  94. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/editing/streaming.py +0 -0
  95. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/editing/transcription_overlay.py +0 -0
  96. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/editing/transforms.py +0 -0
  97. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/editing/video_edit.py +0 -0
  98. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/mcp/__init__.py +0 -0
  99. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/mcp/_models.py +0 -0
  100. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/mcp/server.py +0 -0
  101. {videopython-0.61.0 → videopython-0.61.2}/src/videopython/py.typed +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: videopython
3
- Version: 0.61.0
3
+ Version: 0.61.2
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/
@@ -33,7 +33,7 @@ Requires-Dist: ftfy>=6.1; extra == 'ai'
33
33
  Requires-Dist: imagehash>=4.3; extra == 'ai'
34
34
  Requires-Dist: numba>=0.62; extra == 'ai'
35
35
  Requires-Dist: ollama>=0.5.0; extra == 'ai'
36
- Requires-Dist: pyannote-audio>=4.0.0; extra == 'ai'
36
+ Requires-Dist: pyannote-audio<4.1,>=4.0.7; extra == 'ai'
37
37
  Requires-Dist: pyloudnorm>=0.1.1; extra == 'ai'
38
38
  Requires-Dist: silero-vad>=5.1; extra == 'ai'
39
39
  Requires-Dist: torch>=2.8.0; extra == 'ai'
@@ -42,7 +42,7 @@ Requires-Dist: torchcodec>=0.7.0; extra == 'ai'
42
42
  Requires-Dist: torchvision>=0.23.0; extra == 'ai'
43
43
  Requires-Dist: transformers>=5.2.0; extra == 'ai'
44
44
  Requires-Dist: transnetv2-pytorch>=1.0.5; extra == 'ai'
45
- Requires-Dist: videopython-chatterbox>=0.1.7.post1; extra == 'ai'
45
+ Requires-Dist: videopython-chatterbox>=0.1.7.post2; extra == 'ai'
46
46
  Provides-Extra: mcp
47
47
  Requires-Dist: faster-whisper>=1.2.1; extra == 'mcp'
48
48
  Requires-Dist: imagehash>=4.3; extra == 'mcp'
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "videopython"
3
- version = "0.61.0"
3
+ version = "0.61.2"
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" },
@@ -81,7 +81,9 @@ ai = [
81
81
  # videopython-chatterbox imports librosa, which imports numba. Keep the resolver
82
82
  # from backtracking to a numba release incompatible with the selected NumPy.
83
83
  "numba>=0.62",
84
- "pyannote-audio>=4.0.0",
84
+ # Diarization overrides private pipeline steps verified against 4.0.7.
85
+ # Revalidate inactive-pair filtering and split-frame semantics before 4.1.
86
+ "pyannote-audio>=4.0.7,<4.1",
85
87
  "silero-vad>=5.1",
86
88
  # Visual understanding: detection (D-FINE/YuNet via transformers + opencv core
87
89
  # dep), scene/temporal, VLM (understanding/*, video_analysis)
@@ -91,9 +93,9 @@ ai = [
91
93
  # Audio source separation (understanding/separation.py)
92
94
  "demucs>=4.0.0",
93
95
  # Voice cloning TTS (generation/audio.py). Our fork of chatterbox-tts with
94
- # corrected metadata; import name is still `chatterbox`. Not upstream — its
95
- # `==` pins make [ai] unsatisfiable. See DEVELOPMENT.md "Dependencies".
96
- "videopython-chatterbox>=0.1.7.post1",
96
+ # corrected metadata and short-text alignment fix; import name is `chatterbox`.
97
+ # Upstream's `==` pins make [ai] unsatisfiable. See DEVELOPMENT.md "Dependencies".
98
+ "videopython-chatterbox>=0.1.7.post2",
97
99
  # Local media generation (generation/*). >=0.35 ships QwenImagePipeline + Wan2.2.
98
100
  "diffusers>=0.35.0",
99
101
  # Required, despite looking like diffusers' problem: the Wan2.2 i2v pipeline
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import json
6
+ import logging
6
7
  import re
7
8
  from typing import Any
8
9
 
@@ -12,6 +13,8 @@ from videopython.ai._optional import require
12
13
  from videopython.ai.errors import AiError
13
14
  from videopython.ai.keyframe import encode_png_b64
14
15
 
16
+ logger = logging.getLogger(__name__)
17
+
15
18
 
16
19
  class OllamaError(AiError, RuntimeError):
17
20
  """Ollama returned unusable output (non-JSON or an unexpected shape)."""
@@ -76,9 +79,17 @@ class OllamaStructuredClient:
76
79
  reported by Ollama. An explicit ``num_ctx`` in ``options`` always wins.
77
80
  """
78
81
 
79
- def __init__(self, model: str, *, host: str | None = None, options: dict[str, Any] | None = None) -> None:
82
+ def __init__(
83
+ self,
84
+ model: str,
85
+ *,
86
+ host: str | None = None,
87
+ options: dict[str, Any] | None = None,
88
+ keep_alive: str | int | None = None,
89
+ ) -> None:
80
90
  self.model = model
81
91
  self.host = host
92
+ self.keep_alive = keep_alive
82
93
  self.options: dict[str, Any] = {"temperature": 0.0, **(options or {})}
83
94
  self._client: Any = None
84
95
  self._thinking_capable: bool | None = None
@@ -121,6 +132,8 @@ class OllamaStructuredClient:
121
132
  kwargs: dict[str, Any] = {}
122
133
  if self._supports_thinking():
123
134
  kwargs["think"] = False
135
+ if self.keep_alive is not None:
136
+ kwargs["keep_alive"] = self.keep_alive
124
137
  client = self._get_client()
125
138
  try:
126
139
  response = client.chat(model=self.model, messages=messages, format=schema, options=options, **kwargs)
@@ -130,6 +143,8 @@ class OllamaStructuredClient:
130
143
  raise
131
144
  options = {**options, "num_ctx": retry_num_ctx}
132
145
  response = client.chat(model=self.model, messages=messages, format=schema, options=options, **kwargs)
146
+ if getattr(response, "done_reason", None) == "length":
147
+ raise OllamaError("Ollama exhausted its output budget; refusing an incomplete response")
133
148
  content = response.message.content
134
149
  try:
135
150
  data = json.loads(content)
@@ -140,4 +155,13 @@ class OllamaStructuredClient:
140
155
  return data
141
156
 
142
157
  def unload(self) -> None:
143
- self._client = None
158
+ try:
159
+ if self._client is not None and self.keep_alive is not None:
160
+ # Release explicit residency before the low-memory pipeline
161
+ # loads its next GPU model. Merely dropping the HTTP client
162
+ # leaves the Ollama runner resident on the server.
163
+ self._client.generate(model=self.model, keep_alive=0)
164
+ except Exception as exc:
165
+ logger.warning("Could not unload Ollama model %s; server memory may remain allocated: %s", self.model, exc)
166
+ finally:
167
+ self._client = None
@@ -0,0 +1,32 @@
1
+ import re
2
+
3
+
4
+ def split_text(text: str, max_chars: int) -> list[str]:
5
+ """Prefer sentence, then clause, then word boundaries; retain every character.
6
+
7
+ Whitespace is normalized. Text without usable boundaries (including scripts
8
+ without spaces and long URLs) is split at the character budget as a last resort.
9
+ """
10
+ if max_chars < 1:
11
+ raise ValueError("max_chars must be positive")
12
+ remaining = " ".join(text.split())
13
+ chunks: list[str] = []
14
+ while len(remaining) > max_chars:
15
+ window = remaining[: max_chars + 1]
16
+ boundary = 0
17
+ for pattern in (r"(?:[.!?](?:\s|$)|[。!?])", r"(?:[,;:](?:\s|$)|[,;:])", r"\s"):
18
+ matches = [
19
+ match
20
+ for match in re.finditer(pattern, window)
21
+ if match.start() + (0 if pattern == r"\s" else 1) <= max_chars
22
+ ]
23
+ if matches:
24
+ boundary = matches[-1].start() + (0 if pattern == r"\s" else 1)
25
+ break
26
+ if not boundary:
27
+ boundary = max_chars
28
+ chunks.append(remaining[:boundary].strip())
29
+ remaining = remaining[boundary:].strip()
30
+ if remaining:
31
+ chunks.append(remaining)
32
+ return chunks
@@ -0,0 +1,95 @@
1
+ import math
2
+ import re
3
+
4
+ from videopython.base.transcription import TranscriptionSegment
5
+
6
+ _MAX_SECONDS = 8.0
7
+ _MIN_WORDS = 4
8
+ _ABBREVIATIONS = {"mr.", "mrs.", "ms.", "dr.", "prof.", "e.g.", "i.e.", "np.", "itd.", "itp."}
9
+
10
+
11
+ def timed_phrases(segments: list[TranscriptionSegment]) -> tuple[list[TranscriptionSegment], list[int]]:
12
+ """Return phrases and their source indices, preserving words and speaker ownership.
13
+
14
+ Prefer sentence ends, then pauses/clauses. Bound long runs at word boundaries,
15
+ avoiding tiny fragments which are poor translation and voice-cloning prompts.
16
+ Missing, partial or inconsistent word timing leaves the source segment intact;
17
+ text alone cannot establish trustworthy phrase timestamps.
18
+ """
19
+ phrases: list[TranscriptionSegment] = []
20
+ parents: list[int] = []
21
+ for parent, segment in enumerate(segments):
22
+ words = segment.words
23
+ valid = (
24
+ len(words) >= 2 * _MIN_WORDS
25
+ and "".join(segment.text.split()) == "".join("".join(w.word.split()) for w in words)
26
+ and all(
27
+ math.isfinite(w.start)
28
+ and math.isfinite(w.end)
29
+ and segment.start <= w.start <= w.end <= segment.end
30
+ and w.speaker in (None, segment.speaker)
31
+ for w in words
32
+ )
33
+ and all(a.start <= b.start and a.end <= b.end for a, b in zip(words, words[1:]))
34
+ )
35
+ cuts: list[int] = []
36
+ if valid:
37
+ start = 0
38
+ while len(words) - start >= 2 * _MIN_WORDS:
39
+ strong: list[int] = []
40
+ weak: list[int] = []
41
+ bounded: list[int] = []
42
+ for end in range(start + _MIN_WORDS, len(words) - _MIN_WORDS + 1):
43
+ left, right = words[end - 1], words[end]
44
+ span = left.end - words[start].start
45
+ if span > _MAX_SECONDS:
46
+ break
47
+ if span < 1.5 or left.end > right.start:
48
+ continue
49
+ ending = left.word.rstrip().rstrip("\"'”’)]}")
50
+ bounded.append(end)
51
+ if ending.lower() not in _ABBREVIATIONS and ending.endswith((".", "!", "?", "…", "。", "!", "?")):
52
+ strong.append(end)
53
+ elif span >= 2.5 and (
54
+ ending.endswith((",", ";", ":", ",", ";", ":")) or right.start - left.end >= 0.4
55
+ ):
56
+ weak.append(end)
57
+ # A complete sentence beats an earlier comma: do not detach
58
+ # subordinate clauses when the sentence fits the phrase budget.
59
+ if strong:
60
+ cut = strong[0]
61
+ elif words[-1].end - words[start].start <= _MAX_SECONDS:
62
+ break
63
+ elif weak or bounded:
64
+ cut = (weak or bounded)[-1]
65
+ else:
66
+ break
67
+ cuts.append(cut)
68
+ start = cut
69
+ if not cuts:
70
+ phrases.append(segment)
71
+ parents.append(parent)
72
+ continue
73
+ # Align cuts to the source text so token boundaries do not add spaces.
74
+ text_offsets = [0, *(match.end() for match in re.finditer(r"\S", segment.text))]
75
+ text_start = 0
76
+ text_chars = 0
77
+ start = 0
78
+ for end in [*cuts, len(words)]:
79
+ phrase_words = words[start:end]
80
+ text_chars += sum(len("".join(word.word.split())) for word in phrase_words)
81
+ text_end = text_offsets[text_chars]
82
+ phrases.append(
83
+ segment.model_copy(
84
+ update={
85
+ "start": phrase_words[0].start,
86
+ "end": phrase_words[-1].end,
87
+ "text": segment.text[text_start:text_end].strip(),
88
+ "words": list(phrase_words),
89
+ }
90
+ )
91
+ )
92
+ parents.append(parent)
93
+ start = end
94
+ text_start = text_end
95
+ return phrases, parents
@@ -0,0 +1,29 @@
1
+ from videopython.ai.dubbing.models import TranslatedSegment
2
+
3
+ MAX_GROUP_SECONDS = 10.0
4
+ MAX_GROUP_MEMBERS = 4
5
+ MIN_SYNTHESIS_SECONDS = 0.1
6
+
7
+
8
+ def synthesis_groups(segments: list[TranslatedSegment]) -> list[list[int]]:
9
+ groups: list[list[int]] = []
10
+ for i, segment in enumerate(segments):
11
+ if groups:
12
+ previous = segments[groups[-1][-1]]
13
+ tiny = (
14
+ min(previous.duration, segment.duration) < 1.0
15
+ or min(len(previous.translated_text.strip()), len(segment.translated_text.strip())) < 10
16
+ )
17
+ if (
18
+ tiny
19
+ and len(groups[-1]) < MAX_GROUP_MEMBERS
20
+ and segment.end - segments[groups[-1][0]].start <= MAX_GROUP_SECONDS
21
+ and previous.speaker == segment.speaker
22
+ and 0 <= segment.start - previous.end <= 0.15
23
+ and previous.translated_text.strip()
24
+ and segment.translated_text.strip()
25
+ ):
26
+ groups[-1].append(i)
27
+ continue
28
+ groups.append([i])
29
+ return groups
@@ -21,7 +21,7 @@ class TimingAdjustment:
21
21
  target_duration: Target duration to fit into.
22
22
  actual_duration: Actual duration after adjustment.
23
23
  speed_factor: Speed factor applied (> 1 means sped up).
24
- was_truncated: Whether the segment had to be truncated.
24
+ excessive_speed: Whether fitting exceeded the preferred speed maximum.
25
25
  """
26
26
 
27
27
  segment_index: int
@@ -29,7 +29,7 @@ class TimingAdjustment:
29
29
  target_duration: float
30
30
  actual_duration: float
31
31
  speed_factor: float
32
- was_truncated: bool
32
+ excessive_speed: bool
33
33
 
34
34
 
35
35
  # Speed factors within this band of 1.0 are treated as a "clean" timing
@@ -85,6 +85,7 @@ class TranslatedSegment(BaseModel):
85
85
  speaker: Speaker identifier if available.
86
86
  start: Start time in seconds.
87
87
  end: End time in seconds.
88
+ source_segment_index: Original transcript index when this is a dubbing phrase.
88
89
  """
89
90
 
90
91
  original_segment: TranscriptionSegment
@@ -94,6 +95,7 @@ class TranslatedSegment(BaseModel):
94
95
  speaker: str | None = None
95
96
  start: float = 0.0
96
97
  end: float = 0.0
98
+ source_segment_index: int | None = None
97
99
 
98
100
  @model_validator(mode="after")
99
101
  def _default_timing_from_segment(self) -> TranslatedSegment:
@@ -142,20 +144,14 @@ class SeparatedAudio(BaseModel):
142
144
 
143
145
 
144
146
  class TimingSummary(BaseModel):
145
- """Aggregate stats over per-segment timing adjustments.
146
-
147
- Surfaces how aggressively the timing synchronizer had to compress or
148
- truncate dubbed segments to fit the source's spoken regions. High
149
- truncation rates indicate translation produced text too long for the
150
- source duration.
151
- """
147
+ """Summarize speed changes and count adjustments above the preferred maximum."""
152
148
 
153
149
  total_segments: int
154
150
  clean_count: int
155
151
  stretched_count: int
156
- truncated_count: int
157
152
  mean_speed_factor: float
158
- max_truncation_seconds: float
153
+ excessive_speed_count: int
154
+ max_speed_factor: float
159
155
 
160
156
  @classmethod
161
157
  def from_adjustments(cls, adjustments: list[TimingAdjustment]) -> TimingSummary:
@@ -166,35 +162,20 @@ class TimingSummary(BaseModel):
166
162
  total_segments=0,
167
163
  clean_count=0,
168
164
  stretched_count=0,
169
- truncated_count=0,
170
165
  mean_speed_factor=1.0,
171
- max_truncation_seconds=0.0,
166
+ excessive_speed_count=0,
167
+ max_speed_factor=1.0,
172
168
  )
173
169
 
174
- clean = 0
175
- stretched = 0
176
- truncated = 0
177
- speed_sum = 0.0
178
- max_truncation = 0.0
179
- for adj in adjustments:
180
- speed_sum += adj.speed_factor
181
- if adj.was_truncated:
182
- truncated += 1
183
- truncation = adj.original_duration - adj.actual_duration
184
- if truncation > max_truncation:
185
- max_truncation = truncation
186
- elif abs(adj.speed_factor - 1.0) <= CLEAN_SPEED_TOLERANCE:
187
- clean += 1
188
- else:
189
- stretched += 1
170
+ clean = sum(abs(adj.speed_factor - 1.0) <= CLEAN_SPEED_TOLERANCE for adj in adjustments)
190
171
 
191
172
  return cls(
192
173
  total_segments=total,
193
174
  clean_count=clean,
194
- stretched_count=stretched,
195
- truncated_count=truncated,
196
- mean_speed_factor=speed_sum / total,
197
- max_truncation_seconds=max_truncation,
175
+ stretched_count=total - clean,
176
+ mean_speed_factor=sum(adj.speed_factor for adj in adjustments) / total,
177
+ excessive_speed_count=sum(adj.excessive_speed for adj in adjustments),
178
+ max_speed_factor=max(adj.speed_factor for adj in adjustments),
198
179
  )
199
180
 
200
181
 
@@ -215,6 +196,8 @@ class DubbingResult(BaseModel):
215
196
  translation_failures: Indices of segments the translator could not
216
197
  translate (missing after its parse-retry pass); those segments are
217
198
  dubbed with empty text.
199
+ synthesis_failures: Original segment indices whose speech failed to
200
+ generate or had less than 100 ms after fragment joining.
218
201
  """
219
202
 
220
203
  model_config = ConfigDict(arbitrary_types_allowed=True)
@@ -229,6 +212,8 @@ class DubbingResult(BaseModel):
229
212
  timing_summary: TimingSummary | None = None
230
213
  transcript_quality: TranscriptQuality | None = None
231
214
  translation_failures: list[int] = Field(default_factory=list)
215
+ # Original segment indices, including every member of a failed joined turn.
216
+ synthesis_failures: list[int] = Field(default_factory=list)
232
217
 
233
218
  @property
234
219
  def num_segments(self) -> int:
@@ -160,22 +160,25 @@ class LocalDubbingPipeline:
160
160
  self._init_translator(source_lang=source_lang, target_lang=target_lang)
161
161
 
162
162
  # Translation stage spans 0.35 → 0.50 of overall pipeline progress.
163
- # MarianMT runs sequentially over 8-segment batches; on a 15-min
164
- # source that's minutes of silent dwell on 0.35 without per-batch
165
- # ticks. Map the [0,1] translation fraction onto that 15% window.
163
+ # Map completed bounded translation requests onto the stage's window.
166
164
  def _on_translation_progress(fraction: float) -> None:
167
165
  clamped = max(0.0, min(1.0, fraction))
168
166
  report_progress(f"Translating text ({int(clamped * 100)}%)", 0.35 + 0.15 * clamped)
169
167
 
168
+ from videopython.ai.dubbing._phrases import timed_phrases
169
+
170
+ phrases, parents = timed_phrases(transcription.segments)
170
171
  translated_segments = self._translator.translate_segments(
171
- segments=transcription.segments,
172
+ segments=phrases,
172
173
  target_lang=target_lang,
173
174
  source_lang=source_lang,
174
175
  progress_callback=_on_translation_progress,
175
176
  )
176
- # Capture per-segment failures (always empty for Marian) before
177
+ # Capture per-segment failures before
177
178
  # _maybe_unload nukes the backend in low_memory mode.
178
- translation_failures = list(self._translator.translation_failures)
179
+ translation_failures = sorted({parents[i] for i in self._translator.translation_failures})
180
+ for segment, parent in zip(translated_segments, parents):
181
+ segment.source_segment_index = parent
179
182
  self._maybe_unload("_translator")
180
183
 
181
184
  return translated_segments, translation_failures
@@ -428,6 +431,9 @@ class LocalDubbingPipeline:
428
431
 
429
432
  report_progress("Generating dubbed speech", 0.50)
430
433
 
434
+ from videopython.ai.dubbing._synthesis import MIN_SYNTHESIS_SECONDS, synthesis_groups
435
+
436
+ synthesis_failures: list[int] = []
431
437
  dubbed_segments: list[Audio] = []
432
438
  target_durations: list[float] = []
433
439
  start_times: list[float] = []
@@ -436,8 +442,21 @@ class LocalDubbingPipeline:
436
442
  # The dict is loop-scoped state so the finally block can clean up.
437
443
  speaker_wav_paths: dict[str, Path] = {}
438
444
  try:
439
- for i, segment in enumerate(translated_segments):
440
- if segment.duration < 0.1:
445
+ for indices in synthesis_groups(translated_segments):
446
+ i = max(indices, key=lambda index: translated_segments[index].duration)
447
+ segment = translated_segments[indices[0]]
448
+ if len(indices) > 1:
449
+ segment = segment.model_copy(
450
+ update={
451
+ "translated_text": " ".join(
452
+ translated_segments[index].translated_text for index in indices
453
+ ),
454
+ "end": translated_segments[indices[-1]].end,
455
+ }
456
+ )
457
+ if segment.duration < MIN_SYNTHESIS_SECONDS:
458
+ if segment.translated_text.strip():
459
+ synthesis_failures.extend(indices)
441
460
  continue
442
461
  # Translation filter (translation.py:_is_translatable_text)
443
462
  # leaves translated_text="" for punctuation-only or empty
@@ -446,8 +465,8 @@ class LocalDubbingPipeline:
446
465
  if not segment.translated_text.strip():
447
466
  continue
448
467
 
449
- progress = 0.50 + (0.30 * (i / len(translated_segments)))
450
- report_progress(f"Generating speech ({i + 1}/{len(translated_segments)})", progress)
468
+ progress = 0.50 + (0.30 * (indices[0] / len(translated_segments)))
469
+ report_progress(f"Generating speech ({indices[-1] + 1}/{len(translated_segments)})", progress)
451
470
 
452
471
  speaker = segment.speaker or "speaker_0"
453
472
  dubbed_audio = self._tts_segment_audio(
@@ -460,10 +479,21 @@ class LocalDubbingPipeline:
460
479
  expressiveness=expressiveness_per_segment[i],
461
480
  )
462
481
  if dubbed_audio is None:
482
+ synthesis_failures.extend(indices)
463
483
  continue
464
484
 
465
485
  dubbed_segments.append(dubbed_audio)
466
- target_durations.append(segment.duration)
486
+ # Borrow only unused time before the next original turn, even if
487
+ # that turn failed translation/synthesis. Never cross a speaker.
488
+ next_index = indices[-1] + 1
489
+ next_start = (
490
+ translated_segments[next_index].start
491
+ if next_index < len(translated_segments)
492
+ else source_audio.metadata.duration_seconds
493
+ )
494
+ available = max(segment.duration, next_start - segment.start)
495
+ needed = dubbed_audio.metadata.duration_seconds
496
+ target_durations.append(max(segment.duration, min(available, needed)))
467
497
  start_times.append(segment.start)
468
498
  finally:
469
499
  for path in speaker_wav_paths.values():
@@ -504,6 +534,14 @@ class LocalDubbingPipeline:
504
534
  timing_summary=timing_summary,
505
535
  transcript_quality=transcript_quality,
506
536
  translation_failures=translation_failures,
537
+ synthesis_failures=sorted(
538
+ {
539
+ translated_segments[i].source_segment_index
540
+ if translated_segments[i].source_segment_index is not None
541
+ else i
542
+ for i in synthesis_failures
543
+ }
544
+ ),
507
545
  )
508
546
 
509
547
  def revoice(
@@ -25,14 +25,9 @@ class RemuxError(AiError, RuntimeError):
25
25
 
26
26
 
27
27
  def _build_stream_maps(keep_original_audio: bool) -> list[str]:
28
- """ffmpeg ``-map`` flags for the video + audio + subtitle streams.
29
-
30
- Convention: dubbed audio (input 1) is the *first* audio track so default
31
- playback uses it; original audio (input 0) tags onto the back when
32
- ``keep_original_audio=True`` for editorial A/B. Subtitles from input 0
33
- are carried with ``?`` so sources without subs don't fail the mux.
34
- """
35
- maps = ["-map", "0:v:0", "-map", "1:a:0"]
28
+ """Map the dubbed audio first, followed by optional original audio and subtitles."""
29
+ # MP4/M4A inputs can contain audio only; still produce the dubbed audio.
30
+ maps = ["-map", "0:v:0?", "-map", "1:a:0"]
36
31
  if keep_original_audio:
37
32
  maps += ["-map", "0:a?"]
38
33
  maps += ["-map", "0:s?"]
@@ -96,6 +91,10 @@ def replace_audio_stream_from_audio(
96
91
  "-i",
97
92
  "-",
98
93
  *_build_stream_maps(keep_original_audio),
94
+ "-disposition:a",
95
+ "0",
96
+ "-disposition:a:0",
97
+ "default",
99
98
  "-c:v",
100
99
  "copy",
101
100
  "-c:a",