import os

from minio import Minio
from minio.error import S3Error

MINIO_URL = "www.minio.aida.com.hk:12024"
MINIO_ACCESS = 'vXKFLSJkYeEq2DrSZvkB'
MINIO_SECRET = 'uKTZT3x7C43WvPN9QTc99DiRkwddWZrG9Uh3JVlR'
MINIO_SECURE = True
# 配置MinIO客户端
minio_client = Minio(MINIO_URL, access_key=MINIO_ACCESS, secret_key=MINIO_SECRET, secure=MINIO_SECURE)


# 下载函数
def download_folder(bucket_name, folder_name, local_dir):
    try:
        # 确保本地目录存在
        if not os.path.exists(local_dir):
            os.makedirs(local_dir)

        # 遍历MinIO中的文件
        objects = minio_client.list_objects(bucket_name, prefix=folder_name, recursive=True)
        for obj in objects:
            # 构造本地文件路径
            local_file_path = os.path.join(local_dir, obj.object_name[len(folder_name):])
            local_file_dir = os.path.dirname(local_file_path)

            # 确保本地目录存在
            if not os.path.exists(local_file_dir):
                os.makedirs(local_file_dir)

            # 下载文件
            minio_client.fget_object(bucket_name, obj.object_name, local_file_path)
            print(f"Downloaded {obj.object_name} to {local_file_path}")

    except S3Error as e:
        print(f"Error occurred: {e}")


# 使用示例
bucket_name = "test"  # 替换成你的bucket名称
folder_name = "checkpoints/"  # 权重文件夹的路径
local_dir = "app/service/image2sketch/checkpoints"  # 替换成你希望保存到的本地目录

download_folder(bucket_name, folder_name, local_dir)
