import torch
from diffusers import StableDiffusionPipeline
import tkinter
from PIL import ImageTk
import threading
import time

busyflag = 0   # 処理中フラグ
negative_prompt = "low quality, blurry"

# タイマー処理
def timerctrl():
  # ウインドウが存在しないなら終了
  if not root.winfo_exists():  
    return
    
  global busyflag
  if busyflag == 1:
    busyflag = 0
    starttime = time.time()
    prompt = ent_q.get(0., tkinter.END)

    # 画像を生成
    response = pipeline(prompt=prompt, 
      negative_prompt=negative_prompt)
    image = response.images[0]
    image.save("image.png")
    
    # Tkinter用に変換
    tk_img = ImageTk.PhotoImage(image)
    image_label.config(image=tk_img)
    image_label.image = tk_img

    # 処理時間
    runningtime = time.time() - starttime
    temp = "処理時間:" + str(int(runningtime)) + " 秒"
    ent_a.delete(0., tkinter.END)
    ent_a.insert(tkinter.END,temp)
    btn.place(x=8, y=450, width=280, height=60)

  timer = threading.Timer(1, timerctrl)
  timer.daemon = True
  timer.start()

# ボタンのクリック時のイベントハンドラ
def button_click(event):
  global busyflag
  btn.place_forget() 
  ent_a.delete(0., tkinter.END)
  ent_a.insert(tkinter.END, 'Please wait...')
  busyflag = 1   # 思考中フラグをオンにする

# モデルのフォルダーのパス
model = "./stable-diffusion-v1-5"

# パイプラインを作成
pipeline = StableDiffusionPipeline.from_pretrained(model)

# GPUを使う場合は"cuda"。使わない場合は"cpu"
pipeline = pipeline.to("cuda")

# ウインドウ作成
root = tkinter.Tk()                             
root.geometry("840x580")
root.title("画像生成アプリ")
fontsize = fonts = ("", 16)

# ラベルを作成
lab_q = tkinter.Label(root, text='プロンプト', font=fontsize)  
lab_q.place(x=10, y=10, width=160, height=20)
lab_a = tkinter.Label(root, text='出力結果', font=fontsize)
lab_a.place(x=310, y=10, width=160, height=20)

# 画像表示用ラベルを作成
image_label = tkinter.Label(root)
image_label.place(x=310, y=40, width=512, height=512)

# テキストボックスを作成
ent_q = tkinter.Text(root, font=fontsize )  
ent_q.place(x=8, y=40, width=280, height=300)
ent_a = tkinter.Text(root, font=fontsize) 
ent_a.place(x=8, y=370, width=280, height=30)
ent_q.insert(tkinter.END, "Nature and waterfall illustration.")

# ボタンを作成
btn = tkinter.Button(root, text='画像を生成', font=fontsize)
btn.place(x=8, y=450, width=280, height=60)
btn.bind("<Button-1>", button_click)

# スレッドを作成
thread = threading.Thread(target=timerctrl)
thread.daemon = True
thread.start()

root.mainloop()
