Advertisement
zelenooki87

Topaz Photo AI - batch video upscaling script

Oct 19th, 2024 (edited)
345
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.64 KB | Science | 0 0
  1. import os
  2. import sys
  3. import subprocess
  4. import glob
  5. import time
  6.  
  7. def get_average_fps(video_path):
  8.     """Gets the average FPS of a video using ffprobe."""
  9.     cmd = ['ffprobe', '-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=avg_frame_rate',
  10.            '-of', 'default=noprint_wrappers=1:nokey=1', video_path]
  11.     process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
  12.     output, error = process.communicate()
  13.     if process.returncode != 0:
  14.         raise RuntimeError(f'ffprobe error: {error}')
  15.     num, den = map(int, output.strip().split('/'))
  16.     return num / den
  17.  
  18. def process_video(input_video_path, output_dir):
  19.     """Processes a video using Topaz Photo AI and ffmpeg."""
  20.     video_name = os.path.splitext(os.path.basename(input_video_path))[0]
  21.     temp_dir = os.path.join(output_dir, "temp_frames", video_name)
  22.     upscaled_dir = os.path.join(output_dir, "temp_frames", video_name + "_upscaled")
  23.     os.makedirs(temp_dir, exist_ok=True)
  24.     os.makedirs(upscaled_dir, exist_ok=True)
  25.  
  26.     avg_framerate = get_average_fps(input_video_path)
  27.  
  28.     # Extract frames
  29.     subprocess.run([
  30.         'ffmpeg', '-i', input_video_path, '-vf', f'fps={avg_framerate}', f'{temp_dir}/frame%04d.bmp'
  31.     ])
  32.  
  33.     # Upscale frames using Topaz Photo AI
  34.     subprocess.run([
  35.         'tpai', '--format', 'tiff', '--bit-depth', '16', '-o', upscaled_dir, temp_dir
  36.     ], check=True)  # check=True raises an exception if the command fails
  37.  
  38.  
  39.     # Combine upscaled frames back into video
  40.     output_video_path = os.path.join(output_dir, video_name + "_upscaled.mov")
  41.     subprocess.run([
  42.         'ffmpeg', '-y', '-framerate', str(avg_framerate),
  43.         '-i', f'{upscaled_dir}/frame%04d.tiff',  # Input TIFF files
  44.         '-i', input_video_path, '-map', '0:v', '-map', '1:a',
  45.         '-c:v', 'ffv1', '-pix_fmt', 'rgb48',
  46.         '-metadata:s:v:0', 'encoder=FFV1', '-level', '3', '-g', '1',
  47.         '-slices', '24', '-slicecrc', '1', output_video_path
  48.     ])
  49.  
  50.     # Clean up temporary frames
  51.     subprocess.run(['rm', '-r', temp_dir])
  52.     subprocess.run(['rm', '-r', upscaled_dir])
  53.  
  54.  
  55. if __name__ == "__main__":
  56.     input_dir = "."  # Current directory
  57.     output_dir = "output"
  58.     os.makedirs(output_dir, exist_ok=True)
  59.  
  60. # Find all video files in the input directory using ffmpeg
  61.     input_video_paths = []
  62.     for file in os.listdir(input_dir):
  63.         file_path = os.path.join(input_dir, file)
  64.         try:
  65.             probe_cmd = ['ffprobe', '-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=codec_type',
  66.                        '-of', 'default=noprint_wrappers=1:nokey=1', file_path]
  67.             process = subprocess.Popen(probe_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
  68.             output, error = process.communicate()
  69.             if process.returncode == 0 and output.strip() == 'video':
  70.                 input_video_paths.append(file_path)
  71.         except Exception as e:
  72.             print(f"Error checking file {file_path}: {e}")
  73.  
  74. # Process each video file and store processing times
  75.     processing_times = []
  76.     for input_video_path in input_video_paths:
  77.         start_time = time.time()
  78.         print(f"Processing video: {input_video_path}")
  79.         process_video(input_video_path, output_dir)
  80.         end_time = time.time()
  81.         processing_time = end_time - start_time
  82.         processing_times.append((input_video_path, processing_time))
  83.  
  84. # Print processing times after all videos are processed
  85.     print("\nProcessing times:")
  86.     for input_video_path, processing_time in processing_times:
  87.         print(f"{input_video_path}: {processing_time:.2f} seconds")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement