|
2 | 2 | Copyright © 2025 John Liu |
3 | 3 | """ |
4 | 4 |
|
| 5 | +import json |
5 | 6 | import subprocess |
6 | 7 | import tomllib |
| 8 | +from datetime import datetime |
7 | 9 | from importlib.metadata import version |
| 10 | +from os.path import getmtime, getsize |
8 | 11 | from pathlib import Path |
9 | 12 |
|
| 13 | +import piexif |
| 14 | +import pillow_heif |
10 | 15 | from loguru import logger |
| 16 | +from PIL import Image, ImageChops |
11 | 17 |
|
12 | | -from batch_img.const import PKG_NAME, VER |
| 18 | +from batch_img.const import PKG_NAME, TS_FORMAT, VER |
| 19 | + |
| 20 | +pillow_heif.register_heif_opener() # allow Pillow to open HEIC files |
13 | 21 |
|
14 | 22 |
|
15 | 23 | class Common: |
@@ -51,3 +59,115 @@ def run_cmd(cmd: str) -> tuple: |
51 | 59 | except subprocess.CalledProcessError as e: |
52 | 60 | logger.exception(e) |
53 | 61 | raise e |
| 62 | + |
| 63 | + @staticmethod |
| 64 | + def readable_file_size(in_bytes: int) -> str: |
| 65 | + """Convert bytes to human-readable KB, MB, or GB |
| 66 | +
|
| 67 | + Args: |
| 68 | + in_bytes: input bytes integer |
| 69 | +
|
| 70 | + Returns: |
| 71 | + str |
| 72 | + """ |
| 73 | + for _unit in ["B", "KB", "MB", "GB"]: |
| 74 | + if in_bytes < 1024: |
| 75 | + break |
| 76 | + in_bytes /= 1024 |
| 77 | + res = f"{in_bytes} B" if _unit == "B" else f"{in_bytes:.1f} {_unit}" |
| 78 | + return res |
| 79 | + |
| 80 | + @staticmethod |
| 81 | + def decode_exif(exif_data: str) -> dict: |
| 82 | + """Decode the EXIF data |
| 83 | +
|
| 84 | + Args: |
| 85 | + exif_data: str |
| 86 | +
|
| 87 | + Returns: |
| 88 | + dict |
| 89 | + """ |
| 90 | + exif_dict = piexif.load(exif_data) |
| 91 | + _dict = {} |
| 92 | + for ifd_name, val in exif_dict.items(): |
| 93 | + if not val: |
| 94 | + continue |
| 95 | + for tag_id, value in val.items(): |
| 96 | + tag_name = piexif.TAGS[ifd_name].get(tag_id, {}).get("name", tag_id) |
| 97 | + _dict[tag_name] = value |
| 98 | + for key in ( |
| 99 | + "FNumber", |
| 100 | + "FocalLength", |
| 101 | + "MakerNote", |
| 102 | + "SceneType", |
| 103 | + "SubjectArea", |
| 104 | + "Software", |
| 105 | + "HostComputer", |
| 106 | + ): |
| 107 | + if key in _dict: |
| 108 | + _dict.pop(key) |
| 109 | + keys = list(_dict.keys()) |
| 110 | + for keyword in ( |
| 111 | + "DateTime", |
| 112 | + "GPS", |
| 113 | + "OffsetTime", |
| 114 | + "SubSecTime", |
| 115 | + "Tile", |
| 116 | + "Pixel", |
| 117 | + "Lens", |
| 118 | + "Resolution", |
| 119 | + "Value", |
| 120 | + ): |
| 121 | + for key in keys: |
| 122 | + if key.startswith(keyword) or key.endswith(keyword): |
| 123 | + _dict.pop(key) |
| 124 | + _res = { |
| 125 | + k: (v.decode() if isinstance(v, bytes) else v) for k, v in _dict.items() |
| 126 | + } |
| 127 | + logger.info(f"{_res=}") |
| 128 | + return _res |
| 129 | + |
| 130 | + @staticmethod |
| 131 | + def are_images_equal(path1: Path | str, path2: Path | str) -> bool: |
| 132 | + """Check if two image files are visually equal pixel-wise |
| 133 | +
|
| 134 | + Args: |
| 135 | + path1: image1 file path |
| 136 | + path2: image2 file path |
| 137 | +
|
| 138 | + Returns: |
| 139 | + bool: True - visually equal, False - not visually equal |
| 140 | + """ |
| 141 | + size1 = getsize(path1) |
| 142 | + m_ts1 = datetime.fromtimestamp(getmtime(path1)).strftime(TS_FORMAT) |
| 143 | + with Image.open(path1) as img1: |
| 144 | + data1 = img1.convert("RGB") |
| 145 | + meta1 = { |
| 146 | + "file_size": Common.readable_file_size(size1), |
| 147 | + "file_ts": m_ts1, |
| 148 | + "format": img1.format, |
| 149 | + "size": img1.size, |
| 150 | + "mode": img1.mode, |
| 151 | + "info": img1.info, |
| 152 | + } |
| 153 | + if "exif" in img1.info: |
| 154 | + meta1["info"] = Common.decode_exif(img1.info["exif"]) |
| 155 | + |
| 156 | + size2 = getsize(path2) |
| 157 | + m_ts2 = datetime.fromtimestamp(getmtime(path2)).strftime(TS_FORMAT) |
| 158 | + with Image.open(path2) as img2: |
| 159 | + data2 = img2.convert("RGB") |
| 160 | + meta2 = { |
| 161 | + "file_size": Common.readable_file_size(size2), |
| 162 | + "file_ts": m_ts2, |
| 163 | + "format": img2.format, |
| 164 | + "size": img2.size, |
| 165 | + "mode": img2.mode, |
| 166 | + "info": img2.info, |
| 167 | + } |
| 168 | + if "exif" in img2.info: |
| 169 | + meta2["info"] = Common.decode_exif(img2.info["exif"]) |
| 170 | + |
| 171 | + logger.info(f"Meta of {path1}:\n{json.dumps(meta1, indent=2)}") |
| 172 | + logger.info(f"Meta of {path2}:\n{json.dumps(meta2, indent=2)}") |
| 173 | + return ImageChops.difference(data1, data2).getbbox() is None |
0 commit comments