From 9022facac5c8a7f9bbc90cd3b4bc901e0b1c2faa Mon Sep 17 00:00:00 2001 From: Tanishq Dubey Date: Thu, 14 Nov 2024 18:56:46 -0500 Subject: [PATCH] EXIF Error handling --- app.py | 49 +++++++++++++++++++++++++++---------------------- 1 file changed, 27 insertions(+), 22 deletions(-) diff --git a/app.py b/app.py index 514595b..9213ad0 100644 --- a/app.py +++ b/app.py @@ -461,17 +461,22 @@ def admin_upload(): file_path = os.path.join(app.config["UPLOAD_FOLDER"], filename) file.save(file_path) - # Extract EXIF data - exif = None + # Extract EXIF data with error handling + exif = {} exifraw = None - with Image.open(file_path) as img: - exifraw = img.info["exif"] - width, height = img.size - exif = { - ExifTags.TAGS[k]: v - for k, v in img._getexif().items() - if k in ExifTags.TAGS - } + width = height = 0 + try: + with Image.open(file_path) as img: + width, height = img.size + if hasattr(img, '_getexif') and img._getexif() is not None: + exifraw = img.info.get("exif") + 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 unique_key = hashlib.sha256( @@ -489,25 +494,25 @@ def admin_upload(): # Generate thumbnails generate_thumbnails(filename) - # Get image dimensions - with Image.open(file_path) as img: - width, height = img.size + # Handle exposure time with error handling + try: + 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"] - 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 + # Create database entry with safe defaults db_session = DBSession() new_photo = Photo( input_filename=filename, thumbnail_filename=f"{os.path.splitext(filename)[0]}/256_{filename}", 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, date_taken=datetime.strptime( str(exif.get("DateTime", "1970:01:01 00:00:00")), "%Y:%m:%d %H:%M:%S"