import sys
import os
#sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
#path_to_remove = '/Users/zhangangang/Desktop/Typora文件/CV/DEADiff An Efficient Stylization Diffusion Model with Disentangled Representations/DEADiff-main'

# 从 sys.path 中删除路径
#if path_to_remove in sys.path:
#    sys.path.remove(path_to_remove)

#print(sys.path)
#import cv2
import numpy as np

def generate_gaussian_noise_image(width, height, mean=0, std_dev=50):
    """
    生成一张纯高斯噪声图像

    :param width: 图像宽度
    :param height: 图像高度
    :param mean: 高斯噪声的均值
    :param std_dev: 高斯噪声的标准差
    :return: 纯高斯噪声图像
    """
    # 生成与指定大小相同的高斯噪声
    noise = np.random.normal(mean, std_dev, (height, width, 3)).astype(np.uint8)
    
    return noise

def main():
    # 设置图像的宽度和高度
    width = 512
    height = 512
    
    # 生成纯高斯噪声图像
    noise_image = generate_gaussian_noise_image(width, height, mean=0, std_dev=50)
    
    # 显示纯高斯噪声图像
    #cv2.imshow('Gaussian Noise Image', noise_image)
    
    # 等待按键，然后关闭窗口
    #cv2.waitKey(0)
    #cv2.destroyAllWindows()

from PIL import Image
from tqdm import tqdm



def copy_resize_gt(gt_folder, test_file='DATA/dresscode/upper_body/test_pairs_paired.txt'):
    # 读取 test.txt 文件，获取需要处理的文件名
    with open(test_file, 'r') as f:
        lines = f.readlines()
    target_files = {line.split()[0].strip() for line in lines}  # 提取每个文件名的前半部分

    new_folder = f"{gt_folder}_1024_768"
    os.makedirs(new_folder, exist_ok=True)

    total_files = 0
    processed_files = 0

    # 遍历 gt_folder 文件夹中的所有文件
    for file in tqdm(os.listdir(gt_folder), desc="Processing files"):
        if file in target_files:  # 只处理 test.txt 中指定的文件
            src_file_path = os.path.join(gt_folder, file)
            dst_file_path = os.path.join(new_folder, file)

            if os.path.exists(dst_file_path):
                continue

            # 打开并缩放图像
            try:

                img = Image.open(src_file_path)
                #img = img.resize((768, 1024))
                import torchvision.transforms as transforms
                resize = transforms.Resize((1024, 768),interpolation=2)
                img = resize(img)
                img.save(dst_file_path)
                processed_files += 1
            except Exception as e:
                print(f"Error processing file {file}: {e}")

        total_files += 1

    print(f"Total files: {total_files}, Processed files: {processed_files}")
    return new_folder

from torchvision import transforms
def process_images(input_dir, output_dir, target_size, interpolation="bilinear"):
    """
    用transforms.Resize调整图片尺寸
    :param input_dir: 输入文件夹路径
    :param output_dir: 输出文件夹路径
    :param target_size: 目标尺寸（整数或元组 (H, W)）
    :param interpolation: 插值方法 (nearest/bilinear/bicubic)
    """
    # 创建输出目录
    os.makedirs(output_dir, exist_ok=True)
    
    # 转换插值方法
    interp_dict = {
        "nearest": transforms.InterpolationMode.NEAREST,
        "bilinear": transforms.InterpolationMode.BILINEAR,
        "bicubic": transforms.InterpolationMode.BICUBIC
    }
    
    # 初始化转换器
    resize_transform = transforms.Resize(
        size=target_size,
        interpolation=interp_dict[interpolation]
    )
    
    processed = 0
    for filename in os.listdir(input_dir):
        # 仅处理图片文件
        if not filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp')):
            continue
            
        input_path = os.path.join(input_dir, filename)
        output_path = os.path.join(output_dir, filename)
        
        # 打开图片并转换通道格式
        with Image.open(input_path) as img:
            # 处理RGBA格式（转换为RGB）
            if img.mode == 'RGBA':
                img = img.convert('RGB')
            
            # 执行尺寸调整
            resized = img.resize((768,1024))
            resized = resize_transform(resized)
            
            # 保存图片（保持原始格式）
            #if filename.lower().endswith(('.jpg', '.jpeg')):
            #    resized.save(output_path)
            #else:
            resized.save(output_path)
            
            processed += 1
            print(f"Processed: {filename} => {resized.size}")
            



