datacut 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. datacut/__init__.py +121 -0
  2. datacut/__main__.py +122 -0
  3. datacut/animation/__init__.py +0 -0
  4. datacut/animation/animation.py +336 -0
  5. datacut/animation/composition.py +258 -0
  6. datacut/animation/creation.py +315 -0
  7. datacut/animation/fading.py +328 -0
  8. datacut/animation/growing.py +90 -0
  9. datacut/animation/indication.py +608 -0
  10. datacut/animation/movement.py +165 -0
  11. datacut/animation/numbers.py +92 -0
  12. datacut/animation/physics.py +453 -0
  13. datacut/animation/rotation.py +95 -0
  14. datacut/animation/specialized.py +956 -0
  15. datacut/animation/transform.py +505 -0
  16. datacut/animation/transform_matching_parts.py +343 -0
  17. datacut/animation/update.py +95 -0
  18. datacut/camera/__init__.py +0 -0
  19. datacut/camera/camera.py +795 -0
  20. datacut/camera/camera_frame.py +320 -0
  21. datacut/camera/cinematography.py +1166 -0
  22. datacut/config.py +479 -0
  23. datacut/constants.py +160 -0
  24. datacut/css/__init__.py +189 -0
  25. datacut/css/easing.py +328 -0
  26. datacut/css/engine.py +1727 -0
  27. datacut/css/gradients.py +678 -0
  28. datacut/css/motion.py +1615 -0
  29. datacut/css/parser.py +741 -0
  30. datacut/css/presets.py +143 -0
  31. datacut/css/shader_fill.py +703 -0
  32. datacut/css/values.py +650 -0
  33. datacut/default_config.yml +224 -0
  34. datacut/event_handler/__init__.py +6 -0
  35. datacut/event_handler/event_dispatcher.py +161 -0
  36. datacut/event_handler/event_listner.py +31 -0
  37. datacut/event_handler/event_type.py +11 -0
  38. datacut/event_handler/picking.py +111 -0
  39. datacut/event_keys.py +53 -0
  40. datacut/extract_scene.py +200 -0
  41. datacut/layout/__init__.py +39 -0
  42. datacut/layout/components.py +425 -0
  43. datacut/layout/containers.py +1520 -0
  44. datacut/logger.py +13 -0
  45. datacut/mobject/__init__.py +0 -0
  46. datacut/mobject/boolean_ops.py +168 -0
  47. datacut/mobject/changing.py +209 -0
  48. datacut/mobject/coordinate_systems.py +1056 -0
  49. datacut/mobject/fractals.py +348 -0
  50. datacut/mobject/frame.py +80 -0
  51. datacut/mobject/functions.py +147 -0
  52. datacut/mobject/geometry.py +1834 -0
  53. datacut/mobject/gltf.py +243 -0
  54. datacut/mobject/interactive.py +906 -0
  55. datacut/mobject/lights.py +366 -0
  56. datacut/mobject/materials.py +207 -0
  57. datacut/mobject/matrix.py +570 -0
  58. datacut/mobject/mesh3d.py +2288 -0
  59. datacut/mobject/mobject.py +2885 -0
  60. datacut/mobject/mobject_update_utils.py +123 -0
  61. datacut/mobject/model.py +543 -0
  62. datacut/mobject/number_line.py +517 -0
  63. datacut/mobject/numbers.py +441 -0
  64. datacut/mobject/probability.py +536 -0
  65. datacut/mobject/shape_matchers.py +161 -0
  66. datacut/mobject/subtitles.py +260 -0
  67. datacut/mobject/svg/__init__.py +0 -0
  68. datacut/mobject/svg/brace.py +356 -0
  69. datacut/mobject/svg/drawings.py +1041 -0
  70. datacut/mobject/svg/old_tex_mobject.py +335 -0
  71. datacut/mobject/svg/path_cache.py +155 -0
  72. datacut/mobject/svg/special_tex.py +216 -0
  73. datacut/mobject/svg/string_mobject.py +622 -0
  74. datacut/mobject/svg/svg_mobject.py +657 -0
  75. datacut/mobject/svg/svg_parse.py +437 -0
  76. datacut/mobject/svg/tex_mobject.py +499 -0
  77. datacut/mobject/svg/text_mobject.py +702 -0
  78. datacut/mobject/svg/typst_mobject.py +864 -0
  79. datacut/mobject/three_dimensions.py +686 -0
  80. datacut/mobject/types/__init__.py +0 -0
  81. datacut/mobject/types/dot_cloud.py +220 -0
  82. datacut/mobject/types/image_mobject.py +130 -0
  83. datacut/mobject/types/point_cloud_mobject.py +138 -0
  84. datacut/mobject/types/shader_mobject.py +268 -0
  85. datacut/mobject/types/surface.py +848 -0
  86. datacut/mobject/types/vectorized_mobject.py +1749 -0
  87. datacut/mobject/types/video_mobject.py +3902 -0
  88. datacut/mobject/value_tracker.py +110 -0
  89. datacut/mobject/vector_field.py +585 -0
  90. datacut/module_loader.py +176 -0
  91. datacut/reactive/__init__.py +25 -0
  92. datacut/reactive/signals.py +610 -0
  93. datacut/renderer/__init__.py +4 -0
  94. datacut/renderer/drawing.py +1066 -0
  95. datacut/renderer/gpu.py +800 -0
  96. datacut/renderer/material.py +88 -0
  97. datacut/renderer/pipeline.py +179 -0
  98. datacut/renderer/post_process.py +577 -0
  99. datacut/renderer/renderer.py +1285 -0
  100. datacut/renderer/shader_source.py +146 -0
  101. datacut/renderer/shared_buffer.py +185 -0
  102. datacut/renderer/texture.py +217 -0
  103. datacut/renderer/uniform_block.py +118 -0
  104. datacut/scene/__init__.py +0 -0
  105. datacut/scene/incremental.py +233 -0
  106. datacut/scene/interactive_scene.py +758 -0
  107. datacut/scene/performance.py +226 -0
  108. datacut/scene/presentation_scene.py +783 -0
  109. datacut/scene/recording.py +541 -0
  110. datacut/scene/safe_zones.py +323 -0
  111. datacut/scene/scene.py +2849 -0
  112. datacut/scene/scene_embed.py +277 -0
  113. datacut/scene/scene_file_writer.py +1014 -0
  114. datacut/scene/scene_task.py +183 -0
  115. datacut/scene/sfx.py +164 -0
  116. datacut/scene/sound.py +702 -0
  117. datacut/scene/sound_clip.py +580 -0
  118. datacut/scene/timeline.py +1689 -0
  119. datacut/scene/transcript.py +503 -0
  120. datacut/shaders/fill.wgsl +107 -0
  121. datacut/shaders/fill_depth.wgsl +198 -0
  122. datacut/shaders/image.wgsl +25 -0
  123. datacut/shaders/inserts/NOTE.md +16 -0
  124. datacut/shaders/inserts/clip_test.wgsl +14 -0
  125. datacut/shaders/inserts/complex_functions.wgsl +20 -0
  126. datacut/shaders/inserts/fill_color.wgsl +10 -0
  127. datacut/shaders/inserts/finalize_color.wgsl +44 -0
  128. datacut/shaders/inserts/frame_uniforms.wgsl +37 -0
  129. datacut/shaders/inserts/frame_units.wgsl +18 -0
  130. datacut/shaders/inserts/image_quad.wgsl +28 -0
  131. datacut/shaders/inserts/mobject_uniforms.wgsl +11 -0
  132. datacut/shaders/inserts/project_point.wgsl +44 -0
  133. datacut/shaders/inserts/quad_corners.wgsl +12 -0
  134. datacut/shaders/inserts/read_data.wgsl +33 -0
  135. datacut/shaders/inserts/surface_mesh.wgsl +106 -0
  136. datacut/shaders/mandelbrot_fractal.wgsl +100 -0
  137. datacut/shaders/mesh.wgsl +474 -0
  138. datacut/shaders/newton_fractal.wgsl +200 -0
  139. datacut/shaders/present.wgsl +62 -0
  140. datacut/shaders/stroke.wgsl +1141 -0
  141. datacut/shaders/stroke_depth.wgsl +1136 -0
  142. datacut/shaders/surface.wgsl +40 -0
  143. datacut/shaders/textured_surface.wgsl +59 -0
  144. datacut/shaders/true_dot.wgsl +78 -0
  145. datacut/shaders/video.wgsl +42 -0
  146. datacut/tex_templates.yml +736 -0
  147. datacut/transcribe.py +32 -0
  148. datacut/typing.py +412 -0
  149. datacut/utils/__init__.py +0 -0
  150. datacut/utils/bezier.py +467 -0
  151. datacut/utils/browser_audio.py +423 -0
  152. datacut/utils/browser_code_transform.py +1293 -0
  153. datacut/utils/browser_completions.py +2255 -0
  154. datacut/utils/browser_fonts.py +143 -0
  155. datacut/utils/browser_pathops.py +47 -0
  156. datacut/utils/browser_scheduler.py +18 -0
  157. datacut/utils/browser_typst.py +82 -0
  158. datacut/utils/cache.py +34 -0
  159. datacut/utils/cinematic_vfx.py +779 -0
  160. datacut/utils/color.py +203 -0
  161. datacut/utils/debug.py +46 -0
  162. datacut/utils/dict_ops.py +22 -0
  163. datacut/utils/directories.py +55 -0
  164. datacut/utils/editor_signatures.py +1806 -0
  165. datacut/utils/editor_thumbnails.py +769 -0
  166. datacut/utils/family_ops.py +48 -0
  167. datacut/utils/file_ops.py +65 -0
  168. datacut/utils/images.py +52 -0
  169. datacut/utils/iterables.py +216 -0
  170. datacut/utils/native.py +280 -0
  171. datacut/utils/paths.py +83 -0
  172. datacut/utils/rate_functions.py +154 -0
  173. datacut/utils/render_geometry.py +186 -0
  174. datacut/utils/simple_functions.py +99 -0
  175. datacut/utils/sounds.py +43 -0
  176. datacut/utils/space_ops.py +460 -0
  177. datacut/utils/structured_array.py +256 -0
  178. datacut/utils/svg_export.py +102 -0
  179. datacut/utils/tex.py +139 -0
  180. datacut/utils/tex_file_writing.py +164 -0
  181. datacut/utils/tex_to_symbol_count.py +186 -0
  182. datacut/utils/typst_file_writing.py +205 -0
  183. datacut/utils/vfx_presets.py +4543 -0
  184. datacut/utils/visual_css.py +737 -0
  185. datacut/utils/visual_editor.py +4292 -0
  186. datacut/utils/window_audio.py +760 -0
  187. datacut/window.py +910 -0
  188. datacut-0.1.0.dist-info/METADATA +226 -0
  189. datacut-0.1.0.dist-info/RECORD +193 -0
  190. datacut-0.1.0.dist-info/WHEEL +5 -0
  191. datacut-0.1.0.dist-info/entry_points.txt +2 -0
  192. datacut-0.1.0.dist-info/licenses/LICENSE.md +21 -0
  193. datacut-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,580 @@
