"""Generate the ANSLPR developer-guide PDF.
Covers two features:
1. ALPRChecker — tracker-based voting / text stabilization
2. Plate format validation — SetPlateFormat / SetPlateFormats
Run:
python build_anslpr_devguide_pdf.py
Output:
ANSLPR_ALPRChecker_PlateFormat_Guide.pdf (next to this script)
"""
from pathlib import Path
from reportlab.lib import colors
from reportlab.lib.enums import TA_LEFT
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
from reportlab.lib.units import mm
from reportlab.platypus import (
PageBreak,
Paragraph,
SimpleDocTemplate,
Spacer,
Table,
TableStyle,
)
OUTPUT = Path(__file__).with_name("ANSLPR_ALPRChecker_PlateFormat_Guide.pdf")
# --------------------------------------------------------------------------- #
# Styles #
# --------------------------------------------------------------------------- #
styles = getSampleStyleSheet()
H1 = ParagraphStyle(
"H1", parent=styles["Heading1"],
fontName="Helvetica-Bold", fontSize=18, leading=22,
spaceBefore=4, spaceAfter=10, textColor=colors.HexColor("#0B3D91"),
)
H2 = ParagraphStyle(
"H2", parent=styles["Heading2"],
fontName="Helvetica-Bold", fontSize=13, leading=16,
spaceBefore=14, spaceAfter=6, textColor=colors.HexColor("#0B3D91"),
)
H3 = ParagraphStyle(
"H3", parent=styles["Heading3"],
fontName="Helvetica-Bold", fontSize=11, leading=14,
spaceBefore=10, spaceAfter=4, textColor=colors.HexColor("#222222"),
)
BODY = ParagraphStyle(
"Body", parent=styles["BodyText"],
fontName="Helvetica", fontSize=9.5, leading=13,
spaceBefore=2, spaceAfter=4, alignment=TA_LEFT,
)
NOTE = ParagraphStyle(
"Note", parent=BODY,
leftIndent=10, fontSize=9, textColor=colors.HexColor("#444444"),
)
CODE = ParagraphStyle(
"Code", parent=BODY,
fontName="Courier", fontSize=8.5, leading=11,
leftIndent=8, rightIndent=8, spaceBefore=4, spaceAfter=8,
backColor=colors.HexColor("#F4F4F4"),
borderColor=colors.HexColor("#D0D0D0"), borderWidth=0.5,
borderPadding=4,
)
TABLE_HEADER = ParagraphStyle(
"TH", parent=BODY, fontName="Helvetica-Bold", fontSize=9, leading=12,
textColor=colors.white,
)
TABLE_CELL = ParagraphStyle(
"TC", parent=BODY, fontSize=9, leading=12, spaceBefore=0, spaceAfter=0,
)
TABLE_CELL_MONO = ParagraphStyle(
"TCM", parent=TABLE_CELL, fontName="Courier", fontSize=8.5,
)
# --------------------------------------------------------------------------- #
# Helpers #
# --------------------------------------------------------------------------- #
def p(text, style=BODY):
return Paragraph(text, style)
def code_block(lines):
body = "
".join(
line.replace(" ", " ").replace("<", "<").replace(">", ">")
for line in lines
)
body = body.replace("<br/>", "
")
return Paragraph(body, CODE)
def make_table(header, rows, col_widths=None, mono_cols=None):
mono_cols = mono_cols or set()
def cell(text, col_idx):
style = TABLE_CELL_MONO if col_idx in mono_cols else TABLE_CELL
return Paragraph(text, style)
data = [[Paragraph(h, TABLE_HEADER) for h in header]]
for row in rows:
data.append([cell(c, i) for i, c in enumerate(row)])
t = Table(data, colWidths=col_widths, repeatRows=1)
t.setStyle(TableStyle([
("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#0B3D91")),
("TEXTCOLOR", (0, 0), (-1, 0), colors.white),
("ALIGN", (0, 0), (-1, -1), "LEFT"),
("VALIGN", (0, 0), (-1, -1), "TOP"),
("FONTSIZE", (0, 0), (-1, -1), 9),
("BOTTOMPADDING", (0, 0), (-1, 0), 6),
("TOPPADDING", (0, 0), (-1, 0), 6),
("BOTTOMPADDING", (0, 1), (-1, -1), 4),
("TOPPADDING", (0, 1), (-1, -1), 4),
("LEFTPADDING", (0, 0), (-1, -1), 5),
("RIGHTPADDING", (0, 0), (-1, -1), 5),
("ROWBACKGROUNDS", (0, 1), (-1, -1),
[colors.white, colors.HexColor("#F4F7FB")]),
("GRID", (0, 0), (-1, -1), 0.4, colors.HexColor("#B0B7C3")),
]))
return t
# --------------------------------------------------------------------------- #
# Document content #
# --------------------------------------------------------------------------- #
def build_story():
s = []
# ====================================================================
# Title
# ====================================================================
s.append(p(
"ANSLPR — ALPRChecker & Plate Format Developer Guide",
H1,
))
s.append(p(
"Module: ANSLPR · "
"Base class: ANSCENTER::ANSALPR · "
"Affects every engine subclass "
"(ANSALPR_OD, ANSALPR_OCR, ANSALPR_CPU)",
NOTE,
))
s.append(Spacer(1, 6))
s.append(p(
"This guide documents two independent post-processing features in the "
"ANSLPR pipeline: the ALPRChecker (per-track majority voting + "
"lock + skip-when-locked) and the plate format validator "
"(SetPlateFormat / "
"SetPlateFormats). "
"They share neither state nor toggle; the format validator runs as a "
"filter before the ALPRChecker voter sees any text."
))
# ====================================================================
# PART 1 — ALPRChecker
# ====================================================================
s.append(p("Part 1 — ALPRChecker (tracker-based voting)", H1))
# ── 1.1 Purpose ──────────────────────────────────────────────────────
s.append(p("1.1 Purpose", H2))
s.append(p(
"Convert noisy per-frame OCR strings for the same physical plate "
"(“50H 304.07”, “50H304O7”, “50H304.07”…) "
"into a single stable locked text. The mechanism is layered:"
))
s.append(p(
"track identity → rolling history per track → "
"recency-weighted majority vote → stable lock with "
"edit-distance noise rejection → periodic re-verify "
"so wrong locks can self-correct."
))
# ── 1.2 Default state ────────────────────────────────────────────────
s.append(p("1.2 Default state", H2))
s.append(make_table(
["Flag", "Default", "Source"],
[
["_enableALPRChecker",
"false (opt-in)",
"Member initializer in ANSLPR.h "
"(std::atomic<bool> "
"_enableALPRChecker{false})"],
["Full-frame auto-detect",
"engages after a few pixel-identical frames "
"(only relevant once enabled)",
"shouldUseALPRChecker / ImageSizeTracker"],
["Skip-when-locked re-verify period",
"30 frames",
"tryReuseLockedText default reverifyEvery=30"],
],
col_widths=[55*mm, 50*mm, 63*mm],
mono_cols={0},
))
s.append(Spacer(1, 4))
s.append(p(
"Out of the box: ALPRChecker is OFF. The pipeline emits "
"raw recognizer text per frame — no voting, no lock, no "
"skip-when-locked, no spatial dedup. Callers must opt in with "
"SetALPRCheckerEnabled(true) "
"(or ANSALPR_SetALPRCheckerEnabled(h, 1)) "
"to enable cross-frame stabilization. Once enabled, full-frame "
"auto-detect still gates it on per camera, so pre-cropped pipeline "
"calls remain stateless even when the flag is on.",
NOTE,
))
# ── 1.3 Public API ───────────────────────────────────────────────────
s.append(p("1.3 Public API", H2))
s.append(p("C++ class API (ANSCENTER::ANSALPR):"))
s.append(make_table(
["Method", "Effect"],
[
["void SetALPRCheckerEnabled(bool enable)",
"Atomic flip of _enableALPRChecker. "
"Logs [ALPR_Checker] with prev/new."],
["bool IsALPRCheckerEnabled() const",
"Atomic read. Logs the current value."],
],
col_widths=[80*mm, 88*mm],
mono_cols={0},
))
s.append(Spacer(1, 4))
s.append(p("C exports (LabVIEW / .NET / other clients):"))
s.append(make_table(
["Function", "Args", "Return"],
[
["ANSALPR_SetALPRCheckerEnabled",
"Handle, int enable (0|1)",
"1 OK / -1 invalid handle / 0 exception"],
["ANSALPR_GetALPRCheckerEnabled",
"Handle",
"1 enabled / 0 disabled / -1 invalid handle"],
],
col_widths=[60*mm, 55*mm, 53*mm],
mono_cols={0, 1},
))
# ── 1.4 State (data structures) ──────────────────────────────────────
s.append(p("1.4 Internal state (per ANSALPR instance)", H2))
s.append(code_block([
"class ALPRChecker {",
" int maxFrames = 60; // rolling history depth",
" int minVotesToStabilize = 3; // identical reads to lock",
" float iouMatchThreshold = 0.30f; // spatial match (legacy API)",
" std::recursive_mutex _mutex; // protects all maps",
"",
" // trackId-based primary path",
" unordered_map>",
" trackedPlatesById;",
"",
" // spatial-IoU legacy path",
" unordered_map> trackedPlates;",
"};",
"",
"struct TrackedPlateById {",
" int trackId;",
" deque textHistory; // RAW reads, capped",
" string lockedText; // \"\" until locked",
" int lockCount;",
" int framesSinceLastSeen; // for prune",
" int framesSinceVerify; // for skip-when-locked",
"};",
]))
# ── 1.5 Algorithm ────────────────────────────────────────────────────
s.append(p("1.5 Core algorithm — checkPlateByTrackId", H2))
s.append(p(
"Primary entry point. Hybrid identity strategy: trackId hash lookup "
"(O(1) common case), Levenshtein-1 fallback for lost tracks.",
))
s.append(code_block([
"LOCK _mutex",
"if detectedPlate empty: return \"\"",
"",
"plates = trackedPlatesById[cameraId]",
"for (id, p) in plates: p.framesSinceLastSeen++ // age all",
"",
"// Periodic prune: every 30 calls, drop entries unseen > 180 frames",
"_pruneCounterById++",
"if _pruneCounterById >= 30 and plates.size() > 20:",
" drop entries where framesSinceLastSeen > maxFrames * 3",
"",
"// PRIMARY: O(1) trackId hit",
"if trackId in plates:",
" tp = plates[trackId]",
" tp.framesSinceLastSeen = 0",
" tp.textHistory.push_back(detectedPlate) // RAW",
" if size > maxFrames: pop_front()",
"",
" voted = majorityVote(tp.textHistory)",
"",
" if tp.lockedText empty:",
" if count(history == voted) >= minVotesToStabilize: // 3",
" tp.lockedText = voted // LOCK",
" return voted",
" else:",
" if Levenshtein(detectedPlate, lockedText) == 0:",
" tp.lockCount++; return lockedText",
" elif Levenshtein(voted, lockedText) > 1:",
" // Re-lock if 3 of last 6 votes agree on new text",
" if count(recent6 == voted) >= 3:",
" tp.lockedText = voted // RE-LOCK",
" return lockedText",
" return lockedText // emit lock, ignore noise",
"",
"// FALLBACK: trackId changed (occlusion, ID switch). Migrate.",
"for (id, p) in plates:",
" if Levenshtein(detectedPlate, p.lockedText) <= 1:",
" migrate p to plates[trackId]; erase old id",
" return p.lockedText",
" elif p.lockedText empty and any of last 3 history within edit-1:",
" migrate; return majorityVote(migrated.history)",
"",
"// No match anywhere: fresh entry",
"plates[trackId] = { trackId, history=[detectedPlate], locked=\"\" }",
"return detectedPlate",
]))
s.append(p("1.6 majorityVote", H3))
s.append(p(
"Recency-weighted vote with Levenshtein-1 group boosting. Newest "
"entries get weight 2.0, oldest 1.0. Variants within edit distance 1 "
"donate 0.5× their score to each candidate, so 1-character "
"OCR drift fuses instead of competing."
))
s.append(code_block([
"weightedFreq = {}",
"for i in 0..n-1:",
" weight = 1.0 + i / max(1, n-1) // newest=2.0, oldest=1.0",
" weightedFreq[history[i]] += weight",
"",
"for kv in weightedFreq:",
" total = kv.score",
" for other in weightedFreq:",
" if abs(len(kv) - len(other)) <= 1",
" and Levenshtein(kv, other) == 1:",
" total += other.score * 0.5",
" track best",
"return best",
]))
s.append(p("1.7 tryReuseLockedText — skip-when-locked fast path", H3))
s.append(p(
"Saves ~50–95 ms per locked plate per frame by skipping "
"the OCR call entirely when a stable lock exists. Periodic re-verify "
"(every 30 frames by default) lets one OCR run through so a wrong "
"lock can self-correct via the normal voting path."
))
s.append(code_block([
"LOCK _mutex",
"tp = trackedPlatesById[cameraId][trackId] // miss -> return \"\"",
"if tp.lockedText empty: return \"\" // not locked yet",
"",
"if reverifyEvery > 0 and tp.framesSinceVerify >= reverifyEvery:",
" tp.framesSinceVerify = 0",
" return \"\" // signal: caller runs OCR this frame",
"",
"tp.framesSinceVerify++",
"tp.framesSinceLastSeen = 0 // critical: keep entry alive across",
" // long skip-when-locked windows",
"return tp.lockedText // skip OCR; emit lock directly",
]))
# ── 1.8 Pipeline integration ─────────────────────────────────────────
s.append(PageBreak())
s.append(p("1.8 Pipeline integration", H2))
s.append(p(
"Pipeline mode always bypasses the ALPRChecker, regardless of "
"how _enableALPRChecker is set. Two "
"independent mechanisms enforce this:"
))
s.append(p(
"Mechanism 1 — dedicated batch entry point (hard bypass). "
"ANSALPR_RunInferencesBatch_LV / "
"_LV_V2 "
"(dllmain.cpp:836, 1405) routes through "
"engine->RunInferencesBatch(...). The "
"implementations at "
"ANSALPR_OD::RunInferencesBatch "
"(line 2637) and "
"ANSALPR_OCR::RunInferencesBatch "
"(line 1863) contain zero references to the checker — "
"no shouldUseALPRChecker, no "
"checkPlateByTrackId, no "
"tryReuseLockedText, no "
"ensureUniquePlateText. The flag is "
"never read on this path. Header contract at "
"ANSLPR.h:163-178: "
"“Tracker, voting, spatial dedup, and per-camera "
"accumulating state are all bypassed.”"
))
s.append(p(
"Mechanism 2 — auto-detect floors on the regular "
"RunInference path. "
"shouldUseALPRChecker applies a chain "
"of gates; the last two reject pipeline crops even when the "
"flag is on:"
))
s.append(code_block([
"if !_enableTrackerVoting: return false // OD master (1)",
"if !_enableALPRChecker.load(relaxed): return false // user flag (2)",
"if imageSize.width < MIN_FULLFRAME_WIDTH: return false // HARD FLOOR (3)",
" // = 1000 px",
"tracker = _imageSizeTrackers[cameraId]",
"if imageSize == tracker.lastSize: // CONSISTENCY (4)",
" if ++tracker.consistentCount >= CONFIRM_THRESHOLD: // = 5 frames",
" tracker.detectedFullFrame = true",
"else:",
" tracker.lastSize = imageSize; consistentCount = 1 // reset on any",
" tracker.detectedFullFrame = false // mismatch",
"return tracker.detectedFullFrame",
]))
s.append(p(
"Gates (3) and (4) make the bypass automatic for cropped inputs:"
))
s.append(make_table(
["Pipeline indicator", "Effect", "Independent of flag?"],
[
["width < 1000 px "
"(MIN_FULLFRAME_WIDTH)",
"Returns false immediately, "
"before the auto-detect state machine runs.",
"Yes — rejects all small crops unconditionally "
"after the flag check passes."],
["Frame size varies between calls",
"consistentCount resets to 1 on "
"every mismatch; detectedFullFrame "
"stays false. Pre-cropped vehicle "
"ROIs (e.g. 496×453, 497×455, …) never "
"accumulate consistency.",
"Yes — the consistency requirement is independent "
"of the user flag."],
],
col_widths=[60*mm, 70*mm, 38*mm],
))
s.append(Spacer(1, 4))
s.append(p(
"Practical guarantee. Even if a caller sets "
"SetALPRCheckerEnabled(true) and feeds "
"pipeline crops, voting stays off per camera because the auto-detect "
"never flips detectedFullFrame to true. "
"Mixing full-frame and pipeline calls on different cameras works "
"cleanly: the per-camera _imageSizeTrackers "
"entry tracks each camera's mode independently.",
NOTE,
))
s.append(p("Caller path × flag matrix", H3))
s.append(make_table(
["Caller path", "Input characteristic",
"Flag = OFF", "Flag = ON"],
[
["RunInferencesBatch "
"(pipeline batch, LV/V2)",
"any size, any consistency",
"bypassed (hard)",
"bypassed (hard, flag never read)"],
["RunInference",
"full video frames "
"(≥ 1000 px, consistent size)",
"bypassed",
"active after 5 consistent frames"],
["RunInference",
"cropped vehicle ROI "
"(< 1000 px)",
"bypassed",
"bypassed by MIN_FULLFRAME_WIDTH floor"],
["RunInference",
"varying-size crops "
"(≥ 1000 px but inconsistent)",
"bypassed",
"bypassed by consistency reset"],
],
col_widths=[55*mm, 50*mm, 30*mm, 33*mm],
mono_cols={2, 3},
))
s.append(Spacer(1, 4))
s.append(p(
"In effect, the flag answers a single question: “if the "
"caller is sending real video frames from this camera, should I "
"stabilize the output?” It has no effect on pipeline / "
"cropped inputs — those are always raw OCR.",
NOTE,
))
s.append(p("1.9 OCR engine wiring (per frame)", H3))
s.append(code_block([
"useChecker = shouldUseALPRChecker(frameSize, cameraId) // once",
"",
"for each detected plate box:",
" if useChecker:",
" locked = tryReuseLockedText(cam, trackId)",
" if locked not empty:",
" emit { className=locked, +color }; SKIP CROP",
" continue",
" build crop(s) (padded, optionally rectified, top/bottom split)",
"",
"ONE batched recognizer call across all crops",
"",
"for each plate (non-skipped):",
" text = StripPlateArtifacts(top + \" \" + bottom)",
" if Country == JAPAN and IsJapaneseIncomplete(text):",
" text = recover kana from bottom-half tile",
" text = StripPlateSeparators(text)",
" text = AnalyseLicensePlateText(text) // <-- format filter",
" if text empty: continue // (drops invalid)",
"",
" if useChecker:",
" className = checkPlateByTrackId(cam, text, trackId)",
" else:",
" className = text // raw",
" emit { className, +color }",
"",
"if useChecker:",
" ensureUniquePlateText(output, cam) // spatial dedup",
]))
s.append(p("1.10 OD engine wiring", H3))
s.append(p(
"Same gate at every alprChecker.checkPlateByTrackId "
"call. The OD path doesn't use skip-when-locked because it already "
"runs character classification per detection — nothing to skip. "
"Note OD also has a separate master "
"_enableTrackerVoting "
"flag checked before _enableALPRChecker; "
"if that one is off, the disabled-path applies regardless."
))
# ── 1.11 Disabled mode ──────────────────────────────────────────────
s.append(p("1.11 Disabled mode (default) vs enabled — what runs", H2))
s.append(make_table(
["Stage", "Enabled (opt-in)", "Disabled (default)"],
[
["LP detection",
"Runs", "Runs"],
["ROI cropping + 5% padding",
"Runs", "Runs"],
["Japan rectification + kana recovery",
"Runs (Japan only)", "Runs (Japan only)"],
["Batched recognizer call",
"Runs", "Runs"],
["StripPlateArtifacts / StripPlateSeparators",
"Runs", "Runs"],
["AnalyseLicensePlateText (format filter)",
"Runs (independent toggle)", "Runs (independent toggle)"],
["Skip-when-locked (tryReuseLockedText)",
"Runs", "Bypassed"],
["Per-track voting (checkPlateByTrackId)",
"Runs", "Bypassed — raw recognizer text"],
["Spatial dedup (ensureUniquePlateText)",
"Runs", "Bypassed"],
["trackedPlatesById state",
"Populated and pruned", "Untouched (existing entries frozen)"],
],
col_widths=[60*mm, 53*mm, 55*mm],
))
s.append(Spacer(1, 4))
s.append(p(
"Cost. Disabling skip-when-locked adds ~50–95 ms "
"per locked plate per frame because every plate now goes through "
"OCR every frame.",
NOTE,
))
# ── 1.12 Thread safety ──────────────────────────────────────────────
s.append(p("1.12 Thread safety", H2))
s.append(make_table(
["Concern", "Resolution"],
[
["Toggle race between config thread and inference thread",
"_enableALPRChecker is "
"std::atomic<bool>; "
"store/load use memory_order_relaxed. "
"Tear-free, no fence cost."],
["Concurrent track map mutation",
"ALPRChecker::_mutex "
"(recursive) wraps every read & write of "
"trackedPlatesById / "
"trackedPlates."],
["Concurrent spatial dedup state",
"_plateIdentitiesMutex in "
"ANSALPR_OCR protects "
"_plateIdentities."],
["Toggle while OCR is in flight",
"Safe. The in-flight frame uses whichever value it observed; "
"the next frame picks up the new value."],
],
col_widths=[60*mm, 108*mm],
))
# ── 1.13 Diagnostic logging ─────────────────────────────────────────
s.append(p("1.13 Diagnostic logging (DebugView)", H2))
s.append(make_table(
["Tag", "Emitted by"],
[
["[ALPR_Checker]",
"Set/Get accessors and C-export wrappers — every flag transition "
"and every read."],
["[ALPR_TrackId]",
"checkPlateByTrackId — LOCKED, RE-LOCK, MIGRATED, "
"noise, NEW; tryReuseLockedText — SKIP-LOCKED, REVERIFY."],
["[ALPR_OCR_Checker]",
"shouldUseALPRChecker — full-frame vs pipeline mode auto-detect "
"transitions per camera."],
["[ALPR_Format]",
"AnalyseLicensePlateText — REJECT lines when a plate doesn't "
"match any configured format (see Part 2)."],
["[OCR_Leak]",
"Once-per-60s heartbeat with sizes of each map — useful for "
"spotting unbounded growth in production."],
],
col_widths=[40*mm, 128*mm],
mono_cols={0},
))
s.append(Spacer(1, 4))
s.append(p(
"Tags are gated behind ANSCORE_DEBUGVIEW "
"and ANSCENTER_IsDebugViewEnabled(). "
"Filter DebugView on the bracketed tag to isolate any layer.",
NOTE,
))
# ====================================================================
# PART 2 — Plate format
# ====================================================================
s.append(PageBreak())
s.append(p("Part 2 — Plate format validation", H1))
# ── 2.1 Purpose ──────────────────────────────────────────────────────
s.append(p("2.1 Purpose", H2))
s.append(p(
"Reject OCR output that doesn't match any configured plate pattern. "
"Acts as a hard filter upstream of the ALPRChecker voter, so "
"malformed reads never enter textHistory "
"and a track never locks on garbage."
))
# ── 2.2 Pattern syntax ───────────────────────────────────────────────
s.append(p("2.2 Pattern syntax", H2))
s.append(p(
"Patterns are simple character templates. Each character in the "
"pattern matches one character in the candidate plate; lengths must "
"match exactly."
))
s.append(make_table(
["Token", "Matches", "Notes"],
[
["d", "Any digit (0–9)",
"std::isdigit"],
["l", "Any letter (A–Z, a–z)",
"std::isalpha. Plate text is "
"uppercased before matching."],
["any other char",
"Literal — must match exactly",
"Use uppercase literals (e.g. M, "
"D, NG) "
"since the plate is uppercased first."],
],
col_widths=[20*mm, 80*mm, 68*mm],
mono_cols={0},
))
s.append(Spacer(1, 4))
s.append(p(
"Empty format list = no validation; all plates accepted "
"(MatchesPlateFormat returns true). "
"Calling SetPlateFormats(emptyList) "
"disables filtering.",
NOTE,
))
s.append(p("2.3 Examples", H3))
s.append(make_table(
["Pattern", "Matches", "Doesn't match"],
[
["ddlddddd",
"30A12345 | 51F67890",
"30A1234 (too short) | 30AA12345 "
"(2nd letter where digit expected)"],
["lldddd",
"AB1234 | QC9876",
"A12345 (1st char must be letter) | AB12345 "
"(too long)"],
["dddddNGdd",
"12345NG67",
"12345NN67 (literal mismatch)"],
["ddMDdddddd",
"12MD345678",
"12mD345678 (case mismatch on literal — plate is "
"uppercased, so 'D' must be 'D')"],
],
col_widths=[35*mm, 65*mm, 68*mm],
mono_cols={0, 1, 2},
))
# ── 2.4 Default formats per country ─────────────────────────────────
s.append(p("2.4 Default formats per country", H2))
s.append(p(
"ApplyCountryDefaultPlateFormats() "
"populates the format list automatically based on "
"_country. Called at the end of "
"Initialize() (after country.txt is "
"read) and from SetCountry(), so a "
"runtime country switch picks up the right format set on the very "
"next frame."
))
s.append(make_table(
["Country", "Formats installed"],
[
["VIETNAM",
"ddlddddd, ddldddd, ddldddddd, ddllddddd, ddMDdddddd, "
"dddddNGdd, dddddQTdd, dddddCVdd, dddddNNdd, lldddd "
"(11 patterns covering car / motorbike / military / "
"diplomatic / police)"],
["JAPAN, CHINA, AUSTRALIA, USA, INDONESIA, …",
"Empty — no validation. "
"AnalyseLicensePlateText is also "
"a near-no-op for non-Vietnam countries (preserves kana / "
"kanji / region-specific punctuation verbatim)."],
],
col_widths=[55*mm, 113*mm],
))
# ── 2.5 Public API ──────────────────────────────────────────────────
s.append(p("2.5 Public API", H2))
s.append(p("C++ class API (ANSCENTER::ANSALPR):"))
s.append(make_table(
["Method", "Effect"],
[
["void SetPlateFormat(const string& format)",
"Replace the list with a single pattern."],
["void SetPlateFormats(const vector<string>& formats)",
"Replace the entire list. Pass empty vector to disable validation."],
["vector<string> GetPlateFormats() const",
"Returns the current list."],
["virtual void SetCountry(Country c)",
"Calls ApplyCountryDefaultPlateFormats() so the list resets to "
"the country's defaults."],
],
col_widths=[80*mm, 88*mm],
mono_cols={0},
))
s.append(Spacer(1, 4))
s.append(p("C exports:"))
s.append(make_table(
["Function", "Args", "Return"],
[
["ANSALPR_SetFormat",
"Handle, const char* format",
"1 OK / -1 invalid handle / 0 exception"],
["ANSALPR_SetFormats",
"Handle, const char* formats "
"(semicolon-separated, e.g. \"ddlddddd;ddldddd;lldddd\")",
"1 OK / -1 invalid handle / 0 exception"],
["ANSALPR_GetFormats",
"Handle, LStrHandle outFormats",
"Count written, semicolon-separated"],
["ANSALPR_SetCountry",
"Handle, int country "
"(0=VN, 1=CN, 2=AU, 3=US, 4=ID, 5=JP)",
"1 OK / -1 invalid handle / 0 exception"],
],
col_widths=[55*mm, 65*mm, 48*mm],
mono_cols={0, 1},
))
# ── 2.6 Where it runs ───────────────────────────────────────────────
s.append(PageBreak())
s.append(p("2.6 Where it runs in the pipeline", H2))
s.append(p(
"Sequential post-processing inside the per-plate loop — "
"before the ALPRChecker voter:"
))
s.append(code_block([
"topText, bottomText = OCR results per row",
"combinedText = StripPlateArtifacts(top + \" \" + bottom) // °, ○, screws",
"[Japan] kana recovery if hiragana missing",
"combinedText = StripPlateSeparators(combinedText) // -, comma, ws",
" v",
"combinedText = AnalyseLicensePlateText(combinedText) // <-- PART 2",
" 1. keep only alnum chars",
" 2. uppercase",
" 3. if _plateFormats not empty:",
" if no pattern matches: log REJECT, return \"\"",
" return cleaned plate",
" v",
"if combinedText empty: continue // dropped — voter never sees it",
" v",
"if useChecker: // <-- PART 1",
" className = checkPlateByTrackId(cam, combinedText, trackId)",
"else:",
" className = combinedText",
]))
s.append(Spacer(1, 4))
s.append(p(
"Consequence. When a format list is configured, the voter's "
"textHistory contains only format-valid "
"strings. lockedText is therefore "
"always format-valid by construction. A track that consistently "
"produces format-invalid OCR will never lock — it just never "
"reaches the voter, and no output is emitted for that plate.",
NOTE,
))
# ── 2.7 Country interaction ─────────────────────────────────────────
s.append(p("2.7 Country interaction", H2))
s.append(p(
"AnalyseLicensePlateText behaves "
"differently per country (see "
"ANSALPR_CPU.cpp, "
"ANSALPR_OCR.cpp, "
"ANSALPR_OD.cpp):"
))
s.append(make_table(
["Country", "AnalyseLicensePlateText behavior"],
[
["VIETNAM",
"Strips non-alnum, uppercases, applies suburb-code remapping "
"(13→73, 42→62, 44→64, …), then validates "
"against _plateFormats. Mismatch → \"\""],
["Other countries",
"Returns input unchanged so kana / kanji / region punctuation "
"flow through verbatim. _plateFormats "
"is empty by default for these countries; even if you populate "
"it manually, the format check still runs in OCR (same code "
"path) but is currently a no-op for non-Vietnam in OD."],
],
col_widths=[35*mm, 133*mm],
))
# ── 2.8 Combined behavior matrix ────────────────────────────────────
s.append(p("2.8 ALPRChecker × format combined behavior", H2))
s.append(make_table(
["Format set", "ALPRChecker", "Behavior"],
[
["empty",
"OFF",
"Raw OCR every frame. No filter, no voting. "
"Highest noise, highest recall."],
["empty",
"ON",
"Voted/locked text. Voter learns from raw recognizer output "
"— can lock on bad reads if they're consistent."],
["configured",
"OFF",
"Default for Vietnam. Format-filtered raw OCR per frame. "
"Invalid reads dropped, valid ones emitted as-is "
"(no cross-frame memory)."],
["configured",
"ON",
"Recommended for stable cameras. Format filters bad "
"reads out, voter locks the surviving canonical text. Best "
"stability, lowest false-positive rate. Opt in with "
"SetALPRCheckerEnabled(true)."],
],
col_widths=[35*mm, 30*mm, 103*mm],
mono_cols={0, 1},
))
s.append(Spacer(1, 4))
s.append(p(
"Toggling at runtime. Both flags are independent and "
"thread-safe. Existing locks survive a format-set change — "
"they're not retroactively re-validated. To force a clean slate, "
"destroy and recreate the ANSALPR handle (or wait for the prune "
"pass to expire stale tracks).",
NOTE,
))
# ── 2.9 Caller recipes ──────────────────────────────────────────────
s.append(p("2.9 Caller recipes", H2))
s.append(make_table(
["Goal", "C export sequence"],
[
["Default pipeline (raw OCR + format filter, no voting)",
"Nothing — defaults are fine."],
["Enable tracker voting + skip-when-locked",
"ANSALPR_SetALPRCheckerEnabled(h, 1)"],
["Switch country at runtime",
"ANSALPR_SetCountry(h, 5) // Japan; resets formats"],
["Vietnam-only police plates",
"ANSALPR_SetFormats(h, \"dddddCVdd\")"],
["Vietnam plus a custom long-form pattern",
"ANSALPR_SetFormats(h, \"ddlddddd;ddldddd;dddddCVdd;ddldddddddd\")"],
["Disable format validation entirely",
"ANSALPR_SetFormats(h, \"\") // empty -> accept all"],
["Disable tracker voting (revert to raw OCR every frame)",
"ANSALPR_SetALPRCheckerEnabled(h, 0)"],
["Read current state",
"ANSALPR_GetALPRCheckerEnabled(h); ANSALPR_GetFormats(h, &buf)"],
],
col_widths=[68*mm, 100*mm],
mono_cols={1},
))
# ── 2.10 Diagnostic logging ─────────────────────────────────────────
s.append(p("2.10 Diagnostic logging (DebugView)", H2))
s.append(code_block([
"[ANSLPR] ANSALPR_SetFormat: HandlePtr=0x... format=ddlddddd",
"[ANSLPR] ANSALPR_SetFormats: HandlePtr=0x... formats=ddlddddd;lldddd",
"[ANSLPR] ANSALPR_SetCountry: HandlePtr=0x... country=0",
"[ALPR_Format] REJECT plate='30AA1234' (no _plateFormats match)",
]))
s.append(p(
"Filter on [ALPR_Format] to count how "
"many plates the format filter is rejecting per camera per minute. "
"A high reject rate with a low ALPR result count means the format "
"list is too tight for what the recognizer is producing.",
NOTE,
))
# ── Footer ──────────────────────────────────────────────────────────
s.append(Spacer(1, 14))
s.append(p(
"This guide reflects the ANSLPR API as of the ALPRChecker atomic "
"+ getter export change. File references point to "
"modules/ANSLPR/ANSLPR.{h,cpp}, modules/ANSLPR/ANSLPR_OCR.{h,cpp}, "
"modules/ANSLPR/ANSLPR_OD.{h,cpp}, modules/ANSLPR/ANSLPR_CPU.cpp, "
"and modules/ANSLPR/dllmain.cpp.",
NOTE,
))
return s
# --------------------------------------------------------------------------- #
# Build #
# --------------------------------------------------------------------------- #
def main():
doc = SimpleDocTemplate(
str(OUTPUT),
pagesize=A4,
leftMargin=18*mm, rightMargin=18*mm,
topMargin=18*mm, bottomMargin=18*mm,
title="ANSLPR — ALPRChecker & Plate Format Developer Guide",
author="ANSCORE",
)
story = build_story()
doc.build(story)
print(f"Wrote {OUTPUT}")
if __name__ == "__main__":
main()