subtitle-generator 2.0.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.
src/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """
2
+ Subtitle Generator - Modular Architecture
3
+
4
+ A clean, modular subtitle generation system using Whisper.cpp
5
+ with proper separation of concerns and design patterns.
6
+ """
7
+
8
+ __version__ = "2.0.0"
src/cli/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """CLI module - Command line interface."""
2
+
3
+ from .commands import main, SubtitleCLI
4
+
5
+ __all__ = ["main", "SubtitleCLI"]
src/cli/commands.py ADDED
@@ -0,0 +1,556 @@
1
+ """
2
+ CLI module with Observer pattern for progress tracking.
3
+
4
+ Provides a clean command-line interface for the subtitle generator
5
+ with progress callbacks and rich output.
6
+ """
7
+
8
+ import argparse
9
+ import logging
10
+ import sys
11
+ from abc import ABC, abstractmethod
12
+ from typing import Optional
13
+
14
+ from ..core.transcriber import WhisperCppTranscriber
15
+ from ..core.subtitle_gen import SubtitleGenerator
16
+ from ..core.video_processor import VideoProcessor
17
+ from ..core.batch_processor import BatchProcessor
18
+ from ..models import ModelManager
19
+ from ..utils.downloader import is_url, download_file
20
+ from ..utils.file_handler import sanitize_filename, file_exists, directory_exists
21
+ from ..utils.validators import (
22
+ validate_media_path,
23
+ validate_model_name,
24
+ validate_output_format,
25
+ get_available_models,
26
+ get_supported_formats,
27
+ )
28
+
29
+ # Configure logging
30
+ logging.basicConfig(
31
+ level=logging.INFO,
32
+ format="%(asctime)s - %(levelname)s - %(message)s",
33
+ )
34
+ logger = logging.getLogger(__name__)
35
+
36
+
37
+ # ============================================================================
38
+ # Observer Pattern for Progress Tracking
39
+ # ============================================================================
40
+
41
+ class ProgressObserver(ABC):
42
+ """Abstract observer for progress updates."""
43
+
44
+ @abstractmethod
45
+ def on_progress(self, stage: str, progress: float, message: str = ""):
46
+ """Called when progress is updated."""
47
+ pass
48
+
49
+ @abstractmethod
50
+ def on_complete(self, success: bool, result: Optional[str] = None):
51
+ """Called when processing completes."""
52
+ pass
53
+
54
+ @abstractmethod
55
+ def on_error(self, error: str):
56
+ """Called when an error occurs."""
57
+ pass
58
+
59
+
60
+ class ConsoleProgressObserver(ProgressObserver):
61
+ """Console-based progress observer with pretty output."""
62
+
63
+ STAGE_LABELS = {
64
+ "preparing": "[PREP]",
65
+ "downloading": "[DOWN]",
66
+ "transcribing": "[TRANS]",
67
+ "merging": "[MERGE]",
68
+ "complete": "[DONE]",
69
+ "error": "[ERROR]",
70
+ }
71
+
72
+ def __init__(self, verbose: bool = False):
73
+ self.verbose = verbose
74
+
75
+ def on_progress(self, stage: str, progress: float, message: str = ""):
76
+ label = self.STAGE_LABELS.get(stage, "[...]")
77
+ percentage = f"{progress * 100:.0f}%" if progress > 0 else ""
78
+
79
+ status = f"{label} {stage.capitalize()}"
80
+ if percentage:
81
+ status += f" {percentage}"
82
+ if message and self.verbose:
83
+ status += f" - {message}"
84
+
85
+ print(f"\r{status}", end="", flush=True)
86
+ if progress >= 1.0:
87
+ print()
88
+
89
+ def on_complete(self, success: bool, result: Optional[str] = None):
90
+ if success:
91
+ label = self.STAGE_LABELS["complete"]
92
+ print(f"\n{label} Success!")
93
+ if result:
94
+ print(f" Output: {result}")
95
+ else:
96
+ label = self.STAGE_LABELS["error"]
97
+ print(f"\n{label} Failed")
98
+
99
+ def on_error(self, error: str):
100
+ label = self.STAGE_LABELS["error"]
101
+ print(f"\n{label} Error: {error}", file=sys.stderr)
102
+
103
+
104
+ class SilentProgressObserver(ProgressObserver):
105
+ """Silent observer that captures results without output."""
106
+
107
+ def __init__(self):
108
+ self.stages = []
109
+ self.errors = []
110
+ self.result = None
111
+ self.success = False
112
+
113
+ def on_progress(self, stage: str, progress: float, message: str = ""):
114
+ self.stages.append((stage, progress, message))
115
+
116
+ def on_complete(self, success: bool, result: Optional[str] = None):
117
+ self.success = success
118
+ self.result = result
119
+
120
+ def on_error(self, error: str):
121
+ self.errors.append(error)
122
+
123
+
124
+ # ============================================================================
125
+ # CLI Class
126
+ # ============================================================================
127
+
128
+ class SubtitleCLI:
129
+ """Command-line interface for subtitle generation."""
130
+
131
+ def __init__(self, observer: Optional[ProgressObserver] = None):
132
+ self.observer = observer or ConsoleProgressObserver()
133
+ self.model_manager = ModelManager()
134
+
135
+ def run(self, args: argparse.Namespace) -> int:
136
+ """Run the CLI with parsed arguments."""
137
+ try:
138
+ # Handle subcommands
139
+ if hasattr(args, "command") and args.command:
140
+ if args.command == "models":
141
+ return self._handle_models_command(args)
142
+ elif args.command == "formats":
143
+ return self._handle_formats_command()
144
+ elif args.command == "batch":
145
+ return self._handle_batch_command(args)
146
+
147
+ # Default: process video
148
+ return self._handle_process_command(args)
149
+
150
+ except KeyboardInterrupt:
151
+ print("\n\nOperation cancelled.")
152
+ return 130
153
+ except Exception as e:
154
+ self.observer.on_error(str(e))
155
+ logger.exception("Unexpected error")
156
+ return 1
157
+
158
+ def _handle_process_command(self, args: argparse.Namespace) -> int:
159
+ """Handle the main process command."""
160
+ filepath = args.filepath
161
+ model = args.model
162
+ output_format = args.format
163
+ merge = args.merge
164
+
165
+ if not filepath:
166
+ self.observer.on_error("No video file specified")
167
+ return 1
168
+
169
+ # Handle URL input
170
+ if is_url(filepath):
171
+ self.observer.on_progress("downloading", 0.0)
172
+ try:
173
+ filepath = download_file(filepath, show_progress=True)
174
+ self.observer.on_progress("downloading", 1.0)
175
+ except Exception as e:
176
+ self.observer.on_error(f"Download failed: {e}")
177
+ return 1
178
+
179
+ # Sanitize filename if needed
180
+ if " " in filepath:
181
+ new_path = sanitize_filename(filepath)
182
+ if new_path != filepath:
183
+ import os
184
+ os.rename(filepath, new_path)
185
+ filepath = new_path
186
+
187
+ # Validate inputs
188
+ valid, error = validate_media_path(filepath)
189
+ if not valid:
190
+ self.observer.on_error(error)
191
+ return 1
192
+
193
+ valid, error = validate_model_name(model)
194
+ if not valid:
195
+ self.observer.on_error(error)
196
+ return 1
197
+
198
+ valid, error = validate_output_format(output_format)
199
+ if not valid:
200
+ self.observer.on_error(error)
201
+ return 1
202
+
203
+ # Create transcriber and generator
204
+ transcriber = WhisperCppTranscriber(
205
+ threads=args.threads,
206
+ processors=args.processors,
207
+ )
208
+ generator = SubtitleGenerator(transcriber, self.model_manager)
209
+
210
+ # Generate subtitles
211
+ def progress_callback(stage: str, progress: float):
212
+ self.observer.on_progress(stage, progress)
213
+
214
+ subtitle_path, success = generator.generate_and_rename(
215
+ input_path=filepath,
216
+ model_name=model,
217
+ output_format=output_format,
218
+ progress_callback=progress_callback,
219
+ )
220
+
221
+ if not success:
222
+ self.observer.on_error("Transcription failed")
223
+ return 1
224
+
225
+ # Merge subtitles into video if requested
226
+ if merge:
227
+ self.observer.on_progress("merging", 0.0)
228
+ processor = VideoProcessor()
229
+
230
+ import os
231
+ base, ext = os.path.splitext(filepath)
232
+ output_path = f"{base}_subtitled{ext}"
233
+
234
+ if processor.merge_subtitles(filepath, subtitle_path, output_path):
235
+ self.observer.on_progress("merging", 1.0)
236
+ self.observer.on_complete(True, output_path)
237
+ else:
238
+ self.observer.on_error("Failed to merge subtitles")
239
+ return 1
240
+ else:
241
+ self.observer.on_complete(True, subtitle_path)
242
+
243
+ return 0
244
+
245
+ def _handle_models_command(self, args: argparse.Namespace) -> int:
246
+ """Handle the models subcommand."""
247
+ if hasattr(args, 'list') and args.list:
248
+ available = self.model_manager.list_available_models()
249
+ downloaded = self.model_manager.list_downloaded_models()
250
+
251
+ print("Available models:")
252
+ for model in available:
253
+ status = "x" if model in downloaded else " "
254
+ print(f" [{status}] {model}")
255
+
256
+ print(f"\nDownloaded: {len(downloaded)}/{len(available)}")
257
+ return 0
258
+
259
+ if hasattr(args, 'download') and args.download:
260
+ model_name = args.download
261
+ valid, error = validate_model_name(model_name)
262
+ if not valid:
263
+ self.observer.on_error(error)
264
+ return 1
265
+
266
+ try:
267
+ path = self.model_manager.download_model(model_name)
268
+ print(f"Downloaded: {path}")
269
+ return 0
270
+ except Exception as e:
271
+ self.observer.on_error(str(e))
272
+ return 1
273
+
274
+ # Default: list models
275
+ return self._handle_models_command(argparse.Namespace(list=True, download=None))
276
+
277
+ def _handle_formats_command(self) -> int:
278
+ """Handle the formats subcommand."""
279
+ formats = get_supported_formats()
280
+ print("Supported subtitle formats:")
281
+ for fmt in formats:
282
+ print(f" - {fmt}")
283
+ return 0
284
+
285
+ def _handle_batch_command(self, args: argparse.Namespace) -> int:
286
+ """Handle the batch subcommand."""
287
+ input_dir = args.input_dir
288
+ output_dir = args.output_dir or input_dir
289
+ workers = args.workers
290
+ model = args.model
291
+ output_format = args.format
292
+ resume = args.resume
293
+ extensions = args.extensions.split(",") if args.extensions else None
294
+
295
+ # Validate input directory
296
+ if not directory_exists(input_dir):
297
+ self.observer.on_error(f"Input directory does not exist: {input_dir}")
298
+ return 1
299
+
300
+ # Validate model
301
+ valid, error = validate_model_name(model)
302
+ if not valid:
303
+ self.observer.on_error(error)
304
+ return 1
305
+
306
+ # Validate output format
307
+ valid, error = validate_output_format(output_format)
308
+ if not valid:
309
+ self.observer.on_error(error)
310
+ return 1
311
+
312
+ # Create batch processor
313
+ processor = BatchProcessor(
314
+ workers=workers,
315
+ model=model,
316
+ output_format=output_format,
317
+ extensions=extensions,
318
+ )
319
+
320
+ # Find files first to show count
321
+ video_files = processor.find_video_files(input_dir)
322
+ if not video_files:
323
+ print(f"No video files found in {input_dir}")
324
+ return 0
325
+
326
+ print(f"Found {len(video_files)} video files")
327
+ print(f"Output directory: {output_dir}")
328
+ print(f"Model: {model}, Format: {output_format}, Workers: {workers}")
329
+ if resume:
330
+ print("Resume mode: enabled")
331
+ print()
332
+
333
+ # Progress callback
334
+ def progress_callback(file_path: str, current: int, total: int, status: str):
335
+ filename = file_path.split("/")[-1]
336
+ print(f"[{current}/{total}] {filename}: {status}")
337
+
338
+ # Process batch
339
+ try:
340
+ summary = processor.process_batch(
341
+ input_dir=input_dir,
342
+ output_dir=output_dir,
343
+ resume=resume,
344
+ progress_callback=progress_callback,
345
+ )
346
+
347
+ # Print summary
348
+ print()
349
+ print("=" * 50)
350
+ print("BATCH PROCESSING COMPLETE")
351
+ print("=" * 50)
352
+ print(f"Total files: {summary.total_files}")
353
+ print(f"Successful: {summary.successful}")
354
+ print(f"Failed: {summary.failed}")
355
+ print(f"Skipped: {summary.skipped}")
356
+ print(f"Duration: {summary.total_duration_seconds:.2f}s")
357
+ print()
358
+ print(f"Report saved to: {output_dir}/batch_report.md")
359
+
360
+ return 0 if summary.failed == 0 else 1
361
+
362
+ except Exception as e:
363
+ self.observer.on_error(str(e))
364
+ return 1
365
+
366
+
367
+ # ============================================================================
368
+ # Main Entry Point
369
+ # ============================================================================
370
+
371
+ def create_main_parser() -> argparse.ArgumentParser:
372
+ """Create parser for main video processing commands."""
373
+ parser = argparse.ArgumentParser(
374
+ prog="subtitle",
375
+ description="Generate subtitles for video files using Whisper",
376
+ formatter_class=argparse.RawDescriptionHelpFormatter,
377
+ epilog="""
378
+ Examples:
379
+ subtitle video.mp4 Generate VTT subtitles
380
+ subtitle video.mp4 --merge Generate and embed subtitles
381
+ subtitle video.mp4 --model small Use small model
382
+ subtitle video.mp4 --format srt Generate SRT format
383
+ subtitle models --list List available models
384
+ subtitle models --download large Download large model
385
+ subtitle formats List supported formats
386
+ """,
387
+ )
388
+
389
+ parser.add_argument(
390
+ "filepath",
391
+ type=str,
392
+ nargs="?",
393
+ default=None,
394
+ help="Path to video file or URL",
395
+ )
396
+ parser.add_argument(
397
+ "--model", "-m",
398
+ type=str,
399
+ default="base",
400
+ help="Whisper model to use (default: base)",
401
+ )
402
+ parser.add_argument(
403
+ "--format", "-f",
404
+ type=str,
405
+ default="vtt",
406
+ help="Output subtitle format (default: vtt)",
407
+ )
408
+ parser.add_argument(
409
+ "--merge",
410
+ action="store_true",
411
+ help="Merge subtitles into video file",
412
+ )
413
+ parser.add_argument(
414
+ "--threads", "-t",
415
+ type=int,
416
+ default=4,
417
+ help="Number of threads (default: 4)",
418
+ )
419
+ parser.add_argument(
420
+ "--processors", "-p",
421
+ type=int,
422
+ default=1,
423
+ help="Number of processors (default: 1)",
424
+ )
425
+ parser.add_argument(
426
+ "--verbose", "-v",
427
+ action="store_true",
428
+ help="Verbose output",
429
+ )
430
+
431
+ return parser
432
+
433
+
434
+ def create_models_parser() -> argparse.ArgumentParser:
435
+ """Create parser for models subcommand."""
436
+ parser = argparse.ArgumentParser(
437
+ prog="subtitle models",
438
+ description="Manage Whisper models",
439
+ )
440
+ parser.add_argument(
441
+ "--list", "-l",
442
+ action="store_true",
443
+ help="List available models",
444
+ )
445
+ parser.add_argument(
446
+ "--download", "-d",
447
+ type=str,
448
+ metavar="MODEL",
449
+ help="Download a model",
450
+ )
451
+ return parser
452
+
453
+
454
+ def create_batch_parser() -> argparse.ArgumentParser:
455
+ """Create parser for batch subcommand."""
456
+ parser = argparse.ArgumentParser(
457
+ prog="subtitle batch",
458
+ description="Batch process multiple video files",
459
+ formatter_class=argparse.RawDescriptionHelpFormatter,
460
+ epilog="""
461
+ Examples:
462
+ subtitle batch --input-dir /videos --output-dir /subs
463
+ subtitle batch --input-dir /videos --workers 4
464
+ subtitle batch --input-dir /videos --resume
465
+ """,
466
+ )
467
+ parser.add_argument(
468
+ "--input-dir", "-i",
469
+ type=str,
470
+ required=True,
471
+ help="Directory containing video files",
472
+ )
473
+ parser.add_argument(
474
+ "--output-dir", "-o",
475
+ type=str,
476
+ default=None,
477
+ help="Directory for subtitle output (default: same as input)",
478
+ )
479
+ parser.add_argument(
480
+ "--workers", "-w",
481
+ type=int,
482
+ default=4,
483
+ help="Number of parallel workers (default: 4)",
484
+ )
485
+ parser.add_argument(
486
+ "--model", "-m",
487
+ type=str,
488
+ default="base",
489
+ help="Whisper model to use (default: base)",
490
+ )
491
+ parser.add_argument(
492
+ "--format", "-f",
493
+ type=str,
494
+ default="vtt",
495
+ help="Output subtitle format (default: vtt)",
496
+ )
497
+ parser.add_argument(
498
+ "--resume", "-r",
499
+ action="store_true",
500
+ help="Resume interrupted batch processing",
501
+ )
502
+ parser.add_argument(
503
+ "--extensions", "-e",
504
+ type=str,
505
+ default=None,
506
+ help="Comma-separated video extensions (default: mp4,mkv,avi,mov,webm)",
507
+ )
508
+ return parser
509
+
510
+
511
+ def main(args: Optional[list[str]] = None) -> int:
512
+ """Main entry point for CLI."""
513
+ if args is None:
514
+ args = sys.argv[1:]
515
+
516
+ # Check for subcommands first
517
+ if args and args[0] == "models":
518
+ parser = create_models_parser()
519
+ parsed_args = parser.parse_args(args[1:])
520
+ parsed_args.command = "models"
521
+ observer = ConsoleProgressObserver()
522
+ cli = SubtitleCLI(observer)
523
+ return cli.run(parsed_args)
524
+
525
+ if args and args[0] == "formats":
526
+ cli = SubtitleCLI()
527
+ return cli._handle_formats_command()
528
+
529
+ if args and args[0] == "batch":
530
+ parser = create_batch_parser()
531
+ parsed_args = parser.parse_args(args[1:])
532
+ parsed_args.command = "batch"
533
+ observer = ConsoleProgressObserver()
534
+ cli = SubtitleCLI(observer)
535
+ return cli.run(parsed_args)
536
+
537
+ # Main parser for video processing
538
+ parser = create_main_parser()
539
+ parsed_args = parser.parse_args(args)
540
+ parsed_args.command = None
541
+
542
+ # Show help if no arguments
543
+ if parsed_args.filepath is None:
544
+ parser.print_help()
545
+ return 0
546
+
547
+ # Set up observer
548
+ observer = ConsoleProgressObserver(verbose=parsed_args.verbose)
549
+
550
+ # Run CLI
551
+ cli = SubtitleCLI(observer)
552
+ return cli.run(parsed_args)
553
+
554
+
555
+ if __name__ == "__main__":
556
+ sys.exit(main())
src/config/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Configuration module - Settings management."""
2
+
3
+ from .config_loader import load_config, get_config
4
+ from .settings import Settings
5
+
6
+ __all__ = ["load_config", "get_config", "Settings"]