VIN_OCR / ocr_response.py
Dirner's picture
Upload 4 files
b672a25 verified
Raw History Blame Contribute Delete
7.74 kB
import time
from fastapi.responses import JSONResponse
from gadalka import confidence_from_score
from source_classifier import candidate_has_heavy_repairs
def get_warning(confidence):
if confidence == "none":
return "Не удалось уверенно распознать VIN. Проверьте номер вручную или загрузите более крупное фото."
if confidence == "high":
return "VIN распознан. Проверьте номер перед отправкой."
return "Предварительно распознано. Проверьте номер перед отправкой."
def vehicle_notice(vehicle_type):
if vehicle_type == "commercial":
return {
"special_order": True,
"sales_note": "Коммерческий или грузовой VIN распознан. Такие позиции мы делаем под заказ: оставьте почту и телефон, мы свяжемся с вами.",
}
if vehicle_type == "motorcycle":
return {
"special_order": True,
"sales_note": "VIN мотоцикла распознан. Мотоциклы мы пока не обслуживаем. Можете оставить почту и телефон: мы свяжемся с вами, когда это направление появится.",
}
return {
"special_order": False,
"sales_note": "",
}
def public_candidate(candidate):
return {
"vin": candidate.get("vin", ""),
"score": candidate.get("score", -999),
"confidence": candidate.get("confidence", "none"),
"vehicle_type": candidate.get("vehicle_type", "unknown"),
"rotation": candidate.get("rotation"),
"preprocess": candidate.get("preprocess", ""),
"source_chunk": candidate.get("source_chunk", ""),
"context_score": candidate.get("context_score", 0),
"vag_code": candidate.get("vag_code"),
"opel_code": candidate.get("opel_code"),
"reasons": candidate.get("reasons", []),
}
def pass_summary(pass_result):
summary = {
"index": pass_result["index"],
"stage": pass_result["stage"],
"rotation": pass_result["rotation"],
"preprocess": pass_result["preprocess"],
"elapsed_ms": pass_result["elapsed_ms"],
"cleaned_text_length": pass_result["cleaned_text_length"],
"has_letters": pass_result["has_letters"],
"has_digits": pass_result["has_digits"],
"chunks_count": pass_result["chunks_count"],
"vin_like_chunks_count": pass_result["vin_like_chunks_count"],
"context_chunks_count": pass_result.get("context_chunks_count", 0),
"candidates_count": pass_result["candidates_count"],
"best": pass_result["best"],
}
if pass_result.get("angle_source"):
summary["angle_source"] = pass_result["angle_source"]
return summary
def build_first_pass_exit_response(pass_result, gate_reasons, started_at, image_debug):
elapsed_ms = round((time.perf_counter() - started_at) * 1000)
return JSONResponse(
{
"ok": False,
"vin": "",
"confidence": "none",
"score": -999,
"warning": "VIN не найден на фото. Можно ввести номер вручную или выбрать другое фото.",
"debug": {
"elapsed_ms": elapsed_ms,
"image": image_debug,
"passes_used": [
f"{pass_result['rotation']}:{pass_result['preprocess']}"
],
"passes": [pass_summary(pass_result)],
"rotation": pass_result["rotation"],
"preprocess": pass_result["preprocess"],
"raw_text": pass_result["raw_text"],
"cleaned_text": pass_result["cleaned_text"][:160],
"vin_like_chunks": pass_result["vin_like_chunks"],
"source_chunk": "",
"reasons": gate_reasons,
"candidates": [],
},
}
)
def build_scan_exit_response(passes_used, gate_reasons, started_at, image_debug):
elapsed_ms = round((time.perf_counter() - started_at) * 1000)
last_pass = passes_used[-1] if passes_used else {
"rotation": None,
"preprocess": "",
"raw_text": "",
"cleaned_text": "",
"vin_like_chunks": [],
}
vin_like = []
for pass_result in passes_used:
for chunk in pass_result["vin_like_chunks"]:
if chunk not in vin_like:
vin_like.append(chunk)
return JSONResponse(
{
"ok": False,
"vin": "",
"confidence": "none",
"score": -999,
"warning": "VIN не найден на фото. Можно ввести номер вручную или выбрать другое фото.",
"debug": {
"elapsed_ms": elapsed_ms,
"image": image_debug,
"passes_used": [
f"{item['rotation']}:{item['preprocess']}" for item in passes_used
],
"passes": [pass_summary(item) for item in passes_used],
"rotation": last_pass["rotation"],
"preprocess": last_pass["preprocess"],
"raw_text": last_pass["raw_text"],
"cleaned_text": last_pass["cleaned_text"][:160],
"vin_like_chunks": vin_like[:5],
"source_chunk": "",
"reasons": gate_reasons,
"candidates": [],
},
}
)
def build_response(best, candidates, passes_used, started_at, image_debug):
confidence = confidence_from_score(best["score"])
ok = confidence in {"high", "medium"}
if image_debug.get("source") in {"full_frame", "image", "document"} and confidence != "high":
ok = False
source_class = (image_debug.get("source_class") or {}).get("class")
candidate_risk = []
if confidence == "low":
ok = False
candidate_risk.append("low_confidence_not_inserted")
if source_class == "document" and candidate_has_heavy_repairs(best):
ok = False
candidate_risk.append("document_heavy_repair_not_confirmed")
elapsed_ms = round((time.perf_counter() - started_at) * 1000)
vehicle_type = best.get("vehicle_type", "unknown")
notice = vehicle_notice(vehicle_type)
return JSONResponse(
{
"ok": ok,
"vin": best["vin"] if ok else "",
"confidence": confidence,
"score": best["score"],
"vehicle_type": vehicle_type,
"vag_code": best.get("vag_code"),
"opel_code": best.get("opel_code"),
**notice,
"warning": get_warning(confidence if ok else "none"),
"debug": {
"elapsed_ms": elapsed_ms,
"image": image_debug,
"passes_used": [
f"{item['rotation']}:{item['preprocess']}" for item in passes_used
],
"passes": [pass_summary(item) for item in passes_used],
"rotation": best.get("rotation"),
"preprocess": best.get("preprocess", ""),
"raw_text": best.get("raw_text", ""),
"source_chunk": best.get("source_chunk", ""),
"candidate_risk": candidate_risk,
"reasons": best.get("reasons", []),
"candidates": [public_candidate(candidate) for candidate in candidates[:10]],
},
}
)