PSHomeCacheDepot / MEDIA /scripts /img_corrupt_check.py
pebxcvi's picture
Upload folder using huggingface_hub
5de05bb verified
import os
from shutil import move
from PIL import Image, UnidentifiedImageError
def is_image_corrupt(filepath):
try:
with Image.open(filepath) as img:
img.verify() # Verifies the integrity of the file without loading it.
with Image.open(filepath) as img:
img.load() # Attempt to load the image to catch deeper corruptions separately.
except (IOError, SyntaxError, UnidentifiedImageError, ValueError, AttributeError) as e:
return True, f'File is likely corrupt: {e}'
return False, 'File appears to be OK.'
def check_directory_for_corrupt_images(target_directories):
for target_directory in target_directories:
output_directory_suffix = "corrupted"
for root, dirs, files in os.walk(target_directory):
# Update: Skip the corrupted directory itself to avoid infinite loops.
if root.endswith(output_directory_suffix):
continue
for file in files:
if file.lower().endswith(('.png', '.jpg', '.jpeg', '.dds')):
filepath = os.path.join(root, file)
is_corrupt, message = is_image_corrupt(filepath)
if is_corrupt:
# Calculate the relative path
relative_path = os.path.relpath(root, target_directory)
output_directory = os.path.join(target_directory, output_directory_suffix, relative_path)
if not os.path.exists(output_directory):
os.makedirs(output_directory)
output_path = os.path.join(output_directory, file)
move(filepath, output_path)
print(f"Corrupt file found and moved: {filepath} - {message}")
# Optionally, you can keep track of these files or log this information as needed.
# Example usage
current_directory = os.getcwd()
target_directories = [
os.path.join(current_directory, "ARCHIVE")
]
check_directory_for_corrupt_images(target_directories)
input("Press Enter to exit...")