suba 0.1.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.

Potentially problematic release.


This version of suba might be problematic. Click here for more details.

@@ -0,0 +1,22 @@
1
+ name: Lint
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ branches: [main]
8
+
9
+ jobs:
10
+ ruff:
11
+ runs-on: ubuntu-latest
12
+ steps:
13
+ - uses: actions/checkout@v4
14
+
15
+ - name: Install uv
16
+ uses: astral-sh/setup-uv@v5
17
+
18
+ - name: Lint with ruff
19
+ run: uvx ruff check .
20
+
21
+ - name: Check formatting with ruff
22
+ run: uvx ruff format --check .
@@ -0,0 +1,24 @@
1
+ name: Publish
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - 'v*'
7
+
8
+ jobs:
9
+ pypi:
10
+ runs-on: ubuntu-latest
11
+ environment: pypi
12
+ permissions:
13
+ id-token: write
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+
17
+ - name: Install uv
18
+ uses: astral-sh/setup-uv@v5
19
+
20
+ - name: Build package
21
+ run: uv build
22
+
23
+ - name: Publish to PyPI
24
+ run: uv publish --token "${{ secrets.PYPI_API_TOKEN }}"
suba-0.1.0/.gitignore ADDED
@@ -0,0 +1,4 @@
1
+ .venv/
2
+ __pycache__/
3
+ data/
4
+ AGENTS.md
@@ -0,0 +1 @@
1
+ 3.12
@@ -0,0 +1,39 @@
1
+ # Contributing
2
+
3
+ Thanks for wanting to help. Here's what you need to know.
4
+
5
+ ## Setup
6
+
7
+ ```bash
8
+ git clone https://github.com/xy3/suba
9
+ cd suba
10
+ uv tool install . --with openai-whisper
11
+ ```
12
+
13
+ You'll also need `ffmpeg` on your system.
14
+
15
+ ## Running from source
16
+
17
+ ```bash
18
+ python main.py subtitles.srt video.mkv
19
+ ```
20
+
21
+ No build step needed — it's a single file.
22
+
23
+ ## Project structure
24
+
25
+ Everything is in `main.py` (~340 lines). There are no external Python dependencies beyond `openai-whisper`, and even that is intentionally left out of `pyproject.toml` to keep the package dependency-free.
26
+
27
+ ## What to work on
28
+
29
+ - Support for more subtitle formats (ASS, SSA, SUB)
30
+ - Progressive sync (non-constant drift correction)
31
+ - Better language detection for mixed-language subtitles
32
+ - Tests (there are currently none)
33
+ - CI/CD for automated testing
34
+
35
+ ## Before submitting
36
+
37
+ - Make sure `python main.py subs.srt video.mkv` works end-to-end
38
+ - Keep the single-file structure unless there's a compelling reason to split
39
+ - Don't add `openai-whisper` to `pyproject.toml` — it's handled by `uv tool install --with`
suba-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,5 @@
1
+ Metadata-Version: 2.4
2
+ Name: suba
3
+ Version: 0.1.0
4
+ Summary: Detect subtitle sync offset using Whisper transcription
5
+ Requires-Python: >=3.12
suba-0.1.0/README.md ADDED
@@ -0,0 +1,45 @@
1
+ # suba
2
+
3
+ > Fix subtitle sync with Whisper, because `h` and `g` are for cowards.
4
+
5
+ ---
6
+
7
+ You downloaded subtitles. The first line pops up during the studio logo. By the third act, characters are reacting to things that haven't happened yet. You've spent 20 minutes in VLC tapping keys and you're 90% sure you made it worse.
8
+
9
+ Suba rips a minute of audio from a dialogue-heavy part of your video, transcribes it with Whisper, matches the transcription against the subtitle file, and tells you the offset. Then it writes out a corrected SRT so you can stop thinking about this.
10
+
11
+ ## Install
12
+
13
+ You need `ffmpeg` and [`uv`](https://docs.astral.sh/uv/). Then:
14
+
15
+ ```bash
16
+ uv tool install git+https://github.com/xy3/suba --with openai-whisper
17
+ ```
18
+
19
+ That's it. One command — no clone, no build step.
20
+
21
+ ## Use
22
+
23
+ ```bash
24
+ suba subs.srt movie.mkv -o fixed.srt
25
+ ```
26
+
27
+ ```bash
28
+ suba <subtitles> <video> -o <output.srt|vtt>
29
+ ```
30
+
31
+ | Flag | What |
32
+ |------|------|
33
+ | `-o`, `--output` | Write corrected SRT/VTT |
34
+ | `-m`, `--model` | Whisper model (`base`, `small`, `medium`, `large`) |
35
+ | `-d`, `--duration` | Audio duration in seconds (default 60) |
36
+ | `-t`, `--start` | Manual start time in seconds |
37
+ | `--threshold` | Minimum similarity to accept a match (default 0.2) |
38
+
39
+ ## How it works
40
+
41
+ - Finds the densest 60 seconds of subtitles (more lines = more talking, probably)
42
+ - Extracts that audio with ffmpeg
43
+ - Transcribes it with Whisper
44
+ - Slides windows of the transcription over each candidate subtitle line, scoring by text similarity and timestamp proximity
45
+ - Shifts all timestamps by the detected offset and writes a fixed SRT
suba-0.1.0/article.md ADDED
@@ -0,0 +1,132 @@
1
+ # I Never Manually Sync Subtitles Anymore. Here's the Whisper AI Script I Use.
2
+
3
+ We've all been there. You find the perfect subtitle file for a movie. The first line shows up during the studio logo. By act three, characters are laughing at jokes that haven't been told yet. You open VLC, start tapping `h` and `g`, and twenty minutes later you're 90% sure you made it worse.
4
+
5
+ I got tired of this. So I wrote a tool that fixes subtitle sync automatically using OpenAI's Whisper. It takes two arguments — a subtitle file and a video file — and tells you the exact offset. Then it writes out a corrected file so you never have to think about it again.
6
+
7
+ ## The problem with subtitle sync
8
+
9
+ Most out-of-sync subtitles suffer from a constant offset. Someone ripped them from a different release, or a frame rate mismatch shifted every timestamp by the same amount. The fix is trivial — add or subtract a constant number of seconds to every line — but *finding* that number is the hard part.
10
+
11
+ The traditional approach is manual. You jump to a dialogue-heavy scene, watch a character's lips, and nudge the subtitle track forward or backward until it "feels right." This works if you're patient and have good ears. I am neither.
12
+
13
+ ## How suba works
14
+
15
+ The idea is simple: let Whisper transcribe a chunk of the actual audio, then compare its transcription to the subtitle file. If the subtitles say a character should be speaking at 23:36, but Whisper heard those words at 23:38, your offset is -2 seconds. Shift everything by 2 seconds, and you're done.
16
+
17
+ Here's the pipeline:
18
+
19
+ **1. Find the dialogue.** You don't want to transcribe the opening credits or a long action sequence with no talking. Suba scans the subtitle file and finds the densest 60-second window — the part with the most lines per minute, which almost certainly has people talking.
20
+
21
+ **2. Extract the audio.** ffmpeg pulls that one-minute segment as a mono 16kHz WAV file. Fast and lossless for Whisper's purposes.
22
+
23
+ **3. Transcribe with Whisper.** OpenAI's Whisper model converts the audio to text with timestamps. You get back something like:
24
+
25
+ ```
26
+ [9.00s – 9.90s] You guys suck.
27
+ [9.90s – 10.80s] Both of you guys suck.
28
+ ```
29
+
30
+ **4. Match and score.** This is where it gets interesting. For each subtitle line that falls within the extracted window, suba slides a window over the Whisper transcription and scores how well they match. The scoring combines two things:
31
+
32
+ - **Text similarity** (70% weight): how closely do the words match? Uses Python's `SequenceMatcher` algorithm — the same engine behind `difflib`.
33
+ - **Temporal proximity** (30% weight): how close is the Whisper segment's timestamp to where the subtitle *says* it should be?
34
+
35
+ The combined score prevents false positives. A perfect text match at the wrong time is less convincing than a good text match at roughly the right time.
36
+
37
+ **5. Compute the offset.** Once the best match is found, the math is trivial:
38
+
39
+ ```
40
+ offset = subtitle_start - (audio_extraction_start + whisper_segment_start)
41
+ ```
42
+
43
+ Positive offset means subtitles are behind. Negative means they're ahead. Either way, suba shifts every timestamp by the negation of that offset and writes a corrected SRT or VTT file.
44
+
45
+ ## Real example
46
+
47
+ I tested this on *Zoolander 2*. The subtitles I found were clearly from a different release — the sync drifted badly after the first few minutes.
48
+
49
+ Running suba:
50
+
51
+ ```bash
52
+ $ suba zoolander2.srt Zoolander.2.mp4
53
+ ```
54
+
55
+ Output:
56
+
57
+ ```
58
+ Parsed 1474 subtitle entries
59
+ Extracting audio @ 00:23:29.608 for 60 s
60
+ Transcribing with Whisper (base) …
61
+ Got 43 whisper segments
62
+
63
+ ==========================================================
64
+ Match similarity: 1.000
65
+ Subtitle line: [00:23:36.615 → 00:23:37.914]
66
+ "You guys suck.
67
+ Both of you guys suck."
68
+ Whisper segment: [9.000s → 9.900s in extracted audio]
69
+ "You guys suck."
70
+ Whisper in video: 00:23:38.608
71
+
72
+ SYNC OFFSET: -1.993 s (-1992 ms)
73
+ → Subtitles are 1.993s AHEAD of audio
74
+ ==========================================================
75
+ ```
76
+
77
+ A perfect text match at 23:36 in the subtitle file versus 23:38 in the actual audio. The subtitles are roughly 2 seconds ahead — exactly the kind of constant offset that makes a movie unwatchable. One command, two seconds, problem solved.
78
+
79
+ To write the fixed subtitles:
80
+
81
+ ```bash
82
+ $ suba zoolander2.srt Zoolander.2.mp4 -o fixed.srt
83
+ ```
84
+
85
+ ## Why Whisper?
86
+
87
+ Whisper is remarkably good at this task. It handles background noise, music, and overlapping dialogue better than any open-source speech-to-text model I've tried. The `base` model is small enough to run on a laptop CPU in under a minute for a 60-second clip. If you need higher accuracy, `small` or `medium` will slow things down but improve recognition of mumbled lines or thick accents.
88
+
89
+ ## The algorithm details that matter
90
+
91
+ A few design decisions made this work reliably where simpler approaches failed:
92
+
93
+ **Multi-window matching.** A subtitle line might say "You guys suck. Both of you guys suck." but Whisper might split that into two segments or merge it into one. Suba tries matching each subtitle against 1-, 2-, and 3-segment windows of the transcription and takes the best score.
94
+
95
+ **Dialogue density heuristic.** Instead of requiring the user to pick a start time, suba scans the entire subtitle timeline in 5-second increments and picks the region with the most entries. More lines per minute means more talking, which means better transcription, which means higher confidence in the match.
96
+
97
+ **Similarity threshold.** The default threshold of 0.2 prevents garbage matches. If Whisper hallucinates or the audio region happens to be mostly music, suba exits with an error rather than silently producing a wrong offset.
98
+
99
+ ## Install and use
100
+
101
+ The only prerequisites are `ffmpeg` and `uv` (a fast Python package manager):
102
+
103
+ ```bash
104
+ # Install uv if you don't have it
105
+ curl -LsSf https://astral.sh/uv/install.sh | sh
106
+
107
+ # Install suba (one command — this handles Python and Whisper too)
108
+ uv tool install git+https://github.com/xy3/suba --with openai-whisper
109
+ ```
110
+
111
+ Then:
112
+
113
+ ```bash
114
+ # Find the offset
115
+ suba subtitles.srt movie.mkv
116
+
117
+ # Write corrected subtitles
118
+ suba subtitles.vtt movie.mp4 -o fixed.srt
119
+
120
+ # Use a larger model for better accuracy
121
+ suba -m medium subtitles.srt movie.mkv
122
+ ```
123
+
124
+ ## What it doesn't do
125
+
126
+ Suba assumes a constant offset. If your subtitles drift progressively (the sync gets worse over time), this won't help. It also assumes the subtitle text roughly matches what's being said — it won't work for dubtitles or heavily edited fansubs. And it needs at least a few dialogue-heavy minutes in the video; a silent film with subtitles will fail the density check.
127
+
128
+ ## The bottom line
129
+
130
+ I used to spend 10–15 minutes manually syncing subtitles for every foreign film I watched. Now I run one command to install and one command to sync. The tool is open source, a single Python file, and costs nothing to run. If you watch subtitled content with any regularity, this will save you real time.
131
+
132
+ [suba on GitHub](https://github.com/xy3/suba)
suba-0.1.0/main.py ADDED
@@ -0,0 +1,399 @@
1
+ #!/usr/bin/env python3
2
+ """suba — Detect subtitle sync offset using Whisper transcription."""
3
+
4
+ import argparse
5
+ import difflib
6
+ import os
7
+ import re
8
+ import subprocess
9
+ import sys
10
+ import tempfile
11
+ from typing import Optional
12
+ from pathlib import Path
13
+
14
+ try:
15
+ import whisper
16
+ except ImportError:
17
+ sys.exit(
18
+ "openai-whisper is not installed.\n"
19
+ "Install it first: pip install openai-whisper"
20
+ )
21
+
22
+
23
+ def ts_to_seconds(ts: str) -> float:
24
+ """Parse SRT/VTT timestamp (HH:MM:SS,mmm or HH:MM:SS.mmm) to float seconds."""
25
+ h, m, rest = 0, 0, ts
26
+ parts = ts.split(":")
27
+ if len(parts) == 3:
28
+ h, m, rest = parts
29
+ elif len(parts) == 2:
30
+ m, rest = parts
31
+ s, ms = (
32
+ rest.replace(",", ".").split(".")
33
+ if ("." in rest or "," in rest)
34
+ else (rest, "0")
35
+ )
36
+ return int(h) * 3600 + int(m) * 60 + int(s) + int(ms.ljust(3, "0")) / 1000
37
+
38
+
39
+ def strip_tags(text: str) -> str:
40
+ """Remove VTT/HTML-style tags like <c>, <v>, </c>, etc."""
41
+ return re.sub(r"<[^>]+>", "", text)
42
+
43
+
44
+ def parse_subtitle(path: str) -> list[dict]:
45
+ """Parse SRT or VTT file into [{'start': float, 'end': float, 'text': str}]."""
46
+ with open(path, "r", encoding="utf-8-sig") as f:
47
+ content = f.read()
48
+
49
+ entries = []
50
+ # Split on blank lines
51
+ blocks = re.split(r"\n\s*\n", content.strip())
52
+
53
+ for block in blocks:
54
+ block = block.strip()
55
+ if not block:
56
+ continue
57
+ lines = block.split("\n")
58
+
59
+ # Find the line containing '-->'
60
+ ts_idx = None
61
+ for i, line in enumerate(lines):
62
+ if "-->" in line:
63
+ ts_idx = i
64
+ break
65
+ if ts_idx is None:
66
+ continue
67
+
68
+ ts_line = lines[ts_idx]
69
+ m = re.match(r"([\d:,.-]+?)\s*-->\s*([\d:,.-]+)", ts_line)
70
+ if not m:
71
+ continue
72
+
73
+ start = ts_to_seconds(m.group(1).strip())
74
+ end = ts_to_seconds(m.group(2).strip())
75
+ text = strip_tags("\n".join(lines[ts_idx + 1 :])).strip()
76
+ entries.append({"start": start, "end": end, "text": text})
77
+
78
+ return entries
79
+
80
+
81
+ def find_dialogue_region(entries: list[dict], duration: float) -> float:
82
+ """Pick a start time in the video where subtitle density is highest."""
83
+ if not entries:
84
+ return 0.0
85
+
86
+ t_min = entries[0]["start"]
87
+ t_max = entries[-1]["end"]
88
+
89
+ best_start = entries[0]["start"]
90
+ best_count = 0
91
+ step = 5.0
92
+
93
+ t = t_min
94
+ while t + duration <= t_max:
95
+ count = sum(1 for e in entries if t <= e["start"] < t + duration)
96
+ if count > best_count:
97
+ best_count = count
98
+ best_start = t
99
+ t += step
100
+
101
+ # If absolutely nothing found (sparse subtitles), fall back to 25% into the range
102
+ if best_count == 0:
103
+ best_start = t_min + (t_max - t_min) * 0.25
104
+
105
+ return best_start
106
+
107
+
108
+ def extract_audio(
109
+ video_path: str, start_s: float, duration_s: float, output_path: str
110
+ ) -> None:
111
+ """Extract mono 16 kHz WAV audio segment via ffmpeg."""
112
+ subprocess.run(
113
+ [
114
+ "ffmpeg",
115
+ "-y",
116
+ "-ss",
117
+ str(start_s),
118
+ "-t",
119
+ str(duration_s),
120
+ "-i",
121
+ video_path,
122
+ "-vn",
123
+ "-acodec",
124
+ "pcm_s16le",
125
+ "-ar",
126
+ "16000",
127
+ "-ac",
128
+ "1",
129
+ output_path,
130
+ ],
131
+ check=True,
132
+ capture_output=True,
133
+ )
134
+
135
+
136
+ def text_similarity(a: str, b: str) -> float:
137
+ """Calculate similarity ratio (0–1) between two strings, ignoring punctuation."""
138
+
139
+ def clean(s: str) -> str:
140
+ return re.sub(r"[^\w\s]", "", s.lower())
141
+
142
+ a, b = clean(a), clean(b)
143
+ if not a or not b:
144
+ return 0.0
145
+ return difflib.SequenceMatcher(None, a, b).ratio()
146
+
147
+
148
+ def compress_ws(s: str) -> str:
149
+ """Collapse whitespace."""
150
+ return re.sub(r"\s+", " ", s).strip()
151
+
152
+
153
+ def find_best_match(
154
+ transcription: dict,
155
+ entries: list[dict],
156
+ seg_start: float,
157
+ seg_dur: float,
158
+ ) -> Optional[tuple[dict, dict, float]]:
159
+ """Return the (subtitle_entry, whisper_segment, similarity_score) or None.
160
+
161
+ Only subtitle entries whose *start* falls within the extracted audio segment
162
+ are candidates. The algorithm tries matching against 1-, 2-, and 3-segment
163
+ windows of the Whisper output and weights results by temporal proximity.
164
+ """
165
+ seg_end = seg_start + seg_dur
166
+ candidates = [e for e in entries if seg_start <= e["start"] < seg_end]
167
+ if not candidates:
168
+ return None
169
+
170
+ segments = transcription.get("segments", [])
171
+ if not segments:
172
+ return None
173
+
174
+ best = None # (sub_entry, whisper_seg, text_similarity)
175
+ best_score = 0.0
176
+
177
+ for sub in candidates:
178
+ sub_text = compress_ws(sub["text"])
179
+ if not sub_text:
180
+ continue
181
+ expected_pos = (
182
+ sub["start"] - seg_start
183
+ ) # where in the audio the line should appear
184
+
185
+ for i in range(len(segments)):
186
+ for win in (1, 2, 3):
187
+ if i + win > len(segments):
188
+ break
189
+ combo = " ".join(s["text"].strip() for s in segments[i : i + win])
190
+ combo = compress_ws(combo)
191
+ if not combo:
192
+ continue
193
+
194
+ text_score = text_similarity(sub_text, combo)
195
+ if text_score == 0:
196
+ continue
197
+
198
+ # Temporal weight: closer whisper position → higher weight
199
+ wseg_pos = segments[i]["start"]
200
+ time_diff = abs(wseg_pos - expected_pos)
201
+ max_diff = seg_dur * 0.5
202
+ temporal_weight = max(0.0, 1.0 - time_diff / max_diff)
203
+
204
+ combined = text_score * 0.7 + temporal_weight * 0.3
205
+ if combined > best_score:
206
+ best_score = combined
207
+ best = (sub, segments[i], text_score)
208
+
209
+ return best
210
+
211
+
212
+ def seconds_to_srt_ts(s: float) -> str:
213
+ """Convert float seconds to SRT timestamp HH:MM:SS,mmm."""
214
+ s = max(0, s)
215
+ h, r = divmod(int(s), 3600)
216
+ m, sec = divmod(r, 60)
217
+ ms = int((s - int(s)) * 1000)
218
+ return f"{h:02d}:{m:02d}:{sec:02d},{ms:03d}"
219
+
220
+
221
+ def seconds_to_vtt_ts(s: float) -> str:
222
+ """Convert float seconds to VTT timestamp HH:MM:SS.mmm."""
223
+ s = max(0, s)
224
+ h, r = divmod(int(s), 3600)
225
+ m, sec = divmod(r, 60)
226
+ ms = int((s - int(s)) * 1000)
227
+ return f"{h:02d}:{m:02d}:{sec:02d}.{ms:03d}"
228
+
229
+
230
+ def write_subtitle(path: str, entries: list[dict]) -> None:
231
+ """Write shifted entries to SRT or VTT, auto-detected from extension."""
232
+ ext = Path(path).suffix.lower()
233
+ with open(path, "w", encoding="utf-8") as f:
234
+ if ext == ".vtt":
235
+ f.write("WEBVTT\n\n")
236
+ ts_fn = seconds_to_vtt_ts
237
+ else:
238
+ ts_fn = seconds_to_srt_ts
239
+
240
+ for i, e in enumerate(entries, 1):
241
+ if ext == ".srt":
242
+ f.write(f"{i}\n")
243
+ f.write(f"{ts_fn(e['start'])} --> {ts_fn(e['end'])}\n")
244
+ f.write(f"{e['text']}\n\n")
245
+
246
+
247
+ def fmt_time(s: float) -> str:
248
+ """Format seconds as HH:MM:SS.mmm (with optional leading minus)."""
249
+ sign = "-" if s < 0 else ""
250
+ a = abs(s)
251
+ h, r = divmod(int(a), 3600)
252
+ m, sec = divmod(r, 60)
253
+ ms = int((a - int(a)) * 1000)
254
+ return f"{sign}{h:02d}:{m:02d}:{sec:02d}.{ms:03d}"
255
+
256
+
257
+ def main():
258
+ ap = argparse.ArgumentParser(
259
+ description="subsync — detect subtitle sync offset using Whisper"
260
+ )
261
+ ap.add_argument("subtitle", help="Path to SRT or VTT subtitle file")
262
+ ap.add_argument("video", help="Path to video file")
263
+ ap.add_argument(
264
+ "--duration",
265
+ "-d",
266
+ type=float,
267
+ default=60.0,
268
+ help="Length of audio to extract [default: 60 s]",
269
+ )
270
+ ap.add_argument(
271
+ "--model", "-m", default="base", help="Whisper model to use [default: base]"
272
+ )
273
+ ap.add_argument(
274
+ "--start",
275
+ "-t",
276
+ type=float,
277
+ default=None,
278
+ help="Manual start time in the video (auto-detected if omitted)",
279
+ )
280
+ ap.add_argument(
281
+ "--threshold",
282
+ type=float,
283
+ default=0.2,
284
+ help="Minimum text-similarity to accept a match [default: 0.2]",
285
+ )
286
+ ap.add_argument(
287
+ "--output",
288
+ "-o",
289
+ default=None,
290
+ help="Write fixed subtitles to this file (.srt or .vtt)",
291
+ )
292
+ args = ap.parse_args()
293
+
294
+ # 1. Parse subtitles
295
+ entries = parse_subtitle(args.subtitle)
296
+ if not entries:
297
+ print("error: no subtitle entries found", file=sys.stderr)
298
+ sys.exit(1)
299
+ print(f"Parsed {len(entries)} subtitle entries")
300
+
301
+ # 2. Determine start time
302
+ start_s = (
303
+ args.start
304
+ if args.start is not None
305
+ else find_dialogue_region(entries, args.duration)
306
+ )
307
+ print(f"Extracting audio @ {fmt_time(start_s)} for {args.duration} s")
308
+
309
+ # 3. Extract audio
310
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:
311
+ audio_path = tmp.name
312
+
313
+ try:
314
+ extract_audio(args.video, start_s, args.duration, audio_path)
315
+
316
+ # 4. Transcribe with Whisper
317
+ print(f"Transcribing with Whisper ({args.model}) …")
318
+ model = whisper.load_model(args.model)
319
+ result = model.transcribe(audio_path, verbose=False)
320
+ segments = result.get("segments", [])
321
+ print(f"Got {len(segments)} whisper segments\n")
322
+
323
+ for seg in segments:
324
+ print(
325
+ f" [{seg['start']:7.2f}s – {seg['end']:7.2f}s] {seg['text'].strip()}"
326
+ )
327
+
328
+ if not segments:
329
+ print("error: whisper produced no segments", file=sys.stderr)
330
+ sys.exit(1)
331
+
332
+ # 5. Find best matching subtitle line
333
+ match = find_best_match(result, entries, start_s, args.duration)
334
+
335
+ if match is None:
336
+ print(
337
+ "\nNo subtitle entries found within the transcribed region.",
338
+ file=sys.stderr,
339
+ )
340
+ sys.exit(1)
341
+
342
+ sub_entry, wseg, sim = match
343
+
344
+ if sim < args.threshold:
345
+ print(
346
+ f"\nBest similarity ({sim:.3f}) below threshold ({args.threshold}).",
347
+ file=sys.stderr,
348
+ )
349
+ print(f" Sub: [{fmt_time(sub_entry['start'])}] {sub_entry['text']}")
350
+ print(f" Wsp: [{wseg['start']:.2f}s] {wseg['text'].strip()}")
351
+ sys.exit(1)
352
+
353
+ # 6. Calculate offset
354
+ video_time_of_whisper = start_s + wseg["start"]
355
+ diff = sub_entry["start"] - video_time_of_whisper
356
+
357
+ print()
358
+ print("=" * 58)
359
+ print(f" Match similarity: {sim:.3f}")
360
+ print(
361
+ f" Subtitle line: [{fmt_time(sub_entry['start'])} → {fmt_time(sub_entry['end'])}]"
362
+ )
363
+ print(f' "{sub_entry["text"]}"')
364
+ print(
365
+ f" Whisper segment: [{wseg['start']:.3f}s → {wseg['end']:.3f}s in extracted audio]"
366
+ )
367
+ print(f' "{wseg["text"].strip()}"')
368
+ print(f" Whisper in video: {fmt_time(video_time_of_whisper)}")
369
+ print()
370
+ print(f" SYNC OFFSET: {diff:+.3f} s ({int(diff * 1000):+d} ms)")
371
+ if diff > 0:
372
+ print(f" → Subtitles are {diff:.3f}s BEHIND audio")
373
+ elif diff < 0:
374
+ print(f" → Subtitles are {abs(diff):.3f}s AHEAD of audio")
375
+ else:
376
+ print(" → Subtitles are perfectly synced")
377
+ print("=" * 58)
378
+
379
+ # 7. Write fixed SRT if requested
380
+ if args.output:
381
+ correction = -diff
382
+ shifted = [
383
+ {
384
+ "start": e["start"] + correction,
385
+ "end": e["end"] + correction,
386
+ "text": e["text"],
387
+ }
388
+ for e in entries
389
+ ]
390
+ write_subtitle(args.output, shifted)
391
+ print(f"\nFixed subtitles written to: {args.output}")
392
+
393
+ finally:
394
+ if os.path.exists(audio_path):
395
+ os.unlink(audio_path)
396
+
397
+
398
+ if __name__ == "__main__":
399
+ main()
@@ -0,0 +1,16 @@
1
+ [project]
2
+ name = "suba"
3
+ version = "0.1.0"
4
+ description = "Detect subtitle sync offset using Whisper transcription"
5
+ requires-python = ">=3.12"
6
+ dependencies = []
7
+
8
+ [project.scripts]
9
+ suba = "main:main"
10
+
11
+ [build-system]
12
+ requires = ["hatchling"]
13
+ build-backend = "hatchling.build"
14
+
15
+ [tool.hatch.build.targets.wheel]
16
+ packages = ["."]
suba-0.1.0/uv.lock ADDED
@@ -0,0 +1,8 @@
1
+ version = 1
2
+ revision = 3
3
+ requires-python = ">=3.12"
4
+
5
+ [[package]]
6
+ name = "suba"
7
+ version = "0.1.0"
8
+ source = { editable = "." }