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'
- # Clear the screen before starting the script
- os.system('cls' if os.name == 'nt' else 'clear')
- alien_art = r'''
- _ _______ _
- _dMMMb._ .adOOOOOOOOOba. _,dMMMb_
- dP' ~YMMb dOOOOOOOOOOOOOOOb aMMP~ `Yb
- V ~"Mb dOOOOOOOOOOOOOOOOOb dM"~ V
- `Mb. dOOOOOOOOOOOOOOOOOOOb ,dM'
- `YMb._ |OOOOOOOOOOOOOOOOOOOOO| _,dMP'
- __ `YMMM| OP'~"YOOOOOOOOOOOP"~`YO |MMMP' __
- ,dMMMb. ~~' OO `YOOOOOP' OO `~~ ,dMMMb.
- _,dP~ `YMba_ OOb `OOO' dOO _aMMP' ~Yb._
- `YMMMM\`OOOo OOO oOOO'/MMMMP'
- ,aa. `~YMMb `OOOb._,dOOOb._,dOOO'dMMP~' ,aa.
- ,dMYYMba._ `OOOOOOOOOOOOOOOOO' _,adMYYMb.
- ,MP' `YMMba._ OOOOOOOOOOOOOOOOO _,adMMP' `YM.
- MP' ~YMMMba._ YOOOOPVVVVVYOOOOP _,adMMMMP~ `YM
- YMb ~YMMMM\`OOOOI`````IOOOOO'/MMMMP~ dMP
- `Mb. `YMMMb`OOOI,,,,,IOOOO'dMMMP' ,dM'
- `' `OObNNNNNdOO' `'
- `~OOOOO~' CHILLUMINATI
- '''
- print(alien_art)
- print(f"""
- This script automates the conversion of MP4 files to MKV format using mkvmerge.
- It continuously monitors the directory {SOURCE_DIR} for MP4 files, converting them to MKV using mkvmerge located at {MKVMERGE_EXE}.
- Before running the script, please ensure that the following directories are correct for your system:
- - SOURCE_DIR: Path to the directory containing your MP4 files.
- - MKVMERGE_EXE: Path to the mkvmerge executable (usually located in the MKVToolNix installation directory).
- During processing, the script listens for user commands to stop the conversion:
- You can halt the script at any time with 'n', 'no', 'exit', 'end', 'quit'.
- The script will finish the current file conversion before halting.
- """)
- def input_thread_func(input_queue, halt_flag):
- """
- Continuously checks for user input to potentially halt the conversion process.
- """
- while not halt_flag.is_set():
- 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 completing the current file conversion.")
- halt_flag.set()
- LOG_FILE = os.path.join(SOURCE_DIR, '!conversion_log.txt')
- def convert_to_mkv(source_dir, mp4_file, mkvmerge_exe):
- """
- Converts an MP4 file to an MKV file using mkvmerge.
- """
- 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:
- start_time = time.time()
- result = subprocess.run(convert_command, shell=True, capture_output=True)
- end_time = time.time()
- if result.returncode != 0:
- error_message = result.stderr.decode('utf-8') if result.stderr else 'Unknown error'
- raise Exception(f"Error in conversion: {error_message}")
- if os.path.isfile(mkv_path):
- os.remove(mp4_path)
- return True, mkv_file, end_time - start_time
- return False, mp4_file, end_time - start_time
- except Exception as e:
- print(f"Error converting file {mp4_file}: {e}")
- return False, mp4_file, 0
- def log_converted_files(log_file, converted_files, total_time, conclusion_type):
- """
- Logs the conversion results to a file.
- """
- with open(log_file, 'a') as log:
- timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
- log.write(f"=== {timestamp} ===\n")
- log.write(f"Conclusion Type: {conclusion_type}\n")
- for file_name in converted_files:
- log.write(f"- {file_name}\n")
- log.write(f"Total Time Taken: {total_time:.2f} seconds\n")
- log.write(f"Total Number of Files Converted: {len(converted_files)}\n")
- log.write("=== End of Log Entry ===\n\n")
- def format_duration(seconds):
- """Converts time in seconds to a formatted string DD:HH:MM:SS."""
- days, remainder = divmod(seconds, 86400)
- hours, remainder = divmod(remainder, 3600)
- minutes, seconds = divmod(remainder, 60)
- return f"{int(days):02d}:{int(hours):02d}:{int(minutes):02d}:{int(seconds):02d}"
- def process_files():
- mp4_files = sorted([f for f in os.listdir(SOURCE_DIR) if f.lower().endswith('.mp4')])
- total_files = len(mp4_files)
- input_queue = queue.Queue()
- halt_flag = threading.Event()
- input_thread = threading.Thread(target=input_thread_func, args=(input_queue, halt_flag))
- input_thread.daemon = True
- input_thread.start()
- converted_files = []
- total_time = 0
- file_count = 0
- start_global_time = time.time()
- try:
- for mp4_file in mp4_files:
- file_path = os.path.join(SOURCE_DIR, mp4_file)
- file_size = os.path.getsize(file_path) / (1024 * 1024 * 1024) # File size in GB
- if halt_flag.is_set():
- log_converted_files(LOG_FILE, converted_files, total_time, "Halted")
- break
- file_count += 1
- print(f"\nFile {file_count} of {total_files}: {mp4_file} ({file_size:.2f} GB)")
- conversion_start_time = time.time()
- conversion_successful, processed_file, conversion_time = convert_to_mkv(SOURCE_DIR, mp4_file, MKVMERGE_EXE)
- total_time += conversion_time
- if conversion_successful:
- converted_files.append(processed_file)
- print(f"Conversion successful: {processed_file}")
- print(f"- Time Taken for This File: {conversion_time:.2f} seconds")
- elapsed_time = time.time() - start_global_time
- conversion_rate = file_count / elapsed_time * 60 # Conversion rate in files per minute
- estimated_time_remaining = (total_files - file_count) / conversion_rate * 60 if conversion_rate > 0 else 0
- average_time_per_file = total_time / file_count if file_count > 0 else 0 # Average time per file in seconds
- print(f"- Conversion Rate: {conversion_rate:.2f} files/minute")
- print(f"- Average Time per File: {average_time_per_file:.2f} seconds")
- print(f"- Estimated Time Remaining: {format_duration(estimated_time_remaining)}")
- print("-" * 50)
- if not input_queue.empty():
- user_input = input_queue.get()
- if user_input in ['n', 'no', 'exit', 'end', 'quit']:
- print("\nHalting MKV multiplexing per user request.")
- halt_flag.set()
- log_converted_files(LOG_FILE, converted_files, total_time, "User Halted")
- break
- if file_count % 20 == 0:
- log_converted_files(LOG_FILE, converted_files, total_time, "Periodic Update")
- converted_files = []
- except KeyboardInterrupt:
- print("\nScript halted by KeyboardInterrupt.")
- halt_flag.set()
- average_time_per_file = total_time / file_count if file_count > 0 else 0
- print(f"\nTotal Time Taken: {total_time:.2f} seconds")
- print(f"Average Time per File: {average_time_per_file:.2f} seconds")
- print(f"Total Number of Files Converted: {len(converted_files)}")
- log_converted_files(LOG_FILE, converted_files, total_time, "Keyboard Interrupt")
- if not halt_flag.is_set():
- print("\nAll files processed successfully.")
- log_converted_files(LOG_FILE, converted_files, total_time, "Completed")
- average_time_per_file = total_time / file_count if file_count > 0 else 0
- print(f"\nTotal Time Taken: {total_time:.2f} seconds")
- print(f"Average Time per File: {average_time_per_file:.2f} seconds")
- print(f"Total Number of Files Converted: {len(converted_files)}")
- if __name__ == "__main__":
- process_files()
Add Comment
Please, Sign In to add comment