dubweld 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.
dubweld/__init__.py ADDED
@@ -0,0 +1,45 @@
1
+ """
2
+ Lay a dubbed audio track from one release of a video onto another release, lip-synced.
3
+
4
+ plan = analyze(target, donor); render(plan, target, donor, output); verify(target, output)
5
+ """
6
+
7
+ from importlib.metadata import PackageNotFoundError, version
8
+
9
+ try:
10
+ __version__ = version("dubweld")
11
+ except PackageNotFoundError: # running from a source tree that is not installed
12
+ __version__ = "0.0.0"
13
+
14
+ from dubweld.analyze import AnalyzeOptions, ProgressCallback, analyze
15
+ from dubweld.errors import AnalysisError, DubweldError, PlanError, ProbeError, RenderError, ToolError
16
+ from dubweld.ffmpeg import Tools
17
+ from dubweld.plan import Cut, Evidence, Gap, InputRef, Plan, Segment
18
+ from dubweld.render import RenderOptions, render
19
+ from dubweld.report import write_report
20
+ from dubweld.verify import VerifyReport, verify
21
+
22
+ __all__ = [
23
+ "AnalysisError",
24
+ "AnalyzeOptions",
25
+ "Cut",
26
+ "DubweldError",
27
+ "Evidence",
28
+ "Gap",
29
+ "InputRef",
30
+ "Plan",
31
+ "PlanError",
32
+ "ProbeError",
33
+ "ProgressCallback",
34
+ "RenderError",
35
+ "RenderOptions",
36
+ "Segment",
37
+ "ToolError",
38
+ "Tools",
39
+ "VerifyReport",
40
+ "__version__",
41
+ "analyze",
42
+ "render",
43
+ "verify",
44
+ "write_report",
45
+ ]
dubweld/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from dubweld.cli import main
4
+
5
+ sys.exit(main())
dubweld/analyze.py ADDED
@@ -0,0 +1,403 @@
1
+ """Analysis: from two files to a sync plan (ratio, segments, cuts)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from collections.abc import Callable
7
+ from dataclasses import asdict, dataclass
8
+ from pathlib import Path
9
+
10
+ import numpy as np
11
+
12
+ from dubweld import cache
13
+ from dubweld.cuts import localize
14
+ from dubweld.errors import AnalysisError, ToolError
15
+ from dubweld.features import FRAME_RATE, SAMPLE_RATE, T0, Features, compute_features, stretch
16
+ from dubweld.ffmpeg import Tools, decode_pcm
17
+ from dubweld.levels import COMPETE_DISTANCE, CRISP, Level, find_levels, prune_levels, runs_of, viterbi
18
+ from dubweld.plan import Cut, InputRef, Plan, Segment, mmss
19
+ from dubweld.probe import MediaInfo, probe
20
+ from dubweld.ratio import choose_ratio
21
+ from dubweld.video import VideoReader, match_offset
22
+ from dubweld.xcorr import DECIMATION, Matcher, OffsetTrack, offset_track, scores_at_offset
23
+
24
+ log = logging.getLogger(__name__)
25
+
26
+ ProgressCallback = Callable[[str, float], None]
27
+ """Called with a step name (`speed ratio`, `offsets`) and the fraction of that step done, 0 to 1."""
28
+ CHANGEPOINT_REACH = 120.0
29
+ VIDEO_CLIP = 6.0
30
+ VIDEO_MIN_CORRELATION = 0.6
31
+ # The donor's unmatched head and tail get a second look with short windows: a closing jingle a few seconds long
32
+ # yields too few 8 s windows to form a level
33
+ EDGE_WINDOW = 4.0
34
+ EDGE_HOP = 1.0
35
+ EDGE_MIN = 6.0
36
+
37
+
38
+ @dataclass
39
+ class AnalyzeOptions:
40
+ """
41
+ Analysis settings.
42
+
43
+ :param target_track: audio stream of the target, counted among its audio streams
44
+ :param donor_track: audio stream of the donor holding the dub, counted the same way
45
+ :param ratio: donor-to-target speed ratio (target time = donor time × ratio + offset), or None to choose a
46
+ standard one automatically
47
+ :param use_video: use the videos to place cuts and settle ambiguous offsets; never changes an offset by itself
48
+ :param max_offset: only search offsets within ± this many seconds (faster on long files)
49
+ :param cache_dir: where decoded features are cached, keyed by file size and modification time; None disables
50
+ the cache
51
+ :param window: length of the matched donor windows, seconds; shorter finds shorter segments but matches less
52
+ reliably
53
+ :param hop: spacing of the windows, seconds
54
+ """
55
+
56
+ target_track: int = 0
57
+ donor_track: int = 0
58
+ ratio: float | None = None
59
+ use_video: bool = True
60
+ max_offset: float | None = None
61
+ cache_dir: Path | None = None
62
+ window: float = 8.0
63
+ hop: float = 2.0
64
+
65
+
66
+ def load_features(info: MediaInfo, audio_index: int, cache_dir: Path | None, tools: Tools) -> Features:
67
+ """Decode one audio stream to 16 kHz mono and compute its features (cached)."""
68
+
69
+ def compute() -> Features:
70
+ log.info("decoding %s (audio a:%d)", info.path.name, audio_index)
71
+ skip = info.audio_stream(audio_index).untrimmed_priming
72
+ return compute_features(decode_pcm(info.path, audio_index, SAMPLE_RATE, tools=tools, skip=skip))
73
+
74
+ return cache.features(info.path, audio_index, info.size, info.mtime, cache_dir, compute)
75
+
76
+
77
+ def _input_ref(info: MediaInfo, audio_index: int) -> InputRef:
78
+ stream = info.audio_stream(audio_index)
79
+ return InputRef(
80
+ path=str(info.path),
81
+ audio_index=audio_index,
82
+ duration=info.duration,
83
+ size=info.size,
84
+ mtime=info.mtime,
85
+ fps=str(info.video.fps) if info.video else "",
86
+ sample_rate=stream.sample_rate,
87
+ channels=stream.channels,
88
+ )
89
+
90
+
91
+ class _Video:
92
+ """Both videos, for matching frames at a given stretched donor time."""
93
+
94
+ def __init__(self, a: VideoReader, b: VideoReader) -> None:
95
+ self.a = a
96
+ self.b = b
97
+ self._memo: dict[tuple[float, float], float | None] = {}
98
+
99
+ def offset_at(self, b_time: float, audio_offset: float) -> float | None:
100
+ """Video offset near stretched donor time `b_time`, searched within audio_offset ± 1 s."""
101
+ key = (round(b_time, 1), round(audio_offset, 2))
102
+ if key not in self._memo:
103
+ self._memo[key] = self._offset_at(b_time, audio_offset)
104
+ return self._memo[key]
105
+
106
+ def _offset_at(self, b_time: float, audio_offset: float) -> float | None:
107
+ try:
108
+ donor = self.b.clip(b_time, b_time + VIDEO_CLIP)
109
+ target = self.a.clip(b_time + audio_offset - 1.5, b_time + audio_offset + VIDEO_CLIP + 1.5)
110
+ except ToolError as e:
111
+ log.debug("video match at %.1f failed: %s", b_time, e)
112
+ return None
113
+ found = match_offset(donor, target, audio_offset, 1.0, self.a.frame_duration)
114
+ if found is None or found[1] < VIDEO_MIN_CORRELATION:
115
+ return None
116
+ return found[0]
117
+
118
+ def offset_of(self, times: list[float], audio_offset: float) -> float | None:
119
+ values = [v for v in (self.offset_at(t - VIDEO_CLIP / 2, audio_offset) for t in times) if v is not None]
120
+ return float(np.median(values)) if values else None
121
+
122
+
123
+ def _level_times(track: OffsetTrack, offset: float, idx: np.ndarray | None = None, n: int = 3) -> list[float]:
124
+ """Centers of the best windows at `offset` (±10 ms), spread over time."""
125
+ sel = np.arange(len(track)) if idx is None else idx
126
+ near = sel[np.abs(track.offsets[sel] - offset) <= 0.010]
127
+ near = near[np.argsort(-track.scores[near])]
128
+ picked: list[float] = []
129
+ for i in near:
130
+ if all(abs(track.times[i] - p) > 30 for p in picked):
131
+ picked.append(float(track.times[i]))
132
+ if len(picked) == n:
133
+ break
134
+ return picked
135
+
136
+
137
+ def _refine_offset(track: OffsetTrack, idx: np.ndarray, level: float) -> tuple[float, int]:
138
+ near = idx[(np.abs(track.offsets[idx] - level) <= 0.010) & (track.scores[idx] >= 0.4)]
139
+ if len(near) == 0:
140
+ return level, 0
141
+ o, w = track.offsets[near], track.scores[near]
142
+ order = np.argsort(o)
143
+ cum = np.cumsum(w[order])
144
+ return float(o[order][np.searchsorted(cum, cum[-1] / 2)]), int(len(near))
145
+
146
+
147
+ def analyze(
148
+ target: Path,
149
+ donor: Path,
150
+ options: AnalyzeOptions | None = None,
151
+ tools: Tools | None = None,
152
+ progress: ProgressCallback | None = None,
153
+ ) -> Plan:
154
+ """
155
+ Work out how to lay the donor's audio onto the target: the speed ratio, every offset and every cut.
156
+
157
+ Takes a minute or two for an episode. Nothing is written except the feature cache (`options.cache_dir`).
158
+
159
+ :param target: the file whose video and timeline are kept
160
+ :param donor: the file holding the dub, a different release of the same video
161
+ :param options: analysis settings; the defaults when None
162
+ :param tools: paths of the external executables; found on PATH when None
163
+ :param progress: called as each step advances
164
+ :return: the plan, to pass to `render` or save with `Plan.save`
165
+ :raises ProbeError: when an input is missing, unreadable or lacks the requested audio stream
166
+ :raises ToolError: when ffmpeg or ffprobe is missing or fails
167
+ :raises AnalysisError: when the files cannot be matched
168
+ """
169
+ options = options or AnalyzeOptions()
170
+ tools = tools or Tools()
171
+
172
+ def step(name: str) -> Callable[[float], None] | None:
173
+ return (lambda f: progress(name, f)) if progress else None
174
+
175
+ a_info, b_info = probe(Path(target), tools), probe(Path(donor), tools)
176
+ a_ref, b_ref = _input_ref(a_info, options.target_track), _input_ref(b_info, options.donor_track)
177
+ if len(b_info.audio) > 1 and options.donor_track == 0:
178
+ log.warning(
179
+ "%s has %d audio streams; using a:0 (choose with --donor-track)", b_info.path.name, len(b_info.audio)
180
+ )
181
+
182
+ fa = load_features(a_info, options.target_track, options.cache_dir, tools)
183
+ fb = load_features(b_info, options.donor_track, options.cache_dir, tools)
184
+ matcher = Matcher(fa)
185
+
186
+ fps_a = a_info.video.fps if a_info.video else None
187
+ fps_b = b_info.video.fps if b_info.video else None
188
+ choice = choose_ratio(
189
+ matcher, fb, fps_a, fps_b, forced=options.ratio, progress=step("speed ratio"), hop=options.hop
190
+ )
191
+ log.info("speed ratio %.10f (%s, %s)", choice.ratio, choice.name, choice.method)
192
+ donor = stretch(fb, choice.ratio)
193
+
194
+ track = offset_track(matcher, donor, options.window, options.hop, options.max_offset, progress=step("offsets"))
195
+ levels = find_levels(track)
196
+ if not levels:
197
+ raise AnalysisError("no offset is confirmed by several windows; the files may not share music and effects")
198
+
199
+ video: _Video | None = None
200
+ if options.use_video and a_info.video and b_info.video:
201
+ video = _Video(
202
+ VideoReader(a_info, options.target_track, 1.0, tools),
203
+ VideoReader(b_info, options.donor_track, choice.ratio, tools),
204
+ )
205
+
206
+ av_consistency = _av_consistency(levels, track, video) if video else None
207
+ kept = prune_levels(levels, av_consistency)
208
+ for lv in levels:
209
+ if lv.dropped:
210
+ log.info("dropping level %+.3f s: %s", lv.offset, lv.dropped)
211
+
212
+ level_scores = np.stack([scores_at_offset(matcher, donor, track, lv.offset) for lv in kept], axis=1)
213
+ runs = runs_of(viterbi(level_scores), level_scores, track, kept)
214
+
215
+ offsets: list[float] = []
216
+ counts: list[int] = []
217
+ spans: list[tuple[float, float]] = [] # stretched donor seconds each run claims, before cut placement
218
+ level_times: list[list[float]] = []
219
+ for r in runs:
220
+ idx = np.arange(r.i0, r.i1 + 1)
221
+ off, n = _refine_offset(track, idx, kept[r.level].offset)
222
+ offsets.append(off)
223
+ counts.append(n)
224
+ spans.append((float(track.times[r.i0]), float(track.times[r.i1])))
225
+ level_times.append(_level_times(track, off, idx, n=2))
226
+
227
+ for at_end in (False, True):
228
+ j = len(runs) - 1 if at_end else 0
229
+ conf = runs[j].confident
230
+ edge_from = track.times[conf[-1]] if at_end else 0.0
231
+ edge_to = donor.duration if at_end else track.times[conf[0]]
232
+ edge = _edge_level(matcher, donor, edge_from, edge_to, offsets[j], at_end, options.max_offset)
233
+ if edge is None:
234
+ continue
235
+ log.info(
236
+ "short segment at the %s: %+.3f s (%d windows of %.0f s)",
237
+ "end" if at_end else "start",
238
+ edge.offset,
239
+ edge.members,
240
+ EDGE_WINDOW,
241
+ )
242
+ levels.append(edge)
243
+ if at_end:
244
+ spans[j] = (spans[j][0], float(edge_from))
245
+ offsets.append(edge.offset)
246
+ counts.append(edge.members)
247
+ spans.append((edge.first, donor.duration))
248
+ level_times.append([edge.first, edge.last])
249
+ else:
250
+ spans[0] = (float(edge_to), spans[0][1])
251
+ offsets.insert(0, edge.offset)
252
+ counts.insert(0, edge.members)
253
+ spans.insert(0, (0.0, edge.last))
254
+ level_times.insert(0, [edge.first, edge.last])
255
+
256
+ video_offsets: list[float | None] = []
257
+ for times, off in zip(level_times, offsets):
258
+ video_offsets.append(video.offset_of(times, off) if video else None)
259
+
260
+ cuts: list[Cut] = []
261
+ for j in range(len(offsets) - 1):
262
+ (start0, end0), (start1, end1) = spans[j], spans[j + 1]
263
+ boundary = (end0 + start1) / 2
264
+ lo = max(start0, boundary - CHANGEPOINT_REACH)
265
+ drop = max(0.0, offsets[j] - offsets[j + 1])
266
+ hi = min(end1 + drop, boundary + CHANGEPOINT_REACH + drop)
267
+ shifts = [
268
+ v - o for v, o in ((video_offsets[j], offsets[j]), (video_offsets[j + 1], offsets[j + 1])) if v is not None
269
+ ]
270
+ av_shift = float(np.mean(shifts)) if shifts else 0.0
271
+ cut = localize(matcher, donor, offsets[j], offsets[j + 1], lo, hi, video.b if video else None, av_shift)
272
+ cuts.append(cut)
273
+ log.info(
274
+ "cut at %s: %+.3f -> %+.3f s (%s, %s)",
275
+ mmss(cut.target_time),
276
+ cut.offset_before,
277
+ cut.offset_after,
278
+ cut.confidence,
279
+ cut.evidence[0].kind,
280
+ )
281
+
282
+ segments = _segments(offsets, counts, video_offsets, cuts, donor, a_ref.duration)
283
+ plan = Plan(
284
+ target=a_ref,
285
+ donor=b_ref,
286
+ ratio=choice.ratio,
287
+ ratio_name=choice.name,
288
+ ratio_method=choice.method,
289
+ segments=segments,
290
+ cuts=cuts,
291
+ levels=[{**asdict(lv), "kept": not lv.dropped} for lv in levels],
292
+ candidates=[asdict(c) for c in choice.candidates],
293
+ windows={
294
+ "times": track.times.tolist(),
295
+ "offsets": track.offsets.tolist(),
296
+ "scores": track.scores.tolist(),
297
+ },
298
+ )
299
+ if choice.warning:
300
+ plan.warnings.append(choice.warning)
301
+ for c in cuts:
302
+ if c.confidence == "low":
303
+ plan.warnings.append(
304
+ f"the cut at {mmss(c.target_time)} is a guess; listen there and edit the plan if needed"
305
+ )
306
+ for lv in kept:
307
+ if lv.crispness < 0.5:
308
+ plan.warnings.append(f"offset {lv.offset:+.3f} s is a loose match (crispness {lv.crispness:.2f})")
309
+ plan.normalize()
310
+ plan.validate()
311
+ return plan
312
+
313
+
314
+ def _edge_level(
315
+ matcher: Matcher,
316
+ donor: Features,
317
+ t0: float,
318
+ t1: float,
319
+ neighbor: float,
320
+ at_end: bool,
321
+ max_offset: float | None,
322
+ ) -> Level | None:
323
+ """
324
+ A crisp level in donor [t0, t1] (stretched seconds) that only short windows reveal, or None.
325
+
326
+ It must differ from the neighboring segment's offset and keep the target time moving forward: a theme tune that
327
+ recurs elsewhere in the target matches tightly too, but at an offset that runs backwards.
328
+ """
329
+ if t1 - t0 < EDGE_MIN:
330
+ return None
331
+ m = int(round(EDGE_WINDOW * FRAME_RATE))
332
+ m -= m % DECIMATION
333
+ hop = int(round(EDGE_HOP * FRAME_RATE))
334
+ f0 = max(0, int((t0 - T0) * FRAME_RATE) - m // 2)
335
+ f1 = min(donor.n_frames, int((t1 - T0) * FRAME_RATE) + m // 2)
336
+ if f1 - f0 < m:
337
+ return None
338
+ starts = np.unique(np.append(np.arange(f0, f1 - m + 1, hop), f1 - m)).astype(int)
339
+ positions, scores = matcher.search(donor.bands, starts, m, max_offset=max_offset)
340
+ fine = OffsetTrack(
341
+ times=T0 + (starts + m / 2) / FRAME_RATE,
342
+ offsets=(positions - starts) / FRAME_RATE,
343
+ scores=scores,
344
+ starts=starts,
345
+ window_frames=m,
346
+ )
347
+ ok = []
348
+ for lv in find_levels(fine):
349
+ # Close to the neighbor it is more likely the loose dialogue match than a jump
350
+ if lv.crispness < CRISP or abs(lv.offset - neighbor) <= COMPETE_DISTANCE:
351
+ continue
352
+ forward = lv.first + lv.offset >= t0 + neighbor if at_end else lv.last + lv.offset <= t1 + neighbor
353
+ if forward:
354
+ ok.append(lv)
355
+ return max(ok, key=lambda lv: lv.quality, default=None)
356
+
357
+
358
+ def _av_consistency(levels: list[Level], track: OffsetTrack, video: _Video) -> dict[int, float]:
359
+ """
360
+ Per level: how far its audio-minus-video difference is from the other levels' (seconds). Only computed when
361
+ levels compete, for the competitors and a few crisp references, since every sample decodes video.
362
+ """
363
+ competing = {id(x) for x in levels for y in levels if x is not y and abs(x.offset - y.offset) <= COMPETE_DISTANCE}
364
+ if not competing:
365
+ return {}
366
+ crisp = [lv for lv in levels if lv.crispness >= CRISP and id(lv) not in competing][:3]
367
+ diffs: dict[int, float] = {}
368
+ for lv in [lv for lv in levels if id(lv) in competing] + crisp:
369
+ v = video.offset_of(_level_times(track, lv.offset, n=1), lv.offset)
370
+ if v is not None:
371
+ diffs[id(lv)] = lv.offset - v
372
+ # Loose levels do not vote: their audio offsets are off by design
373
+ voters = {id(lv) for lv in levels if lv.crispness >= CRISP and id(lv) in diffs}
374
+ out: dict[int, float] = {}
375
+ for lv in levels:
376
+ if id(lv) not in diffs:
377
+ continue
378
+ others = [diffs[k] for k in voters if k != id(lv) and abs(diffs[k] - diffs[id(lv)]) < 1.0]
379
+ if others:
380
+ out[id(lv)] = abs(diffs[id(lv)] - float(np.median(others)))
381
+ return out
382
+
383
+
384
+ def _segments(
385
+ offsets: list[float],
386
+ counts: list[int],
387
+ video_offsets: list[float | None],
388
+ cuts: list[Cut],
389
+ donor: Features,
390
+ a_duration: float,
391
+ ) -> list[Segment]:
392
+ donor_end = donor.duration
393
+ segments: list[Segment] = []
394
+ for j, off in enumerate(offsets):
395
+ b0 = 0.0 if j == 0 else cuts[j - 1].donor_time + max(0.0, offsets[j - 1] - off)
396
+ b1 = donor_end if j == len(offsets) - 1 else cuts[j].donor_time
397
+ a0, a1 = max(0.0, b0 + off), min(a_duration, b1 + off)
398
+ if a1 - a0 <= 0.0:
399
+ continue
400
+ segments.append(
401
+ Segment(target_start=a0, target_end=a1, offset=off, windows=counts[j], video_offset=video_offsets[j])
402
+ )
403
+ return segments
dubweld/cache.py ADDED
@@ -0,0 +1,59 @@
1
+ """On-disk cache of decoded features, keyed by file signature, so re-analyzing a pair is fast."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import logging
7
+ import os
8
+ from collections.abc import Callable
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+
13
+ from dubweld.features import Features
14
+
15
+ log = logging.getLogger(__name__)
16
+
17
+ # Bump when feature extraction changes, so stale entries are never read
18
+ FEATURE_VERSION = 3
19
+
20
+
21
+ def default_cache_dir() -> Path:
22
+ """`$XDG_CACHE_HOME/dubweld`, or `~/.cache/dubweld`."""
23
+ base = os.environ.get("XDG_CACHE_HOME") or str(Path.home() / ".cache")
24
+ return Path(base) / "dubweld"
25
+
26
+
27
+ def _key(path: Path, audio_index: int, size: int, mtime: float) -> str:
28
+ raw = f"{Path(path).resolve()}|{size}|{mtime:.6f}|{audio_index}|v{FEATURE_VERSION}"
29
+ return hashlib.sha1(raw.encode()).hexdigest()
30
+
31
+
32
+ def features(
33
+ path: Path,
34
+ audio_index: int,
35
+ size: int,
36
+ mtime: float,
37
+ cache_dir: Path | None,
38
+ compute: Callable[[], Features],
39
+ ) -> Features:
40
+ """Load features from `cache_dir` or compute and store them; with no `cache_dir`, always compute."""
41
+ if cache_dir is None:
42
+ return compute()
43
+ file = Path(cache_dir) / f"features-{_key(path, audio_index, size, mtime)}.npz"
44
+ if file.is_file():
45
+ try:
46
+ with np.load(file) as data:
47
+ log.debug("features of %s from cache", Path(path).name)
48
+ return Features(bands=data["bands"], env_db=data["env_db"])
49
+ except (OSError, ValueError, KeyError) as e:
50
+ log.debug("ignoring unreadable cache entry %s: %s", file, e)
51
+ result = compute()
52
+ try:
53
+ Path(cache_dir).mkdir(parents=True, exist_ok=True)
54
+ tmp = file.with_suffix(".tmp.npz")
55
+ np.savez(tmp, bands=result.bands, env_db=result.env_db)
56
+ tmp.replace(file)
57
+ except OSError as e:
58
+ log.debug("cannot write cache %s: %s", file, e)
59
+ return result