cutcaption 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.
cutcaption/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Public package metadata for cutcaption."""
2
+
3
+ from cutcaption._version import __version__
4
+
5
+ __all__ = ["__version__"]
cutcaption/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Module entrypoint for ``python -m cutcaption``."""
2
+
3
+ from cutcaption.cli import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
cutcaption/_version.py ADDED
@@ -0,0 +1,3 @@
1
+ """Package version kept in one importable location."""
2
+
3
+ __version__ = "0.1.0"
cutcaption/chunking.py ADDED
@@ -0,0 +1,240 @@
1
+ """Convert transcript timestamps into readable caption chunks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ from cutcaption.config import CaptionConfig
8
+ from cutcaption.models import Caption, Segment, Transcript, Word, WordTiming
9
+
10
+ PUNCTUATION_ENDINGS = (".", "?", "!", ",", ";", ":")
11
+ LONG_PAUSE_SECONDS = 0.45
12
+ MIN_READABLE_WORDS = 2
13
+ MAX_LINE_CHARS = 26
14
+
15
+
16
+ def build_captions(transcript: Transcript, config: CaptionConfig) -> list[Caption]:
17
+ """Build short creator-friendly captions from a transcript."""
18
+
19
+ words = _clean_words(transcript.words)
20
+ if words:
21
+ chunks = _chunk_words(words, config)
22
+ chunks = _merge_one_word_fragments(chunks, config)
23
+ return [_caption_from_words(chunk) for chunk in chunks]
24
+
25
+ if transcript.segments is None:
26
+ return []
27
+ return _captions_from_segments(transcript.segments)
28
+
29
+
30
+ def chunk_words(
31
+ words: list[WordTiming] | tuple[WordTiming, ...],
32
+ *,
33
+ min_words: int = MIN_READABLE_WORDS,
34
+ max_words: int = 5,
35
+ max_pause: float = LONG_PAUSE_SECONDS,
36
+ ) -> list[Caption]:
37
+ """Group timestamped words into short captions.
38
+
39
+ This compatibility wrapper keeps the original word-only API available while
40
+ routing through the same cleanup and caption model used by build_captions.
41
+ """
42
+
43
+ if min_words < 1:
44
+ raise ValueError("min_words must be at least 1.")
45
+ if max_words < min_words:
46
+ raise ValueError("max_words must be greater than or equal to min_words.")
47
+
48
+ config = CaptionConfig(max_words=max_words)
49
+ clean_words = _clean_words(words)
50
+ chunks = _chunk_words(clean_words, config, min_words=min_words, max_pause=max_pause)
51
+ chunks = _merge_one_word_fragments(chunks, config)
52
+ return [_caption_from_words(chunk) for chunk in chunks]
53
+
54
+
55
+ def _chunk_words(
56
+ words: tuple[Word, ...],
57
+ config: CaptionConfig,
58
+ *,
59
+ min_words: int = MIN_READABLE_WORDS,
60
+ max_pause: float = LONG_PAUSE_SECONDS,
61
+ ) -> list[list[Word]]:
62
+ chunks: list[list[Word]] = []
63
+ current: list[Word] = []
64
+
65
+ for word in words:
66
+ if current and _should_split_before(
67
+ current,
68
+ word,
69
+ config,
70
+ min_words=min_words,
71
+ max_pause=max_pause,
72
+ ):
73
+ chunks.append(current)
74
+ current = []
75
+
76
+ current.append(word)
77
+
78
+ if current:
79
+ chunks.append(current)
80
+
81
+ return chunks
82
+
83
+
84
+ def _should_split_before(
85
+ current: list[Word],
86
+ next_word: Word,
87
+ config: CaptionConfig,
88
+ *,
89
+ min_words: int,
90
+ max_pause: float,
91
+ ) -> bool:
92
+ if len(current) >= config.max_words:
93
+ return True
94
+
95
+ if _would_exceed_max_lines(current, next_word, config):
96
+ return _can_stand_alone(current, config, min_words=min_words)
97
+
98
+ current_start = current[0].start
99
+ current_end = current[-1].end
100
+ current_duration = current_end - current_start
101
+ would_duration = next_word.end - current_start
102
+
103
+ if would_duration > config.max_caption_duration:
104
+ return _can_stand_alone(current, config, min_words=1)
105
+
106
+ previous = current[-1]
107
+ pause = next_word.start - previous.end
108
+ if pause > max_pause:
109
+ return _can_stand_alone(current, config, min_words=min_words)
110
+
111
+ if previous.text.endswith(PUNCTUATION_ENDINGS):
112
+ return _can_stand_alone(current, config, min_words=min_words)
113
+
114
+ return current_duration >= config.max_caption_duration
115
+
116
+
117
+ def _can_stand_alone(current: list[Word], config: CaptionConfig, *, min_words: int) -> bool:
118
+ duration = current[-1].end - current[0].start
119
+ if len(current) >= config.max_words:
120
+ return True
121
+ if duration >= config.max_caption_duration:
122
+ return True
123
+ return len(current) >= min_words and duration >= config.min_caption_duration
124
+
125
+
126
+ def _merge_one_word_fragments(
127
+ chunks: list[list[Word]],
128
+ config: CaptionConfig,
129
+ ) -> list[list[Word]]:
130
+ if len(chunks) < 2:
131
+ return chunks
132
+
133
+ merged: list[list[Word]] = []
134
+ index = 0
135
+ while index < len(chunks):
136
+ chunk = chunks[index]
137
+ if len(chunk) != 1:
138
+ merged.append(chunk)
139
+ index += 1
140
+ continue
141
+
142
+ if merged and _can_merge(merged[-1], chunk, config):
143
+ merged[-1].extend(chunk)
144
+ index += 1
145
+ continue
146
+
147
+ if index + 1 < len(chunks) and _can_merge(chunk, chunks[index + 1], config):
148
+ merged.append(chunk + chunks[index + 1])
149
+ index += 2
150
+ continue
151
+
152
+ merged.append(chunk)
153
+ index += 1
154
+
155
+ if len(merged) >= 2 and len(merged[-1]) == 1 and _can_merge(merged[-2], merged[-1], config):
156
+ merged[-2].extend(merged.pop())
157
+ elif (
158
+ len(merged) >= 2
159
+ and len(merged[-1]) == 1
160
+ and len(merged[-2]) > MIN_READABLE_WORDS
161
+ and _line_count(_caption_text([merged[-2][-1], *merged[-1]])) <= config.max_lines
162
+ ):
163
+ merged[-1].insert(0, merged[-2].pop())
164
+
165
+ return merged
166
+
167
+
168
+ def _can_merge(left: list[Word], right: list[Word], config: CaptionConfig) -> bool:
169
+ combined = left + right
170
+ return (
171
+ len(combined) <= config.max_words
172
+ and combined[-1].end - combined[0].start <= config.max_caption_duration
173
+ and _line_count(_caption_text(combined)) <= config.max_lines
174
+ )
175
+
176
+
177
+ def _would_exceed_max_lines(current: list[Word], next_word: Word, config: CaptionConfig) -> bool:
178
+ return _line_count(_caption_text([*current, next_word])) > config.max_lines
179
+
180
+
181
+ def _line_count(text: str) -> int:
182
+ if not text:
183
+ return 0
184
+
185
+ lines = 1
186
+ line_length = 0
187
+ for token in text.split():
188
+ token_length = len(token)
189
+ separator = 1 if line_length else 0
190
+ if line_length and line_length + separator + token_length > MAX_LINE_CHARS:
191
+ lines += 1
192
+ line_length = token_length
193
+ else:
194
+ line_length += separator + token_length
195
+ return lines
196
+
197
+
198
+ def _captions_from_segments(segments: list[Segment]) -> list[Caption]:
199
+ captions: list[Caption] = []
200
+ for segment in segments:
201
+ _validate_timing(segment.text, segment.start, segment.end)
202
+ text = _clean_text(segment.text)
203
+ if text:
204
+ captions.append(Caption(text=text, start=segment.start, end=segment.end, words=[]))
205
+ return captions
206
+
207
+
208
+ def _caption_from_words(words: list[Word]) -> Caption:
209
+ return Caption(text=_caption_text(words), start=words[0].start, end=words[-1].end, words=words)
210
+
211
+
212
+ def _caption_text(words: list[Word]) -> str:
213
+ return _clean_text(" ".join(word.text for word in words))
214
+
215
+
216
+ def _clean_words(words: list[WordTiming] | tuple[WordTiming, ...]) -> tuple[Word, ...]:
217
+ clean_words: list[Word] = []
218
+ for word in words:
219
+ _validate_timing(word.text, word.start, word.end)
220
+ text = _clean_text(word.text)
221
+ if text:
222
+ clean_words.append(
223
+ Word(
224
+ text=text,
225
+ start=word.start,
226
+ end=word.end,
227
+ probability=word.probability,
228
+ )
229
+ )
230
+ return tuple(clean_words)
231
+
232
+
233
+ def _clean_text(text: str) -> str:
234
+ clean = re.sub(r"\s+", " ", text.strip())
235
+ return re.sub(r"\s+([.,?!;:])", r"\1", clean)
236
+
237
+
238
+ def _validate_timing(text: str, start: float, end: float) -> None:
239
+ if start < 0 or end < 0 or end <= start:
240
+ raise ValueError(f"Invalid word timing for '{text}'.")
cutcaption/cli.py ADDED
@@ -0,0 +1,347 @@
1
+ """Typer-based command line interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ from dataclasses import replace
7
+ from pathlib import Path
8
+ from typing import Annotated
9
+
10
+ import typer
11
+ from rich.console import Console
12
+ from rich.panel import Panel
13
+ from rich.table import Table
14
+
15
+ from cutcaption import __version__
16
+ from cutcaption.config import CutcapConfig, load_config, write_default_config
17
+ from cutcaption.doctor import DoctorCheck, has_critical_failures, run_doctor_checks
18
+ from cutcaption.models import BatchResult, JobResult, VideoJob
19
+ from cutcaption.pipeline import plan_jobs, process_batch
20
+ from cutcaption.styles import list_styles as available_styles
21
+ from cutcaption.utils.paths import folder_output_dir
22
+
23
+ app = typer.Typer(
24
+ add_completion=False,
25
+ help="One command. Pretty captions. Batch videos. No editing software.",
26
+ )
27
+ console = Console()
28
+
29
+
30
+ def version_callback(value: bool) -> None:
31
+ if value:
32
+ console.print(f"cutcaption {__version__}")
33
+ raise typer.Exit()
34
+
35
+
36
+ def caption(
37
+ input_path: Annotated[
38
+ Path | None,
39
+ typer.Argument(help="Video file or folder to caption."),
40
+ ] = None,
41
+ config_path: Annotated[
42
+ Path | None,
43
+ typer.Option("--config", help="Path to a cutcaption TOML config file."),
44
+ ] = None,
45
+ preset: Annotated[str | None, typer.Option("--preset", help="Caption preset.")] = None,
46
+ style: Annotated[str | None, typer.Option("--style", help="Caption style preset.")] = None,
47
+ model: Annotated[
48
+ str | None,
49
+ typer.Option("--model", help="faster-whisper model name."),
50
+ ] = None,
51
+ mode: Annotated[
52
+ str | None,
53
+ typer.Option("--mode", help="Processing mode: fast, balanced, accurate."),
54
+ ] = None,
55
+ language: Annotated[
56
+ str | None,
57
+ typer.Option("--language", help="Language code, or omit for auto detection."),
58
+ ] = None,
59
+ output: Annotated[Path | None, typer.Option("--output", "-o", help="Output directory.")] = None,
60
+ srt: Annotated[bool | None, typer.Option("--srt/--no-srt", help="Write SRT subtitles.")] = None,
61
+ ass: Annotated[
62
+ bool | None,
63
+ typer.Option("--ass/--no-ass", help="Write ASS subtitles."),
64
+ ] = None,
65
+ json_output: Annotated[
66
+ bool | None,
67
+ typer.Option("--json/--no-json", help="Write JSON metadata."),
68
+ ] = None,
69
+ burn: Annotated[
70
+ bool | None,
71
+ typer.Option("--burn/--no-burn", help="Render burned-in captioned MP4."),
72
+ ] = None,
73
+ recursive: Annotated[
74
+ bool | None,
75
+ typer.Option("--recursive/--no-recursive", help="Search folders recursively."),
76
+ ] = None,
77
+ overwrite: Annotated[
78
+ bool | None,
79
+ typer.Option("--overwrite/--no-overwrite", help="Replace existing outputs."),
80
+ ] = None,
81
+ skip_existing: Annotated[
82
+ bool | None,
83
+ typer.Option(
84
+ "--skip-existing/--no-skip-existing",
85
+ help="Skip jobs with existing requested outputs.",
86
+ ),
87
+ ] = None,
88
+ jobs: Annotated[
89
+ int | None,
90
+ typer.Option("--jobs", help="Number of worker jobs. Currently processed sequentially."),
91
+ ] = None,
92
+ dry_run: Annotated[
93
+ bool,
94
+ typer.Option("--dry-run", help="Plan jobs without transcription or rendering."),
95
+ ] = False,
96
+ version: Annotated[
97
+ bool,
98
+ typer.Option("--version", callback=version_callback, is_eager=True),
99
+ ] = False,
100
+ ) -> None:
101
+ _ = version
102
+ if input_path is None:
103
+ console.print("Usage: cutcaption INPUT [OPTIONS]\n\nRun `cutcaption --help` for options.")
104
+ raise typer.Exit()
105
+
106
+ try:
107
+ config = _apply_cli_overrides(
108
+ load_config(config_path),
109
+ preset=preset,
110
+ style=style,
111
+ model=model,
112
+ mode=mode,
113
+ language=language,
114
+ output=output,
115
+ srt=srt,
116
+ ass=ass,
117
+ json_output=json_output,
118
+ burn=burn,
119
+ recursive=recursive,
120
+ overwrite=overwrite,
121
+ skip_existing=skip_existing,
122
+ jobs=jobs,
123
+ )
124
+ planned_jobs = plan_jobs(input_path, config)
125
+ except Exception as exc:
126
+ console.print(f"[bold red]Error:[/bold red] {exc}")
127
+ raise typer.Exit(code=1) from exc
128
+
129
+ _print_planned_jobs(planned_jobs)
130
+ if dry_run:
131
+ console.print("[yellow]Dry run complete. No files were processed.[/yellow]")
132
+ return
133
+
134
+ with console.status("[bold cyan]Processing videos...[/bold cyan]"):
135
+ result = process_batch(
136
+ [job.source for job in planned_jobs],
137
+ config,
138
+ folder_output_dir(input_path, config.output),
139
+ )
140
+
141
+ _print_batch_summary(result)
142
+ if result.failed:
143
+ raise typer.Exit(code=1)
144
+
145
+
146
+ @app.command()
147
+ def doctor() -> None:
148
+ """Check local tools and Python dependencies."""
149
+
150
+ checks = run_doctor_checks()
151
+ table = Table(title="cutcaption doctor", show_lines=True)
152
+ table.add_column("Check")
153
+ table.add_column("Status")
154
+ table.add_column("Detail")
155
+
156
+ for check in checks:
157
+ table.add_row(
158
+ check.name,
159
+ _doctor_status(check),
160
+ check.message,
161
+ )
162
+
163
+ console.print(
164
+ Panel(
165
+ "ffmpeg is required for burned-in captioned videos. "
166
+ "Transcription and subtitle export may still work without it.",
167
+ title="Video rendering",
168
+ border_style="cyan",
169
+ )
170
+ )
171
+ console.print(table)
172
+
173
+ hints = _doctor_hints(checks)
174
+ if hints:
175
+ console.print(Panel("\n\n".join(hints), title="Actionable fixes", border_style="yellow"))
176
+
177
+ if has_critical_failures(checks):
178
+ raise typer.Exit(code=1)
179
+
180
+
181
+ @app.command("styles")
182
+ def list_styles() -> None:
183
+ """List built-in caption styles."""
184
+
185
+ table = Table(title="Caption styles")
186
+ table.add_column("Name")
187
+ table.add_column("Description")
188
+ table.add_column("Uppercase")
189
+ table.add_column("Font size")
190
+ table.add_column("Box")
191
+ for style in available_styles():
192
+ table.add_row(
193
+ style.name,
194
+ style.description,
195
+ "yes" if style.uppercase else "no",
196
+ str(style.font_size),
197
+ "yes" if style.box else "no",
198
+ )
199
+ console.print(table)
200
+
201
+
202
+ @app.command()
203
+ def init() -> None:
204
+ """Create a starter config file."""
205
+
206
+ config_path = Path("cutcaption.toml")
207
+ if config_path.exists():
208
+ console.print("[yellow]cutcaption.toml already exists.[/yellow]")
209
+ raise typer.Exit(code=1)
210
+ write_default_config(config_path)
211
+ console.print("[green]Created cutcaption.toml[/green]")
212
+
213
+
214
+ @app.command()
215
+ def preview() -> None:
216
+ """Preview caption styles. Stubbed for the MVP foundation."""
217
+
218
+ console.print("[yellow]Preview is not implemented yet.[/yellow]")
219
+
220
+
221
+ def main() -> None:
222
+ args = sys.argv[1:]
223
+ if args and args[0] in {"doctor", "styles", "init", "preview"}:
224
+ app(args=args)
225
+ return
226
+ typer.run(caption)
227
+
228
+
229
+ def _apply_cli_overrides(
230
+ config: CutcapConfig,
231
+ *,
232
+ preset: str | None,
233
+ style: str | None,
234
+ model: str | None,
235
+ mode: str | None,
236
+ language: str | None,
237
+ output: Path | None,
238
+ srt: bool | None,
239
+ ass: bool | None,
240
+ json_output: bool | None,
241
+ burn: bool | None,
242
+ recursive: bool | None,
243
+ overwrite: bool | None,
244
+ skip_existing: bool | None,
245
+ jobs: int | None,
246
+ ) -> CutcapConfig:
247
+ transcription = replace(
248
+ config.transcription,
249
+ **_without_none({"model": model, "mode": mode, "language": language}),
250
+ )
251
+ caption = replace(config.caption, **_without_none({"preset": preset, "style": style}))
252
+ render = replace(
253
+ config.render,
254
+ **_without_none({"srt": srt, "ass": ass, "json": json_output, "burn": burn}),
255
+ )
256
+ batch_overrides = _without_none(
257
+ {
258
+ "recursive": recursive,
259
+ "overwrite": overwrite,
260
+ "skip_existing": skip_existing,
261
+ "jobs": jobs,
262
+ }
263
+ )
264
+ if overwrite is True and skip_existing is None:
265
+ batch_overrides["skip_existing"] = False
266
+ batch = replace(config.batch, **batch_overrides)
267
+ return CutcapConfig(
268
+ transcription=transcription,
269
+ caption=caption,
270
+ render=render,
271
+ batch=batch,
272
+ output=output if output is not None else config.output,
273
+ )
274
+
275
+
276
+ def _without_none(values: dict[str, object | None]) -> dict[str, object]:
277
+ return {key: value for key, value in values.items() if value is not None}
278
+
279
+
280
+ def _doctor_status(check: DoctorCheck) -> str:
281
+ if check.ok:
282
+ return "[green]✓ ok[/green]"
283
+ if check.critical:
284
+ return "[red]✗ missing[/red]"
285
+ return "[yellow]optional[/yellow]"
286
+
287
+
288
+ def _doctor_hints(checks: list[DoctorCheck]) -> list[str]:
289
+ hints: list[str] = []
290
+ for check in checks:
291
+ if not check.ok and check.hint and check.hint not in hints:
292
+ hints.append(check.hint)
293
+ return hints
294
+
295
+
296
+ def _print_planned_jobs(jobs: list[VideoJob]) -> None:
297
+ table = Table(title=f"Planned caption jobs ({len(jobs)})")
298
+ table.add_column("Input")
299
+ table.add_column("SRT")
300
+ table.add_column("ASS")
301
+ table.add_column("JSON")
302
+ table.add_column("Captioned video")
303
+
304
+ for job in jobs:
305
+ table.add_row(
306
+ str(job.source),
307
+ str(job.srt_path),
308
+ str(job.ass_path),
309
+ str(job.json_path),
310
+ str(job.rendered_path),
311
+ )
312
+
313
+ console.print(table)
314
+
315
+
316
+ def _print_batch_summary(result: BatchResult) -> None:
317
+ table = Table(title="Caption results")
318
+ table.add_column("Input")
319
+ table.add_column("Status")
320
+ table.add_column("Outputs")
321
+ table.add_column("Duration")
322
+ table.add_column("Error")
323
+
324
+ for job_result in result.results:
325
+ table.add_row(
326
+ str(job_result.input_path),
327
+ _result_status(job_result),
328
+ "\n".join(str(path) for path in job_result.outputs_written) or "-",
329
+ f"{job_result.duration:.2f}s" if job_result.duration is not None else "-",
330
+ job_result.error_message or "-",
331
+ )
332
+
333
+ console.print(table)
334
+ console.print(
335
+ f"Total: {result.total} "
336
+ f"Succeeded: {result.succeeded} "
337
+ f"Failed: {result.failed} "
338
+ f"Skipped: {result.skipped}"
339
+ )
340
+
341
+
342
+ def _result_status(result: JobResult) -> str:
343
+ if result.skipped:
344
+ return "[yellow]skipped[/yellow]"
345
+ if result.success:
346
+ return "[green]success[/green]"
347
+ return "[red]failed[/red]"