from io import BytesIO
import json
import os
import base64
from PIL import Image

def encode_image_to_base64(image):
    buffered = BytesIO()
    image.save(buffered, format="JPEG")
    encoded_string = base64.b64encode(buffered.getvalue()).decode('utf-8')
    return f"data:image/jpeg;base64,{encoded_string}"

def downscale_image(image_path, size=(128, 128)):
    with Image.open(image_path) as img:
        img = img.resize(size, Image.LANCZOS)
    return img


def read_image_metadata(image_path):
    with Image.open(image_path) as img:
        parameters = img.info.get('parameters')
        if parameters:
            metadata = json.loads(parameters).get('sui_image_params')
            return metadata['gridgenpresets']
    return None

def update_presets_with_images(json_filepath, images_folder):
    with open(json_filepath, 'r') as file:
        presets = json.load(file)

    image_files = [f for f in os.listdir(images_folder) if os.path.isfile(os.path.join(images_folder, f))]
    i = 1
    for image_file in image_files:
        image_path = os.path.join(images_folder, image_file)
        metadata = read_image_metadata(image_path)
        print(f"processing image: {i} / {len(image_files)}")
        i = i+1
        if metadata:
            if metadata in presets:
                downscaled_image = downscale_image(image_path)
                base64_image = encode_image_to_base64(downscaled_image)
                presets[metadata]['preview_image'] = base64_image

    with open(json_filepath, 'w') as file:
        json.dump(presets, file, indent=4)

if __name__ == "__main__":
    json_filepath = 'Fooocus_All_Presets_For_StableSwarmUI.json'
    images_folder = 'preset_images'
    update_presets_with_images(json_filepath, images_folder)