VIN_OCR / ocr_orchestra.py
Dirner's picture
Upload ocr_orchestra.py
cb8b5c9 verified
Raw History Blame Contribute Delete
14.6 kB
import time
import easyocr
from gadalka import confidence_from_score, rank_candidates
from image_geometry import (
build_angle_probe_passes,
build_full_frame_fast_scan_passes,
prepare_image_for_ocr,
preprocess_image,
rotate_image,
)
from ocr_config import (
CROP_FAST_PASSES,
DEEP_PASSES,
FULL_FRAME_FOLLOWUP_PASSES,
FULL_FRAME_SOURCES,
FULL_FRAME_STOP_LOW_SCORE,
MAX_CROP_ELAPSED_MS,
MAX_DEEP_PROMISING_ROTATIONS,
MAX_FULL_FRAME_ELAPSED_MS,
MAX_UPLOAD_BYTES,
MEDIUM_SCORE,
MIN_FIRST_PASS_TEXT_LENGTH,
MIN_FULL_FRAME_ANGLE_PROBE_SCORE,
REGULAR_PASSES,
)
from ocr_response import (
build_first_pass_exit_response,
build_response,
build_scan_exit_response,
public_candidate,
)
from source_classifier import (
candidate_has_heavy_repairs,
classify_full_frame_source,
clean_alnum,
full_frame_can_early_return,
)
from vidalka import extract_chunk_records
reader = easyocr.Reader(["en"], gpu=False)
def empty_best():
return {
"vin": "",
"score": -999,
"confidence": "none",
"rotation": None,
"preprocess": "",
"source_chunk": "",
"raw_text": "",
"reasons": [],
}
def merge_candidates(existing, incoming, limit=20):
by_vin = {candidate["vin"]: candidate for candidate in existing if candidate.get("vin")}
for candidate in incoming:
vin = candidate.get("vin")
if not vin:
continue
current = by_vin.get(vin)
if current is None or candidate["score"] > current["score"]:
by_vin[vin] = candidate
return sorted(by_vin.values(), key=lambda item: item["score"], reverse=True)[:limit]
def vin_like_chunks(chunks):
result = []
for chunk in chunks:
value = chunk.get("chunk", "") if isinstance(chunk, dict) else chunk
cleaned = clean_alnum(value)
if MIN_FIRST_PASS_TEXT_LENGTH <= len(cleaned) <= 24:
result.append(cleaned)
return result
def run_ocr_pass(image, pass_config, index, source="unknown"):
started_at = time.perf_counter()
rotation = pass_config["rotation"]
preprocess = pass_config["preprocess"]
rotated = rotate_image(image, rotation)
prepared = preprocess_image(rotated, preprocess)
results = reader.readtext(prepared, detail=0)
raw_text = " ".join(str(item) for item in results)
cleaned_text = clean_alnum(raw_text)
chunks = extract_chunk_records(results, source=source)
first_pass_chunks = vin_like_chunks(chunks)
candidates = rank_candidates(chunks, rotation=rotation, preprocess=preprocess)
context_chunks = [
chunk for chunk in chunks if chunk.get("context_score", 0) > 0
]
elapsed_ms = round((time.perf_counter() - started_at) * 1000)
return {
"index": index,
"stage": pass_config["stage"],
"rotation": rotation,
"preprocess": preprocess,
"angle_source": pass_config.get("angle_source", ""),
"elapsed_ms": elapsed_ms,
"raw_text": raw_text,
"cleaned_text": cleaned_text,
"cleaned_text_length": len(cleaned_text),
"has_letters": any(char.isalpha() for char in cleaned_text),
"has_digits": any(char.isdigit() for char in cleaned_text),
"chunks_count": len(chunks),
"vin_like_chunks_count": len(first_pass_chunks),
"vin_like_chunks": first_pass_chunks[:5],
"context_chunks_count": len(context_chunks),
"context_chunks": context_chunks[:5],
"candidates_count": len(candidates),
"best": public_candidate(candidates[0]) if candidates else None,
"candidates": candidates,
}
def first_pass_gate_reasons(pass_result):
reasons = []
if pass_result["cleaned_text_length"] < MIN_FIRST_PASS_TEXT_LENGTH:
reasons.append("first_pass_text_too_short")
if not (pass_result["has_letters"] and pass_result["has_digits"]):
reasons.append("first_pass_needs_letters_and_digits")
if pass_result["vin_like_chunks_count"] == 0:
reasons.append("first_pass_no_vin_like_chunk_12_24")
return reasons
def pass_has_vin_signal(pass_result):
return (
pass_result["vin_like_chunks_count"] > 0
or pass_result["candidates_count"] > 0
or pass_result.get("context_chunks_count", 0) > 0
)
def update_best_from_pass(pass_result, best, all_candidates):
all_candidates = merge_candidates(all_candidates, pass_result["candidates"])
if all_candidates and all_candidates[0]["score"] > best["score"]:
best = {
**all_candidates[0],
"raw_text": pass_result["raw_text"],
}
return best, all_candidates
def unique_promising_rotations(passes_used):
rotations = []
for pass_result in passes_used:
if not pass_has_vin_signal(pass_result):
continue
rotation = pass_result["rotation"]
if rotation not in rotations:
rotations.append(rotation)
return rotations
def ranked_promising_rotations(passes_used, limit=MAX_DEEP_PROMISING_ROTATIONS):
by_rotation = {}
for order, pass_result in enumerate(passes_used):
if not pass_has_vin_signal(pass_result):
continue
rotation = pass_result["rotation"]
best = pass_result.get("best") or {}
score = best.get("score", -999)
current = by_rotation.get(rotation)
if current is None or score > current["score"]:
by_rotation[rotation] = {
"rotation": rotation,
"score": score,
"order": order,
}
ranked = sorted(
by_rotation.values(),
key=lambda item: (item["score"], -item["order"]),
reverse=True,
)
return [item["rotation"] for item in ranked[:limit]]
def candidate_has_stable_vin_shape(candidate):
if not candidate:
return False
reasons = candidate.get("reasons", [])
return (
"length:17" in reasons
and "valid_charset" in reasons
and any(reason.startswith("serial_tail_digits") for reason in reasons)
and any(reason.startswith("checksum_match") for reason in reasons)
)
def crop_first_pass_is_empty(pass_result):
return (
pass_result["cleaned_text_length"] < MIN_FIRST_PASS_TEXT_LENGTH
and not (pass_result["has_letters"] and pass_result["has_digits"])
and not pass_has_vin_signal(pass_result)
)
def elapsed_ms_since(started_at):
return round((time.perf_counter() - started_at) * 1000)
def ocr_budget_exceeded(started_at, max_elapsed_ms):
return elapsed_ms_since(started_at) >= max_elapsed_ms
def run_crop_strategy(image, source_mode, started_at, image_debug):
best = empty_best()
all_candidates = []
passes_used = []
image_debug["strategy"] = "crop_fast"
image_debug["source_class"] = {
"class": "camera_crop",
"document_hits": 0,
"plate_hits": 0,
"chunks_count": 0,
"context_chunks_count": 0,
"aspect": round(
(image_debug.get("ocr_width") or image_debug.get("original_width") or 0)
/ max(image_debug.get("ocr_height") or image_debug.get("original_height") or 1, 1),
2,
),
}
for index, pass_config in enumerate(CROP_FAST_PASSES, start=1):
pass_result = run_ocr_pass(image, pass_config, index, source=source_mode)
passes_used.append(pass_result)
best, all_candidates = update_best_from_pass(pass_result, best, all_candidates)
if confidence_from_score(best["score"]) == "high":
return build_response(best, all_candidates, passes_used, started_at, image_debug)
if index == 2 and all_candidates:
return build_response(best, all_candidates, passes_used, started_at, image_debug)
if index == 3 and all_candidates:
return build_response(best, all_candidates, passes_used, started_at, image_debug)
if all_candidates:
return build_response(best, all_candidates, passes_used, started_at, image_debug)
return build_scan_exit_response(
passes_used,
["crop_fast_no_vin_signal"],
started_at,
image_debug,
)
def run_full_frame_strategy(image, source_mode, started_at, image_debug):
best = empty_best()
all_candidates = []
passes_used = []
pass_index = 1
fast_scan_passes = build_full_frame_fast_scan_passes(image)
early_angle_done = False
source_class = "unknown"
image_debug["strategy"] = "full_frame_classified"
image_debug["fast_scan_rotations"] = [
pass_config["rotation"] for pass_config in fast_scan_passes
]
for pass_config in fast_scan_passes[:1]:
pass_result = run_ocr_pass(image, pass_config, pass_index, source=source_mode)
pass_index += 1
passes_used.append(pass_result)
best, all_candidates = update_best_from_pass(pass_result, best, all_candidates)
classification = classify_full_frame_source(pass_result, image_debug)
source_class = classification["class"]
image_debug["source_class"] = classification
if full_frame_can_early_return(best, source_class):
return build_response(best, all_candidates, passes_used, started_at, image_debug)
if ocr_budget_exceeded(started_at, MAX_FULL_FRAME_ELAPSED_MS):
return build_response(best, all_candidates, passes_used, started_at, image_debug)
if passes_used and (
best["score"] >= MIN_FULL_FRAME_ANGLE_PROBE_SCORE
or pass_has_vin_signal(passes_used[0])
):
early_angle_passes = build_angle_probe_passes(
image,
"angle_probe",
include_fixed_45=False,
)
image_debug["angle_probe_rotations"] = [
pass_config["rotation"] for pass_config in early_angle_passes
]
for pass_config in early_angle_passes:
if ocr_budget_exceeded(started_at, MAX_FULL_FRAME_ELAPSED_MS):
return build_response(best, all_candidates, passes_used, started_at, image_debug)
early_angle_done = True
pass_result = run_ocr_pass(image, pass_config, pass_index, source=source_mode)
pass_index += 1
passes_used.append(pass_result)
best, all_candidates = update_best_from_pass(pass_result, best, all_candidates)
if full_frame_can_early_return(best, source_class):
return build_response(best, all_candidates, passes_used, started_at, image_debug)
if source_class == "document" and candidate_has_heavy_repairs(best):
return build_response(best, all_candidates, passes_used, started_at, image_debug)
for pass_config in fast_scan_passes[1:]:
if ocr_budget_exceeded(started_at, MAX_FULL_FRAME_ELAPSED_MS):
return build_response(best, all_candidates, passes_used, started_at, image_debug)
pass_result = run_ocr_pass(image, pass_config, pass_index, source=source_mode)
pass_index += 1
passes_used.append(pass_result)
best, all_candidates = update_best_from_pass(pass_result, best, all_candidates)
if full_frame_can_early_return(best, source_class):
return build_response(best, all_candidates, passes_used, started_at, image_debug)
if ocr_budget_exceeded(started_at, MAX_FULL_FRAME_ELAPSED_MS):
return build_response(best, all_candidates, passes_used, started_at, image_debug)
promising_rotations = unique_promising_rotations(passes_used)
if not promising_rotations:
fast_scan_label = "_".join(str(item["rotation"]) for item in fast_scan_passes)
return build_scan_exit_response(
passes_used,
[f"fast_scan_no_vin_signal_{fast_scan_label}"],
started_at,
image_debug,
)
if best["score"] >= MIN_FULL_FRAME_ANGLE_PROBE_SCORE and not early_angle_done:
for pass_config in build_angle_probe_passes(
image,
"angle_probe",
include_fixed_45=True,
):
if ocr_budget_exceeded(started_at, MAX_FULL_FRAME_ELAPSED_MS):
return build_response(best, all_candidates, passes_used, started_at, image_debug)
pass_result = run_ocr_pass(image, pass_config, pass_index, source=source_mode)
pass_index += 1
passes_used.append(pass_result)
best, all_candidates = update_best_from_pass(pass_result, best, all_candidates)
if full_frame_can_early_return(best, source_class):
return build_response(best, all_candidates, passes_used, started_at, image_debug)
if best["score"] >= FULL_FRAME_STOP_LOW_SCORE and candidate_has_stable_vin_shape(best):
return build_response(best, all_candidates, passes_used, started_at, image_debug)
for pass_config in FULL_FRAME_FOLLOWUP_PASSES:
if ocr_budget_exceeded(started_at, MAX_FULL_FRAME_ELAPSED_MS):
return build_response(best, all_candidates, passes_used, started_at, image_debug)
pass_result = run_ocr_pass(image, pass_config, pass_index, source=source_mode)
pass_index += 1
passes_used.append(pass_result)
best, all_candidates = update_best_from_pass(pass_result, best, all_candidates)
if full_frame_can_early_return(best, source_class):
return build_response(best, all_candidates, passes_used, started_at, image_debug)
if ocr_budget_exceeded(started_at, MAX_FULL_FRAME_ELAPSED_MS):
return build_response(best, all_candidates, passes_used, started_at, image_debug)
promising_rotations = ranked_promising_rotations(passes_used)
for rotation in promising_rotations:
if ocr_budget_exceeded(started_at, MAX_FULL_FRAME_ELAPSED_MS):
return build_response(best, all_candidates, passes_used, started_at, image_debug)
pass_config = {
"stage": "deep_promising",
"rotation": rotation,
"preprocess": "grayscale",
}
pass_result = run_ocr_pass(image, pass_config, pass_index, source=source_mode)
pass_index += 1
passes_used.append(pass_result)
best, all_candidates = update_best_from_pass(pass_result, best, all_candidates)
if full_frame_can_early_return(best, source_class):
return build_response(best, all_candidates, passes_used, started_at, image_debug)
return build_response(best, all_candidates, passes_used, started_at, image_debug)