对MJ数据的统一处理流程

发布时间 2023-11-14 16:47:36作者: 不上火星不改名

1.删前缀(用户名),删后缀(乱码),加统一标签,打开excel微调。(输入项为1.单个文件夹地址 2.)

import os
import openpyxl
import re

UNWANTED_UNITS = ["undefined", "皮皮", "zly324"]


# 第一步:删名称
def rename_files(path):
    files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
    renamed_files = []

    counter = 1
    for file in files:
        filename, ext = os.path.splitext(file)

        # 乱码类
        if re.search(r'[a-f0-9]{32}', filename) or not '_' in filename:
            renamed = f"({counter})"
            counter += 1
        # AI出图类
        else:
            parts = re.split(r'[_]+', filename)
            parts.pop(0)  # 删除第一个单元

            # 删除特定的单元
            parts = [part for part in parts if part not in UNWANTED_UNITS]

            # 删除所有带数字的单元
            parts = [part for part in parts if not any(char.isdigit() for char in part)]

            # 结尾规则
            # 删除UUID风格数字
            while parts and re.search(r'^[a-f0-9\-]{32,}$', parts[-1]):
                parts.pop(-1)
            # 删除长度小于等于4的部分
            while parts and len(parts[-1]) <= 4:
                parts.pop(-1)

            renamed = '_'.join(parts)

        renamed_files.append(renamed + ext)

    return renamed_files


# 第二步:增名称
def add_prefix(files, prefix):
    prefixed_files = [f"{prefix}_{file}" if not file.startswith(prefix) else file for file in files]

    # 删除特定的单元
    prefixed_files = ['_'.join([part for part in re.split(r'[_]+', name) if part not in UNWANTED_UNITS]) for name in
                      prefixed_files]

    return prefixed_files


# 第三步:创建Excel并自动打开
def create_and_open_excel(files, renamed_files, path):
    wb = openpyxl.Workbook()
    ws = wb.active

    for original, renamed in zip(files, renamed_files):
        ws.append([original, renamed])

    excel_path = os.path.join(path, os.path.basename(path) + ".xlsx")
    wb.save(excel_path)

    # 打开Excel文件
    os.system(f'start "" "{excel_path}"')

    return excel_path


# 第五步:读取Excel并重命名文件
def rename_files_from_excel(path, excel_path):
    wb = openpyxl.load_workbook(excel_path)
    ws = wb.active

    for row in ws.iter_rows(values_only=True):
        original_name, new_name = row
        target_path = os.path.join(path, new_name)

        # 检查原文件是否存在
        if os.path.exists(os.path.join(path, original_name)):
            # 如果目标文件名已存在,则添加一个编号
            counter = 1
            base_name, ext = os.path.splitext(new_name)
            while os.path.exists(target_path):
                new_name = f"{base_name} ({counter}){ext}"
                target_path = os.path.join(path, new_name)
                counter += 1

            os.rename(os.path.join(path, original_name), target_path)

    print("重命名完成。")


# 主函数
def main():
    path = input("请输入文件夹地址: ")
    files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
    renamed_files = rename_files(path)

    prefix = input("请输入需要批量命名的词: ")
    prefixed_files = add_prefix(renamed_files, prefix)

    excel_path = create_and_open_excel(files, prefixed_files, path)
    print(f"Excel文件已保存为:{excel_path}")
    print("请在Excel里微调B列数据,然后保存和关闭Excel文件。完成后按Enter键继续...")

    input()

    # 重命名文件
    rename_files_from_excel(path, excel_path)


if __name__ == "__main__":
    main()

2.统一删除所有下划线

import os
import shutil

def copy_directory(src, dst):
    """Copy the contents from src directory to dst directory."""
    try:
        shutil.copytree(src, dst)
    except FileExistsError:
        print(f"备份目录 '{dst}' 已存在。")

def rename_image_files(directory):
    """Rename image files by replacing underscores with spaces and adding an incremental number if needed."""
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):
                new_file_name = file.replace('_', ' ')
                if new_file_name != file:
                    original_file_path = os.path.join(root, file)
                    new_file_path = os.path.join(root, new_file_name)
                    increment = 1
                    # 循环直到找到不冲突的文件名
                    while os.path.exists(new_file_path):
                        # 分离文件名和扩展名
                        file_name, file_extension = os.path.splitext(new_file_name)
                        # 添加增量数字
                        new_file_name = f"{file_name} ({increment}){file_extension}"
                        new_file_path = os.path.join(root, new_file_name)
                        increment += 1
                    os.rename(original_file_path, new_file_path)
                    print(f"已将文件 {original_file_path} 重命名为 {new_file_path}")

def main():
    # Ask the user for the directory to process
    input_directory = input("请输入要处理的目录路径: ")

    # Check if the directory exists
    if not os.path.exists(input_directory):
        print(f"指定的目录 {input_directory} 不存在。")
        return

    # Create a backup of the directory
    backup_directory = os.path.join(input_directory, "_backup")
    print(f"正在创建备份目录: {backup_directory}")
    copy_directory(input_directory, backup_directory)

    # Rename image files in the backup directory
    print("正在重命名备份目录中的图片文件...")
    rename_image_files(backup_directory)
    print("重命名操作完成。")

if __name__ == "__main__":
    main()

3.插件统一增添分隔符(自己看需求)

4.加上WJ前缀,如原来是unmbrella_xxx就变为WJunmbrella_umbrella_xxx