
import xml.etree.ElementTree as ET
import json
import boto3
import os

def lambda_handler(event, context):
    # Get the bucket and object from the event 
    records = event['Records'][0]
    bucket = records['s3']['bucket']['name'] 
    xml_file = records['s3']['object']['key'] 
    
    xml_to_aws_rekognition(bucket,xml_file)

    return {
        'statusCode': 200,
        'body': json.dumps({'message': 'Json created successfully'})
        
    }


def xml_to_aws_rekognition(bucket,xml_file):
    # get xml file from s3 bucket
    s3_connection = boto3.resource('s3')
    s3_object = s3_connection.Object(bucket,xml_file)
    xml_content = s3_object.get()['Body'].read()

    # Parse the XML content from string
    root = ET.fromstring(xml_content)

    # Get image size    
    size = root.find('size')    
    img_width = int(size.find('width').text)    
    img_height = int(size.find('height').text)    
    
    # Prepare JSON structure    
    annotations = {        
        "Labels": []    
    }    
    # Loop through each object in the XML    
    for obj in root.findall('object'):        
        label = obj.find('name').text        
        bndbox = obj.find('bndbox')        
        xmin = int(bndbox.find('xmin').text)        
        ymin = int(bndbox.find('ymin').text)        
        xmax = int(bndbox.find('xmax').text)        
        ymax = int(bndbox.find('ymax').text)        

        # Normalize coordinates for AWS Rekognition        
        left = xmin / img_width        
        top = ymin / img_height        
        width = (xmax - xmin) / img_width        
        height = (ymax - ymin) / img_height        
        annotation = {            
            "Name": label,            
            "BoundingBox": {                
                "Left": left,                
                "Top": top,                
                "Width": width,                
                "Height": height            
                }        
            }        
        annotations["Labels"].append(annotation)    
    
    # Convert annotations to JSON
    json_response = json.dumps(annotations, indent=4)

    # Save response to S3
    output_file_name = os.path.splitext(xml_file)[0] + '.json'
    s3_client = boto3.client('s3')
    s3_client.put_object(Bucket=bucket, Key=output_file_name, Body=json_response)
