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/config.py
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
"""Typed configuration models and TOML loading helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import asdict, dataclass, field, fields, is_dataclass
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, Literal
|
|
8
|
+
|
|
9
|
+
try:
|
|
10
|
+
import tomllib
|
|
11
|
+
except ModuleNotFoundError: # pragma: no cover - covered on Python 3.10 only
|
|
12
|
+
import tomli as tomllib
|
|
13
|
+
|
|
14
|
+
CaptionPreset = Literal["shorts", "youtube", "podcast", "default"]
|
|
15
|
+
CaptionStyleName = Literal["clean", "bold", "pop", "minimal", "boxed", "shorts"]
|
|
16
|
+
ProcessingMode = Literal["fast", "balanced", "accurate"]
|
|
17
|
+
|
|
18
|
+
BUILT_IN_PRESETS = frozenset({"shorts", "youtube", "podcast", "default"})
|
|
19
|
+
BUILT_IN_STYLES = frozenset({"clean", "bold", "pop", "minimal", "boxed", "shorts"})
|
|
20
|
+
PROCESSING_MODES = frozenset({"fast", "balanced", "accurate"})
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True, slots=True)
|
|
24
|
+
class TranscriptionConfig:
|
|
25
|
+
model: str = "small"
|
|
26
|
+
mode: ProcessingMode = "balanced"
|
|
27
|
+
language: str | None = None
|
|
28
|
+
device: str = "auto"
|
|
29
|
+
compute_type: str = "auto"
|
|
30
|
+
|
|
31
|
+
def __post_init__(self) -> None:
|
|
32
|
+
_validate_non_empty("model", self.model)
|
|
33
|
+
_validate_choice("mode", self.mode, PROCESSING_MODES)
|
|
34
|
+
_validate_non_empty("device", self.device)
|
|
35
|
+
_validate_non_empty("compute_type", self.compute_type)
|
|
36
|
+
if self.language is not None:
|
|
37
|
+
_validate_non_empty("language", self.language)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True, slots=True)
|
|
41
|
+
class CaptionConfig:
|
|
42
|
+
preset: CaptionPreset = "shorts"
|
|
43
|
+
style: CaptionStyleName = "clean"
|
|
44
|
+
max_words: int = 5
|
|
45
|
+
max_lines: int = 2
|
|
46
|
+
min_caption_duration: float = 0.25
|
|
47
|
+
max_caption_duration: float = 2.5
|
|
48
|
+
|
|
49
|
+
def __post_init__(self) -> None:
|
|
50
|
+
_validate_choice("preset", self.preset, BUILT_IN_PRESETS)
|
|
51
|
+
_validate_choice("style", self.style, BUILT_IN_STYLES)
|
|
52
|
+
_validate_positive_int("max_words", self.max_words)
|
|
53
|
+
_validate_positive_int("max_lines", self.max_lines)
|
|
54
|
+
_validate_positive_number("min_caption_duration", self.min_caption_duration)
|
|
55
|
+
_validate_positive_number("max_caption_duration", self.max_caption_duration)
|
|
56
|
+
if self.max_caption_duration < self.min_caption_duration:
|
|
57
|
+
raise ValueError("max_caption_duration must be greater than min_caption_duration.")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass(frozen=True, slots=True)
|
|
61
|
+
class RenderConfig:
|
|
62
|
+
burn: bool = True
|
|
63
|
+
srt: bool = True
|
|
64
|
+
ass: bool = False
|
|
65
|
+
json: bool = False
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass(frozen=True, slots=True)
|
|
69
|
+
class BatchConfig:
|
|
70
|
+
recursive: bool = False
|
|
71
|
+
skip_existing: bool = True
|
|
72
|
+
overwrite: bool = False
|
|
73
|
+
jobs: int = 1
|
|
74
|
+
|
|
75
|
+
def __post_init__(self) -> None:
|
|
76
|
+
_validate_positive_int("jobs", self.jobs)
|
|
77
|
+
if self.skip_existing and self.overwrite:
|
|
78
|
+
raise ValueError("skip_existing and overwrite cannot both be true.")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass(frozen=True, slots=True)
|
|
82
|
+
class CutcapConfig:
|
|
83
|
+
transcription: TranscriptionConfig = field(default_factory=TranscriptionConfig)
|
|
84
|
+
caption: CaptionConfig = field(default_factory=CaptionConfig)
|
|
85
|
+
render: RenderConfig = field(default_factory=RenderConfig)
|
|
86
|
+
batch: BatchConfig = field(default_factory=BatchConfig)
|
|
87
|
+
output: Path | None = None
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def model(self) -> str:
|
|
91
|
+
return self.transcription.model
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def mode(self) -> ProcessingMode:
|
|
95
|
+
return self.transcription.mode
|
|
96
|
+
|
|
97
|
+
@property
|
|
98
|
+
def language(self) -> str | None:
|
|
99
|
+
return self.transcription.language
|
|
100
|
+
|
|
101
|
+
@property
|
|
102
|
+
def device(self) -> str:
|
|
103
|
+
return self.transcription.device
|
|
104
|
+
|
|
105
|
+
@property
|
|
106
|
+
def compute_type(self) -> str:
|
|
107
|
+
return self.transcription.compute_type
|
|
108
|
+
|
|
109
|
+
@property
|
|
110
|
+
def preset(self) -> CaptionPreset:
|
|
111
|
+
return self.caption.preset
|
|
112
|
+
|
|
113
|
+
@property
|
|
114
|
+
def style(self) -> CaptionStyleName:
|
|
115
|
+
return self.caption.style
|
|
116
|
+
|
|
117
|
+
@property
|
|
118
|
+
def write_srt(self) -> bool:
|
|
119
|
+
return self.render.srt
|
|
120
|
+
|
|
121
|
+
@property
|
|
122
|
+
def write_ass(self) -> bool:
|
|
123
|
+
return self.render.ass
|
|
124
|
+
|
|
125
|
+
@property
|
|
126
|
+
def write_json(self) -> bool:
|
|
127
|
+
return self.render.json
|
|
128
|
+
|
|
129
|
+
@property
|
|
130
|
+
def burn(self) -> bool:
|
|
131
|
+
return self.render.burn
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
CutcaptionConfig = CutcapConfig
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def load_config(path: Path | None) -> CutcapConfig:
|
|
138
|
+
"""Load a TOML config file, or return defaults when no path is provided."""
|
|
139
|
+
|
|
140
|
+
if path is None:
|
|
141
|
+
return CutcapConfig()
|
|
142
|
+
|
|
143
|
+
config_path = path.expanduser()
|
|
144
|
+
if not config_path.exists():
|
|
145
|
+
raise FileNotFoundError(f"Config file does not exist: {config_path}")
|
|
146
|
+
|
|
147
|
+
try:
|
|
148
|
+
data = tomllib.loads(config_path.read_text(encoding="utf-8"))
|
|
149
|
+
except tomllib.TOMLDecodeError as exc:
|
|
150
|
+
raise ValueError(f"Invalid TOML config '{config_path}': {exc}") from exc
|
|
151
|
+
|
|
152
|
+
if not isinstance(data, dict):
|
|
153
|
+
raise ValueError(f"Config file '{config_path}' must contain a TOML table.")
|
|
154
|
+
|
|
155
|
+
return _config_from_mapping(data, source=config_path)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def write_default_config(path: Path) -> None:
|
|
159
|
+
"""Write a readable default TOML config file."""
|
|
160
|
+
|
|
161
|
+
config_path = path.expanduser()
|
|
162
|
+
config_path.parent.mkdir(parents=True, exist_ok=True)
|
|
163
|
+
config_path.write_text(_render_default_toml(CutcapConfig()), encoding="utf-8")
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _config_from_mapping(data: dict[str, Any], *, source: Path) -> CutcapConfig:
|
|
167
|
+
allowed_sections = {"transcription", "caption", "render", "batch", "output"}
|
|
168
|
+
_reject_unknown_keys(data, allowed_sections, context=str(source))
|
|
169
|
+
|
|
170
|
+
output = data.get("output")
|
|
171
|
+
if output is not None and not isinstance(output, str):
|
|
172
|
+
raise ValueError("Config key 'output' must be a string path.")
|
|
173
|
+
|
|
174
|
+
return CutcapConfig(
|
|
175
|
+
transcription=_section_from_mapping(
|
|
176
|
+
TranscriptionConfig,
|
|
177
|
+
data.get("transcription", {}),
|
|
178
|
+
"transcription",
|
|
179
|
+
),
|
|
180
|
+
caption=_section_from_mapping(CaptionConfig, data.get("caption", {}), "caption"),
|
|
181
|
+
render=_section_from_mapping(RenderConfig, data.get("render", {}), "render"),
|
|
182
|
+
batch=_section_from_mapping(BatchConfig, data.get("batch", {}), "batch"),
|
|
183
|
+
output=Path(output).expanduser() if output else None,
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _section_from_mapping(model_type: type[Any], data: Any, section_name: str) -> Any:
|
|
188
|
+
if not isinstance(data, dict):
|
|
189
|
+
raise ValueError(f"Config section '{section_name}' must be a TOML table.")
|
|
190
|
+
|
|
191
|
+
allowed_keys = {field.name for field in fields(model_type)}
|
|
192
|
+
_reject_unknown_keys(data, allowed_keys, context=section_name)
|
|
193
|
+
if section_name == "transcription" and data.get("language") == "":
|
|
194
|
+
data = {**data, "language": None}
|
|
195
|
+
return model_type(**data)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _reject_unknown_keys(data: dict[str, Any], allowed_keys: set[str], *, context: str) -> None:
|
|
199
|
+
unknown_keys = sorted(set(data) - allowed_keys)
|
|
200
|
+
if unknown_keys:
|
|
201
|
+
keys = ", ".join(unknown_keys)
|
|
202
|
+
allowed = ", ".join(sorted(allowed_keys))
|
|
203
|
+
raise ValueError(f"Unknown config key in {context}: {keys}. Allowed keys: {allowed}.")
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _render_default_toml(config: CutcapConfig) -> str:
|
|
207
|
+
data = asdict(config)
|
|
208
|
+
lines = [
|
|
209
|
+
"# cutcaption configuration",
|
|
210
|
+
"# Defaults are tuned for short-form creator videos.",
|
|
211
|
+
"",
|
|
212
|
+
]
|
|
213
|
+
|
|
214
|
+
output = data.pop("output")
|
|
215
|
+
if output is not None:
|
|
216
|
+
lines.extend([f'output = "{output}"', ""])
|
|
217
|
+
|
|
218
|
+
for section_name in ("transcription", "caption", "render", "batch"):
|
|
219
|
+
section = data[section_name]
|
|
220
|
+
lines.append(f"[{section_name}]")
|
|
221
|
+
for key, value in section.items():
|
|
222
|
+
lines.append(f"{key} = {_toml_value(value)}")
|
|
223
|
+
lines.append("")
|
|
224
|
+
|
|
225
|
+
return "\n".join(lines)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _toml_value(value: Any) -> str:
|
|
229
|
+
if isinstance(value, bool):
|
|
230
|
+
return "true" if value else "false"
|
|
231
|
+
if isinstance(value, str):
|
|
232
|
+
return f'"{value}"'
|
|
233
|
+
if value is None:
|
|
234
|
+
return '"" # auto'
|
|
235
|
+
if is_dataclass(value):
|
|
236
|
+
raise TypeError("Nested dataclasses must be rendered as TOML sections.")
|
|
237
|
+
return str(value)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _validate_choice(name: str, value: str, allowed: frozenset[str]) -> None:
|
|
241
|
+
if value not in allowed:
|
|
242
|
+
choices = ", ".join(sorted(allowed))
|
|
243
|
+
raise ValueError(f"Unsupported {name} '{value}'. Choose one of: {choices}.")
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _validate_non_empty(name: str, value: str) -> None:
|
|
247
|
+
if not value.strip():
|
|
248
|
+
raise ValueError(f"{name} cannot be empty.")
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _validate_positive_int(name: str, value: int) -> None:
|
|
252
|
+
if not isinstance(value, int) or isinstance(value, bool) or value <= 0:
|
|
253
|
+
raise ValueError(f"{name} must be a positive integer.")
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _validate_positive_number(name: str, value: float) -> None:
|
|
257
|
+
if not isinstance(value, int | float) or isinstance(value, bool) or value <= 0:
|
|
258
|
+
raise ValueError(f"{name} must be a positive number.")
|
cutcaption/doctor.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""Environment checks for cutcaption."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib.util
|
|
6
|
+
import sys
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from uuid import uuid4
|
|
11
|
+
|
|
12
|
+
from cutcaption.utils.ffmpeg import executable_exists
|
|
13
|
+
|
|
14
|
+
FFMPEG_INSTALL_HINT = """Install ffmpeg:
|
|
15
|
+
macOS: brew install ffmpeg
|
|
16
|
+
Ubuntu/Debian: sudo apt install ffmpeg
|
|
17
|
+
Windows: winget install Gyan.FFmpeg"""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True, slots=True)
|
|
21
|
+
class DoctorCheck:
|
|
22
|
+
name: str
|
|
23
|
+
ok: bool
|
|
24
|
+
message: str
|
|
25
|
+
critical: bool = True
|
|
26
|
+
hint: str | None = None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def run_doctor_checks(cwd: Path | None = None) -> list[DoctorCheck]:
|
|
30
|
+
"""Run all environment checks without raising for missing dependencies."""
|
|
31
|
+
|
|
32
|
+
working_dir = cwd or Path.cwd()
|
|
33
|
+
checks = [
|
|
34
|
+
check_python_version(sys.version_info[:3]),
|
|
35
|
+
check_import("faster_whisper", "faster-whisper"),
|
|
36
|
+
check_import("pysubs2", "pysubs2"),
|
|
37
|
+
check_executable(
|
|
38
|
+
"ffmpeg",
|
|
39
|
+
missing_message="ffmpeg not found. Burning captions into video requires ffmpeg.",
|
|
40
|
+
found_message="ffmpeg found. Burned-in video output is available.",
|
|
41
|
+
hint=FFMPEG_INSTALL_HINT,
|
|
42
|
+
),
|
|
43
|
+
check_executable(
|
|
44
|
+
"ffprobe",
|
|
45
|
+
missing_message="ffprobe not found. Media probing requires ffprobe.",
|
|
46
|
+
found_message="ffprobe found. Media probing is available.",
|
|
47
|
+
hint=FFMPEG_INSTALL_HINT,
|
|
48
|
+
),
|
|
49
|
+
check_write_access(working_dir),
|
|
50
|
+
]
|
|
51
|
+
cuda_check = check_cuda_available()
|
|
52
|
+
if cuda_check is not None:
|
|
53
|
+
checks.append(cuda_check)
|
|
54
|
+
return checks
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def has_critical_failures(checks: list[DoctorCheck]) -> bool:
|
|
58
|
+
return any(check.critical and not check.ok for check in checks)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def check_python_version(version_info: tuple[int, int, int]) -> DoctorCheck:
|
|
62
|
+
version = ".".join(str(part) for part in version_info)
|
|
63
|
+
ok = version_info >= (3, 10, 0)
|
|
64
|
+
if ok:
|
|
65
|
+
return DoctorCheck("Python 3.10+", True, f"Python {version} is supported.")
|
|
66
|
+
return DoctorCheck(
|
|
67
|
+
"Python 3.10+",
|
|
68
|
+
False,
|
|
69
|
+
f"Python {version} is too old. cutcaption requires Python 3.10 or newer.",
|
|
70
|
+
hint="Install Python 3.10+ and rerun cutcaption in that environment.",
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def check_import(module_name: str, package_name: str) -> DoctorCheck:
|
|
75
|
+
if importlib.util.find_spec(module_name) is not None:
|
|
76
|
+
return DoctorCheck(package_name, True, f"{package_name} available.")
|
|
77
|
+
|
|
78
|
+
return DoctorCheck(
|
|
79
|
+
package_name,
|
|
80
|
+
False,
|
|
81
|
+
f"{package_name} not installed.",
|
|
82
|
+
hint=f"Install runtime dependencies with: python -m pip install {package_name}",
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def check_executable(
|
|
87
|
+
name: str,
|
|
88
|
+
*,
|
|
89
|
+
missing_message: str,
|
|
90
|
+
found_message: str,
|
|
91
|
+
hint: str,
|
|
92
|
+
exists: Callable[[str], bool] = executable_exists,
|
|
93
|
+
) -> DoctorCheck:
|
|
94
|
+
if exists(name):
|
|
95
|
+
return DoctorCheck(name, True, found_message)
|
|
96
|
+
return DoctorCheck(name, False, missing_message, hint=hint)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def check_write_access(directory: Path) -> DoctorCheck:
|
|
100
|
+
path = directory.expanduser()
|
|
101
|
+
test_path = path / f".cutcaption-doctor-{uuid4().hex}.tmp"
|
|
102
|
+
try:
|
|
103
|
+
test_path.write_text("ok", encoding="utf-8")
|
|
104
|
+
test_path.unlink()
|
|
105
|
+
except OSError as exc:
|
|
106
|
+
return DoctorCheck(
|
|
107
|
+
"Current directory writable",
|
|
108
|
+
False,
|
|
109
|
+
f"Cannot write to {path}: {exc.strerror or exc}.",
|
|
110
|
+
hint="Choose a writable folder or pass --output to a writable directory.",
|
|
111
|
+
)
|
|
112
|
+
return DoctorCheck("Current directory writable", True, f"Can write to {path}.")
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def check_cuda_available() -> DoctorCheck | None:
|
|
116
|
+
"""Best-effort optional CUDA detection.
|
|
117
|
+
|
|
118
|
+
CUDA is not required. If the local Python environment lacks common GPU
|
|
119
|
+
packages, omit this check instead of reporting a failure.
|
|
120
|
+
"""
|
|
121
|
+
|
|
122
|
+
torch_spec = importlib.util.find_spec("torch")
|
|
123
|
+
if torch_spec is None:
|
|
124
|
+
return None
|
|
125
|
+
|
|
126
|
+
try:
|
|
127
|
+
import torch
|
|
128
|
+
except Exception:
|
|
129
|
+
return DoctorCheck(
|
|
130
|
+
"CUDA",
|
|
131
|
+
False,
|
|
132
|
+
"Could not inspect CUDA through torch. CPU transcription can still work.",
|
|
133
|
+
critical=False,
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
if torch.cuda.is_available():
|
|
137
|
+
return DoctorCheck("CUDA", True, "CUDA appears available.", critical=False)
|
|
138
|
+
return DoctorCheck(
|
|
139
|
+
"CUDA",
|
|
140
|
+
False,
|
|
141
|
+
"CUDA not detected. CPU transcription can still work.",
|
|
142
|
+
critical=False,
|
|
143
|
+
)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Subtitle and metadata exporters."""
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""ASS subtitle exporter."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from cutcaption.config import RenderConfig
|
|
8
|
+
from cutcaption.models import Caption, Word
|
|
9
|
+
from cutcaption.styles import CaptionStyle, StyleConfig
|
|
10
|
+
|
|
11
|
+
PLAY_RES_X = 1080
|
|
12
|
+
PLAY_RES_Y = 1920
|
|
13
|
+
MARGIN_L = 80
|
|
14
|
+
MARGIN_R = 80
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def render_ass(captions: list[Caption] | tuple[Caption, ...], style: CaptionStyle) -> str:
|
|
18
|
+
events = [
|
|
19
|
+
"Dialogue: 0,"
|
|
20
|
+
f"{_ass_timestamp(start)},{_ass_timestamp(end)},Default,,0,0,0,,"
|
|
21
|
+
f"{_escape_ass(_style_text(text, style))}"
|
|
22
|
+
for text, start, end in _iter_events(captions, style)
|
|
23
|
+
]
|
|
24
|
+
border_style = 3 if style.box else 1
|
|
25
|
+
|
|
26
|
+
return (
|
|
27
|
+
"\n".join(
|
|
28
|
+
[
|
|
29
|
+
"[Script Info]",
|
|
30
|
+
"ScriptType: v4.00+",
|
|
31
|
+
"WrapStyle: 2",
|
|
32
|
+
"ScaledBorderAndShadow: yes",
|
|
33
|
+
f"PlayResX: {PLAY_RES_X}",
|
|
34
|
+
f"PlayResY: {PLAY_RES_Y}",
|
|
35
|
+
"",
|
|
36
|
+
"[V4+ Styles]",
|
|
37
|
+
"Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, "
|
|
38
|
+
"OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, "
|
|
39
|
+
"ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, "
|
|
40
|
+
"MarginL, MarginR, MarginV, Encoding",
|
|
41
|
+
f"Style: Default,{style.font_name},{style.font_size},{style.primary_color},"
|
|
42
|
+
f"{style.primary_color},{style.outline_color},{style.back_color},"
|
|
43
|
+
f"{-1 if style.bold else 0},{-1 if style.italic else 0},0,0,100,100,0,0,"
|
|
44
|
+
f"{border_style},{style.outline_width},{style.shadow},{style.alignment},"
|
|
45
|
+
f"{MARGIN_L},{MARGIN_R},{style.margin_v},1",
|
|
46
|
+
"",
|
|
47
|
+
"[Events]",
|
|
48
|
+
"Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text",
|
|
49
|
+
*events,
|
|
50
|
+
]
|
|
51
|
+
)
|
|
52
|
+
+ "\n"
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def write_ass(
|
|
57
|
+
captions: list[Caption],
|
|
58
|
+
path: Path,
|
|
59
|
+
style: StyleConfig,
|
|
60
|
+
render: RenderConfig,
|
|
61
|
+
) -> None:
|
|
62
|
+
del render
|
|
63
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
64
|
+
path.write_text(render_ass(captions, style), encoding="utf-8")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _iter_events(
|
|
68
|
+
captions: list[Caption] | tuple[Caption, ...],
|
|
69
|
+
style: CaptionStyle,
|
|
70
|
+
) -> list[tuple[str, float, float]]:
|
|
71
|
+
events: list[tuple[str, float, float]] = []
|
|
72
|
+
for caption in captions:
|
|
73
|
+
if style.one_word_at_a_time and caption.words:
|
|
74
|
+
events.extend(_word_events(caption.words))
|
|
75
|
+
else:
|
|
76
|
+
events.append((caption.text, caption.start, caption.end))
|
|
77
|
+
return events
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _word_events(words: list[Word]) -> list[tuple[str, float, float]]:
|
|
81
|
+
return [(word.text, word.start, word.end) for word in words]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _style_text(text: str, style: CaptionStyle) -> str:
|
|
85
|
+
return text.upper() if style.uppercase else text
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _ass_timestamp(seconds: float) -> str:
|
|
89
|
+
centiseconds = round(seconds * 100)
|
|
90
|
+
hours, remainder = divmod(centiseconds, 360_000)
|
|
91
|
+
minutes, remainder = divmod(remainder, 6_000)
|
|
92
|
+
whole_seconds, centiseconds = divmod(remainder, 100)
|
|
93
|
+
return f"{hours}:{minutes:02d}:{whole_seconds:02d}.{centiseconds:02d}"
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _escape_ass(text: str) -> str:
|
|
97
|
+
return text.replace("\\", r"\\").replace("{", r"\{").replace("}", r"\}")
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""JSON metadata exporter."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from cutcaption.models import Caption, Segment, Transcript, Word
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def render_json(
|
|
12
|
+
transcript: Transcript | list[Caption] | tuple[Caption, ...],
|
|
13
|
+
captions: list[Caption] | tuple[Caption, ...] | None = None,
|
|
14
|
+
) -> str:
|
|
15
|
+
if captions is None:
|
|
16
|
+
captions = transcript # Backward-compatible caption-only rendering.
|
|
17
|
+
transcript = Transcript()
|
|
18
|
+
|
|
19
|
+
payload = {
|
|
20
|
+
"transcript": _transcript_metadata(transcript),
|
|
21
|
+
"segments": [_segment_payload(segment) for segment in transcript.segments or []],
|
|
22
|
+
"captions": [_caption_payload(caption) for caption in captions],
|
|
23
|
+
}
|
|
24
|
+
return json.dumps(payload, indent=2) + "\n"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def write_json(transcript: Transcript, captions: list[Caption], path: Path) -> None:
|
|
28
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
29
|
+
path.write_text(render_json(transcript, captions), encoding="utf-8")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _transcript_metadata(transcript: Transcript) -> dict[str, object]:
|
|
33
|
+
return {
|
|
34
|
+
"language": transcript.language,
|
|
35
|
+
"duration": transcript.duration,
|
|
36
|
+
"word_count": len(transcript.words),
|
|
37
|
+
"segment_count": len(transcript.segments or []),
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _segment_payload(segment: Segment) -> dict[str, object]:
|
|
42
|
+
return {
|
|
43
|
+
"text": segment.text,
|
|
44
|
+
"start": segment.start,
|
|
45
|
+
"end": segment.end,
|
|
46
|
+
"words": [_word_payload(word) for word in segment.words],
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _caption_payload(caption: Caption) -> dict[str, object]:
|
|
51
|
+
return {
|
|
52
|
+
"text": caption.text,
|
|
53
|
+
"start": caption.start,
|
|
54
|
+
"end": caption.end,
|
|
55
|
+
"words": [_word_payload(word) for word in caption.words],
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _word_payload(word: Word) -> dict[str, object]:
|
|
60
|
+
payload: dict[str, object] = {
|
|
61
|
+
"text": word.text,
|
|
62
|
+
"start": word.start,
|
|
63
|
+
"end": word.end,
|
|
64
|
+
}
|
|
65
|
+
if word.probability is not None:
|
|
66
|
+
payload["probability"] = word.probability
|
|
67
|
+
return payload
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""SRT subtitle exporter."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import textwrap
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from cutcaption.models import Caption
|
|
9
|
+
|
|
10
|
+
DEFAULT_MAX_LINES = 2
|
|
11
|
+
DEFAULT_LINE_WIDTH = 42
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def render_srt(captions: list[Caption] | tuple[Caption, ...]) -> str:
|
|
15
|
+
blocks = []
|
|
16
|
+
for index, caption in enumerate(captions, start=1):
|
|
17
|
+
blocks.append(
|
|
18
|
+
"\n".join(
|
|
19
|
+
[
|
|
20
|
+
str(index),
|
|
21
|
+
f"{_srt_timestamp(caption.start)} --> {_srt_timestamp(caption.end)}",
|
|
22
|
+
_wrap_caption_text(caption.text),
|
|
23
|
+
]
|
|
24
|
+
)
|
|
25
|
+
)
|
|
26
|
+
return "\n\n".join(blocks) + ("\n" if blocks else "")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def write_srt(captions: list[Caption], path: Path) -> None:
|
|
30
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
31
|
+
path.write_text(render_srt(captions), encoding="utf-8")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _srt_timestamp(seconds: float) -> str:
|
|
35
|
+
milliseconds = round(seconds * 1000)
|
|
36
|
+
hours, remainder = divmod(milliseconds, 3_600_000)
|
|
37
|
+
minutes, remainder = divmod(remainder, 60_000)
|
|
38
|
+
whole_seconds, milliseconds = divmod(remainder, 1000)
|
|
39
|
+
return f"{hours:02d}:{minutes:02d}:{whole_seconds:02d},{milliseconds:03d}"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _wrap_caption_text(
|
|
43
|
+
text: str,
|
|
44
|
+
*,
|
|
45
|
+
max_lines: int = DEFAULT_MAX_LINES,
|
|
46
|
+
line_width: int = DEFAULT_LINE_WIDTH,
|
|
47
|
+
) -> str:
|
|
48
|
+
clean = " ".join(text.split())
|
|
49
|
+
if not clean:
|
|
50
|
+
return ""
|
|
51
|
+
|
|
52
|
+
wrapped = textwrap.wrap(
|
|
53
|
+
clean,
|
|
54
|
+
width=line_width,
|
|
55
|
+
break_long_words=False,
|
|
56
|
+
break_on_hyphens=False,
|
|
57
|
+
)
|
|
58
|
+
if len(wrapped) <= max_lines:
|
|
59
|
+
return "\n".join(wrapped)
|
|
60
|
+
|
|
61
|
+
return clean
|
cutcaption/media.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Media probing boundary."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from cutcaption.utils.ffmpeg import run_command
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def probe_duration(path: Path) -> float:
|
|
11
|
+
result = run_command(
|
|
12
|
+
[
|
|
13
|
+
"ffprobe",
|
|
14
|
+
"-v",
|
|
15
|
+
"error",
|
|
16
|
+
"-show_entries",
|
|
17
|
+
"format=duration",
|
|
18
|
+
"-of",
|
|
19
|
+
"default=noprint_wrappers=1:nokey=1",
|
|
20
|
+
str(path),
|
|
21
|
+
]
|
|
22
|
+
)
|
|
23
|
+
return float(result.stdout.strip())
|