Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import subprocess
- import time
- import threading
- import queue
- # Config variables - EDIT & MAKE SURE THESE ARE CORRECT
- SOURCE_DIR = r'\\PlexBox\data\movies'
- MKVMERGE_EXE = r'C:\Program Files\MKVToolNix\mkvmerge.exe'
- BATCH_SIZE = 10
- TIMEOUT = 10
- # Clear the screen before starting the script
- os.system('cls' if os.name == 'nt' else 'clear')
- # Script description and user instructions
- print("""
- This script converts MP4 files in the specified directory to MKV format using mkvmerge.
- It processes files in batches and prompts for user input after each batch to decide whether to continue.
- User input options:
- - 'y' or 'yes' (case-insensitive): Continue to the next batch of files.
- - 'n', 'no', 'exit', 'end', 'quit' (case-insensitive): Stop processing and exit the script.
- - No input within the specified timeout (default 10 seconds): Automatically continue to the next batch.
- """)
- def input_thread_func(input_queue):
- while True:
- user_input = input().strip().lower()
- input_queue.put(user_input)
- if user_input in ['n', 'no', 'exit', 'end', 'quit']:
- print("\nThe script will stop after the current file is complete.")
- break
- def convert_to_mkv(source_dir, mp4_file, mkvmerge_exe):
- mp4_path = os.path.join(source_dir, mp4_file)
- mkv_file = mp4_file[:-4] + '.mkv'
- mkv_path = os.path.join(source_dir, mkv_file)
- convert_command = f'"{mkvmerge_exe}" -o "{mkv_path}" "{mp4_path}"'
- try:
- result = subprocess.run(convert_command, shell=True, capture_output=True)
- if result.returncode != 0:
- raise Exception(f"Error in conversion: {result.stderr}")
- if os.path.isfile(mkv_path):
- os.remove(mp4_path)
- return True, mp4_file
- return False, mp4_file
- except Exception as e:
- print(f"Error converting file {mp4_file}: {e}")
- return False, mp4_file
- def log_batch(source_dir, batch_index, batch_total_time, files_processed):
- log_file_path = os.path.join(source_dir, '!conversion_log.txt')
- with open(log_file_path, 'a') as log_file:
- timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
- log_file.write(f"=== {timestamp} ===\n")
- log_file.write(f"Batch {batch_index}\n")
- log_file.write(f"Total Time Taken for Batch: {batch_total_time:.2f} seconds\n")
- for file_name in files_processed:
- log_file.write(f"- {file_name}\n")
- log_file.write(f"Total Number of Files Deleted in Batch: {len(files_processed)}\n")
- log_file.write("=== End of Log Entry ===\n\n")
- def process_files():
- mp4_files = sorted([file for file in os.listdir(SOURCE_DIR) if file.lower().endswith('.mp4')])
- start_index = 0
- batch_index = 1
- files_processed = []
- input_queue = queue.Queue()
- input_thread = threading.Thread(target=input_thread_func, args=(input_queue,))
- input_thread.daemon = True
- input_thread.start()
- while start_index < len(mp4_files):
- current_batch = mp4_files[start_index:start_index + BATCH_SIZE]
- batch_start_time = time.time()
- for file_index, mp4_file in enumerate(current_batch, 1):
- print("-" * 50)
- print(f"Batch {batch_index}, File {file_index} - Starting to process: {mp4_file}")
- conversion_successful, processed_file = convert_to_mkv(SOURCE_DIR, mp4_file, MKVMERGE_EXE)
- if conversion_successful:
- files_processed.append(processed_file)
- print(f"Batch {batch_index}, File {file_index} - Converted and removed: {processed_file}")
- if not input_queue.empty():
- user_input = input_queue.get()
- if user_input in ['n', 'no', 'exit', 'end', 'quit']:
- print("\nHalting MKV multiplexing as per user request.")
- log_batch(SOURCE_DIR, batch_index, time.time() - batch_start_time, files_processed)
- return
- batch_end_time = time.time()
- batch_total_time = batch_end_time - batch_start_time
- log_batch(SOURCE_DIR, batch_index, batch_total_time, files_processed)
- files_processed.clear()
- start_index += BATCH_SIZE
- batch_index += 1
- if start_index < len(mp4_files):
- try:
- user_input = input_queue.get(timeout=TIMEOUT)
- except queue.Empty:
- print("\nNo user input received. Continuing with the next batch.")
- continue
- if user_input in ['n', 'no', 'exit', 'end', 'quit']:
- print("\nHalting MKV multiplexing per user request.")
- break
- print("\nConversion and batch processing completed.")
- if __name__ == "__main__":
- process_files()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement