sinhala-subtitle-hardcoder / batch_process.py
000x's picture
add : all
51e419e
Raw History Blame Contribute Delete
4.76 kB
#!/usr/bin/env python3
"""
Advanced Batch Processing Script
Allows processing videos from a configuration file without using the web UI
"""
import json
import sys
import os
from pathlib import Path
# Add the app directory to path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from app import VideoSubtitleProcessor
def load_config(config_file):
"""Load configuration from JSON file"""
try:
with open(config_file, 'r', encoding='utf-8') as f:
return json.load(f)
except Exception as e:
print(f"Error loading config: {e}")
sys.exit(1)
def process_batch(config_file):
"""Process videos based on configuration file"""
config = load_config(config_file)
print("=" * 60)
print("Sinhala Subtitle Hardcoder - Batch Processing")
print("=" * 60)
# Validate config
if 'videos' not in config or 'subtitle' not in config:
print("Error: Config must have 'videos' and 'subtitle' keys")
sys.exit(1)
video_urls = config['videos']
subtitle_path = config['subtitle']
if not video_urls:
print("Error: No videos specified")
sys.exit(1)
if not os.path.exists(subtitle_path):
print(f"Error: Subtitle file not found: {subtitle_path}")
sys.exit(1)
print(f"\nVideos to process: {len(video_urls)}")
print(f"Subtitle file: {subtitle_path}")
print()
# Create processor
processor = VideoSubtitleProcessor()
class SimpleProgress:
def __call__(self, progress=None, desc=None):
if desc:
print(f" {desc}")
progress = SimpleProgress()
try:
# Create a mock file object for subtitle
class MockFile:
def __init__(self, path):
self.name = path
subtitle_file = MockFile(subtitle_path)
# Process videos
print("Starting processing...")
print("-" * 60)
uploaded_links, output_paths = processor.process_multiple_videos(
video_urls,
subtitle_file,
progress
)
print("-" * 60)
print("\n✅ Processing complete!")
print("\nPixelDrain Links:")
for i, link in enumerate(uploaded_links, 1):
print(f"{i}. {link}")
print("\nLocal Output Files:")
for i, path in enumerate(output_paths, 1):
if os.path.exists(path):
size_mb = os.path.getsize(path) / (1024 * 1024)
print(f"{i}. {path} ({size_mb:.1f} MB)")
# Save results
results = {
'success': True,
'processed_count': len(uploaded_links),
'pixeldrain_links': uploaded_links,
'local_files': output_paths
}
results_file = 'batch_results.json'
with open(results_file, 'w', encoding='utf-8') as f:
json.dump(results, f, indent=2, ensure_ascii=False)
print(f"\nResults saved to: {results_file}")
except Exception as e:
print(f"\n❌ Error: {e}")
sys.exit(1)
finally:
processor.cleanup()
def create_example_config():
"""Create an example configuration file"""
example = {
"videos": [
"https://pixeldrain.com/u/example1",
"https://pixeldrain.com/u/example2",
"https://example.com/video.mp4"
],
"subtitle": "example_subtitle.srt",
"description": "This is an example configuration file. Edit the 'videos' and 'subtitle' values."
}
config_file = 'batch_config.example.json'
with open(config_file, 'w', encoding='utf-8') as f:
json.dump(example, f, indent=2, ensure_ascii=False)
print(f"Example configuration created: {config_file}")
print(f"\nEdit this file and rename to 'batch_config.json' to use it.")
def main():
if len(sys.argv) < 2:
print("Sinhala Subtitle Hardcoder - Batch Processing")
print("\nUsage:")
print(f" {sys.argv[0]} <config.json> - Process videos from config")
print(f" {sys.argv[0]} --example - Create example config")
print("\nConfig file format (JSON):")
print('{')
print(' "videos": ["url1", "url2", ...],')
print(' "subtitle": "path/to/subtitle.srt"')
print('}')
sys.exit(1)
if sys.argv[1] == '--example':
create_example_config()
else:
config_file = sys.argv[1]
if not os.path.exists(config_file):
print(f"Error: Config file not found: {config_file}")
sys.exit(1)
process_batch(config_file)
if __name__ == "__main__":
main()