subtitle-generator 3.0.0__tar.gz → 3.0.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/PKG-INFO +26 -1
  2. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/PYPI_README.md +25 -0
  3. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/docs/PACKAGING.md +20 -10
  4. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/pyproject.toml +1 -1
  5. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/subtitle_generator/__init__.py +1 -1
  6. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/subtitle_generator/cli/commands.py +92 -23
  7. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/subtitle_generator/core/batch_processor.py +13 -4
  8. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/subtitle_generator/core/subtitle_gen.py +6 -2
  9. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/subtitle_generator/core/transcriber.py +110 -56
  10. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/subtitle_generator/models/model_manager.py +40 -10
  11. subtitle_generator-3.0.2/subtitle_generator/utils/paths.py +199 -0
  12. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/subtitle_generator.egg-info/SOURCES.txt +1 -0
  13. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/CONTRIBUTING.md +0 -0
  14. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/LICENSE +0 -0
  15. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/MANIFEST.in +0 -0
  16. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/README.md +0 -0
  17. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/config/default.yaml +0 -0
  18. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/docs/API.md +0 -0
  19. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/docs/TROUBLESHOOTING.md +0 -0
  20. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/docs/example.md +0 -0
  21. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/environment.yml +0 -0
  22. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/requirements.txt +0 -0
  23. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/setup.cfg +0 -0
  24. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/setup.py +0 -0
  25. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/subtitle_generator/cli/__init__.py +0 -0
  26. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/subtitle_generator/config/__init__.py +0 -0
  27. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/subtitle_generator/config/config_loader.py +0 -0
  28. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/subtitle_generator/config/settings.py +0 -0
  29. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/subtitle_generator/core/__init__.py +0 -0
  30. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/subtitle_generator/core/async_processor.py +0 -0
  31. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/subtitle_generator/core/video_processor.py +0 -0
  32. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/subtitle_generator/models/__init__.py +0 -0
  33. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/subtitle_generator/utils/__init__.py +0 -0
  34. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/subtitle_generator/utils/downloader.py +0 -0
  35. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/subtitle_generator/utils/exceptions.py +0 -0
  36. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/subtitle_generator/utils/file_handler.py +0 -0
  37. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/subtitle_generator/utils/formatters.py +0 -0
  38. {subtitle_generator-3.0.0 → subtitle_generator-3.0.2}/subtitle_generator/utils/validators.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: subtitle-generator
3
- Version: 3.0.0
3
+ Version: 3.0.2
4
4
  Summary: AI-powered subtitle generation from video/audio using Whisper.
5
5
  Author-email: Ved Gupta <vedgupta@protonmail.com>
6
6
  Maintainer-email: Ved Gupta <vedgupta@protonmail.com>
@@ -67,6 +67,10 @@ pip install subtitle-generator
67
67
 
68
68
  ### Prerequisites
69
69
 
