#!/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()