1
+ """
2
+ Sounds added to a scene, as Scene.add_sound hands them back: each can fade in and out, have its
3
+ volume changed over time, be stopped early, and duck under narration.
4
+
5
+ music = self.add_sound("music.mp3", gain=-6, fade_in=2, duck=True)
6
+ with AudioContextManager(self, "overview1.wav"): # or add_sound(..., voice=True)
7
+ ...
8
+ music.set_gain(-18, duration=1.5) # from now, over a second and a half
9
+ ...
10
+ music.stop(fade_out=3) # fading out from now, for three seconds
11
+
12
+ voice = self.add_sound("overview1.wav", voice=True)
13
+ voice.process_words("clave", lambda s: s.reverb(room=0.95, wet=0.6)) # as in a cathedral
14
+ voice.process(lambda s: s.highpass(120), start=3.0, end=5.5) # scene clock times
15
+
16
+ self.add_sound("loop.wav", loop=True, fade_out=2) # over and over until the scene ends,
17
+ # fading out over its last two seconds
18
+ self.add_sound("ding.wav", loop=3) # three times over
19
+
20
+ All of it is written into the movie's audio, see SceneFileWriter: what can be known when a
21
+ sound is added, its fades, is applied there and then; what depends on what the scene goes on to
22
+ do, changes of volume, stopping it and ducking, once the scene is over, on the same events
23
+ every other sound of the scene is mixed from. A sound none of this is asked of is mixed exactly
24
+ as it always was.
25
+
26
+ Volumes are in decibels, as gain always has been: 0 is the sound as it was given, -6 about half
27
+ as loud, and a change of volume moves evenly in decibels between where it was and where it goes.
28
+ Fades are even in amplitude, from silence.
29
+
30
+ Playing a scene in a window, or in the browser, plays its sounds as they are, none of this
31
+ applied; but for process and process_words, which the browser hears too, for a sound which is a
32
+ WAV file or a Sound, asked of it before it starts playing.
33
+ """
34
+ from __future__ import annotations
35
+
36
+ import numpy as np
37
+
38
+ from typing import TYPE_CHECKING
39
+
40
+ if TYPE_CHECKING:
41
+ from typing import Callable, Sequence
42
+ from datacut.scene.sound import Sound
43
+ from pydub import AudioSegment
44
+ from datacut.scene.scene_file_writer import SceneFileWriter
45
+
46
+
47
+ # How far a ducked sound drops under narration, in decibels, and how long it takes to get
48
+ # there before the voice comes in and to come back after it stops, in seconds
49
+ DEFAULT_DUCK_GAIN = -12.0
50
+ DEFAULT_DUCK_ATTACK = 0.15
51
+ DEFAULT_DUCK_RELEASE = 0.5
52
+
53
+ # Below this a sound is taken to be silent, so that a ramp down to "nothing" can be asked for
54
+ SILENT_DB = -120.0
55
+
56
+
57
+ class SoundClip(object):
58
+ """
59
+ One sound of a scene, from where it starts on the scene's clock.
60
+
61
+ Handed back by Scene.add_sound. One made while nothing is being written, as in a window or
62
+ while animations are being skipped, takes the same calls and does nothing with them.
63
+ """
64
+
65
+ def __init__(
66
+ self,
67
+ file_writer: SceneFileWriter | None = None,
68
+ segment: AudioSegment | None = None,
69
+ scene_start: float = 0.0,
70
+ event: tuple | None = None,
71
+ fade_in: float = 0.0,
72
+ fade_out: float = 0.0,
73
+ voice: bool = False,
74
+ duck: bool | float = False,
75
+ duck_attack: float = DEFAULT_DUCK_ATTACK,
76
+ duck_release: float = DEFAULT_DUCK_RELEASE,
77
+ loop: bool | int = False,
78
+ source=None,
79
+ transcription: dict | None = None,
80
+ transcript=None,
81
+ window_mixer=None,
82
+ ):
83
+ self.file_writer = file_writer
84
+ self.window_mixer = window_mixer
85
+ # What it was made from, a file's name or a Sound, for transcribing it, see transcript
86
+ self.source = source
87
+ # How to transcribe it unless told otherwise, see Scene.set_transcription
88
+ self.transcription: dict = dict(transcription or {})
89
+ self._transcripts: dict = {}
90
+ # One handed over, a Transcript or a JSON file's name, used instead of transcribing
91
+ self.given_transcript = transcript
92
+ # In the browser, what plays it, so that what process does is heard there too: the
93
+ # scene, and its entry in the scene's sound events, see Scene.add_sound
94
+ self.browser_scene = None
95
+ self.browser_event: tuple | None = None
96
+ self.browser_gain: float = 0.0
97
+ self.browser_gain_baked: bool = False
98
+ self.browser_gain_to_background: float | None = None
99
+ # As given, gain included, before anything here is done to it
100
+ self.raw = segment
101
+ self.scene_start = scene_start
102
+ # Its entry in the file writer's audio_events, replaced whenever it is mixed anew
103
+ self.event = event
104
+ self.fade_in = max(float(fade_in), 0.0)
105
+ self.fade_out = max(float(fade_out), 0.0)
106
+ self.voice = voice
107
+ if duck is True:
108
+ duck = DEFAULT_DUCK_GAIN
109
+ self.duck_gain: float | None = None if duck is False or duck is None else float(duck)
110
+ self.duck_attack = max(float(duck_attack), 0.0)
111
+ self.duck_release = max(float(duck_release), 0.0)
112
+ # Played over and over, True for until stopped or the scene ends, a number for that
113
+ # many times in all
114
+ if loop is True or loop is False:
115
+ self.loop = loop
116
+ else:
117
+ self.loop = max(int(loop), 1)
118
+ # For loop=True with no stop, how far into the clip the scene ends, set once it has,
119
+ # see SceneFileWriter.apply_sound_clip_changes
120
+ self.loop_until: float | None = None
121
+ # Changes of volume, as (seconds into the clip, decibels), in order. Before the first
122
+ # the clip plays as given
123
+ self.gain_keys: list[tuple[float, float]] = []
124
+ # Where it is cut off and over how long it fades out to there, seconds into the clip
125
+ self.stop_at: float | None = None
126
+ self.stop_fade = 0.0
127
+ # Stretches of it put through a function, see process: (from, to, function,
128
+ # crossfade), seconds into the clip, in the order asked
129
+ self.edits: list[tuple[float, float, Callable, float]] = []
130
+ self._edited: tuple[int, AudioSegment] | None = None
131
+ # Whether something asked of it since it was added has yet to be mixed in, see
132
+ # SceneFileWriter.apply_sound_clip_changes
133
+ self.pending = False
134
+
135
+ @property
136
+ def is_null(self) -> bool:
137
+ if self.browser_scene is not None:
138
+ return False
139
+ return (self.file_writer is None and self.window_mixer is None) or self.raw is None
140
+
141
+ @property
142
+ def loops_until_end(self) -> bool:
143
+ """Whether it goes on looping until the scene ends, there being nothing to stop it"""
144
+ return self.loop is True and self.stop_at is None
145
+
146
+ def source_length(self) -> float:
147
+ """
148
+ How long the sound is, once through. For a clip handed back while nothing is written,
149
+ read from what it was made from the first time it is asked, so that waiting for it to
150
+ end takes as long whether the scene is written, previewed or skipped through.
151
+ """
152
+ if self.raw is not None:
153
+ return self.raw.duration_seconds
154
+ if self.source is None:
155
+ return 0.0
156
+ if getattr(self, "_source_length", None) is None:
157
+ self._source_length = _length_of(self.source)
158
+ return self._source_length
159
+
160
+ def full_length(self) -> float:
161
+ """How long it plays for before any stop, looped as many times as it is"""
162
+ length = self.source_length()
163
+ if self.loop is True:
164
+ if self.stop_at is not None:
165
+ return max(self.stop_at, length)
166
+ if self.loop_until is not None:
167
+ return max(self.loop_until, 0.0)
168
+ return length
169
+ if self.loop:
170
+ return length * self.loop
171
+ return length
172
+
173
+ @property
174
+ def duration(self) -> float:
175
+ """How long it plays for, in seconds, cut short by stop"""
176
+ if self.raw is None and self.source is None:
177
+ return 0.0
178
+ length = self.full_length()
179
+ if self.stop_at is not None:
180
+ length = min(length, self.stop_at)
181
+ return length
182
+
183
+ def edited(self) -> AudioSegment:
184
+ """
185
+ The segment with every stretch asked for put through its function, see process: the
186
+ very segment it was given where none was.
187
+ """
188
+ if not self.edits or self.raw is None:
189
+ return self.raw
190
+ if self._edited is not None and self._edited[0] == len(self.edits):
191
+ return self._edited[1]
192
+ from datacut.scene.sound import Sound
193
+ sound = Sound.from_segment(self.raw)
194
+ for start, end, function, crossfade in self.edits:
195
+ sound = process_stretch(sound, start, end, function, crossfade)
196
+ width = 4 if self.raw.sample_width >= 3 else self.raw.sample_width
197
+ seg = sound.to_segment(width)
198
+ self._edited = (len(self.edits), seg)
199
+ return seg
200
+
201
+ def looped(self) -> AudioSegment:
202
+ """The segment played over as many times as it is looped, cut to how long that is"""
203
+ seg = self.edited()
204
+ if not self.loop:
205
+ return seg
206
+ target_ms = int(round(self.full_length() * 1000))
207
+ if target_ms <= len(seg):
208
+ return seg if self.loop is True and self.loop_until is None else seg[:target_ms]
209
+ times = -(-target_ms // max(len(seg), 1))
210
+ return (seg * times)[:target_ms]
211
+
212
+ @property
213
+ def scene_end(self) -> float:
214
+ return self.scene_start + self.duration
215
+
216
+ # What is said in it
217
+
218
+ def transcript(self, **options):
219
+ """
220
+ What is said in it, word by word, see datacut.scene.transcript. `options` go to
221
+ transcribe, over the scene's, see Scene.set_transcription. Cut short where it was
222
+ stopped. Known even while nothing is being written, as when animations are skipped,
223
+ so that waiting on its words takes the same time either way.
224
+ """
225
+ from datacut.scene.sound import Sound
226
+ from datacut.scene.transcript import transcribe
227
+ if self.given_transcript is not None:
228
+ from datacut.scene.transcript import Transcript
229
+ if not isinstance(self.given_transcript, Transcript):
230
+ self.given_transcript = Transcript.load(self.given_transcript)
231
+ result = self.given_transcript
232
+ if self.stop_at is not None and self.raw is not None:
233
+ result = result.until(self.duration)
234
+ return result
235
+ if self.source is None:
236
+ raise ValueError("A sound with nothing to transcribe")
237
+ opts = {**self.transcription, **options}
238
+ key = tuple(sorted(opts.items()))
239
+ if key not in self._transcripts:
240
+ source = self.source
241
+ if not isinstance(source, (str, Sound)) and not hasattr(source, "__fspath__"):
242
+ # A pydub AudioSegment
243
+ source = Sound.from_segment(source)
244
+ self._transcripts[key] = transcribe(source, **opts)
245
+ result = self._transcripts[key]
246
+ if self.stop_at is not None and self.raw is not None:
247
+ result = result.until(self.duration)
248
+ return result
249
+
250
+ def at(
251
+ self,
252
+ phrase: str,
253
+ occurrence: int = 1,
254
+ end: bool = False,
255
+ after: float | None = None,
256
+ **options,
257
+ ) -> float:
258
+ """
259
+ When on the scene's clock `phrase` begins to be said in it, or when it has been for
260
+ end=True: what to hand Scene.wait_until. Found regardless of case, accents and
261
+ punctuation; `occurrence` picks which time it is said, counting from 1, from `after`
262
+ on the scene's clock where given.
263
+ """
264
+ within = 0.0 if after is None else max(after - self.scene_start, 0.0)
265
+ return self.scene_start + self.transcript(**options).at(phrase, occurrence, end, after=within)
266
+
267
+ def now(self) -> float:
268
+ """How far into the clip the scene now is"""
269
+ if self.file_writer is not None:
270
+ scene = self.file_writer.scene
271
+ elif self.window_mixer is not None:
272
+ scene = self.window_mixer.scene
273
+ else:
274
+ scene = self.browser_scene
275
+ return float(scene.get_time()) - self.scene_start
276
+
277
+ def _notify_mixer(self) -> None:
278
+ if self.window_mixer is not None:
279
+ self.window_mixer.mark_dirty(self)
280
+
281
+ # Asked for while the scene runs
282
+
283
+ def set_gain(self, gain: float, duration: float = 0.0) -> SoundClip:
284
+ """
285
+ Takes the volume from wherever it is now to `gain` decibels, over `duration` seconds,
286
+ or at once. Whatever was asked for after now is dropped, this being what happens next.
287
+ """
288
+ if self.is_null:
289
+ return self
290
+ start = max(self.now(), 0.0)
291
+ current = gain_at(self.gain_keys, start)
292
+ keys = [key for key in self.gain_keys if key[0] <= start]
293
+ keys.append((start, current))
294
+ keys.append((start + max(float(duration), 0.0), float(gain)))
295
+ self.gain_keys = keys
296
+ self.pending = True
297
+ self._notify_mixer()
298
+ return self
299
+
300
+ def fade_to(self, gain: float, duration: float = 1.0) -> SoundClip:
301
+ """set_gain, over a second unless said otherwise"""
302
+ return self.set_gain(gain, duration)
303
+
304
+ def process(
305
+ self,
306
+ function: Callable[[Sound], Sound],
307
+ start: float | None = None,
308
+ end: float | None = None,
309
+ crossfade: float = 0.01,
310
+ ) -> SoundClip:
311
+ """
312
+ Puts the stretch of it from `start` to `end` on the scene's clock, as `at` hands back,
313
+ through `function`, from Sound to Sound, see datacut.scene.sound; the whole of it where
314
+ neither is given:
315
+
316
+ voice.process(lambda s: s.reverb(room=0.9, wet=0.5), voice.at("es la"), voice.at("clave", end=True))
317
+
318
+ What `function` hands back takes the stretch's place, crossfaded in and out over
319
+ `crossfade` seconds just outside it so that nothing clicks, and may be longer, a
320
+ reverb's tail say, which is then heard over what follows. Asked again, each is put
321
+ through in turn. The movie written hears it, and the browser, for a WAV file or a Sound
322
+ asked of before it starts playing; a window plays it as it was.
323
+ """
324
+ if self.is_null and self.browser_scene is None:
325
+ return self
326
+ a = 0.0 if start is None else max(float(start) - self.scene_start, 0.0)
327
+ b = self.source_length() if end is None else float(end) - self.scene_start
328
+ if b <= a:
329
+ return self
330
+ self.edits.append((a, b, function, max(float(crossfade), 0.0)))
331
+ self.pending = True
332
+ self._notify_mixer()
333
+ if self.browser_scene is not None:
334
+ self._play_edited_in_browser()
335
+ return self
336
+
337
+ def _play_edited_in_browser(self) -> None:
338
+ """Has the browser play the sound with every edit, in place of what it was to play"""
339
+ from datacut.logger import log
340
+ from datacut.scene.sound import Sound
341
+ scene = self.browser_scene
342
+ if float(scene.get_time()) > self.scene_start + 1e-6:
343
+ log.warning(
344
+ "The browser has begun playing this sound, and plays it as it was: process it "
345
+ "right after adding it"
346
+ )
347
+ return
348
+ source = self.source
349
+ if isinstance(source, Sound):
350
+ sound = source.gain(self.browser_gain)
351
+ else:
352
+ sound = Sound.from_file(source)
353
+ for start, end, function, crossfade in self.edits:
354
+ sound = process_stretch(sound, start, end, function, crossfade)
355
+ key = f"datacut-sound-{id(self)}-edit-{len(self.edits)}"
356
+ from datacut.utils.browser_audio import browser_audio
357
+ browser_audio.register_wav(key, sound.to_wav_bytes())
358
+ events = scene._interactive_sound_events
359
+ for i, event in enumerate(events):
360
+ if event is self.browser_event:
361
+ self.browser_event = (event[0], key, event[2])
362
+ events[i] = self.browser_event
363
+ break
364
+
365
+ def process_words(
366
+ self,
367
+ phrase: str,
368
+ function: Callable[[Sound], Sound],
369
+ occurrence: int = 1,
370
+ pad: float = 0.03,
371
+ crossfade: float = 0.01,
372
+ **options,
373
+ ) -> SoundClip:
374
+ """
375
+ Puts what is said where `phrase` is through `function`, see process, from `pad` seconds
376
+ before it begins to `pad` after it ends; `occurrence` picks which time it is said:
377
+
378
+ voice.process_words("clave", lambda s: s.reverb(room=0.95, wet=0.6))
379
+
380
+ Found as `at` finds it, transcribing the clip with `options` if it is not yet.
381
+ """
382
+ if self.is_null and self.browser_scene is None:
383
+ return self
384
+ start = self.at(phrase, occurrence, **options) - pad
385
+ end = self.at(phrase, occurrence, end=True, **options) + pad
386
+ return self.process(function, start, end, crossfade)
387
+
388
+ def stop(self, fade_out: float = 0.0) -> SoundClip:
389
+ """Fades it out from now over `fade_out` seconds, or cuts it off now"""
390
+ if self.is_null:
391
+ return self
392
+ fade_out = max(float(fade_out), 0.0)
393
+ self.stop_at = max(self.now(), 0.0) + fade_out
394
+ self.stop_fade = fade_out
395
+ self.pending = True
396
+ self._notify_mixer()
397
+ return self
398
+
399
+ # Mixing
400
+
401
+ def processed(self, duck_keys: Sequence[tuple[float, float]] = ()) -> AudioSegment:
402
+ """
403
+ The clip as it is to be heard: cut short where stopped, its volume changes and any
404
+ ducking applied, and faded in and out. The very segment it was given where none of
405
+ that changes anything.
406
+ """
407
+ if self.raw is None:
408
+ return self.raw
409
+ seg = self.looped()
410
+ length = self.full_length()
411
+ if self.stop_at is not None and self.stop_at < length:
412
+ seg = seg[:int(round(self.stop_at * 1000))]
413
+ fade_out = self.fade_out
414
+ if self.stop_at is not None and self.stop_at <= length:
415
+ fade_out = self.stop_fade
416
+ elif self.loops_until_end and self.loop_until is None:
417
+ # Where it ends is not known until the scene has, and its fade out goes there
418
+ fade_out = 0.0
419
+ keys = combine_gain_keys(self.gain_keys, duck_keys)
420
+ if not keys and self.fade_in <= 0 and fade_out <= 0:
421
+ return seg
422
+ return apply_envelope(seg, keys, self.fade_in, fade_out)
423
+
424
+
425
+ def process_stretch(
426
+ sound: Sound,
427
+ start: float,
428
+ end: float,
429
+ function: Callable[[Sound], Sound],
430
+ crossfade: float = 0.01,
431
+ ) -> Sound:
432
+ """
433
+ `sound` with what it has from `start` to `end` seconds in put through `function`, see
434
+ SoundClip.process: the stretch, faded in and out over `crossfade` seconds outside it, is
435
+ taken out of the sound and what `function` makes of it put back in its place, overlaid from
436
+ where it was taken, so that the two fades add up to the sound as it was wherever `function`
437
+ leaves it alone.
438
+ """
439
+ from datacut.scene.sound import Sound
440
+ rate = sound.sample_rate
441
+ n = len(sound)
442
+ t = np.arange(n) / rate
443
+ if crossfade > 0:
444
+ mask = np.clip((t - (start - crossfade)) / crossfade, 0.0, 1.0)
445
+ mask *= np.clip(((end + crossfade) - t) / crossfade, 0.0, 1.0)
446
+ else:
447
+ mask = ((t >= start) & (t < end)).astype(float)
448
+ lo = max(int(np.floor((start - crossfade) * rate)), 0)
449
+ hi = min(int(np.ceil((end + crossfade) * rate)), n)
450
+ if hi <= lo:
451
+ return sound
452
+ samples = sound.samples.astype(np.float64)
453
+ piece = Sound(samples[lo:hi] * mask[lo:hi, None], rate)
454
+ rest = Sound(samples * (1.0 - mask[:, None]), rate)
455
+ return rest.overlay(function(piece), at=lo / rate)
456
+
457
+
458
+ def _length_of(source) -> float:
459
+ """How long a sound file, Sound or AudioSegment is, decoded as the movie's audio is"""
460
+ from datacut.scene.sound import Sound
461
+ if isinstance(source, Sound):
462
+ return source.duration
463
+ if hasattr(source, "duration_seconds"):
464
+ return source.duration_seconds
465
+ from datacut.utils.sounds import get_full_sound_file_path
466
+ path = get_full_sound_file_path(source)
467
+ try:
468
+ from pydub import AudioSegment
469
+ except ImportError:
470
+ return Sound.from_file(path).duration
471
+ return AudioSegment.from_file(path).duration_seconds
472
+
473
+
474
+ def gain_at(keys: Sequence[tuple[float, float]], t: float) -> float:
475
+ """The volume, in decibels, `keys` put at `t`: even between keys, held past the last"""
476
+ if not keys or t < keys[0][0]:
477
+ return 0.0
478
+ for (t0, g0), (t1, g1) in zip(keys, keys[1:]):
479
+ if t0 <= t < t1:
480
+ return g0 + (g1 - g0) * (t - t0) / (t1 - t0)
481
+ # Past the last key, or on a step, two keys at one time, where the later one holds
482
+ value = 0.0
483
+ for tk, gk in keys:
484
+ if tk <= t:
485
+ value = gk
486
+ return value
487
+
488
+
489
+ def combine_gain_keys(
490
+ a: Sequence[tuple[float, float]],
491
+ b: Sequence[tuple[float, float]],
492
+ ) -> list[tuple[float, float]]:
493
+ """Two sets of volume changes heard together: their decibels added, at every key of either"""
494
+ if not a:
495
+ return list(b)
496
+ if not b:
497
+ return list(a)
498
+ times = sorted({t for t, _ in a} | {t for t, _ in b})
499
+ return [(t, gain_at(a, t) + gain_at(b, t)) for t in times]
500
+
501
+
502
+ def duck_keys_for(
503
+ clip: SoundClip,
504
+ voices: Sequence[SoundClip],
505
+ ) -> list[tuple[float, float]]:
506
+ """
507
+ The volume changes ducking puts on `clip`, in seconds into it: down by its duck gain over
508
+ its attack before each stretch of narration, back up over its release after. Stretches
509
+ closer together than that are run together rather than let the sound bob up between them.
510
+ """
511
+ if clip.duck_gain is None:
512
+ return []
513
+ spans = sorted(
514
+ (v.scene_start, v.scene_end) for v in voices
515
+ if v is not clip and not v.is_null and v.duration > 0
516
+ )
517
+ merged: list[list[float]] = []
518
+ gap = clip.duck_attack + clip.duck_release
519
+ for a, b in spans:
520
+ if merged and a - merged[-1][1] <= gap:
521
+ merged[-1][1] = max(merged[-1][1], b)
522
+ else:
523
+ merged.append([a, b])
524
+ keys: list[tuple[float, float]] = []
525
+ for a, b in merged:
526
+ a -= clip.scene_start
527
+ b -= clip.scene_start
528
+ keys += [
529
+ (a - clip.duck_attack, 0.0),
530
+ (a, clip.duck_gain),
531
+ (b, clip.duck_gain),
532
+ (b + clip.duck_release, 0.0),
533
+ ]
534
+ return keys
535
+
536
+
537
+ def apply_envelope(
538
+ seg: AudioSegment,
539
+ keys: Sequence[tuple[float, float]],
540
+ fade_in: float,
541
+ fade_out: float,
542
+ ) -> AudioSegment:
543
+ """
544
+ `seg` with its volume taken through `keys` (seconds, decibels), then faded in from silence
545
+ over `fade_in` seconds and out to silence over its last `fade_out`, each sample scaled and
546
+ kept within what its sample width can hold.
547
+ """
548
+ if seg.sample_width == 3:
549
+ # numpy has no 24-bit integers
550
+ seg = seg.set_sample_width(4)
551
+ dtype = {1: np.int8, 2: np.int16, 4: np.int32}[seg.sample_width]
552
+ samples = np.frombuffer(seg.raw_data, dtype=dtype).reshape(-1, seg.channels)
553
+ n = len(samples)
554
+ if n == 0:
555
+ return seg
556
+ t = np.arange(n) / seg.frame_rate
557
+
558
+ scale = np.ones(n)
559
+ if keys:
560
+ times = np.array([k[0] for k in keys], dtype=float)
561
+ gains = np.array([k[1] for k in keys], dtype=float)
562
+ # np.interp wants times strictly increasing: a step, two keys at one time, has the
563
+ # later one moved a hair later, so that it holds from there on as gain_at has it
564
+ for i in range(1, len(times)):
565
+ if times[i] <= times[i - 1]:
566
+ times[i] = np.nextafter(times[i - 1], np.inf)
567
+ # Held past the ends; before the first key the clip plays as given
568
+ db = np.interp(t, times, gains)
569
+ db[t < times[0]] = 0.0
570
+ db = np.maximum(db, SILENT_DB)
571
+ scale *= 10.0 ** (db / 20.0)
572
+ if fade_in > 0:
573
+ scale *= np.clip(t / fade_in, 0.0, 1.0)
574
+ if fade_out > 0:
575
+ length = n / seg.frame_rate
576
+ scale *= np.clip((length - t) / fade_out, 0.0, 1.0)
577
+
578
+ info = np.iinfo(dtype)
579
+ out = np.clip(np.round(samples * scale[:, None]), info.min, info.max).astype(dtype)
580
+ return seg._spawn(out.tobytes())