|
| 1 | +""" |
| 2 | +EXIF data extraction module for image files. |
| 3 | +Extracts only date/time, GPS coordinates, and device identifiers. |
| 4 | +Excludes exposure settings and image metadata. |
| 5 | +""" |
| 6 | + |
| 7 | +import exifread |
| 8 | +from PIL import Image |
| 9 | +from PIL.ExifTags import TAGS |
| 10 | +from datetime import datetime |
| 11 | +from typing import List, Optional, Tuple |
| 12 | +from data_model import ExifData |
| 13 | +import os |
| 14 | +import warnings |
| 15 | +from pathlib import Path |
| 16 | +from contextlib import redirect_stderr |
| 17 | +from io import StringIO |
| 18 | + |
| 19 | +# Increase PIL image size limit to handle large images (we only read EXIF, not the full image) |
| 20 | +Image.MAX_IMAGE_PIXELS = None # Disable decompression bomb check |
| 21 | +warnings.filterwarnings('ignore', category=Image.DecompressionBombWarning) |
| 22 | + |
| 23 | + |
| 24 | +def _convert_to_decimal(degrees, minutes, seconds, ref): |
| 25 | + """ |
| 26 | + Convert GPS coordinates from degrees/minutes/seconds to decimal. |
| 27 | + """ |
| 28 | + decimal = float(degrees) + float(minutes) / 60.0 + float(seconds) / 3600.0 |
| 29 | + if ref in ['S', 'W']: |
| 30 | + decimal = -decimal |
| 31 | + return decimal |
| 32 | + |
| 33 | + |
| 34 | +def _get_gps_data(exif_data): |
| 35 | + """ |
| 36 | + Extract GPS coordinates from EXIF data (PIL format). |
| 37 | + """ |
| 38 | + if 'GPSInfo' not in exif_data: |
| 39 | + return None, None, None |
| 40 | + |
| 41 | + gps_info = exif_data['GPSInfo'] |
| 42 | + lat = lon = alt = None |
| 43 | + |
| 44 | + if 2 in gps_info and 3 in gps_info: |
| 45 | + lat_deg, lat_min, lat_sec = gps_info[2][0], gps_info[2][1], gps_info[2][2] |
| 46 | + lat_ref = gps_info[3] |
| 47 | + lat = _convert_to_decimal(lat_deg, lat_min, lat_sec, lat_ref) |
| 48 | + |
| 49 | + if 4 in gps_info and 5 in gps_info: |
| 50 | + lon_deg, lon_min, lon_sec = gps_info[4][0], gps_info[4][1], gps_info[4][2] |
| 51 | + lon_ref = gps_info[5] |
| 52 | + lon = _convert_to_decimal(lon_deg, lon_min, lon_sec, lon_ref) |
| 53 | + |
| 54 | + if 6 in gps_info: |
| 55 | + alt = float(gps_info[6]) |
| 56 | + |
| 57 | + return lat, lon, alt |
| 58 | + |
| 59 | + |
| 60 | +def _parse_datetime(date_str: str) -> Optional[datetime]: |
| 61 | + """ |
| 62 | + Parse EXIF datetime string to datetime object. |
| 63 | + """ |
| 64 | + if not date_str or not isinstance(date_str, str): |
| 65 | + return None |
| 66 | + date_str = date_str.strip() |
| 67 | + if not date_str: |
| 68 | + return None |
| 69 | + |
| 70 | + try: |
| 71 | + return datetime.strptime(date_str, "%Y:%m:%d %H:%M:%S") |
| 72 | + except (ValueError, TypeError): |
| 73 | + pass |
| 74 | + |
| 75 | + try: |
| 76 | + from dateutil import parser as dateutil_parser |
| 77 | + return dateutil_parser.parse(date_str) |
| 78 | + except Exception: |
| 79 | + pass |
| 80 | + |
| 81 | + for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%dT%H:%M:%SZ"): |
| 82 | + try: |
| 83 | + return datetime.strptime(date_str.replace('Z', '').split('.')[0].strip(), fmt) |
| 84 | + except (ValueError, TypeError): |
| 85 | + continue |
| 86 | + return None |
| 87 | + |
| 88 | + |
| 89 | +# Tag keys that contain binary data; show a short summary instead of raw bytes |
| 90 | +_BINARY_TAGS = frozenset({ |
| 91 | + 'JPEGThumbnail', 'TIFFThumbnail', 'EXIF MakerNote', 'EXIF Makernote', |
| 92 | + 'InteroperabilityTag', 'Image Tag 0x927C', 'Image Tag 0x9C9B', 'Image Tag 0x9C9C', |
| 93 | +}) |
| 94 | + |
| 95 | + |
| 96 | +def get_all_exif_tags(file_path: str) -> List[Tuple[str, str]]: |
| 97 | + """ |
| 98 | + Read all EXIF/metadata tags from an image file for display. |
| 99 | + Returns a sorted list of (tag_name, value_str). Binary tags are summarized as "(binary, N bytes)". |
| 100 | + On error returns an empty list. |
| 101 | + """ |
| 102 | + result: List[Tuple[str, str]] = [] |
| 103 | + seen: set = set() |
| 104 | + |
| 105 | + def add_tag(name: str, value_str: str) -> None: |
| 106 | + if name in seen: |
| 107 | + return |
| 108 | + seen.add(name) |
| 109 | + result.append((name, value_str)) |
| 110 | + |
| 111 | + try: |
| 112 | + with open(file_path, 'rb') as f: |
| 113 | + tags = exifread.process_file(f) |
| 114 | + except (OSError, IOError, ValueError): |
| 115 | + return [] |
| 116 | + |
| 117 | + for tag_name, value in tags.items(): |
| 118 | + if tag_name in _BINARY_TAGS or isinstance(value, (bytes, bytearray)): |
| 119 | + try: |
| 120 | + size = len(value) |
| 121 | + except (TypeError, AttributeError): |
| 122 | + size = 0 |
| 123 | + add_tag(tag_name, f"(binary, {size} bytes)") |
| 124 | + else: |
| 125 | + try: |
| 126 | + add_tag(tag_name, str(value).strip()) |
| 127 | + except Exception: |
| 128 | + add_tag(tag_name, "(unable to convert)") |
| 129 | + |
| 130 | + if not result: |
| 131 | + try: |
| 132 | + with warnings.catch_warnings(): |
| 133 | + warnings.filterwarnings('ignore') |
| 134 | + with redirect_stderr(StringIO()): |
| 135 | + with Image.open(file_path) as img: |
| 136 | + if hasattr(img, '_getexif') and img._getexif() is not None: |
| 137 | + for tag_id, value in img._getexif().items(): |
| 138 | + name = TAGS.get(tag_id, f"Tag {tag_id}") |
| 139 | + if name in seen: |
| 140 | + continue |
| 141 | + seen.add(name) |
| 142 | + try: |
| 143 | + result.append((name, str(value).strip())) |
| 144 | + except Exception: |
| 145 | + result.append((name, "(unable to convert)")) |
| 146 | + except Exception: |
| 147 | + pass |
| 148 | + |
| 149 | + return sorted(result, key=lambda x: x[0]) |
| 150 | + |
| 151 | + |
| 152 | +def extract_exif_data(file_path: str) -> ExifData: |
| 153 | + """ |
| 154 | + Extract EXIF data from an image file. |
| 155 | + Only extracts date/time, GPS coordinates, and device identifiers. |
| 156 | + """ |
| 157 | + file_name = os.path.basename(file_path) |
| 158 | + exif_data = ExifData(file_path=file_path, file_name=file_name) |
| 159 | + |
| 160 | + try: |
| 161 | + stderr_capture = StringIO() |
| 162 | + with redirect_stderr(stderr_capture): |
| 163 | + with open(file_path, 'rb') as f: |
| 164 | + tags = exifread.process_file(f, details=False) |
| 165 | + |
| 166 | + for date_tag in ['EXIF DateTimeOriginal', 'Image DateTime', 'EXIF DateTimeDigitized']: |
| 167 | + if date_tag in tags: |
| 168 | + date_str = str(tags[date_tag]) |
| 169 | + exif_data.date_taken = _parse_datetime(date_str) |
| 170 | + if exif_data.date_taken: |
| 171 | + break |
| 172 | + |
| 173 | + if 'Image Make' in tags: |
| 174 | + exif_data.make = str(tags['Image Make']).strip() |
| 175 | + if 'Image Model' in tags: |
| 176 | + exif_data.model = str(tags['Image Model']).strip() |
| 177 | + if 'EXIF BodySerialNumber' in tags: |
| 178 | + exif_data.serial_number = str(tags['EXIF BodySerialNumber']).strip() |
| 179 | + elif 'Image SerialNumber' in tags: |
| 180 | + exif_data.serial_number = str(tags['Image SerialNumber']).strip() |
| 181 | + if 'Image Software' in tags: |
| 182 | + exif_data.software = str(tags['Image Software']).strip() |
| 183 | + |
| 184 | + if 'GPS GPSLatitude' in tags and 'GPS GPSLatitudeRef' in tags: |
| 185 | + lat_deg = tags['GPS GPSLatitude'].values[0] |
| 186 | + lat_min = tags['GPS GPSLatitude'].values[1] |
| 187 | + lat_sec = tags['GPS GPSLatitude'].values[2] |
| 188 | + lat_ref = str(tags['GPS GPSLatitudeRef']) |
| 189 | + exif_data.latitude = _convert_to_decimal(lat_deg, lat_min, lat_sec, lat_ref) |
| 190 | + |
| 191 | + if 'GPS GPSLongitude' in tags and 'GPS GPSLongitudeRef' in tags: |
| 192 | + lon_deg = tags['GPS GPSLongitude'].values[0] |
| 193 | + lon_min = tags['GPS GPSLongitude'].values[1] |
| 194 | + lon_sec = tags['GPS GPSLongitude'].values[2] |
| 195 | + lon_ref = str(tags['GPS GPSLongitudeRef']) |
| 196 | + exif_data.longitude = _convert_to_decimal(lon_deg, lon_min, lon_sec, lon_ref) |
| 197 | + |
| 198 | + if 'GPS GPSAltitude' in tags: |
| 199 | + alt = tags['GPS GPSAltitude'] |
| 200 | + exif_data.altitude = float(alt.values[0]) |
| 201 | + if 'GPS GPSAltitudeRef' in tags and str(tags['GPS GPSAltitudeRef']) == '1': |
| 202 | + exif_data.altitude = -exif_data.altitude |
| 203 | + |
| 204 | + if not exif_data.has_gps(): |
| 205 | + try: |
| 206 | + with warnings.catch_warnings(): |
| 207 | + warnings.filterwarnings('ignore') |
| 208 | + try: |
| 209 | + with redirect_stderr(StringIO()): |
| 210 | + with Image.open(file_path) as img: |
| 211 | + if hasattr(img, '_getexif') and img._getexif() is not None: |
| 212 | + exif_dict = img._getexif() |
| 213 | + lat, lon, alt = _get_gps_data(exif_dict) |
| 214 | + if lat is not None: |
| 215 | + exif_data.latitude = lat |
| 216 | + if lon is not None: |
| 217 | + exif_data.longitude = lon |
| 218 | + if alt is not None: |
| 219 | + exif_data.altitude = alt |
| 220 | + if exif_data.date_taken is None: |
| 221 | + for tag_id, value in exif_dict.items(): |
| 222 | + tag = TAGS.get(tag_id, tag_id) |
| 223 | + if tag in ['DateTime', 'DateTimeOriginal', 'DateTimeDigitized']: |
| 224 | + exif_data.date_taken = _parse_datetime(str(value)) |
| 225 | + if exif_data.date_taken: |
| 226 | + break |
| 227 | + if not exif_data.make: |
| 228 | + for tag_id, value in exif_dict.items(): |
| 229 | + tag = TAGS.get(tag_id, tag_id) |
| 230 | + if tag == 'Make': |
| 231 | + exif_data.make = str(value).strip() |
| 232 | + elif tag == 'Model': |
| 233 | + exif_data.model = str(value).strip() |
| 234 | + elif tag == 'Software': |
| 235 | + exif_data.software = str(value).strip() |
| 236 | + except (Exception, IOError, OSError): |
| 237 | + pass |
| 238 | + except Exception: |
| 239 | + pass |
| 240 | + |
| 241 | + except Exception: |
| 242 | + pass |
| 243 | + |
| 244 | + return exif_data |
0 commit comments