import gradio as gr
import os
import sys
from pathlib import Path
import random
import string
import time
from queue import Queue
from threading import Thread
import emoji

text_gen=gr.Interface.load("spaces/phenomenon1981/MagicPrompt-Stable-Diffusion")
def get_prompts(prompt_text):
    if prompt_text:
        return text_gen("photo, " + prompt_text)
    else:
        return text_gen("")
proc1=gr.Interface.load("models/dreamlike-art/dreamlike-photoreal-2.0")

def restart_script_periodically():
    while True:
        random_time = random.randint(540, 600)
        time.sleep(random_time)
        os.execl(sys.executable, sys.executable, *sys.argv)


restart_thread = Thread(target=restart_script_periodically, daemon=True)
restart_thread.start()


queue = Queue()
queue_threshold = 100

def add_random_noise(prompt, noise_level=0.00):
    if noise_level == 0:
        noise_level = 0.00
    percentage_noise = noise_level * 5
    num_noise_chars = int(len(prompt) * (percentage_noise/100))
    noise_indices = random.sample(range(len(prompt)), num_noise_chars)
    prompt_list = list(prompt)
    noise_chars = list(string.ascii_letters + string.punctuation + ' ' + string.digits)
    noise_chars.extend(['😍', 'ðŸ’Đ', '😂', 'ðŸĪ”', '😊', 'ðŸĪ—', '😭', '🙄', '😷', 'ðŸĪŊ', 'ðŸĪŦ', 'ðŸĨī', 'ðŸ˜ī', 'ðŸĪĐ', 'ðŸĨģ', '😔', 'ðŸ˜Đ', 'ðŸĪŠ', '😇', 'ðŸĪĒ', '😈', 'ðŸ‘đ', 'ðŸ‘ŧ', 'ðŸĪ–', 'ðŸ‘―', '💀', '🎃', '🎅', '🎄', '🎁', '🎂', '🎉', '🎈', '🎊', 'ðŸŽŪ', 'âĪïļ', '💔', '💕', '💖', '💗', 'ðŸķ', 'ðŸą', '🐭', 'ðŸđ', 'ðŸĶŠ', 'ðŸŧ', 'ðŸĻ', 'ðŸŊ', 'ðŸĶ', '🐘', 'ðŸ”Ĩ', '🌧ïļ', '🌞', '🌈', 'ðŸ’Ĩ', 'ðŸŒī', '🌊', '🌚', 'ðŸŒŧ', 'ðŸŒļ', 'ðŸŽĻ', '🌅', '🌌', '☁ïļ', '⛈ïļ', '❄ïļ', '☀ïļ', 'ðŸŒĪïļ', '⛅ïļ', 'ðŸŒĨïļ', 'ðŸŒĶïļ', '🌧ïļ', 'ðŸŒĐïļ', 'ðŸŒĻïļ', 'ðŸŒŦïļ', '☔ïļ', '🌎ïļ', 'ðŸ’Ļ', '🌊ïļ', '🌈'])
    for index in noise_indices:
        prompt_list[index] = random.choice(noise_chars)
    return "".join(prompt_list)


def send_it1(inputs, noise_level, proc1=proc1):
    prompt_with_noise = add_random_noise(inputs, noise_level)
    while queue.qsize() >= queue_threshold:
        time.sleep(2)
    queue.put(prompt_with_noise)
    output1 = proc1(prompt_with_noise)
    return output1

def send_it2(inputs, noise_level, proc1=proc1):
    prompt_with_noise = add_random_noise(inputs, noise_level)
    while queue.qsize() >= queue_threshold:
        time.sleep(2)
    queue.put(prompt_with_noise)
    output2 = proc1(prompt_with_noise)
    return output2

#def send_it3(inputs, noise_level, proc1=proc1):
    #prompt_with_noise = add_random_noise(inputs, noise_level)
    #while queue.qsize() >= queue_threshold:
        #time.sleep(2)
    #queue.put(prompt_with_noise)
    #output3 = proc1(prompt_with_noise)
    #return output3

#def send_it4(inputs, noise_level, proc1=proc1):
    #prompt_with_noise = add_random_noise(inputs, noise_level)
    #while queue.qsize() >= queue_threshold:
        #time.sleep(2)
    #queue.put(prompt_with_noise)
    #output4 = proc1(prompt_with_noise)
    #return output4



with gr.Blocks(css='style.css') as demo:
    gr.HTML(
        """
            <div style="text-align: center; max-width: 650px; margin: 0 auto;">
              <div>
                <h1 style="font-weight: 900; font-size: 3rem; margin-bottom:20px;">
                  Dreamlike Photoreal 2.0
                </h1>
              </div>
              <p style="margin-bottom: 10px; font-size: 96%">
              Noise Level: Controls how much randomness is added to the input before it is sent to the model. Higher noise level produces more diverse outputs, while lower noise level produces similar outputs,
                <a href="https://twitter.com/DavidJohnstonxx/">created by Phenomenon1981</a>.
              </p>
              <p style="margin-bottom: 10px; font-size: 98%">
              âĪïļ Press the Like Button if you enjoy my space! âĪïļ</a>
              </p>
            </div>
        """
    )
    with gr.Column(elem_id="col-container"):
        with gr.Row(variant="compact"):
            input_text = gr.Textbox(
                label="Short Prompt",
                show_label=False,
                max_lines=2,
                placeholder="Enter a basic idea and click 'Magic Prompt'. Got no ideas? No problem, Simply just hit the magic button!",
            ).style(
                container=False,
            )
            see_prompts = gr.Button("âœĻ Magic Prompt âœĻ").style(full_width=False)

        
        with gr.Row(variant="compact"):
            prompt = gr.Textbox(
                label="Enter your prompt",
                show_label=False,
                max_lines=2,
                placeholder="Full Prompt",
            ).style(
                container=False,
            )
            run = gr.Button("Generate Images").style(full_width=False)
        
        with gr.Row():
            with gr.Row():
                noise_level = gr.Slider(minimum=0.0, maximum=3, step=0.1, label="Noise Level")
        with gr.Row():
            with gr.Row():
                output1=gr.Image(label="Dreamlike-photoreal-2.0",show_label=False)
                output2=gr.Image(label="Dreamlike-photoreal-2.0",show_label=False)
        
    #with gr.Row():
        #output1=gr.Image()

        see_prompts.click(get_prompts, inputs=[input_text], outputs=[prompt], queue=False)
        run.click(send_it1, inputs=[prompt, noise_level], outputs=[output1])
        run.click(send_it2, inputs=[prompt, noise_level], outputs=[output2])
        


        with gr.Row():
                gr.HTML(
    """
        <div class="footer">
        <p> Demo for <a href="https://huggingface.co/dreamlike-art/dreamlike-photoreal-2.0">Dreamlike Photoreal 2.0</a> Stable Diffusion model
</p>
</div>
        <div class="acknowledgments" style="font-size: 115%">
            <p> Unleash your creative side and generate mesmerizing images with just a few clicks! Enter a spark of inspiration in the "Basic Idea" text box and click the "Magic Prompt" button to elevate it to a polished masterpiece. Make any final tweaks in the "Full Prompt" box and hit the "Generate Images" button to watch your vision come to life. Experiment with the "Noise Level" for a diverse range of outputs, from similar to wildly unique. Let the fun begin!
            </p>
        </div>
    """
)

    demo.launch(enable_queue=True, inline=True)
    block.queue(concurrency_count=100)