doc-preproc 0.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 IT-Engineer-K
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,85 @@
1
+ Metadata-Version: 2.4
2
+ Name: doc-preproc
3
+ Version: 0.1.0
4
+ Summary: Lightweight, non-destructive document image quality diagnosis, adaptive preprocessing, and exact 2D coordinate mapping.
5
+ Author: doc-preproc contributors
6
+ License: MIT
7
+ Keywords: document,preprocessing,deskew,image-quality,affine-transform
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Topic :: Scientific/Engineering :: Image Processing
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Provides-Extra: dev
21
+ Requires-Dist: pytest>=7.0; extra == "dev"
22
+ Dynamic: license-file
23
+
24
+ # doc-preproc
25
+
26
+ Lightweight, zero-dependency, non-destructive document image quality diagnosis, adaptive preprocessing, and exact 2D coordinate mapping for Python (`>=3.10`).
27
+
28
+ ## Design Principles
29
+
30
+ - **Pure Python core, zero required runtime dependencies**: Operates on a lightweight `GrayImage` 2D grid (`0..255`) with seamless duck-typed support for 2D grayscale or 3D RGB `numpy` arrays when passed in.
31
+ - **Non-destructive by default**: Never mutates input images and never applies destructive hard binarization.
32
+ - **No-op fast path**: Clean images with negligible skew, healthy contrast, and even lighting incur zero pixel transforms (`is_noop=True`, identity `AffineTransform2D`).
33
+ - **Exact reversible geometry**: Every geometric transform returns an exact 2x3 `AffineTransform2D` with `forward(x, y)` and `inverse(x', y')` mapping between original and preprocessed coordinates.
34
+ - **Strict safety boundary**: Performs deterministic signal processing only—no OCR inference, no generative super-resolution/image synthesis, and no network calls.
35
+
36
+ ## Installation
37
+
38
+ Install in editable mode from a local checkout:
39
+
40
+ ```bash
41
+ pip install -e .
42
+ ```
43
+
44
+ ## Quick Start
45
+
46
+ ```python
47
+ from doc_preproc import GrayImage, compute_crop_plan, diagnose, preprocess
48
+
49
+ # Construct from nested lists (or pass a 2D/3D numpy array directly)
50
+ image = GrayImage.filled(120, 80, value=250.0)
51
+
52
+ # 1. Inspect image quality
53
+ report = diagnose(image)
54
+ print(report.skew_angle_deg, report.blur_score, report.contrast_score)
55
+
56
+ # 2. Run adaptive, non-destructive preprocessing
57
+ result = preprocess(image, profile="receipt")
58
+ print(result.is_noop, result.applied_transforms)
59
+
60
+ # Map a point from preprocessed coordinates back to original image coordinates
61
+ orig_x, orig_y = result.transform.inverse(50.0, 30.0)
62
+
63
+ # 3. Compute an optimal local re-read crop plan with exact coordinate transform
64
+ plan = compute_crop_plan(
65
+ bbox=(10.0, 20.0, 90.0, 45.0),
66
+ image_size=(image.width, image.height),
67
+ estimated_char_height_px=14.0,
68
+ target_char_height_px=28.0,
69
+ )
70
+ print(plan.scale_factor, plan.output_size)
71
+ ```
72
+
73
+ ## Public API
74
+
75
+ - `GrayImage`: Row-major 2D grayscale container with `from_nested`, `from_any`, `to_nested`, `copy`, and bilinear sampling.
76
+ - `AffineTransform2D`: Composable 2x3 affine matrix (`identity`, `translation`, `scale`, `rotation`, `forward`, `inverse`, `invert`, `compose`).
77
+ - `diagnose(image, config=None) -> QualityReport`: Computes `skew_angle_deg`, `blur_score`, `contrast_score`, `illumination_unevenness`, `estimated_char_height_px`, `aspect_ratio`, and advisory `unreadable_flag` / `unreadable_reasons`.
78
+ - `preprocess(image, profile="receipt"|"invoice"|"crop", config=None) -> PreprocessResult`: Runs diagnosis and applies only needed transforms (`deskew`, `illumination_normalization`, `contrast_normalization`), returning `(image, report, transform, applied_transforms, is_noop)`.
79
+ - `compute_crop_plan(...) -> CropPlan` & `apply_crop_plan(image, plan) -> GrayImage`: Computes padded crop bounds, optimal scale factor, and exact coordinate transform for local re-read regions.
80
+
81
+ ## Running Tests
82
+
83
+ ```bash
84
+ PYTHONPATH=src python -m unittest discover -s tests -v
85
+ ```
@@ -0,0 +1,62 @@
1
+ # doc-preproc
2
+
3
+ Lightweight, zero-dependency, non-destructive document image quality diagnosis, adaptive preprocessing, and exact 2D coordinate mapping for Python (`>=3.10`).
4
+
5
+ ## Design Principles
6
+
7
+ - **Pure Python core, zero required runtime dependencies**: Operates on a lightweight `GrayImage` 2D grid (`0..255`) with seamless duck-typed support for 2D grayscale or 3D RGB `numpy` arrays when passed in.
8
+ - **Non-destructive by default**: Never mutates input images and never applies destructive hard binarization.
9
+ - **No-op fast path**: Clean images with negligible skew, healthy contrast, and even lighting incur zero pixel transforms (`is_noop=True`, identity `AffineTransform2D`).
10
+ - **Exact reversible geometry**: Every geometric transform returns an exact 2x3 `AffineTransform2D` with `forward(x, y)` and `inverse(x', y')` mapping between original and preprocessed coordinates.
11
+ - **Strict safety boundary**: Performs deterministic signal processing only—no OCR inference, no generative super-resolution/image synthesis, and no network calls.
12
+
13
+ ## Installation
14
+
15
+ Install in editable mode from a local checkout:
16
+
17
+ ```bash
18
+ pip install -e .
19
+ ```
20
+
21
+ ## Quick Start
22
+
23
+ ```python
24
+ from doc_preproc import GrayImage, compute_crop_plan, diagnose, preprocess
25
+
26
+ # Construct from nested lists (or pass a 2D/3D numpy array directly)
27
+ image = GrayImage.filled(120, 80, value=250.0)
28
+
29
+ # 1. Inspect image quality
30
+ report = diagnose(image)
31
+ print(report.skew_angle_deg, report.blur_score, report.contrast_score)
32
+
33
+ # 2. Run adaptive, non-destructive preprocessing
34
+ result = preprocess(image, profile="receipt")
35
+ print(result.is_noop, result.applied_transforms)
36
+
37
+ # Map a point from preprocessed coordinates back to original image coordinates
38
+ orig_x, orig_y = result.transform.inverse(50.0, 30.0)
39
+
40
+ # 3. Compute an optimal local re-read crop plan with exact coordinate transform
41
+ plan = compute_crop_plan(
42
+ bbox=(10.0, 20.0, 90.0, 45.0),
43
+ image_size=(image.width, image.height),
44
+ estimated_char_height_px=14.0,
45
+ target_char_height_px=28.0,
46
+ )
47
+ print(plan.scale_factor, plan.output_size)
48
+ ```
49
+
50
+ ## Public API
51
+
52
+ - `GrayImage`: Row-major 2D grayscale container with `from_nested`, `from_any`, `to_nested`, `copy`, and bilinear sampling.
53
+ - `AffineTransform2D`: Composable 2x3 affine matrix (`identity`, `translation`, `scale`, `rotation`, `forward`, `inverse`, `invert`, `compose`).
54
+ - `diagnose(image, config=None) -> QualityReport`: Computes `skew_angle_deg`, `blur_score`, `contrast_score`, `illumination_unevenness`, `estimated_char_height_px`, `aspect_ratio`, and advisory `unreadable_flag` / `unreadable_reasons`.
55
+ - `preprocess(image, profile="receipt"|"invoice"|"crop", config=None) -> PreprocessResult`: Runs diagnosis and applies only needed transforms (`deskew`, `illumination_normalization`, `contrast_normalization`), returning `(image, report, transform, applied_transforms, is_noop)`.
56
+ - `compute_crop_plan(...) -> CropPlan` & `apply_crop_plan(image, plan) -> GrayImage`: Computes padded crop bounds, optimal scale factor, and exact coordinate transform for local re-read regions.
57
+
58
+ ## Running Tests
59
+
60
+ ```bash
61
+ PYTHONPATH=src python -m unittest discover -s tests -v
62
+ ```
@@ -0,0 +1,39 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "doc-preproc"
7
+ version = "0.1.0"
8
+ description = "Lightweight, non-destructive document image quality diagnosis, adaptive preprocessing, and exact 2D coordinate mapping."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "MIT" }
12
+ authors = [
13
+ { name = "doc-preproc contributors" }
14
+ ]
15
+ keywords = ["document", "preprocessing", "deskew", "image-quality", "affine-transform"]
16
+ classifiers = [
17
+ "Development Status :: 3 - Alpha",
18
+ "Intended Audience :: Developers",
19
+ "License :: OSI Approved :: MIT License",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Topic :: Scientific/Engineering :: Image Processing",
25
+ "Typing :: Typed",
26
+ ]
27
+ dependencies = []
28
+
29
+ [project.optional-dependencies]
30
+ dev = ["pytest>=7.0"]
31
+
32
+ [tool.setuptools]
33
+ package-dir = { "" = "src" }
34
+
35
+ [tool.setuptools.packages.find]
36
+ where = ["src"]
37
+
38
+ [tool.setuptools.package-data]
39
+ doc_preproc = ["py.typed"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,51 @@
1
+ """doc-preproc: lightweight, non-destructive document image preprocessing."""
2
+
3
+ from .diagnose import (
4
+ compute_blur_score,
5
+ compute_contrast_score,
6
+ compute_illumination_unevenness,
7
+ diagnose,
8
+ estimate_char_height_px,
9
+ estimate_skew_angle,
10
+ )
11
+ from .geometry import AffineTransform2D
12
+ from .models import (
13
+ CropPlan,
14
+ GrayImage,
15
+ PreprocessConfig,
16
+ PreprocessResult,
17
+ ProfileName,
18
+ QualityReport,
19
+ )
20
+ from .preprocess import (
21
+ apply_crop_plan,
22
+ compute_crop_plan,
23
+ deskew_image,
24
+ normalize_illumination,
25
+ preprocess,
26
+ stretch_contrast,
27
+ )
28
+
29
+ __all__ = [
30
+ "AffineTransform2D",
31
+ "CropPlan",
32
+ "GrayImage",
33
+ "PreprocessConfig",
34
+ "PreprocessResult",
35
+ "ProfileName",
36
+ "QualityReport",
37
+ "apply_crop_plan",
38
+ "compute_blur_score",
39
+ "compute_contrast_score",
40
+ "compute_crop_plan",
41
+ "compute_illumination_unevenness",
42
+ "deskew_image",
43
+ "diagnose",
44
+ "estimate_char_height_px",
45
+ "estimate_skew_angle",
46
+ "normalize_illumination",
47
+ "preprocess",
48
+ "stretch_contrast",
49
+ ]
50
+
51
+ __version__ = "0.1.0"
@@ -0,0 +1,318 @@
1
+ """Document image quality diagnosis metrics."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from typing import Any, Sequence
7
+
8
+ from .models import GrayImage, PreprocessConfig, QualityReport
9
+
10
+
11
+ def _percentile(sorted_vals: Sequence[float], q: float) -> float:
12
+ """Compute linear-interpolated percentile from a pre-sorted sequence."""
13
+ n = len(sorted_vals)
14
+ if n == 0:
15
+ return 0.0
16
+ if n == 1:
17
+ return sorted_vals[0]
18
+ pos = q * (n - 1)
19
+ lo = int(math.floor(pos))
20
+ hi = min(lo + 1, n - 1)
21
+ frac = pos - lo
22
+ return sorted_vals[lo] * (1.0 - frac) + sorted_vals[hi] * frac
23
+
24
+
25
+ def _image_stats(gray: GrayImage) -> tuple[float, float, float, float, float, float]:
26
+ """Return (mean, std, min_val, max_val, p5, p95) for pixel intensities."""
27
+ flat: list[float] = []
28
+ for row in gray.pixels:
29
+ flat.extend(row)
30
+ n = len(flat)
31
+ mean = sum(flat) / n
32
+ var = sum((v - mean) * (v - mean) for v in flat) / n
33
+ std = math.sqrt(var)
34
+ flat.sort()
35
+ return (
36
+ mean,
37
+ std,
38
+ flat[0],
39
+ flat[-1],
40
+ _percentile(flat, 0.05),
41
+ _percentile(flat, 0.95),
42
+ )
43
+
44
+
45
+ def compute_blur_score(image: GrayImage | Any) -> float:
46
+ """Estimate sharpness via variance of the discrete 2D Laplacian.
47
+
48
+ Higher values indicate sharper edges; values near zero indicate
49
+ severe blur or flat/featureless content.
50
+ """
51
+ gray = GrayImage.from_any(image)
52
+ w, h = gray.width, gray.height
53
+ if w < 3 or h < 3:
54
+ return 0.0
55
+
56
+ pixels = gray.pixels
57
+ count = (w - 2) * (h - 2)
58
+ sum_l = 0.0
59
+ sum_l2 = 0.0
60
+ for y in range(1, h - 1):
61
+ row_prev = pixels[y - 1]
62
+ row_curr = pixels[y]
63
+ row_next = pixels[y + 1]
64
+ for x in range(1, w - 1):
65
+ lap = (
66
+ row_prev[x]
67
+ + row_next[x]
68
+ + row_curr[x - 1]
69
+ + row_curr[x + 1]
70
+ - 4.0 * row_curr[x]
71
+ )
72
+ sum_l += lap
73
+ sum_l2 += lap * lap
74
+
75
+ mean_l = sum_l / count
76
+ var_l = (sum_l2 / count) - (mean_l * mean_l)
77
+ return max(0.0, var_l)
78
+
79
+
80
+ def compute_contrast_score(image: GrayImage | Any) -> float:
81
+ """Compute contrast as the standard deviation of grayscale intensities."""
82
+ gray = GrayImage.from_any(image)
83
+ _, std, _, _, _, _ = _image_stats(gray)
84
+ return std
85
+
86
+
87
+ def compute_illumination_unevenness(
88
+ image: GrayImage | Any,
89
+ grid_rows: int = 4,
90
+ grid_cols: int = 4,
91
+ ) -> float:
92
+ """Measure spatial illumination gradient across a grid of blocks.
93
+
94
+ Uses the 85th percentile inside each block as a robust local background
95
+ estimate so that text density differences do not masquerade as shadows.
96
+ Returns ``max(block_bg) - min(block_bg)``.
97
+ """
98
+ gray = GrayImage.from_any(image)
99
+ w, h = gray.width, gray.height
100
+ rows = min(grid_rows, h)
101
+ cols = min(grid_cols, w)
102
+ if rows <= 1 and cols <= 1:
103
+ return 0.0
104
+
105
+ block_bgs: list[float] = []
106
+ pixels = gray.pixels
107
+ for r in range(rows):
108
+ y0 = (r * h) // rows
109
+ y1 = ((r + 1) * h) // rows
110
+ if y1 <= y0:
111
+ continue
112
+ for c in range(cols):
113
+ x0 = (c * w) // cols
114
+ x1 = ((c + 1) * w) // cols
115
+ if x1 <= x0:
116
+ continue
117
+ vals: list[float] = []
118
+ for y in range(y0, y1):
119
+ vals.extend(pixels[y][x0:x1])
120
+ vals.sort()
121
+ block_bgs.append(_percentile(vals, 0.85))
122
+
123
+ if len(block_bgs) < 2:
124
+ return 0.0
125
+ return max(block_bgs) - min(block_bgs)
126
+
127
+
128
+ def estimate_skew_angle(
129
+ image: GrayImage | Any,
130
+ max_angle_deg: float = 10.0,
131
+ step_deg: float = 0.5,
132
+ ) -> float:
133
+ """Estimate document micro-skew angle in degrees via projection-profile variance.
134
+
135
+ Positive angle means horizontal text lines slope downward to the right
136
+ (clockwise tilt in top-left image coordinates). Deskewing rotates by
137
+ ``-skew_angle_deg``.
138
+ """
139
+ gray = GrayImage.from_any(image)
140
+ w, h = gray.width, gray.height
141
+ if w < 8 or h < 8:
142
+ return 0.0
143
+
144
+ mean, std, _, _, _, _ = _image_stats(gray)
145
+ if std < 1.0:
146
+ return 0.0
147
+
148
+ # Uniform downsampling for speed on large images while preserving aspect ratio.
149
+ stride = max(1, max(w, h) // 160)
150
+ cx = (w - 1) / 2.0
151
+ cy = (h - 1) / 2.0
152
+
153
+ thresh = mean - 0.35 * std
154
+ fg_points: list[tuple[float, float, float]] = []
155
+ pixels = gray.pixels
156
+ for y in range(0, h, stride):
157
+ row = pixels[y]
158
+ dy = (y - cy) / stride
159
+ for x in range(0, w, stride):
160
+ p = row[x]
161
+ if p < thresh:
162
+ fg_points.append(((x - cx) / stride, dy, thresh - p))
163
+
164
+ if len(fg_points) < 10:
165
+ fg_points = []
166
+ for y in range(0, h, stride):
167
+ row = pixels[y]
168
+ dy = (y - cy) / stride
169
+ for x in range(0, w, stride):
170
+ p = row[x]
171
+ if p < mean:
172
+ fg_points.append(((x - cx) / stride, dy, mean - p))
173
+
174
+ if len(fg_points) < 10:
175
+ return 0.0
176
+
177
+ scaled_w = w / stride
178
+ scaled_h = h / stride
179
+ half_diag = int(math.ceil(math.hypot(scaled_w, scaled_h) / 2.0)) + 2
180
+ num_bins = 2 * half_diag + 4
181
+
182
+ def _projection_energy(angle_deg: float) -> float:
183
+ rad = math.radians(angle_deg)
184
+ sin_a = math.sin(rad)
185
+ cos_a = math.cos(rad)
186
+ bins = [0.0] * num_bins
187
+ offset = float(half_diag + 1)
188
+ for dx, dy, weight in fg_points:
189
+ # Project onto rotated y-axis for deskew angle (-angle_deg).
190
+ y_rot = -dx * sin_a + dy * cos_a + offset
191
+ idx = int(math.floor(y_rot))
192
+ if 0 <= idx < num_bins - 1:
193
+ frac = y_rot - idx
194
+ bins[idx] += weight * (1.0 - frac)
195
+ bins[idx + 1] += weight * frac
196
+ return sum(b * b for b in bins)
197
+
198
+ # Coarse search
199
+ step = max(0.1, float(step_deg))
200
+ num_steps = int(round((2.0 * max_angle_deg) / step))
201
+ best_angle = 0.0
202
+ best_energy = _projection_energy(0.0)
203
+ zero_energy = best_energy
204
+
205
+ for i in range(num_steps + 1):
206
+ angle = -max_angle_deg + i * step
207
+ energy = _projection_energy(angle)
208
+ if energy > best_energy:
209
+ best_energy = energy
210
+ best_angle = angle
211
+
212
+ # Fine refinement around best coarse angle
213
+ fine_step = min(0.1, step / 4.0)
214
+ fine_start = max(-max_angle_deg, best_angle - step)
215
+ fine_end = min(max_angle_deg, best_angle + step)
216
+ fine_steps = int(round((fine_end - fine_start) / fine_step))
217
+ for i in range(fine_steps + 1):
218
+ angle = fine_start + i * fine_step
219
+ energy = _projection_energy(angle)
220
+ if energy > best_energy:
221
+ best_energy = energy
222
+ best_angle = angle
223
+
224
+ # Prefer exact 0.0 if improvement over 0 deg is negligible.
225
+ if best_energy <= zero_energy * 1.001:
226
+ return 0.0
227
+
228
+ return round(best_angle, 3)
229
+
230
+
231
+ def estimate_char_height_px(image: GrayImage | Any) -> float:
232
+ """Estimate typical character/line stroke height in pixels from horizontal runs."""
233
+ gray = GrayImage.from_any(image)
234
+ w, h = gray.width, gray.height
235
+ if w < 4 or h < 4:
236
+ return 0.0
237
+
238
+ flat: list[float] = []
239
+ for row in gray.pixels:
240
+ flat.extend(row)
241
+ n = len(flat)
242
+ mean = sum(flat) / n
243
+ std = math.sqrt(sum((v - mean) * (v - mean) for v in flat) / n)
244
+ if std < 2.0:
245
+ return 0.0
246
+
247
+ flat.sort()
248
+ bg_est = _percentile(flat, 0.85)
249
+ ink_thresh = bg_est - max(15.0, 0.5 * std)
250
+ min_ink_per_row = max(2, int(0.02 * w))
251
+
252
+ runs: list[int] = []
253
+ current_run = 0
254
+ for row in gray.pixels:
255
+ ink_count = sum(1 for v in row if v < ink_thresh)
256
+ if ink_count >= min_ink_per_row:
257
+ current_run += 1
258
+ elif current_run > 0:
259
+ runs.append(current_run)
260
+ current_run = 0
261
+ if current_run > 0:
262
+ runs.append(current_run)
263
+
264
+ if not runs:
265
+ return 0.0
266
+
267
+ runs.sort()
268
+ mid = len(runs) // 2
269
+ if len(runs) % 2 == 1:
270
+ return float(runs[mid])
271
+ return 0.5 * (runs[mid - 1] + runs[mid])
272
+
273
+
274
+ def diagnose(
275
+ image: GrayImage | Any,
276
+ config: PreprocessConfig | None = None,
277
+ ) -> QualityReport:
278
+ """Run all lightweight quality diagnostics on a document image.
279
+
280
+ Unreadable flags are strictly advisory and never reject an image.
281
+ """
282
+ gray = GrayImage.from_any(image)
283
+ cfg = config if config is not None else PreprocessConfig()
284
+
285
+ mean, std, min_val, max_val, p5, p95 = _image_stats(gray)
286
+ blur_score = compute_blur_score(gray)
287
+ contrast_score = std
288
+ illumination_unevenness = compute_illumination_unevenness(gray)
289
+ skew_angle_deg = estimate_skew_angle(
290
+ gray,
291
+ max_angle_deg=cfg.max_skew_search_deg,
292
+ step_deg=cfg.skew_step_deg,
293
+ )
294
+ estimated_char_height_px = estimate_char_height_px(gray)
295
+ aspect_ratio = gray.height / float(gray.width)
296
+
297
+ reasons: list[str] = []
298
+ if mean < 15.0 and p95 < 30.0:
299
+ reasons.append("crushed_blacks")
300
+ if mean > 245.0 and p5 > 235.0:
301
+ reasons.append("blown_highlights")
302
+ if contrast_score < 2.0 or (max_val - min_val) < cfg.min_dynamic_range:
303
+ reasons.append("flat_image")
304
+ if blur_score < cfg.blur_unreadable_threshold:
305
+ reasons.append("extreme_blur")
306
+
307
+ return QualityReport(
308
+ width=gray.width,
309
+ height=gray.height,
310
+ skew_angle_deg=skew_angle_deg,
311
+ blur_score=blur_score,
312
+ contrast_score=contrast_score,
313
+ illumination_unevenness=illumination_unevenness,
314
+ estimated_char_height_px=estimated_char_height_px,
315
+ aspect_ratio=aspect_ratio,
316
+ unreadable_flag=bool(reasons),
317
+ unreadable_reasons=tuple(reasons),
318
+ )