import requests
import os
from pathlib import Path
# Replace 'YOUR_API_KEY' with your actual RapidAPI key
API_KEY = 'YOUR_API_KEY'
# API endpoint for uploading an image
url = "https://lunapic-photo-effects.p.rapidapi.com/upload-image"
# Headers required by RapidAPI
headers = {
"X-RapidAPI-Key": API_KEY,
"X-RapidAPI-Host": "lunapic-photo-effects.p.rapidapi.com"
}
# Directories for input and output
input_dir = "input_images" # Directory containing images to process
output_dir = "output_images" # Directory to save processed images
# Ensure directories exist
Path(input_dir).mkdir(exist_ok=True)
Path(output_dir).mkdir(exist_ok=True)
# Optional: Specify a filter to apply (e.g., "cartoon", "sketch")
filter_effect = "cartoon"
# Supported image extensions
image_extensions = (".jpg", ".jpeg", ".png", ".bmp")
def process_image(image_path, output_dir):
"""Process a single image and save the result."""
file_name = os.path.basename(image_path)
output_file_name = f"processed_{file_name}"
output_path = os.path.join(output_dir, output_file_name)
# Skip if output file already exists
if os.path.exists(output_path):
print(f"Skipping {file_name} - already processed.")
return
# Prepare the file for upload
files = {
"upload-image": (file_name, open(image_path, "rb"), "image/jpeg")
}
data = {"filter": filter_effect} if filter_effect else {}
try:
# Upload the image
response = requests.post(url, headers=headers, files=files, data=data)
if response.status_code == 200:
result = response.json()
if "output_url" in result:
output_url = result["output_url"]
print(f"Processing {file_name} succeeded. Downloading result...")
# Download the processed image
image_response = requests.get(output_url)
if image_response.status_code == 200:
with open(output_path, "wb") as f:
f.write(image_response.content)
print(f"Saved processed image to {output_path}")
else:
print(f"Failed to download processed image for {file_name}: {image_response.status_code}")
else:
print(f"No output URL in response for {file_name}: {result}")
else:
print(f"Upload failed for {file_name}: {response.status_code} - {response.text}")
except requests.exceptions.RequestException as e:
print(f"Error processing {file_name}: {e}")
finally:
files["file"][1].close()
def batch_process_images(input_dir, output_dir):
"""Process all images in the input directory."""
print(f"Starting batch processing from {input_dir}...")
# Get list of image files
image_files = [
f for f in os.listdir(input_dir)
if f.lower().endswith(image_extensions)
]
if not image_files:
print(f"No images found in {input_dir} with extensions {image_extensions}")
return
# Process each image
for image_file in image_files:
image_path = os.path.join(input_dir, image_file)
process_image(image_path, output_dir)
print("Batch processing complete!")
# Run the batch processing
if __name__ == "__main__":
batch_process_images(input_dir, output_dir) |