import os
import shutil
import time
from PIL import Image

def is_image_valid(image_path):
    """Check if the image is valid."""
    try:
        with Image.open(image_path) as img:
            img.verify()  # Verify the image integrity.
        return True
    except:
        return False

def scan_images(folder_path, log_file='invalid_images_log.txt', move_broken=False, broken_folder_path=None):
    """Scan all images in the folder and its subfolders and optionally move broken images."""
    image_paths = []
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.tiff')):
                image_paths.append(os.path.join(root, file))

    total_images = len(image_paths)
    processed_images = 0
    invalid_images_count = 0
    total_time = 0

    if move_broken and broken_folder_path and not os.path.exists(broken_folder_path):
        os.makedirs(broken_folder_path)

    with open(log_file, 'w') as log:
        for image_path in image_paths:
            start_time = time.time()

            if not is_image_valid(image_path):
                log.write(image_path + '\n')
                invalid_images_count += 1
                print(f"Invalid image found: {image_path}")

                if move_broken and broken_folder_path:
                    parent_folder = os.path.basename(os.path.dirname(image_path))
                    target_folder = os.path.join(broken_folder_path, parent_folder)
                    if not os.path.exists(target_folder):
                        os.makedirs(target_folder)
                    shutil.move(image_path, os.path.join(target_folder, os.path.basename(image_path)))

            end_time = time.time()
            processed_images += 1
            total_time += (end_time - start_time)

            average_time_ms = (total_time / processed_images) * 1000
            images_left = total_images - processed_images

            print(f"Processed: {processed_images}/{total_images}, Remaining: {images_left}, "
                  f"Average Time: {average_time_ms:.2f} ms, Invalid Images: {invalid_images_count}")

# Example usage
folder_path = r'G:\woman dataset\fixed_faces_png'  # Replace with your folder path
broken_folder_path = r'H:\woman broken'  # Replace with your desired path for broken images
scan_images(folder_path, move_broken=True, broken_folder_path=broken_folder_path)
