videopython 0.61.1__tar.gz → 0.62.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 (105) hide show
  1. {videopython-0.61.1 → videopython-0.62.0}/PKG-INFO +16 -31
  2. {videopython-0.61.1 → videopython-0.62.0}/README.md +14 -29
  3. {videopython-0.61.1 → videopython-0.62.0}/pyproject.toml +4 -4
  4. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/_ffmpeg.py +24 -1
  5. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/_ollama.py +39 -2
  6. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/_predictor.py +4 -0
  7. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/_revisions.py +10 -0
  8. videopython-0.62.0/src/videopython/ai/_text_chunks.py +32 -0
  9. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/auto_edit/__init__.py +2 -1
  10. videopython-0.62.0/src/videopython/ai/auto_edit/_speech.py +54 -0
  11. videopython-0.62.0/src/videopython/ai/auto_edit/catalog.py +146 -0
  12. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/auto_edit/models.py +18 -1
  13. videopython-0.62.0/src/videopython/ai/dubbing/_phrases.py +95 -0
  14. videopython-0.62.0/src/videopython/ai/dubbing/_synthesis.py +29 -0
  15. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/dubbing/config.py +1 -1
  16. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/dubbing/models.py +18 -33
  17. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/dubbing/pipeline.py +49 -11
  18. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/dubbing/remux.py +7 -8
  19. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/dubbing/timing.py +72 -41
  20. videopython-0.62.0/src/videopython/ai/dubbing/translation.py +271 -0
  21. videopython-0.62.0/src/videopython/ai/generation/_speech_graphs.py +115 -0
  22. videopython-0.62.0/src/videopython/ai/generation/_speech_tokens.py +35 -0
  23. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/generation/audio.py +60 -10
  24. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/keyframe.py +0 -9
  25. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/understanding/_pyannote_patches.py +4 -10
  26. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/understanding/audio.py +11 -4
  27. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/understanding/classification.py +5 -0
  28. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/understanding/faces.py +8 -0
  29. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/understanding/image.py +3 -0
  30. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/understanding/temporal.py +6 -0
  31. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/video_analysis/__init__.py +2 -0
  32. videopython-0.62.0/src/videopython/ai/video_analysis/_identity.py +10 -0
  33. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/video_analysis/analyzer.py +27 -6
  34. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/video_analysis/detectors.py +16 -3
  35. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/video_analysis/models.py +24 -0
  36. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/audio/audio.py +20 -6
  37. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/base/video.py +33 -30
  38. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/editing/__init__.py +2 -0
  39. videopython-0.62.0/src/videopython/editing/progress.py +55 -0
  40. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/editing/streaming.py +14 -4
  41. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/editing/video_edit.py +55 -11
  42. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/mcp/_models.py +13 -1
  43. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/mcp/server.py +99 -17
  44. videopython-0.61.1/src/videopython/ai/auto_edit/catalog.py +0 -90
  45. videopython-0.61.1/src/videopython/ai/dubbing/translation.py +0 -328
  46. {videopython-0.61.1 → videopython-0.62.0}/.gitignore +0 -0
  47. {videopython-0.61.1 → videopython-0.62.0}/LICENSE +0 -0
  48. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/__init__.py +0 -0
  49. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/_exceptions.py +0 -0
  50. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/__init__.py +0 -0
  51. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/_device.py +0 -0
  52. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/_optional.py +0 -0
  53. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/auto_edit/backend.py +0 -0
  54. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/auto_edit/editor.py +0 -0
  55. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/auto_edit/local.py +0 -0
  56. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/auto_edit/resolve.py +0 -0
  57. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/dubbing/__init__.py +0 -0
  58. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/dubbing/_tts_backend.py +0 -0
  59. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/dubbing/audio_ops.py +0 -0
  60. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/dubbing/dubber.py +0 -0
  61. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/dubbing/quality.py +0 -0
  62. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/dubbing/separation.py +0 -0
  63. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/dubbing/voice_sample.py +0 -0
  64. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/effects.py +0 -0
  65. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/errors.py +0 -0
  66. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/generation/__init__.py +0 -0
  67. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/generation/image.py +0 -0
  68. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/generation/video.py +0 -0
  69. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/ops.py +0 -0
  70. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/transforms.py +0 -0
  71. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/understanding/__init__.py +0 -0
  72. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/understanding/_detector.py +0 -0
  73. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/understanding/objects.py +0 -0
  74. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/video_analysis/sampling.py +0 -0
  75. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/ai/video_analysis/source_metadata.py +0 -0
  76. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/audio/__init__.py +0 -0
  77. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/audio/analysis.py +0 -0
  78. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/base/__init__.py +0 -0
  79. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/base/_dimensions.py +0 -0
  80. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/base/_video_io.py +0 -0
  81. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/base/description.py +0 -0
  82. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/base/draw_detections.py +0 -0
  83. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/base/fonts/Anton-OFL.txt +0 -0
  84. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/base/fonts/Anton-Regular.ttf +0 -0
  85. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/base/fonts/BebasNeue-OFL.txt +0 -0
  86. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/base/fonts/BebasNeue-Regular.ttf +0 -0
  87. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/base/fonts/DejaVuSans.ttf +0 -0
  88. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/base/fonts/LICENSE_DEJAVU +0 -0
  89. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/base/fonts/Lato-Bold.ttf +0 -0
  90. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/base/fonts/Lato-OFL.txt +0 -0
  91. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/base/fonts/Poppins-Bold.ttf +0 -0
  92. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/base/fonts/Poppins-OFL.txt +0 -0
  93. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/base/fonts/__init__.py +0 -0
  94. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/base/transcription.py +0 -0
  95. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/editing/_ass.py +0 -0
  96. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/editing/_easing.py +0 -0
  97. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/editing/_schema.py +0 -0
  98. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/editing/audio_ops.py +0 -0
  99. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/editing/effects.py +0 -0
  100. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/editing/errors.py +0 -0
  101. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/editing/operation.py +0 -0
  102. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/editing/transcription_overlay.py +0 -0
  103. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/editing/transforms.py +0 -0
  104. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/mcp/__init__.py +0 -0
  105. {videopython-0.61.1 → videopython-0.62.0}/src/videopython/py.typed +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: videopython
