File size: 6,388 Bytes
ddd3d9d
abf9a43
 
 
ddd3d9d
0fd798f
ddd3d9d
abf9a43
0fd798f
ddd3d9d
 
8a761b6
 
 
 
 
 
 
0fd798f
2fd7dbf
0fd798f
 
37f6711
 
 
 
 
 
 
 
2660afa
0fd798f
 
015c029
0fd798f
 
1f42688
 
 
 
ddd3d9d
 
 
 
 
 
 
 
 
b7c5537
 
0fd798f
6d28b94
ddd3d9d
0fd798f
cd38e97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
015c029
0fd798f
 
 
7b9c8f6
 
015c029
 
ddd3d9d
 
 
 
 
 
 
 
 
7b9c8f6
ddd3d9d
0fd798f
 
6d28b94
c60d509
2fd7dbf
db1bd33
 
2fd7dbf
db1bd33
abf9a43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
196
197
198
199
200
201
202
203
204
205
import time
import urllib.error
import urllib.parse
import urllib.request

import cv2
import numpy as np
from fastapi import Body, FastAPI, File, Form, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse

from ocr_orchestra import (
    FULL_FRAME_SOURCES,
    MAX_UPLOAD_BYTES,
    prepare_image_for_ocr,
    run_crop_strategy,
    run_full_frame_strategy,
)


app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/")
def home():
    return {"status": "VIN OCR API is running", "endpoint": "/ocr"}


@app.post("/debug-upload")
async def debug_upload(file: UploadFile = File(...)):
    contents = await file.read()

    return JSONResponse(
        {
            "ok": True,
            "filename": file.filename,
            "content_type": file.content_type,
            "size_bytes": len(contents),
            "message": "File reached HuggingFace Space",
        }
    )


@app.post("/ocr")
async def ocr(file: UploadFile = File(...), source: str = Form("unknown")):
    started_at = time.perf_counter()
    contents = await file.read()

    if len(contents) > MAX_UPLOAD_BYTES:
        return JSONResponse(
            {
                "ok": False,
                "vin": "",
                "confidence": "none",
                "score": -999,
                "warning": "Файл слишком большой для OCR. Сожмите фото или выберите фрагмент VIN.",
                "debug": {
                    "elapsed_ms": round((time.perf_counter() - started_at) * 1000),
                    "upload_size_bytes": len(contents),
                    "max_upload_bytes": MAX_UPLOAD_BYTES,
                    "passes_used": [],
                    "passes": [],
                    "candidates": [],
                    "reasons": ["upload_too_large"],
                },
            },
            status_code=413,
        )

    image = cv2.imdecode(np.frombuffer(contents, np.uint8), cv2.IMREAD_COLOR)

    if image is None:
        return JSONResponse(
            {
                "ok": False,
                "vin": "",
                "confidence": "none",
                "score": -999,
                "warning": "Не удалось прочитать изображение.",
                "debug": {
                    "elapsed_ms": round((time.perf_counter() - started_at) * 1000),
                    "passes_used": [],
                    "passes": [],
                    "candidates": [],
                    "reasons": ["image_decode_failed"],
                },
            },
            status_code=400,
        )

    image, image_debug = prepare_image_for_ocr(image, source)
    source_mode = image_debug.get("source", "unknown")

    if source_mode in FULL_FRAME_SOURCES:
        return run_full_frame_strategy(image, source_mode, started_at, image_debug)

    return run_crop_strategy(image, source_mode, started_at, image_debug)


def download_image_url(image_url):
    parsed = urllib.parse.urlparse(image_url)
    if parsed.scheme not in {"http", "https"} or not parsed.netloc:
        return None, "invalid_image_url"

    request = urllib.request.Request(
        image_url,
        headers={
            "User-Agent": "ORIONISPRO-VIN-OCR/1.0",
            "Accept": "image/*,*/*;q=0.8",
        },
    )

    try:
        with urllib.request.urlopen(request, timeout=20) as response:
            content_type = response.headers.get("Content-Type", "")
            contents = response.read(MAX_UPLOAD_BYTES + 1)
    except urllib.error.URLError as error:
        return None, f"url_download_failed:{error.reason}"

    if len(contents) > MAX_UPLOAD_BYTES:
        return None, "url_image_too_large"

    return {
        "contents": contents,
        "content_type": content_type,
        "size_bytes": len(contents),
    }, ""


@app.post("/ocr_url")
async def ocr_url(payload: dict = Body(...)):
    started_at = time.perf_counter()
    image_url = str(payload.get("image_url", "")).strip()
    source = str(payload.get("source", "full_frame")).strip() or "full_frame"
    downloaded, error = download_image_url(image_url)

    if error:
        return JSONResponse(
            {
                "ok": False,
                "vin": "",
                "confidence": "none",
                "score": -999,
                "warning": "Could not download image URL for OCR.",
                "debug": {
                    "elapsed_ms": round((time.perf_counter() - started_at) * 1000),
                    "transport": "url_json",
                    "image_url": image_url,
                    "passes_used": [],
                    "passes": [],
                    "candidates": [],
                    "reasons": [error],
                },
            },
            status_code=400,
        )

    contents = downloaded["contents"]
    image = cv2.imdecode(np.frombuffer(contents, np.uint8), cv2.IMREAD_COLOR)

    if image is None:
        return JSONResponse(
            {
                "ok": False,
                "vin": "",
                "confidence": "none",
                "score": -999,
                "warning": "Could not read image downloaded by URL.",
                "debug": {
                    "elapsed_ms": round((time.perf_counter() - started_at) * 1000),
                    "transport": "url_json",
                    "remote_content_type": downloaded["content_type"],
                    "remote_size_bytes": downloaded["size_bytes"],
                    "passes_used": [],
                    "passes": [],
                    "candidates": [],
                    "reasons": ["image_decode_failed"],
                },
            },
            status_code=400,
        )

    image, image_debug = prepare_image_for_ocr(image, source)
    image_debug.update(
        {
            "transport": "url_json",
            "remote_content_type": downloaded["content_type"],
            "remote_size_bytes": downloaded["size_bytes"],
        }
    )
    source_mode = image_debug.get("source", "unknown")

    if source_mode in FULL_FRAME_SOURCES:
        return run_full_frame_strategy(image, source_mode, started_at, image_debug)

    return run_crop_strategy(image, source_mode, started_at, image_debug)