ImageRenamer Class
The ImageRenamer class is the main orchestrator for the image renaming pipeline. It coordinates validation, AI analysis, and file operations.
Class Definition
class ImageRenamer:
def __init__(self, args: argparse.Namespace) -> None:
...
def rename(self) -> None:
...Module: ai_image_renamer.renamer
Import:
from ai_image_renamer import ImageRenamer
# or
from ai_image_renamer.renamer import ImageRenamerConstructor
__init__(self, args)
Initialize and immediately process all specified images.
Parameters:
| Name | Type | Description |
|---|---|---|
args | argparse.Namespace | Parsed arguments containing image_paths (list[str]) and words (int) |
Attributes Set:
| Attribute | Type | Description |
|---|---|---|
self.args | argparse.Namespace | Stored arguments |
self.image_paths | list[str] | List of image paths to process |
Side Effects:
- Calls
self.rename()automatically - Renames files on the filesystem
- Prints progress to stdout
Example:
import argparse
args = argparse.Namespace(
image_paths=["photo.jpg", "image.png"],
words=6
)
renamer = ImageRenamer(args)
# Output:
# Processing photo.jpg...
# Renamed photo.jpg to /path/descriptive-name.jpg
# Processing image.png...
# Renamed image.png to /path/another-name.pngMethods
rename(self) -> None
Process and rename all images in self.image_paths.
This method implements the complete renaming pipeline:
- Verification: Skip invalid images
- Content Extraction: Get AI description
- Path Sanitization: Generate clean filename
- File Rename: Execute the rename operation
Returns: None
Side Effects:
- Renames files on the filesystem
- Prints progress messages to stdout
Pipeline Details:
def rename(self):
for path in self.image_paths:
# Step 1: Validate
if not verify_image_file(path):
print(f"Skipping invalid image file: {path}")
continue
# Step 2: AI Analysis
print(f"Processing {path}...")
content = get_words(path, self.args.words)
if not content:
print(f"Failed to retrieve content from image: {path}")
continue
# Step 3: Sanitize
new_path = sanitize_image_path(path, content)
if len(new_path) <= 3:
print(f"Generated filename too short, skipping: {path}")
continue
# Step 4: Rename
os.rename(path, new_path)
print(f"Renamed {path} to {new_path}")Error Handling:
| Condition | Behavior |
|---|---|
| Invalid file | Skip with warning, continue |
| API failure | Skip with warning, continue |
| Short filename | Skip silently, continue |
| File in use | Exception propagates |
Usage Patterns
Basic Usage
import argparse
from ai_image_renamer import ImageRenamer
args = argparse.Namespace(
image_paths=["vacation.jpg"],
words=5
)
renamer = ImageRenamer(args)Processing Multiple Files
import argparse
from ai_image_renamer import ImageRenamer
args = argparse.Namespace(
image_paths=[
"photos/img1.jpg",
"photos/img2.jpg",
"photos/img3.png"
],
words=6
)
renamer = ImageRenamer(args)Custom Word Count
import argparse
from ai_image_renamer import ImageRenamer
# Short filenames
args_short = argparse.Namespace(
image_paths=["photo.jpg"],
words=3
)
# Detailed filenames
args_detailed = argparse.Namespace(
image_paths=["photo.jpg"],
words=15
)With Error Handling
import argparse
import os
from ai_image_renamer import ImageRenamer
args = argparse.Namespace(
image_paths=["photo.jpg"],
words=6
)
try:
renamer = ImageRenamer(args)
except RuntimeError as e:
print(f"Configuration error: {e}")
# Handle missing API key
except FileNotFoundError as e:
print(f"File not found: {e}")
except PermissionError as e:
print(f"Permission denied: {e}")Post-Processing
Since ImageRenamer renames files immediately, capture paths beforehand if you need to reference them:
import argparse
import os
from ai_image_renamer import ImageRenamer
image_paths = ["photo.jpg", "image.png"]
original_paths = [os.path.abspath(p) for p in image_paths]
args = argparse.Namespace(
image_paths=image_paths,
words=6
)
renamer = ImageRenamer(args)
# Note: original_paths still point to old names
# You'd need to track renames separately if neededDesign Notes
Immediate Execution
The class processes images in __init__() rather than requiring a separate rename() call. This design choice:
- Simplifies usage: One line to rename images
- Matches CLI behavior:
rename-images photo.jpgis immediate - Reduces boilerplate: No separate "run" method
No Return Value
The constructor and rename() return None. Results are communicated via:
- Side effects: Files are renamed
- Print output: Progress shown in console
- Exceptions: Errors propagate to caller
If you need the new filenames, use utility functions directly.
Sequential Processing
Files are processed one at a time, not in parallel. This is intentional to:
- Stay within API rate limits
- Provide ordered, readable output
- Simplify error handling
Related Topics
- Utility Functions — Lower-level operations
- Examples — Complete code samples
- How It Works — Pipeline explanation
CLI Entry Point
main() Function
The CLI entry point that parses arguments and invokes ImageRenamer.
Module: ai_image_renamer.cli
Import:
from ai_image_renamer import main
# or
from ai_image_renamer.cli import mainFunction Signature:
def main() -> None:
...What It Does:
- Loads environment variables from
.envfile - Creates argument parser with
--wordsand--versionoptions - Parses command-line arguments
- Instantiates
ImageRenamer
Example:
import sys
from ai_image_renamer.cli import main
# Simulate command-line arguments
sys.argv = ["rename-images", "photo.jpg", "-w", "5"]
# Run the CLI
main()Normally Used Via:
# This is configured in pyproject.toml:
# [project.scripts]
# rename-images = "ai_image_renamer.cli:main"
rename-images photo.jpg