import os
import re
import shutil
from concurrent.futures import ThreadPoolExecutor, as_completed

def copy_one(tiff_path, target_path):
    shutil.copy(tiff_path, target_path)
    return os.path.basename(tiff_path)

def copy_file_by_txt(txt_path, tiff_path, dst_path, workers=8):
    os.makedirs(dst_path, exist_ok=True)

    # 遍历所有txt
    tiff_files = {re.sub(r'_image.tiff', '', f): f for f in os.listdir(tiff_path) if f.lower().endswith('.tiff')}

    tasks = []
    with ThreadPoolExecutor(max_workers=workers) as executor:
        # 遍历txt_path中所有txt
        for file in os.listdir(txt_path):
            if file.lower().endswith('.txt'):
                # basename = os.path.splitext(file)[0]
                basename = re.sub(r'_image.txt', '', file)
                if basename in tiff_files:
                    tiff_name = tiff_files[basename]
                    tiff_folder = os.path.join(tiff_path, tiff_name)
                    target_folder = os.path.join(dst_path, tiff_name)

                    # 并发提交复制任务
                    tasks.append(executor.submit(copy_one, tiff_folder, target_folder))

        for future in as_completed(tasks):
            try:
                print(f"Copied: {future.result()}")
            except Exception as e:
                print(f"Error copying file: {e}")


if __name__ == "__main__":
    txt_path = r"R:\TYSAR-德清院\B-模型处理-预标注\20250826-不分类-处理20250906\人工检查\剔除空标注\20250918"
    tiff_path = r"R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250826-不分类\A-预处理\AB-图像预处理\tifffolder"
    dst_path = r"R:\TYSAR-德清院\B-模型处理-预标注\20250826-不分类-处理20250906\人工检查\剔除空标注\20250918"

    copy_file_by_txt(txt_path, tiff_path, dst_path)