# Analyze Image

This Lambda function processes images using a trained AWS Rekognition Custom Labels model. It retrieves unprocessed images from Supabase, analyzes them with the active model, and stores the results back in Supabase.

## Functionality

The function performs the following operations:

1. Retrieves active model from Supabase (checks both `model_status` and `status` fields)
2. Fetches unprocessed images from the `product_images` table
3. Analyzes each image using the model via Rekognition's `detect_custom_labels` API
4. Draws bounding boxes around detected objects
5. Saves the processed images to Supabase storage using upsert to handle duplicates
6. Updates records in the database with results and processed status
7. Checks for existing records in the `product_ml` table and updates them if they exist

## Environment Variables

- `MIN_CONFIDENCE`: Minimum confidence threshold for custom label detection (default: 50.0)

The function also retrieves configuration from SSM Parameter Store:
- `/supabase/url`: URL for the Supabase instance
- `/supabase/anon`: Anonymous API key for Supabase
- `/datafy-rekognition-stack/project-arn`: Project ARN for Rekognition

## Model Version Selection

The function uses a multi-tiered approach to find an appropriate model:

1. First checks for models with `model_status='RUNNING'` (models started with the start_model function)
2. Falls back to models with `status='RUNNING'` (for backward compatibility)
3. If no running model is found, checks for models with `model_status='TRAINING_COMPLETED'`
4. Finally checks for models with `status='TRAINING_COMPLETED'`

This approach ensures compatibility with both new and legacy model status tracking.

## Image Processing

The function processes images in the following manner:

1. Retrieves the image from its URL
2. Sends the image to Rekognition for custom label detection
3. Draws bounding boxes around detected objects (with a line thickness of 2 pixels)
4. Saves the processed image to Supabase storage using the upsert feature

### Note on Text Labels

The code includes functionality for drawing text labels on images, but this is currently commented out due to display issues. The code is preserved for future reference if this feature is needed.

## Storage Handling

The function uses an improved approach for storing processed images:

1. Uses the `uploads/ml` bucket in Supabase storage
2. Employs the `upsert: "true"` parameter to handle duplicate files gracefully
3. Automatically overwrites existing files with the same name
4. Generates consistent URLs based on the original filename

This approach eliminates the need for separate delete operations and handles duplicates efficiently.

## Database Schema

### Required Tables

The function interacts with several Supabase tables:

1. **model_versions**: Stores information about trained models
   - Contains `status` and `model_status` fields for tracking model state

2. **product_images**: Stores information about images to be processed
   - `id`: Record identifier
   - `product_id`: Associated product identifier
   - `image_path`: URL to the image to be processed
   - `processed`: Boolean flag indicating processing status
   - `error`: Error message if processing failed
   - `project_version_arn`: ARN of the model version used for processing

3. **product_ml**: Stores results from model analysis
   - `product_id`: Associated product identifier
   - `ml_image_path`: URL to the processed image with bounding boxes
   - `ml_result`: JSON result from Rekognition
   - `product_images_id`: Reference to the original image record
   - `project_version_arn`: ARN of the model version used

### Storage Buckets

The function uses Supabase storage:
- Bucket: `uploads/ml` - Stores the processed images with bounding boxes

## Error Handling

The function includes robust error handling:
- Model selection failures
- Image retrieval errors
- Rekognition API errors
- Image processing errors
- Database update errors
- Storage duplicate handling with upsert

Each image is processed independently, with errors logged but not preventing other images from being processed.

## Usage

This function is typically invoked as part of the Rekognition state machine workflow:
1. After the "Is Model Available" choice state confirms the model is running
2. Before the "Stop Model" state that shuts down the model when processing is complete

It can also be triggered:
- On a schedule to process new images
- Manually when new images are uploaded

## Troubleshooting

Common issues:
- No active model: Ensure a model has been successfully trained and started
- Image processing errors: Check image format and access permissions
- Supabase errors: Verify database schema and storage buckets exist
- Missing model_status field: Run the schema update script if implementing the new dual-status approach
- Storage errors: Verify the `uploads/ml` bucket exists and has appropriate permissions 