File size: 7,738 Bytes
8a761b6
 
 
 
 
c024057
8a761b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8e7f4d
b672a25
8a761b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02e2d53
8a761b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02e2d53
8a761b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8e7f4d
8a761b6
 
c024057
 
a8e7f4d
 
 
c024057
 
 
8a761b6
 
 
 
 
 
 
 
 
 
 
a8e7f4d
b672a25
8a761b6
 
 
 
 
 
 
 
 
 
 
 
 
c024057
8a761b6
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
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]],
            },
        }
    )