EXIF Error handling

This commit is contained in:
Tanishq Dubey 2024-11-14 18:56:46 -05:00
parent 07725c99b4
commit 9022facac5

49
app.py
View File

@ -461,17 +461,22 @@ def admin_upload():
file_path = os.path.join(app.config["UPLOAD_FOLDER"], filename) file_path = os.path.join(app.config["UPLOAD_FOLDER"], filename)
file.save(file_path) file.save(file_path)
# Extract EXIF data # Extract EXIF data with error handling
exif = None exif = {}
exifraw = None exifraw = None
with Image.open(file_path) as img: width = height = 0
exifraw = img.info["exif"] try:
width, height = img.size with Image.open(file_path) as img:
exif = { width, height = img.size
ExifTags.TAGS[k]: v if hasattr(img, '_getexif') and img._getexif() is not None:
for k, v in img._getexif().items() exifraw = img.info.get("exif")
if k in ExifTags.TAGS exif = {
} ExifTags.TAGS[k]: v
for k, v in img._getexif().items()
if k in ExifTags.TAGS
}
except Exception as e:
logger.warning(f"Error reading EXIF data for {filename}: {str(e)}")
# Generate a unique key for the image # Generate a unique key for the image
unique_key = hashlib.sha256( unique_key = hashlib.sha256(
@ -489,25 +494,25 @@ def admin_upload():
# Generate thumbnails # Generate thumbnails
generate_thumbnails(filename) generate_thumbnails(filename)
# Get image dimensions # Handle exposure time with error handling
with Image.open(file_path) as img: try:
width, height = img.size exposure_time = exif.get("ExposureTime", 0)
if isinstance(exposure_time, tuple):
exposure_fraction = f"{exposure_time[0]}/{exposure_time[1]}"
else:
exposure_fraction = f"1/{int(1/float(exposure_time))}" if exposure_time else "0"
except (TypeError, ZeroDivisionError):
exposure_fraction = "0"
exposure_time = exif["ExposureTime"] # Create database entry with safe defaults
if isinstance(exposure_time, tuple):
exposure_fraction = f"{exposure_time[0]}/{exposure_time[1]}"
else:
exposure_fraction = f"1/{int(1/float(exposure_time))}"
# Create database entry
db_session = DBSession() db_session = DBSession()
new_photo = Photo( new_photo = Photo(
input_filename=filename, input_filename=filename,
thumbnail_filename=f"{os.path.splitext(filename)[0]}/256_{filename}", thumbnail_filename=f"{os.path.splitext(filename)[0]}/256_{filename}",
focal_length=str( focal_length=str(
exif.get("FocalLengthIn35mmFilm", exif.get("FocalLength", "")) exif.get("FocalLengthIn35mmFilm", exif.get("FocalLength", "0"))
), ),
aperture=str(exif.get("FNumber", "")), aperture=str(exif.get("FNumber", "0")),
shutter_speed=exposure_fraction, shutter_speed=exposure_fraction,
date_taken=datetime.strptime( date_taken=datetime.strptime(
str(exif.get("DateTime", "1970:01:01 00:00:00")), "%Y:%m:%d %H:%M:%S" str(exif.get("DateTime", "1970:01:01 00:00:00")), "%Y:%m:%d %H:%M:%S"