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 +5 -0
- cutcaption/__main__.py +6 -0
- cutcaption/_version.py +3 -0
- cutcaption/chunking.py +240 -0
- cutcaption/cli.py +347 -0
- cutcaption/config.py +258 -0
- cutcaption/doctor.py +143 -0
- cutcaption/exporters/__init__.py +1 -0
- cutcaption/exporters/ass.py +97 -0
- cutcaption/exporters/json.py +67 -0
- cutcaption/exporters/srt.py +61 -0
- cutcaption/media.py +23 -0
- cutcaption/models.py +93 -0
- cutcaption/pipeline.py +151 -0
- cutcaption/render.py +76 -0
- cutcaption/styles.py +149 -0
- cutcaption/transcribe.py +131 -0
- cutcaption/utils/__init__.py +1 -0
- cutcaption/utils/ffmpeg.py +143 -0
- cutcaption/utils/logging.py +7 -0
- cutcaption/utils/paths.py +82 -0
- cutcaption-0.1.0.dist-info/METADATA +390 -0
- cutcaption-0.1.0.dist-info/RECORD +27 -0
- cutcaption-0.1.0.dist-info/WHEEL +5 -0
- cutcaption-0.1.0.dist-info/entry_points.txt +2 -0
- cutcaption-0.1.0.dist-info/licenses/LICENSE +21 -0
- cutcaption-0.1.0.dist-info/top_level.txt +1 -0
cutcaption/models.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Shared data models for caption generation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
VIDEO_EXTENSIONS = frozenset({".mp4", ".mov", ".mkv", ".webm", ".avi", ".m4v"})
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True, slots=True)
|
|
12
|
+
class Word:
|
|
13
|
+
text: str
|
|
14
|
+
start: float
|
|
15
|
+
end: float
|
|
16
|
+
probability: float | None = None
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
WordTiming = Word
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True, slots=True)
|
|
23
|
+
class Segment:
|
|
24
|
+
text: str
|
|
25
|
+
start: float
|
|
26
|
+
end: float
|
|
27
|
+
words: list[Word]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True, slots=True)
|
|
31
|
+
class Caption:
|
|
32
|
+
text: str
|
|
33
|
+
start: float
|
|
34
|
+
end: float
|
|
35
|
+
words: list[Word] = field(default_factory=list)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True, slots=True)
|
|
39
|
+
class OutputPaths:
|
|
40
|
+
srt_path: Path
|
|
41
|
+
ass_path: Path
|
|
42
|
+
json_path: Path
|
|
43
|
+
captioned_video_path: Path
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True, slots=True)
|
|
47
|
+
class JobResult:
|
|
48
|
+
input_path: Path
|
|
49
|
+
success: bool
|
|
50
|
+
outputs_written: list[Path]
|
|
51
|
+
skipped: bool = False
|
|
52
|
+
error_message: str | None = None
|
|
53
|
+
duration: float | None = None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True, slots=True)
|
|
57
|
+
class BatchResult:
|
|
58
|
+
total: int
|
|
59
|
+
succeeded: int
|
|
60
|
+
failed: int
|
|
61
|
+
skipped: int
|
|
62
|
+
results: list[JobResult]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(frozen=True, slots=True)
|
|
66
|
+
class VideoJob:
|
|
67
|
+
source: Path
|
|
68
|
+
srt_path: Path
|
|
69
|
+
ass_path: Path
|
|
70
|
+
json_path: Path
|
|
71
|
+
rendered_path: Path
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def output_paths(self) -> OutputPaths:
|
|
75
|
+
return OutputPaths(
|
|
76
|
+
srt_path=self.srt_path,
|
|
77
|
+
ass_path=self.ass_path,
|
|
78
|
+
json_path=self.json_path,
|
|
79
|
+
captioned_video_path=self.rendered_path,
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass(frozen=True, slots=True)
|
|
84
|
+
class Transcript:
|
|
85
|
+
language: str | None = None
|
|
86
|
+
duration: float | None = None
|
|
87
|
+
segments: list[Segment] | None = None
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def words(self) -> tuple[Word, ...]:
|
|
91
|
+
if self.segments is None:
|
|
92
|
+
return ()
|
|
93
|
+
return tuple(word for segment in self.segments for word in segment.words)
|
cutcaption/pipeline.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""High-level captioning orchestration."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from cutcaption.chunking import build_captions
|
|
8
|
+
from cutcaption.config import CutcaptionConfig
|
|
9
|
+
from cutcaption.exporters.ass import write_ass
|
|
10
|
+
from cutcaption.exporters.json import write_json
|
|
11
|
+
from cutcaption.exporters.srt import write_srt
|
|
12
|
+
from cutcaption.models import BatchResult, JobResult, OutputPaths, VideoJob
|
|
13
|
+
from cutcaption.render import OutputExistsError, burn_subtitles
|
|
14
|
+
from cutcaption.styles import get_style
|
|
15
|
+
from cutcaption.transcribe import FasterWhisperTranscriber
|
|
16
|
+
from cutcaption.utils.paths import (
|
|
17
|
+
build_output_paths,
|
|
18
|
+
build_video_job,
|
|
19
|
+
discover_inputs,
|
|
20
|
+
folder_output_dir,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def process_video(
|
|
25
|
+
input_path: Path,
|
|
26
|
+
output_paths: OutputPaths,
|
|
27
|
+
config: CutcaptionConfig,
|
|
28
|
+
) -> JobResult:
|
|
29
|
+
"""Transcribe, caption, export, and optionally render one video."""
|
|
30
|
+
|
|
31
|
+
requested_outputs = _requested_outputs(output_paths, config)
|
|
32
|
+
existing_outputs = [path for path in requested_outputs if path.exists()]
|
|
33
|
+
if existing_outputs and config.batch.skip_existing and not config.batch.overwrite:
|
|
34
|
+
return JobResult(
|
|
35
|
+
input_path=input_path,
|
|
36
|
+
success=True,
|
|
37
|
+
outputs_written=[],
|
|
38
|
+
skipped=True,
|
|
39
|
+
duration=None,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
outputs_written: list[Path] = []
|
|
43
|
+
try:
|
|
44
|
+
_ensure_outputs_writable(requested_outputs, config)
|
|
45
|
+
transcript = FasterWhisperTranscriber().transcribe(input_path, config)
|
|
46
|
+
captions = build_captions(transcript, config.caption)
|
|
47
|
+
style = get_style(config.style)
|
|
48
|
+
|
|
49
|
+
if config.write_srt:
|
|
50
|
+
write_srt(captions, output_paths.srt_path)
|
|
51
|
+
outputs_written.append(output_paths.srt_path)
|
|
52
|
+
|
|
53
|
+
if config.write_ass or config.burn:
|
|
54
|
+
write_ass(captions, output_paths.ass_path, style, config.render)
|
|
55
|
+
outputs_written.append(output_paths.ass_path)
|
|
56
|
+
|
|
57
|
+
if config.write_json:
|
|
58
|
+
write_json(transcript, captions, output_paths.json_path)
|
|
59
|
+
outputs_written.append(output_paths.json_path)
|
|
60
|
+
|
|
61
|
+
if config.burn:
|
|
62
|
+
burn_subtitles(
|
|
63
|
+
input_path,
|
|
64
|
+
output_paths.ass_path,
|
|
65
|
+
output_paths.captioned_video_path,
|
|
66
|
+
overwrite=config.batch.overwrite,
|
|
67
|
+
)
|
|
68
|
+
outputs_written.append(output_paths.captioned_video_path)
|
|
69
|
+
|
|
70
|
+
return JobResult(
|
|
71
|
+
input_path=input_path,
|
|
72
|
+
success=True,
|
|
73
|
+
outputs_written=outputs_written,
|
|
74
|
+
duration=transcript.duration,
|
|
75
|
+
)
|
|
76
|
+
except Exception as exc:
|
|
77
|
+
return JobResult(
|
|
78
|
+
input_path=input_path,
|
|
79
|
+
success=False,
|
|
80
|
+
outputs_written=outputs_written,
|
|
81
|
+
error_message=str(exc),
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def process_batch(
|
|
86
|
+
input_paths: list[Path],
|
|
87
|
+
config: CutcaptionConfig,
|
|
88
|
+
output_dir: Path | None,
|
|
89
|
+
) -> BatchResult:
|
|
90
|
+
"""Process videos sequentially.
|
|
91
|
+
|
|
92
|
+
TODO: Use config.batch.jobs for parallel processing once shared model loading
|
|
93
|
+
and progress reporting are coordinated.
|
|
94
|
+
"""
|
|
95
|
+
|
|
96
|
+
results: list[JobResult] = []
|
|
97
|
+
for input_path in input_paths:
|
|
98
|
+
output_paths = build_output_paths(input_path, output_dir)
|
|
99
|
+
results.append(process_video(input_path, output_paths, config))
|
|
100
|
+
|
|
101
|
+
succeeded = sum(1 for result in results if result.success and not result.skipped)
|
|
102
|
+
failed = sum(1 for result in results if not result.success)
|
|
103
|
+
skipped = sum(1 for result in results if result.skipped)
|
|
104
|
+
return BatchResult(
|
|
105
|
+
total=len(results),
|
|
106
|
+
succeeded=succeeded,
|
|
107
|
+
failed=failed,
|
|
108
|
+
skipped=skipped,
|
|
109
|
+
results=results,
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def plan_jobs(input_path: Path, config: CutcaptionConfig) -> list[VideoJob]:
|
|
114
|
+
videos = discover_inputs(input_path, recursive=config.batch.recursive)
|
|
115
|
+
output_dir = folder_output_dir(input_path, config.output)
|
|
116
|
+
return [build_video_job(video, output_dir) for video in videos]
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class CaptionPipeline:
|
|
120
|
+
"""Compatibility wrapper around the function-based pipeline API."""
|
|
121
|
+
|
|
122
|
+
def plan(self, input_path: Path, config: CutcaptionConfig) -> list[VideoJob]:
|
|
123
|
+
return plan_jobs(input_path, config)
|
|
124
|
+
|
|
125
|
+
def run(self, input_path: Path, config: CutcaptionConfig) -> list[JobResult]:
|
|
126
|
+
jobs = self.plan(input_path, config)
|
|
127
|
+
output_dir = folder_output_dir(input_path, config.output)
|
|
128
|
+
return process_batch([job.source for job in jobs], config, output_dir).results
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _requested_outputs(output_paths: OutputPaths, config: CutcaptionConfig) -> list[Path]:
|
|
132
|
+
outputs: list[Path] = []
|
|
133
|
+
if config.write_srt:
|
|
134
|
+
outputs.append(output_paths.srt_path)
|
|
135
|
+
if config.write_ass or config.burn:
|
|
136
|
+
outputs.append(output_paths.ass_path)
|
|
137
|
+
if config.write_json:
|
|
138
|
+
outputs.append(output_paths.json_path)
|
|
139
|
+
if config.burn:
|
|
140
|
+
outputs.append(output_paths.captioned_video_path)
|
|
141
|
+
return outputs
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _ensure_outputs_writable(outputs: list[Path], config: CutcaptionConfig) -> None:
|
|
145
|
+
if config.batch.overwrite:
|
|
146
|
+
return
|
|
147
|
+
for path in outputs:
|
|
148
|
+
if path.exists():
|
|
149
|
+
raise OutputExistsError(
|
|
150
|
+
f"Output already exists: {path}. Use overwrite or skip existing outputs."
|
|
151
|
+
)
|
cutcaption/render.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Video rendering boundary."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from cutcaption.utils.ffmpeg import FfmpegError, FfmpegNotFoundError, check_ffmpeg, run_command
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class RenderError(FfmpegError):
|
|
11
|
+
"""Base error for video rendering failures."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class OutputExistsError(RenderError):
|
|
15
|
+
"""Raised when a render target already exists and overwrite is disabled."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def burn_subtitles(
|
|
19
|
+
video_path: Path,
|
|
20
|
+
ass_path: Path,
|
|
21
|
+
output_path: Path,
|
|
22
|
+
overwrite: bool = False,
|
|
23
|
+
) -> None:
|
|
24
|
+
"""Burn ASS subtitles into a video while preserving the original audio."""
|
|
25
|
+
|
|
26
|
+
if not check_ffmpeg():
|
|
27
|
+
raise FfmpegNotFoundError("ffmpeg not found. Install ffmpeg to burn subtitles into video.")
|
|
28
|
+
if output_path.exists() and not overwrite:
|
|
29
|
+
raise OutputExistsError(
|
|
30
|
+
f"Output already exists: {output_path}. Pass overwrite=True to replace it."
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
34
|
+
run_command(_burn_subtitles_command(video_path, ass_path, output_path, overwrite=overwrite))
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _burn_subtitles_command(
|
|
38
|
+
video_path: Path,
|
|
39
|
+
ass_path: Path,
|
|
40
|
+
output_path: Path,
|
|
41
|
+
*,
|
|
42
|
+
overwrite: bool,
|
|
43
|
+
) -> list[str]:
|
|
44
|
+
return [
|
|
45
|
+
"ffmpeg",
|
|
46
|
+
"-y" if overwrite else "-n",
|
|
47
|
+
"-i",
|
|
48
|
+
str(video_path),
|
|
49
|
+
"-vf",
|
|
50
|
+
f"subtitles=filename='{_escape_subtitle_filter_path(ass_path)}'",
|
|
51
|
+
"-map",
|
|
52
|
+
"0:v:0",
|
|
53
|
+
"-map",
|
|
54
|
+
"0:a?",
|
|
55
|
+
"-c:v",
|
|
56
|
+
"libx264",
|
|
57
|
+
"-crf",
|
|
58
|
+
"18",
|
|
59
|
+
"-preset",
|
|
60
|
+
"medium",
|
|
61
|
+
"-c:a",
|
|
62
|
+
"copy",
|
|
63
|
+
str(output_path),
|
|
64
|
+
]
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _escape_subtitle_filter_path(path: Path) -> str:
|
|
68
|
+
text = str(path)
|
|
69
|
+
return (
|
|
70
|
+
text.replace("\\", "\\\\")
|
|
71
|
+
.replace("'", r"\'")
|
|
72
|
+
.replace(":", r"\:")
|
|
73
|
+
.replace(",", r"\,")
|
|
74
|
+
.replace("[", r"\[")
|
|
75
|
+
.replace("]", r"\]")
|
|
76
|
+
)
|
cutcaption/styles.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""Caption style presets."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True, slots=True)
|
|
9
|
+
class StyleConfig:
|
|
10
|
+
name: str
|
|
11
|
+
description: str
|
|
12
|
+
font_name: str
|
|
13
|
+
font_size: int
|
|
14
|
+
bold: bool
|
|
15
|
+
italic: bool
|
|
16
|
+
primary_color: str
|
|
17
|
+
outline_color: str
|
|
18
|
+
back_color: str
|
|
19
|
+
outline_width: int
|
|
20
|
+
shadow: int
|
|
21
|
+
alignment: int
|
|
22
|
+
margin_v: int
|
|
23
|
+
uppercase: bool
|
|
24
|
+
box: bool
|
|
25
|
+
highlight_current_word: bool = False
|
|
26
|
+
one_word_at_a_time: bool = False
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
CaptionStyle = StyleConfig
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
STYLES: dict[str, StyleConfig] = {
|
|
33
|
+
"clean": StyleConfig(
|
|
34
|
+
name="clean",
|
|
35
|
+
description="Readable white text with a moderate outline.",
|
|
36
|
+
font_name="Arial",
|
|
37
|
+
font_size=72,
|
|
38
|
+
bold=True,
|
|
39
|
+
italic=False,
|
|
40
|
+
primary_color="&H00FFFFFF",
|
|
41
|
+
outline_color="&H00000000",
|
|
42
|
+
back_color="&H80000000",
|
|
43
|
+
outline_width=5,
|
|
44
|
+
shadow=0,
|
|
45
|
+
alignment=2,
|
|
46
|
+
margin_v=180,
|
|
47
|
+
uppercase=False,
|
|
48
|
+
box=False,
|
|
49
|
+
),
|
|
50
|
+
"bold": StyleConfig(
|
|
51
|
+
name="bold",
|
|
52
|
+
description="Larger bold uppercase captions with a thicker outline.",
|
|
53
|
+
font_name="Arial",
|
|
54
|
+
font_size=84,
|
|
55
|
+
bold=True,
|
|
56
|
+
italic=False,
|
|
57
|
+
primary_color="&H00FFFFFF",
|
|
58
|
+
outline_color="&H00000000",
|
|
59
|
+
back_color="&H80000000",
|
|
60
|
+
outline_width=7,
|
|
61
|
+
shadow=1,
|
|
62
|
+
alignment=2,
|
|
63
|
+
margin_v=180,
|
|
64
|
+
uppercase=True,
|
|
65
|
+
box=False,
|
|
66
|
+
),
|
|
67
|
+
"pop": StyleConfig(
|
|
68
|
+
name="pop",
|
|
69
|
+
description="Big creator-style uppercase captions with thick outline and shadow.",
|
|
70
|
+
font_name="Arial",
|
|
71
|
+
font_size=88,
|
|
72
|
+
bold=True,
|
|
73
|
+
italic=False,
|
|
74
|
+
primary_color="&H0000FFFF",
|
|
75
|
+
outline_color="&H00000000",
|
|
76
|
+
back_color="&H80000000",
|
|
77
|
+
outline_width=7,
|
|
78
|
+
shadow=2,
|
|
79
|
+
alignment=2,
|
|
80
|
+
margin_v=180,
|
|
81
|
+
uppercase=True,
|
|
82
|
+
box=False,
|
|
83
|
+
),
|
|
84
|
+
"minimal": StyleConfig(
|
|
85
|
+
name="minimal",
|
|
86
|
+
description="Smaller captions with a thin outline and no uppercase transform.",
|
|
87
|
+
font_name="Arial",
|
|
88
|
+
font_size=58,
|
|
89
|
+
bold=False,
|
|
90
|
+
italic=False,
|
|
91
|
+
primary_color="&H00FFFFFF",
|
|
92
|
+
outline_color="&H00000000",
|
|
93
|
+
back_color="&H80000000",
|
|
94
|
+
outline_width=2,
|
|
95
|
+
shadow=0,
|
|
96
|
+
alignment=2,
|
|
97
|
+
margin_v=180,
|
|
98
|
+
uppercase=False,
|
|
99
|
+
box=False,
|
|
100
|
+
),
|
|
101
|
+
"boxed": StyleConfig(
|
|
102
|
+
name="boxed",
|
|
103
|
+
description="Readable text over a semi-transparent box background.",
|
|
104
|
+
font_name="Arial",
|
|
105
|
+
font_size=68,
|
|
106
|
+
bold=True,
|
|
107
|
+
italic=False,
|
|
108
|
+
primary_color="&H00FFFFFF",
|
|
109
|
+
outline_color="&H00000000",
|
|
110
|
+
back_color="&H99000000",
|
|
111
|
+
outline_width=2,
|
|
112
|
+
shadow=0,
|
|
113
|
+
alignment=2,
|
|
114
|
+
margin_v=180,
|
|
115
|
+
uppercase=False,
|
|
116
|
+
box=True,
|
|
117
|
+
),
|
|
118
|
+
"shorts": StyleConfig(
|
|
119
|
+
name="shorts",
|
|
120
|
+
description="One spoken word at a time for fast short-form captions.",
|
|
121
|
+
font_name="Arial",
|
|
122
|
+
font_size=90,
|
|
123
|
+
bold=True,
|
|
124
|
+
italic=False,
|
|
125
|
+
primary_color="&H00FFFFFF",
|
|
126
|
+
outline_color="&H00000000",
|
|
127
|
+
back_color="&H80000000",
|
|
128
|
+
outline_width=7,
|
|
129
|
+
shadow=2,
|
|
130
|
+
alignment=2,
|
|
131
|
+
margin_v=210,
|
|
132
|
+
uppercase=True,
|
|
133
|
+
box=False,
|
|
134
|
+
one_word_at_a_time=True,
|
|
135
|
+
),
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def get_style(name: str) -> StyleConfig:
|
|
140
|
+
key = name.lower().strip()
|
|
141
|
+
try:
|
|
142
|
+
return STYLES[key]
|
|
143
|
+
except KeyError as exc:
|
|
144
|
+
available = ", ".join(sorted(STYLES))
|
|
145
|
+
raise ValueError(f"Unknown style '{name}'. Available styles: {available}.") from exc
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def list_styles() -> list[StyleConfig]:
|
|
149
|
+
return [STYLES[name] for name in sorted(STYLES)]
|
cutcaption/transcribe.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""faster-whisper transcription adapter."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from cutcaption.config import CutcapConfig, TranscriptionConfig
|
|
9
|
+
from cutcaption.models import Segment, Transcript, Word
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def transcribe_video(path: Path, config: TranscriptionConfig) -> Transcript:
|
|
13
|
+
"""Transcribe a video with faster-whisper and capture word timestamps."""
|
|
14
|
+
|
|
15
|
+
model = _load_model(config)
|
|
16
|
+
try:
|
|
17
|
+
segments, info = model.transcribe(
|
|
18
|
+
str(path),
|
|
19
|
+
language=config.language,
|
|
20
|
+
word_timestamps=True,
|
|
21
|
+
beam_size=_beam_size(config.mode),
|
|
22
|
+
vad_filter=True,
|
|
23
|
+
)
|
|
24
|
+
except Exception as exc:
|
|
25
|
+
raise RuntimeError(f"Transcription failed for '{path}': {exc}") from exc
|
|
26
|
+
|
|
27
|
+
return _build_transcript(segments, info)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class FasterWhisperTranscriber:
|
|
31
|
+
def transcribe(
|
|
32
|
+
self,
|
|
33
|
+
video_path: Path,
|
|
34
|
+
config: CutcapConfig | TranscriptionConfig,
|
|
35
|
+
) -> Transcript:
|
|
36
|
+
transcription_config = (
|
|
37
|
+
config.transcription if isinstance(config, CutcapConfig) else config
|
|
38
|
+
)
|
|
39
|
+
return transcribe_video(video_path, transcription_config)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _load_model(config: TranscriptionConfig) -> Any:
|
|
43
|
+
try:
|
|
44
|
+
from faster_whisper import WhisperModel
|
|
45
|
+
except ImportError as exc:
|
|
46
|
+
raise RuntimeError(
|
|
47
|
+
"faster-whisper is required for transcription. "
|
|
48
|
+
"Install cutcaption with its runtime dependencies."
|
|
49
|
+
) from exc
|
|
50
|
+
|
|
51
|
+
device = _resolve_device(config.device)
|
|
52
|
+
compute_type = _resolve_compute_type(device, config.compute_type)
|
|
53
|
+
|
|
54
|
+
try:
|
|
55
|
+
return WhisperModel(config.model, device=device, compute_type=compute_type)
|
|
56
|
+
except Exception as exc:
|
|
57
|
+
if config.compute_type == "auto" and compute_type != "int8":
|
|
58
|
+
try:
|
|
59
|
+
return WhisperModel(config.model, device=device, compute_type="int8")
|
|
60
|
+
except Exception as fallback_exc:
|
|
61
|
+
raise _model_load_error(config.model, fallback_exc) from fallback_exc
|
|
62
|
+
raise _model_load_error(config.model, exc) from exc
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _model_load_error(model: str, exc: Exception) -> RuntimeError:
|
|
66
|
+
return RuntimeError(
|
|
67
|
+
f"Could not load faster-whisper model '{model}': {exc}. "
|
|
68
|
+
"Try a smaller model, check available disk space, or run `cutcaption doctor`."
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _build_transcript(segments: Any, info: Any) -> Transcript:
|
|
73
|
+
transcript_segments: list[Segment] = []
|
|
74
|
+
for segment in segments:
|
|
75
|
+
words = [_word_from_faster_whisper(word) for word in getattr(segment, "words", None) or []]
|
|
76
|
+
transcript_segments.append(
|
|
77
|
+
Segment(
|
|
78
|
+
text=str(getattr(segment, "text", "")).strip(),
|
|
79
|
+
start=float(getattr(segment, "start", 0.0)),
|
|
80
|
+
end=float(getattr(segment, "end", 0.0)),
|
|
81
|
+
words=[word for word in words if word is not None],
|
|
82
|
+
)
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
return Transcript(
|
|
86
|
+
language=getattr(info, "language", None),
|
|
87
|
+
duration=_optional_float(getattr(info, "duration", None)),
|
|
88
|
+
segments=transcript_segments,
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _word_from_faster_whisper(word: Any) -> Word | None:
|
|
93
|
+
text = str(getattr(word, "word", "")).strip()
|
|
94
|
+
start = getattr(word, "start", None)
|
|
95
|
+
end = getattr(word, "end", None)
|
|
96
|
+
if not text or start is None or end is None:
|
|
97
|
+
return None
|
|
98
|
+
return Word(
|
|
99
|
+
text=text,
|
|
100
|
+
start=float(start),
|
|
101
|
+
end=float(end),
|
|
102
|
+
probability=_optional_float(getattr(word, "probability", None)),
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _beam_size(mode: str) -> int:
|
|
107
|
+
if mode == "fast":
|
|
108
|
+
return 1
|
|
109
|
+
if mode == "accurate":
|
|
110
|
+
return 5
|
|
111
|
+
return 3
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _resolve_device(device: str) -> str:
|
|
115
|
+
if device == "auto":
|
|
116
|
+
return "cpu"
|
|
117
|
+
return device
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _resolve_compute_type(device: str, compute_type: str) -> str:
|
|
121
|
+
if compute_type != "auto":
|
|
122
|
+
return compute_type
|
|
123
|
+
if device == "cuda":
|
|
124
|
+
return "float16"
|
|
125
|
+
return "int8"
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _optional_float(value: Any) -> float | None:
|
|
129
|
+
if value is None:
|
|
130
|
+
return None
|
|
131
|
+
return float(value)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Utility helpers."""
|