Japanese ASR with Multi-language Translation Support
Python
0
65 commits
updated Dec 5, 2025
A powerful, well-architected application for generating Japanese subtitles with multi-language translation support. Built with modern AI models and a user-friendly Tkinter interface. Get the highest quality subtitles locally.
We have completely re-architected the ASR pipeline to prioritize timestamp accuracy and hallucination prevention, addressing the "2-minute segment" and "silence hallucination" issues.
Key Changes:
JapaneseLinguisticProcessor merging logic, which previously ignored timestamps to find "sentence boundaries" (causing 2-minute segments).max_merge_gap (2.0s).split_audio_chunks that was resetting timestamps to 0, ensuring absolute timing is preserved.Sakura-14B-Qwen2.5-v1.0-GGUF (Standard 4-bit)A sophisticated multi-stage pipeline has been implemented to eliminate LLM hallucinations and drastically improve translation quality:
VAD Merging (1888โ230 segments)
โ
SakuraLLM Batch Translation
โ
_detect_hallucinations() Detection (repetition > 30%)
โ
confidence=0.0 Marking
โ
HallucinationFilter Filtering
โ
โจ Clean Output
Key Improvements:
| Stage | Purpose | Mechanism | Result |
|---|---|---|---|
| VAD Merging | Reduce fragmentation | Groups 1888 short (1-2s) VAD fragments into 230 merged chunks (~14s target) | ASR receives better context |
| Batch Detection | Early hallucination identification | Detects repetition patterns (>30% single character, 100% character sequences) | Marks confidence=0.0 before final output |
| HallucinationFilter | Final quality control | Filters low-confidence (<0.35) and invalid translations | Removes 7+ hallucination entries |
| Retry Mechanism | Handle parsing failures | Detects untranslated segments (still contains Japanese) and retries individually | 16/16 successful retry rate |
Processing 61-minute video with 195 subtitle segments:
Hallucination Reduction:
Structural Improvements:
Content Quality:
| Metric | Before | After | Improvement |
|---|---|---|---|
| Hallucination presence | โญโญ | โ Eliminated | +400% |
| Batch translation success | โญโญโญ | โญโญโญโญ | +25% |
| Usability | โญโญ | โญโญโญโญโญ | +150-200% |
Exclusive Chunk Control:
chunk_length (direct split): Used only when VAD disabled (5-60s, default 9s)chunk_length_s (VAD merge target): Used only when VAD enabled (5-30s, default 14s)Enhanced Settings Dialog:
New Methods Added:
_detect_hallucinations(): Detects repetitive character patterns and marks as low-confidence_on_vad_toggled(): Manages mutually exclusive chunk controls_apply_hallucination_filter(): Logs detailed filtering operationsConfiguration Parameters:
{
"asr": {
"chunk_length": 9, // Direct split threshold (non-VAD)
"vad": { "enabled": true }
},
"chunk_length_s": 14 // VAD merge target (soft limit)
}
prompts/ directory for specialized translation needs.no_speech_threshold: Lowered to 0.3 (default 0.6) to capture more low-volume speechpreamp: Increased to 6.0 for audio amplificationcondition_on_previous_text: Disabled to reduce repetitioncompression_ratio_threshold: Set to 3.0 for more flexible content acceptancejapanese-asr/distil-whisper-large-v3-ja-reazonspeech-all to UI model selector, providing a fast and memory-efficient Japanese ASR alternative (~1.5GB).n_gpu_layers=-1 (full GPU offload) on Apple Silicon, eliminating previous OOM issues.Original> with Chinese content, Translation>/็ฟป่ญฏ> prefixes, and alignment preservation for failed translations.frame_duration_ms=30) and VAD parameters (enable, mode, frame duration, padding, min segment duration) exposed in the Settings dialog for easy runtime tuning.return_token_timestamps while keeping native Whisper generate() usage for reliable timestamps and no token-limit behavior.prompts/; the SakuraLLM translator loads the selected template from config. The Settings dialog dynamically lists templates available in prompts/.SakuraTranslator.create_from_config() now passes the configured prompt template style to the translator so the chosen template is actually used during translation.Translation> prefixes and simple line-by-line), enabling ~20x faster translation while preserving timestamps and supporting all existing prompt templates.standard templates selected in the UI are applied correctly.python -m py_compile.Translation> prefix ratio, preventing ~90% translation loss where translations were replaced with Japanese text.Translation> prefixes) and simple line-by-line format, resolving Chinese translation filtering issues where 541 translations were incorrectly rejected.AudioData.start_time across scene-based processing so subtitle timestamps remain correct after chunking.asr.auto_preamp_enabled, asr.target_rms, asr.preamp_max) and manual override (asr.preamp) exposed in the Settings dialog to improve VAD and ASR quality on low-RMS recordings.outputs/vad_fallbacks.jsonl via a background writer to avoid blocking IO during processing.["zh"] (Chinese) and English translation is opt-in in the UI.This project is GPU-first and optimized for hardware acceleration:
If you only have CPU and need CPU-optimized inference, this project focuses on GPU acceleration. For CPU-only setups, consider:
ctransformers-based classes for CPU optimizationProcessing large videos repeatedly no longer re-extracts audio or re-detects scenes:
Cache Features:
Cache Structure:
.cache/
โโโ audio/ # Extracted WAV files
โ โโโ video_6d661ee2a9a1.wav
โโโ scenes/ # Scene detection JSON
โ โโโ video_6d661ee2a9a1_scenes.json
โโโ cache_metadata.json # LRU tracking + checksums
Performance Impact (3667s video test):
| Scenario | Time | Speedup |
|---|---|---|
| First run (no cache) | ~160s | 1.0x |
| Repeat run (cache hit) | ~120s | 1.33x โ |
| Cache storage | 113MB | <200MB max |
Final configuration after extensive testing and mathematical validation:
{
"vad": {
"mode": 3, // Most sensitive detection
"padding_ms": 300, // 0.3s boundary protection
"min_segment_duration": 0.65, // Filters โค0.05s noise
"frame_duration_ms": 30 // Standard 30ms frames
}
}
Mathematical Validation:
Boundary protection: 2 ร 300ms = 600ms
Min duration threshold: 650ms
Interpretation:
โ
Segments โฅ 0.65s preserved (speech)
โ
Segments < 0.05s filtered (noise)
โ
No clipping due to: 600ms < 650ms
Quality Impact:
Known Limitation:
Full pipeline on Apple Silicon M4:
| Stage | Time | Caching Benefit |
|---|---|---|
| Audio Extraction | 27s | 18.8x realtime (hardware accelerated) |
| Scene Detection | 15s | โ Cache hit (0s) |
| VAD Segmentation | 18s | Reduced from 1888 โ 230 segments |
| ASR Processing | 70s | ~4s per batch |
| Translation | 20s | Batch optimized |
| Total (repeat run) | ~120s | Cache saves ~45s โ |
New File: src/utils/cache_manager.py
hashlib.md5(file_content).hexdigest()[:12]last_accessed timestampsIntegration Points:
src/subtitle/subtitle_generator.py: Cache audio/scenes extractionsrc/utils/audio_processor.py: Load cached WAV filesconfig.json: VAD parameters locked for reproducibility.gitignore: Cache directory excluded from version controlBug Fixes (This Session):
video_data โ scene_detectorconfidence โ score (3 occurrences)video_file.path โ video_file.file_path (3 occurrences)Cross-Platform Hardware Acceleration with significant performance improvements:
| Platform | Acceleration | Performance | Realtime Factor |
|---|---|---|---|
| Apple Silicon | VideoToolbox | 18.8x realtime | M1/M2/M3/M4 optimized |
| Windows/Linux | CUDA | 15-20x realtime | RTX/GTX GPU acceleration |
| Software Fallback | CPU | 1.0x realtime | Universal compatibility |
| Component | Performance Gain | Notes |
|---|---|---|
| ASR Processing | 3-5x faster | MPS/CUDA acceleration for Whisper models |
| Translation | 2-4x faster | Hardware-optimized PyTorch operations |
| Model Loading | 50% faster | Optimized dependencies with uv |
| Memory Usage | 20-30% less | Efficient native libraries |
whisper-medium (1.5GB vs 3GB)whisper-small for better CPU performance๐ See Default Models & Requirements section for detailed specifications
git clone <repository-url>
cd py-sub-generator-sakura
# No installation needed - runs in isolated environment!
uv run python main.py
git clone <repository-url>
cd py-sub-generator-sakura
uv run python setup.py # Use uv run to avoid polluting system Python!
# OR (if you must):
python setup.py # โ ๏ธ May install to system Python if uv not available
git clone <repository-url>
cd py-sub-generator-sakura
python setup_apple_silicon.py # Maximum performance setup
git clone <repository-url>
cd py-sub-generator-sakura
# Install with uv (automatically handles dependencies)
uv pip install -e . # Basic installation
uv pip install -e ".[gpu]" # With GPU support
uv pip install -e ".[apple-silicon]" # Apple Silicon optimized
uv pip install -e ".[dev]" # Development dependencies
# Or install development dependencies separately
uv pip install -e . --group dev
git clone <repository-url>
cd py-sub-generator-sakura
pip install -e . # Basic installation
pip install -e ".[gpu]" # With GPU support
pip install -e ".[apple-silicon]" # Apple Silicon optimized
# With uv (fastest, automatic dependency management):
uv run python main.py
# After installation with setup.py or setup_apple_silicon.py:
python main.py
# With uv (no installation needed)
uv run python main.py --no-gui video.mp4
# After installation
python main.py --no-gui video.mp4
The application supports dual language subtitle output, perfect for language learning and multilingual content creation:
_ja.srt, _zh.srt)Via GUI Settings:
File Output Example:
video.mp4 โ
โโโ video_ja.srt (Japanese original subtitles)
โโโ video_zh.srt (Chinese translated subtitles)
Advanced Customization:
_ja (can change to _japanese, _orig, etc.)_zh (can change to _chinese, _trans, etc.)# Install dev dependencies (modern way)
uv pip install -e . --group dev
# Or using optional dependencies
uv pip install -e ".[dev]"
# Run tests
uv run pytest
# Format code
uv run black src/
uv run isort src/
# Type checking
uv run mypy src/
# Run with specific Python version
uv run --python 3.11 python main.py
This project uses modern Python packaging with GPU-first dependencies:
hatchling - Fast, modern PEP 517/518 compliant builderpyproject.toml - No setup.py neededuv - Ultra-fast Python package installer and resolverdependency-groups for development dependenciespyproject.toml configurationuv run support without installationIf you need CPU-only inference, consider developing additional classes:
# Example CPU-optimized approach (not included in main project)
from ctransformers import AutoModelForCausalLM # CPU-optimized
# This project focuses on GPU acceleration instead
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[dependency-groups]
dev = ["pytest", "black", "isort", "mypy", "ruff"]
The application follows a clean, modular architecture:
src/
โโโ models/ # Data models and structures
โโโ utils/ # Utilities (config, logging, file handling, audio processing)
โโโ asr/ # Automatic Speech Recognition modules
โโโ translation/ # Translation pipeline and models
โโโ subtitle/ # Subtitle processing and generation
โโโ ui/ # Tkinter GUI components
src/subtitle/subtitle_generator.py)The main orchestrator that coordinates the entire subtitle generation pipeline:
src/asr/)base_asr.py): Abstract interface for ASR implementationswhisper_asr.py): OpenAI Whisper integration with batching supportsrc/translation/)translation_pipeline.py): Coordinates multi-stage translationhuggingface_translator.py): Transformer-based GPU translationpytorch_translator.py): GPU-first PyTorch implementationSakuraLLM Integration Example:
# Specialized Japanese light novel translation
sakura_translator = PyTorchTranslator(
model_name="SakuraLLM/Sakura-1.5B-Qwen2.5-v1.0-GGUF",
source_lang="ja", target_lang="zh",
device="auto", torch_dtype="float16"
)
Note for CPU Users: This project prioritizes GPU acceleration. If you require CPU-only inference, consider implementing additional ctransformers-based classes, though this is outside the current project scope.
src/ui/)main_window.py): Primary application interfacesrc/utils/)config.py): JSON-based configuration with defaultsfile_handler.py): Video validation and file operationsaudio_processor.py): Audio extraction and preprocessinglogger.py): Structured logging with file rotationThe application uses a JSON configuration file with sensible defaults:
{
"asr": {
"model_name": "openai/whisper-large-v3",
"device": "auto",
"chunk_length": 30
},
"translation": {
"ja_to_en_model": "Helsinki-NLP/opus-mt-ja-en",
"en_to_zh_model": "Helsinki-NLP/opus-mt-en-zh",
"batch_size": 8
},
"dual_language": {
"generate_both_languages": false,
"japanese_suffix": "_ja",
"translated_suffix": "_zh"
},
"ui": {
"window_size": "800x600",
"theme": "default"
}
}
Configuration can be modified through:
config.json)openai/whisper-large-v3Hardware Requirements:
| Hardware | Minimum | Recommended |
|---|---|---|
| Apple Silicon | M1 8GB | M2/M3 16GB+ |
| NVIDIA GPU | GTX 1660 6GB | RTX 3070 8GB+ |
| CPU Only | 16GB RAM | 32GB RAM |
| Processing | 2x realtime | 8-12x realtime |
| Model | Size | Speed | Accuracy | Min Requirements |
|---|---|---|---|---|
| whisper-large-v3 | 3GB | Slow | Highest | 8GB VRAM/RAM |
| kotoba-whisper-v2.2 | 3GB | Slow | Highest (JA) | 8GB VRAM/RAM |
| distil-whisper-reazonspeech | 1.5GB | Fast | High (JA) | 4GB VRAM/RAM |
| whisper-medium | 1.5GB | Medium | High | 4GB VRAM/RAM |
| whisper-small | 500MB | Fast | Good | 2GB VRAM/RAM |
| whisper-base | 150MB | Fastest | Fair | 1GB VRAM/RAM |
Helsinki-NLP/opus-mt-ja-enHelsinki-NLP/opus-mt-en-zhTranslation Hardware Requirements:
| Hardware | Both Models Combined |
|---|---|
| GPU Memory | 1GB VRAM (both models) |
| System RAM | 2GB RAM (both models) |
| Processing | 4x faster on GPU vs CPU |
| Component | Download Size | Runtime Memory |
|---|---|---|
| Whisper Large-v3 | 3.0GB | 6GB VRAM/RAM |
| Translation Models | 0.6GB | 1GB VRAM/RAM |
| Total | 3.6GB | 7GB VRAM/RAM |
๐ Apple Silicon (Optimal):
๐ NVIDIA GPU (Optimal):
๐ป Budget/Lower-end Hardware:
# Use smaller models in config.json
{
"asr": {
"model_name": "openai/whisper-medium" # 1.5GB vs 3GB
}
}
| Model | Hugging Face Link | License | Purpose |
|---|---|---|---|
| Whisper Large-v3 | ๐ค Link | MIT | Japanese ASR |
| OPUS JA-EN | ๐ค Link | Apache 2.0 | JapaneseโEnglish |
| OPUS EN-ZH | ๐ค Link | Apache 2.0 | EnglishโChinese |
// config.json for optimal performance
{
"asr": {
"model_name": "openai/whisper-large-v3",
"batch_size": 1,
"device": "auto"
},
"translation": {
"batch_size": 8,
"device": "auto"
}
}
Hardware: M3/M4 16GB+ or RTX 3070+ 8GB
Performance: 8-12x realtime
Use Case: Production subtitle generation
// config.json for balanced performance/memory
{
"asr": {
"model_name": "openai/whisper-medium",
"batch_size": 1,
"device": "auto"
},
"translation": {
"batch_size": 4,
"device": "auto"
}
}
Hardware: M1/M2 8GB or GTX 1660 6GB
Performance: 4-6x realtime
Use Case: Personal use, occasional processing
// config.json for low-resource systems
{
"asr": {
"model_name": "openai/whisper-small",
"batch_size": 1,
"device": "cpu"
},
"translation": {
"batch_size": 1,
"device": "cpu"
}
}
Hardware: Any system with 8GB RAM
Performance: 1-2x realtime
Use Case: Testing, very low-end hardware
# First run will download all models (~3.6GB)
uv run python main.py
# Downloads will occur to:
# ~/.cache/huggingface/transformers/
# Total download time: 5-15 minutes (depending on internet)
# Note: Models cache to ~/.cache/huggingface/ and won't re-download
Models are cached to ~/.cache/huggingface/ and reused across runs. However, you might see downloads for:
Cache Status Check:
# Check cached models
ls ~/.cache/huggingface/hub/
# Cache size
du -sh ~/.cache/huggingface/
Force Pre-download:
# Pre-download all model formats to avoid future downloads
uv run python predownload_models.py
# Pre-download script (optional)
uv run python -c "
from transformers import AutoModel, AutoTokenizer, pipeline
# Download ASR model
pipeline('automatic-speech-recognition', model='openai/whisper-large-v3')
# Download translation models
pipeline('translation', model='Helsinki-NLP/opus-mt-ja-en')
pipeline('translation', model='Helsinki-NLP/opus-mt-en-zh')
print('All models downloaded successfully!')
"
For users seeking highest quality JapaneseโChinese translation, we support SakuraLLM integration via the PyTorchTranslator:
| Model | Parameters | Download Size | Memory Req | Performance | Quality |
|---|---|---|---|---|---|
| ๐ธ Sakura-1.5B โญ | 1.78B | ~2-4GB | 4-6GB | 8-15x faster | Very Good |
| ๐ธ Sakura-14B | 14.8B | ~15-30GB | 16-32GB | 2-4x slower | Excellent |
# config.json - SakuraLLM setup
{
"translation": {
"use_sakura": true,
"sakura_model": "SakuraLLM/Sakura-1.5B-Qwen2.5-v1.0-GGUF",
"source_lang": "ja",
"target_lang": "zh",
"device": "auto",
"torch_dtype": "float16"
}
}
# Usage with PyTorchTranslator
from src.translation.pytorch_translator import PyTorchTranslator
sakura = PyTorchTranslator(
model_name="SakuraLLM/Sakura-1.5B-Qwen2.5-v1.0-GGUF",
source_lang="ja",
target_lang="zh",
device="auto", # GPU-first
force_gpu=True
)
SakuraLLM supports custom terminology dictionaries for consistent translation of specialized terms:
# prompts/my_glossary.txt
# Format: ๅๆ->่ฏๆ (Japanese->Chinese)
ใๅ
ใกใใ->ๅฅๅฅ
ๅ
่ผฉ->ๅ่ผฉ
้ญๆณๅฐๅฅณ->้ญๆณๅฐๅฅณ
Usage in config.json:
{
"sakura": {
"prompt_template": "my_glossary"
}
}
The glossary ensures consistent translation of character names, honorifics, and domain-specific terminology.
| Backend | Quality | Speed | Memory | Languages | Use Case |
|---|---|---|---|---|---|
| Helsinki-NLP | Good | Very Fast | 1GB | Multi-pair | General |
| SakuraLLM 1.5B | Very Good | Fast | 4GB | JAโZH | Anime/LN |
| SakuraLLM 14B | Excellent | Moderate | 16GB | JAโZH | Premium |
| Backend | Apple M3 | NVIDIA RTX 4080 | CPU Only (Intel/AMD) |
|---|---|---|---|
| Whisper Large-v3 | 8x realtime (MPS) | 12x realtime (CUDA) | 1.5x realtime |
| Helsinki Translation | 4x faster (MPS) | 6x faster (CUDA) | Baseline |
| SakuraLLM 1.5B | 3x faster (MPS) | 5x faster (CUDA) | 0.5x baseline |
| Memory Usage | 8GB unified | 6GB VRAM | 16GB RAM |
| Power Efficiency | Excellent | Moderate | Poor |
If you're limited to CPU-only inference:
ctransformers with GGUF modelsuv tool for development tools instead of project dependenciesgenerate() methodFor complete technical details, see TECHNICAL_CHANGELOG.md
The codebase is designed for extensibility:
BaseASR classBaseTranslator classSubtitleFile classsrc/ui/components/[License information]
Built with โค๏ธ for the subtitle generation community ๐ธ
Japanese ASR with Multi-language Translation Support
Python
0
65 commits
updated Dec 5, 2025
A powerful, well-architected application for generating Japanese subtitles with multi-language translation support. Built with modern AI models and a user-friendly Tkinter interface. Get the highest quality subtitles locally.
We have completely re-architected the ASR pipeline to prioritize timestamp accuracy and hallucination prevention, addressing the "2-minute segment" and "silence hallucination" issues.
Key Changes:
JapaneseLinguisticProcessor merging logic, which previously ignored timestamps to find "sentence boundaries" (causing 2-minute segments).max_merge_gap (2.0s).split_audio_chunks that was resetting timestamps to 0, ensuring absolute timing is preserved.Sakura-14B-Qwen2.5-v1.0-GGUF (Standard 4-bit)A sophisticated multi-stage pipeline has been implemented to eliminate LLM hallucinations and drastically improve translation quality:
VAD Merging (1888โ230 segments)
โ
SakuraLLM Batch Translation
โ
_detect_hallucinations() Detection (repetition > 30%)
โ
confidence=0.0 Marking
โ
HallucinationFilter Filtering
โ
โจ Clean Output
Key Improvements:
| Stage | Purpose | Mechanism | Result |
|---|---|---|---|
| VAD Merging | Reduce fragmentation | Groups 1888 short (1-2s) VAD fragments into 230 merged chunks (~14s target) | ASR receives better context |
| Batch Detection | Early hallucination identification | Detects repetition patterns (>30% single character, 100% character sequences) | Marks confidence=0.0 before final output |
| HallucinationFilter | Final quality control | Filters low-confidence (<0.35) and invalid translations | Removes 7+ hallucination entries |
| Retry Mechanism | Handle parsing failures | Detects untranslated segments (still contains Japanese) and retries individually | 16/16 successful retry rate |
Processing 61-minute video with 195 subtitle segments:
Hallucination Reduction:
Structural Improvements:
Content Quality:
| Metric | Before | After | Improvement |
|---|---|---|---|
| Hallucination presence | โญโญ | โ Eliminated | +400% |
| Batch translation success | โญโญโญ | โญโญโญโญ | +25% |
| Usability | โญโญ | โญโญโญโญโญ | +150-200% |
Exclusive Chunk Control:
chunk_length (direct split): Used only when VAD disabled (5-60s, default 9s)chunk_length_s (VAD merge target): Used only when VAD enabled (5-30s, default 14s)Enhanced Settings Dialog:
New Methods Added:
_detect_hallucinations(): Detects repetitive character patterns and marks as low-confidence_on_vad_toggled(): Manages mutually exclusive chunk controls_apply_hallucination_filter(): Logs detailed filtering operationsConfiguration Parameters:
{
"asr": {
"chunk_length": 9, // Direct split threshold (non-VAD)
"vad": { "enabled": true }
},
"chunk_length_s": 14 // VAD merge target (soft limit)
}
prompts/ directory for specialized translation needs.no_speech_threshold: Lowered to 0.3 (default 0.6) to capture more low-volume speechpreamp: Increased to 6.0 for audio amplificationcondition_on_previous_text: Disabled to reduce repetitioncompression_ratio_threshold: Set to 3.0 for more flexible content acceptancejapanese-asr/distil-whisper-large-v3-ja-reazonspeech-all to UI model selector, providing a fast and memory-efficient Japanese ASR alternative (~1.5GB).n_gpu_layers=-1 (full GPU offload) on Apple Silicon, eliminating previous OOM issues.Original> with Chinese content, Translation>/็ฟป่ญฏ> prefixes, and alignment preservation for failed translations.frame_duration_ms=30) and VAD parameters (enable, mode, frame duration, padding, min segment duration) exposed in the Settings dialog for easy runtime tuning.return_token_timestamps while keeping native Whisper generate() usage for reliable timestamps and no token-limit behavior.prompts/; the SakuraLLM translator loads the selected template from config. The Settings dialog dynamically lists templates available in prompts/.SakuraTranslator.create_from_config() now passes the configured prompt template style to the translator so the chosen template is actually used during translation.Translation> prefixes and simple line-by-line), enabling ~20x faster translation while preserving timestamps and supporting all existing prompt templates.standard templates selected in the UI are applied correctly.python -m py_compile.Translation> prefix ratio, preventing ~90% translation loss where translations were replaced with Japanese text.Translation> prefixes) and simple line-by-line format, resolving Chinese translation filtering issues where 541 translations were incorrectly rejected.AudioData.start_time across scene-based processing so subtitle timestamps remain correct after chunking.asr.auto_preamp_enabled, asr.target_rms, asr.preamp_max) and manual override (asr.preamp) exposed in the Settings dialog to improve VAD and ASR quality on low-RMS recordings.outputs/vad_fallbacks.jsonl via a background writer to avoid blocking IO during processing.["zh"] (Chinese) and English translation is opt-in in the UI.This project is GPU-first and optimized for hardware acceleration:
If you only have CPU and need CPU-optimized inference, this project focuses on GPU acceleration. For CPU-only setups, consider:
ctransformers-based classes for CPU optimizationProcessing large videos repeatedly no longer re-extracts audio or re-detects scenes:
Cache Features:
Cache Structure:
.cache/
โโโ audio/ # Extracted WAV files
โ โโโ video_6d661ee2a9a1.wav
โโโ scenes/ # Scene detection JSON
โ โโโ video_6d661ee2a9a1_scenes.json
โโโ cache_metadata.json # LRU tracking + checksums
Performance Impact (3667s video test):
| Scenario | Time | Speedup |
|---|---|---|
| First run (no cache) | ~160s | 1.0x |
| Repeat run (cache hit) | ~120s | 1.33x โ |
| Cache storage | 113MB | <200MB max |
Final configuration after extensive testing and mathematical validation:
{
"vad": {
"mode": 3, // Most sensitive detection
"padding_ms": 300, // 0.3s boundary protection
"min_segment_duration": 0.65, // Filters โค0.05s noise
"frame_duration_ms": 30 // Standard 30ms frames
}
}
Mathematical Validation:
Boundary protection: 2 ร 300ms = 600ms
Min duration threshold: 650ms
Interpretation:
โ
Segments โฅ 0.65s preserved (speech)
โ
Segments < 0.05s filtered (noise)
โ
No clipping due to: 600ms < 650ms
Quality Impact:
Known Limitation:
Full pipeline on Apple Silicon M4:
| Stage | Time | Caching Benefit |
|---|---|---|
| Audio Extraction | 27s | 18.8x realtime (hardware accelerated) |
| Scene Detection | 15s | โ Cache hit (0s) |
| VAD Segmentation | 18s | Reduced from 1888 โ 230 segments |
| ASR Processing | 70s | ~4s per batch |
| Translation | 20s | Batch optimized |
| Total (repeat run) | ~120s | Cache saves ~45s โ |
New File: src/utils/cache_manager.py
hashlib.md5(file_content).hexdigest()[:12]last_accessed timestampsIntegration Points:
src/subtitle/subtitle_generator.py: Cache audio/scenes extractionsrc/utils/audio_processor.py: Load cached WAV filesconfig.json: VAD parameters locked for reproducibility.gitignore: Cache directory excluded from version controlBug Fixes (This Session):
video_data โ scene_detectorconfidence โ score (3 occurrences)video_file.path โ video_file.file_path (3 occurrences)Cross-Platform Hardware Acceleration with significant performance improvements:
| Platform | Acceleration | Performance | Realtime Factor |
|---|---|---|---|
| Apple Silicon | VideoToolbox | 18.8x realtime | M1/M2/M3/M4 optimized |
| Windows/Linux | CUDA | 15-20x realtime | RTX/GTX GPU acceleration |
| Software Fallback | CPU | 1.0x realtime | Universal compatibility |
| Component | Performance Gain | Notes |
|---|---|---|
| ASR Processing | 3-5x faster | MPS/CUDA acceleration for Whisper models |
| Translation | 2-4x faster | Hardware-optimized PyTorch operations |
| Model Loading | 50% faster | Optimized dependencies with uv |
| Memory Usage | 20-30% less | Efficient native libraries |
whisper-medium (1.5GB vs 3GB)whisper-small for better CPU performance๐ See Default Models & Requirements section for detailed specifications
git clone <repository-url>
cd py-sub-generator-sakura
# No installation needed - runs in isolated environment!
uv run python main.py
git clone <repository-url>
cd py-sub-generator-sakura
uv run python setup.py # Use uv run to avoid polluting system Python!
# OR (if you must):
python setup.py # โ ๏ธ May install to system Python if uv not available
git clone <repository-url>
cd py-sub-generator-sakura
python setup_apple_silicon.py # Maximum performance setup
git clone <repository-url>
cd py-sub-generator-sakura
# Install with uv (automatically handles dependencies)
uv pip install -e . # Basic installation
uv pip install -e ".[gpu]" # With GPU support
uv pip install -e ".[apple-silicon]" # Apple Silicon optimized
uv pip install -e ".[dev]" # Development dependencies
# Or install development dependencies separately
uv pip install -e . --group dev
git clone <repository-url>
cd py-sub-generator-sakura
pip install -e . # Basic installation
pip install -e ".[gpu]" # With GPU support
pip install -e ".[apple-silicon]" # Apple Silicon optimized
# With uv (fastest, automatic dependency management):
uv run python main.py
# After installation with setup.py or setup_apple_silicon.py:
python main.py
# With uv (no installation needed)
uv run python main.py --no-gui video.mp4
# After installation
python main.py --no-gui video.mp4
The application supports dual language subtitle output, perfect for language learning and multilingual content creation:
_ja.srt, _zh.srt)Via GUI Settings:
File Output Example:
video.mp4 โ
โโโ video_ja.srt (Japanese original subtitles)
โโโ video_zh.srt (Chinese translated subtitles)
Advanced Customization:
_ja (can change to _japanese, _orig, etc.)_zh (can change to _chinese, _trans, etc.)# Install dev dependencies (modern way)
uv pip install -e . --group dev
# Or using optional dependencies
uv pip install -e ".[dev]"
# Run tests
uv run pytest
# Format code
uv run black src/
uv run isort src/
# Type checking
uv run mypy src/
# Run with specific Python version
uv run --python 3.11 python main.py
This project uses modern Python packaging with GPU-first dependencies:
hatchling - Fast, modern PEP 517/518 compliant builderpyproject.toml - No setup.py neededuv - Ultra-fast Python package installer and resolverdependency-groups for development dependenciespyproject.toml configurationuv run support without installationIf you need CPU-only inference, consider developing additional classes:
# Example CPU-optimized approach (not included in main project)
from ctransformers import AutoModelForCausalLM # CPU-optimized
# This project focuses on GPU acceleration instead
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[dependency-groups]
dev = ["pytest", "black", "isort", "mypy", "ruff"]
The application follows a clean, modular architecture:
src/
โโโ models/ # Data models and structures
โโโ utils/ # Utilities (config, logging, file handling, audio processing)
โโโ asr/ # Automatic Speech Recognition modules
โโโ translation/ # Translation pipeline and models
โโโ subtitle/ # Subtitle processing and generation
โโโ ui/ # Tkinter GUI components
src/subtitle/subtitle_generator.py)The main orchestrator that coordinates the entire subtitle generation pipeline:
src/asr/)base_asr.py): Abstract interface for ASR implementationswhisper_asr.py): OpenAI Whisper integration with batching supportsrc/translation/)translation_pipeline.py): Coordinates multi-stage translationhuggingface_translator.py): Transformer-based GPU translationpytorch_translator.py): GPU-first PyTorch implementationSakuraLLM Integration Example:
# Specialized Japanese light novel translation
sakura_translator = PyTorchTranslator(
model_name="SakuraLLM/Sakura-1.5B-Qwen2.5-v1.0-GGUF",
source_lang="ja", target_lang="zh",
device="auto", torch_dtype="float16"
)
Note for CPU Users: This project prioritizes GPU acceleration. If you require CPU-only inference, consider implementing additional ctransformers-based classes, though this is outside the current project scope.
src/ui/)main_window.py): Primary application interfacesrc/utils/)config.py): JSON-based configuration with defaultsfile_handler.py): Video validation and file operationsaudio_processor.py): Audio extraction and preprocessinglogger.py): Structured logging with file rotationThe application uses a JSON configuration file with sensible defaults:
{
"asr": {
"model_name": "openai/whisper-large-v3",
"device": "auto",
"chunk_length": 30
},
"translation": {
"ja_to_en_model": "Helsinki-NLP/opus-mt-ja-en",
"en_to_zh_model": "Helsinki-NLP/opus-mt-en-zh",
"batch_size": 8
},
"dual_language": {
"generate_both_languages": false,
"japanese_suffix": "_ja",
"translated_suffix": "_zh"
},
"ui": {
"window_size": "800x600",
"theme": "default"
}
}
Configuration can be modified through:
config.json)openai/whisper-large-v3Hardware Requirements:
| Hardware | Minimum | Recommended |
|---|---|---|
| Apple Silicon | M1 8GB | M2/M3 16GB+ |
| NVIDIA GPU | GTX 1660 6GB | RTX 3070 8GB+ |
| CPU Only | 16GB RAM | 32GB RAM |
| Processing | 2x realtime | 8-12x realtime |
| Model | Size | Speed | Accuracy | Min Requirements |
|---|---|---|---|---|
| whisper-large-v3 | 3GB | Slow | Highest | 8GB VRAM/RAM |
| kotoba-whisper-v2.2 | 3GB | Slow | Highest (JA) | 8GB VRAM/RAM |
| distil-whisper-reazonspeech | 1.5GB | Fast | High (JA) | 4GB VRAM/RAM |
| whisper-medium | 1.5GB | Medium | High | 4GB VRAM/RAM |
| whisper-small | 500MB | Fast | Good | 2GB VRAM/RAM |
| whisper-base | 150MB | Fastest | Fair | 1GB VRAM/RAM |
Helsinki-NLP/opus-mt-ja-enHelsinki-NLP/opus-mt-en-zhTranslation Hardware Requirements:
| Hardware | Both Models Combined |
|---|---|
| GPU Memory | 1GB VRAM (both models) |
| System RAM | 2GB RAM (both models) |
| Processing | 4x faster on GPU vs CPU |
| Component | Download Size | Runtime Memory |
|---|---|---|
| Whisper Large-v3 | 3.0GB | 6GB VRAM/RAM |
| Translation Models | 0.6GB | 1GB VRAM/RAM |
| Total | 3.6GB | 7GB VRAM/RAM |
๐ Apple Silicon (Optimal):
๐ NVIDIA GPU (Optimal):
๐ป Budget/Lower-end Hardware:
# Use smaller models in config.json
{
"asr": {
"model_name": "openai/whisper-medium" # 1.5GB vs 3GB
}
}
| Model | Hugging Face Link | License | Purpose |
|---|---|---|---|
| Whisper Large-v3 | ๐ค Link | MIT | Japanese ASR |
| OPUS JA-EN | ๐ค Link | Apache 2.0 | JapaneseโEnglish |
| OPUS EN-ZH | ๐ค Link | Apache 2.0 | EnglishโChinese |
// config.json for optimal performance
{
"asr": {
"model_name": "openai/whisper-large-v3",
"batch_size": 1,
"device": "auto"
},
"translation": {
"batch_size": 8,
"device": "auto"
}
}
Hardware: M3/M4 16GB+ or RTX 3070+ 8GB
Performance: 8-12x realtime
Use Case: Production subtitle generation
// config.json for balanced performance/memory
{
"asr": {
"model_name": "openai/whisper-medium",
"batch_size": 1,
"device": "auto"
},
"translation": {
"batch_size": 4,
"device": "auto"
}
}
Hardware: M1/M2 8GB or GTX 1660 6GB
Performance: 4-6x realtime
Use Case: Personal use, occasional processing
// config.json for low-resource systems
{
"asr": {
"model_name": "openai/whisper-small",
"batch_size": 1,
"device": "cpu"
},
"translation": {
"batch_size": 1,
"device": "cpu"
}
}
Hardware: Any system with 8GB RAM
Performance: 1-2x realtime
Use Case: Testing, very low-end hardware
# First run will download all models (~3.6GB)
uv run python main.py
# Downloads will occur to:
# ~/.cache/huggingface/transformers/
# Total download time: 5-15 minutes (depending on internet)
# Note: Models cache to ~/.cache/huggingface/ and won't re-download
Models are cached to ~/.cache/huggingface/ and reused across runs. However, you might see downloads for:
Cache Status Check:
# Check cached models
ls ~/.cache/huggingface/hub/
# Cache size
du -sh ~/.cache/huggingface/
Force Pre-download:
# Pre-download all model formats to avoid future downloads
uv run python predownload_models.py
# Pre-download script (optional)
uv run python -c "
from transformers import AutoModel, AutoTokenizer, pipeline
# Download ASR model
pipeline('automatic-speech-recognition', model='openai/whisper-large-v3')
# Download translation models
pipeline('translation', model='Helsinki-NLP/opus-mt-ja-en')
pipeline('translation', model='Helsinki-NLP/opus-mt-en-zh')
print('All models downloaded successfully!')
"
For users seeking highest quality JapaneseโChinese translation, we support SakuraLLM integration via the PyTorchTranslator:
| Model | Parameters | Download Size | Memory Req | Performance | Quality |
|---|---|---|---|---|---|
| ๐ธ Sakura-1.5B โญ | 1.78B | ~2-4GB | 4-6GB | 8-15x faster | Very Good |
| ๐ธ Sakura-14B | 14.8B | ~15-30GB | 16-32GB | 2-4x slower | Excellent |
# config.json - SakuraLLM setup
{
"translation": {
"use_sakura": true,
"sakura_model": "SakuraLLM/Sakura-1.5B-Qwen2.5-v1.0-GGUF",
"source_lang": "ja",
"target_lang": "zh",
"device": "auto",
"torch_dtype": "float16"
}
}
# Usage with PyTorchTranslator
from src.translation.pytorch_translator import PyTorchTranslator
sakura = PyTorchTranslator(
model_name="SakuraLLM/Sakura-1.5B-Qwen2.5-v1.0-GGUF",
source_lang="ja",
target_lang="zh",
device="auto", # GPU-first
force_gpu=True
)
SakuraLLM supports custom terminology dictionaries for consistent translation of specialized terms:
# prompts/my_glossary.txt
# Format: ๅๆ->่ฏๆ (Japanese->Chinese)
ใๅ
ใกใใ->ๅฅๅฅ
ๅ
่ผฉ->ๅ่ผฉ
้ญๆณๅฐๅฅณ->้ญๆณๅฐๅฅณ
Usage in config.json:
{
"sakura": {
"prompt_template": "my_glossary"
}
}
The glossary ensures consistent translation of character names, honorifics, and domain-specific terminology.
| Backend | Quality | Speed | Memory | Languages | Use Case |
|---|---|---|---|---|---|
| Helsinki-NLP | Good | Very Fast | 1GB | Multi-pair | General |
| SakuraLLM 1.5B | Very Good | Fast | 4GB | JAโZH | Anime/LN |
| SakuraLLM 14B | Excellent | Moderate | 16GB | JAโZH | Premium |
| Backend | Apple M3 | NVIDIA RTX 4080 | CPU Only (Intel/AMD) |
|---|---|---|---|
| Whisper Large-v3 | 8x realtime (MPS) | 12x realtime (CUDA) | 1.5x realtime |
| Helsinki Translation | 4x faster (MPS) | 6x faster (CUDA) | Baseline |
| SakuraLLM 1.5B | 3x faster (MPS) | 5x faster (CUDA) | 0.5x baseline |
| Memory Usage | 8GB unified | 6GB VRAM | 16GB RAM |
| Power Efficiency | Excellent | Moderate | Poor |
If you're limited to CPU-only inference:
ctransformers with GGUF modelsuv tool for development tools instead of project dependenciesgenerate() methodFor complete technical details, see TECHNICAL_CHANGELOG.md
The codebase is designed for extensibility:
BaseASR classBaseTranslator classSubtitleFile classsrc/ui/components/[License information]
Built with โค๏ธ for the subtitle generation community ๐ธ