Advertisement
Guest User

Plex/MKVToolNix mp4 to mkv Converter v2

a guest
Apr 10th, 2024
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.74 KB | Source Code | 0 0
  1. import os
  2. import subprocess
  3. import time
  4. import threading
  5. import queue
  6.  
  7. # Config variables - EDIT & MAKE SURE THESE ARE CORRECT
  8. SOURCE_DIR = r'\\PlexBox\data\movies'
  9. MKVMERGE_EXE = r'C:\Program Files\MKVToolNix\mkvmerge.exe'
  10. BATCH_SIZE = 10
  11. TIMEOUT = 10
  12.  
  13. # Clear the screen before starting the script
  14. os.system('cls' if os.name == 'nt' else 'clear')
  15.  
  16. # Script description and user instructions
  17. print("""
  18. This script converts MP4 files in the specified directory to MKV format using mkvmerge.
  19. It processes files in batches and prompts for user input after each batch to decide whether to continue.
  20.  
  21. User input options:
  22. - 'y' or 'yes' (case-insensitive): Continue to the next batch of files.
  23. - 'n', 'no', 'exit', 'end', 'quit' (case-insensitive): Stop processing and exit the script.
  24. - No input within the specified timeout (default 10 seconds): Automatically continue to the next batch.
  25. """)
  26.  
  27. def input_thread_func(input_queue):
  28.     while True:
  29.         user_input = input().strip().lower()
  30.         input_queue.put(user_input)
  31.         if user_input in ['n', 'no', 'exit', 'end', 'quit']:
  32.             print("\nThe script will stop after the current file is complete.")
  33.             break
  34.  
  35. def convert_to_mkv(source_dir, mp4_file, mkvmerge_exe):
  36.     mp4_path = os.path.join(source_dir, mp4_file)
  37.     mkv_file = mp4_file[:-4] + '.mkv'
  38.     mkv_path = os.path.join(source_dir, mkv_file)
  39.     convert_command = f'"{mkvmerge_exe}" -o "{mkv_path}" "{mp4_path}"'
  40.     try:
  41.         result = subprocess.run(convert_command, shell=True, capture_output=True)
  42.         if result.returncode != 0:
  43.             raise Exception(f"Error in conversion: {result.stderr}")
  44.         if os.path.isfile(mkv_path):
  45.             os.remove(mp4_path)
  46.             return True, mp4_file
  47.         return False, mp4_file
  48.     except Exception as e:
  49.         print(f"Error converting file {mp4_file}: {e}")
  50.         return False, mp4_file
  51.  
  52. def log_batch(source_dir, batch_index, batch_total_time, files_processed):
  53.     log_file_path = os.path.join(source_dir, '!conversion_log.txt')
  54.     with open(log_file_path, 'a') as log_file:
  55.         timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  56.         log_file.write(f"=== {timestamp} ===\n")
  57.         log_file.write(f"Batch {batch_index}\n")
  58.         log_file.write(f"Total Time Taken for Batch: {batch_total_time:.2f} seconds\n")
  59.         for file_name in files_processed:
  60.             log_file.write(f"- {file_name}\n")
  61.         log_file.write(f"Total Number of Files Deleted in Batch: {len(files_processed)}\n")
  62.         log_file.write("=== End of Log Entry ===\n\n")
  63.  
  64. def process_files():
  65.     mp4_files = sorted([file for file in os.listdir(SOURCE_DIR) if file.lower().endswith('.mp4')])
  66.     start_index = 0
  67.     batch_index = 1
  68.     files_processed = []
  69.  
  70.     input_queue = queue.Queue()
  71.     input_thread = threading.Thread(target=input_thread_func, args=(input_queue,))
  72.     input_thread.daemon = True
  73.     input_thread.start()
  74.  
  75.     while start_index < len(mp4_files):
  76.         current_batch = mp4_files[start_index:start_index + BATCH_SIZE]
  77.         batch_start_time = time.time()
  78.  
  79.         for file_index, mp4_file in enumerate(current_batch, 1):
  80.             print("-" * 50)
  81.             print(f"Batch {batch_index}, File {file_index} - Starting to process: {mp4_file}")
  82.             conversion_successful, processed_file = convert_to_mkv(SOURCE_DIR, mp4_file, MKVMERGE_EXE)
  83.             if conversion_successful:
  84.                 files_processed.append(processed_file)
  85.                 print(f"Batch {batch_index}, File {file_index} - Converted and removed: {processed_file}")
  86.  
  87.             if not input_queue.empty():
  88.                 user_input = input_queue.get()
  89.                 if user_input in ['n', 'no', 'exit', 'end', 'quit']:
  90.                     print("\nHalting MKV multiplexing as per user request.")
  91.                     log_batch(SOURCE_DIR, batch_index, time.time() - batch_start_time, files_processed)
  92.                     return
  93.  
  94.         batch_end_time = time.time()
  95.         batch_total_time = batch_end_time - batch_start_time
  96.         log_batch(SOURCE_DIR, batch_index, batch_total_time, files_processed)
  97.  
  98.         files_processed.clear()
  99.         start_index += BATCH_SIZE
  100.         batch_index += 1
  101.  
  102.         if start_index < len(mp4_files):
  103.             try:
  104.                 user_input = input_queue.get(timeout=TIMEOUT)
  105.             except queue.Empty:
  106.                 print("\nNo user input received. Continuing with the next batch.")
  107.                 continue
  108.  
  109.             if user_input in ['n', 'no', 'exit', 'end', 'quit']:
  110.                 print("\nHalting MKV multiplexing per user request.")
  111.                 break
  112.  
  113.     print("\nConversion and batch processing completed.")
  114.  
  115. if __name__ == "__main__":
  116.     process_files()
  117.  
Tags: Plex
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement