|
2 | 2 |
|
3 | 3 | from __future__ import annotations |
4 | 4 |
|
| 5 | +import itertools |
5 | 6 | from contextlib import suppress |
| 7 | +from copy import deepcopy |
6 | 8 | from typing import TYPE_CHECKING |
7 | 9 |
|
8 | 10 | from PIL import Image, UnidentifiedImageError |
9 | 11 |
|
10 | 12 | from .exceptions import UnknownFieldError |
11 | | -from .fields import FIELDS, FieldGroup |
| 13 | +from .fields import EXIF_TAG_MAPPING, OWNERSHIP_FIELDS, PRESERVE_FIELDS, FieldGroup |
12 | 14 |
|
13 | 15 | if TYPE_CHECKING: |
14 | 16 | import os |
@@ -40,22 +42,38 @@ def process_image( |
40 | 42 | suppress(FileNotFoundError, UnidentifiedImageError), |
41 | 43 | Image.open(filename) as image, |
42 | 44 | ): |
43 | | - if exif := image.getexif(): |
44 | | - if FieldGroup.ALL in fields: |
45 | | - exif.clear() |
46 | | - has_changed = True |
47 | | - else: |
48 | | - for field in fields: |
49 | | - if locations := FIELDS.get(field): |
50 | | - for location in locations: |
51 | | - with suppress(KeyError): |
52 | | - del exif[location] |
53 | | - has_changed = True |
54 | | - else: |
55 | | - raise UnknownFieldError(field, FieldGroup) |
56 | | - |
57 | | - if has_changed: |
58 | | - image.save(filename, exif=exif) |
59 | | - print(f'Stripped EXIF metadata from {filename}') |
| 45 | + exif = image.getexif() |
| 46 | + |
| 47 | + if FieldGroup.ALL in fields: |
| 48 | + original_exif = deepcopy(exif) |
| 49 | + |
| 50 | + fields_to_preserve = { |
| 51 | + location: value |
| 52 | + for location in itertools.chain( |
| 53 | + PRESERVE_FIELDS, |
| 54 | + OWNERSHIP_FIELDS if FieldGroup.COPYRIGHT not in fields else {}, |
| 55 | + ) |
| 56 | + if (value := exif.get(location)) |
| 57 | + } |
| 58 | + |
| 59 | + exif.clear() |
| 60 | + |
| 61 | + for field, value in fields_to_preserve.items(): |
| 62 | + exif[field] = value |
| 63 | + |
| 64 | + has_changed = original_exif != exif |
| 65 | + else: |
| 66 | + for field in fields: |
| 67 | + if locations := EXIF_TAG_MAPPING.get(field): |
| 68 | + for location in locations: |
| 69 | + with suppress(KeyError): |
| 70 | + del exif[location] |
| 71 | + has_changed = True |
| 72 | + else: |
| 73 | + raise UnknownFieldError(field, FieldGroup) |
| 74 | + |
| 75 | + if has_changed: |
| 76 | + image.save(filename, exif=exif) |
| 77 | + print(f'Stripped EXIF metadata from {filename}') |
60 | 78 |
|
61 | 79 | return has_changed |
0 commit comments