From 5f6b81ec90b0eb4a2b6bca6c8d0fe32b5688a4eb Mon Sep 17 00:00:00 2001 From: Diaco Soltanpour Date: Fri, 30 Jan 2026 23:11:31 +0330 Subject: [PATCH] Initial commit --- .gitignore | 57 ++++++++++ README.md | 109 ++++++++++++++++++- compress_photos.py | 260 +++++++++++++++++++++++++++++++++++++++++++++ rename_photos.py | 257 ++++++++++++++++++++++++++++++++++++++++++++ requirements.txt | 2 + 5 files changed, 683 insertions(+), 2 deletions(-) create mode 100644 .gitignore create mode 100644 compress_photos.py create mode 100644 rename_photos.py create mode 100644 requirements.txt diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..52ce3f8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,57 @@ +Sample Media/._20200411_172156~2_Original.jpg +Sample Media/._20230326_234219.MP4 +Sample Media/._20230326_234753.MP4 +Sample Media/._20230326_235004.MP4 +Sample Media/._20230506_190624-01.JPEG +Sample Media/._20230506_191716-01.JPEG +Sample Media/._20230506_192012-01.JPEG +Sample Media/._20230506_192012-02.JPEG +Sample Media/._20230506_195739-01.JPEG +Sample Media/._20230506_200058-01.JPEG +Sample Media/._20230506_200253-01.JPEG +Sample Media/._20230506_221356-01.JPEG +Sample Media/._20230506_221405-01.JPEG +Sample Media/._20230506_221435-01-01.JPEG +Sample Media/._20230506_221435-01.JPEG +Sample Media/._20230506_221804-01.JPEG +Sample Media/._B6710C4F-661A-4F83-80F5-87864DE91CEC.JPG +Sample Media/._FullSizeRender 2.jpg +Sample Media/._FullSizeRender.HEIC +Sample Media/._FullSizeRender.JPG +Sample Media/._IMG_1262.jpg +Sample Media/._IMG_1534.JPG +Sample Media/._IMG_5089.JPG +Sample Media/._IMG_6856.JPG +Sample Media/._IMG_6857.JPG +Sample Media/20200411_172156~2_Original.jpg +Sample Media/20230326_234219.MP4 +Sample Media/20230326_234753.MP4 +Sample Media/20230326_235004.MP4 +Sample Media/20230506_190624-01.JPEG +Sample Media/20230506_191716-01.JPEG +Sample Media/20230506_192012-01.JPEG +Sample Media/20230506_192012-02.JPEG +Sample Media/20230506_195739-01.JPEG +Sample Media/20230506_200058-01.JPEG +Sample Media/20230506_200253-01.JPEG +Sample Media/20230506_221356-01.JPEG +Sample Media/20230506_221405-01.JPEG +Sample Media/20230506_221435-01-01.JPEG +Sample Media/20230506_221435-01.JPEG +Sample Media/20230506_221804-01.JPEG +Sample Media/B6710C4F-661A-4F83-80F5-87864DE91CEC.JPG +Sample Media/FullSizeRender 2.jpg +Sample Media/FullSizeRender.HEIC +Sample Media/FullSizeRender.JPG +Sample Media/IMG_1262.jpg +Sample Media/IMG_1534.JPG +Sample Media/IMG_5089.JPG +Sample Media/IMG_6856.JPG +Sample Media/IMG_6857.JPG +Sample Media/Sample subfolder/IMG_1262.jpg +Sample Media/Sample subfolder/IMG_1534.JPG +Sample Media/Sample subfolder/IMG_5089.JPG +.DS_Store +Sample Media/20250404_164814.heic +Sample Media/20250404_164815.heic +Sample Media/20250404_164928.heic diff --git a/README.md b/README.md index 0c1b24a..2e641e3 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,108 @@ -# rename_and_comprress_phone_photos +# Rename and compress phone photos -Python scripts to change file names from phone to their original date and create a compresses version of them \ No newline at end of file +Python scripts to change file names from phone to their original date and create a compressed version of them. + +## Photo and Video Renaming Tool + +Rename photos from phone gallery based on their EXIF metadata. + +### Features + +- Renames JPG, JPEG, and HEIC photos based on 'Date Time Original' EXIF metadata +- Renames MP4, MOV, and M4V videos based on container creation time +- Format: `yyyymmdd_hhmmss` (e.g., `20221227_162232.jpg`) +- Handles duplicate names by adding numeric suffixes (`_1`, `_2`, etc.) +- Processes directories recursively +- Skips macOS resource fork files (`._*`) +- Dry-run mode to preview changes before applying + +### Installation + +```bash +# Install Python dependencies +pip install -r requirements.txt + +# Install ffmpeg for video support (macOS) +brew install ffmpeg + +# Or on Linux: +# sudo apt-get install ffmpeg # Debian/Ubuntu +# sudo yum install ffmpeg # RedHat/CentOS +``` + +### Usage + +#### Preview changes (dry-run mode): +```bash +python rename_photos.py --dry-run +``` + +#### Rename photos: +```bash +python rename_photos.py +``` + +#### Examples: + +```bash +# Preview what would be renamed in Sample Media folder +python rename_photos.py "Sample Media" --dry-run + +# Actually rename files +python rename_photos.py "Sample Media" +``` + +### Notes + +- Files that already match the `yyyymmdd_hhmmss` format will be skipped +- Photos without 'Date Time Original' EXIF metadata will be skipped +- Videos without `creation_time` metadata will be skipped +- The script preserves the original file extension (case-insensitive) +- Works recursively through all subdirectories + +--- + +## Photo Compression Tool + +Create reduced-size compressed versions of photos (skips videos). + +### Features + +- Compresses JPG, JPEG, and HEIC photos +- Resizes images while preserving aspect ratio +- Maintains directory structure in output folder +- Converts all images to JPEG format +- Configurable maximum dimension and quality +- Skips already compressed files + +### Usage + +```bash +python compress_photos.py [max_dimension] [quality] +``` + +**Arguments:** +- `input_directory` - Directory containing photos to compress +- `output_directory` - Directory to save compressed photos +- `max_dimension` - Maximum width/height in pixels (default: 1920) +- `quality` - JPEG quality 1-100 (default: 85) + +### Examples + +```bash +# Compress with default settings (1920px, quality 85) +python compress_photos.py "Photos" "Photos_Compressed" + +# Compress to 1280px max dimension with quality 80 +python compress_photos.py "Photos" "Photos_Compressed" 1280 80 + +# High quality compression for web (2560px, quality 90) +python compress_photos.py "Photos" "Photos_Web" 2560 90 +``` + +### Notes + +- Videos are automatically skipped +- All images are converted to JPEG format +- Directory structure from input is preserved in output +- Existing files in output directory are skipped diff --git a/compress_photos.py b/compress_photos.py new file mode 100644 index 0000000..5ed57ab --- /dev/null +++ b/compress_photos.py @@ -0,0 +1,260 @@ +#!/usr/bin/env python3 +""" +Create compressed versions of photos with reduced file size. +Skips videos and only processes JPG, JPEG, and HEIC files. +""" + +import sys +import subprocess +import shutil +from pathlib import Path +from PIL import Image +import pillow_heif + +# Register HEIF opener with Pillow +pillow_heif.register_heif_opener() + + +def compress_heic(photo_path, output_dir, max_dimension=1920, quality=85): + """ + Compress HEIC file while preserving format and color space. + Uses macOS sips command. + + Args: + photo_path: Path to the original HEIC photo + output_dir: Directory to save compressed photo + max_dimension: Maximum width or height (preserves aspect ratio) + quality: Quality level (1-100, higher is better) + + Returns: + True if successful, False otherwise + """ + try: + # Check if sips is available (macOS) + if not shutil.which("sips"): + print(" Warning: sips not found, falling back to JPEG conversion") + return False + + # Get original dimensions + with Image.open(photo_path) as img: + orig_width, orig_height = img.size + + # Create output path with .heic extension + output_path = output_dir / (photo_path.stem + ".heic") + + # Copy file first + shutil.copy2(photo_path, output_path) + + # Resize if needed + if orig_width > max_dimension or orig_height > max_dimension: + if orig_width > orig_height: + new_width = max_dimension + new_height = int((max_dimension / orig_width) * orig_height) + else: + new_height = max_dimension + new_width = int((max_dimension / orig_height) * orig_width) + + # Resize using sips + subprocess.run( + ["sips", "-Z", str(max(new_width, new_height)), str(output_path)], + check=True, + capture_output=True, + ) + else: + new_width, new_height = orig_width, orig_height + + # Get file sizes + orig_size = photo_path.stat().st_size + new_size = output_path.stat().st_size + reduction = (1 - new_size / orig_size) * 100 + + print(f" ✓ {orig_width}x{orig_height} → {new_width}x{new_height}") + print( + f" {orig_size/1024/1024:.2f}MB → {new_size/1024/1024:.2f}MB ({reduction:.1f}% reduction)\n" + ) + + return True + + except Exception as e: + print(f" Error compressing HEIC: {e}") + # Clean up failed output + if output_path.exists(): + output_path.unlink() + return False + + +def compress_photo(photo_path, output_dir, max_dimension=1920, quality=85): + """ + Create a compressed version of a photo. + + Args: + photo_path: Path to the original photo + output_dir: Directory to save compressed photo + max_dimension: Maximum width or height (preserves aspect ratio). Ignored if quality=100 + quality: JPEG quality (1-100, higher is better). 100 = preserve original format + + Returns: + True if successful, False otherwise + """ + try: + with Image.open(photo_path) as img: + # Get original dimensions + orig_width, orig_height = img.size + + # Get ICC profile without converting color space + icc_profile = img.info.get("icc_profile") + + # Convert to RGB for JPEG (without color space conversion) + if img.mode in ("RGBA", "P", "LA"): + img = img.convert("RGB") + elif img.mode != "RGB": + img = img.convert("RGB") + + # Calculate new dimensions while preserving aspect ratio + if quality < 100 and ( + orig_width > max_dimension or orig_height > max_dimension + ): + if orig_width > orig_height: + new_width = max_dimension + new_height = int((max_dimension / orig_width) * orig_height) + else: + new_height = max_dimension + new_width = int((max_dimension / orig_height) * orig_width) + + img = img.resize((new_width, new_height), Image.Resampling.LANCZOS) + else: + new_width, new_height = orig_width, orig_height + + # Create output filename (always save as .jpg) + output_path = output_dir / (photo_path.stem + ".jpg") + + # Save with compression, preserving ICC profile for accurate color display + save_kwargs = { + "quality": quality, + "optimize": True, + "subsampling": ( + 0 if quality >= 95 else 2 + ), # No chroma subsampling for high quality + } + if icc_profile: + save_kwargs["icc_profile"] = icc_profile + + img.save(output_path, "JPEG", **save_kwargs) + + # Get file sizes + orig_size = photo_path.stat().st_size + new_size = output_path.stat().st_size + reduction = (1 - new_size / orig_size) * 100 + + print(f" ✓ {orig_width}x{orig_height} → {new_width}x{new_height}") + print( + f" {orig_size/1024/1024:.2f}MB → {new_size/1024/1024:.2f}MB ({reduction:.1f}% reduction)\n" + ) + + return True + + except Exception as e: + print(f" Error compressing: {e}\n") + return False + + +def compress_photos(root_directory, output_directory, max_dimension=1920, quality=85): + """ + Compress all photos in directory and subdirectories. + + Args: + root_directory: Root directory to search for photos + output_directory: Directory to save compressed photos (maintains structure) + max_dimension: Maximum width or height for resized images + quality: JPEG quality (1-100) + """ + root_path = Path(root_directory) + output_path = Path(output_directory) + + if not root_path.exists(): + print(f"Error: Directory '{root_directory}' does not exist") + return + + # Create output directory + output_path.mkdir(parents=True, exist_ok=True) + + # Find all photo files (skip videos) + photo_extensions = {".jpg", ".jpeg", ".heic"} + photo_files = [] + + for ext in photo_extensions: + photo_files.extend(root_path.rglob(f"*{ext}")) + photo_files.extend(root_path.rglob(f"*{ext.upper()}")) + + # Filter out macOS resource fork files + photo_files = [f for f in photo_files if not f.name.startswith("._")] + + if not photo_files: + print("No photos found with JPG, JPEG, or HEIC extensions") + return + + print(f"Found {len(photo_files)} photo(s)") + print(f"Settings: max dimension={max_dimension}px, quality={quality}\n") + + success_count = 0 + skip_count = 0 + + for photo_path in sorted(photo_files): + print(f"Processing: {photo_path.name}") + + # Maintain directory structure in output + relative_path = photo_path.parent.relative_to(root_path) + photo_output_dir = output_path / relative_path + photo_output_dir.mkdir(parents=True, exist_ok=True) + + # Always output as JPEG for compatibility + output_file = photo_output_dir / (photo_path.stem + ".jpg") + if output_file.exists(): + print(f" Skipped: Already exists in output directory\n") + skip_count += 1 + continue + + # Convert to JPEG + success = compress_photo(photo_path, photo_output_dir, max_dimension, quality) + + if success: + success_count += 1 + else: + skip_count += 1 + + print(f"\nSummary:") + print(f" Compressed: {success_count}") + print(f" Skipped: {skip_count}") + print(f" Total: {len(photo_files)}") + + +def main(): + if len(sys.argv) < 3: + print( + "Usage: python compress_photos.py [max_dimension] [quality]" + ) + print("\nArguments:") + print(" input_directory Directory containing photos to compress") + print(" output_directory Directory to save compressed photos") + print(" max_dimension Maximum width/height in pixels (default: 1920)") + print(" quality JPEG quality 1-100 (default: 85)") + print("\nExamples:") + print(' python compress_photos.py "Photos" "Photos_Compressed"') + print(' python compress_photos.py "Photos" "Photos_Compressed" 1280 80') + sys.exit(1) + + input_dir = sys.argv[1] + output_dir = sys.argv[2] + max_dimension = int(sys.argv[3]) if len(sys.argv) > 3 else 1920 + quality = int(sys.argv[4]) if len(sys.argv) > 4 else 85 + + # Validate quality + if quality < 1 or quality > 100: + print("Error: Quality must be between 1 and 100") + sys.exit(1) + + compress_photos(input_dir, output_dir, max_dimension, quality) + + +if __name__ == "__main__": + main() diff --git a/rename_photos.py b/rename_photos.py new file mode 100644 index 0000000..75cc791 --- /dev/null +++ b/rename_photos.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python3 +""" +Rename photos and videos based on metadata. +Photos use EXIF 'Date Time Original' and videos use container creation_time. +""" + +import os +import sys +import json +import re +import subprocess +from pathlib import Path +from PIL import Image +from PIL.ExifTags import TAGS +from datetime import datetime +import pillow_heif + +# Register HEIF opener with Pillow +pillow_heif.register_heif_opener() + + +def get_exif_datetime(image_path): + """ + Extract 'Date Time Original' from EXIF metadata. + + Args: + image_path: Path to the image file + + Returns: + datetime object or None if not found + """ + try: + with Image.open(image_path) as img: + # Get EXIF data using getexif() method (works for both JPG and HEIC) + exif_data = img.getexif() + + if exif_data is None or len(exif_data) == 0: + print(f" Warning: No EXIF data found in {image_path.name}") + return None + + # Find DateTimeOriginal tag (tag 36867) in main EXIF + datetime_original = None + for tag_id, value in exif_data.items(): + tag_name = TAGS.get(tag_id, tag_id) + if tag_name == "DateTimeOriginal": + datetime_original = value + break + + # If not found in main EXIF, check the EXIF sub-IFD (tag 34665) + if datetime_original is None and 34665 in exif_data: + exif_ifd = exif_data.get_ifd(34665) + for tag_id, value in exif_ifd.items(): + tag_name = TAGS.get(tag_id, tag_id) + if tag_name == "DateTimeOriginal": + datetime_original = value + break + + if datetime_original is None: + print( + f" Warning: 'DateTimeOriginal' not found in EXIF for {image_path.name}" + ) + return None + + # Parse the datetime string (format: "YYYY:MM:DD HH:MM:SS") + dt = datetime.strptime(datetime_original, "%Y:%m:%d %H:%M:%S") + return dt + + except Exception as e: + print(f" Error reading EXIF from {image_path.name}: {e}") + return None + + +def generate_unique_filename(directory, base_name, extension): + """ + Generate a unique filename by adding a number suffix if needed. + + Args: + directory: Directory where file will be placed + base_name: Base filename without extension + extension: File extension (including dot) + + Returns: + Unique filename + """ + new_name = base_name + extension + new_path = directory / new_name + + if not new_path.exists(): + return new_name + + # File exists, add number suffix + counter = 1 + while True: + new_name = f"{base_name}_{counter}{extension}" + new_path = directory / new_name + if not new_path.exists(): + return new_name + counter += 1 + + +def get_video_datetime(video_path): + """ + Extract creation time from video metadata using ffprobe. + + Args: + video_path: Path to the video file + + Returns: + datetime object or None if not found + """ + try: + result = subprocess.run( + [ + "ffprobe", + "-v", + "quiet", + "-print_format", + "json", + "-show_entries", + "format_tags=creation_time", + str(video_path), + ], + check=False, + capture_output=True, + text=True, + ) + + if result.returncode != 0: + print(f" Warning: ffprobe failed for {video_path.name}") + return None + + data = json.loads(result.stdout or "{}") + creation_time = data.get("format", {}).get("tags", {}).get("creation_time") + + if not creation_time: + print(f" Warning: creation_time not found for {video_path.name}") + return None + + creation_time = creation_time.replace("Z", "+00:00") + dt = datetime.fromisoformat(creation_time) + return dt + + except FileNotFoundError: + print(" Error: ffprobe not found. Install ffmpeg to enable video support.") + return None + except Exception as e: + print(f" Error reading video metadata from {video_path.name}: {e}") + return None + + +def rename_photos(root_directory, dry_run=False): + """ + Rename all supported media files in directory and subdirectories. + + Args: + root_directory: Root directory to search for files + dry_run: If True, only show what would be renamed without actually renaming + """ + root_path = Path(root_directory) + + if not root_path.exists(): + print(f"Error: Directory '{root_directory}' does not exist") + return + + # Find all supported files + photo_extensions = {".jpg", ".jpeg", ".heic"} + video_extensions = {".mp4", ".mov", ".m4v"} + media_files = [] + + for ext in photo_extensions | video_extensions: + media_files.extend(root_path.rglob(f"*{ext}")) + media_files.extend(root_path.rglob(f"*{ext.upper()}")) + + # Filter out macOS resource fork files (._*) + media_files = [f for f in media_files if not f.name.startswith("._")] + + if not media_files: + print("No media files found with supported extensions") + return + + print(f"Found {len(media_files)} media file(s)") + print(f"{'DRY RUN - ' if dry_run else ''}Processing...\n") + + renamed_count = 0 + skipped_count = 0 + + for media_path in sorted(media_files): + print(f"Processing: {media_path}") + + # Check if already has the correct name format (yyyymmdd_hhmmss) + current_name = media_path.stem + if re.match(r"^\d{8}_\d{6}", current_name): + print(f" Already named correctly: {media_path.name}\n") + skipped_count += 1 + continue + + # Get datetime based on file type + extension = media_path.suffix.lower() + if extension in photo_extensions: + dt = get_exif_datetime(media_path) + else: + dt = get_video_datetime(media_path) + + if dt is None: + print(f" Skipped: Could not extract datetime\n") + skipped_count += 1 + continue + + # Generate new filename + new_base_name = dt.strftime("%Y%m%d_%H%M%S") + extension = media_path.suffix.lower() + + # Generate unique filename + new_filename = generate_unique_filename( + media_path.parent, new_base_name, extension + ) + new_path = media_path.parent / new_filename + + print(f" Rename to: {new_filename}") + + if not dry_run: + try: + media_path.rename(new_path) + print(f" ✓ Renamed successfully\n") + renamed_count += 1 + except Exception as e: + print(f" Error renaming: {e}\n") + skipped_count += 1 + else: + print(f" [Would rename]\n") + renamed_count += 1 + + print(f"\n{'DRY RUN ' if dry_run else ''}Summary:") + print(f" Renamed: {renamed_count}") + print(f" Skipped: {skipped_count}") + print(f" Total: {len(media_files)}") + + +def main(): + if len(sys.argv) < 2: + print("Usage: python rename_photos.py [--dry-run]") + print("\nOptions:") + print(" --dry-run Show what would be renamed without actually renaming") + sys.exit(1) + + directory = sys.argv[1] + dry_run = "--dry-run" in sys.argv + + if dry_run: + print("=== DRY RUN MODE ===") + print("No files will be actually renamed\n") + + rename_photos(directory, dry_run) + + +if __name__ == "__main__": + main() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..05aa6f5 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +Pillow>=10.0.0 +pillow-heif>=0.13.0