import gradio as gr
from random import randint
from all_models import models
from externalmod import gr_Interface_load
import asyncio
import os
from threading import RLock
lock = RLock()
HF_TOKEN = os.environ.get("HF_TOKEN") if os.environ.get("HF_TOKEN") else None


def load_fn(models):
    global models_load
    models_load = {}
    for model in models:
        if model not in models_load.keys():
            try:
                m = gr_Interface_load(f'models/{model}', hf_token=HF_TOKEN)
            except Exception as error:
                print(error)
                m = gr.Interface(lambda: None, ['text'], ['image'])
            models_load.update({model: m})


load_fn(models)


num_models = 6
max_images = 6
inference_timeout = 300
default_models = models[:num_models]


def extend_choices(choices):
    return choices[:num_models] + (num_models - len(choices[:num_models])) * ['NA']


def update_imgbox(choices):
    choices_plus = extend_choices(choices[:num_models])
    return [gr.Image(None, label = m, visible = (m != 'NA')) for m in choices_plus]


def random_choices():
    import random
    random.seed()
    return random.choices(models, k = num_models)


# https://huggingface.co/docs/api-inference/detailed_parameters
# https://huggingface.co/docs/huggingface_hub/package_reference/inference_client
async def infer(model_str, prompt, nprompt="", height=None, width=None, steps=None, cfg=None, timeout=inference_timeout):
    from pathlib import Path
    kwargs = {}
    if height is not None and height >= 256: kwargs["height"] = height
    if width is not None and width >= 256: kwargs["width"] = width
    if steps is not None and steps >= 1: kwargs["num_inference_steps"] = steps
    if cfg is not None and cfg > 0: cfg = kwargs["guidance_scale"] = cfg
    noise = ""
    rand = randint(1, 500)
    for i in range(rand):
        noise += " "
    task = asyncio.create_task(asyncio.to_thread(models_load[model_str].fn,
                               prompt=f'{prompt} {noise}', negative_prompt=nprompt, **kwargs, token=HF_TOKEN))
    await asyncio.sleep(0)
    try:
        result = await asyncio.wait_for(task, timeout=timeout)
    except (Exception, asyncio.TimeoutError) as e:
        print(e)
        print(f"Task timed out: {model_str}")
        if not task.done(): task.cancel()
        result = None
    if task.done() and result is not None:
        with lock:
            png_path = "image.png"
            result.save(png_path)
            image = str(Path(png_path).resolve())
        return image
    return None


def gen_fn(model_str, prompt, nprompt="", height=None, width=None, steps=None, cfg=None):
    if model_str == 'NA':
        return None
    try:
        loop = asyncio.new_event_loop()
        result = loop.run_until_complete(infer(model_str, prompt, nprompt,
                                         height, width, steps, cfg, inference_timeout))
    except (Exception, asyncio.CancelledError) as e:
        print(e)
        print(f"Task aborted: {model_str}")
        result = None
    finally:
        loop.close()
    return result


def add_gallery(image, model_str, gallery):
    if gallery is None: gallery = []
    with lock:
        if image is not None: gallery.insert(0, (image, model_str))
    return gallery


CSS="""
#container { max-width: 1200px; margin: 0 auto; !important; }
.output { width=112px; height=112px; !important; }
.gallery { width=100%; min_height=768px; !important; }
.guide { text-align: center; !important; }
"""

