captionkit 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.
- captionkit/__init__.py +3 -0
- captionkit/batch.py +150 -0
- captionkit/burner.py +280 -0
- captionkit/cli.py +321 -0
- captionkit/formatter.py +191 -0
- captionkit/transcriber.py +129 -0
- captionkit-0.1.0.dist-info/METADATA +226 -0
- captionkit-0.1.0.dist-info/RECORD +11 -0
- captionkit-0.1.0.dist-info/WHEEL +4 -0
- captionkit-0.1.0.dist-info/entry_points.txt +2 -0
- captionkit-0.1.0.dist-info/licenses/LICENSE +21 -0
captionkit/__init__.py
ADDED
captionkit/batch.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""Batch processing for folders of media files."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from rich.console import Console
|
|
8
|
+
from rich.progress import Progress
|
|
9
|
+
|
|
10
|
+
from captionkit.burner import (
|
|
11
|
+
burn_captions,
|
|
12
|
+
get_preset,
|
|
13
|
+
preset_to_ass_kwargs,
|
|
14
|
+
preset_to_karaoke_kwargs,
|
|
15
|
+
)
|
|
16
|
+
from captionkit.formatter import to_ass, to_ass_karaoke, write_all_formats
|
|
17
|
+
from captionkit.transcriber import TranscriptionResult, transcribe
|
|
18
|
+
|
|
19
|
+
MEDIA_EXTENSIONS = {
|
|
20
|
+
".mp4",
|
|
21
|
+
".mkv",
|
|
22
|
+
".avi",
|
|
23
|
+
".mov",
|
|
24
|
+
".webm",
|
|
25
|
+
".flv",
|
|
26
|
+
".wmv",
|
|
27
|
+
".mp3",
|
|
28
|
+
".wav",
|
|
29
|
+
".flac",
|
|
30
|
+
".ogg",
|
|
31
|
+
".m4a",
|
|
32
|
+
".aac",
|
|
33
|
+
".wma",
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
console = Console()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def find_media_files(directory: Path) -> list[Path]:
|
|
40
|
+
"""Find all supported media files in a directory (non-recursive)."""
|
|
41
|
+
return sorted(
|
|
42
|
+
f for f in directory.iterdir() if f.is_file() and f.suffix.lower() in MEDIA_EXTENSIONS
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def batch_transcribe(
|
|
47
|
+
directory: str | Path,
|
|
48
|
+
*,
|
|
49
|
+
output_dir: str | Path | None = None,
|
|
50
|
+
model_size: str = "base",
|
|
51
|
+
language: str | None = None,
|
|
52
|
+
translate: bool = False,
|
|
53
|
+
) -> list[dict[str, Path]]:
|
|
54
|
+
"""Transcribe all media files in a directory.
|
|
55
|
+
|
|
56
|
+
Returns:
|
|
57
|
+
List of dicts mapping format name to output file path.
|
|
58
|
+
"""
|
|
59
|
+
directory = Path(directory)
|
|
60
|
+
if not directory.is_dir():
|
|
61
|
+
raise NotADirectoryError(f"Not a directory: {directory}")
|
|
62
|
+
|
|
63
|
+
files = find_media_files(directory)
|
|
64
|
+
if not files:
|
|
65
|
+
console.print(f"[yellow]No media files found in {directory}[/yellow]")
|
|
66
|
+
return []
|
|
67
|
+
|
|
68
|
+
out = Path(output_dir) if output_dir else directory
|
|
69
|
+
results: list[dict[str, Path]] = []
|
|
70
|
+
|
|
71
|
+
with Progress(console=console) as progress:
|
|
72
|
+
task = progress.add_task("Transcribing...", total=len(files))
|
|
73
|
+
for media_file in files:
|
|
74
|
+
console.print(f" [cyan]{media_file.name}[/cyan]")
|
|
75
|
+
result = transcribe(
|
|
76
|
+
media_file,
|
|
77
|
+
model_size=model_size,
|
|
78
|
+
language=language,
|
|
79
|
+
translate=translate,
|
|
80
|
+
)
|
|
81
|
+
paths = write_all_formats(result, out, media_file.stem)
|
|
82
|
+
results.append(paths)
|
|
83
|
+
progress.advance(task)
|
|
84
|
+
|
|
85
|
+
return results
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def batch_burn(
|
|
89
|
+
directory: str | Path,
|
|
90
|
+
*,
|
|
91
|
+
output_dir: str | Path | None = None,
|
|
92
|
+
preset_name: str = "clean",
|
|
93
|
+
model_size: str = "base",
|
|
94
|
+
language: str | None = None,
|
|
95
|
+
translate: bool = False,
|
|
96
|
+
overwrite: bool = False,
|
|
97
|
+
) -> list[Path]:
|
|
98
|
+
"""Transcribe and burn captions for all video files in a directory.
|
|
99
|
+
|
|
100
|
+
Returns:
|
|
101
|
+
List of output video paths.
|
|
102
|
+
"""
|
|
103
|
+
directory = Path(directory)
|
|
104
|
+
if not directory.is_dir():
|
|
105
|
+
raise NotADirectoryError(f"Not a directory: {directory}")
|
|
106
|
+
|
|
107
|
+
video_exts = {".mp4", ".mkv", ".avi", ".mov", ".webm", ".flv", ".wmv"}
|
|
108
|
+
files = sorted(f for f in directory.iterdir() if f.is_file() and f.suffix.lower() in video_exts)
|
|
109
|
+
if not files:
|
|
110
|
+
console.print(f"[yellow]No video files found in {directory}[/yellow]")
|
|
111
|
+
return []
|
|
112
|
+
|
|
113
|
+
out = Path(output_dir) if output_dir else directory
|
|
114
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
115
|
+
preset = get_preset(preset_name)
|
|
116
|
+
outputs: list[Path] = []
|
|
117
|
+
|
|
118
|
+
with Progress(console=console) as progress:
|
|
119
|
+
task = progress.add_task("Burning captions...", total=len(files))
|
|
120
|
+
for video_file in files:
|
|
121
|
+
console.print(f" [cyan]{video_file.name}[/cyan]")
|
|
122
|
+
result = transcribe(
|
|
123
|
+
video_file,
|
|
124
|
+
model_size=model_size,
|
|
125
|
+
language=language,
|
|
126
|
+
translate=translate,
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
ass_path = out / f"{video_file.stem}.ass"
|
|
130
|
+
ass_content = _generate_ass(result, preset)
|
|
131
|
+
ass_path.write_text(ass_content, encoding="utf-8")
|
|
132
|
+
|
|
133
|
+
output_video = out / f"{video_file.stem}_captioned{video_file.suffix}"
|
|
134
|
+
burn_captions(video_file, ass_path, output_video, overwrite=overwrite)
|
|
135
|
+
outputs.append(output_video)
|
|
136
|
+
progress.advance(task)
|
|
137
|
+
|
|
138
|
+
return outputs
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _generate_ass(result: TranscriptionResult, preset: object) -> str:
|
|
142
|
+
"""Generate ASS content based on preset settings."""
|
|
143
|
+
from captionkit.burner import BurnPreset
|
|
144
|
+
|
|
145
|
+
if not isinstance(preset, BurnPreset):
|
|
146
|
+
raise TypeError("preset must be a BurnPreset")
|
|
147
|
+
|
|
148
|
+
if preset.karaoke:
|
|
149
|
+
return to_ass_karaoke(result, **preset_to_karaoke_kwargs(preset))
|
|
150
|
+
return to_ass(result, **preset_to_ass_kwargs(preset))
|
captionkit/burner.py
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
"""Burn captions into video using ffmpeg with ASS subtitles."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import shutil
|
|
6
|
+
import subprocess
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
FONT_FALLBACK_LIST = [
|
|
11
|
+
"Arial",
|
|
12
|
+
"Noto Sans",
|
|
13
|
+
"Noto Sans CJK SC",
|
|
14
|
+
"Noto Sans CJK TC",
|
|
15
|
+
"Noto Sans CJK JP",
|
|
16
|
+
"Noto Sans CJK KR",
|
|
17
|
+
"Noto Sans Arabic",
|
|
18
|
+
"Noto Sans Devanagari",
|
|
19
|
+
"Noto Sans Bengali",
|
|
20
|
+
"Noto Sans Thai",
|
|
21
|
+
"DejaVu Sans",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass
|
|
26
|
+
class BurnPreset:
|
|
27
|
+
"""A named preset for caption burning."""
|
|
28
|
+
|
|
29
|
+
name: str
|
|
30
|
+
font_name: str
|
|
31
|
+
font_size: int
|
|
32
|
+
primary_color: str
|
|
33
|
+
outline_color: str
|
|
34
|
+
back_color: str
|
|
35
|
+
alignment: int
|
|
36
|
+
margin_v: int
|
|
37
|
+
play_res_x: int
|
|
38
|
+
play_res_y: int
|
|
39
|
+
bold: bool
|
|
40
|
+
karaoke: bool
|
|
41
|
+
highlight_color: str
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
PRESETS: dict[str, BurnPreset] = {
|
|
45
|
+
"clean": BurnPreset(
|
|
46
|
+
name="clean",
|
|
47
|
+
font_name="Arial",
|
|
48
|
+
font_size=20,
|
|
49
|
+
primary_color="&H00FFFFFF",
|
|
50
|
+
outline_color="&H00000000",
|
|
51
|
+
back_color="&H80000000",
|
|
52
|
+
alignment=2,
|
|
53
|
+
margin_v=30,
|
|
54
|
+
play_res_x=1920,
|
|
55
|
+
play_res_y=1080,
|
|
56
|
+
bold=False,
|
|
57
|
+
karaoke=False,
|
|
58
|
+
highlight_color="&H00FFFFFF",
|
|
59
|
+
),
|
|
60
|
+
"minimal": BurnPreset(
|
|
61
|
+
name="minimal",
|
|
62
|
+
font_name="Arial",
|
|
63
|
+
font_size=18,
|
|
64
|
+
primary_color="&H00FFFFFF",
|
|
65
|
+
outline_color="&H40000000",
|
|
66
|
+
back_color="&H00000000",
|
|
67
|
+
alignment=2,
|
|
68
|
+
margin_v=20,
|
|
69
|
+
play_res_x=1920,
|
|
70
|
+
play_res_y=1080,
|
|
71
|
+
bold=False,
|
|
72
|
+
karaoke=False,
|
|
73
|
+
highlight_color="&H00FFFFFF",
|
|
74
|
+
),
|
|
75
|
+
"shorts": BurnPreset(
|
|
76
|
+
name="shorts",
|
|
77
|
+
font_name="Arial",
|
|
78
|
+
font_size=22,
|
|
79
|
+
primary_color="&H00FFFFFF",
|
|
80
|
+
outline_color="&H00000000",
|
|
81
|
+
back_color="&H80000000",
|
|
82
|
+
alignment=2,
|
|
83
|
+
margin_v=50,
|
|
84
|
+
play_res_x=1080,
|
|
85
|
+
play_res_y=1920,
|
|
86
|
+
bold=True,
|
|
87
|
+
karaoke=False,
|
|
88
|
+
highlight_color="&H00FFFFFF",
|
|
89
|
+
),
|
|
90
|
+
"shorts-karaoke": BurnPreset(
|
|
91
|
+
name="shorts-karaoke",
|
|
92
|
+
font_name="Arial",
|
|
93
|
+
font_size=24,
|
|
94
|
+
primary_color="&H00FFFFFF",
|
|
95
|
+
outline_color="&H00000000",
|
|
96
|
+
back_color="&H80000000",
|
|
97
|
+
alignment=2,
|
|
98
|
+
margin_v=60,
|
|
99
|
+
play_res_x=1080,
|
|
100
|
+
play_res_y=1920,
|
|
101
|
+
bold=True,
|
|
102
|
+
karaoke=True,
|
|
103
|
+
highlight_color="&H0000FFFF",
|
|
104
|
+
),
|
|
105
|
+
"reels": BurnPreset(
|
|
106
|
+
name="reels",
|
|
107
|
+
font_name="Arial",
|
|
108
|
+
font_size=22,
|
|
109
|
+
primary_color="&H00FFFFFF",
|
|
110
|
+
outline_color="&H00000000",
|
|
111
|
+
back_color="&H64000000",
|
|
112
|
+
alignment=2,
|
|
113
|
+
margin_v=55,
|
|
114
|
+
play_res_x=1080,
|
|
115
|
+
play_res_y=1920,
|
|
116
|
+
bold=True,
|
|
117
|
+
karaoke=False,
|
|
118
|
+
highlight_color="&H00FFFFFF",
|
|
119
|
+
),
|
|
120
|
+
"reels-karaoke": BurnPreset(
|
|
121
|
+
name="reels-karaoke",
|
|
122
|
+
font_name="Arial",
|
|
123
|
+
font_size=24,
|
|
124
|
+
primary_color="&H00FFFFFF",
|
|
125
|
+
outline_color="&H00000000",
|
|
126
|
+
back_color="&H64000000",
|
|
127
|
+
alignment=2,
|
|
128
|
+
margin_v=60,
|
|
129
|
+
play_res_x=1080,
|
|
130
|
+
play_res_y=1920,
|
|
131
|
+
bold=True,
|
|
132
|
+
karaoke=True,
|
|
133
|
+
highlight_color="&H0042D4FF",
|
|
134
|
+
),
|
|
135
|
+
"tiktok": BurnPreset(
|
|
136
|
+
name="tiktok",
|
|
137
|
+
font_name="Arial",
|
|
138
|
+
font_size=24,
|
|
139
|
+
primary_color="&H00FFFFFF",
|
|
140
|
+
outline_color="&H00000000",
|
|
141
|
+
back_color="&H80000000",
|
|
142
|
+
alignment=2,
|
|
143
|
+
margin_v=55,
|
|
144
|
+
play_res_x=1080,
|
|
145
|
+
play_res_y=1920,
|
|
146
|
+
bold=True,
|
|
147
|
+
karaoke=False,
|
|
148
|
+
highlight_color="&H00FFFFFF",
|
|
149
|
+
),
|
|
150
|
+
"tiktok-karaoke": BurnPreset(
|
|
151
|
+
name="tiktok-karaoke",
|
|
152
|
+
font_name="Arial",
|
|
153
|
+
font_size=26,
|
|
154
|
+
primary_color="&H00FFFFFF",
|
|
155
|
+
outline_color="&H00000000",
|
|
156
|
+
back_color="&H80000000",
|
|
157
|
+
alignment=2,
|
|
158
|
+
margin_v=60,
|
|
159
|
+
play_res_x=1080,
|
|
160
|
+
play_res_y=1920,
|
|
161
|
+
bold=True,
|
|
162
|
+
karaoke=True,
|
|
163
|
+
highlight_color="&H0000BFFF",
|
|
164
|
+
),
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _find_ffmpeg() -> str:
|
|
169
|
+
"""Locate the ffmpeg binary."""
|
|
170
|
+
path = shutil.which("ffmpeg")
|
|
171
|
+
if path is None:
|
|
172
|
+
raise RuntimeError("ffmpeg not found. Install it: https://ffmpeg.org/download.html")
|
|
173
|
+
return path
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _build_fontsdir_arg() -> list[str]:
|
|
177
|
+
"""Build fontsdir argument for ASS rendering if system fonts exist."""
|
|
178
|
+
for fonts_dir in ["/usr/share/fonts", "/usr/local/share/fonts", Path.home() / ".fonts"]:
|
|
179
|
+
if Path(fonts_dir).is_dir():
|
|
180
|
+
return [f"fontsdir={fonts_dir}"]
|
|
181
|
+
return []
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def burn_captions(
|
|
185
|
+
video_path: str | Path,
|
|
186
|
+
ass_path: str | Path,
|
|
187
|
+
output_path: str | Path | None = None,
|
|
188
|
+
*,
|
|
189
|
+
overwrite: bool = False,
|
|
190
|
+
) -> Path:
|
|
191
|
+
"""Burn ASS subtitles into a video file using ffmpeg.
|
|
192
|
+
|
|
193
|
+
Args:
|
|
194
|
+
video_path: Input video file.
|
|
195
|
+
ass_path: ASS subtitle file.
|
|
196
|
+
output_path: Output video file. Defaults to <stem>_captioned.<ext>.
|
|
197
|
+
overwrite: Whether to overwrite existing output.
|
|
198
|
+
|
|
199
|
+
Returns:
|
|
200
|
+
Path to the output video.
|
|
201
|
+
"""
|
|
202
|
+
video_path = Path(video_path)
|
|
203
|
+
ass_path = Path(ass_path)
|
|
204
|
+
|
|
205
|
+
if not video_path.exists():
|
|
206
|
+
raise FileNotFoundError(f"Video not found: {video_path}")
|
|
207
|
+
if not ass_path.exists():
|
|
208
|
+
raise FileNotFoundError(f"ASS file not found: {ass_path}")
|
|
209
|
+
|
|
210
|
+
if output_path is None:
|
|
211
|
+
output_path = video_path.parent / f"{video_path.stem}_captioned{video_path.suffix}"
|
|
212
|
+
output_path = Path(output_path)
|
|
213
|
+
|
|
214
|
+
if output_path.exists() and not overwrite:
|
|
215
|
+
raise FileExistsError(f"Output already exists: {output_path}. Use --overwrite to replace.")
|
|
216
|
+
|
|
217
|
+
ffmpeg = _find_ffmpeg()
|
|
218
|
+
|
|
219
|
+
ass_escaped = str(ass_path).replace(":", r"\:").replace("'", r"\'")
|
|
220
|
+
fontsdir = _build_fontsdir_arg()
|
|
221
|
+
subtitles_filter = f"ass={ass_escaped}"
|
|
222
|
+
if fontsdir:
|
|
223
|
+
subtitles_filter += f":{fontsdir[0]}"
|
|
224
|
+
|
|
225
|
+
cmd = [
|
|
226
|
+
ffmpeg,
|
|
227
|
+
"-y" if overwrite else "-n",
|
|
228
|
+
"-i",
|
|
229
|
+
str(video_path),
|
|
230
|
+
"-vf",
|
|
231
|
+
subtitles_filter,
|
|
232
|
+
"-c:a",
|
|
233
|
+
"copy",
|
|
234
|
+
str(output_path),
|
|
235
|
+
]
|
|
236
|
+
|
|
237
|
+
result = subprocess.run(cmd, capture_output=True, text=True)
|
|
238
|
+
if result.returncode != 0:
|
|
239
|
+
raise RuntimeError(f"ffmpeg failed:\n{result.stderr}")
|
|
240
|
+
|
|
241
|
+
return output_path
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def get_preset(name: str) -> BurnPreset:
|
|
245
|
+
"""Get a burn preset by name. Raises KeyError if not found."""
|
|
246
|
+
if name not in PRESETS:
|
|
247
|
+
available = ", ".join(sorted(PRESETS.keys()))
|
|
248
|
+
raise KeyError(f"Unknown preset '{name}'. Available: {available}")
|
|
249
|
+
return PRESETS[name]
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def preset_to_ass_kwargs(preset: BurnPreset) -> dict:
|
|
253
|
+
"""Convert a BurnPreset to kwargs for the ASS formatter."""
|
|
254
|
+
return {
|
|
255
|
+
"font_name": preset.font_name,
|
|
256
|
+
"font_size": preset.font_size,
|
|
257
|
+
"primary_color": preset.primary_color,
|
|
258
|
+
"outline_color": preset.outline_color,
|
|
259
|
+
"back_color": preset.back_color,
|
|
260
|
+
"alignment": preset.alignment,
|
|
261
|
+
"margin_v": preset.margin_v,
|
|
262
|
+
"play_res_x": preset.play_res_x,
|
|
263
|
+
"play_res_y": preset.play_res_y,
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def preset_to_karaoke_kwargs(preset: BurnPreset) -> dict:
|
|
268
|
+
"""Convert a BurnPreset to kwargs for the karaoke ASS formatter."""
|
|
269
|
+
return {
|
|
270
|
+
"font_name": preset.font_name,
|
|
271
|
+
"font_size": preset.font_size,
|
|
272
|
+
"primary_color": preset.primary_color,
|
|
273
|
+
"highlight_color": preset.highlight_color,
|
|
274
|
+
"outline_color": preset.outline_color,
|
|
275
|
+
"back_color": preset.back_color,
|
|
276
|
+
"alignment": preset.alignment,
|
|
277
|
+
"margin_v": preset.margin_v,
|
|
278
|
+
"play_res_x": preset.play_res_x,
|
|
279
|
+
"play_res_y": preset.play_res_y,
|
|
280
|
+
}
|
captionkit/cli.py
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
"""CaptionKit CLI — accurate captions from your own machine."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import click
|
|
8
|
+
from rich.console import Console
|
|
9
|
+
from rich.table import Table
|
|
10
|
+
|
|
11
|
+
from captionkit import __version__
|
|
12
|
+
from captionkit.burner import (
|
|
13
|
+
PRESETS,
|
|
14
|
+
burn_captions,
|
|
15
|
+
get_preset,
|
|
16
|
+
preset_to_ass_kwargs,
|
|
17
|
+
preset_to_karaoke_kwargs,
|
|
18
|
+
)
|
|
19
|
+
from captionkit.formatter import to_ass, to_ass_karaoke, write_all_formats
|
|
20
|
+
from captionkit.transcriber import transcribe
|
|
21
|
+
|
|
22
|
+
console = Console()
|
|
23
|
+
|
|
24
|
+
MODEL_SIZES = ["tiny", "base", "small", "medium", "large-v3"]
|
|
25
|
+
PRESET_NAMES = list(PRESETS.keys())
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@click.group()
|
|
29
|
+
@click.version_option(version=__version__, prog_name="captionkit")
|
|
30
|
+
def main() -> None:
|
|
31
|
+
"""CaptionKit — local-first video & audio captioning powered by Whisper.
|
|
32
|
+
|
|
33
|
+
Accurate captions in 90+ languages. No cloud. No paid APIs.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@main.command(name="transcribe")
|
|
38
|
+
@click.argument("file", type=click.Path(exists=True, path_type=Path))
|
|
39
|
+
@click.option(
|
|
40
|
+
"-m",
|
|
41
|
+
"--model",
|
|
42
|
+
"model_size",
|
|
43
|
+
default="base",
|
|
44
|
+
type=click.Choice(MODEL_SIZES),
|
|
45
|
+
help="Whisper model size.",
|
|
46
|
+
)
|
|
47
|
+
@click.option("-l", "--language", default=None, help="Language code (auto-detect if omitted).")
|
|
48
|
+
@click.option("--translate", is_flag=True, help="Translate output to English.")
|
|
49
|
+
@click.option(
|
|
50
|
+
"-o",
|
|
51
|
+
"--output-dir",
|
|
52
|
+
default=None,
|
|
53
|
+
type=click.Path(path_type=Path),
|
|
54
|
+
help="Output directory (default: same as input).",
|
|
55
|
+
)
|
|
56
|
+
@click.option("--device", default=None, help="Compute device: cpu, cuda.")
|
|
57
|
+
def transcribe_cmd(
|
|
58
|
+
file: Path,
|
|
59
|
+
model_size: str,
|
|
60
|
+
language: str | None,
|
|
61
|
+
translate: bool,
|
|
62
|
+
output_dir: Path | None,
|
|
63
|
+
device: str | None,
|
|
64
|
+
) -> None:
|
|
65
|
+
"""Transcribe a video or audio file to SRT, VTT, ASS, and JSON."""
|
|
66
|
+
console.print(f"[bold green]CaptionKit[/bold green] v{__version__}")
|
|
67
|
+
console.print(f"Transcribing: [cyan]{file.name}[/cyan]")
|
|
68
|
+
console.print(f"Model: [yellow]{model_size}[/yellow] Device: {device or 'auto'}")
|
|
69
|
+
|
|
70
|
+
result = transcribe(
|
|
71
|
+
file,
|
|
72
|
+
model_size=model_size,
|
|
73
|
+
language=language,
|
|
74
|
+
translate=translate,
|
|
75
|
+
device=device,
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
out = output_dir or file.parent
|
|
79
|
+
paths = write_all_formats(result, out, file.stem)
|
|
80
|
+
|
|
81
|
+
console.print()
|
|
82
|
+
console.print(
|
|
83
|
+
f"[green]✓[/green] Language: {result.language} ({result.language_probability:.0%})"
|
|
84
|
+
)
|
|
85
|
+
console.print(f"[green]✓[/green] Segments: {len(result.segments)}")
|
|
86
|
+
|
|
87
|
+
table = Table(title="Output Files")
|
|
88
|
+
table.add_column("Format", style="cyan")
|
|
89
|
+
table.add_column("Path")
|
|
90
|
+
for fmt, path in paths.items():
|
|
91
|
+
table.add_row(fmt.upper(), str(path))
|
|
92
|
+
console.print(table)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@main.command()
|
|
96
|
+
@click.argument("file", type=click.Path(exists=True, path_type=Path))
|
|
97
|
+
@click.option(
|
|
98
|
+
"-m",
|
|
99
|
+
"--model",
|
|
100
|
+
"model_size",
|
|
101
|
+
default="base",
|
|
102
|
+
type=click.Choice(MODEL_SIZES),
|
|
103
|
+
help="Whisper model size.",
|
|
104
|
+
)
|
|
105
|
+
@click.option("-l", "--language", default=None, help="Language code (auto-detect if omitted).")
|
|
106
|
+
@click.option("--translate", is_flag=True, help="Translate output to English.")
|
|
107
|
+
@click.option(
|
|
108
|
+
"-p",
|
|
109
|
+
"--preset",
|
|
110
|
+
"preset_name",
|
|
111
|
+
default="clean",
|
|
112
|
+
type=click.Choice(PRESET_NAMES),
|
|
113
|
+
help="Burn style preset.",
|
|
114
|
+
)
|
|
115
|
+
@click.option(
|
|
116
|
+
"-o",
|
|
117
|
+
"--output",
|
|
118
|
+
"output_path",
|
|
119
|
+
default=None,
|
|
120
|
+
type=click.Path(path_type=Path),
|
|
121
|
+
help="Output video path.",
|
|
122
|
+
)
|
|
123
|
+
@click.option("--font", default=None, help="Override font name.")
|
|
124
|
+
@click.option("--font-size", default=None, type=int, help="Override font size.")
|
|
125
|
+
@click.option("--color", default=None, help="Primary color in ASS hex (e.g. &H00FFFFFF).")
|
|
126
|
+
@click.option(
|
|
127
|
+
"--position",
|
|
128
|
+
default=None,
|
|
129
|
+
type=click.Choice(["top", "center", "bottom"]),
|
|
130
|
+
help="Caption vertical position.",
|
|
131
|
+
)
|
|
132
|
+
@click.option("--max-chars", default=None, type=int, help="Max characters per line.")
|
|
133
|
+
@click.option("--overwrite", is_flag=True, help="Overwrite existing output.")
|
|
134
|
+
@click.option("--device", default=None, help="Compute device: cpu, cuda.")
|
|
135
|
+
def burn(
|
|
136
|
+
file: Path,
|
|
137
|
+
model_size: str,
|
|
138
|
+
language: str | None,
|
|
139
|
+
translate: bool,
|
|
140
|
+
preset_name: str,
|
|
141
|
+
output_path: Path | None,
|
|
142
|
+
font: str | None,
|
|
143
|
+
font_size: int | None,
|
|
144
|
+
color: str | None,
|
|
145
|
+
position: str | None,
|
|
146
|
+
max_chars: int | None,
|
|
147
|
+
overwrite: bool,
|
|
148
|
+
device: str | None,
|
|
149
|
+
) -> None:
|
|
150
|
+
"""Burn styled captions into a video file."""
|
|
151
|
+
console.print(f"[bold green]CaptionKit[/bold green] v{__version__}")
|
|
152
|
+
console.print(f"Input: [cyan]{file.name}[/cyan] Preset: [yellow]{preset_name}[/yellow]")
|
|
153
|
+
|
|
154
|
+
result = transcribe(
|
|
155
|
+
file,
|
|
156
|
+
model_size=model_size,
|
|
157
|
+
language=language,
|
|
158
|
+
translate=translate,
|
|
159
|
+
device=device,
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
if max_chars:
|
|
163
|
+
_wrap_segments(result, max_chars)
|
|
164
|
+
|
|
165
|
+
preset = get_preset(preset_name)
|
|
166
|
+
if preset.karaoke:
|
|
167
|
+
ass_kwargs = preset_to_karaoke_kwargs(preset)
|
|
168
|
+
else:
|
|
169
|
+
ass_kwargs = preset_to_ass_kwargs(preset)
|
|
170
|
+
|
|
171
|
+
if font:
|
|
172
|
+
ass_kwargs["font_name"] = font
|
|
173
|
+
if font_size:
|
|
174
|
+
ass_kwargs["font_size"] = font_size
|
|
175
|
+
if color:
|
|
176
|
+
ass_kwargs["primary_color"] = color
|
|
177
|
+
if position:
|
|
178
|
+
alignment_map = {"top": 8, "center": 5, "bottom": 2}
|
|
179
|
+
ass_kwargs["alignment"] = alignment_map[position]
|
|
180
|
+
|
|
181
|
+
if preset.karaoke:
|
|
182
|
+
ass_content = to_ass_karaoke(result, **ass_kwargs)
|
|
183
|
+
else:
|
|
184
|
+
ass_content = to_ass(result, **ass_kwargs)
|
|
185
|
+
|
|
186
|
+
ass_path = file.parent / f"{file.stem}_burn.ass"
|
|
187
|
+
ass_path.write_text(ass_content, encoding="utf-8")
|
|
188
|
+
|
|
189
|
+
out = burn_captions(file, ass_path, output_path, overwrite=overwrite)
|
|
190
|
+
ass_path.unlink(missing_ok=True)
|
|
191
|
+
|
|
192
|
+
console.print(f"\n[green]✓[/green] Captioned video: [bold]{out}[/bold]")
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
@main.command()
|
|
196
|
+
@click.argument("directory", type=click.Path(exists=True, file_okay=False, path_type=Path))
|
|
197
|
+
@click.option(
|
|
198
|
+
"--mode",
|
|
199
|
+
type=click.Choice(["transcribe", "burn"]),
|
|
200
|
+
default="transcribe",
|
|
201
|
+
help="Batch operation mode.",
|
|
202
|
+
)
|
|
203
|
+
@click.option(
|
|
204
|
+
"-m",
|
|
205
|
+
"--model",
|
|
206
|
+
"model_size",
|
|
207
|
+
default="base",
|
|
208
|
+
type=click.Choice(MODEL_SIZES),
|
|
209
|
+
help="Whisper model size.",
|
|
210
|
+
)
|
|
211
|
+
@click.option("-l", "--language", default=None, help="Language code.")
|
|
212
|
+
@click.option("--translate", is_flag=True, help="Translate to English.")
|
|
213
|
+
@click.option(
|
|
214
|
+
"-p",
|
|
215
|
+
"--preset",
|
|
216
|
+
"preset_name",
|
|
217
|
+
default="clean",
|
|
218
|
+
type=click.Choice(PRESET_NAMES),
|
|
219
|
+
help="Burn preset (burn mode only).",
|
|
220
|
+
)
|
|
221
|
+
@click.option(
|
|
222
|
+
"-o", "--output-dir", default=None, type=click.Path(path_type=Path), help="Output directory."
|
|
223
|
+
)
|
|
224
|
+
@click.option("--overwrite", is_flag=True, help="Overwrite existing files.")
|
|
225
|
+
def batch(
|
|
226
|
+
directory: Path,
|
|
227
|
+
mode: str,
|
|
228
|
+
model_size: str,
|
|
229
|
+
language: str | None,
|
|
230
|
+
translate: bool,
|
|
231
|
+
preset_name: str,
|
|
232
|
+
output_dir: Path | None,
|
|
233
|
+
overwrite: bool,
|
|
234
|
+
) -> None:
|
|
235
|
+
"""Process all media files in a folder."""
|
|
236
|
+
console.print(f"[bold green]CaptionKit[/bold green] v{__version__} — Batch Mode")
|
|
237
|
+
console.print(f"Directory: [cyan]{directory}[/cyan] Mode: [yellow]{mode}[/yellow]")
|
|
238
|
+
|
|
239
|
+
from captionkit.batch import batch_burn, batch_transcribe
|
|
240
|
+
|
|
241
|
+
if mode == "transcribe":
|
|
242
|
+
results = batch_transcribe(
|
|
243
|
+
directory,
|
|
244
|
+
output_dir=output_dir,
|
|
245
|
+
model_size=model_size,
|
|
246
|
+
language=language,
|
|
247
|
+
translate=translate,
|
|
248
|
+
)
|
|
249
|
+
console.print(f"\n[green]✓[/green] Transcribed {len(results)} file(s)")
|
|
250
|
+
else:
|
|
251
|
+
outputs = batch_burn(
|
|
252
|
+
directory,
|
|
253
|
+
output_dir=output_dir,
|
|
254
|
+
preset_name=preset_name,
|
|
255
|
+
model_size=model_size,
|
|
256
|
+
language=language,
|
|
257
|
+
translate=translate,
|
|
258
|
+
overwrite=overwrite,
|
|
259
|
+
)
|
|
260
|
+
console.print(f"\n[green]✓[/green] Burned captions into {len(outputs)} video(s)")
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
@main.command(name="presets")
|
|
264
|
+
def list_presets() -> None:
|
|
265
|
+
"""Show available burn presets."""
|
|
266
|
+
table = Table(title="Burn Presets")
|
|
267
|
+
table.add_column("Name", style="cyan")
|
|
268
|
+
table.add_column("Resolution")
|
|
269
|
+
table.add_column("Font Size")
|
|
270
|
+
table.add_column("Karaoke")
|
|
271
|
+
table.add_column("Description")
|
|
272
|
+
|
|
273
|
+
descriptions = {
|
|
274
|
+
"clean": "Clean captions for landscape 16:9 video",
|
|
275
|
+
"minimal": "Minimal, low-profile captions for 16:9",
|
|
276
|
+
"shorts": "YouTube Shorts 9:16 portrait",
|
|
277
|
+
"shorts-karaoke": "YouTube Shorts 9:16 word-by-word highlight",
|
|
278
|
+
"reels": "Instagram Reels 9:16 portrait",
|
|
279
|
+
"reels-karaoke": "Instagram Reels 9:16 word-by-word highlight",
|
|
280
|
+
"tiktok": "TikTok 9:16 portrait",
|
|
281
|
+
"tiktok-karaoke": "TikTok 9:16 word-by-word highlight",
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
for name, preset in PRESETS.items():
|
|
285
|
+
table.add_row(
|
|
286
|
+
name,
|
|
287
|
+
f"{preset.play_res_x}x{preset.play_res_y}",
|
|
288
|
+
str(preset.font_size),
|
|
289
|
+
"✓" if preset.karaoke else "",
|
|
290
|
+
descriptions.get(name, ""),
|
|
291
|
+
)
|
|
292
|
+
console.print(table)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def _wrap_segments(result: object, max_chars: int) -> None:
|
|
296
|
+
"""Wrap segment text to max_chars per line."""
|
|
297
|
+
from captionkit.transcriber import TranscriptionResult
|
|
298
|
+
|
|
299
|
+
if not isinstance(result, TranscriptionResult):
|
|
300
|
+
return
|
|
301
|
+
for seg in result.segments:
|
|
302
|
+
if len(seg.text) <= max_chars:
|
|
303
|
+
continue
|
|
304
|
+
words = seg.text.split()
|
|
305
|
+
lines: list[str] = []
|
|
306
|
+
current_line = ""
|
|
307
|
+
for word in words:
|
|
308
|
+
test = f"{current_line} {word}".strip()
|
|
309
|
+
if len(test) <= max_chars:
|
|
310
|
+
current_line = test
|
|
311
|
+
else:
|
|
312
|
+
if current_line:
|
|
313
|
+
lines.append(current_line)
|
|
314
|
+
current_line = word
|
|
315
|
+
if current_line:
|
|
316
|
+
lines.append(current_line)
|
|
317
|
+
seg.text = "\n".join(lines)
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
if __name__ == "__main__":
|
|
321
|
+
main()
|
captionkit/formatter.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""Output formatters: SRT, VTT, ASS, JSON."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from dataclasses import asdict
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import TYPE_CHECKING
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from captionkit.transcriber import TranscriptionResult
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _ts_srt(seconds: float) -> str:
|
|
15
|
+
"""Format seconds as SRT timestamp: HH:MM:SS,mmm"""
|
|
16
|
+
h = int(seconds // 3600)
|
|
17
|
+
m = int((seconds % 3600) // 60)
|
|
18
|
+
s = int(seconds % 60)
|
|
19
|
+
ms = round((seconds - int(seconds)) * 1000)
|
|
20
|
+
return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _ts_vtt(seconds: float) -> str:
|
|
24
|
+
"""Format seconds as VTT timestamp: HH:MM:SS.mmm"""
|
|
25
|
+
h = int(seconds // 3600)
|
|
26
|
+
m = int((seconds % 3600) // 60)
|
|
27
|
+
s = int(seconds % 60)
|
|
28
|
+
ms = round((seconds - int(seconds)) * 1000)
|
|
29
|
+
return f"{h:02d}:{m:02d}:{s:02d}.{ms:03d}"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _ts_ass(seconds: float) -> str:
|
|
33
|
+
"""Format seconds as ASS timestamp: H:MM:SS.cc"""
|
|
34
|
+
h = int(seconds // 3600)
|
|
35
|
+
m = int((seconds % 3600) // 60)
|
|
36
|
+
s = int(seconds % 60)
|
|
37
|
+
cs = round((seconds - int(seconds)) * 100)
|
|
38
|
+
return f"{h}:{m:02d}:{s:02d}.{cs:02d}"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def to_srt(result: TranscriptionResult) -> str:
|
|
42
|
+
"""Convert transcription result to SRT format."""
|
|
43
|
+
lines: list[str] = []
|
|
44
|
+
for seg in result.segments:
|
|
45
|
+
lines.append(str(seg.id))
|
|
46
|
+
lines.append(f"{_ts_srt(seg.start)} --> {_ts_srt(seg.end)}")
|
|
47
|
+
lines.append(seg.text)
|
|
48
|
+
lines.append("")
|
|
49
|
+
return "\n".join(lines)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def to_vtt(result: TranscriptionResult) -> str:
|
|
53
|
+
"""Convert transcription result to WebVTT format."""
|
|
54
|
+
lines: list[str] = ["WEBVTT", ""]
|
|
55
|
+
for seg in result.segments:
|
|
56
|
+
lines.append(str(seg.id))
|
|
57
|
+
lines.append(f"{_ts_vtt(seg.start)} --> {_ts_vtt(seg.end)}")
|
|
58
|
+
lines.append(seg.text)
|
|
59
|
+
lines.append("")
|
|
60
|
+
return "\n".join(lines)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def to_ass(
|
|
64
|
+
result: TranscriptionResult,
|
|
65
|
+
*,
|
|
66
|
+
font_name: str = "Arial",
|
|
67
|
+
font_size: int = 20,
|
|
68
|
+
primary_color: str = "&H00FFFFFF",
|
|
69
|
+
outline_color: str = "&H00000000",
|
|
70
|
+
back_color: str = "&H80000000",
|
|
71
|
+
alignment: int = 2,
|
|
72
|
+
margin_v: int = 30,
|
|
73
|
+
play_res_x: int = 1920,
|
|
74
|
+
play_res_y: int = 1080,
|
|
75
|
+
) -> str:
|
|
76
|
+
"""Convert transcription result to ASS (Advanced SubStation Alpha) format."""
|
|
77
|
+
header = f"""[Script Info]
|
|
78
|
+
Title: CaptionKit
|
|
79
|
+
ScriptType: v4.00+
|
|
80
|
+
PlayResX: {play_res_x}
|
|
81
|
+
PlayResY: {play_res_y}
|
|
82
|
+
WrapStyle: 0
|
|
83
|
+
|
|
84
|
+
[V4+ Styles]
|
|
85
|
+
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
|
|
86
|
+
Style: Default,{font_name},{font_size},{primary_color},&H000000FF,{outline_color},{back_color},-1,0,0,0,100,100,0,0,1,2,1,{alignment},10,10,{margin_v},1
|
|
87
|
+
|
|
88
|
+
[Events]
|
|
89
|
+
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text"""
|
|
90
|
+
|
|
91
|
+
events: list[str] = []
|
|
92
|
+
for seg in result.segments:
|
|
93
|
+
text = seg.text.replace("\n", "\\N")
|
|
94
|
+
events.append(f"Dialogue: 0,{_ts_ass(seg.start)},{_ts_ass(seg.end)},Default,,0,0,0,,{text}")
|
|
95
|
+
|
|
96
|
+
return header + "\n" + "\n".join(events) + "\n"
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def to_ass_karaoke(
|
|
100
|
+
result: TranscriptionResult,
|
|
101
|
+
*,
|
|
102
|
+
font_name: str = "Arial",
|
|
103
|
+
font_size: int = 24,
|
|
104
|
+
primary_color: str = "&H00FFFFFF",
|
|
105
|
+
highlight_color: str = "&H0000FFFF",
|
|
106
|
+
outline_color: str = "&H00000000",
|
|
107
|
+
back_color: str = "&H80000000",
|
|
108
|
+
alignment: int = 2,
|
|
109
|
+
margin_v: int = 60,
|
|
110
|
+
play_res_x: int = 1080,
|
|
111
|
+
play_res_y: int = 1920,
|
|
112
|
+
) -> str:
|
|
113
|
+
"""Generate ASS with word-by-word karaoke highlighting for Shorts/Reels."""
|
|
114
|
+
header = f"""[Script Info]
|
|
115
|
+
Title: CaptionKit Karaoke
|
|
116
|
+
ScriptType: v4.00+
|
|
117
|
+
PlayResX: {play_res_x}
|
|
118
|
+
PlayResY: {play_res_y}
|
|
119
|
+
WrapStyle: 0
|
|
120
|
+
|
|
121
|
+
[V4+ Styles]
|
|
122
|
+
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
|
|
123
|
+
Style: Default,{font_name},{font_size},{primary_color},&H000000FF,{outline_color},{back_color},-1,0,0,0,100,100,0,0,1,2,1,{alignment},10,10,{margin_v},1
|
|
124
|
+
Style: Highlight,{font_name},{font_size},{highlight_color},&H000000FF,{outline_color},{back_color},-1,0,0,0,100,100,0,0,1,2,1,{alignment},10,10,{margin_v},1
|
|
125
|
+
|
|
126
|
+
[Events]
|
|
127
|
+
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text"""
|
|
128
|
+
|
|
129
|
+
events: list[str] = []
|
|
130
|
+
for seg in result.segments:
|
|
131
|
+
if not seg.words:
|
|
132
|
+
text = seg.text.replace("\n", "\\N")
|
|
133
|
+
events.append(
|
|
134
|
+
f"Dialogue: 0,{_ts_ass(seg.start)},{_ts_ass(seg.end)},Default,,0,0,0,,{text}"
|
|
135
|
+
)
|
|
136
|
+
continue
|
|
137
|
+
|
|
138
|
+
for i, word in enumerate(seg.words):
|
|
139
|
+
parts: list[str] = []
|
|
140
|
+
for j, w in enumerate(seg.words):
|
|
141
|
+
if j == i:
|
|
142
|
+
parts.append(r"{\rHighlight}" + w.word + r"{\rDefault}")
|
|
143
|
+
else:
|
|
144
|
+
parts.append(w.word)
|
|
145
|
+
line = " ".join(parts)
|
|
146
|
+
events.append(
|
|
147
|
+
f"Dialogue: 0,{_ts_ass(word.start)},{_ts_ass(word.end)},Default,,0,0,0,,{line}"
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
return header + "\n" + "\n".join(events) + "\n"
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def to_json(result: TranscriptionResult) -> str:
|
|
154
|
+
"""Convert transcription result to JSON."""
|
|
155
|
+
return json.dumps(asdict(result), indent=2, ensure_ascii=False)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def write_all_formats(
|
|
159
|
+
result: TranscriptionResult,
|
|
160
|
+
output_dir: Path,
|
|
161
|
+
stem: str,
|
|
162
|
+
*,
|
|
163
|
+
karaoke: bool = False,
|
|
164
|
+
ass_kwargs: dict | None = None,
|
|
165
|
+
) -> dict[str, Path]:
|
|
166
|
+
"""Write SRT, VTT, ASS, and JSON files. Returns dict of format->path."""
|
|
167
|
+
output_dir.mkdir(parents=True, exist_ok=True)
|
|
168
|
+
ass_kwargs = ass_kwargs or {}
|
|
169
|
+
|
|
170
|
+
paths: dict[str, Path] = {}
|
|
171
|
+
|
|
172
|
+
srt_path = output_dir / f"{stem}.srt"
|
|
173
|
+
srt_path.write_text(to_srt(result), encoding="utf-8")
|
|
174
|
+
paths["srt"] = srt_path
|
|
175
|
+
|
|
176
|
+
vtt_path = output_dir / f"{stem}.vtt"
|
|
177
|
+
vtt_path.write_text(to_vtt(result), encoding="utf-8")
|
|
178
|
+
paths["vtt"] = vtt_path
|
|
179
|
+
|
|
180
|
+
ass_path = output_dir / f"{stem}.ass"
|
|
181
|
+
if karaoke:
|
|
182
|
+
ass_path.write_text(to_ass_karaoke(result, **ass_kwargs), encoding="utf-8")
|
|
183
|
+
else:
|
|
184
|
+
ass_path.write_text(to_ass(result, **ass_kwargs), encoding="utf-8")
|
|
185
|
+
paths["ass"] = ass_path
|
|
186
|
+
|
|
187
|
+
json_path = output_dir / f"{stem}.json"
|
|
188
|
+
json_path.write_text(to_json(result), encoding="utf-8")
|
|
189
|
+
paths["json"] = json_path
|
|
190
|
+
|
|
191
|
+
return paths
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Transcription engine backed by faster-whisper."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from faster_whisper import WhisperModel
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class WordSegment:
|
|
14
|
+
"""A single word with its timing."""
|
|
15
|
+
|
|
16
|
+
word: str
|
|
17
|
+
start: float
|
|
18
|
+
end: float
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class Segment:
|
|
23
|
+
"""A subtitle segment (one or more sentences)."""
|
|
24
|
+
|
|
25
|
+
id: int
|
|
26
|
+
start: float
|
|
27
|
+
end: float
|
|
28
|
+
text: str
|
|
29
|
+
words: list[WordSegment] = field(default_factory=list)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass
|
|
33
|
+
class TranscriptionResult:
|
|
34
|
+
"""Full transcription output."""
|
|
35
|
+
|
|
36
|
+
language: str
|
|
37
|
+
language_probability: float
|
|
38
|
+
segments: list[Segment]
|
|
39
|
+
duration: float = 0.0
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _pick_device() -> tuple[str, str]:
|
|
43
|
+
"""Auto-detect the best available compute device."""
|
|
44
|
+
device = os.environ.get("CAPTIONKIT_DEVICE", "").lower()
|
|
45
|
+
if device:
|
|
46
|
+
if device == "cuda":
|
|
47
|
+
return "cuda", "float16"
|
|
48
|
+
if device in ("mps", "apple"):
|
|
49
|
+
return "cpu", "int8"
|
|
50
|
+
return "cpu", "int8"
|
|
51
|
+
|
|
52
|
+
try:
|
|
53
|
+
import torch
|
|
54
|
+
|
|
55
|
+
if torch.cuda.is_available():
|
|
56
|
+
return "cuda", "float16"
|
|
57
|
+
except ImportError:
|
|
58
|
+
pass
|
|
59
|
+
|
|
60
|
+
return "cpu", "int8"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def transcribe(
|
|
64
|
+
file_path: str | Path,
|
|
65
|
+
*,
|
|
66
|
+
model_size: str = "base",
|
|
67
|
+
language: str | None = None,
|
|
68
|
+
translate: bool = False,
|
|
69
|
+
device: str | None = None,
|
|
70
|
+
compute_type: str | None = None,
|
|
71
|
+
word_timestamps: bool = True,
|
|
72
|
+
) -> TranscriptionResult:
|
|
73
|
+
"""Transcribe an audio or video file using faster-whisper.
|
|
74
|
+
|
|
75
|
+
Args:
|
|
76
|
+
file_path: Path to the media file.
|
|
77
|
+
model_size: Whisper model size (tiny, base, small, medium, large-v3).
|
|
78
|
+
language: ISO 639-1 language code, or None for auto-detect.
|
|
79
|
+
translate: If True, translate output to English.
|
|
80
|
+
device: Compute device override (cpu, cuda).
|
|
81
|
+
compute_type: Compute type override (int8, float16, float32).
|
|
82
|
+
word_timestamps: Whether to include word-level timestamps.
|
|
83
|
+
|
|
84
|
+
Returns:
|
|
85
|
+
TranscriptionResult with segments and detected language.
|
|
86
|
+
"""
|
|
87
|
+
file_path = Path(file_path)
|
|
88
|
+
if not file_path.exists():
|
|
89
|
+
raise FileNotFoundError(f"File not found: {file_path}")
|
|
90
|
+
|
|
91
|
+
if device is None or compute_type is None:
|
|
92
|
+
auto_device, auto_ct = _pick_device()
|
|
93
|
+
device = device or auto_device
|
|
94
|
+
compute_type = compute_type or auto_ct
|
|
95
|
+
|
|
96
|
+
model = WhisperModel(model_size, device=device, compute_type=compute_type)
|
|
97
|
+
|
|
98
|
+
task = "translate" if translate else "transcribe"
|
|
99
|
+
|
|
100
|
+
segments_gen, info = model.transcribe(
|
|
101
|
+
str(file_path),
|
|
102
|
+
language=language,
|
|
103
|
+
task=task,
|
|
104
|
+
word_timestamps=word_timestamps,
|
|
105
|
+
vad_filter=True,
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
segments: list[Segment] = []
|
|
109
|
+
for idx, seg in enumerate(segments_gen, start=1):
|
|
110
|
+
words = []
|
|
111
|
+
if seg.words:
|
|
112
|
+
words = [WordSegment(word=w.word.strip(), start=w.start, end=w.end) for w in seg.words]
|
|
113
|
+
|
|
114
|
+
segments.append(
|
|
115
|
+
Segment(
|
|
116
|
+
id=idx,
|
|
117
|
+
start=seg.start,
|
|
118
|
+
end=seg.end,
|
|
119
|
+
text=seg.text.strip(),
|
|
120
|
+
words=words,
|
|
121
|
+
)
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
return TranscriptionResult(
|
|
125
|
+
language=info.language,
|
|
126
|
+
language_probability=info.language_probability,
|
|
127
|
+
segments=segments,
|
|
128
|
+
duration=info.duration,
|
|
129
|
+
)
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: captionkit
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Local-first CLI that makes accurate captions for any video or audio in 90+ languages with Whisper — no cloud, no paid APIs.
|
|
5
|
+
Project-URL: Homepage, https://github.com/abubakar60675/captionkit
|
|
6
|
+
Project-URL: Repository, https://github.com/abubakar60675/captionkit
|
|
7
|
+
Project-URL: Issues, https://github.com/abubakar60675/captionkit/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/abubakar60675/captionkit/blob/main/CHANGELOG.md
|
|
9
|
+
Author: Muhammad Abubakar
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: accessibility,ass,audio,captions,srt,subtitles,transcription,video,vtt,whisper
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Environment :: Console
|
|
15
|
+
Classifier: Intended Audience :: End Users/Desktop
|
|
16
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
|
|
24
|
+
Classifier: Topic :: Multimedia :: Video
|
|
25
|
+
Requires-Python: >=3.10
|
|
26
|
+
Requires-Dist: click>=8.1
|
|
27
|
+
Requires-Dist: faster-whisper>=1.0.0
|
|
28
|
+
Requires-Dist: rich>=13.0
|
|
29
|
+
Provides-Extra: dev
|
|
30
|
+
Requires-Dist: pytest-cov>=4.0; extra == 'dev'
|
|
31
|
+
Requires-Dist: pytest>=7.0; extra == 'dev'
|
|
32
|
+
Requires-Dist: ruff>=0.4; extra == 'dev'
|
|
33
|
+
Description-Content-Type: text/markdown
|
|
34
|
+
|
|
35
|
+
# CaptionKit
|
|
36
|
+
|
|
37
|
+
**Local-first CLI that makes accurate captions for any video or audio in 90+ languages with Whisper — no cloud, no paid APIs.**
|
|
38
|
+
|
|
39
|
+
CaptionKit runs entirely on your machine. Your media never leaves your computer. It uses [faster-whisper](https://github.com/SYSTRAN/faster-whisper) for transcription and ffmpeg for burning captions into video — both free and open source.
|
|
40
|
+
|
|
41
|
+
<p align="center">
|
|
42
|
+
<img src="https://raw.githubusercontent.com/abubakar60675/captionkit/main/assets/demo-terminal.gif" alt="CaptionKit terminal demo" width="700">
|
|
43
|
+
</p>
|
|
44
|
+
|
|
45
|
+
<p align="center">
|
|
46
|
+
<img src="https://raw.githubusercontent.com/abubakar60675/captionkit/main/assets/demo-burn.gif" alt="CaptionKit karaoke burn demo" width="280">
|
|
47
|
+
</p>
|
|
48
|
+
|
|
49
|
+
## Why CaptionKit?
|
|
50
|
+
|
|
51
|
+
- **Free forever** — no API keys, no subscriptions, no usage limits
|
|
52
|
+
- **Private** — your files never leave your machine
|
|
53
|
+
- **Offline** — works without an internet connection (after model download)
|
|
54
|
+
- **Accurate** — powered by OpenAI's Whisper model via faster-whisper
|
|
55
|
+
- **90+ languages** — auto-detects the language or use `--language` to specify
|
|
56
|
+
- **Multiple formats** — outputs SRT, VTT, ASS, and JSON with word-level timestamps
|
|
57
|
+
- **Burn captions into video** — styled presets for YouTube Shorts, Reels, TikTok
|
|
58
|
+
- **Karaoke mode** — word-by-word highlight captions for short-form content
|
|
59
|
+
- **RTL and CJK support** — proper rendering for Arabic, Hebrew, Chinese, Japanese, Korean
|
|
60
|
+
- **Batch processing** — caption an entire folder in one command
|
|
61
|
+
|
|
62
|
+
## Install
|
|
63
|
+
|
|
64
|
+
Requires Python 3.10+ and ffmpeg.
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
# Install ffmpeg (if not already installed)
|
|
68
|
+
# macOS: brew install ffmpeg
|
|
69
|
+
# Ubuntu: sudo apt install ffmpeg
|
|
70
|
+
# Windows: https://ffmpeg.org/download.html
|
|
71
|
+
|
|
72
|
+
# Install from PyPI
|
|
73
|
+
pip install captionkit
|
|
74
|
+
|
|
75
|
+
# Or with pipx (isolated install)
|
|
76
|
+
pipx install captionkit
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
For GPU acceleration (optional):
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
# NVIDIA CUDA
|
|
83
|
+
pip install captionkit ctranslate2 nvidia-cublas-cu12 nvidia-cudnn-cu12
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Quick start
|
|
87
|
+
|
|
88
|
+
### Transcribe a file
|
|
89
|
+
|
|
90
|
+
```bash
|
|
91
|
+
# Auto-detect language, output SRT + VTT + ASS + JSON
|
|
92
|
+
captionkit transcribe video.mp4
|
|
93
|
+
|
|
94
|
+
# Specify language
|
|
95
|
+
captionkit transcribe podcast.mp3 --language en
|
|
96
|
+
|
|
97
|
+
# Use a larger model for better accuracy
|
|
98
|
+
captionkit transcribe interview.wav --model large-v3
|
|
99
|
+
|
|
100
|
+
# Translate to English
|
|
101
|
+
captionkit transcribe video_french.mp4 --translate
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### Burn captions into video
|
|
105
|
+
|
|
106
|
+
```bash
|
|
107
|
+
# Clean captions for landscape video
|
|
108
|
+
captionkit burn video.mp4
|
|
109
|
+
|
|
110
|
+
# TikTok-style with karaoke highlighting
|
|
111
|
+
captionkit burn video.mp4 --preset tiktok-karaoke
|
|
112
|
+
|
|
113
|
+
# YouTube Shorts preset
|
|
114
|
+
captionkit burn video.mp4 --preset shorts
|
|
115
|
+
|
|
116
|
+
# Custom styling
|
|
117
|
+
captionkit burn video.mp4 --font "Noto Sans" --font-size 28 --position top
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
### Batch process a folder
|
|
121
|
+
|
|
122
|
+
```bash
|
|
123
|
+
# Transcribe all media files in a folder
|
|
124
|
+
captionkit batch ./videos/ --mode transcribe
|
|
125
|
+
|
|
126
|
+
# Burn captions into all videos with Reels preset
|
|
127
|
+
captionkit batch ./videos/ --mode burn --preset reels-karaoke
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
### List available presets
|
|
131
|
+
|
|
132
|
+
```bash
|
|
133
|
+
captionkit presets
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
## Presets
|
|
137
|
+
|
|
138
|
+
| Preset | Aspect | Karaoke | Use case |
|
|
139
|
+
|--------|--------|---------|----------|
|
|
140
|
+
| `clean` | 16:9 | No | Standard landscape video |
|
|
141
|
+
| `minimal` | 16:9 | No | Low-profile captions |
|
|
142
|
+
| `shorts` | 9:16 | No | YouTube Shorts |
|
|
143
|
+
| `shorts-karaoke` | 9:16 | Yes | YouTube Shorts with word highlighting |
|
|
144
|
+
| `reels` | 9:16 | No | Instagram Reels |
|
|
145
|
+
| `reels-karaoke` | 9:16 | Yes | Instagram Reels with word highlighting |
|
|
146
|
+
| `tiktok` | 9:16 | No | TikTok |
|
|
147
|
+
| `tiktok-karaoke` | 9:16 | Yes | TikTok with word highlighting |
|
|
148
|
+
|
|
149
|
+
## Model sizes
|
|
150
|
+
|
|
151
|
+
| Model | Parameters | English | Multilingual | Speed | VRAM |
|
|
152
|
+
|-------|-----------|---------|-------------|-------|------|
|
|
153
|
+
| `tiny` | 39M | Good | Okay | Fastest | ~1 GB |
|
|
154
|
+
| `base` | 74M | Good | Good | Fast | ~1 GB |
|
|
155
|
+
| `small` | 244M | Great | Good | Moderate | ~2 GB |
|
|
156
|
+
| `medium` | 769M | Great | Great | Slow | ~5 GB |
|
|
157
|
+
| `large-v3` | 1550M | Best | Best | Slowest | ~10 GB |
|
|
158
|
+
|
|
159
|
+
Default is `base` — a good balance of speed and accuracy. Use `tiny` for quick drafts, `large-v3` for final production.
|
|
160
|
+
|
|
161
|
+
## Language support
|
|
162
|
+
|
|
163
|
+
CaptionKit supports 90+ languages through Whisper, including but not limited to:
|
|
164
|
+
|
|
165
|
+
**Latin script:** English, Spanish, French, German, Portuguese, Italian, Dutch, Polish, Turkish, Vietnamese, Indonesian, Malay, Swahili, and many more
|
|
166
|
+
|
|
167
|
+
**Arabic script:** Arabic, Urdu, Persian, Pashto
|
|
168
|
+
|
|
169
|
+
**CJK:** Chinese (Simplified & Traditional), Japanese, Korean
|
|
170
|
+
|
|
171
|
+
**Devanagari:** Hindi, Marathi, Sanskrit, Nepali
|
|
172
|
+
|
|
173
|
+
**Other scripts:** Thai, Greek, Russian, Ukrainian, Georgian, Armenian, Hebrew, Bengali, Tamil, Telugu, Kannada, Malayalam, Burmese, Khmer, Lao
|
|
174
|
+
|
|
175
|
+
Language is auto-detected by default. Use `--language <code>` to specify (e.g., `--language ar` for Arabic, `--language zh` for Chinese).
|
|
176
|
+
|
|
177
|
+
### RTL and CJK rendering
|
|
178
|
+
|
|
179
|
+
When burning captions, CaptionKit uses font fallback to find appropriate fonts for the detected script. For best results with RTL or CJK content, install [Noto fonts](https://fonts.google.com/noto):
|
|
180
|
+
|
|
181
|
+
```bash
|
|
182
|
+
# Ubuntu/Debian
|
|
183
|
+
sudo apt install fonts-noto fonts-noto-cjk fonts-noto-color-emoji
|
|
184
|
+
|
|
185
|
+
# macOS (via Homebrew)
|
|
186
|
+
brew install font-noto-sans font-noto-sans-cjk
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
## Output formats
|
|
190
|
+
|
|
191
|
+
| Format | Extension | Word timestamps | Use case |
|
|
192
|
+
|--------|-----------|----------------|----------|
|
|
193
|
+
| SRT | `.srt` | Segment-level | Most video players and editors |
|
|
194
|
+
| WebVTT | `.vtt` | Segment-level | Web video, HTML5 `<track>` |
|
|
195
|
+
| ASS | `.ass` | Word-level (karaoke) | Advanced styling, burning |
|
|
196
|
+
| JSON | `.json` | Word-level | Programmatic access, custom tools |
|
|
197
|
+
|
|
198
|
+
## Development
|
|
199
|
+
|
|
200
|
+
```bash
|
|
201
|
+
git clone https://github.com/abubakar60675/captionkit.git
|
|
202
|
+
cd captionkit
|
|
203
|
+
python -m venv .venv
|
|
204
|
+
source .venv/bin/activate
|
|
205
|
+
pip install -e ".[dev]"
|
|
206
|
+
|
|
207
|
+
# Run tests
|
|
208
|
+
pytest -v
|
|
209
|
+
|
|
210
|
+
# Lint
|
|
211
|
+
ruff check src/ tests/
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md) for the full contribution guide.
|
|
215
|
+
|
|
216
|
+
## Changelog
|
|
217
|
+
|
|
218
|
+
See [CHANGELOG.md](CHANGELOG.md) for release history.
|
|
219
|
+
|
|
220
|
+
## Roadmap
|
|
221
|
+
|
|
222
|
+
See [ROADMAP.md](ROADMAP.md) for planned features and `good first issue` ideas.
|
|
223
|
+
|
|
224
|
+
## License
|
|
225
|
+
|
|
226
|
+
[MIT](LICENSE) — free for personal and commercial use.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
captionkit/__init__.py,sha256=rue2M0hqFeKYuOAN9mp1U4SuPBaZwxL4CrxGbahyS2g,99
|
|
2
|
+
captionkit/batch.py,sha256=M98nM4x70N3mUxg_3HbH9aNWbKUoUWUjVwI-CZCOyz4,4461
|
|
3
|
+
captionkit/burner.py,sha256=uoz5PaDwJwzta9fDRKsh9E2sk0W5BGde7MPYoOxvxv8,7544
|
|
4
|
+
captionkit/cli.py,sha256=aKTwznJ9-zrAgeIUt-mikjxsE9_bbxlM5AKvj2TZ8Zo,9725
|
|
5
|
+
captionkit/formatter.py,sha256=vXQzimPA5xDBtR1HUIvGomIkIWNNNxV4ffVhYv2muRM,6392
|
|
6
|
+
captionkit/transcriber.py,sha256=FfyHjVgQF1TT5ZlGIA8RYzNj9X8GiL_Ehnjrcigx4As,3357
|
|
7
|
+
captionkit-0.1.0.dist-info/METADATA,sha256=Jh0XrOemu8hCSzuuLCJB9ubGn0bAPS6bwgbcX1MAaoU,7590
|
|
8
|
+
captionkit-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
captionkit-0.1.0.dist-info/entry_points.txt,sha256=wQSWqyy7tHpGS4oaKEA-0NqjNG29YpWOZKuw9aCNcu4,51
|
|
10
|
+
captionkit-0.1.0.dist-info/licenses/LICENSE,sha256=qlIeLgd4aYwJvkrqdNv4n2xwNCdqzIT_1tsbafnqBaU,1074
|
|
11
|
+
captionkit-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Muhammad Abubakar
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|