delete_config = {
    "test": {
        "duplicates": ["02015_00.jpg", "09660_00.jpg", "14196_00.jpg", "11934_00.jpg", "07980_00.jpg", "14471_00.jpg"],
        "leaked": ["07309_00.jpg", "03527_00.jpg", "12178_00.jpg", "11675_00.jpg", "01261_00.jpg", "13105_00.jpg", "11921_00.jpg", "11504_00.jpg", "03696_00.jpg", "02771_00.jpg", "10665_00.jpg", "13102_00.jpg", "02770_00.jpg", "08989_00.jpg", "02245_00.jpg", "07726_00.jpg", "11676_00.jpg", "04452_00.jpg", "11606_00.jpg", "12181_00.jpg", "08735_00.jpg", "01260_00.jpg", "01008_00.jpg", "09493_00.jpg", "14112_00.jpg", "07977_00.jpg", "03444_00.jpg", "12598_00.jpg", "09744_00.jpg", "07560_00.jpg", "11085_00.jpg", "14041_00.jpg", "07475_00.jpg", "10330_00.jpg", "06132_00.jpg", "09996_00.jpg"]
    }
}

def delete_specific_files(folder_path):
    """
    删除指定文件夹中预定义的文件和clean的vitonhd计算tryoff指标
    :param folder_path: 目标文件夹路径
    """
    # 合并需要删除的文件列表
    files_to_delete = set()
    for key in ["duplicates", "leaked"]:
        for filename in delete_config["test"][key]:
            png_name = filename.replace(".jpg", ".png")
            files_to_delete.add(png_name)
            #files_to_delete.add(filename)
    #files_to_delete = set(delete_config["test"]["duplicates"] + delete_config["test"]["leaked"])
    
    # 遍历文件夹
    deleted_count = 0
    for filename in os.listdir(folder_path):
        if filename in files_to_delete:
            file_path = os.path.join(folder_path, filename)
            try:
                os.remove(file_path)
                print(f"已删除: {filename}")
                deleted_count += 1
            except Exception as e:
                print(f"删除失败: {filename} - {str(e)}")
    
    print(f"\n操作完成！共删除 {deleted_count} 个文件")

if __name__ == "__main__":
    """
    try:
        import xformers
        import xformers.ops
        XFORMERS_IS_AVAILBLE = True #and XFORMERS_IS_AVAILBLE
        print(f'XFORMERS_IS_AVAILBLE:{XFORMERS_IS_AVAILBLE}')
    except:
        XFORMERS_IS_AVAILBLE = False
        print(f'XFORMERS_IS_AVAILBLE:{XFORMERS_IS_AVAILBLE}')
    import torch
    print(torch.cuda.is_available())
    print("CUDA Version:", torch.version.cuda)
    """
    #1. VITON-HD或者dresscode数据集的test数据集裁剪
    #copy_resize_gt('DATA/dresscode/upper_body/images')
    # copy_resize_gt('DATA/dresscode/dresses/images', test_file='DATA/dresscode/dresses/test_pairs_paired.txt')

    #2. 对模型生成的结果图片裁剪尺寸
    #process_images('DATA/dresscode/dresses/images_512_512', 'DATA/dresscode/dresses/images_1024_768_2', (1024,768), interpolation="bilinear")
    # process_images('DATA/IDM/result_dresses', 'DATA/IDM/result_dresses_image_all_512_512', (512,512), interpolation="bilinear")

    #3. 删除tryoff指标中不需要的图片
    delete_specific_files('outputs/tryoff_maskfree_500_200epoch_TEST')
    # delete_specific_files('outputs/Tryon-samples/4_ablation2IpAdapter_TryOFF_Epoch59')


#----------------
# 20250614_viton_tryon_fromScratch_fromDresscodeUpBody99 0.018
# 20250614_viton_tryon_fromvitonhd299  0.0146

# 20250614_viton_tryoff_fromScratch_fromDresscodeUpBody99  0.03
# 20250614_viton_tryoff_fromvitonhd299  0.0278

# 20250614_dresses_4_from_tryon_upper99 0.0204