with gr.Blocks(theme='Nymbo/Nymbo_Theme', fill_width=True, css=CSS) as demo:
    with gr.Tab('The Dream'):
        with gr.Column(scale=2):
            with gr.Group():
                txt_input = gr.Textbox(label='Your prompt:', lines=4)
                neg_input = gr.Textbox(label='Negative prompt:', lines=1)
                with gr.Accordion("Advanced", open=False, visible=True):
                    width = gr.Number(label="Width", info="If 0, the default value is used.", maximum=1216, step=32, value=0)
                    height = gr.Number(label="Height", info="If 0, the default value is used.", maximum=1216, step=32, value=0)
                    steps = gr.Number(label="Number of inference steps", info="If 0, the default value is used.", maximum=100, step=1, value=0)
                    cfg = gr.Number(label="Guidance scale", info="If 0, the default value is used.", maximum=30.0, step=0.1, value=0)
            with gr.Row():
                gen_button = gr.Button(f'Generate up to {int(num_models)} images in up to 3 minutes total', scale=3)
                random_button = gr.Button(f'Random {int(num_models)} 🎲', variant='secondary', scale=1)
                stop_button = gr.Button('Stop', variant='secondary', interactive=False, scale=1)
                gen_button.click(lambda: gr.update(interactive=True), None, stop_button)
            gr.Markdown("Scroll down to see more images and select models.", elem_classes="guide")

        with gr.Column(scale=1):
            with gr.Group():
                with gr.Row():
                    output = [gr.Image(label=m, show_download_button=True, elem_classes="output",
                              interactive=False, min_width=80, show_share_button=False, format=".png",
                              visible=True) for m in default_models]
                    current_models = [gr.Textbox(m, visible=False) for m in default_models]

        with gr.Column(scale=2):
            gallery = gr.Gallery(label="Output", show_download_button=True, elem_classes="gallery",
                                interactive=False, show_share_button=True, container=True, format="png",
                                preview=True, object_fit="cover", columns=2, rows=2) 

        for m, o in zip(current_models, output):
            gen_event = gr.on(triggers=[gen_button.click, txt_input.submit], fn=gen_fn,
                              inputs=[m, txt_input, neg_input, height, width, steps, cfg], outputs=[o])
            o.change(add_gallery, [o, m, gallery], [gallery])
            stop_button.click(lambda: gr.update(interactive=False), None, stop_button, cancels=[gen_event])

        with gr.Column(scale=4):
            with gr.Accordion('Model selection'):
                model_choice = gr.CheckboxGroup(models, label = f'Choose up to {int(num_models)} different models from the {len(models)} available!', value=default_models, interactive=True)
                model_choice.change(update_imgbox, model_choice, output)
                model_choice.change(extend_choices, model_choice, current_models)
                random_button.click(random_choices, None, model_choice)

    with gr.Tab('Single model'):
        with gr.Column(scale=2):
            model_choice2 = gr.Dropdown(models, label='Choose model', value=models[0])
            with gr.Group():
                txt_input2 = gr.Textbox(label='Your prompt:', lines=4)
                neg_input2 = gr.Textbox(label='Negative prompt:', lines=1)
                with gr.Accordion("Advanced", open=False, visible=True):
                    width2 = gr.Number(label="Width", info="If 0, the default value is used.", maximum=1216, step=32, value=0)
                    height2 = gr.Number(label="Height", info="If 0, the default value is used.", maximum=1216, step=32, value=0)
                    steps2 = gr.Number(label="Number of inference steps", info="If 0, the default value is used.", maximum=100, step=1, value=0)
                    cfg2 = gr.Number(label="Guidance scale", info="If 0, the default value is used.", maximum=30.0, step=0.1, value=0)
            num_images = gr.Slider(1, max_images, value=max_images, step=1, label='Number of images')
            with gr.Row():
                gen_button2 = gr.Button('Generate', scale=2)
                stop_button2 = gr.Button('Stop', variant='secondary', interactive=False, scale=1)
                gen_button2.click(lambda: gr.update(interactive=True), None, stop_button2)

        with gr.Column(scale=1):
            with gr.Group():
                with gr.Row():
                    output2 = [gr.Image(label='', show_download_button=True, elem_classes="output",
                               interactive=False, min_width=80, visible=True, format=".png",
                               show_share_button=False, show_label=False) for _ in range(max_images)]

        with gr.Column(scale=2):
            gallery2 = gr.Gallery(label="Output", show_download_button=True, elem_classes="gallery",
                                interactive=False, show_share_button=True, container=True, format="png",
                                preview=True, object_fit="cover", columns=2, rows=2) 

        for i, o in enumerate(output2):
            img_i = gr.Number(i, visible = False)
            num_images.change(lambda i, n: gr.update(visible = (i < n)), [img_i, num_images], o)
            gen_event2 = gr.on(triggers=[gen_button2.click, txt_input2.submit],
                               fn=lambda i, n, m, t1, t2, n1, n2, n3, n4: gen_fn(m, t1, t2, n1, n2, n3, n4) if (i < n) else None,
                               inputs=[img_i, num_images, model_choice2, txt_input2, neg_input2,
                                       height2, width2, steps2, cfg2], outputs=[o])
            o.change(add_gallery, [o, model_choice2, gallery2], [gallery2])
            stop_button2.click(lambda: gr.update(interactive=False), None, stop_button2, cancels=[gen_event2])

    gr.Markdown("Based on the [TestGen](https://huggingface.co/spaces/derwahnsinn/TestGen) Space by derwahnsinn, the [SpacIO](https://huggingface.co/spaces/RdnUser77/SpacIO_v1) Space by RdnUser77 and Omnibus's Maximum Multiplier!")

demo.queue()
demo.launch()