Of course! This is a fantastic use case for PySpark. We'll create a robust ETL job that can process a large number of images efficiently.
Here is a complete guide, including the PySpark code and step-by-step instructions on how to run it on AWS.
Overview of the Solution
The process will follow these steps:
- Read Data: We'll use PySpark's
binaryFile format to read each image file from S3 into a DataFrame. Each row will contain the file's path, modification time, and its raw binary content.
- Process with a UDF: We'll define a User Defined Function (UDF) that takes the binary content of an image. Inside this function, we'll use popular Python libraries (
Pillow and exifread) to extract the metadata.
- Structure the Data: The UDF will return a structured object (a
StructType) containing all the extracted metadata (e.g., dimensions, format, camera model, GPS data).
- Write Output: We'll flatten this structured data into new columns in our DataFrame and write the final result to S3 in either CSV or Parquet format.
Prerequisites
- AWS Account: You need an AWS account with an S3 bucket for input images and another for the output metadata.
- PySpark Environment: You need a place to run the Spark job. The most common choices on AWS are:
- AWS EMR (Elastic MapReduce): A managed cluster service. Ideal for large-scale, customizable jobs.
- AWS Glue: A serverless ETL service. Simpler to manage but less flexible than EMR.
- IAM Role: The EMR cluster or Glue job will need an IAM Role with permissions to read from the input S3 bucket and write to the output S3 bucket.
- Python Libraries: The script relies on
Pillow for basic image info and exifread for detailed EXIF data. These will need to be installed on the Spark cluster.
Step 1: The PySpark ETL Script
This script is the core of our solution. It's designed to be robust, handling potential errors like corrupted images or missing EXIF data.
Save this code as image_metadata_etl.py.
import io
from pyspark.sql import SparkSession
from pyspark.sql.functions import udf, col
from pyspark.sql.types import StructType, StructField, StringType, IntegerType, DoubleType, TimestampType
# Using Pillow for image dimensions and format, and exifread for detailed EXIF data
try:
from PIL import Image
import exifread
except ImportError:
print("Required libraries not found. Please install Pillow and exifread.")
# On AWS Glue or EMR, you'll install these as dependencies.
# 1. DEFINE THE SCHEMA FOR THE METADATA UDF
# It's a best practice to define the schema for UDFs. It improves performance and prevents errors.
metadata_schema = StructType([
StructField("format", StringType(), True),
StructField("mode", StringType(), True),
StructField("width", IntegerType(), True),
StructField("height", IntegerType(), True),
StructField("image_datetime", StringType(), True), # EXIF DateTime
StructField("camera_make", StringType(), True), # EXIF Make
StructField("camera_model", StringType(), True), # EXIF Model
StructField("f_number", StringType(), True), # EXIF FNumber
StructField("iso_speed", StringType(), True), # EXIF ISOSpeedRatings
StructField("latitude", DoubleType(), True), # GPS Latitude
StructField("longitude", DoubleType(), True), # GPS Longitude
StructField("error", StringType(), True) # Field to log any errors during processing
])
# 2. CREATE THE METADATA EXTRACTION FUNCTION
def extract_metadata(binary_content):
"""
Takes the binary content of an image and extracts metadata.
Returns a dictionary matching the metadata_schema.
"""
try:
# --- GPS Helper Function ---
def _get_if_exist(data, key):
if key in data:
return data[key]
return None
def _convert_to_degress(value):
d = float(value.values[0].num) / float(value.values[0].den)
m = float(value.values[1].num) / float(value.values[1].den)
s = float(value.values[2].num) / float(value.values[2].den)
return d + (m / 60.0) + (s / 3600.0)
# --- Main Extraction Logic ---
image_data = {}
img_io = io.BytesIO(binary_content)
# Use Pillow for basic metadata
with Image.open(img_io) as img:
image_data["format"] = img.format
image_data["mode"] = img.mode
image_data["width"] = img.width
image_data["height"] = img.height
# Reset stream position for exifread
img_io.seek(0)
# Use exifread for detailed EXIF tags
tags = exifread.process_file(img_io, details=False)
# Safely extract common EXIF tags
image_data["image_datetime"] = str(_get_if_exist(tags, 'Image DateTime'))
image_data["camera_make"] = str(_get_if_exist(tags, 'Image Make'))
image_data["camera_model"] = str(_get_if_exist(tags, 'Image Model'))
image_data["f_number"] = str(_get_if_exist(tags, 'EXIF FNumber'))
image_data["iso_speed"] = str(_get_if_exist(tags, 'EXIF ISOSpeedRatings'))
# Extract and convert GPS data if available
lat_tag = _get_if_exist(tags, 'GPS GPSLatitude')
lon_tag = _get_if_exist(tags, 'GPS GPSLongitude')
lat_ref_tag = _get_if_exist(tags, 'GPS GPSLatitudeRef')
lon_ref_tag = _get_if_exist(tags, 'GPS GPSLongitudeRef')
if lat_tag and lon_tag and lat_ref_tag and lon_ref_tag:
lat = _convert_to_degress(lat_tag)
lon = _convert_to_degress(lon_tag)
if str(lat_ref_tag) != 'N': lat = -lat
if str(lon_ref_tag) != 'W': lon = -lon
image_data["latitude"] = lat
image_data["longitude"] = lon
return image_data
except Exception as e:
# If anything goes wrong (e.g., not an image, corrupted file), log the error
return {"error": str(e)}
# 3. REGISTER THE UDF
extract_metadata_udf = udf(extract_metadata, metadata_schema)
def run_job(spark, input_path, output_path, output_format):
"""Main ETL job function."""
# 4. READ THE IMAGES FROM S3
# 'binaryFile' format reads files as (path, modificationTime, length, content)
# 'recursiveFileLookup' allows reading from subdirectories
df_raw = spark.read.format("binaryFile") \
.option("pathGlobFilter", "*.{jpg,jpeg,png,tiff}") \
.option("recursiveFileLookup", "true") \
.load(input_path)
# 5. APPLY THE UDF AND EXTRACT METADATA
df_with_metadata = df_raw.withColumn("metadata", extract_metadata_udf(col("content")))
# Filter out rows where metadata extraction failed
df_successful = df_with_metadata.filter(col("metadata.error").isNull())
# OPTIONAL: Save rows that failed for later inspection
df_failed = df_with_metadata.filter(col("metadata.error").isNotNull())
if not df_failed.rdd.isEmpty():
df_failed.select("path", "metadata.error") \
.write.mode("overwrite").format("csv").option("header", "true") \
.save(f"{output_path}/_failed_records")
# 6. FLATTEN THE METADATA STRUCT INTO COLUMNS
# Select original columns and expand the metadata struct
df_final = df_successful.select(
col("path"),
col("modificationTime"),
col("length"),
col("metadata.*") # This neat trick expands the struct into columns
)
# 7. WRITE THE OUTPUT TO S3
print(f"Writing {df_final.count()} records to {output_path} in {output_format} format...")
df_final.write.mode("overwrite") \
.format(output_format) \
.option("header", "true") \
.save(output_path)
print("Job completed successfully!")
if __name__ == "__main__":
# Initialize Spark Session
spark = SparkSession.builder \
.appName("ImageMetadataExtraction") \
.getOrCreate()
# Define S3 paths
# IMPORTANT: Replace these with your actual S3 bucket paths
S3_INPUT_PATH = "s3://your-input-bucket/images/"
S3_OUTPUT_PATH_PARQUET = "s3://your-output-bucket/metadata/parquet/"
S3_OUTPUT_PATH_CSV = "s3://your-output-bucket/metadata/csv/"
# Run the job for Parquet
run_job(spark, S3_INPUT_PATH, S3_OUTPUT_PATH_PARQUET, "parquet")
# Run the job for CSV
# run_job(spark, S3_INPUT_PATH, S3_OUTPUT_PATH_CSV, "csv")
# Stop the Spark session
spark.stop()
Step 2: Handling Python Dependencies
Your Spark cluster's worker nodes need the Pillow and exifread libraries. Here's how to package them.
- Create a
requirements.txt file:
Pillow==9.4.0
exifread==3.0.0
- Create a dependency zip file:
On your local machine (with Python and pip installed), run these commands:
# Create a directory to hold the packages
mkdir dependencies
cd dependencies
# Install the packages into the current directory
pip install -t . -r ../requirements.txt
# Zip the contents
zip -r ../dependencies.zip .
cd ..
# Now you have a 'dependencies.zip' file in your project root.
- Upload to S3: Upload
image_metadata_etl.py and dependencies.zip to an S3 bucket that your Spark job can access (e.g., s3://your-code-bucket/).
Step 3: Running the Job on AWS
Here are guides for the two most popular options.
Option A: Running on AWS EMR (Recommended for large-scale jobs)
-
Launch an EMR Cluster: Go to the EMR console and create a cluster. You can use the default settings for now. Make sure the "EC2 instance profile" IAM role has S3 read/write access.
-
Submit the Job as a Step: After the cluster is in the "Waiting" state, select it, go to the "Steps" tab, and add a new step with the following configuration:
- Step type: Spark application
- Application location:
s3://your-code-bucket/image_metadata_etl.py (your script's S3 path)
- Spark-submit options: This is the crucial part. It tells Spark where to find your dependencies and the necessary S3 connector.
--deploy-mode cluster \
--py-files s3://your-code-bucket/dependencies.zip
- Arguments: Leave blank, as the paths are hardcoded in the script for this example. (For better practice, you could pass the S3 paths as arguments).
-
Monitor: The step will run, and you can monitor its progress in the EMR console. Once finished, your Parquet or CSV files will be in the specified output S3 bucket.
Option B: Running on AWS Glue (Recommended for serverless/managed execution)
- Create a Glue Job: Go to the AWS Glue console, navigate to "ETL jobs", and create a new job.
- Configure the Job:
- Choose: "Spark script editor" and "Upload and edit an existing script".
- Upload: Upload your
image_metadata_etl.py script.
- Job details:
- Give it a name (e.g.,
image-metadata-etl).
- Select an IAM Role with S3 access.
- Type: Spark
- Glue version: Glue 4.0 (or 3.0) is recommended.
- Job parameters (in the "Advanced properties" section): This is where you specify the Python dependencies.
- Find the key
--additional-python-modules.
- Set its value to:
Pillow==9.4.0,exifread==3.0.0
- (This is the modern way. The older way was to upload the
dependencies.zip and point to it in the "Python library path" field, but this is simpler).
- Save and Run: Save the job and click "Run". Glue will provision the resources, run your script, and terminate everything automatically.
- Monitor: You can monitor the run in the "Runs" tab. The output files will appear in your S3 output bucket upon completion.
Choosing Between CSV and Parquet
The script shows how to write to both formats. Here's a quick comparison:
- CSV (Comma-Separated Values):
- Pros: Human-readable, easy to open in any spreadsheet program.
- Cons: No schema enforcement, takes up more space, slower to read for analytical queries.
- Parquet:
- Pros: Columnar format, highly compressed, stores schema with the data, significantly faster for Spark and other big data tools to query. This is the recommended format for any downstream analytical work.
- Cons: Not human-readable.
By following these steps, you will have a scalable and efficient ETL pipeline for generating valuable metadata from your image library in S3.