from PIL import Image, UnidentifiedImageError def is_valid(resource, file): """Check if the content is a readable JPEG image.""" try: with Image.open(file.name, formats=["JPEG"]): return True except UnidentifiedImageError: return False