diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..7a79a90 Binary files /dev/null and b/.DS_Store differ diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..ff07ce2 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,46 @@ +# Git +.git +.gitignore + +# Python +__pycache__ +*.py[cod] +*$py.class +*.so +.Python +.venv +venv/ +ENV/ +.eggs/ +*.egg-info/ +.pytest_cache/ + +# IDE +.idea/ +.vscode/ +*.swp +*.swo + +# Video files (will be mounted via volume) +*.mp4 +*.avi +*.mov +*.mkv +*.gif +videos/ + +# Model files (downloaded at build time) +*.pt + +# Docker +Dockerfile +docker-compose.yml +.dockerignore + +# Docs +README.md +*.md + + + + diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..5e7e80e --- /dev/null +++ b/Dockerfile @@ -0,0 +1,48 @@ +# Multi-stage build for smaller final image +FROM python:3.11-slim AS builder + +WORKDIR /app + +# Install build dependencies +RUN apt-get update && apt-get install -y --no-install-recommends \ + build-essential \ + && rm -rf /var/lib/apt/lists/* + +# Copy and install Python dependencies +COPY requirements.txt . +RUN pip install --no-cache-dir --user -r requirements.txt + +# Final stage +FROM python:3.11-slim + +WORKDIR /app + +# Install FFmpeg and OpenCV dependencies +RUN apt-get update && apt-get install -y --no-install-recommends \ + ffmpeg \ + libgl1 \ + libglib2.0-0 \ + libsm6 \ + libxext6 \ + libxrender1 \ + && rm -rf /var/lib/apt/lists/* + +# Copy installed packages from builder +COPY --from=builder /root/.local /root/.local +ENV PATH=/root/.local/bin:$PATH + +# Copy application code +COPY main.py . + +# Create directories for input/output videos +RUN mkdir -p /videos/input /videos/output + +# Pre-download YOLO model on build (optional, speeds up first run) +RUN python -c "from ultralytics import YOLO; YOLO('yolov8n.pt')" + +# Set working directory for video processing +WORKDIR /videos + +ENTRYPOINT ["python", "/app/main.py"] +CMD ["--help"] + diff --git a/README.md b/README.md index f27eaf0..529b3c2 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,8 @@ This script is built on a pipeline that uses specialized libraries for each step ### Usage +#### Option A: Local Installation + 1. **Clone the repository:** ```bash git clone https://github.com/kamilstanuch/AutoCrop-Vertical.git @@ -61,15 +63,45 @@ This script is built on a pipeline that uses specialized libraries for each step The `yolov8n.pt` model weights will be downloaded automatically on the first run. 3. **Run the script:** - Use the `--input` and `--output` arguments to specify the source and destination files. + You can provide a local file or a YouTube URL. + **Local file:** ```bash - python main.py --input path/to/horizontal_video.mp4 --output path/to/vertical_video.mp4 + python main.py --input path/to/video.mp4 --output path/to/output.mp4 + ``` + + **YouTube URL:** + ```bash + # Auto-generates output name + python main.py --url "https://www.youtube.com/watch?v=VIDEO_ID" + + # Specific output name + python main.py --url "https://www.youtube.com/watch?v=VIDEO_ID" --output vertical_video.mp4 + ``` + +#### Option B: Running with Docker (Recommended) + +Docker is the easiest way to run the project as it includes all dependencies (FFmpeg, OpenCV, etc.) pre-configured. + +1. **Build the image:** + ```bash + docker compose build + ``` + +2. **Process a local video:** + Place your video in a `videos/` folder (it will be mounted inside the container). + ```bash + docker compose run --rm autocrop -i /videos/input/video.mp4 -o /videos/output/video_vertical.mp4 + ``` + +3. **Process a YouTube video:** + ```bash + docker compose run --rm autocrop -u "https://www.youtube.com/watch?v=VIDEO_ID" -o /videos/output/vertical.mp4 ``` --- -### Prerequisites +### Prerequisites (for Local Installation) * Python 3.8+ * **FFmpeg:** This script requires `ffmpeg` to be installed and available in your system's PATH. It can be installed via a package manager (e.g., `brew install ffmpeg` on macOS, `sudo apt install ffmpeg` on Debian/Ubuntu). diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..fc0dbc8 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,19 @@ +services: + autocrop: + build: + context: . + dockerfile: Dockerfile + image: autocrop-vertical:latest + container_name: autocrop-vertical + volumes: + # Mount local videos directory for input/output + - ./videos:/videos + # Examples: + # From local file: + # docker compose run --rm autocrop -i /videos/input/video.mp4 -o /videos/output/video_vertical.mp4 + # From YouTube URL: + # docker compose run --rm autocrop -u "https://youtube.com/watch?v=VIDEO_ID" -o /videos/output/video_vertical.mp4 + # From YouTube (auto-named output): + # docker compose run --rm autocrop -u "https://youtube.com/watch?v=VIDEO_ID" + command: ["--help"] + diff --git a/main.py b/main.py index 6d99530..74c87b8 100644 --- a/main.py +++ b/main.py @@ -3,6 +3,7 @@ import cv2 import scenedetect import subprocess import argparse +import re from scenedetect import VideoManager, SceneManager from scenedetect.detectors import ContentDetector from ultralytics import YOLO @@ -10,6 +11,7 @@ import torch import os import numpy as np from tqdm import tqdm +import yt_dlp # --- Constants --- ASPECT_RATIO = 9 / 16 @@ -129,16 +131,112 @@ def get_video_resolution(video_path): cap.release() return width, height + +def sanitize_filename(filename): + """Remove invalid characters from filename.""" + # Remove invalid characters for filenames + filename = re.sub(r'[<>:"/\\|?*]', '', filename) + # Replace spaces with underscores + filename = filename.replace(' ', '_') + # Limit length + return filename[:100] + + +def download_youtube_video(url, output_dir="."): + """ + Downloads a YouTube video using yt-dlp. + Returns the path to the downloaded video and the video title. + """ + print("šŸ“„ Downloading video from YouTube...") + step_start_time = time.time() + + # First, get video info to determine the title + ydl_opts_info = { + 'quiet': True, + 'no_warnings': True, + } + + with yt_dlp.YoutubeDL(ydl_opts_info) as ydl: + info = ydl.extract_info(url, download=False) + video_title = info.get('title', 'youtube_video') + sanitized_title = sanitize_filename(video_title) + + # Download the video + # Force H.264 codec (avc1) instead of AV1 for better compatibility with OpenCV + output_template = os.path.join(output_dir, f'{sanitized_title}.%(ext)s') + + # Delete existing file if present (to force re-download with correct codec) + expected_file = os.path.join(output_dir, f'{sanitized_title}.mp4') + if os.path.exists(expected_file): + os.remove(expected_file) + print(f"šŸ—‘ļø Removed existing file to re-download with H.264 codec") + + ydl_opts = { + 'format': 'bestvideo[vcodec^=avc1][ext=mp4]+bestaudio[ext=m4a]/bestvideo[vcodec^=avc1]+bestaudio/best[ext=mp4]/best', + 'outtmpl': output_template, + 'merge_output_format': 'mp4', + 'quiet': False, + 'no_warnings': True, + 'overwrites': True, # Force overwrite if file exists + } + + with yt_dlp.YoutubeDL(ydl_opts) as ydl: + ydl.download([url]) + + # Find the downloaded file + downloaded_file = os.path.join(output_dir, f'{sanitized_title}.mp4') + + if not os.path.exists(downloaded_file): + # Try to find any file matching the pattern + for f in os.listdir(output_dir): + if f.startswith(sanitized_title) and f.endswith('.mp4'): + downloaded_file = os.path.join(output_dir, f) + break + + step_end_time = time.time() + print(f"āœ… Video downloaded in {step_end_time - step_start_time:.2f}s: {downloaded_file}") + + return downloaded_file, sanitized_title + + if __name__ == '__main__': parser = argparse.ArgumentParser(description="Smartly crops a horizontal video into a vertical one.") - parser.add_argument('-i', '--input', type=str, required=True, help="Path to the input video file.") - parser.add_argument('-o', '--output', type=str, required=True, help="Path to the output video file.") + + # Create mutually exclusive group for input source + input_group = parser.add_mutually_exclusive_group(required=True) + input_group.add_argument('-i', '--input', type=str, help="Path to the input video file.") + input_group.add_argument('-u', '--url', type=str, help="YouTube URL to download and process.") + + parser.add_argument('-o', '--output', type=str, help="Path to the output video file. (Auto-generated if not provided with --url)") + parser.add_argument('--keep-original', action='store_true', help="Keep the downloaded YouTube video after processing.") args = parser.parse_args() script_start_time = time.time() - - input_video = args.input - final_output_video = args.output + + downloaded_video = None # Track if we downloaded a video + + # Handle YouTube URL + if args.url: + # Determine output directory + output_dir = os.path.dirname(args.output) if args.output else "." + if output_dir == "": + output_dir = "." + os.makedirs(output_dir, exist_ok=True) + + # Download the video + input_video, video_title = download_youtube_video(args.url, output_dir) + downloaded_video = input_video + + # Generate output filename if not provided + if args.output: + final_output_video = args.output + else: + final_output_video = os.path.join(output_dir, f"{video_title}_vertical.mp4") + else: + if not args.output: + parser.error("--output is required when using --input") + input_video = args.input + final_output_video = args.output # Define temporary file paths based on the output name base_name = os.path.splitext(final_output_video)[0] @@ -288,6 +386,11 @@ if __name__ == '__main__': # Clean up temp files os.remove(temp_video_output) os.remove(temp_audio_output) + + # Clean up downloaded YouTube video if not keeping it + if downloaded_video and not args.keep_original: + os.remove(downloaded_video) + print(f"šŸ—‘ļø Cleaned up downloaded video: {downloaded_video}") script_end_time = time.time() print(f"\nšŸŽ‰ All done! Final video saved to {final_output_video}") diff --git a/requirements.txt b/requirements.txt index 15d3ec2..b944e78 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,3 +4,4 @@ ultralytics torch torchvision tqdm +yt-dlp diff --git a/videos/.DS_Store b/videos/.DS_Store new file mode 100644 index 0000000..db6a42f Binary files /dev/null and b/videos/.DS_Store differ diff --git a/videos/output/.DS_Store b/videos/output/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/videos/output/.DS_Store differ