imagent-cli 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- imagent/__init__.py +0 -0
- imagent/__main__.py +5 -0
- imagent/cli.py +128 -0
- imagent/commands/__init__.py +0 -0
- imagent/commands/after_add.py +82 -0
- imagent/commands/delete.py +200 -0
- imagent/commands/failed.py +24 -0
- imagent/commands/forget.py +63 -0
- imagent/commands/help.py +82 -0
- imagent/commands/menu.py +155 -0
- imagent/commands/scan.py +1394 -0
- imagent/commands/search.py +432 -0
- imagent/commands/settings.py +139 -0
- imagent/commands/setup.py +1409 -0
- imagent/commands/uninstall.py +379 -0
- imagent/config.py +331 -0
- imagent/db/__init__.py +1 -0
- imagent/db/connection.py +237 -0
- imagent/db/operations.py +683 -0
- imagent/db/schema.sql +454 -0
- imagent/image_processing/__init__.py +14 -0
- imagent/image_processing/convert.py +48 -0
- imagent/image_processing/features.py +88 -0
- imagent/image_processing/hashing.py +49 -0
- imagent/image_processing/memory.py +101 -0
- imagent/image_processing/metadata.py +122 -0
- imagent/image_processing/ocr.py +129 -0
- imagent/image_processing/preprocess.py +33 -0
- imagent/image_processing/problems.py +53 -0
- imagent/image_processing/sample_pictures.py +214 -0
- imagent/os_specific/__init__.py +15 -0
- imagent/os_specific/convert.py +34 -0
- imagent/os_specific/files.py +64 -0
- imagent/os_specific/locking.py +31 -0
- imagent/os_specific/memory.py +153 -0
- imagent/os_specific/process.py +19 -0
- imagent/os_specific/storage.py +102 -0
- imagent/pipeline/__init__.py +1 -0
- imagent/pipeline/console.py +111 -0
- imagent/pipeline/discovery.py +107 -0
- imagent/pipeline/error_logger.py +69 -0
- imagent/pipeline/error_messages.py +56 -0
- imagent/pipeline/failure.py +51 -0
- imagent/pipeline/folder_picker.py +289 -0
- imagent/pipeline/locking.py +44 -0
- imagent/pipeline/progress.py +243 -0
- imagent/pipeline/serialisation.py +20 -0
- imagent/pipeline/storage.py +30 -0
- imagent/pipeline/validation.py +68 -0
- imagent/pipeline/versions.py +56 -0
- imagent/prompts/analysis_prompt.txt +8 -0
- imagent/prompts/analysis_schema.json +12 -0
- imagent/prompts/query_prompt.txt +14 -0
- imagent/text_processing/__init__.py +1 -0
- imagent/text_processing/cleaners.py +32 -0
- imagent/text_processing/formatters.py +79 -0
- imagent/vlm/__init__.py +1 -0
- imagent/vlm/analyzer.py +348 -0
- imagent/vlm/calibration.py +288 -0
- imagent/vlm/client.py +302 -0
- imagent/vlm/reply_validation.py +72 -0
- imagent/vlm/response_format.py +7 -0
- imagent_cli-0.1.0.dist-info/METADATA +171 -0
- imagent_cli-0.1.0.dist-info/RECORD +68 -0
- imagent_cli-0.1.0.dist-info/WHEEL +5 -0
- imagent_cli-0.1.0.dist-info/entry_points.txt +2 -0
- imagent_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
- imagent_cli-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""
|
|
2
|
+
imagent/image_processing/memory.py — Decide whether an image fits in the memory this computer has free right now.
|
|
3
|
+
|
|
4
|
+
No pixel count is fixed in advance: what an image may be depends on the machine, and on what else is using it. Before an
|
|
5
|
+
image is opened its size is read from the file's header; if the memory it needs at its peak is more than the share of the
|
|
6
|
+
free memory it may use, the image is set aside with the reason. When this computer will not say how much memory is free,
|
|
7
|
+
Pillow's own limit stands in for it (see image_processing/__init__.py), so an image is never let through unchecked.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from PIL import Image
|
|
13
|
+
|
|
14
|
+
from imagent import config
|
|
15
|
+
from imagent.image_processing import PIXEL_LIMIT_WHEN_MEMORY_UNKNOWN
|
|
16
|
+
from imagent.image_processing.problems import TOO_LARGE, explain, problem
|
|
17
|
+
from imagent.os_specific.memory import available_memory
|
|
18
|
+
|
|
19
|
+
# Bytes of memory one pixel needs at the peak of reading an image, by the picture's mode. Pillow keeps a decoded picture in
|
|
20
|
+
# 1 byte a pixel for the modes 1, L and P, 2 for the 16-bit gray ones and 4 for every other (RGB too: it is padded to 4; the
|
|
21
|
+
# 3 bytes are only those of tobytes() and of an array), the same on every system. Reading a picture holds, besides the decoded
|
|
22
|
+
# image, the larger of two copies of it that are never held together: the RGB copy of a picture that is not RGB already
|
|
23
|
+
# (4 bytes a pixel), or the picture turned by its EXIF orientation (ImageOps.exif_transpose makes the turned one before it
|
|
24
|
+
# lets go of the first, in place or not), plus a little the decoder keeps while it decodes. That makes, turned or not:
|
|
25
|
+
# RGB 5 (9 when turned), RGBA and every other mode of 4 bytes 9, L, P and 1 6, 16-bit gray 7. The peaks measured on pictures of
|
|
26
|
+
# 48 megapixels agree: RGB 4.6 (8.3 turned), RGBA 8.6. Not counted: the OCR engine's array of a whole picture, 3 more bytes, which
|
|
27
|
+
# is only made of a picture small enough for the engine to read in one piece.
|
|
28
|
+
_ONE_BYTE_MODES = {"1", "L", "P"}
|
|
29
|
+
_TWO_BYTE_MODES = {"I;16", "I;16L", "I;16B", "I;16N"}
|
|
30
|
+
_RGB_COPY = 4
|
|
31
|
+
_DECODER_EXTRA = 1
|
|
32
|
+
_EXIF_ORIENTATION = 0x0112
|
|
33
|
+
_TURNED = range(2, 9) # the orientations ImageOps.exif_transpose acts on; 1, or none, leaves the picture as it is
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def peak_bytes_per_pixel(mode: str, turned: bool = False) -> int:
|
|
37
|
+
"""Bytes of memory one pixel of a picture of this ``mode`` needs at the peak of reading it (see above).
|
|
38
|
+
|
|
39
|
+
``turned``: the picture is turned by its EXIF orientation. A mode that is not known is taken to be one of 4 bytes."""
|
|
40
|
+
stored = 1 if mode in _ONE_BYTE_MODES else 2 if mode in _TWO_BYTE_MODES else 4
|
|
41
|
+
copy = max(_RGB_COPY if mode != "RGB" else 0, stored if turned else 0)
|
|
42
|
+
return stored + copy + _DECODER_EXTRA
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _is_turned(img: Image.Image) -> bool:
|
|
46
|
+
"""Whether reading the opened picture turns it by its EXIF orientation, told from the header alone.
|
|
47
|
+
|
|
48
|
+
A PNG's ``getexif()`` decodes the whole picture when the header has no EXIF chunk, which is what the check is there to avoid,
|
|
49
|
+
so such a PNG counts as not turned."""
|
|
50
|
+
if img.format == "PNG" and "exif" not in img.info:
|
|
51
|
+
return False
|
|
52
|
+
return img.getexif().get(_EXIF_ORIENTATION, 1) in _TURNED
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def fits_in_memory(width: int, height: int, bytes_per_pixel: int, available: int | None, share: float | None = None) -> bool:
|
|
56
|
+
"""Whether an image of this size fits in the memory free.
|
|
57
|
+
|
|
58
|
+
``available`` None means this computer does not say; the image then fits if it is within Pillow's own limit.
|
|
59
|
+
``bytes_per_pixel``: what a pixel of the image needs at the peak (``peak_bytes_per_pixel``).
|
|
60
|
+
``share`` is the part of the free memory the image may use; ``config.IMAGE_MEMORY_SHARE`` unless given.
|
|
61
|
+
"""
|
|
62
|
+
if available is None:
|
|
63
|
+
return PIXEL_LIMIT_WHEN_MEMORY_UNKNOWN is None or width * height <= PIXEL_LIMIT_WHEN_MEMORY_UNKNOWN
|
|
64
|
+
budget = available * (config.IMAGE_MEMORY_SHARE if share is None else share)
|
|
65
|
+
return width * height * bytes_per_pixel <= budget
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def exif_can_be_read(img: Image.Image) -> bool:
|
|
69
|
+
"""Whether the EXIF of the opened picture can be asked for without risking the memory.
|
|
70
|
+
|
|
71
|
+
A PNG whose header has no EXIF chunk is the exception: Pillow then reads to the end of the file for one, which decodes the
|
|
72
|
+
whole picture, so it is asked only when the picture fits in the memory free. Every other format keeps its EXIF in the header."""
|
|
73
|
+
if img.format != "PNG" or "exif" in img.info:
|
|
74
|
+
return True
|
|
75
|
+
width, height = img.size
|
|
76
|
+
return fits_in_memory(width, height, peak_bytes_per_pixel(img.mode), available_memory())
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def check_image_size(path: str, share: float | None = None) -> None:
|
|
80
|
+
"""Raises ``ImageProblem`` if the image at ``path`` cannot be opened or is too large for the memory free.
|
|
81
|
+
|
|
82
|
+
``share``: the part of the free memory the image may use, ``config.IMAGE_MEMORY_SHARE`` unless given (see ``fits_in_memory``)."""
|
|
83
|
+
try:
|
|
84
|
+
with Image.open(path) as img:
|
|
85
|
+
width, height = img.size
|
|
86
|
+
bytes_per_pixel = peak_bytes_per_pixel(img.mode, _is_turned(img))
|
|
87
|
+
except Exception as exc:
|
|
88
|
+
raise (explain(exc, path) or exc) from exc
|
|
89
|
+
available = available_memory()
|
|
90
|
+
share = config.IMAGE_MEMORY_SHARE if share is None else share
|
|
91
|
+
if not fits_in_memory(width, height, bytes_per_pixel, available, share):
|
|
92
|
+
megapixels = width * height / 1_000_000
|
|
93
|
+
if available is None:
|
|
94
|
+
detail = f"this computer does not say how much memory is free, and the picture is more than Pillow's own limit of {PIXEL_LIMIT_WHEN_MEMORY_UNKNOWN} pixels"
|
|
95
|
+
error_id = "picture_too_large_memory_unknown"
|
|
96
|
+
else:
|
|
97
|
+
detail = (f"more than the memory free right now allows: it needs about {width * height * bytes_per_pixel // 10**6} MB "
|
|
98
|
+
f"and {int(available * share) // 10**6} MB can be used")
|
|
99
|
+
error_id = "picture_too_large"
|
|
100
|
+
raise problem(TOO_LARGE, error_id, params={"megapixels": f"{megapixels:.0f}"},
|
|
101
|
+
step="checked the size", detail=f"{megapixels:.0f} megapixels, {detail}", park=False)
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""
|
|
2
|
+
imagent/image_processing/metadata.py — Extract file-level metadata from an image path.
|
|
3
|
+
|
|
4
|
+
Reads OS-level stat data (size, timestamps) and opens the image with Pillow to
|
|
5
|
+
determine pixel dimensions and MIME type. Does not call the VLM.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import mimetypes
|
|
11
|
+
import os
|
|
12
|
+
from datetime import datetime, timezone
|
|
13
|
+
|
|
14
|
+
from PIL import Image
|
|
15
|
+
|
|
16
|
+
from imagent.image_processing.memory import exif_can_be_read
|
|
17
|
+
|
|
18
|
+
# What ``mimetypes`` knows depends on the computer's own list (and the Python version): it has no entry for HEIC, the iPhone's
|
|
19
|
+
# format, on many. The formats Imagent reads are named here, so the type stored does not depend on the computer.
|
|
20
|
+
_MIME_TYPES = {
|
|
21
|
+
".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png", ".webp": "image/webp", ".gif": "image/gif",
|
|
22
|
+
".bmp": "image/bmp", ".tif": "image/tiff", ".tiff": "image/tiff", ".heic": "image/heic", ".heif": "image/heif",
|
|
23
|
+
".avif": "image/avif",
|
|
24
|
+
}
|
|
25
|
+
_EXIF_IFD = 0x8769 # pointer to the Exif sub-directory (DateTimeOriginal lives here)
|
|
26
|
+
_GPS_IFD = 0x8825 # pointer to the GPS sub-directory
|
|
27
|
+
_NO_EXIF = {"taken_at": None, "camera_make": None, "camera_model": None, "gps_lat": None, "gps_lon": None}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def extract_file_metadata(path: str) -> dict:
|
|
31
|
+
"""Return a dict of file-level metadata for the image at *path*.
|
|
32
|
+
|
|
33
|
+
Keys returned:
|
|
34
|
+
width (int | None) — pixel width; None if Pillow cannot open the file.
|
|
35
|
+
height (int | None) — pixel height; None if Pillow cannot open the file.
|
|
36
|
+
file_size (int) — file size in bytes.
|
|
37
|
+
mime_type (str | None) — guessed MIME type (e.g. 'image/jpeg').
|
|
38
|
+
created_at (str | None) — ISO 8601 UTC timestamp of file birth (None where the filesystem doesn't report it).
|
|
39
|
+
modified_at (str) — ISO 8601 UTC timestamp of last modification.
|
|
40
|
+
taken_at (str | None) — ISO 8601 local capture time from EXIF (no timezone); None if absent.
|
|
41
|
+
camera_make (str | None), camera_model (str | None) — from EXIF; None if absent.
|
|
42
|
+
gps_lat (float | None), gps_lon (float | None) — decimal degrees from EXIF; None if absent.
|
|
43
|
+
"""
|
|
44
|
+
stat = os.stat(path)
|
|
45
|
+
|
|
46
|
+
# --- Dimensions and EXIF ---
|
|
47
|
+
width: int | None = None
|
|
48
|
+
height: int | None = None
|
|
49
|
+
exif_fields = dict(_NO_EXIF)
|
|
50
|
+
try:
|
|
51
|
+
with Image.open(path) as img:
|
|
52
|
+
width, height = img.size
|
|
53
|
+
if exif_can_be_read(img): # not for a PNG too large to decode: the size check that follows refuses it
|
|
54
|
+
exif_fields = _extract_exif(img)
|
|
55
|
+
except Exception:
|
|
56
|
+
# Non-fatal: dimensions stay None; the rest of the metadata is still valid.
|
|
57
|
+
pass
|
|
58
|
+
|
|
59
|
+
# --- MIME type ---
|
|
60
|
+
mime_type = _MIME_TYPES.get(os.path.splitext(path)[1].lower()) or mimetypes.guess_type(path)[0]
|
|
61
|
+
|
|
62
|
+
# --- Timestamps ---
|
|
63
|
+
modified_at = iso_utc(stat.st_mtime)
|
|
64
|
+
|
|
65
|
+
# st_birthtime exists on macOS and (Python 3.12+) Windows, not on Linux; st_ctime is not a creation time, so don't substitute it.
|
|
66
|
+
created_at: str | None = None
|
|
67
|
+
if hasattr(stat, "st_birthtime"):
|
|
68
|
+
created_at = iso_utc(stat.st_birthtime)
|
|
69
|
+
|
|
70
|
+
return {
|
|
71
|
+
"width": width,
|
|
72
|
+
"height": height,
|
|
73
|
+
"file_size": stat.st_size,
|
|
74
|
+
"mime_type": mime_type,
|
|
75
|
+
"created_at": created_at,
|
|
76
|
+
"modified_at": modified_at,
|
|
77
|
+
**exif_fields,
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _extract_exif(img: Image.Image) -> dict:
|
|
82
|
+
"""Read capture time, camera and GPS from EXIF. Fields the file lacks stay None."""
|
|
83
|
+
fields = dict(_NO_EXIF)
|
|
84
|
+
try:
|
|
85
|
+
exif = img.getexif()
|
|
86
|
+
if not exif:
|
|
87
|
+
return fields
|
|
88
|
+
fields["camera_make"] = _clean_text(exif.get(0x010F))
|
|
89
|
+
fields["camera_model"] = _clean_text(exif.get(0x0110))
|
|
90
|
+
raw = exif.get_ifd(_EXIF_IFD).get(0x9003) or exif.get(0x0132) # DateTimeOriginal, else DateTime
|
|
91
|
+
if raw:
|
|
92
|
+
try:
|
|
93
|
+
fields["taken_at"] = datetime.strptime(str(raw).strip(), "%Y:%m:%d %H:%M:%S").isoformat()
|
|
94
|
+
except ValueError:
|
|
95
|
+
pass
|
|
96
|
+
gps = exif.get_ifd(_GPS_IFD)
|
|
97
|
+
fields["gps_lat"] = _gps_degrees(gps.get(2), gps.get(1))
|
|
98
|
+
fields["gps_lon"] = _gps_degrees(gps.get(4), gps.get(3))
|
|
99
|
+
except Exception:
|
|
100
|
+
# Non-fatal: EXIF is optional extra metadata; keep whatever was read.
|
|
101
|
+
pass
|
|
102
|
+
return fields
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _clean_text(value) -> str | None:
|
|
106
|
+
text = str(value).replace("\x00", "").strip() if value is not None else ""
|
|
107
|
+
return text or None
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _gps_degrees(dms, ref) -> float | None:
|
|
111
|
+
"""Convert EXIF (degrees, minutes, seconds) plus an N/S/E/W reference to signed decimal degrees."""
|
|
112
|
+
try:
|
|
113
|
+
degrees, minutes, seconds = (float(part) for part in dms)
|
|
114
|
+
except (TypeError, ValueError, ZeroDivisionError):
|
|
115
|
+
return None
|
|
116
|
+
value = degrees + minutes / 60 + seconds / 3600
|
|
117
|
+
return -value if ref in ("S", "W") else value
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def iso_utc(timestamp: float) -> str:
|
|
121
|
+
"""Convert a POSIX timestamp to an ISO 8601 UTC string (also used by commands/scan.py, so both agree on the format)."""
|
|
122
|
+
return datetime.fromtimestamp(timestamp, tz=timezone.utc).isoformat()
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""
|
|
2
|
+
imagent/image_processing/ocr.py — Read the text in an image with a local OCR engine.
|
|
3
|
+
|
|
4
|
+
Runs on the original full-size image: the VLM only sees a downscaled copy, which loses small text.
|
|
5
|
+
Does not call Ollama.
|
|
6
|
+
|
|
7
|
+
An image larger than the engine reads without shrinking it is cut into tiles from the start (the engine would shrink it,
|
|
8
|
+
and finds text only above about 2% of the image side). When reading fails, what is tried next depends on where it failed,
|
|
9
|
+
and each step changes something: the whole image; then the image cut into tiles (no tile is larger than the engine reads without shrinking it,
|
|
10
|
+
so nothing is lost, and the engine works on far less at a time); then the tiles again with the engine loaded afresh.
|
|
11
|
+
When all of them fail the image is not stored without its text: it is set aside (``ImageProblem`` of kind ``ocr_failed``).
|
|
12
|
+
Finding no text is not a failure.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import functools
|
|
18
|
+
import warnings
|
|
19
|
+
|
|
20
|
+
import numpy as np
|
|
21
|
+
from PIL import Image, ImageOps
|
|
22
|
+
|
|
23
|
+
from imagent import config
|
|
24
|
+
from imagent.image_processing.preprocess import to_rgb
|
|
25
|
+
from imagent.image_processing.problems import OCR_FAILED, TOO_LARGE, ImageProblem, explain
|
|
26
|
+
from imagent.pipeline.failure import attempt_record
|
|
27
|
+
|
|
28
|
+
_EXIF_ORIENTATION = 0x0112
|
|
29
|
+
# What each EXIF orientation does to a picture, undone on each tile the same way ImageOps.exif_transpose does on a whole image.
|
|
30
|
+
_UNTURN = {
|
|
31
|
+
2: Image.Transpose.FLIP_LEFT_RIGHT, 3: Image.Transpose.ROTATE_180, 4: Image.Transpose.FLIP_TOP_BOTTOM,
|
|
32
|
+
5: Image.Transpose.TRANSPOSE, 6: Image.Transpose.ROTATE_270, 7: Image.Transpose.TRANSVERSE, 8: Image.Transpose.ROTATE_90,
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@functools.lru_cache(maxsize=1)
|
|
37
|
+
def _engine():
|
|
38
|
+
# Imported here because loading the OCR models takes a moment and is only needed once.
|
|
39
|
+
# The first import of requests (by rapidocr) warns when Python is built on LibreSSL, as the one macOS ships is;
|
|
40
|
+
# nothing here depends on it, since Ollama is reached over plain http.
|
|
41
|
+
warnings.filterwarnings("ignore", message="urllib3 v2 only supports OpenSSL")
|
|
42
|
+
from rapidocr import RapidOCR
|
|
43
|
+
# By default it logs every model it loads; "error" also hides its warning for every image without text.
|
|
44
|
+
return RapidOCR(params={"Global.log_level": "error"})
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def check_available() -> None:
|
|
48
|
+
"""Load the OCR engine now, so a problem shows before indexing starts and not as images set aside for their text.
|
|
49
|
+
|
|
50
|
+
Raises whatever the engine raises when it cannot load.
|
|
51
|
+
"""
|
|
52
|
+
_engine()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _read(pixels_bgr: np.ndarray) -> list[str]:
|
|
56
|
+
"""The pieces of text the engine finds in an image (an array of BGR pixels), above the confidence limit."""
|
|
57
|
+
output = _engine()(pixels_bgr)
|
|
58
|
+
texts = output.txts if output.txts is not None else () # None when no text was found
|
|
59
|
+
confidences = output.scores if output.scores is not None else ()
|
|
60
|
+
return [
|
|
61
|
+
text.strip()
|
|
62
|
+
for text, confidence in zip(texts, confidences)
|
|
63
|
+
if text.strip() and float(confidence) >= config.OCR_MIN_CONFIDENCE
|
|
64
|
+
]
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _bgr(img: Image.Image) -> np.ndarray:
|
|
68
|
+
return np.array(to_rgb(img))[:, :, ::-1] # the engine expects BGR
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _read_whole(image_path: str) -> list[str]:
|
|
72
|
+
"""Read the image in one piece; one that is larger than the engine reads without shrinking it is read in tiles at once,
|
|
73
|
+
because the engine would shrink it and miss the smaller text."""
|
|
74
|
+
with Image.open(image_path) as img:
|
|
75
|
+
longest = max(img.size)
|
|
76
|
+
if longest > int(getattr(_engine(), "max_side_len", 0) or longest):
|
|
77
|
+
return _read_tiled(image_path)
|
|
78
|
+
with Image.open(image_path) as img:
|
|
79
|
+
ImageOps.exif_transpose(img, in_place=True) # turned where it is: a copy of the whole image is not made
|
|
80
|
+
pixels = _bgr(img)
|
|
81
|
+
return _read(pixels)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _starts(length: int, side: int, step: int) -> list[int]:
|
|
85
|
+
"""Where tiles of ``side`` begin along an edge of ``length``, ``step`` apart, the last one ending at the edge."""
|
|
86
|
+
if length <= side:
|
|
87
|
+
return [0]
|
|
88
|
+
return sorted({*range(0, length - side, step), length - side})
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _read_tiled(image_path: str) -> list[str]:
|
|
92
|
+
"""Read the image tile by tile, from one decoded copy; only a tile is turned into an array at a time."""
|
|
93
|
+
with Image.open(image_path) as img:
|
|
94
|
+
orientation = img.getexif().get(_EXIF_ORIENTATION, 1)
|
|
95
|
+
rgb = to_rgb(img)
|
|
96
|
+
width, height = rgb.size
|
|
97
|
+
# The engine shrinks anything above its own maximum side and, tested on images of text, finds text only when it is above about 2% of the image side;
|
|
98
|
+
# so a tile is a share of that maximum, which makes smaller text readable.
|
|
99
|
+
side = max(int(getattr(_engine(), "max_side_len", 0) * config.OCR_TILE_SHARE) or max(width, height), 1)
|
|
100
|
+
step = max(int(side * (1 - config.OCR_TILE_OVERLAP)), 1)
|
|
101
|
+
texts: list[str] = []
|
|
102
|
+
for top in _starts(height, side, step):
|
|
103
|
+
for left in _starts(width, side, step):
|
|
104
|
+
tile = rgb.crop((left, top, min(left + side, width), min(top + side, height)))
|
|
105
|
+
if orientation in _UNTURN:
|
|
106
|
+
tile = tile.transpose(_UNTURN[orientation])
|
|
107
|
+
texts.extend(_read(_bgr(tile)))
|
|
108
|
+
return texts
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def extract_text_blocks(image_path: str) -> list[str]:
|
|
112
|
+
"""Return each separate piece of text found in the image (empty if it has none).
|
|
113
|
+
|
|
114
|
+
Raises ``ImageProblem`` if the image cannot be opened, or if reading its text failed in every way tried.
|
|
115
|
+
"""
|
|
116
|
+
steps = [("whole image", _read_whole), ("tiles", _read_tiled), ("tiles, engine loaded afresh", _read_tiled)]
|
|
117
|
+
attempts: list[dict] = []
|
|
118
|
+
for name, read in steps:
|
|
119
|
+
if name.endswith("afresh"):
|
|
120
|
+
_engine.cache_clear()
|
|
121
|
+
try:
|
|
122
|
+
return read(image_path)
|
|
123
|
+
except Exception as exc:
|
|
124
|
+
found = explain(exc, image_path)
|
|
125
|
+
if found is not None and not (found.kind == TOO_LARGE and name == "whole image"): # too little memory for the whole image: try tiles
|
|
126
|
+
raise found from exc # the image itself cannot be read; no other way of reading it helps
|
|
127
|
+
attempts.append(attempt_record(name, OCR_FAILED, f"{type(exc).__name__}: {exc}"))
|
|
128
|
+
steps = "; ".join(f"{a['step']}: {a['detail']}" for a in attempts)
|
|
129
|
+
raise ImageProblem(OCR_FAILED, "text_unreadable", attempts, params={"steps": steps}, service=True)
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import io
|
|
2
|
+
from PIL import Image, ImageOps
|
|
3
|
+
from imagent import config
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def to_rgb(img: Image.Image) -> Image.Image:
|
|
7
|
+
"""The picture as RGB. A picture with transparent parts is shown on white, as image viewers show it: dropping the alpha channel
|
|
8
|
+
instead leaves whatever color the transparent pixels hold, usually black, which hides a dark logo or text from the model."""
|
|
9
|
+
if img.mode == "RGB":
|
|
10
|
+
return img
|
|
11
|
+
if img.mode in ("RGBA", "LA", "PA", "La", "RGBa") or "transparency" in img.info:
|
|
12
|
+
rgba = img.convert("RGBA")
|
|
13
|
+
flat = Image.new("RGB", rgba.size, (255, 255, 255))
|
|
14
|
+
flat.paste(rgba, mask=rgba.getchannel("A"))
|
|
15
|
+
return flat
|
|
16
|
+
return img.convert("RGB")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def preprocess_image(image_path: str) -> bytes:
|
|
20
|
+
"""The image as the JPEG sent to the vision model, at most ``config.IMAGE_MAX_LONG_EDGE`` on its long side."""
|
|
21
|
+
with Image.open(image_path) as img:
|
|
22
|
+
ImageOps.exif_transpose(img, in_place=True) # turned where it is: a copy of the whole image is not made
|
|
23
|
+
img = to_rgb(img)
|
|
24
|
+
w, h = img.size
|
|
25
|
+
long_edge = max(w, h)
|
|
26
|
+
if long_edge > config.IMAGE_MAX_LONG_EDGE:
|
|
27
|
+
scale = config.IMAGE_MAX_LONG_EDGE / long_edge
|
|
28
|
+
new_w = max(round(w * scale), 1)
|
|
29
|
+
new_h = max(round(h * scale), 1)
|
|
30
|
+
img = img.resize((new_w, new_h), Image.LANCZOS)
|
|
31
|
+
buf = io.BytesIO() # inside the with: when the image is already RGB and small enough, img is still the opened file
|
|
32
|
+
img.save(buf, format="JPEG", quality=config.IMAGE_JPEG_QUALITY, optimize=True)
|
|
33
|
+
return buf.getvalue()
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""
|
|
2
|
+
imagent/image_processing/problems.py — Tell what is wrong with an image that cannot be opened, from the error Pillow raised.
|
|
3
|
+
|
|
4
|
+
A damaged file, a format without a decoder, a file that is still being copied and an image too big for the memory
|
|
5
|
+
at hand each need a different answer, and none of them gets better by trying the same thing again.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
|
|
12
|
+
from PIL import Image, UnidentifiedImageError
|
|
13
|
+
|
|
14
|
+
from imagent.pipeline.failure import IndexingFailure, attempt_record
|
|
15
|
+
|
|
16
|
+
UNREADABLE = "unreadable" # damaged or incomplete: it is queued again when the file changes
|
|
17
|
+
UNSUPPORTED = "unsupported" # no decoder for its format on this computer
|
|
18
|
+
TOO_LARGE = "too_large" # more pixels than the memory free right now can hold
|
|
19
|
+
NOT_DOWNLOADED = "not_downloaded" # kept in cloud storage and not on this computer: reading it would download it
|
|
20
|
+
NO_PERMISSION = "no_permission" # the operating system does not let Imagent read the file: tried again on every scan, as fixing it does not change the file
|
|
21
|
+
OCR_FAILED = "ocr_failed" # the text in the image could not be read, by any of the ways tried
|
|
22
|
+
BUSY = "busy" # changed since it was scanned, so perhaps still being written: tried again later, nothing is held against the file (see commands/scan.py)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ImageProblem(IndexingFailure):
|
|
26
|
+
"""An image that cannot be indexed because of the image itself."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def problem(kind: str, error_id: str, step: str = "opened the image", detail: str = "", params: dict | None = None,
|
|
30
|
+
**flags) -> ImageProblem:
|
|
31
|
+
"""``error_id`` (with ``params``) is what the user is told (the reason and what can be done); ``detail`` is the technical side, kept in the record."""
|
|
32
|
+
failure = ImageProblem(kind, error_id, params=params, **flags)
|
|
33
|
+
failure.attempts = [attempt_record(step, kind, detail or str(failure))]
|
|
34
|
+
return failure
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def explain(exc: BaseException, path: str) -> ImageProblem | None:
|
|
38
|
+
"""The problem with the image that ``exc`` (raised while opening or reading it) stands for, or None if it is another kind of error.
|
|
39
|
+
|
|
40
|
+
Pillow's own errors (an unknown or broken file, a truncated one) carry no error number; a locked file, a bad sector
|
|
41
|
+
or a dropped drive do, and are left to the caller, who tells them from a drive that has gone.
|
|
42
|
+
"""
|
|
43
|
+
if isinstance(exc, MemoryError):
|
|
44
|
+
return problem(TOO_LARGE, "no_memory_to_open",
|
|
45
|
+
detail=f"{type(exc).__name__}: {exc}", park=False)
|
|
46
|
+
if not (isinstance(exc, (UnidentifiedImageError, SyntaxError)) or (isinstance(exc, OSError) and exc.errno is None)):
|
|
47
|
+
return None
|
|
48
|
+
suffix = os.path.splitext(path)[1].lower()
|
|
49
|
+
if isinstance(exc, UnidentifiedImageError) and suffix not in Image.registered_extensions():
|
|
50
|
+
return problem(UNSUPPORTED, "unsupported_format", params={"suffix": suffix},
|
|
51
|
+
detail=f"no decoder is installed for {suffix} files", retry_when="on_request")
|
|
52
|
+
return problem(UNREADABLE, "damaged_picture",
|
|
53
|
+
detail=f"{type(exc).__name__}: {exc}", retry_when="file_changed")
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
"""
|
|
2
|
+
imagent/image_processing/sample_pictures.py — The pictures setup checks this computer with.
|
|
3
|
+
|
|
4
|
+
Real photos of many kinds and sizes come as one zip (with a manifest of where each came from and its licence). It is not part of
|
|
5
|
+
the installed package: ``download`` fetches it from the project's GitHub release and checks it against the SHA-256 pinned in
|
|
6
|
+
config.py. What no zip should hold is made here instead: pictures far larger than anyone would commit, and files that are
|
|
7
|
+
damaged or odd in their way of storing colour. How many are made, and how big, follows the memory and disk this computer has.
|
|
8
|
+
|
|
9
|
+
``check_pictures`` then runs the steps of indexing that need no model over all of them and says how each one went.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import hashlib
|
|
15
|
+
import io
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import shutil
|
|
19
|
+
import tempfile
|
|
20
|
+
import urllib.request
|
|
21
|
+
import zipfile
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Callable
|
|
24
|
+
|
|
25
|
+
import numpy as np
|
|
26
|
+
from PIL import Image
|
|
27
|
+
|
|
28
|
+
from imagent import config
|
|
29
|
+
from imagent.image_processing.memory import available_memory, check_image_size, peak_bytes_per_pixel
|
|
30
|
+
from imagent.image_processing.preprocess import preprocess_image
|
|
31
|
+
from imagent.image_processing.problems import BUSY, TOO_LARGE, UNREADABLE, UNSUPPORTED, ImageProblem, explain
|
|
32
|
+
|
|
33
|
+
TARGET_BYTES = 120_000_000 # the size of the largest picture made: the range the pictures cover runs from small up to this
|
|
34
|
+
PROBE_PIXELS = 4_000_000 # a picture this size is made first, to learn how many bytes a pixel of such a picture takes
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def download(target: Path) -> None:
|
|
38
|
+
"""Download the zip of test pictures into ``target``. Raises ValueError, and leaves no file, when what arrives is not the pinned one."""
|
|
39
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
40
|
+
digest = hashlib.sha256()
|
|
41
|
+
request = urllib.request.Request(config.TEST_PICTURES_URL, headers={"User-Agent": "imagent"})
|
|
42
|
+
try:
|
|
43
|
+
with urllib.request.urlopen(request, timeout=config.TEST_PICTURES_TIMEOUT) as response, open(target, "wb") as out:
|
|
44
|
+
while chunk := response.read(1 << 20):
|
|
45
|
+
out.write(chunk)
|
|
46
|
+
digest.update(chunk)
|
|
47
|
+
if digest.hexdigest() != config.TEST_PICTURES_SHA256:
|
|
48
|
+
raise ValueError("the downloaded test pictures are not the file Imagent was made for (its checksum is different)")
|
|
49
|
+
except BaseException:
|
|
50
|
+
target.unlink(missing_ok=True)
|
|
51
|
+
raise
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _already_unpacked(folder: Path) -> int | None:
|
|
55
|
+
"""How many pictures ``folder`` holds when it already has every one of the manifest's, whole; None when something is missing."""
|
|
56
|
+
try:
|
|
57
|
+
manifest = json.loads((folder / "manifest.json").read_text(encoding="utf-8"))
|
|
58
|
+
if all((folder / entry["file"]).stat().st_size == entry["bytes"] for entry in manifest):
|
|
59
|
+
return len(manifest)
|
|
60
|
+
except (OSError, ValueError, KeyError, TypeError):
|
|
61
|
+
pass
|
|
62
|
+
return None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def unpack(folder: Path, archive: Path | None = None) -> int:
|
|
66
|
+
"""Extract the zip into ``folder``, leaving files already there as they are. Returns how many pictures it holds.
|
|
67
|
+
|
|
68
|
+
Without ``archive`` the zip is downloaded first, unless ``folder`` already holds every picture."""
|
|
69
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
70
|
+
if archive is None:
|
|
71
|
+
count = _already_unpacked(folder)
|
|
72
|
+
if count is not None:
|
|
73
|
+
return count
|
|
74
|
+
with tempfile.TemporaryDirectory(dir=folder.parent) as scratch:
|
|
75
|
+
fetched = Path(scratch) / "images.zip"
|
|
76
|
+
download(fetched)
|
|
77
|
+
return unpack(folder, fetched)
|
|
78
|
+
with zipfile.ZipFile(archive) as zipped:
|
|
79
|
+
names = [name for name in zipped.namelist() if name == os.path.basename(name)] # a flat folder: nothing can land elsewhere
|
|
80
|
+
for name in names:
|
|
81
|
+
target = folder / name
|
|
82
|
+
if not target.exists() or target.stat().st_size != zipped.getinfo(name).file_size:
|
|
83
|
+
with zipped.open(name) as source, open(target, "wb") as handle:
|
|
84
|
+
shutil.copyfileobj(source, handle)
|
|
85
|
+
return sum(1 for name in names if name != "manifest.json")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _noise_jpeg(pixels: int, quality: int = 92) -> bytes:
|
|
89
|
+
"""A JPEG of about ``pixels`` pixels that is hard to compress (smooth noise), so its size follows its pixel count."""
|
|
90
|
+
side = max(int(pixels ** 0.5), 8)
|
|
91
|
+
rng = np.random.default_rng(pixels)
|
|
92
|
+
small = rng.integers(0, 256, (side // 2, side // 2, 3), dtype=np.uint8)
|
|
93
|
+
picture = Image.fromarray(small).resize((side, side), Image.BICUBIC)
|
|
94
|
+
buffer = io.BytesIO()
|
|
95
|
+
picture.save(buffer, format="JPEG", quality=quality)
|
|
96
|
+
return buffer.getvalue()
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _fits(pixels: int, folder: Path) -> str | None:
|
|
100
|
+
"""None if a picture of this many pixels can be made here, else why not (memory to build it, disk to keep it)."""
|
|
101
|
+
available = available_memory()
|
|
102
|
+
if available is not None and pixels * 8 > available * config.IMAGE_MEMORY_SHARE:
|
|
103
|
+
return "not enough free memory to make it"
|
|
104
|
+
if shutil.disk_usage(folder).free < pixels * 4 + TARGET_BYTES:
|
|
105
|
+
return "not enough free disk space to keep it"
|
|
106
|
+
return None
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def make_extremes(folder: Path, target_bytes: int = TARGET_BYTES, say: Callable[[str], None] = lambda m: None) -> dict:
|
|
110
|
+
"""Make the pictures no zip should hold. Returns {file name: what reading it should come to} for the ones made.
|
|
111
|
+
|
|
112
|
+
The huge photographs are an eighth, half and all of ``target_bytes``; any this computer has no room for is left out, and said so."""
|
|
113
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
114
|
+
made: dict[str, str] = {}
|
|
115
|
+
|
|
116
|
+
probe = len(_noise_jpeg(PROBE_PIXELS))
|
|
117
|
+
for share, label in ((8, "large"), (2, "very-large"), (1, "huge")):
|
|
118
|
+
pixels = int(target_bytes / share / probe * PROBE_PIXELS)
|
|
119
|
+
reason = _fits(pixels, folder)
|
|
120
|
+
if reason:
|
|
121
|
+
say(f"Skipped the {label} photograph ({pixels / 1e6:.0f} megapixels): {reason}.")
|
|
122
|
+
continue
|
|
123
|
+
name = f"extreme-{label}.jpg"
|
|
124
|
+
(folder / name).write_bytes(_noise_jpeg(pixels))
|
|
125
|
+
made[name] = "read" # read or too large for the free memory, but never an unexpected error
|
|
126
|
+
|
|
127
|
+
# A small file that expands to twice the pixels the memory check allows, kept as one bit a pixel so that making it is cheap.
|
|
128
|
+
available = available_memory()
|
|
129
|
+
if available:
|
|
130
|
+
side = int((2 * available * config.IMAGE_MEMORY_SHARE / peak_bytes_per_pixel("1")) ** 0.5)
|
|
131
|
+
if _fits(side * side // 8, folder) is None:
|
|
132
|
+
Image.new("1", (side, side)).save(folder / "extreme-expands-to-many-pixels.png")
|
|
133
|
+
made["extreme-expands-to-many-pixels.png"] = "too large"
|
|
134
|
+
|
|
135
|
+
good = io.BytesIO()
|
|
136
|
+
Image.fromarray(np.random.default_rng(1).integers(0, 256, (600, 800, 3), dtype=np.uint8)).save(good, format="JPEG")
|
|
137
|
+
jpeg = good.getvalue()
|
|
138
|
+
png = io.BytesIO()
|
|
139
|
+
Image.fromarray(np.random.default_rng(2).integers(0, 256, (300, 400, 3), dtype=np.uint8)).save(png, format="PNG")
|
|
140
|
+
whole_png = png.getvalue()
|
|
141
|
+
# What damage looks like in practice: a copy that stopped half way, an empty file, a file that is not a picture at all,
|
|
142
|
+
# a header with nothing after it, and a JPEG start followed by noise.
|
|
143
|
+
damaged = {
|
|
144
|
+
"damaged-cut-off.jpg": jpeg[: len(jpeg) * 6 // 10],
|
|
145
|
+
"damaged-empty.jpg": b"",
|
|
146
|
+
"damaged-not-a-picture.png": b"This is text, not a picture.\n" * 40,
|
|
147
|
+
"damaged-cut-off.png": whole_png[: len(whole_png) // 2],
|
|
148
|
+
"damaged-header-only.png": whole_png[:8],
|
|
149
|
+
"damaged-noise-after-jpeg-start.jpg": b"\xff\xd8\xff\xe0" + np.random.default_rng(3).bytes(4000),
|
|
150
|
+
}
|
|
151
|
+
for name, content in damaged.items():
|
|
152
|
+
(folder / name).write_bytes(content)
|
|
153
|
+
made[name] = "damaged"
|
|
154
|
+
|
|
155
|
+
animated = [Image.new("RGB", (120, 90), colour) for colour in ((255, 0, 0), (0, 255, 0), (0, 0, 255))]
|
|
156
|
+
sideways = Image.Exif()
|
|
157
|
+
sideways[0x0112] = 6 # stored sideways: shown turned a quarter
|
|
158
|
+
palette = Image.new("P", (200, 150))
|
|
159
|
+
palette.putpalette([0, 0, 0, 255, 128, 0] + [0] * 762)
|
|
160
|
+
palette.paste(1, (50, 40, 150, 110))
|
|
161
|
+
odd = {
|
|
162
|
+
"odd-transparent.png": Image.new("RGBA", (400, 300), (0, 0, 0, 0)),
|
|
163
|
+
"odd-sixteen-bit.png": Image.fromarray((np.arange(300 * 400, dtype=np.uint32).reshape(300, 400) % 65536).astype(np.uint16)),
|
|
164
|
+
"odd-cmyk.jpg": Image.new("CMYK", (400, 300), (10, 80, 200, 20)),
|
|
165
|
+
"odd-panorama.jpg": Image.new("RGB", (12000, 300), (90, 140, 200)),
|
|
166
|
+
"odd-tall-and-thin.jpg": Image.new("RGB", (40, 9000), (200, 140, 90)),
|
|
167
|
+
"odd-one-pixel.png": Image.new("RGB", (1, 1), (255, 0, 0)),
|
|
168
|
+
"odd-black-and-white.png": Image.new("1", (300, 200), 1),
|
|
169
|
+
"odd-grey-with-transparency.png": Image.new("LA", (300, 200), (128, 200)),
|
|
170
|
+
"odd-palette.png": palette,
|
|
171
|
+
}
|
|
172
|
+
for name, picture in odd.items():
|
|
173
|
+
picture.save(folder / name)
|
|
174
|
+
made[name] = "read"
|
|
175
|
+
animated[0].save(folder / "odd-animated.gif", save_all=True, append_images=animated[1:], duration=100, loop=0)
|
|
176
|
+
Image.new("RGB", (600, 300), (30, 90, 160)).save(folder / "odd-stored-sideways.jpg", exif=sideways)
|
|
177
|
+
(folder / "odd-capital-extension.JPG").write_bytes(jpeg)
|
|
178
|
+
(folder / "odd-a-jpeg-named-png.png").write_bytes(jpeg) # Pillow goes by what is inside, not by the name
|
|
179
|
+
(folder / "odd name (with spaces, an accent é and # % &).jpg").write_bytes(jpeg) # what no file name should be able to break
|
|
180
|
+
made.update({name: "read" for name in ("odd-animated.gif", "odd-stored-sideways.jpg", "odd-capital-extension.JPG",
|
|
181
|
+
"odd-a-jpeg-named-png.png", "odd name (with spaces, an accent é and # % &).jpg")})
|
|
182
|
+
return made
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def check_pictures(folder: Path, expected: dict | None = None, say: Callable[[str], None] = lambda m: None) -> dict:
|
|
186
|
+
"""Run the steps of indexing that need no model over every picture in ``folder``. Returns the number of pictures per outcome.
|
|
187
|
+
|
|
188
|
+
The outcomes: ``read``, ``too large`` for the
|
|
189
|
+
memory this computer has free, ``damaged``, ``unsupported``, ``busy``, and ``unexpected`` for an error that should have been
|
|
190
|
+
one of those. Where ``expected`` says what a picture should come to, any other outcome is said."""
|
|
191
|
+
outcomes: dict[str, int] = {}
|
|
192
|
+
for path in sorted(p for p in folder.iterdir() if p.is_file() and p.name != "manifest.json"):
|
|
193
|
+
try:
|
|
194
|
+
check_image_size(str(path))
|
|
195
|
+
try:
|
|
196
|
+
preprocess_image(str(path))
|
|
197
|
+
except Exception as exc: # as vlm.analyzer.analyse_image does: an error of the picture becomes its explanation
|
|
198
|
+
raise (explain(exc, str(path)) or exc) from exc
|
|
199
|
+
outcome = "read"
|
|
200
|
+
except ImageProblem as problem:
|
|
201
|
+
outcome = {TOO_LARGE: "too large", UNREADABLE: "damaged", UNSUPPORTED: "unsupported", BUSY: "busy"}.get(problem.kind, "unexpected")
|
|
202
|
+
except Exception as exc: # an error that no step of indexing turns into a plain explanation
|
|
203
|
+
outcome = "unexpected"
|
|
204
|
+
say(f"{path.name}: {type(exc).__name__}: {exc}")
|
|
205
|
+
outcomes[outcome] = outcomes.get(outcome, 0) + 1
|
|
206
|
+
wanted = (expected or {}).get(path.name)
|
|
207
|
+
if wanted and outcome not in _accepted(wanted):
|
|
208
|
+
say(f"{path.name} came to '{outcome}', not '{wanted}'.")
|
|
209
|
+
return outcomes
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _accepted(wanted: str) -> tuple:
|
|
213
|
+
"""What a picture meant to be read may come to: read, or too large for the memory this computer has free."""
|
|
214
|
+
return ("read", "too large") if wanted == "read" else (wanted,)
|