因为本人平时喜好存一些图片,但经常批量下载,存了又不怎么看,因此有很多图片实际上并不需要,因此我想到了这个办法。

使用这个工具,输入路径后,会自动随机抽取路径下的两张图片,然后可以自己选择留下哪一张,或者是直接跳过。

同时,我还使用了HTTP服务,因此可以躺床上用手机操作。

开始运行后访问localhost:1145即可。

代码如下。

import os
import random
from pywebio.input import *
from pywebio.output import *
from pywebio import start_server
import shutil

# 配置常量
IMAGE_EXTENSIONS = (".png", ".jpg", ".jpeg")
DIRECTORIES = [
    r"./",
    r"D:\Pics\new",
    r"D:\Pics\1",
    r"D:\Pics\2",
    r"D:\Pics\3",
]


def show_images(epoch):
    """显示图片并处理用户选择"""
    current_dir = DIRECTORIES[epoch]
    target_dir = DIRECTORIES[epoch + 1]

    # 获取并打乱图片列表
    images = [
        f for f in os.listdir(current_dir) if f.lower().endswith(IMAGE_EXTENSIONS)
    ]
    random.shuffle(images)

    while len(images) >= 2:
        img_name1 = images.pop()
        img_name2 = images.pop()
        path1 = os.path.join(current_dir, img_name1)
        path2 = os.path.join(current_dir, img_name2)

        # 检查文件是否存在(防止被外部删除)
        if not (os.path.exists(path1) and os.path.exists(path2)):
            continue

        # 读取并显示图片
        with open(path1, "rb") as f1, open(path2, "rb") as f2:
            put_row(
                [
                    put_image(f1.read(), width="100%"),
                    put_image(f2.read(), width="100%"),
                ],
                size="50% 50%",
            )

        # 创建按钮
        choice = actions(
            "请选择保留的图片", ["留下左边", "留下右边", "都可以", "都不行"]
        )

        # 刷新页面
        clear()
        # 处理用户选择
        try:
            if choice == "留下左边":
                shutil.move(path1, target_dir)
                os.remove(path2)
            elif choice == "留下右边":
                shutil.move(path2, target_dir)
                os.remove(path1)
            elif choice == "都可以":
                # shutil.move(path1, target_dir)
                # shutil.move(path2, target_dir)
                continue # 若都可以则不动,等待以后对比处理
            elif choice == "都不行":
                os.remove(path1)
                os.remove(path2)
        except Exception as e:
            toast(f"操作失败: {e}", color="error")

    put_text("目录中没有足够的图片")


def main():
    """主入口:选择阶段"""
    stages = {
        "第一轮": 1,
        "第二轮": 2,
        "第三轮": 3,
    }
    choice = actions("请选择清洗阶段", list(stages.keys()))
    show_images(stages[choice])


if __name__ == "__main__":
    start_server(main, port=1450)