70
+ This package shells out to the [`whisper.cpp`](https://github.com/ggml-org/whisper.cpp)
71
+ `whisper-cli` binary. It is **not bundled in the wheel** (whisper.cpp is per-OS
72
+ native code), so you need to provide it once.
73
+
70
74
  - **FFmpeg** is required for video/audio processing:
71
75
  ```bash
72
76
  # macOS
@@ -79,6 +83,27 @@ pip install subtitle-generator
79
83
  choco install ffmpeg
80
84
  ```
81
85
 
86
+ - **whisper-cli** (the whisper.cpp transcription binary):
87
+ ```bash
88
+ # macOS (recommended — also adds the binary to your PATH)
89
+ brew install whisper-cpp
90
+
91
+ # Linux — build from source
92
+ git clone https://github.com/ggml-org/whisper.cpp
93
+ cd whisper.cpp && cmake -B build && cmake --build build --config Release
94
+ export SUBTITLE_WHISPER_BINARY="$(pwd)/build/bin/whisper-cli"
95
+
96
+ # Windows — download a prebuilt release
97
+ # https://github.com/ggml-org/whisper.cpp/releases
98
+ # then add the folder containing whisper-cli.exe to PATH
99
+ ```
100
+
101
+ The CLI auto-discovers the binary in this order:
102
+ 1. `--whisper-binary /path/to/whisper-cli`
103
+ 2. `SUBTITLE_WHISPER_BINARY` environment variable
104
+ 3. `whisper-cli` / `whisper-cpp` / `main` on your `PATH`
105
+ 4. `./binary/whisper-cli` relative to the current directory (legacy)
106
+
82
107
  ## Quick Start
83
108
 
84
109
  ```bash
@@ -22,6 +22,10 @@ pip install subtitle-generator
22
22
 
23
23
  ### Prerequisites
24
24
 
25
+ This package shells out to the [`whisper.cpp`](https://github.com/ggml-org/whisper.cpp)
26
+ `whisper-cli` binary. It is **not bundled in the wheel** (whisper.cpp is per-OS
27
+ native code), so you need to provide it once.
28
+
25
29
  - **FFmpeg** is required for video/audio processing:
26
30
  ```bash
27
31
  # macOS
@@ -34,6 +38,27 @@ pip install subtitle-generator
34
38
  choco install ffmpeg
35
39
  ```
36
40
 
41
+ - **whisper-cli** (the whisper.cpp transcription binary):
42
+ ```bash
43
+ # macOS (recommended — also adds the binary to your PATH)
44
+ brew install whisper-cpp
45
+
46
+ # Linux — build from source
47
+ git clone https://github.com/ggml-org/whisper.cpp
48
+ cd whisper.cpp && cmake -B build && cmake --build build --config Release
49
+ export SUBTITLE_WHISPER_BINARY="$(pwd)/build/bin/whisper-cli"
50
+
51
+ # Windows — download a prebuilt release
52
+ # https://github.com/ggml-org/whisper.cpp/releases
53
+ # then add the folder containing whisper-cli.exe to PATH
54
+ ```
55
+
56
+ The CLI auto-discovers the binary in this order:
57
+ 1. `--whisper-binary /path/to/whisper-cli`
58
+ 2. `SUBTITLE_WHISPER_BINARY` environment variable
59
+ 3. `whisper-cli` / `whisper-cpp` / `main` on your `PATH`
60
+ 4. `./binary/whisper-cli` relative to the current directory (legacy)
61
+
37
62
  ## Quick Start
38
63
 
39
64
  ```bash
@@ -20,10 +20,10 @@ pip install -e ".[dev]"
20
20
 
21
21
  | Package | Purpose | Used In |
22
22
  |---------|---------|---------|
23
- | `ffmpeg-python` | Video/audio processing | `src/core/video_processor.py` |
24
- | `tqdm` | Progress bars | `src/models/model_manager.py`, `src/utils/downloader.py` |
25
- | `pyyaml` | Config loading | `src/config/config_loader.py` |
26
- | `gdown` | Google Drive downloads | `src/utils/downloader.py` (lazy import) |
23
+ | `ffmpeg-python` | Video/audio processing | `subtitle_generator/core/video_processor.py` |
24
+ | `tqdm` | Progress bars | `subtitle_generator/models/model_manager.py`, `subtitle_generator/utils/downloader.py` |
25
+ | `pyyaml` | Config loading | `subtitle_generator/config/config_loader.py` |
26
+ | `gdown` | Google Drive downloads | `subtitle_generator/utils/downloader.py` (lazy import) |
27
27
 
28
28
  ### Optional: Dev Dependencies
29
29
  ```bash
@@ -43,15 +43,25 @@ subtitle batch --input-dir /dir # Batch process videos
43
43
 
44
44
  ## Publishing to PyPI
45
45
 
46
+ The recommended path is the automated GitHub Actions release pipeline (see
47
+ [CHANGELOG.md](../CHANGELOG.md) for the full flow):
48
+
46
49
  ```bash
47
- # 1. Install build tools
48
- pip install build twine
50
+ # 1. Bump `version` in pyproject.toml.
51
+ # 2. Commit and push, then push a matching tag:
52
+ git commit -am "Bump version to X.Y.Z"
53
+ git push origin master
54
+ git tag -a vX.Y.Z -m "Release X.Y.Z"
55
+ git push origin vX.Y.Z
56
+ # GitHub Actions runs cross-OS tests, builds, and publishes automatically.
57
+ ```
49
58
 
50
- # 2. Build distribution
51
- python -m build
59
+ Manual publishing (only if the workflow is unavailable):
52
60
 
53
- # 3. Upload to PyPI
54
- twine upload dist/*
61
+ ```bash
62
+ pip install build twine
63
+ python -m build
64
+ TWINE_USERNAME=__token__ TWINE_PASSWORD='pypi-...' twine upload dist/*
55
65
  ```
56
66
 
57
67
  ## Configuration Files
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "subtitle-generator"
7
- version = "3.0.0"
7
+ version = "3.0.2"
8
8
  description = "AI-powered subtitle generation from video/audio using Whisper."
9
9
  readme = "PYPI_README.md"
10
10
  license = {text = "MIT"}
@@ -5,4 +5,4 @@ A clean, modular subtitle generation system using Whisper.cpp
5
5
  with proper separation of concerns and design patterns.
6
6
  """
7
7
 
8
- __version__ = "2.0.2"
8
+ __version__ = "3.0.2"
@@ -17,7 +17,9 @@ from ..core.video_processor import VideoProcessor
17
17
  from ..core.batch_processor import BatchProcessor
18
18
  from ..models import ModelManager
19
19
  from ..utils.downloader import is_url, download_file
20
+ from ..utils.exceptions import TranscriptionError
20
21
  from ..utils.file_handler import sanitize_filename, file_exists, directory_exists
22
+ from ..utils.paths import default_output_dir
21
23
  from ..utils.validators import (
22
24
  validate_media_path,
23
25
  validate_model_name,
@@ -128,9 +130,19 @@ class SilentProgressObserver(ProgressObserver):
128
130
  class SubtitleCLI:
129
131
  """Command-line interface for subtitle generation."""
130
132
 
131
- def __init__(self, observer: Optional[ProgressObserver] = None):
133
+ def __init__(
134
+ self,
135
+ observer: Optional[ProgressObserver] = None,
136
+ models_dir: Optional[str] = None,
137
+ whisper_binary: Optional[str] = None,
138
+ ):
132
139
  self.observer = observer or ConsoleProgressObserver()
133
- self.model_manager = ModelManager()
140
+ # `whisper_binary` is plumbed through to `WhisperCppTranscriber` so
141
+ # users can override the binary location via --whisper-binary or
142
+ # SUBTITLE_WHISPER_BINARY. `models_dir` is plumbed through to
143
+ # `ModelManager` so models can be cached anywhere the user prefers.
144
+ self.whisper_binary = whisper_binary
145
+ self.model_manager = ModelManager(models_dir=models_dir)
134
146
 
135
147
  def run(self, args: argparse.Namespace) -> int:
136
148
  """Run the CLI with parsed arguments."""
@@ -200,21 +212,29 @@ class SubtitleCLI:
200
212
  self.observer.on_error(error)
201
213
  return 1
202
214
 
203
- # Create transcriber and generator
204
- transcriber = WhisperCppTranscriber(
205
- threads=args.threads,
206
- processors=args.processors,
207
- )
215
+ # Create transcriber and generator. Binary discovery happens here
216
+ # (not in ModelManager / SubtitleGenerator) so that a misconfiguration
217
+ # surfaces with a clear, actionable message before we waste time
218
+ # downloading models.
219
+ try:
220
+ transcriber = WhisperCppTranscriber(
221
+ binary_path=self.whisper_binary,
222
+ threads=args.threads,
223
+ processors=args.processors,
224
+ )
225
+ except TranscriptionError as e:
226
+ self.observer.on_error(str(e))
227
+ return 1
208
228
  generator = SubtitleGenerator(transcriber, self.model_manager)
209
-
210
- # Generate subtitles
229
+
211
230
  def progress_callback(stage: str, progress: float):
212
231
  self.observer.on_progress(stage, progress)
213
-
232
+
214
233
  subtitle_path, success = generator.generate_and_rename(
215
234
  input_path=filepath,
216
235
  model_name=model,
217
236
  output_format=output_format,
237
+ output_dir=default_output_dir(),
218
238
  progress_callback=progress_callback,
219
239
  )
220
240
 
@@ -309,12 +329,13 @@ class SubtitleCLI:
309
329
  self.observer.on_error(error)
310
330
  return 1
311
331
 
312
- # Create batch processor
313
332
  processor = BatchProcessor(
314
333
  workers=workers,
315
334
  model=model,
316
335
  output_format=output_format,
317
336
  extensions=extensions,
337
+ whisper_binary=self.whisper_binary,
338
+ models_dir=self.model_manager.models_dir,
318
339
  )
319
340
 
320
341
  # Find files first to show count
@@ -427,7 +448,28 @@ Examples:
427
448
  action="store_true",
428
449
  help="Verbose output",
429
450
  )
430
-
451
+ parser.add_argument(
452
+ "--whisper-binary",
453
+ type=str,
454
+ default=None,
455
+ metavar="PATH",
456
+ help=(
457
+ "Path to the whisper-cli binary. Overrides the "
458
+ "SUBTITLE_WHISPER_BINARY env var and PATH lookup."
459
+ ),
460
+ )
461
+ parser.add_argument(
462
+ "--models-dir",
463
+ type=str,
464
+ default=None,
465
+ metavar="DIR",
466
+ help=(
467
+ "Directory used to cache downloaded Whisper models. "
468
+ "Defaults to a per-OS user cache (e.g. "
469
+ "~/Library/Caches/subtitle-generator on macOS)."
470
+ ),
471
+ )
472
+
431
473
  return parser
432
474
 
433
475
 
@@ -448,6 +490,13 @@ def create_models_parser() -> argparse.ArgumentParser:
448
490
  metavar="MODEL",
449
491
  help="Download a model",
450
492
  )
493
+ parser.add_argument(
494
+ "--models-dir",
495
+ type=str,
496
+ default=None,
497
+ metavar="DIR",
498
+ help="Directory used to cache downloaded Whisper models",
499
+ )
451
500
  return parser
452
501
 
453
502
 
@@ -505,6 +554,20 @@ Examples:
505
554
  default=None,
506
555
  help="Comma-separated video extensions (default: mp4,mkv,avi,mov,webm)",
507
556
  )
557
+ parser.add_argument(
558
+ "--whisper-binary",
559
+ type=str,
560
+ default=None,
561
+ metavar="PATH",
562
+ help="Path to the whisper-cli binary (overrides env / PATH lookup)",
563
+ )
564
+ parser.add_argument(
565
+ "--models-dir",
566
+ type=str,
567
+ default=None,
568
+ metavar="DIR",
569
+ help="Directory used to cache downloaded Whisper models",
570
+ )
508
571
  return parser
509
572
 
510
573
 
@@ -519,36 +582,42 @@ def main(args: Optional[list[str]] = None) -> int:
519
582
  parsed_args = parser.parse_args(args[1:])
520
583
  parsed_args.command = "models"
521
584
  observer = ConsoleProgressObserver()
522
- cli = SubtitleCLI(observer)
585
+ cli = SubtitleCLI(observer, models_dir=parsed_args.models_dir)
523
586
  return cli.run(parsed_args)
524
-
587
+
525
588
  if args and args[0] == "formats":
526
589
  cli = SubtitleCLI()
527
590
  return cli._handle_formats_command()
528
-
591
+
529
592
  if args and args[0] == "batch":
530
593
  parser = create_batch_parser()
531
594
  parsed_args = parser.parse_args(args[1:])
532
595
  parsed_args.command = "batch"
533
596
  observer = ConsoleProgressObserver()
534
- cli = SubtitleCLI(observer)
597
+ cli = SubtitleCLI(
598
+ observer,
599
+ models_dir=parsed_args.models_dir,
600
+ whisper_binary=parsed_args.whisper_binary,
601
+ )
535
602
  return cli.run(parsed_args)
536
-
603
+
537
604
  # Main parser for video processing
538
605
  parser = create_main_parser()
539
606
  parsed_args = parser.parse_args(args)
540
607
  parsed_args.command = None
541
-
608
+
542
609
  # Show help if no arguments
543
610
  if parsed_args.filepath is None:
544
611
  parser.print_help()
545
612
  return 0
546
-
547
- # Set up observer
613
+
548
614
  observer = ConsoleProgressObserver(verbose=parsed_args.verbose)
549
-
550
- # Run CLI
551
- cli = SubtitleCLI(observer)
615
+
616
+ cli = SubtitleCLI(
617
+ observer,
618
+ models_dir=parsed_args.models_dir,
619
+ whisper_binary=parsed_args.whisper_binary,
620
+ )
552
621
  return cli.run(parsed_args)
553
622
 
554
623
 
@@ -150,20 +150,27 @@ class BatchProcessor:
150
150
  model: str = "base",
151
151
  output_format: str = "vtt",
152
152
  extensions: Optional[list[str]] = None,
153
+ whisper_binary: Optional[str] = None,
154
+ models_dir: Optional[str] = None,
153
155
  ):
154
156
  """
155
157
  Initialize the batch processor.
156
-
158
+
157
159
  Args:
158
160
  workers: Number of parallel workers
159
161
  model: Whisper model to use
160
162
  output_format: Output subtitle format
161
163
  extensions: Video file extensions to process
164
+ whisper_binary: Optional override for the whisper-cli binary path.
165
+ Falls back to env / PATH discovery (see ``utils.paths``).
166
+ models_dir: Optional override for the models cache directory.
162
167
  """
163
168
  self.workers = max(1, workers)
164
169
  self.model = model
165
170
  self.output_format = output_format
166
171
  self.extensions = extensions or DEFAULT_VIDEO_EXTENSIONS
172
+ self.whisper_binary = whisper_binary
173
+ self.models_dir = models_dir
167
174
 
168
175
  def find_video_files(self, input_dir: str) -> list[str]:
169
176
  """
@@ -330,9 +337,11 @@ class BatchProcessor:
330
337
  from .subtitle_gen import SubtitleGenerator
331
338
  from ..models import ModelManager
332
339
 
333
- # Create generator
334
- transcriber = WhisperCppTranscriber()
335
- model_manager = ModelManager()
340
+ # Create generator. We pass through the user-supplied (or
341
+ # env-derived) overrides so each batch worker resolves the same
342
+ # binary / models cache as the parent CLI invocation.
343
+ transcriber = WhisperCppTranscriber(binary_path=self.whisper_binary)
344
+ model_manager = ModelManager(models_dir=self.models_dir)
336
345
  generator = SubtitleGenerator(transcriber, model_manager)
337
346
 
338
347
  # Generate subtitles
@@ -102,17 +102,20 @@ class SubtitleGenerator:
102
102
  input_path: str,
103
103
  model_name: str = "base",
104
104
  output_format: str = "vtt",
105
+ output_dir: str = "data",
105
106
  progress_callback: Optional[Callable[[str, float], None]] = None,
106
107
  ) -> tuple[str, bool]:
107
108
  """
108
109
  Generate subtitles and rename output to match input filename.
109
-
110
+
110
111
  Args:
111
112
  input_path: Path to input audio/video file
112
113
  model_name: Name of the model to use
113
114
  output_format: Output subtitle format
115
+ output_dir: Directory for the transient transcription output
116
+ (the file is renamed next to ``input_path`` afterwards).
114
117
  progress_callback: Optional callback for progress updates
115
-
118
+
116
119
  Returns:
117
120
  Tuple of (output_path, success)
118
121
  """
@@ -120,6 +123,7 @@ class SubtitleGenerator:
120
123
  input_path=input_path,
121
124
  model_name=model_name,
122
125
  output_format=output_format,
126
+ output_dir=output_dir,
123
127
  progress_callback=progress_callback,
124
128
  )
125
129
 
@@ -13,13 +13,19 @@ from abc import ABC, abstractmethod
13
13
  from dataclasses import dataclass
14
14
  from typing import Optional, Callable
15
15
 
16
+ from ..utils.exceptions import TranscriptionError
17
+ from ..utils.paths import (
18
+ find_whisper_binary,
19
+ whisper_binary_install_hint,
20
+ )
21
+
16
22
  logger = logging.getLogger(__name__)
17
23
 
18
24
 
19
25
  @dataclass
20
26
  class TranscriptionResult:
21
27
  """Result of a transcription operation."""
22
-
28
+
23
29
  process_id: str
24
30
  input_path: str
25
31
  output_path: str
@@ -30,7 +36,7 @@ class TranscriptionResult:
30
36
 
31
37
  class TranscriberStrategy(ABC):
32
38
  """Abstract base class for transcription strategies."""
33
-
39
+
34
40
  @abstractmethod
35
41
  def transcribe(
36
42
  self,
@@ -42,19 +48,19 @@ class TranscriberStrategy(ABC):
42
48
  ) -> TranscriptionResult:
43
49
  """
44
50
  Transcribe audio/video file to subtitles.
45
-
51
+
46
52
  Args:
47
53
  input_path: Path to input audio/video file
48
54
  model_path: Path to the model file
49
55
  output_format: Output subtitle format (vtt, srt, etc.)
50
56
  output_dir: Directory to write output files
51
57
  progress_callback: Optional callback for progress updates
52
-
58
+
53
59
  Returns:
54
60
  TranscriptionResult with transcription details
55
61
  """
56
62
  pass
57
-
63
+
58
64
  @abstractmethod
59
65
  def get_supported_formats(self) -> list[str]:
60
66
  """Return list of supported output formats."""
@@ -63,29 +69,57 @@ class TranscriberStrategy(ABC):
63
69
 
64
70
  class WhisperCppTranscriber(TranscriberStrategy):
65
71
  """Whisper.cpp binary-based transcription implementation."""
66
-
72
+
73
+ # Map subtitle format to whisper.cpp output flag.
74
+ _FORMAT_FLAGS = {
75
+ "vtt": "-ovtt",
76
+ "srt": "-osrt",
77
+ "txt": "-otxt",
78
+ "json": "-oj",
79
+ "lrc": "-olrc",
80
+ }
81
+
67
82
  def __init__(
68
83
  self,
69
- binary_path: str = "./binary/whisper-cli",
84
+ binary_path: Optional[str] = None,
70
85
  threads: int = 4,
71
86
  processors: int = 1,
72
87
  ):
73
88
  """
74
89
  Initialize Whisper.cpp transcriber.
75
-
90
+
76
91
  Args:
77
- binary_path: Path to whisper-cli binary
92
+ binary_path: Optional explicit path to the whisper-cli binary.
93
+ When ``None`` (the default), the binary is discovered at
94
+ instantiation time via :func:`utils.paths.find_whisper_binary`,
95
+ which checks the ``SUBTITLE_WHISPER_BINARY`` env var, ``PATH``,
96
+ and the legacy ``./binary/whisper-cli`` checkout layout.
78
97
  threads: Number of threads to use
79
98
  processors: Number of processors to use
99
+
100
+ Raises:
101
+ TranscriptionError: If the whisper-cli binary cannot be located.
102
+ The error includes OS-specific install instructions so the
103
+ user can fix it without reading source code.
80
104
  """
81
- self.binary_path = binary_path
105
+ resolved = find_whisper_binary(binary_path)
106
+ if not resolved:
107
+ raise TranscriptionError(
108
+ whisper_binary_install_hint(),
109
+ details={
110
+ "explicit_binary_path": binary_path,
111
+ "cwd": os.getcwd(),
112
+ },
113
+ )
114
+ self.binary_path = resolved
82
115
  self.threads = threads
83
116
  self.processors = processors
84
-
117
+ logger.debug("Using whisper-cli binary at: %s", self.binary_path)
118
+
85
119
  def get_supported_formats(self) -> list[str]:
86
120
  """Return list of supported output formats."""
87
- return ["vtt", "srt", "txt", "json", "lrc"]
88
-
121
+ return list(self._FORMAT_FLAGS.keys())
122
+
89
123
  def transcribe(
90
124
  self,
91
125
  input_path: str,
@@ -96,64 +130,69 @@ class WhisperCppTranscriber(TranscriberStrategy):
96
130
  ) -> TranscriptionResult:
97
131
  """
98
132
  Transcribe using Whisper.cpp binary.
99
-
133
+
100
134
  Args:
101
135
  input_path: Path to input audio/video file
102
136
  model_path: Path to the model file
103
137
  output_format: Output subtitle format
104
138
  output_dir: Directory to write output files
105
139
  progress_callback: Optional callback for progress updates
106
-
140
+
107
141
  Returns:
108
142
  TranscriptionResult with transcription details
109
143
  """
110
144
  process_id = str(uuid.uuid4())
111
-
112
- # Ensure output directory exists
145
+
113
146
  os.makedirs(output_dir, exist_ok=True)
114
-
115
- # Build output path (without extension - whisper adds it)
147
+
148
+ # whisper.cpp appends the format extension itself, so pass a
149
+ # base path without one.
116
150
  output_base = os.path.join(output_dir, process_id)
117
-
118
- # Map format to whisper.cpp output flag
119
- format_flags = {
120
- "vtt": "-ovtt",
121
- "srt": "-osrt",
122
- "txt": "-otxt",
123
- "json": "-oj",
124
- "lrc": "-olrc",
125
- }
126
-
127
- output_flag = format_flags.get(output_format, "-ovtt")
128
- actual_format = output_format if output_format in format_flags else "vtt"
129
-
130
- # Build command
131
- command = (
132
- f"{self.binary_path} "
133
- f"-t {self.threads} "
134
- f"-p {self.processors} "
135
- f"-m {model_path} "
136
- f"-vi " # Video input mode
137
- f"-f {input_path} "
138
- f"{output_flag} "
139
- f"-of {output_base}"
140
- )
141
-
151
+
152
+ output_flag = self._FORMAT_FLAGS.get(output_format, "-ovtt")
153
+ actual_format = output_format if output_format in self._FORMAT_FLAGS else "vtt"
154
+
155
+ # Use an argv list rather than `shell=True`. This eliminates a class
156
+ # of injection / quoting bugs on filenames containing spaces, quotes,
157
+ # or shell metacharacters (the previous f-string version broke on
158
+ # those) and complies with the project's secure-shell-execution rule.
159
+ argv = [
160
+ self.binary_path,
161
+ "-t",
162
+ str(self.threads),
163
+ "-p",
164
+ str(self.processors),
165
+ "-m",
166
+ model_path,
167
+ "-vi", # video input mode
168
+ "-f",
169
+ input_path,
170
+ output_flag,
171
+ "-of",
172
+ output_base,
173
+ ]
174
+
142
175
  if progress_callback:
143
176
  progress_callback("transcribing", 0.0)
144
-
177
+
145
178
  try:
146
- logger.info(f"Running transcription: {command}")
147
- result = subprocess.check_output(
148
- command, shell=True, stderr=subprocess.STDOUT
179
+ logger.info("Running transcription: %s", " ".join(argv))
180
+ completed = subprocess.run(
181
+ argv,
182
+ check=True,
183
+ capture_output=True,
149
184
  )
150
- logger.debug(f"Transcription output: {result.decode('utf-8')}")
151
-
185
+ if completed.stdout:
186
+ logger.debug(
187
+ "Transcription stdout: %s",
188
+ completed.stdout.decode("utf-8", errors="replace"),
189
+ )
190
+
152
191
  if progress_callback:
153
192
  progress_callback("transcribing", 1.0)
154
-
193
+
155
194
  output_path = f"{output_base}.{actual_format}"
156
-
195
+
157
196
  return TranscriptionResult(
158
197
  process_id=process_id,
159
198
  input_path=input_path,
@@ -161,11 +200,26 @@ class WhisperCppTranscriber(TranscriberStrategy):
161
200
  format=actual_format,
162
201
  success=True,
163
202
  )
164
-
203
+
204
+ except FileNotFoundError as e:
205
+ # The binary path was valid at construction time but disappeared
206
+ # between then and now (e.g. user uninstalled). Surface the same
207
+ # actionable hint.
208
+ logger.error("Transcription failed: %s", e)
209
+ return TranscriptionResult(
210
+ process_id=process_id,
211
+ input_path=input_path,
212
+ output_path="",
213
+ format=actual_format,
214
+ success=False,
215
+ error=whisper_binary_install_hint(),
216
+ )
165
217
  except subprocess.CalledProcessError as e:
166
- error_msg = e.output.decode("utf-8").strip() if e.output else str(e)
167
- logger.error(f"Transcription failed: {error_msg}")
168
-
218
+ stderr = (e.stderr or b"").decode("utf-8", errors="replace").strip()
219
+ stdout = (e.stdout or b"").decode("utf-8", errors="replace").strip()
220
+ error_msg = stderr or stdout or str(e)
221
+ logger.error("Transcription failed: %s", error_msg)
222
+
169
223
  return TranscriptionResult(
170
224
  process_id=process_id,
171
225
  input_path=input_path,
@@ -59,7 +59,7 @@ class ModelManager:
59
59
  DEFAULT_SOURCE = "https://huggingface.co/ggerganov/whisper.cpp"
60
60
  TDRZ_SOURCE = "https://huggingface.co/akashmjn/tinydiarize-whisper.cpp"
61
61
 
62
- def __new__(cls, models_dir: str = "models"):
62
+ def __new__(cls, models_dir: Optional[str] = None):
63
63
  """Create or return singleton instance."""
64
64
  if cls._instance is None:
65
65
  with cls._lock:
@@ -69,25 +69,55 @@ class ModelManager:
69
69
  instance._initialized = False
70
70
  cls._instance = instance
71
71
  return cls._instance
72
-
73
- def __init__(self, models_dir: str = "models"):
72
+
73
+ def __init__(self, models_dir: Optional[str] = None):
74
74
  """
75
75
  Initialize model manager.
76
-
76
+
77
77
  Args:
78
- models_dir: Directory to store models
78
+ models_dir: Directory to store models. When ``None`` (the default),
79
+ a writable per-OS user cache directory is used (see
80
+ :func:`utils.paths.default_models_dir`). This avoids dumping
81
+ downloaded models into the user's current working directory
82
+ when the package is installed via pip.
79
83
  """
80
84
  if self._initialized:
81
85
  return
82
-
83
- self.models_dir = models_dir
86
+
87
+ # Late import to keep this module importable even if utils.paths is
88
+ # being refactored or stubbed in tests.
89
+ from ..utils.paths import default_models_dir
90
+
91
+ self.models_dir = models_dir if models_dir else default_models_dir()
84
92
  self._ensure_models_dir()
85
93
  self._initialized = True
86
- logger.info(f"ModelManager initialized with models_dir: {models_dir}")
94
+ logger.info(f"ModelManager initialized with models_dir: {self.models_dir}")
87
95
 
88
96
  def _ensure_models_dir(self):
89
- """Ensure models directory exists."""
90
- os.makedirs(self.models_dir, exist_ok=True)
97
+ """Ensure models directory exists.
98
+
99
+ Falls back to the per-OS default if the explicitly requested
100
+ directory cannot be created (e.g. read-only filesystem). This makes
101
+ the CLI more resilient when run from places like /usr/local/bin or
102
+ a Docker working dir mounted read-only.
103
+ """
104
+ try:
105
+ os.makedirs(self.models_dir, exist_ok=True)
106
+ except OSError as e:
107
+ from ..utils.paths import default_models_dir
108
+
109
+ fallback = default_models_dir()
110
+ if fallback != self.models_dir:
111
+ logger.warning(
112
+ "Cannot create models dir %s (%s); falling back to %s",
113
+ self.models_dir,
114
+ e,
115
+ fallback,
116
+ )
117
+ self.models_dir = fallback
118
+ os.makedirs(self.models_dir, exist_ok=True)
119
+ else:
120
+ raise
91
121
 
92
122
  def get_model(self, name: str) -> str:
93
123
  """
@@ -0,0 +1,199 @@
1
+ """
2
+ Cross-platform filesystem path resolution for binaries and caches.
3
+
4
+ Centralises the logic for:
5
+ * locating the `whisper-cli` binary at runtime (no hardcoded relative paths)
6
+ * choosing a writable, OS-appropriate cache directory for downloaded models
7
+
8
+ Both are designed to work whether the package is installed via pip, run from a
9
+ git checkout, or invoked from an arbitrary CWD.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import logging
15
+ import os
16
+ import shutil
17
+ import sys
18
+ from typing import Optional
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ # Environment variables that let users override defaults without code changes.
24
+ ENV_WHISPER_BINARY = "SUBTITLE_WHISPER_BINARY"
25
+ ENV_MODELS_DIR = "SUBTITLE_MODELS_DIR"
26
+
27
+ # Names that whisper.cpp ships its CLI under across releases / package managers.
28
+ # Order matters: we prefer the canonical upstream name first.
29
+ _WHISPER_BINARY_NAMES = ("whisper-cli", "whisper-cpp", "main")
30
+
31
+
32
+ def _is_executable_file(path: str) -> bool:
33
+ """Return True if `path` exists, is a regular file, and is executable."""
34
+ try:
35
+ return os.path.isfile(path) and os.access(path, os.X_OK)
36
+ except OSError:
37
+ return False
38
+
39
+
40
+ def _candidate_with_exe(path: str) -> str:
41
+ """On Windows, append `.exe` if the path doesn't already end with it.
42
+
43
+ Returns the original path on non-Windows or if `.exe` is already present.
44
+ """
45
+ if sys.platform != "win32":
46
+ return path
47
+ if path.lower().endswith(".exe"):
48
+ return path
49
+ return path + ".exe"
50
+
51
+
52
+ def find_whisper_binary(explicit: Optional[str] = None) -> Optional[str]:
53
+ """Resolve the path to the whisper.cpp CLI binary.
54
+
55
+ Lookup order (first hit wins):
56
+ 1. `explicit` argument (e.g. from a CLI flag).
57
+ 2. The ``SUBTITLE_WHISPER_BINARY`` environment variable.
58
+ 3. ``shutil.which`` against known binary names. This picks up
59
+ Homebrew installs (``brew install whisper-cpp``), system packages,
60
+ and anything the user added to ``PATH``.
61
+ 4. A legacy ``./binary/whisper-cli`` (or ``.exe`` on Windows) relative
62
+ to the current working directory. This preserves backwards
63
+ compatibility with this project's own ``setup_whisper.sh`` layout.
64
+
65
+ Returns the absolute path to an executable, or ``None`` if no candidate
66
+ is found. Callers are expected to surface a helpful error in the latter
67
+ case (see :func:`whisper_binary_install_hint`).
68
+ """
69
+
70
+ def _normalise(p: str) -> Optional[str]:
71
+ # Expand ~ and turn into an absolute path so downstream argv calls
72
+ # are unambiguous regardless of subsequent CWD changes.
73
+ p = os.path.abspath(os.path.expanduser(p))
74
+ if _is_executable_file(p):
75
+ return p
76
+ win_p = _candidate_with_exe(p)
77
+ if win_p != p and _is_executable_file(win_p):
78
+ return win_p
79
+ return None
80
+
81
+ if explicit:
82
+ resolved = _normalise(explicit)
83
+ if resolved:
84
+ return resolved
85
+ logger.debug("Explicit whisper binary path %r not usable", explicit)
86
+
87
+ env_value = os.environ.get(ENV_WHISPER_BINARY)
88
+ if env_value:
89
+ resolved = _normalise(env_value)
90
+ if resolved:
91
+ return resolved
92
+ logger.warning(
93
+ "%s=%r is set but does not point to an executable file",
94
+ ENV_WHISPER_BINARY,
95
+ env_value,
96
+ )
97
+
98
+ for name in _WHISPER_BINARY_NAMES:
99
+ # `shutil.which` already handles PATHEXT (.exe) on Windows.
100
+ on_path = shutil.which(name)
101
+ if on_path and _is_executable_file(on_path):
102
+ return os.path.abspath(on_path)
103
+
104
+ legacy = os.path.join(os.getcwd(), "binary", "whisper-cli")
105
+ resolved = _normalise(legacy)
106
+ if resolved:
107
+ return resolved
108
+
109
+ return None
110
+
111
+
112
+ def whisper_binary_install_hint() -> str:
113
+ """Return a user-facing string explaining how to obtain whisper-cli.
114
+
115
+ Tailored per-OS so the error a user sees in their terminal is
116
+ actionable rather than generic.
117
+ """
118
+ common = (
119
+ "\n - Set the SUBTITLE_WHISPER_BINARY environment variable to the "
120
+ "absolute path of an existing whisper-cli binary, or"
121
+ "\n - Pass --whisper-binary /absolute/path/to/whisper-cli on the CLI."
122
+ )
123
+ if sys.platform == "darwin":
124
+ os_hint = (
125
+ "\n - macOS: install via Homebrew: brew install whisper-cpp"
126
+ "\n (this places `whisper-cli` on your PATH automatically)"
127
+ )
128
+ elif sys.platform.startswith("linux"):
129
+ os_hint = (
130
+ "\n - Linux: build whisper.cpp from source:"
131
+ "\n git clone https://github.com/ggml-org/whisper.cpp"
132
+ "\n cd whisper.cpp && cmake -B build && cmake --build build --config Release"
133
+ "\n then point SUBTITLE_WHISPER_BINARY at build/bin/whisper-cli"
134
+ )
135
+ elif sys.platform == "win32":
136
+ os_hint = (
137
+ "\n - Windows: download a prebuilt release from "
138
+ "https://github.com/ggml-org/whisper.cpp/releases"
139
+ "\n and add the folder containing whisper-cli.exe to PATH."
140
+ )
141
+ else:
142
+ os_hint = (
143
+ "\n - Build whisper.cpp from source: "
144
+ "https://github.com/ggml-org/whisper.cpp"
145
+ )
146
+ return (
147
+ "Could not find the `whisper-cli` binary on this system."
148
+ + os_hint
149
+ + common
150
+ )
151
+
152
+
153
+ def default_models_dir() -> str:
154
+ """Return a writable, OS-appropriate directory for cached Whisper models.
155
+
156
+ Resolution order:
157
+ 1. ``SUBTITLE_MODELS_DIR`` environment variable, if set.
158
+ 2. Per-OS user cache location:
159
+ * macOS: ``~/Library/Caches/subtitle-generator/models``
160
+ * Windows: ``%LOCALAPPDATA%/subtitle-generator/Cache/models``
161
+ * Linux: ``$XDG_CACHE_HOME/subtitle-generator/models`` falling
162
+ back to ``~/.cache/subtitle-generator/models``.
163
+
164
+ The directory is **not** created here; callers create it lazily so that
165
+ instantiating a ``ModelManager`` has no filesystem side effects on
166
+ import.
167
+ """
168
+ env_dir = os.environ.get(ENV_MODELS_DIR)
169
+ if env_dir:
170
+ return os.path.abspath(os.path.expanduser(env_dir))
171
+
172
+ if sys.platform == "darwin":
173
+ base = os.path.expanduser("~/Library/Caches/subtitle-generator")
174
+ elif sys.platform == "win32":
175
+ local_app = os.environ.get("LOCALAPPDATA") or os.path.expanduser(
176
+ "~/AppData/Local"
177
+ )
178
+ base = os.path.join(local_app, "subtitle-generator", "Cache")
179
+ else:
180
+ xdg = os.environ.get("XDG_CACHE_HOME")
181
+ if xdg:
182
+ base = os.path.join(xdg, "subtitle-generator")
183
+ else:
184
+ base = os.path.expanduser("~/.cache/subtitle-generator")
185
+
186
+ return os.path.join(base, "models")
187
+
188
+
189
+ def default_output_dir() -> str:
190
+ """Return a writable directory for transient transcription output.
191
+
192
+ Whisper.cpp writes its raw output here under a UUID-prefixed name; the
193
+ final subtitle file is then renamed next to the user's input video.
194
+ Using a temp-style path avoids polluting the user's CWD with a ``data/``
195
+ folder on every invocation.
196
+ """
197
+ import tempfile
198
+
199
+ return os.path.join(tempfile.gettempdir(), "subtitle-generator")
@@ -31,4 +31,5 @@ subtitle_generator/utils/downloader.py
31
31
  subtitle_generator/utils/exceptions.py
32
32
  subtitle_generator/utils/file_handler.py
33
33
  subtitle_generator/utils/formatters.py
34
+ subtitle_generator/utils/paths.py
34
35
  subtitle_generator/utils/validators.py