Optimize this code, add GPU acceleration.
```python
import os
import subprocess
import re
import time
import psutil
from tqdm import tqdm

def get_system_info():
    """Get system information for optimal resource usage"""
    cpu_count_physical = psutil.cpu_count(logical=False) or 1
    cpu_count_logical = psutil.cpu_count(logical=True) or 2
    memory_gb = round(psutil.virtual_memory().total / (1024**3), 1)
    
    # Get available disk space
    disk_usage = psutil.disk_usage('/')
    available_gb = round(disk_usage.free / (1024**3), 1)
    
    # Determine optimal thread count (leave some resources for system)
    optimal_threads = max(1, cpu_count_logical - 1)
    
    return {
        "cpu_physical": cpu_count_physical,
        "cpu_logical": cpu_count_logical,
        "memory_gb": memory_gb,
        "available_gb": available_gb,
        "optimal_threads": optimal_threads
    }

def check_codec_availability(codec):
    """Check if a codec is available in the current ffmpeg installation"""
    try:
        result = subprocess.run(
            ["ffmpeg", "-encoders"],
            capture_output=True,
            text=True,
            check=True
        )
        return codec in result.stdout
    except:
        return False

def get_video_duration(file_path):
    """Get the duration of a video file in seconds"""
    try:
        result = subprocess.run(
            ["ffprobe", "-v", "error", "-show_entries", "format=duration", 
             "-of", "default=noprint_wrappers=1:nokey=1", file_path],
            capture_output=True,
            text=True,
            check=True
        )
        return float(result.stdout.strip())
    except:
        return None

def get_file_size(file_path):
    """Get file size in GB"""
    try:
        size_bytes = os.path.getsize(file_path)
        size_gb = size_bytes / (1024**3)
        return round(size_gb, 2)
    except:
        return 0

def parse_progress(line):
    """Parse ffmpeg progress output"""
    time_match = re.search(r'time=(\d+):(\d+):(\d+)', line)
    if time_match:
        hours, minutes, seconds = map(int, time_match.groups())
        return hours * 3600 + minutes * 60 + seconds
    
    # Alternative format: out_time_ms or out_time
    time_ms_match = re.search(r'out_time_ms=(\d+)', line)
    if time_ms_match:
        return int(time_ms_match.group(1)) / 1000
    
    time_match = re.search(r'out_time=(\d+):(\d+):(\d+\.\d+)', line)
    if time_match:
        hours, minutes, seconds = time_match.groups()
        return int(hours) * 3600 + int(minutes) * 60 + float(seconds)
    
    return None

def run_ffmpeg_with_progress(cmd, description, total_duration):
    """Run ffmpeg command with progress bar"""
    print(f"Command: {' '.join(cmd)}\n")
    
    process = subprocess.Popen(
        cmd,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        universal_newlines=True,
        bufsize=1
    )
    
    with tqdm(total=total_duration, desc=description, unit="s", 
              bar_format="{desc}: {percentage:3.0f}%|{bar}| {n:.0f}s/{total:.0f}s [{elapsed}<{remaining}]") as pbar:
        
        # Monitor stderr for progress
        stderr_lines = []
        while process.poll() is None:
            stderr_line = process.stderr.readline()
            if stderr_line:
                stderr_lines.append(stderr_line)
                progress = parse_progress(stderr_line)
                if progress is not None and progress <= total_duration:
                    pbar.n = progress
                    pbar.refresh()
        
        # Get remaining output
        remaining_stderr = process.stderr.read()
        if remaining_stderr:
            stderr_lines.append(remaining_stderr)
        
        stderr = "".join(stderr_lines)
        return_code = process.returncode
        
        # Complete the progress bar
        if return_code == 0:
            pbar.n = total_duration
            pbar.refresh()
    
    if return_code != 0:
        print(f"❌ Error: FFmpeg failed with return code {return_code}")
        if stderr:
            print(f"Error details: {stderr[:500]}..." if len(stderr) > 500 else stderr)
        return False
    
    print(f"✅ {description} completed successfully!")
    return True

def generate_noise_video(threads, duration=3600):
    """Generate random noise video"""
    output_file = "output.mkv"
    
    cmd = [
        "ffmpeg",
        "-f", "lavfi",
        "-i", "nullsrc=s=32x32:r=69.420,geq=random(1)*255:random(1)*255:random(1)*255",
        "-f", "lavfi",
        "-i", "aevalsrc=-2+random(0):s=98000:c=mono",
        "-allow_raw_vfw", "1",
        "-c:v", "rawvideo",
        "-pix_fmt", "rgb24",
        "-sample_fmt", "s64",
        "-c:a", "pcm_s64le",
        "-t", str(duration),
        "-threads", str(threads),
        "-y",
        output_file
    ]
    
    success = run_ffmpeg_with_progress(cmd, "🎥 Generating noise video", duration)
    if success:
        size_gb = get_file_size(output_file)
        print(f"📁 Raw video size: {size_gb} GB")
    
    return output_file if success else None

def upscale_to_4k_h264(input_file, threads, duration=3600):
    """Upscale to 4K using H.264 (most compatible)"""
    output_file = "output_4K_H264.mkv"
    
    cmd = [
        "ffmpeg",
        "-i", input_file,
        "-vf", "scale=3840:2160:flags=lanczos",
        "-c:v", "libx264",
        "-preset", "medium",
        "-crf", "23",
        "-c:a", "copy",
        "-threads", str(threads),
        "-y",
        output_file
    ]
    
    success = run_ffmpeg_with_progress(cmd, "🚀 Upscaling to 4K with H264", duration)
    return output_file if success else None

def upscale_to_4k_h265(input_file, threads, duration=3600):
    """Upscale to 4K using H.265/HEVC"""
    output_file = "output_4K_H265.mkv"
    
    cmd = [
        "ffmpeg",
        "-i", input_file,
        "-vf", "scale=3840:2160:flags=lanczos",
        "-c:v", "libx265",
        "-preset", "medium",
        "-crf", "28",
        "-c:a", "copy",
        "-threads", str(threads),
        "-y",
        output_file
    ]
    
    success = run_ffmpeg_with_progress(cmd, "🚀 Upscaling to 4K with H265", duration)
    return output_file if success else None

def upscale_to_4k_av1(input_file, threads, duration=3600):
    """Upscale to 4K using AV1 (if available)"""
    output_file = "output_4K_AV1.mkv"
    
    # Check if SVT-AV1 is available
    has_svtav1 = check_codec_availability("libsvtav1")
    
    if has_svtav1:
        cmd = [
            "ffmpeg",
            "-i", input_file,
            "-vf", "scale=3840:2160:flags=lanczos",
            "-c:v", "libsvtav1",
            "-preset", "6",  # Range is 0-13, higher is faster but lower quality
            "-crf", "30",    # Range is 0-63, lower is higher quality
            "-c:a", "copy",
            "-threads", str(threads),
            "-y",
            output_file
        ]
    else:
        # Try libaom-av1 as fallback
        has_aomav1 = check_codec_availability("libaom-av1")
        if has_aomav1:
            cmd = [
                "ffmpeg",
                "-i", input_file,
                "-vf", "scale=3840:2160:flags=lanczos",
                "-c:v", "libaom-av1",
                "-cpu-used", "4",  # Range is 0-8, higher is faster but lower quality
                "-crf", "30",      # Range is 0-63, lower is higher quality
                "-c:a", "copy",
                "-threads", str(threads),
                "-y",
                output_file
            ]
        else:
            print("❌ AV1 codec not available. Falling back to H.265.")
            return upscale_to_4k_h265(input_file, threads, duration)
    
    success = run_ffmpeg_with_progress(cmd, "🚀 Upscaling to 4K with AV1", duration)
    return output_file if success else upscale_to_4k_h265(input_file, threads, duration)

def install_dependencies():
    """Install required dependencies"""
    print("Installing dependencies...")
    
    # Install ffmpeg if not already installed
    try:
        subprocess.run(["ffmpeg", "-version"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
    except:
        subprocess.run(["apt-get", "update", "-qq"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        subprocess.run(["apt-get", "install", "-y", "ffmpeg"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    
    # Install Python dependencies
    try:
        import tqdm
        import psutil
    except ImportError:
        subprocess.run(["pip", "install", "tqdm", "psutil"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    
    print("Dependencies installed!")

def main():
    """Main function to run the video generation and upscaling pipeline"""
    print("\n🎬 Starting Noise Video Generation and 4K Upscaling Pipeline")
    print("=" * 60)
    
    # Install dependencies
    install_dependencies()
    
    # Get system info
    sys_info = get_system_info()
    print(f"💻 System Info:")
    print(f"   CPU Cores: {sys_info['cpu_physical']} physical, {sys_info['cpu_logical']} logical")
    print(f"   Memory: {sys_info['memory_gb']} GB")
    print(f"   Available Disk: {sys_info['available_gb']} GB")
    
    threads = sys_info['optimal_threads']
    print(f"🔧 Using {threads} threads for optimal performance\n")
    
    # Generate noise video
    raw_video = generate_noise_video(threads)
    if not raw_video:
        print("❌ Failed to generate raw video. Exiting.")
        return
    
    # Get actual duration
    duration = get_video_duration(raw_video)
    if not duration:
        duration = 3600  # Fallback to 1 hour
    
    # Ask user for codec choice with fallback options
    print("\nChoose codec for 4K upscaling:")
    print("1. H.265/HEVC (good compression, wide compatibility)")
    print("2. H.264/AVC (best compatibility, larger file size)")
    print("3. AV1 (best compression, limited compatibility)")
    
    choice = input("Enter choice (1, 2, or 3, default=1): ").strip() or "1"
    
    # Process based on choice with fallbacks
    if choice == "3":
        output_file = upscale_to_4k_av1(raw_video, threads, duration)
        if not output_file:
            print("⚠️ AV1 encoding failed, falling back to H.265...")
            output_file = upscale_to_4k_h265(raw_video, threads, duration)
    elif choice == "2":
        output_file = upscale_to_4k_h264(raw_video, threads, duration)
    else:  # Default to H.265
        output_file = upscale_to_4k_h265(raw_video, threads, duration)
    
    if output_file and os.path.exists(output_file):
        size_gb = get_file_size(output_file)
        print(f"\n🎉 Processing complete!")
        print(f"📁 Final video size: {size_gb} GB")
        print(f"📺 Output file: {output_file}")
    else:
        print("\n❌ Failed to create final video.")

if __name__ == "__main__":
    main()
```