Files
WeKnora/docreader/tests/test_image_preprocess.py
8d47e6e979 feat(image): add opt-in, bounded preprocessing before OCR (#4381)
* feat(docreader): add PreprocessImage RPC implementing the R22 page pipeline

Straightens and crops a photographed page before OCR: RapidOCR text-line detection, dominant-angle consensus on the 180-degree circle, content quad from outer support lines, perspective correction and 0/180 orientation. Declines (fallback_needed) instead of raising when the input is not a correctable page.

* feat(image): preprocess the page before OCR in the smartocr pipeline

New registered action 'preprocess', scheduled between the OCR decision and OCR itself. Every failure mode is a no-op: only a successful result overwrites r.imageBytes, so OCR falls back to the original photograph without a second code path.

* docs(i18n,licenses): describe the preprocess step and declare new docreader deps

Six locales gain the preprocessing sentence in the smartocr description; RapidOCR, ONNX Runtime, OpenCV and NumPy notices are added (licenses/sources/modules.tsv records Go modules only).

* style(image): gofmt runContext field alignment

* feat(image): add internal observation attributes for preprocess gating

Registers contain.margin and contain.upright as Internal attributes: they steer preprocess scheduling and are persisted like any other observation, but AttrSpec.Internal keeps them out of the gallery's filter surface.

* feat(image): three-state preprocess switch with on-demand attribute injection

PreprocessMode (off/auto/force) decides both whether the describe round asks the geometry attributes and whether the page is straightened:
- off:   no geometry attributes, no preprocessing — the prompt is byte-identical to what it was before this feature
- auto:  asks contain.margin / contain.upright, preprocesses only when they say the page is worth fixing
- force: preprocesses every readable page without asking, prompt untouched

AttrSpec gains Inject (always | on_demand) so an attribute decides for itself whether it is a standing question or asked only when a consumer is switched on, and Internal so the gallery keeps it out of its filter surface.

* feat(image): carry the preprocess mode from the knowledge base to the run

ResolveProcessConfig resolves ImageProcessingConfig.PreprocessMode once, at enqueue time, and the value travels in ImageMultimodalPayload next to ImagePipelineID: a task already in flight must run the mode it was enqueued under, not the mode the knowledge base happens to have later. The run context reads it from the payload and falls back to auto for payloads written before the field existed.

* feat(image): expose the preprocess switch in the settings and upload dialogs

The knowledge base editor, the upload dialog and the reparse dialog all show the switch and start from the knowledge base's own value; a deliberate change is sent as a per-document override, and an untouched dialog sends nothing so a document is not pinned to a setting the KB may later change. Backend gains KnowledgeProcessOverrides.PreprocessMode for that override path.

* refactor(image): let the preprocess switch follow the existing override semantics

The switch now behaves exactly like the pipeline pick next to it: the dialogs show the knowledge base's value, a reparse starts from the document's own stored overrides, and what the dialog shows is what it sends. No new precedence rule is introduced here — how a document's setting and the knowledge base default should interact is a separate question that belongs in its own change.

* fix(image): read a presence attribute as the bool it is stored as

coerceAttrValue stores a presence attribute as a real bool and an extent attribute as a string, so the string accessor added for contain.upright silently read nothing. Auto mode would then treat an unobserved orientation as upright and skip a page that plainly needed straightening. The accessor now returns (upright, observed) so 'the model said no' stays distinguishable from 'the model did not say'.

* feat(image): rework the pipeline panel and rename the geometry attributes

The switch keeps its own namespace: contain.* describes what the picture holds, layout.* describes how the page is laid out. Renames contain.margin/layout.upright accordingly, translates both for all six locales, and groups the panel by business order (pick -> describe -> straighten -> read) with the explanatory text folded into a collapsed block at the foot, so the panel stays short as attributes accumulate.

* refactor(image): lay the pipeline panel out in three sections and fold only the attribute help

The panel now reads as three sections separated by rules: the pipeline pick with its description, then every switch with its own description beside it, then the observation attributes the smart pipeline relies on. Only the third section folds (it is reference material that will grow with the registry); a switch's description stays next to its switch, and the attribute rows are no longer ruled off from each other. The geometry attribute translations move from the imagePipeline namespace to imageAttr, which is where the panel looks them up — that is why they still read as English.

* feat(image): declare pipeline fields in three runs and fold the optional ones

A pipeline now declares its fields in three consecutive runs — standing switches, advanced switches, notes — and the panel renders them as three places: the switches outright, then two folded blocks styled like the chunking panel's advanced options (a real button, so the title opens as well as the arrow). A run a pipeline leaves empty draws nothing at all, title and rule included.

This is what fixes the manual pipeline's panel: its switches and the thinking tunables that belong to them no longer interleave, because the panel stopped guessing a layout from key prefixes and renders the declaration instead. TestFieldDeclarationOrder holds every pipeline to the three runs, and the page-straightening switch is declared by the smart pipeline alone — it is the only one with an observation round to drive it.

* feat(image): fold the pipeline panel's optional runs without rules and move the OCR fallback switch in

Only the rule between the pick and the switches survives: the two folded runs follow the switches directly, so the panel reads as three parts rather than as five lines of rules. A folded run the pipeline does not declare still draws nothing at all.

The OCR policy's unobserved clause is now a field the smart pipeline declares next to the straightening switch, instead of a row the host dialogs drew below the panel — it belongs to the pipeline that observes attributes, and it reads as part of the same switch area. Like the straightening switch its value is a knowledge base setting rather than a param, so the panel binds it there.

* feat(image): fold the attribute dictionary into the panel's notes

The dictionary explains what the pipeline's OCR policy reads, but it comes from the attribute registry rather than from the pipeline, so the panel cannot declare it: the host hands it over through a slot and the panel folds it with the pipeline's own notes. The attribute block keeps the registry-driven rendering it had — adding an attribute still needs no frontend change, and the policy it documents cannot drift from the backend that applies it.

* fix(image): close the pipeline panel tag now that it takes a slot

A component with slot children cannot close itself; the notes slot left the tag self-closing, which vue-tsc accepted and only the production build rejected (Element is missing end tag).

* refactor(image): give parameter keys one owner-derived namespace

A tunable's key is now always <owner>.<name>: an action declares a bare name and types.ActionParam adds its id, so two actions may each offer a "thinking" without either inventing a distinct spelling for it, and a pipeline carries those fields by reference (types.ActionField) instead of listing them by index. The stored keys are unchanged — caption.thinking, ocr.thinking, ocr.on_unobserved — so no stored config or trace needs migrating.

Guards: every field an action declares must be namespaced by its own id; a pipeline may only carry a dotted key an action declared, never invent one; and the per-pipeline lookup (namespaced first, bare key as the documented compatibility path) now has a test of its own.

* docs(image): write down how image pipeline keys are named

The image pipeline names keys in three containers — settings, the per-image
trace, and the stored per-image record — and until now the rules lived only in
the heads of whoever wrote each key. This adds the rules as a design document
under docs/design (the same place the agent HITL model is written down) and
points at it from the symbols a developer actually touches: ActionParam, the
field definition, the pipeline interface and runContext.out.

The document states the one principle the rest follows from — a name is owner
plus name, and the owner is only written down when a container has more than
one writer — then the ownership test (what the parameter decides, not who its
subject is), the three vocabularies, which keys are contracts (consumed by code)
versus diagnostics, and the list of places to change when renaming one.

* refactor(image): name the OCR trace keys after their action, and pin the contract ones

The OCR action's keys now read as <action>.<what>: ocr.result, ocr.chars,
ocr.error_code, ocr.raw_chars, ocr.preview, ocr.prompt, ocr.rejection_reason.
ocr_status and ocr_skipped become one key — ocr.result — whose values carry
the reason (skipped_no_text, skipped_attr_policy, skipped_observation_failed),
which removes the pair that recorded the same fact twice.

The four keys code reads back (result, error_code, error, chars) are now
constants shared by writer and reader, with the reader named in the constant's
comment: they live in two functions, and two literals that must agree is how a
rename comes to be written into the trace and not read out of it.

Tests use the constants too, including the negative assertions — a NotContains
on a stale key name passes forever, which is worse than failing.

* refactor(image): one owner per key — actions own their keys, pipelines own their switches

Trace keys now read as <action>.<what the action produced>: caption.result and
caption.chars, observation.result and observation.caption_*, ocr.result,
preprocess.result/bytes/error. ocr_status and ocr_skipped were one fact written
twice and are now one key whose values carry the reason; observation_failed and
caption_missing were two dimensions of one answer and are now observation.result
(how much was observed) plus observation.caption_result (what became of the
description); attr_policy mixed a setting with a state and is gone, its halves
living in ocr.result and the new config echo; action_skipped recorded a
programming error, and execute now fails the image instead of quietly skipping a
step.

Settings follow the same rule. A switch is named <name>_enabled
(caption_enabled, ocr_enabled, thinking_enabled), an action's tunable is
<pipeline>.<action>.<name> (smartocr.preprocess.mode, smartocr.ocr_on_unobserved),
and the switches move into the actions that read them — so a caption that is off
still records that it was off, which is what an action that never ran could not
do. Two keys nobody could reach are gone: allow_ocr (a ceiling contradicting the
policy that already decides) and capture_caption (an unexposed sub-item switch,
now observation.caption_enabled).

The trace gains config (the settings this run used, under the keys the knowledge
base stores them under) and actions (the sequence that actually ran). Contract
keys — the ones code reads back — became constants shared by writer and reader,
with the reader named in the comment, and the value vocabularies live in code
because a guard test checks the trace against them.

* refactor(image): keep a pipeline's settings in that pipeline's slot

The panel used to write a pipeline's private tunables under their bare key and
to bind two of the fields — the straightening switch and the OCR fallback
clause — to knowledge-base fields instead, because neither is what the panel
would otherwise have called a parameter. So the same idea had two spellings:
the key the trace echoed as configuration was not always the key the run read,
and a value the panel stored could be one the run never looked at.

Now every declared field is a setting of the pipeline that declared it, stored
under that pipeline's slot (`<pipeline>.<key>`, types.SlotKey) and read back the
same way (types.ImagePipelineParam). The panel stops special-casing anything: it
renders the fields the registry publishes and writes each one to its owner's
slot, which is also why switching pipelines now keeps the other pipeline's
answers instead of clearing them.

The knowledge base fields the two settings lived in — preprocess_mode, and the
OCR clause under image_actions — are read as the fallback they already are
(types.ResolvePreprocessMode, service.resolveImageActions), so a base saved
before the move runs exactly as it did. The frontend mirrors both rules
(pipelineParamKey/readPipelineParam) and folds the older values into the slot
when it reads a base, or the panel would draw a field default the next save
would then write over the setting the base was actually using.

A per-task override carries the pick and its parameters as one unit, so the two
slot-resident settings are resolved again from the slot that will run — without
that, a dialog offering those controls would be offering a knob the run ignores.

Also fixes the panel's dangling v-else, left behind when the two special-cased
branches went away: the production build rejects it, and vue-tsc does not.

* test(image): pin the key naming rules, and fix what the gate found

The naming规范 is only worth writing down if breaking it is red, so the rules
that can be checked now are: a setting is never named like a result (the trace
reserves result/status/chars/bytes/preview/error for what an action produced),
an action's result key is `<action>.result` built from the action id rather than
spelled again, every action-level trace key is namespaced with a registered
action, every result value is one of a closed vocabulary, the slot lookup does
not double a pipeline id and prefers the slot over the bare key, and the
preprocess mode resolves slot-first with the older field behind it.

Writing those found three things to fix rather than document around: the
frame-level outcome words were literals in several branches of one long function
with the vocabulary list sitting next to them unread, so the branches now name
the constants and the list is what the tests read; a dead nil check on a run
context that is always non-nil; and four lines over 120 columns, one of them a
doc comment attached to the wrong function.

The frontend guard rides with them: a control writes under the slot of the
pipeline that declared it, and switching pipelines keeps what the other one was
set to.

* fix(image): let the trace name the setting the run actually used

The preprocess mode could be resolved three ways — the pipeline's slot, the
knowledge base field the slot replaced, and a per-task override — and the
resolved answer travelled to the run in a field of its own, while the trace
echoed the pipeline's parameters. So a task whose mode came from the older field
straightened the page to `off` and reported `auto`: its trace named the field's
declared default instead of the mode it read the page with, which is exactly the
trace that cannot be audited.

The task now folds the resolved mode back into the running pipeline's slot, so
one map answers for every setting of that pipeline and the run reads what the
trace echoes. Nothing is written when leaving the map alone would report the same
value, and the map is copied rather than written through — it belongs to a loaded
knowledge base, and nothing resolved for one task may land in the stored config.

Found by the end-to-end smoke test rather than by a unit test, which is what the
smoke test is for: `works/ocr-preprocess/smoke-slot-resolution.sh` runs the same
document five times through a real parse and reads the verdict off the trace.

Also fixes the golden test harness, which built a run context without a pipeline
id: with the id empty every slot lookup missed and the pipeline fell back to its
declared defaults, so a test about parameters was reading defaults and passing.

* docs(image): name the geometry attributes by the names they have

The preprocess mode's doc comment pointed at contain.margin and contain.upright;
the attributes the describe round is asked about are layout.margin and
layout.upright. A comment that names a key nothing writes is the same failure as
a trace that names a setting nothing read, one layer down.

* refactor(image): give every pipeline setting exactly one home

The page-straightening mode and the OCR fallback clause each had two homes: the
pipeline's slot, and a knowledge-base field the slot replaced. Reading either
one meant deciding which home won, and the two answers could differ — a run that
skipped on `off` while its trace reported `auto` was the visible symptom, and the
patch that folded the resolved value back into the slot was the symptom of the
symptom. The OCR clause had a third: it lived in the attribute table, which is
the user's list of conditions, and was then copied into the payload beside it.

Both are now a setting of the pipeline that declares them and nothing else:

- `preprocess.mode` is read where it is used (`runContext.preprocessMode`), from
  the slot the trace echoes. The flat carriers are gone — the KB field, the
  per-task override field, the payload field, `EffectiveProcessConfig`, and the
  resolvers that reconciled them. The mode the run acts on and the mode its trace
  reports are one lookup, so they cannot disagree.
- `ocr_on_unobserved` is passed to the decision as its own argument
  (`DecideOCR(attrs, policy, onUnobserved)`). It is not an attribute match, so it
  leaves `ImageActionsConfig` — the table is the conditions and nothing else —
  and the attribute decision no longer reads a field that means "scheduling".

Neither key ever reached main, and neither is a value a user cannot set again in
the panel they must pass through to upload or reparse, so the older spellings are
silently discarded rather than migrated: a base that stored one gets the declared
default, shows it, and writes it back on the next save. That also removes the
bare-key fallback in `ImagePipelineParam` / `readPipelineParam` — the same
compatibility for a spelling nothing ever wrote.

The frontend stops naming any field: it renders what the registry publishes and
writes each value under the slot of the pipeline that declared it, so the two
mirrored constants and the read-time fold are gone with them.

Tests that used the discarded spellings now build configs the way the panel
does. Three of them had been passing for the wrong reason: a harness without a
pipeline id read declared defaults while claiming to test stored switches, a
caption-only failure was asserting the OCR result of an OCR that ran because its
switch was spelled in a name nothing had read since the rename, and the
namespace-precedence cases exercised a fallback that no longer exists.

* fix(image): self-review pass one — reasons, hygiene, and stale claims

Findings from reading the diff as a reviewer would, all cheap and all in
this PR's own debt:

- A skipped preprocessing step answered "this build has no preprocessor"
  before "the user switched it off", so a deployment without the document
  service reported the same reason for every setting. The user's choice is
  the more specific answer and now comes first; the order is pinned by a
  test (internal/application/service/image_pipeline_preprocess_test.go).
- The docreader preprocessing module is now written in the language the
  rest of docreader uses: English docstrings and comments, logging instead
  of a bare print, and no dead imports. The algorithm notes are kept —
  the 180-degree periodic mode, the ±90 split that breaks a median, the
  ANG_TOL reason, and why use_cls must be passed explicitly — only the
  internal narrative is gone.
- The stale claims about keys that two pipelines share are corrected: a
  setting lives in the slot of the pipeline that declares it, so an action
  key carried by two pipelines is the same spelling with two values, not
  one shared value. The golden test's cross-pipeline exemption is now the
  general rule (an action-declared key may be carried by any pipeline; a
  bare key a pipeline invents for itself may not mean two things).
- image_param_naming_test.go asserted that a bare key still answers "so an
  old knowledge base stays readable" — a fallback the code deliberately
  does not have, and an assertion that could not fail because the declared
  default it fell back to was true. It now pins the truth with a default of
  false, so the bare key being read would turn it red.
- i18n: the stray blank line inside smartocr.ocr and the mis-indented
  imagePipelineValidateError are fixed in all six locales, and the Japanese
  string no longer mixes a simplified-Chinese character into its sentence.

* test(docreader): cover the page-straightening geometry

The module is pure geometry over boxes and points, and it had no unit tests
while the rest of docreader/tests carries twenty-odd files. These tests build
their own inputs and never load RapidOCR, so they run in the same suite as
everything else (unittest discover, no extra dependency).

The load-bearing one is dominant_angle: a near-vertical page lands at both ends
of the (-90, 90] window, and the case built here has enough short boxes near
zero to BE the median of the raw angles — an implementation that took one would
answer 0 and align the page by nothing. Swapping the weighted mode for a median
turns that test red, which is how it was checked.

The thresholds are pinned just inside and just outside rather than exactly on
the value: the angle comes back through float32, so "exactly on it" is not a
number the arithmetic can be asked to produce.

* feat(image): give the straightening pass a subspan and a deadline

Two halves of the same complaint: the step is the most expensive thing the
smart pipeline does and it was the only one of its neighbours without either.

The subspan is raised where the call happens, after the skip decisions, so a
skipped pass leaves no empty row in the timeline. It carries the same status and
byte count the trace row does, and a failure fails it with a stable code — which
is what makes "how long did straightening take, and did it work" readable from
the timeline instead of inferred. The end-to-end run puts numbers on it: on a
3072x4096 phone photo five calls measured 13.7-30.0s, more than the OCR call
they exist to help (9.2s).

The deadline is the caller's, not the task's: a document service that hangs must
not hold a worker until the whole document's budget is gone. The first draft of
this cap was 30s, and the end-to-end run landed exactly on it — the slowest call
measured 30013ms, which is the margin such a guard must not have. It is now 60s,
still an order of magnitude below the docreader RPC timeout a hung call would
otherwise consume, and a call cut short is recorded like any other failure with
OCR reading the original bytes.

* feat(docreader): let the straightening thresholds be overridden for a run

The five thresholds were tuned on the 17-image benchmark, and asking "what would
this page look like with a different residual tolerance" meant rebuilding the
image. They now read WEKNORA_PREPROCESS_<NAME> once at import, with the tuned
value as the default, and the compose file passes those five through so a
deployment can set them without editing the file.

An override is validated against the range the value has to mean something in,
and a bad one is refused with the default left in place rather than clamped into
range: a typo should not quietly run the pipeline at a value nobody chose, and a
refusal is logged where a clamp would be invisible.

The set in force is named in the server's startup banner, next to the other
settings it prints, so the output of a debugging run can be read back against
the tuning that produced it. Logged from main rather than from the module: the
module is imported before the log level is set, and an INFO line emitted then
would go nowhere.

These are engine constants rather than knowledge base settings, so they stay out
of the run's config echo — see the PR description for why the per-image echo is
a separate (proto-changing) piece of work.

* fix(image): follow the rename through the PATCH path main added

#4427 taught the knowledge-base PATCH endpoint to toggle the two image switches
through image_caption_enabled / image_ocr_enabled, writing "enable_caption" and
"enable_ocr" plus their "default." slots. Those are the names this branch
renames, so the endpoint would have written a key nothing reads: the switch
would silently do nothing, which is the failure the naming rules exist to
remove. CI caught it as TestImageControlsPreserveOtherParamsAndRespectNamespace.

The handler now writes the pipeline's own slot and nothing else — one setting,
one home — and takes the keys from the pipeline's declaration
(service.ImageCaptionSwitchKey / ImageOCRSwitchKey) instead of spelling them at
the call site, because a second spelling is how the next rename breaks it again.

The tests and fixtures that still named the old keys follow: the handler test
(which now also pins that no bare key is written), the overrides and thinking
tests, and the two frontend suites that used them as sample parameters.

* fix(image): correct preprocessing and agent config projection

* fix(docreader): isolate and bound opt-in image preprocessing

---------

Co-authored-by: tayadwx <tayadwx@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-21 19:20:16 +08:00

439 lines
20 KiB
Python

"""Unit tests for the page-straightening geometry in parser/image_preprocess.
Geometry tests build their own boxes and points. Engine isolation is exercised
with a mutable recognizer double, so these tests never load RapidOCR models.
The values that matter most are the ones a wrong answer would hide:
* dominant_angle must fold the 180-degree period, because a near-vertical page
lands at BOTH ends of the (-90, 90] window and a median would call it 0;
* filter_items must keep the box that sits exactly on a threshold, so a change
from <= to < is visible rather than a silent one-box difference;
* fit_quad must enclose every box it was given — a quad that cuts a line off
is the failure the padding and the supporting lines exist to prevent.
"""
from concurrent.futures import ThreadPoolExecutor
import threading
from types import SimpleNamespace
import unittest
from unittest.mock import patch
import cv2
import numpy as np
from docreader.parser import image_preprocess
from docreader.parser.image_preprocess import (
ANG_TOL,
DEFAULT_PAD,
MIN_SCORE,
PAD,
QUAD_TOL,
SIZE_MIN,
_THRESHOLDS as THRESHOLDS,
_boundary_line,
_intersect,
_tls,
align_residual,
box_angle,
choose_rotation,
dominant_angle,
effective_thresholds,
filter_items,
fit_quad,
order_pts,
resolve_threshold,
warp,
wrap90,
)
def box(cx, cy, w, h, angle_deg=0.0):
"""One text-line box: four corners, long edge first, as RapidOCR returns them."""
t = np.radians(angle_deg)
ux, uy = np.cos(t), np.sin(t)
vx, vy = -np.sin(t), np.cos(t)
corners = [
(cx - w / 2 * ux - h / 2 * vx, cy - w / 2 * uy - h / 2 * vy),
(cx + w / 2 * ux - h / 2 * vx, cy + w / 2 * uy - h / 2 * vy),
(cx + w / 2 * ux + h / 2 * vx, cy + w / 2 * uy + h / 2 * vy),
(cx - w / 2 * ux + h / 2 * vx, cy - w / 2 * uy + h / 2 * vy),
]
return np.array(corners, "float32")
def line(cx, cy, length, angle_deg=0.0, height=8.0, score=0.9):
"""A detected line: the box plus the score detect() would have attached."""
return (box(cx, cy, length, height, angle_deg), score)
def grid(xs, ys):
"""The point set a box list turns into after the alignment transform."""
return np.array([(float(x), float(y)) for x in xs for y in ys], "float32")
class EngineIsolationTest(unittest.TestCase):
def test_concurrent_detection_cannot_enable_recognition_classification(self):
scoring_started = threading.Event()
detection_finished = threading.Event()
class MutableRecognizer:
def __init__(self, **kwargs):
pass
def __call__(self, img, *, use_cls):
self.use_cls = use_cls
if not use_cls:
scoring_started.set()
if not detection_finished.wait(timeout=5):
raise TimeoutError("concurrent detection did not finish")
# Classification would make the recognition score insensitive
# to orientation. Expose another call changing this flag.
score = 0.9 if use_cls or not self.use_cls else 0.1
return SimpleNamespace(boxes=[box(50, 50, 100, 10)], scores=[score])
img = np.zeros((10, 10, 3), "uint8")
def score_page():
engine = image_preprocess._engine()
score, count = image_preprocess.rec_score(img)
return engine, image_preprocess._engine(), score, count
def detect_page():
try:
return image_preprocess._engine(), image_preprocess.detect(img)
finally:
detection_finished.set()
with patch.object(image_preprocess, "RapidOCR", side_effect=MutableRecognizer):
with ThreadPoolExecutor(max_workers=2) as pool:
scoring = pool.submit(score_page)
try:
self.assertTrue(scoring_started.wait(timeout=5))
detecting = pool.submit(detect_page)
detection_engine, boxes = detecting.result(timeout=5)
score_engine, reused_engine, score, count = scoring.result(timeout=5)
finally:
detection_finished.set()
self.assertAlmostEqual(score, 0.9, places=6)
self.assertEqual(count, 1)
self.assertEqual(len(boxes), 1)
self.assertIs(score_engine, reused_engine, "one worker should reuse its engine")
self.assertIsNot(score_engine, detection_engine, "workers must not share mutable OCR state")
def test_engine_limits_native_threads(self):
def create():
return image_preprocess._engine()
with patch.object(image_preprocess, "RapidOCR") as factory:
with ThreadPoolExecutor(max_workers=1) as pool:
pool.submit(create).result(timeout=5)
params = factory.call_args.kwargs["params"]
self.assertEqual(params["EngineConfig.onnxruntime.intra_op_num_threads"],
image_preprocess.CONFIG.preprocess_threads)
self.assertEqual(params["EngineConfig.onnxruntime.inter_op_num_threads"], 1)
class BoxAngleTest(unittest.TestCase):
def test_long_edge_sets_the_angle(self):
angle, length = box_angle(box(50, 50, 100, 10, 30))
self.assertAlmostEqual(angle, 30.0, places=3)
self.assertAlmostEqual(length, 100.0, places=3)
def test_a_tall_box_reports_its_long_edge_not_its_first(self):
# w < h: the first edge is the short one, so the long edge decides.
angle, length = box_angle(box(50, 50, 10, 100, 0))
self.assertAlmostEqual(abs(angle), 90.0, places=3)
self.assertAlmostEqual(length, 100.0, places=3)
def test_a_vertical_box_reports_the_sign_of_its_long_edge(self):
positive, _ = box_angle(box(50, 50, 100, 10, 45))
negative, _ = box_angle(box(50, 50, 100, 10, -45))
self.assertGreater(positive, 0)
self.assertLess(negative, 0)
class Wrap90Test(unittest.TestCase):
def test_folds_onto_the_period_a_line_really_has(self):
for given, want in (
(0.0, 0.0),
(89.0, 89.0),
(-89.0, -89.0),
(90.0, -90.0),
(-90.0, -90.0),
(91.0, -89.0),
(180.0, 0.0),
(270.0, -90.0),
):
with self.subTest(angle=given):
self.assertAlmostEqual(wrap90(given), want, places=6)
class DominantAngleTest(unittest.TestCase):
def test_no_boxes_is_no_angle(self):
self.assertEqual(dominant_angle([]), 0.0)
def test_a_flat_page_reads_zero(self):
items = [line(10 * i, 50, 100, 0) for i in range(1, 6)]
self.assertAlmostEqual(dominant_angle(items), 0.0, places=1)
def test_a_tilted_page_reads_its_tilt(self):
items = [line(10 * i, 50, 100, 30) for i in range(1, 6)]
self.assertAlmostEqual(dominant_angle(items), 30.0, places=1)
def test_a_quarter_turned_page_is_not_called_flat(self):
# The load-bearing test of this file. A near-vertical page lands at BOTH
# ends of the (-90, 90] window, because the sign of the long edge's x
# component is pixel noise: the measured case split ~47% at -89 and ~37%
# at +89. Here the short boxes near 0 are numerous enough to BE the
# median of the raw angles, so an implementation that took one would
# answer 0 and "align" the page by nothing; the length-weighted mode
# answers the vertical direction the page actually has.
items = [line(10 * i, 300, 10, 0) for i in range(1, 21)]
items += [line(10 * i, 50, 100, -89) for i in range(1, 5)]
items += [line(10 * i, 200, 100, 89) for i in range(1, 5)]
angle = dominant_angle(items)
self.assertAlmostEqual(abs(angle), 90.0, delta=0.5)
def test_too_few_boxes_leave_the_angle_approximate(self):
# Below three in-tolerance boxes the circular mean is not worth
# trusting, so the answer is the window's own peak — the edge of a
# plateau that can sit up to ANG_TOL away from the true angle. Two boxes
# is not a page, so the bound is what this pins.
items = [line(10, 50, 100, 20), line(200, 50, 100, 20)]
self.assertAlmostEqual(dominant_angle(items), 20.0, delta=ANG_TOL)
class FilterItemsTest(unittest.TestCase):
def test_keeps_what_agrees_and_drops_the_rest(self):
items = [line(10 * i, 50, 100, 0) for i in range(1, 4)]
items.append(line(500, 50, 100, 45)) # a background object's edge
items.append(line(600, 50, 10, 0)) # a speck, far below the median
kept = filter_items(items, 0.0)
self.assertEqual(len(kept), 3)
def test_a_box_just_inside_the_angle_threshold_is_kept(self):
# Just inside and just outside rather than exactly on it: the angle
# comes back through float32, so "exactly on it" is not a value the
# arithmetic can be asked to produce. This still pins the threshold and
# the direction of the comparison.
items = [line(10 * i, 50, 100, 0) for i in range(1, 4)]
items.append(line(500, 50, 100, ANG_TOL - 0.01))
self.assertEqual(len(filter_items(items, 0.0)), 4)
items[-1] = line(500, 50, 100, ANG_TOL + 0.01)
self.assertEqual(len(filter_items(items, 0.0)), 3)
def test_a_box_exactly_on_the_size_threshold_is_kept(self):
items = [line(10 * i, 50, 100, 0) for i in range(1, 4)]
items.append(line(500, 50, SIZE_MIN * 100, 0))
self.assertEqual(len(filter_items(items, 0.0)), 4)
items[-1] = line(500, 50, SIZE_MIN * 100 - 0.5, 0)
self.assertEqual(len(filter_items(items, 0.0)), 3)
def test_no_boxes_filters_to_nothing(self):
self.assertEqual(filter_items([], 0.0), [])
class RotationTest(unittest.TestCase):
def test_residual_is_smallest_at_the_alignment_that_matches(self):
items = [line(10 * i, 50, 100, 30) for i in range(1, 6)]
self.assertAlmostEqual(align_residual(items, 30), 0.0, places=1)
self.assertAlmostEqual(align_residual(items, -30), 60.0, places=1)
def test_rotation_is_chosen_by_the_smaller_residual(self):
tilted_up = [line(10 * i, 50, 100, 30) for i in range(1, 6)]
tilted_down = [line(10 * i, 50, 100, -30) for i in range(1, 6)]
self.assertAlmostEqual(choose_rotation(tilted_up, 30), 30.0, places=6)
self.assertAlmostEqual(choose_rotation(tilted_down, -30), -30.0, places=6)
class LeastSquaresTest(unittest.TestCase):
def test_fits_a_line_through_points_on_one(self):
pts = np.array([(x, 2.0 * x + 1.0) for x in range(10)], "float32")
slope, intercept = _tls(pts, 0)
self.assertAlmostEqual(slope, 2.0, places=3)
self.assertAlmostEqual(intercept, 1.0, places=3)
def test_needs_two_points_across_the_axis(self):
self.assertIsNone(_tls(np.array([(5.0, 5.0)], "float32"), 0))
self.assertIsNone(_tls(np.array([(5.0, 1.0), (5.0, 9.0)], "float32"), 0))
class BoundaryLineTest(unittest.TestCase):
def test_sloped_sides_are_fitted_across_both_axes(self):
# A perspective-distorted page narrows from 100 to 60 pixels. Its side
# slopes are within the accepted range and span the full page height.
pts = np.array([(x, y) for y in range(0, 201, 5)
for x in (0.1 * y, 100 - 0.1 * y)], "float32")
for axis, points in ((0, pts), (1, pts[:, ::-1])):
for side, expected_slope, expected_intercept in (("min", 0.1, 0), ("max", -0.1, 100)):
with self.subTest(axis=axis, side=side):
slope, intercept = _boundary_line(points, axis, side)
self.assertAlmostEqual(slope, expected_slope, places=5)
self.assertAlmostEqual(intercept, expected_intercept, places=4)
residual = points[:, axis] - (slope * points[:, 1 - axis] + intercept)
if side == "min":
self.assertGreaterEqual(float(residual.min()), -1e-4)
else:
self.assertLessEqual(float(residual.max()), 1e-4)
def test_a_short_extreme_band_does_not_extrapolate_its_slope(self):
pts = np.array([(0.1 * y, y) for y in range(10)] + [(100, 100)], "float32")
slope, intercept = _boundary_line(pts, 0, "min")
self.assertEqual(slope, 0.0)
self.assertEqual(intercept, 0.0)
def test_the_min_side_encloses_every_point(self):
pts = grid((0, 50, 100), (0, 40, 80))
slope, intercept = _boundary_line(pts, 1, "min")
residual = pts[:, 1] - (slope * pts[:, 0] + intercept)
self.assertGreaterEqual(float(residual.min()), -1e-4)
self.assertAlmostEqual(float(residual.min()), 0.0, places=3)
def test_the_max_side_encloses_every_point(self):
pts = grid((0, 50, 100), (0, 40, 80))
slope, intercept = _boundary_line(pts, 1, "max")
residual = pts[:, 1] - (slope * pts[:, 0] + intercept)
self.assertLessEqual(float(residual.max()), 1e-4)
self.assertAlmostEqual(float(residual.max()), 0.0, places=3)
def test_a_flat_band_has_no_line(self):
# Every point shares the coordinate this side is measured along, so
# there is no outer edge to find.
pts = np.array([(0.0, 5.0), (10.0, 5.0), (20.0, 5.0)], "float32")
self.assertIsNone(_boundary_line(pts, 0, "min"))
class IntersectTest(unittest.TestCase):
def test_two_lines_meet_where_they_should(self):
# y = 0*x + 1 and x = 0*y + 2 meet at (2, 1).
self.assertEqual(_intersect((0.0, 1.0), (0.0, 2.0)), (2.0, 1.0))
def test_parallel_lines_do_not_meet(self):
# m1 * m2 == 1: the two lines are parallel, so the intersection is at
# infinity and there is no corner.
self.assertIsNone(_intersect((2.0, 1.0), (0.5, 3.0)))
class OrderPointsTest(unittest.TestCase):
def test_corners_come_back_in_a_known_order(self):
corners = np.array([(100.0, 80.0), (0.0, 0.0), (0.0, 80.0), (100.0, 0.0)], "float32")
ordered = order_pts(corners)
self.assertEqual([tuple(p) for p in ordered], [(0.0, 0.0), (100.0, 0.0), (100.0, 80.0), (0.0, 80.0)])
class FitQuadTest(unittest.TestCase):
def test_perspective_edges_produce_a_trapezoid_instead_of_a_bounding_box(self):
pts = np.array([(x, y) for y in range(0, 201, 5)
for x in (0.1 * y, 100 - 0.1 * y)], "float32")
quad = fit_quad(pts)
self.assertIsNotNone(quad)
np.testing.assert_allclose(quad, [[0, 0], [100, 0], [80, 200], [20, 200]], atol=1e-4)
for x, y in pts:
self.assertGreaterEqual(cv2.pointPolygonTest(quad, (float(x), float(y)), True), -1e-4)
def test_the_quad_encloses_every_point_it_was_given(self):
pts = grid(range(0, 101, 10), range(0, 81, 10))
quad = fit_quad(pts)
self.assertIsNotNone(quad)
for x, y in pts:
# pointPolygonTest returns the distance to the nearest edge, signed:
# negative means the point is outside.
distance = cv2.pointPolygonTest(quad, (float(x), float(y)), True)
self.assertGreaterEqual(distance, -1e-3, f"point ({x}, {y}) fell outside the quad")
def test_the_quad_is_tight_around_the_points(self):
pts = grid(range(0, 101, 10), range(0, 81, 10))
quad = fit_quad(pts)
self.assertAlmostEqual(float(quad[:, 0].min()), 0.0, delta=1.0)
self.assertAlmostEqual(float(quad[:, 0].max()), 100.0, delta=1.0)
self.assertAlmostEqual(float(quad[:, 1].min()), 0.0, delta=1.0)
self.assertAlmostEqual(float(quad[:, 1].max()), 80.0, delta=1.0)
def test_points_on_one_line_have_no_quad(self):
# Nothing spans the other axis, so two of the four supporting lines do
# not exist and there is no content area to speak of.
pts = np.array([(float(x), 5.0) for x in range(0, 101, 10)], "float32")
self.assertIsNone(fit_quad(pts))
class WarpTest(unittest.TestCase):
def test_fitted_perspective_edges_become_straight_after_warp(self):
pts = np.array([(x + 50, y + 50) for y in range(0, 201, 5)
for x in (0.1 * y, 100 - 0.1 * y)], "float32")
img = np.zeros((300, 200, 3), "uint8")
cv2.fillConvexPoly(img, np.array([[50, 50], [150, 50], [130, 250], [70, 250]]), (255, 255, 255))
rect, _ = warp(img, fit_quad(pts), pad=0)
# A bounding-box crop retains black wedges beside the narrower end.
# Rectification must fill both sides throughout the page height.
self.assertGreater(float(rect[5:-5, 5:10].mean()), 250)
self.assertGreater(float(rect[5:-5, -10:-5].mean()), 250)
def test_the_result_is_the_quad_plus_its_padding(self):
img = np.full((300, 300, 3), 255, "uint8")
quad = np.array([(50.0, 50.0), (150.0, 50.0), (150.0, 100.0), (50.0, 100.0)], "float32")
rect, padded = warp(img, quad)
side = float(np.mean([np.linalg.norm(padded[(i + 1) % 4] - padded[i]) for i in range(4)]))
grown = 2 * PAD * side
self.assertAlmostEqual(rect.shape[1], 100 + grown, delta=2.0)
self.assertAlmostEqual(rect.shape[0], 50 + grown, delta=2.0)
def test_the_padding_grows_the_quad_outward(self):
img = np.full((300, 300, 3), 255, "uint8")
quad = np.array([(50.0, 50.0), (150.0, 50.0), (150.0, 100.0), (50.0, 100.0)], "float32")
_, padded = warp(img, quad)
self.assertLess(float(padded[:, 0].min()), 50.0)
self.assertGreater(float(padded[:, 1].max()), 100.0)
class ThresholdsTest(unittest.TestCase):
"""The thresholds are env-overridable, so the override has to be trustworthy.
The defaults are the tuned values; an override has to parse as a number in
the threshold's range, and anything else is refused with the default left in
place rather than clamped into range — a typo must not quietly run the
pipeline at a value nobody chose.
"""
def test_an_unset_override_leaves_the_tuned_default(self):
for name, (default, _, _) in THRESHOLDS.items():
with self.subTest(threshold=name):
self.assertEqual(resolve_threshold(name, None), default)
self.assertEqual(resolve_threshold(name, " "), default)
def test_a_valid_override_is_taken(self):
self.assertEqual(resolve_threshold("ANG_TOL", "25"), 25.0)
self.assertEqual(resolve_threshold("QUAD_TOL", "-0.05"), -0.05)
self.assertEqual(resolve_threshold("PAD", "0.02"), 0.02)
def test_the_ends_of_the_range_are_inside_it(self):
for name, (_, low, high) in THRESHOLDS.items():
with self.subTest(threshold=name):
self.assertEqual(resolve_threshold(name, repr(low)), low)
self.assertEqual(resolve_threshold(name, repr(high)), high)
def test_a_value_outside_the_range_is_refused(self):
for name, (default, low, high) in THRESHOLDS.items():
for bad in (low - 1.0, high + 1.0):
with self.subTest(threshold=name, value=bad):
self.assertEqual(resolve_threshold(name, repr(bad)), default)
def test_a_value_that_is_not_a_number_is_refused(self):
for raw in ("wide", "0.015x", "1,5", "nan-ish"):
with self.subTest(raw=raw):
self.assertEqual(resolve_threshold("PAD", raw), DEFAULT_PAD)
def test_the_effective_set_is_what_the_module_uses(self):
# The log line printed at import reads this, so it has to agree with the
# names the functions actually close over.
effective = effective_thresholds()
self.assertEqual(effective["PAD"], PAD)
self.assertEqual(effective["MIN_SCORE"], MIN_SCORE)
self.assertEqual(effective["ANG_TOL"], ANG_TOL)
self.assertEqual(effective["SIZE_MIN"], SIZE_MIN)
self.assertEqual(effective["QUAD_TOL"], QUAD_TOL)
if __name__ == "__main__":
unittest.main()