import tkinter as tk
from tkinter import filedialog, Label, simpledialog
from PIL import Image, ImageTk
import json
import random
import string
import os
import shutil
import sys
 
# 创建主窗口
root = tk.Tk()
root.title("Image Viewer with Dialogue")
root.geometry("1000x600")  # 设置窗口默认大小
 
dialogue_entries = []  # 用来存储动态创建的对话输入框
 
# 加载并显示图片的函数
def load_and_display_image():
    global image_label
    global image_path
    file_path = filedialog.askopenfilename(filetypes=[("Image files", "*.png;*.jpg;*.jpeg")])
    image_path = file_path
    if file_path:
        image = Image.open(file_path)
        # 根据原图片宽高比确定图像显示区域的宽度
        width = int((400 / image.height) * image.width)
        image = image.resize((width, 400), Image.ANTIALIAS)
        photo = ImageTk.PhotoImage(image)
        
        if 'image_label' in globals():
            image_label.config(image=photo)
        else:
            image_label = tk.Label(image_frame, image=photo)
            image_label.pack(padx=7, pady=7)
        image_label.image = photo  # keep a reference to the image
        # 创建添加对话的按钮
        add_dialogue_button = tk.Button(root, text="Add Dialogue", command=add_dialogue_boxes)
        add_dialogue_button.pack(side="top", padx=(5, 0), pady=(7, 0))
 
        # 创建保存按钮
        save_button = tk.Button(root, text="Save", command=save_to_json)
        save_button.pack(side="top", pady=(7, 0))
 
        # 创建文本提示框和输入框
        global input_box_1,input_box_2
        input_box_1 = create_labeled_input(root, "Input with the picture:")
        input_box_2 = create_labeled_input(root, "Assistant:")
 
 
 
# 创建左侧的图片显示框架
image_frame = tk.Frame(root)
image_frame.pack(side="left", anchor="nw", padx=7, pady=7)
 
# 创建打开图片的按钮
open_button = tk.Button(root, text="Open Image", command=load_and_display_image)
open_button.pack(side="top", pady=(7, 0))
 
# 创建文本提示框和输入框的函数
def create_labeled_input(parent, label_text):
    label = tk.Label(parent, text=label_text)
    label.pack(side="top")
    entry = tk.Entry(parent, width=50)
    entry.pack(side="top")
    return entry
 
 
 
# 动态添加对话输入框的函数
def add_dialogue_boxes():
    user_entry = create_labeled_input(root, "User:")
    assistant_entry = create_labeled_input(root, "Assistant:")
    dialogue_entries.append((user_entry, assistant_entry))
 
 
# 将输入的文本保存为 JSON 文件的函数
def save_to_json():
    save_dir = "saves"
 
    # 生成一个10位的随机字符串作为文件名
    random_filename = ''.join(random.choices(string.ascii_lowercase + string.digits, k=10))
    
    # 确保save_dir存在
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)
 
    # 定义JSON文件的完整路径
    json_file_path = os.path.join(save_dir, random_filename + '.json')
    # 定义图片文件的完整路径
    image_file_path = os.path.join(save_dir, random_filename + '.jpg')
 
 
    cat1 = "Picture 1: <img>"
    cat2 = random_filename
    cat3 = ".jpg</img>\n"
    cat4 = input_box_1.get()
    cat = cat1+cat2+cat3+cat4
    dialogue_data = {
        
        "conversations": []
    }
 
    dialogue_data["conversations"].append({
        "from":"user",
        "value": cat
    })
    
    dialogue_data["conversations"].append({
        "from": "assistant",
        "value": input_box_2.get()
    })
    for user_entry, assistant_entry in dialogue_entries:
        dialogue_data["conversations"].append({
            "from": "user",
            "value": user_entry.get()
        })
        dialogue_data["conversations"].append({
            "from": "assistant",
            "assistant": assistant_entry.get()
        })
    
    # 把对话数据保存到JSON文件
    with open(json_file_path, 'w', encoding='utf-8') as json_file:
        json.dump(dialogue_data, json_file, ensure_ascii=False, indent=4)
 
    # 把图片文件保存到指定的文件夹
    if image_path and os.path.isfile(image_path):
        shutil.copy2(image_path, image_file_path)
    
    
    subprocess.Popen(["python", "test.py"])
    sys.exit()
 
 
 
 
root.mainloop()