|

Media File Optimizer

This guide is designed for your website and provides a complete, step-by-step walkthrough for building an automated media optimizer. This system uses Python to “watch” a folder and automatically convert images to WebP and optimize videos using FFmpeg.


๐Ÿš€ Building an Automated Media Optimizer for Windows 11

In this guide, we will build a “Hot Folder” system. Any PNG or MP4 you drop into your source folder will be automatically processed, moved to a destination folder, and the original will be cleaned up.

1. The Toolkit (Prerequisites)

We need three main components. Instead of relying on Windows to find them, we will store them in a dedicated folder: C:\Tools.

Step A: Install Python 3.x

  1. Download the latest version from python.org.
  2. Important: During installation, select Customize installation.
  3. Under Advanced Options, change the install location to C:\Python312 (or your version number).
  4. Check the box for “Add Python to environment variables”.

Step B: Download the Binaries (The “Engine”)

  • FFmpeg (Video): Download the “release-essentials” zip from Gyan.dev. Extract ffmpeg.exe into C:\Tools.
  • cwebp (Images): Download the WebP zip from WebM Project. Extract cwebp.exe into C:\Tools.

2. Setting Up the Python Environment

Open PowerShell and install the Watchdog library, which allows Python to monitor file system events in real-time:

PowerShell

pip install watchdog

3. The Automation Script

Create a file named optimizer.py. This script uses hard-coded paths to your tools to ensure 100% reliability regardless of your system settings.

Python

import os, subprocess, time
from pathlib import Path
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

# --- CONFIGURATION ---
SOURCE_DIR = r"C:\AI-PNG"
IMAGE_DEST = r"C:\AI-PNG\WEBP"
VIDEO_DEST = r"C:\AI-PNG\OPTIMIZED_VIDEO"

# Hard-coded tool paths
CWEBP_EXE = r"C:\Tools\cwebp.exe"
FFMPEG_EXE = r"C:\Tools\ffmpeg.exe"

def delete_original(file_path):
    try:
        os.remove(file_path)
        print(f"๐Ÿ—‘๏ธ Cleaned up: {file_path.name}")
    except Exception as e:
        print(f"โš ๏ธ Cleanup failed: {e}")

def process_file(file_path):
    ext = file_path.suffix.lower()
    
    # PNG to WebP Conversion
    if ext == '.png':
        output = os.path.join(IMAGE_DEST, file_path.stem + ".webp")
        print(f"๐Ÿ“ธ Processing Image: {file_path.name}")
        result = subprocess.run([CWEBP_EXE, "-q", "75", str(file_path), "-o", output])
        if result.returncode == 0: delete_original(file_path)

    # MP4 Optimization (No Audio, Web-Ready)
    elif ext == '.mp4' and "_web" not in file_path.name:
        output = os.path.join(VIDEO_DEST, file_path.stem + "_web.mp4")
        print(f"๐ŸŽฅ Processing Video: {file_path.name}")
        result = subprocess.run([
            FFMPEG_EXE, "-i", str(file_path), "-vcodec", "libx264", 
            "-crf", "28", "-an", "-movflags", "+faststart", output
        ])
        if result.returncode == 0: delete_original(file_path)

class Handler(FileSystemEventHandler):
    def on_created(self, event):
        if not event.is_directory:
            time.sleep(1) # Wait for file copy to finish
            process_file(Path(event.src_path))

if __name__ == "__main__":
    for d in [IMAGE_DEST, VIDEO_DEST]: os.makedirs(d, exist_ok=True)
    observer = Observer()
    observer.schedule(Handler(), SOURCE_DIR, recursive=False)
    observer.start()
    print(f"๐Ÿš€ Monitor Active on {SOURCE_DIR}...")
    try:
        while True: time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

4. Running as a Background Service

To make this run automatically when you turn on your computer without a messy console window:

  1. Rename the file from optimizer.py to optimizer.pyw. The .pyw extension tells Windows to run the script silently in the background.
  2. Use Task Scheduler:
    • Search for Task Scheduler in the Start Menu.
    • Click Create Task.
    • Trigger: Set to “At log on”.
    • Action: Set to “Start a program”.
    • Program/script: pythonw.exe
    • Add arguments: The full path to your script (e.g., C:\ai-png\optimizer.pyw).

๐Ÿ› ๏ธ Troubleshooting Tips

  • Permissions: Run PowerShell as Administrator if the script fails to create folders.
  • FFmpeg Errors: Ensure ffmpeg.exe is actually in C:\Tools and not in a subfolder like C:\Tools\bin.
  • Wait Times: For very large videos, increase the time.sleep(1) to time.sleep(5) to ensure the file is fully “unlocked” by Windows before processing begins.

Similar Posts

  • Install Portainer-CE on Linux

  • Pi-hole is built natively for Linux

  • Pinokio Create AI Apps

  • Run WordPress on Linux with MySQL and PHP.

  • Optimize Website Photos for Speed