Examples
This page provides practical code examples for using AI Image Renamer CLI as a Python library.
Basic Examples
Rename a Single Image
python
import argparse
from ai_image_renamer import ImageRenamer
# Create arguments
args = argparse.Namespace(
image_paths=["vacation.jpg"],
words=6
)
# Rename the image
renamer = ImageRenamer(args)Rename Multiple Images
python
import argparse
from ai_image_renamer import ImageRenamer
args = argparse.Namespace(
image_paths=[
"photos/beach.jpg",
"photos/mountain.png",
"photos/city.webp"
],
words=5
)
renamer = ImageRenamer(args)Custom Word Count
python
import argparse
from ai_image_renamer import ImageRenamer
# Short, concise names
args = argparse.Namespace(
image_paths=["screenshot.png"],
words=3
)
renamer = ImageRenamer(args)
# Result: "code-editor.png" (approximately)Advanced Examples
Preview Without Renaming
Use utility functions to see what would happen without actually renaming:
python
import os
from ai_image_renamer import verify_image_file, get_words, sanitize_image_path
os.environ["GROQ_API_KEY"] = "gsk_xxx"
def preview_rename(image_path: str, words: int = 6):
"""Show what the new filename would be without renaming."""
if not verify_image_file(image_path):
print(f"❌ Invalid: {image_path}")
return None
description = get_words(image_path, words)
if not description:
print(f"❌ AI failed: {image_path}")
return None
new_path = sanitize_image_path(image_path, description)
print(f"✅ {image_path}")
print(f" → {os.path.basename(new_path)}")
print(f" Description: {description}")
return new_path
# Preview multiple files
for img in ["photo1.jpg", "photo2.jpg", "photo3.jpg"]:
preview_rename(img, words=5)Batch Processing with Logging
python
import argparse
import os
import sys
from datetime import datetime
from ai_image_renamer import ImageRenamer, verify_image_file
def batch_rename_with_log(directory: str, log_file: str = "rename_log.txt"):
"""Rename all images in a directory and log the results."""
# Find all images
image_extensions = {'.jpg', '.jpeg', '.png', '.webp', '.gif'}
image_paths = []
for filename in os.listdir(directory):
ext = os.path.splitext(filename)[1].lower()
if ext in image_extensions:
full_path = os.path.join(directory, filename)
if verify_image_file(full_path):
image_paths.append(full_path)
print(f"Found {len(image_paths)} images to process")
# Open log file
with open(log_file, 'w') as log:
log.write(f"Rename Log - {datetime.now()}\n")
log.write("=" * 50 + "\n\n")
# Process each image
for path in image_paths:
original_name = os.path.basename(path)
log.write(f"Original: {original_name}\n")
# Capture stdout to log
old_stdout = sys.stdout
class Logger:
def __init__(self, log, stdout):
self.log = log
self.stdout = stdout
def write(self, text):
self.log.write(text)
self.stdout.write(text)
def flush(self):
self.log.flush()
self.stdout.flush()
sys.stdout = Logger(log, old_stdout)
try:
args = argparse.Namespace(image_paths=[path], words=6)
renamer = ImageRenamer(args)
log.write("\n")
except Exception as e:
log.write(f"ERROR: {e}\n\n")
finally:
sys.stdout = old_stdout
print(f"\nLog saved to: {log_file}")
# Usage
batch_rename_with_log("/Users/me/Photos/vacation/")Custom Pipeline with Error Recovery
python
import os
import time
from ai_image_renamer import verify_image_file, get_words, sanitize_image_path
os.environ["GROQ_API_KEY"] = "gsk_xxx"
def rename_with_retry(image_path: str, words: int = 6, max_retries: int = 3):
"""Rename with automatic retry on API failures."""
if not verify_image_file(image_path):
return None, "Invalid image file"
for attempt in range(max_retries):
try:
description = get_words(image_path, words)
if description:
new_path = sanitize_image_path(image_path, description)
if len(new_path) > 3:
os.rename(image_path, new_path)
return new_path, None
else:
return None, "Generated filename too short"
else:
if attempt < max_retries - 1:
print(f"Retry {attempt + 1}/{max_retries} for {image_path}")
time.sleep(2) # Wait before retry
else:
return None, "AI analysis failed after retries"
except Exception as e:
if attempt < max_retries - 1:
print(f"Error, retrying: {e}")
time.sleep(2)
else:
return None, str(e)
return None, "Max retries exceeded"
# Process directory with error tracking
def process_directory(directory: str):
successes = []
failures = []
for filename in os.listdir(directory):
if filename.lower().endswith(('.jpg', '.jpeg', '.png', '.webp')):
path = os.path.join(directory, filename)
new_path, error = rename_with_retry(path, words=5)
if new_path:
successes.append((filename, os.path.basename(new_path)))
else:
failures.append((filename, error))
print(f"\n✅ Successes: {len(successes)}")
for old, new in successes:
print(f" {old} → {new}")
print(f"\n❌ Failures: {len(failures)}")
for old, error in failures:
print(f" {old}: {error}")
process_directory("./photos/")Integration with File Watcher
python
import os
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from ai_image_renamer import verify_image_file, get_words, sanitize_image_path
os.environ["GROQ_API_KEY"] = "gsk_xxx"
class ImageRenameHandler(FileSystemEventHandler):
"""Automatically rename new images in a watched directory."""
def __init__(self, words: int = 6):
self.words = words
def on_created(self, event):
if event.is_directory:
return
# Wait for file to be fully written
time.sleep(1)
path = event.src_path
if verify_image_file(path):
print(f"New image detected: {path}")
description = get_words(path, self.words)
if description:
new_path = sanitize_image_path(path, description)
if len(new_path) > 3:
os.rename(path, new_path)
print(f"Renamed to: {os.path.basename(new_path)}")
def watch_directory(directory: str, words: int = 6):
"""Watch a directory and auto-rename new images."""
event_handler = ImageRenameHandler(words)
observer = Observer()
observer.schedule(event_handler, directory, recursive=False)
observer.start()
print(f"Watching {directory} for new images...")
print("Press Ctrl+C to stop")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
# Usage
watch_directory("./uploads/", words=5)Generate Report of Current Names
python
import os
from ai_image_renamer import verify_image_file, get_words
os.environ["GROQ_API_KEY"] = "gsk_xxx"
def generate_descriptions_report(directory: str, output_file: str = "descriptions.txt"):
"""Generate a report of AI descriptions for all images."""
report_lines = []
image_count = 0
for filename in sorted(os.listdir(directory)):
path = os.path.join(directory, filename)
if verify_image_file(path):
image_count += 1
description = get_words(path, words=10)
line = f"{filename}: {description}"
report_lines.append(line)
print(f"Processed {image_count}: {filename}")
with open(output_file, 'w') as f:
f.write(f"Image Descriptions Report\n")
f.write(f"Generated for: {directory}\n")
f.write(f"Images processed: {image_count}\n")
f.write("=" * 60 + "\n\n")
f.write('\n'.join(report_lines))
print(f"\nReport saved to: {output_file}")
generate_descriptions_report("./photos/")Filter by Content
python
import os
from ai_image_renamer import verify_image_file, get_words
os.environ["GROQ_API_KEY"] = "gsk_xxx"
def find_images_by_keyword(directory: str, keyword: str):
"""Find images that contain a specific subject."""
matches = []
for filename in os.listdir(directory):
path = os.path.join(directory, filename)
if verify_image_file(path):
description = get_words(path, words=15)
if keyword.lower() in description.lower():
matches.append({
'path': path,
'description': description
})
print(f"✅ {filename}: {description}")
print(f"\nFound {len(matches)} images matching '{keyword}'")
return matches
# Find all beach photos
find_images_by_keyword("./vacation-photos/", "beach")Web Integration
Flask API Endpoint
python
from flask import Flask, request, jsonify
from ai_image_renamer import verify_image_file, get_words, sanitize_image_path
import os
import tempfile
app = Flask(__name__)
os.environ["GROQ_API_KEY"] = "gsk_xxx"
@app.route('/analyze', methods=['POST'])
def analyze_image():
"""API endpoint to analyze an uploaded image."""
if 'image' not in request.files:
return jsonify({'error': 'No image provided'}), 400
file = request.files['image']
words = request.form.get('words', 6, type=int)
# Save to temp file
with tempfile.NamedTemporaryFile(delete=False, suffix='..' + file.filename.split('.')[-1]) as tmp:
file.save(tmp.name)
tmp_path = tmp.name
try:
if not verify_image_file(tmp_path):
return jsonify({'error': 'Invalid image file'}), 400
description = get_words(tmp_path, words)
if not description:
return jsonify({'error': 'AI analysis failed'}), 500
suggested_name = os.path.basename(
sanitize_image_path(tmp_path, description)
)
return jsonify({
'description': description,
'suggested_filename': suggested_name,
'words': words
})
finally:
os.unlink(tmp_path)
if __name__ == '__main__':
app.run(debug=True)Related Topics
- ImageRenamer Class — Main class documentation
- Utility Functions — Individual function docs
- Installation — Setting up the environment