import json
import base64
# from PIL import Image
import io
from model_handler import ModelHandler

def init_context(context):
    context.logger.info("Init context...  0%")

    context.logger.info("Initializing EMDetection model...")
    context.user_data.model_handler = ModelHandler()

    context.logger.info("Init context...100%")

def handler(context, event):
    context.logger.info("Run EMDetection model")
    data = event.body
    image_data = base64.b64decode(data["image"])
    threshold = float(data.get("threshold", 0.5))

    results = context.user_data.model_handler.infer(image_data, threshold)

    return context.Response(body=json.dumps(results), headers={},
        content_type='application/json', status_code=200)
