Utility Functions
The utils module provides atomic operations for image validation, encoding, and AI interaction. These functions can be used independently for custom workflows.
Function Reference
verify_image_file()
Validate that a file path points to a supported image file.
Signature
def verify_image_file(image_path: str) -> bool:
...Parameters
| Name | Type | Description |
|---|---|---|
image_path | str | Path to the file to validate |
Returns
bool — True if the file is a valid image, False otherwise.
Description
This function performs two validations:
- Existence check: Does the file exist?
- Type detection: Is it a supported image format?
The type detection uses magic bytes (file headers), not file extensions. This is more secure and accurate than trusting extensions.
Supported Formats
| Format | Magic Bytes | MIME Type |
|---|---|---|
| JPEG | FF D8 FF | image/jpeg |
| PNG | 89 50 4E 47 | image/png |
| WebP | 52 49 46 46 ... 57 45 42 50 | image/webp |
| GIF | 47 49 46 38 | image/gif |
Examples
from ai_image_renamer import verify_image_file
# Valid image
verify_image_file("photo.jpg") # True
verify_image_file("image.png") # True
verify_image_file("graphic.webp") # True
# Invalid cases
verify_image_file("document.pdf") # False (not an image)
verify_image_file("nonexistent.jpg") # False (doesn't exist)
verify_image_file("folder/") # False (directory)
verify_image_file("fake.jpg") # False (if content isn't JPEG)Use Case
Filter files before processing:
from ai_image_renamer import verify_image_file
import os
# Get all files in a directory
all_files = os.listdir("photos/")
# Filter to only valid images
image_files = [
f for f in all_files
if verify_image_file(os.path.join("photos", f))
]
print(f"Found {len(image_files)} valid images")encode_image()
Convert an image file to a Base64-encoded string.
Signature
def encode_image(image_path: str) -> str:
...Parameters
| Name | Type | Description |
|---|---|---|
image_path | str | Path to the image file |
Returns
str — Base64-encoded string of the file contents.
Raises
| Exception | Condition |
|---|---|
FileNotFoundError | File doesn't exist |
PermissionError | No read permission |
OSError | Filesystem error |
Description
Base64 encoding converts binary image data into ASCII text, which is required for JSON payloads in API requests.
The returned string is raw Base64 — it doesn't include the data URL prefix (data:image/jpeg;base64,).
Examples
from ai_image_renamer import encode_image
# Encode an image
encoded = encode_image("photo.jpg")
# Result is a long string
print(encoded[:50]) # "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgH..."
print(len(encoded)) # Depends on file size
# Use in data URL
data_url = f"data:image/jpeg;base64,{encoded}"Memory Considerations
The entire file is loaded into memory. For very large images:
# 10 MB image → ~13.3 MB Base64 string in memory
# Consider chunked processing for files > 50 MBsanitize_image_path()
Generate a clean, SEO-friendly filename from a description.
Signature
def sanitize_image_path(image_path: str, image_content: str) -> str:
...Parameters
| Name | Type | Description |
|---|---|---|
image_path | str | Original file path (for directory and extension) |
image_content | str | Descriptive text to convert to filename |
Returns
str — Absolute path with sanitized filename.
Description
Transforms a text description into a valid, SEO-friendly filename:
- Convert to lowercase
- Remove non-alphabetic characters (keep only a-z and spaces)
- Replace spaces with hyphens
- Preserve the original file extension
Examples
from ai_image_renamer import sanitize_image_path
# Basic transformation
sanitize_image_path("IMG_001.jpg", "sunset beach palm trees")
# "/absolute/path/to/sunset-beach-palm-trees.jpg"
# Handles punctuation
sanitize_image_path("photo.png", "Dog's ball! Playing @ park.")
# "/absolute/path/to/dogs-ball-playing-park.png"
# Preserves extension case-insensitively
sanitize_image_path("PHOTO.JPG", "mountain view")
# "/absolute/path/to/mountain-view.jpg"
# Non-alphabetic content results in short name
sanitize_image_path("test.jpg", "123 456 !!!")
# "/absolute/path/to/.jpg" (empty slug)Directory Handling
# Relative paths become absolute
sanitize_image_path("photos/img.jpg", "description")
# "/current/working/dir/photos/description.jpg"
# Absolute paths are preserved
sanitize_image_path("/Users/me/Desktop/photo.jpg", "family portrait")
# "/Users/me/Desktop/family-portrait.jpg"get_words()
Generate an AI-powered description of an image.
Signature
def get_words(image_path: str, words: int = 6) -> str:
...Parameters
| Name | Type | Default | Description |
|---|---|---|---|
image_path | str | required | Path to the image file |
words | int | 6 | Maximum words in description |
Returns
str — AI-generated description, or empty string on failure.
Raises
| Exception | Condition |
|---|---|
RuntimeError | GROQ_API_KEY not set |
FileNotFoundError | Image file doesn't exist |
Description
Sends the image to Groq's API for analysis using the Llama 4 Scout model. The response is a short, SEO-friendly description.
Environment Variable Required
import os
os.environ["GROQ_API_KEY"] = "gsk_your-key-here"Examples
import os
from ai_image_renamer import get_words
# Set API key
os.environ["GROQ_API_KEY"] = "gsk_xxx"
# Get description
description = get_words("beach.jpg", words=5)
print(description) # "sunset beach palm trees ocean"
# Default word count (6)
description = get_words("photo.jpg")
print(description) # "family having picnic sunny park day"
# Handle failures
description = get_words("invalid.jpg", 6)
if not description:
print("Failed to analyze image")Error Handling
import os
from ai_image_renamer import get_words
# Missing API key
try:
get_words("photo.jpg", 6)
except RuntimeError as e:
print(f"API key error: {e}")
# "GROQ_API_KEY environment variable is not set..."
# File doesn't exist
try:
get_words("nonexistent.jpg", 6)
except FileNotFoundError as e:
print(f"File not found: {e}")API Details
| Parameter | Value |
|---|---|
| Model | meta-llama/llama-4-scout-17b-16e-instruct |
| Temperature | 2.0 (high creativity) |
| Prompt | "What's in this image? Describe with N words in an SEO-friendly way" |
Complete Workflow Example
import os
from ai_image_renamer import (
verify_image_file,
encode_image,
get_words,
sanitize_image_path
)
# Set API key
os.environ["GROQ_API_KEY"] = "gsk_xxx"
def rename_image_smart(path: str, words: int = 6) -> str:
"""
Custom rename function with full control.
Returns the new path, or empty string on failure.
"""
# Step 1: Validate
if not verify_image_file(path):
print(f"Invalid image: {path}")
return ""
# Step 2: Get AI description
description = get_words(path, words)
if not description:
print(f"AI analysis failed: {path}")
return ""
# Step 3: Generate new filename
new_path = sanitize_image_path(path, description)
if len(new_path) <= 3:
print(f"Filename too short: {path}")
return ""
# Step 4: Preview (don't actually rename)
print(f"Would rename: {path} -> {new_path}")
# Step 5: Uncomment to actually rename
# os.rename(path, new_path)
return new_path
# Usage
rename_image_smart("vacation.jpg", words=5)Related Topics
- ImageRenamer Class — High-level API
- Examples — More code samples
- How It Works — Pipeline explanation