3
- Version: 0.61.1
3
+ Version: 0.62.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/
@@ -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'
@@ -65,12 +65,11 @@ Structured, local-first video editing for Python and AI agents.
65
65
 
66
66
  Videopython represents an edit as a validated Python model or JSON plan. Whether the
67
67
  plan comes from your code, an LLM, or an MCP client, it renders through the same
68
- bounded-memory streaming engine.
68
+ streaming engine with bounded frame buffers.
69
69
 
70
70
  [Documentation](https://videopython.com) ·
71
71
  [First edit](https://videopython.com/tutorials/first-edit/) ·
72
- [API reference](https://videopython.com/reference/) ·
73
- [Roadmap](ROADMAP.md)
72
+ [API reference](https://videopython.com/reference/)
74
73
 
75
74
  ## Why videopython?
76
75
 
@@ -87,19 +86,10 @@ bounded-memory streaming engine.
87
86
 
88
87
  ## Installation
89
88
 
90
- Install [FFmpeg](https://ffmpeg.org/download.html), then choose the package extras you
91
- need:
92
-
93
- ```bash
94
- pip install videopython # core video and audio editing
95
- pip install "videopython[ai]" # all local AI features
96
- pip install "videopython[mcp]" # MCP and its focused analysis stack
97
- ```
98
-
99
- Videopython supports Python `>=3.11, <3.15`. The `ai` and `mcp` extras are independent;
100
- install `videopython[ai,mcp]` if you need both. See the
101
- [installation guide](https://videopython.com/install/) for FFmpeg features, model
102
- downloads, Ollama setup, and hardware requirements.
89
+ Install FFmpeg, then run `uv add videopython` (or `pip install videopython`).
90
+ The optional `ai` and `mcp` extras add model runtimes and the MCP server.
91
+ See the [installation guide](https://videopython.com/install/) for supported
92
+ Python versions, extras, FFmpeg features, and model setup.
103
93
 
104
94
  ## Quick start
105
95
 
@@ -127,8 +117,8 @@ edit.validate()
127
117
  edit.run_to_file("output.mp4")
128
118
  ```
129
119
 
130
- `run_to_file()` streams the source through FFmpeg and the operation pipeline, so memory
131
- use stays bounded for long videos. Continue with
120
+ `run_to_file()` streams the source through FFmpeg and the operation pipeline, so frame buffers
121
+ stay bounded for long videos. Continue with
132
122
  [Your first edit](https://videopython.com/tutorials/first-edit/).
133
123
 
134
124
  ## What you can build
@@ -143,22 +133,17 @@ use stays bounded for long videos. Continue with
143
133
  Core editing does not install PyTorch or other model runtimes. AI dependencies load only
144
134
  when you use an AI feature.
145
135
 
146
- ## Documentation
147
-
148
- The documentation follows [Diataxis](https://diataxis.fr/):
136
+ ## Scope
149
137
 
150
- - [Tutorials](https://videopython.com/tutorials/) teach the library through complete
151
- examples.
152
- - [How-to guides](https://videopython.com/how-to/) cover specific editing and AI tasks.
153
- - [Reference](https://videopython.com/reference/) documents the API, operations, and
154
- JSON wire format.
155
- - [Explanation](https://videopython.com/explanation/) covers the streaming engine,
156
- plan lifecycle, architecture, and LLM-first design.
138
+ Videopython is a library for programmatic editing. It does not provide a hosted
139
+ inference service, an interactive editing application, universal support for model
140
+ runtimes and FFmpeg builds, or a second in-memory operation engine.
157
141
 
158
142
  ## Project status
159
143
 
160
144
  Videopython is pre-1.0, so public interfaces can still change. See the
161
- [roadmap](ROADMAP.md) for the stability criteria and [release notes](RELEASE_NOTES.md)
145
+ [compatibility policy](docs/reference/compatibility.md) for public contracts and
146
+ versioning rules, and [release notes](RELEASE_NOTES.md)
162
147
  for changes between versions. Report vulnerabilities through the [security
163
148
  policy](SECURITY.md).
164
149
 
@@ -9,12 +9,11 @@ Structured, local-first video editing for Python and AI agents.
9
9
 
10
10
  Videopython represents an edit as a validated Python model or JSON plan. Whether the
11
11
  plan comes from your code, an LLM, or an MCP client, it renders through the same
12
- bounded-memory streaming engine.
12
+ streaming engine with bounded frame buffers.
13
13
 
14
14
  [Documentation](https://videopython.com) ·
15
15
  [First edit](https://videopython.com/tutorials/first-edit/) ·
16
- [API reference](https://videopython.com/reference/) ·
17
- [Roadmap](ROADMAP.md)
16
+ [API reference](https://videopython.com/reference/)
18
17
 
19
18
  ## Why videopython?
20
19
 
@@ -31,19 +30,10 @@ bounded-memory streaming engine.
31
30
 
32
31
  ## Installation
33
32
 
34
- Install [FFmpeg](https://ffmpeg.org/download.html), then choose the package extras you
35
- need:
36
-
37
- ```bash
38
- pip install videopython # core video and audio editing
39
- pip install "videopython[ai]" # all local AI features
40
- pip install "videopython[mcp]" # MCP and its focused analysis stack
41
- ```
42
-
43
- Videopython supports Python `>=3.11, <3.15`. The `ai` and `mcp` extras are independent;
44
- install `videopython[ai,mcp]` if you need both. See the
45
- [installation guide](https://videopython.com/install/) for FFmpeg features, model
46
- downloads, Ollama setup, and hardware requirements.
33
+ Install FFmpeg, then run `uv add videopython` (or `pip install videopython`).
34
+ The optional `ai` and `mcp` extras add model runtimes and the MCP server.
35
+ See the [installation guide](https://videopython.com/install/) for supported
36
+ Python versions, extras, FFmpeg features, and model setup.
47
37
 
48
38
  ## Quick start
49
39
 
@@ -71,8 +61,8 @@ edit.validate()
71
61
  edit.run_to_file("output.mp4")
72
62
  ```
73
63
 
74
- `run_to_file()` streams the source through FFmpeg and the operation pipeline, so memory
75
- use stays bounded for long videos. Continue with
64
+ `run_to_file()` streams the source through FFmpeg and the operation pipeline, so frame buffers
65
+ stay bounded for long videos. Continue with
76
66
  [Your first edit](https://videopython.com/tutorials/first-edit/).
77
67
 
78
68
  ## What you can build
@@ -87,22 +77,17 @@ use stays bounded for long videos. Continue with
87
77
  Core editing does not install PyTorch or other model runtimes. AI dependencies load only
88
78
  when you use an AI feature.
89
79
 
90
- ## Documentation
91
-
92
- The documentation follows [Diataxis](https://diataxis.fr/):
80
+ ## Scope
93
81
 
94
- - [Tutorials](https://videopython.com/tutorials/) teach the library through complete
95
- examples.
96
- - [How-to guides](https://videopython.com/how-to/) cover specific editing and AI tasks.
97
- - [Reference](https://videopython.com/reference/) documents the API, operations, and
98
- JSON wire format.
99
- - [Explanation](https://videopython.com/explanation/) covers the streaming engine,
100
- plan lifecycle, architecture, and LLM-first design.
82
+ Videopython is a library for programmatic editing. It does not provide a hosted
83
+ inference service, an interactive editing application, universal support for model
84
+ runtimes and FFmpeg builds, or a second in-memory operation engine.
101
85
 
102
86
  ## Project status
103
87
 
104
88
  Videopython is pre-1.0, so public interfaces can still change. See the
105
- [roadmap](ROADMAP.md) for the stability criteria and [release notes](RELEASE_NOTES.md)
89
+ [compatibility policy](docs/reference/compatibility.md) for public contracts and
90
+ versioning rules, and [release notes](RELEASE_NOTES.md)
106
91
  for changes between versions. Report vulnerabilities through the [security
107
92
  policy](SECURITY.md).
108
93
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "videopython"
3
- version = "0.61.1"
3
+ version = "0.62.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" },
@@ -93,9 +93,9 @@ ai = [
93
93
  # Audio source separation (understanding/separation.py)
94
94
  "demucs>=4.0.0",
95
95
  # Voice cloning TTS (generation/audio.py). Our fork of chatterbox-tts with
96
- # corrected metadata; import name is still `chatterbox`. Not upstream — its
97
- # `==` pins make [ai] unsatisfiable. See DEVELOPMENT.md "Dependencies".
98
- "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",
99
99
  # Local media generation (generation/*). >=0.35 ships QwenImagePipeline + Wan2.2.
100
100
  "diffusers>=0.35.0",
101
101
  # Required, despite looking like diffusers' problem: the Wan2.2 i2v pipeline
@@ -14,7 +14,7 @@ import subprocess
14
14
  import tempfile
15
15
  from contextlib import contextmanager
16
16
  from pathlib import Path
17
- from typing import Any, BinaryIO, Iterator, Sequence, cast
17
+ from typing import Any, BinaryIO, Callable, Iterator, Sequence, cast
18
18
 
19
19
  from videopython._exceptions import FFmpegProbeError, FFmpegRunError
20
20
 
@@ -50,6 +50,29 @@ def run(cmd: Sequence[str], *, stdin: bytes | None = None) -> bytes:
50
50
  return result.stdout
51
51
 
52
52
 
53
+ def run_with_progress(cmd: Sequence[str], on_frame: Callable[[int], None]) -> None:
54
+ """Run an FFmpeg file output and drain frame progress until the process exits."""
55
+ argv = [cmd[0], "-progress", "pipe:1", "-stats_period", "0.25", "-nostats", *cmd[1:]]
56
+ with tempfile.TemporaryFile() as errors:
57
+ try:
58
+ proc = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=errors)
59
+ except FileNotFoundError as e:
60
+ raise FFmpegRunError(f"binary not found on PATH: {cmd[0]}") from e
61
+ try:
62
+ for line in cast(BinaryIO, proc.stdout):
63
+ key, _, value = line.partition(b"=")
64
+ if key == b"frame":
65
+ on_frame(int(value))
66
+ if proc.wait() != 0:
67
+ errors.seek(0)
68
+ raise FFmpegRunError(
69
+ f"ffmpeg failed (exit {proc.returncode}): {errors.read().decode(errors='replace')}"
70
+ )
71
+ finally:
72
+ _terminate(proc)
73
+ cast(BinaryIO, proc.stdout).close()
74
+
75
+
53
76
  def probe(path: str | Path, *, extra_args: Sequence[str] | None = None) -> dict[str, Any]:
54
77
  """Run ffprobe and return the parsed JSON payload.
55
78
 
@@ -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)
@@ -139,5 +154,27 @@ class OllamaStructuredClient:
139
154
  raise OllamaError(f"Ollama returned a non-object JSON value: {type(data).__name__}")
140
155
  return data
141
156
 
157
+ def model_provenance(self) -> dict[str, str | None] | None:
158
+ """Resolve the used model tag to a server digest, without inference."""
159
+ if self._client is None:
160
+ return None
161
+ try:
162
+ models = self._client.list().models
163
+ except Exception:
164
+ return None
165
+ for model in models:
166
+ if model.model in (self.model, f"{self.model}:latest"):
167
+ return {model.model: model.digest}
168
+ return None
169
+
142
170
  def unload(self) -> None:
143
- self._client = None
171
+ try:
172
+ if self._client is not None and self.keep_alive is not None:
173
+ # Release explicit residency before the low-memory pipeline
174
+ # loads its next GPU model. Merely dropping the HTTP client
175
+ # leaves the Ollama runner resident on the server.
176
+ self._client.generate(model=self.model, keep_alive=0)
177
+ except Exception as exc:
178
+ logger.warning("Could not unload Ollama model %s; server memory may remain allocated: %s", self.model, exc)
179
+ finally:
180
+ self._client = None
@@ -51,6 +51,10 @@ class ManagedPredictor:
51
51
  # Attribute holding the resolved device passed to release_device_memory.
52
52
  _device_attr: str = "device"
53
53
 
54
+ def model_provenance(self) -> dict[str, str | None] | None:
55
+ """Return recorded model IDs and revisions, or None when unknown."""
56
+ return None
57
+
54
58
  def unload(self) -> None:
55
59
  """Drop the model reference(s) and release device memory. Idempotent."""
56
60
  for attr in self._model_attrs:
@@ -43,6 +43,8 @@ Usage:
43
43
 
44
44
  from __future__ import annotations
45
45
 
46
+ from importlib import metadata
47
+
46
48
  # Exact model-identifier string -> pinned commit SHA. The key must match the
47
49
  # literal value passed to from_pretrained/hf_hub_download at the call site so
48
50
  # ``pinned(model_id)`` resolves with a plain dict lookup. SHAs captured from
@@ -100,3 +102,11 @@ def pinned(model_id: str) -> str | None:
100
102
  The pinned SHA, or ``None`` when no pin is registered for ``model_id``.
101
103
  """
102
104
  return MODEL_REVISIONS.get(model_id)
105
+
106
+
107
+ def package_revision(distribution: str) -> str | None:
108
+ """Identify bundled weights by their installed package release, when available."""
109
+ try:
110
+ return f"package:{metadata.version(distribution)}"
111
+ except metadata.PackageNotFoundError:
112
+ return 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
@@ -14,7 +14,7 @@ from .backend import PlannerError, StructuredVisionLLM
14
14
  from .catalog import build_catalog
15
15
  from .editor import AutoEditError, AutoEditor
16
16
  from .local import OllamaVisionLLM
17
- from .models import CatalogBundle, CatalogScene, EditCatalog, EditPlan, PlanSegment
17
+ from .models import CatalogBundle, CatalogScene, EditCatalog, EditPlan, PlanSegment, SpeechCandidateConfig
18
18
  from .resolve import UnknownSceneIdsError, resolve_plan
19
19
 
20
20
  __all__ = [
@@ -28,6 +28,7 @@ __all__ = [
28
28
  "PlanSegment",
29
29
  "PlannerError",
30
30
  "StructuredVisionLLM",
31
+ "SpeechCandidateConfig",
31
32
  "UnknownSceneIdsError",
32
33
  "build_catalog",
33
34
  "resolve_plan",
@@ -0,0 +1,54 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+
5
+ from videopython.base.transcription import Transcription, TranscriptionWord
6
+
7
+ from .models import SpeechCandidateConfig
8
+
9
+
10
+ def speech_passages(
11
+ transcription: Transcription | None, config: SpeechCandidateConfig
12
+ ) -> list[list[TranscriptionWord]]:
13
+ if transcription is None or any(segment.text.strip() and not segment.words for segment in transcription.segments):
14
+ return []
15
+ words = sorted(transcription.words, key=lambda word: (word.start, word.end))
16
+ if not words:
17
+ return []
18
+ if any(not math.isfinite(w.start) or not math.isfinite(w.end) or w.start < 0 or w.end < w.start for w in words):
19
+ raise ValueError("Speech candidates require finite word times with 0 <= start <= end")
20
+
21
+ spans: list[list[TranscriptionWord]] = []
22
+ first = 0
23
+ end = words[0].end
24
+ for index, word in enumerate(words):
25
+ end = max(end, word.end)
26
+ following = words[index + 1] if index + 1 < len(words) else None
27
+ if following is not None and following.start < end:
28
+ continue
29
+ terminal = word.word.rstrip().rstrip("\"'”’»)]}").endswith((".", "?", "!", "…", "。", "?", "!"))
30
+ pause = following is not None and following.start - end >= config.pause_duration
31
+ if terminal or pause:
32
+ spans.append(words[first : index + 1])
33
+ first = index + 1
34
+ if following is not None:
35
+ end = following.end
36
+
37
+ passages: list[list[TranscriptionWord]] = []
38
+ pending: list[TranscriptionWord] = []
39
+ for span in spans:
40
+ start = span[0].start
41
+ end = max(word.end for word in span)
42
+ if end - start > config.max_duration:
43
+ pending = []
44
+ continue
45
+ if pending and (
46
+ start - max(word.end for word in pending) >= config.pause_duration
47
+ or end - pending[0].start > config.max_duration
48
+ ):
49
+ pending = []
50
+ pending.extend(span)
51
+ if end - pending[0].start >= config.min_duration:
52
+ passages.append(pending)
53
+ pending = []
54
+ return passages
@@ -0,0 +1,146 @@
1
+ """Build the LLM-facing edit catalog from VideoAnalysis results."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ from collections.abc import Sequence
8
+ from pathlib import Path
9
+ from typing import TYPE_CHECKING, Literal
10
+
11
+ import numpy as np
12
+
13
+ from videopython.base.video import extract_frames_at_times
14
+
15
+ from ._speech import speech_passages
16
+ from .models import CatalogBundle, CatalogScene, EditCatalog, SpeechCandidateConfig
17
+
18
+ if TYPE_CHECKING:
19
+ from videopython.ai.video_analysis import SceneAnalysisSample, VideoAnalysis
20
+ from videopython.base.transcription import Transcription
21
+
22
+ DEFAULT_TRANSCRIPT_CHARS = 280
23
+
24
+
25
+ def build_catalog(
26
+ analyses: Sequence[VideoAnalysis],
27
+ *,
28
+ keyframes: bool = True,
29
+ max_transcript_chars: int = DEFAULT_TRANSCRIPT_CHARS,
30
+ mode: Literal["visual", "speech"] = "visual",
31
+ speech: SpeechCandidateConfig | None = None,
32
+ ) -> CatalogBundle:
33
+ """Build visual scenes or timed speech passages; speech mode requires speech settings."""
34
+ if mode not in ("visual", "speech") or (mode == "speech") != (speech is not None):
35
+ raise ValueError("Supply speech settings exactly when mode='speech'")
36
+ scenes: list[CatalogScene] = []
37
+ transcripts: dict[str, str] = {}
38
+ used_ids: set[str] = set()
39
+
40
+ for analysis in analyses:
41
+ source_path = analysis.source.path
42
+ samples = analysis.scenes.samples if analysis.scenes else []
43
+ transcription = analysis.audio.transcription if analysis.audio else None
44
+ stem = Path(source_path).stem if source_path else "clip"
45
+
46
+ if speech is not None:
47
+ if analysis.source.duration is None:
48
+ raise ValueError("Speech candidates require the source duration")
49
+ identity = json.dumps(
50
+ [
51
+ str(Path(source_path).resolve()) if source_path else None,
52
+ transcription.model_dump() if transcription else None,
53
+ speech.model_dump(),
54
+ ],
55
+ sort_keys=True,
56
+ )
57
+ digest = hashlib.sha256(identity.encode()).hexdigest()[:24]
58
+ for index, passage in enumerate(speech_passages(transcription, speech)):
59
+ start, end = passage[0].start, max(word.end for word in passage)
60
+ if end > analysis.source.duration or start >= analysis.source.duration:
61
+ continue
62
+ scene_id = _unique_id(f"{stem}#speech-{digest}", index, used_ids)
63
+ text = " ".join(" ".join(word.word.split()) for word in passage).strip()
64
+ scenes.append(
65
+ CatalogScene(
66
+ id=scene_id,
67
+ source=Path(source_path) if source_path else Path(stem),
68
+ start=start,
69
+ end=end,
70
+ duration=end - start,
71
+ transcript=_shorten(text, max_transcript_chars),
72
+ has_speech=True,
73
+ )
74
+ )
75
+ transcripts[scene_id] = text
76
+ if keyframes and source_path is None:
77
+ raise ValueError(f"Scene {scene_id!r} has no source path to extract a keyframe from.")
78
+ continue
79
+
80
+ for sample in samples:
81
+ scene_id = _unique_id(stem, sample.scene_index, used_ids)
82
+ caption, shot_type = _description(sample)
83
+ text = _transcript_text(transcription, sample.start_second, sample.end_second)
84
+ transcripts[scene_id] = text
85
+ transcript = _shorten(text, max_transcript_chars)
86
+ scenes.append(
87
+ CatalogScene(
88
+ id=scene_id,
89
+ source=Path(source_path) if source_path else Path(stem),
90
+ start=sample.start_second,
91
+ end=sample.end_second,
92
+ duration=max(0.0, sample.end_second - sample.start_second),
93
+ shot_type=shot_type,
94
+ caption=caption,
95
+ transcript=transcript,
96
+ has_speech=bool(transcript),
97
+ has_faces=bool(sample.faces),
98
+ )
99
+ )
100
+ if keyframes and source_path is None:
101
+ raise ValueError(f"Scene {scene_id!r} has no source path to extract a keyframe from.")
102
+
103
+ frames = extract_catalog_keyframes(scenes) if keyframes else {}
104
+ return CatalogBundle(catalog=EditCatalog(scenes=scenes), keyframes=frames, transcripts=transcripts)
105
+
106
+
107
+ def extract_catalog_keyframes(scenes: Sequence[CatalogScene]) -> dict[str, np.ndarray]:
108
+ """Extract scene midpoints in one decode per source, preserving scene IDs."""
109
+ by_source: dict[Path, list[CatalogScene]] = {}
110
+ for scene in scenes:
111
+ by_source.setdefault(scene.source, []).append(scene)
112
+ frames: dict[str, np.ndarray] = {}
113
+ for source, source_scenes in by_source.items():
114
+ timestamps = [(scene.start + scene.end) / 2.0 for scene in source_scenes]
115
+ extracted = extract_frames_at_times(source, timestamps)
116
+ for index, scene in enumerate(source_scenes):
117
+ frames[scene.id] = extracted[index]
118
+ return frames
119
+
120
+
121
+ def _unique_id(stem: str, scene_index: int, used: set[str]) -> str:
122
+ base = f"{stem}#{scene_index}"
123
+ candidate, suffix = base, 2
124
+ while candidate in used:
125
+ candidate = f"{base}-{suffix}"
126
+ suffix += 1
127
+ used.add(candidate)
128
+ return candidate
129
+
130
+
131
+ def _description(sample: SceneAnalysisSample) -> tuple[str, str | None]:
132
+ desc = sample.scene_description
133
+ return (desc.caption or "", desc.shot_type) if desc else ("", None)
134
+
135
+
136
+ def _transcript_text(transcription: Transcription | None, start: float, end: float) -> str:
137
+ sliced = transcription.slice(start, end) if transcription else None
138
+ if sliced is None:
139
+ return ""
140
+ return " ".join(" ".join(segment.text.split()) for segment in sliced.segments).strip()
141
+
142
+
143
+ def _shorten(text: str, max_chars: int) -> str:
144
+ if len(text) > max_chars:
145
+ text = text[: max_chars - 3].rstrip() + "..."
146
+ return text
@@ -7,13 +7,29 @@ from pathlib import Path
7
7
  from typing import Any
8
8
 
9
9
  import numpy as np
10
- from pydantic import BaseModel, ConfigDict, Field
10
+ from pydantic import BaseModel, ConfigDict, Field, model_validator
11
11
 
12
12
  from videopython.editing._schema import array_field_schema, field_schema, optional_model_field_schema
13
13
  from videopython.editing.operation import Operation, _to_strict_schema
14
14
  from videopython.editing.video_edit import OperationInput, TransitionSpec
15
15
 
16
16
 
17
+ class SpeechCandidateConfig(BaseModel):
18
+ """Duration limits and minimum pause for deterministic speech candidates."""
19
+
20
+ model_config = ConfigDict(extra="forbid", frozen=True, allow_inf_nan=False)
21
+
22
+ min_duration: float = Field(gt=0)
23
+ max_duration: float = Field(gt=0)
24
+ pause_duration: float = Field(0.8, gt=0)
25
+
26
+ @model_validator(mode="after")
27
+ def _ordered_limits(self) -> SpeechCandidateConfig:
28
+ if self.max_duration < self.min_duration:
29
+ raise ValueError("max_duration must be at least min_duration")
30
+ return self
31
+
32
+
17
33
  class CatalogScene(BaseModel):
18
34
  """A candidate scene the planner picks by id; carries the exact source bounds."""
19
35
 
@@ -44,6 +60,7 @@ class CatalogBundle:
44
60
 
45
61
  catalog: EditCatalog
46
62
  keyframes: dict[str, np.ndarray] = field(default_factory=dict)
63
+ transcripts: dict[str, str] = field(default_factory=dict)
47
64
 
48
65
 
49
66
  class PlanSegment(BaseModel):