xyc
昨天 3d684b1b053a2401e0cc924ea85e43a6c17fedc4
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
import argparse
import json
import math
import os
import re
import sys
import unicodedata
 
from PIL import Image, ImageEnhance, ImageOps
from rapidocr_onnxruntime import RapidOCR
 
 
VIN_LABEL_WORDS = ('\u8f66\u8f86\u8bc6\u522b', 'VIN')
INVOICE_WORDS = ('\u673a\u52a8\u8f66\u9500\u552e\u7edf\u4e00\u53d1\u7968', '\u4ef7\u7a0e\u5408\u8ba1')
LICENSE_WORDS = ('\u673a\u52a8\u8f66\u884c\u9a76\u8bc1',)
TRANSPORT_CERT_WORDS = ('\u9053\u8def\u8fd0\u8f93\u8bc1',)
APPLICATION_WORDS = ('\u62a5\u5e9f\u66f4\u65b0\u8d44\u91d1\u7533\u8bf7\u8868',)
 
 
def normalize_text(value):
    value = unicodedata.normalize('NFKC', value or '')
    return re.sub(r'\s+', '', value).upper()
 
 
def normalize_vin(value):
    value = normalize_text(value)
    value = value.replace('O', '0').replace('I', '1').replace('Q', '0')
    return re.sub(r'[^A-HJ-NPR-Z0-9]', '', value)
 
 
def has_any(text, words):
    text = normalize_text(text)
    return any(normalize_text(word) in text for word in words)
 
 
def box_center(box):
    xs = [float(point[0]) for point in box]
    ys = [float(point[1]) for point in box]
    return sum(xs) / 4.0, sum(ys) / 4.0
 
 
def item_text(item):
    return item.get('text') or ''
 
 
def find_label(items, words):
    matches = []
    for item in items:
        text = normalize_text(item_text(item))
        if any(normalize_text(word) in text for word in words):
            matches.append(item)
    return matches
 
 
def extract_vin_candidates(items):
    candidates = []
    for item in items:
        text = normalize_vin(item_text(item))
        for candidate in re.findall(r'[A-HJ-NPR-Z0-9]{17}', text):
            candidates.append((candidate, item))
    return candidates
 
 
def extract_partial_vin(items):
    result = []
    for item in items:
        text = normalize_vin(item_text(item))
        for candidate in re.findall(r'[A-HJ-NPR-Z0-9]{6,16}', text):
            if re.search(r'\d', candidate) and re.search(r'[A-Z]', candidate):
                result.append((candidate, item))
    return result
 
 
def common_suffix_length(left, right):
    count = 0
    for a, b in zip(reversed(left), reversed(right)):
        if a != b:
            break
        count += 1
    return count
 
 
def match_vin(items, expected_vins):
    expected = [(normalize_vin(vin), vin) for vin in expected_vins if normalize_vin(vin)]
    exact_candidates = extract_vin_candidates(items)
    for candidate, item in exact_candidates:
        for normalized, original in expected:
            if candidate == normalized:
                return {
                    'vin': original,
                    'vinCandidate': item_text(item),
                    'vinMatch': 'EXACT',
                    'vinScore': round(float(item.get('score', 0.0)), 4),
                }
    partial = [(normalize_vin(item_text(item)), item) for item in items]
    best = None
    for text, item in partial:
        for normalized, original in expected:
            suffix = common_suffix_length(text, normalized)
            if suffix >= 6 and (best is None or suffix > best[0]):
                best = (suffix, original, item_text(item), item)
    if best:
        return {
            'vin': best[1],
            'vinCandidate': best[2],
            'vinMatch': 'SUFFIX',
            'vinScore': round(float(best[3].get('score', 0.0)), 4),
        }
    return {
        'vin': None,
        'vinCandidate': None,
        'vinMatch': 'NONE',
        'vinScore': 0.0,
    }
 
 
def extract_money_tokens(items):
    tokens = []
    pattern = re.compile(r'[\u00a5\uffe5Xx]?\s*([0-9][0-9,]*\.[0-9]{2})')
    for item in items:
        text = unicodedata.normalize('NFKC', item_text(item))
        for match in pattern.finditer(text):
            raw = match.group(1).replace(',', '')
            try:
                value = float(raw)
            except ValueError:
                continue
            if 0.0 < value < 100000000.0:
                x, y = box_center(item['box'])
                tokens.append((value, x, y, item))
    return tokens
 
 
def nearest_amount(items, money_tokens, words, used_indexes):
    labels = find_label(items, words)
    best = None
    for label in labels:
        if any(word in normalize_text(item_text(label)) for word in ('\u7a0e\u7387', '\u5f81\u6536\u7387')):
            continue
        lx, ly = box_center(label['box'])
        for index, (value, x, y, item) in enumerate(money_tokens):
            if index in used_indexes:
                continue
            score = abs(y - ly) + 0.08 * abs(x - lx)
            if best is None or score < best[0]:
                best = (score, index, value, item_text(item))
    if best is None:
        return None, None
    used_indexes.add(best[1])
    return best[2], best[3]
 
 
def classify(items):
    text = ' '.join(item_text(item) for item in items)
    if has_any(text, INVOICE_WORDS) and has_any(text, VIN_LABEL_WORDS):
        return 'INVOICE'
    if has_any(text, APPLICATION_WORDS):
        return 'APPLICATION'
    if has_any(text, LICENSE_WORDS):
        return 'LICENSE'
    if has_any(text, TRANSPORT_CERT_WORDS):
        return 'TRANSPORT_CERTIFICATE'
    return 'OTHER'
 
 
def crop_vin_region(image_path, items):
    labels = find_label(items, VIN_LABEL_WORDS)
    if not labels:
        return None
    image = Image.open(image_path).convert('RGB')
    width, height = image.size
    label = labels[0]
    lx, ly = box_center(label['box'])
    left = max(0, int(lx - width * 0.16))
    right = min(width, int(lx + width * 0.42))
    top = max(0, int(ly - height * 0.035))
    bottom = min(height, int(ly + height * 0.045))
    crop = image.crop((left, top, right, bottom))
    gray = ImageOps.autocontrast(ImageOps.grayscale(crop), cutoff=1)
    gray = ImageEnhance.Contrast(gray).enhance(2.4)
    gray = ImageEnhance.Sharpness(gray).enhance(2.0)
    return gray.resize((gray.width * 2, gray.height * 2), Image.LANCZOS).convert('RGB')
 
 
def run_ocr(engine, image_path, expected_vins):
    result, _ = engine(image_path)
    items = []
    for line in result or []:
        items.append({
            'box': line[0],
            'text': line[1],
            'score': float(line[2]),
        })
    page_type = classify(items)
    vin_match = match_vin(items, expected_vins)
    if page_type == 'INVOICE' and vin_match['vinMatch'] == 'NONE':
        crop = crop_vin_region(image_path, items)
        if crop is not None:
            enhanced_result, _ = engine(crop)
            enhanced_items = []
            for line in enhanced_result or []:
                enhanced_items.append({
                    'box': line[0],
                    'text': line[1],
                    'score': float(line[2]),
                })
            enhanced_match = match_vin(enhanced_items, expected_vins)
            if enhanced_match['vinMatch'] != 'NONE':
                vin_match = enhanced_match
                vin_match['vinEnhanced'] = True
            elif enhanced_match['vinCandidate']:
                vin_match = enhanced_match
                vin_match['vinEnhanced'] = True
    page = {
        'pageType': page_type,
        'rawText': ' | '.join(item_text(item) for item in items),
        'vin': vin_match['vin'],
        'vinCandidate': vin_match['vinCandidate'],
        'vinMatch': vin_match['vinMatch'],
        'vinScore': vin_match['vinScore'],
        'vinEnhanced': bool(vin_match.get('vinEnhanced', False)),
        'priceTaxTotal': None,
        'taxAmount': None,
        'amountExcludingTax': None,
        'taxRate': None,
        'warnings': [],
    }
    if page_type == 'INVOICE':
        money_tokens = extract_money_tokens(items)
        used = set()
        total, raw_total = nearest_amount(items, money_tokens, ('\u4ef7\u7a0e\u5408\u8ba1',), used)
        tax, raw_tax = nearest_amount(items, money_tokens, ('\u7a0e\u989d',), used)
        no_tax, raw_no_tax = nearest_amount(items, money_tokens, ('\u4e0d\u542b\u7a0e\u4ef7',), used)
        if no_tax is None and total is not None and tax is not None:
            for index, (value, x, y, item) in enumerate(money_tokens):
                if index in used:
                    continue
                if abs(total - tax - value) <= 0.02:
                    no_tax = value
                    raw_no_tax = item_text(item)
                    used.add(index)
                    break
        page['priceTaxTotal'] = total
        page['taxAmount'] = tax
        page['amountExcludingTax'] = no_tax
        page['amountRaw'] = {
            'priceTaxTotal': raw_total,
            'taxAmount': raw_tax,
            'amountExcludingTax': raw_no_tax,
        }
        rate_candidates = re.findall(r'(?:13|9|6|3)%', page['rawText'])
        if rate_candidates:
            page['taxRate'] = rate_candidates[0]
        if total is not None and tax is not None and no_tax is not None:
            if abs(total - tax - no_tax) > 0.02:
                page['warnings'].append('\u4ef7\u7a0e\u5408\u8ba1\u4e0e\u7a0e\u989d+\u4e0d\u542b\u7a0e\u4ef7\u4e0d\u4e00\u81f4')
        elif total is not None:
            page['warnings'].append('\u53d1\u7968\u7a0e\u989d\u6216\u4e0d\u542b\u7a0e\u4ef7\u672a\u8bc6\u522b')
    return page
 
 
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--manifest', required=True)
    parser.add_argument('--output', required=True)
    args = parser.parse_args()
    with open(args.manifest, 'r', encoding='utf-8') as stream:
        manifest = json.load(stream)
    expected_vins = manifest.get('expectedVins', [])
    pages = manifest.get('pages', [])
    engine = RapidOCR()
    results = []
    total = len(pages)
    for index, page_info in enumerate(pages, 1):
        image_path = page_info['imagePath']
        try:
            page = run_ocr(engine, image_path, expected_vins)
            page['sourceFile'] = page_info.get('sourceFile')
            page['pageNumber'] = int(page_info.get('pageNumber', index))
        except Exception as exc:
            page = {
                'sourceFile': page_info.get('sourceFile'),
                'pageNumber': int(page_info.get('pageNumber', index)),
                'pageType': 'ERROR',
                'rawText': '',
                'vin': None,
                'vinCandidate': None,
                'vinMatch': 'NONE',
                'vinScore': 0.0,
                'priceTaxTotal': None,
                'taxAmount': None,
                'amountExcludingTax': None,
                'taxRate': None,
                'warnings': [str(exc)],
            }
        results.append(page)
        print('PROGRESS|%d|%d' % (index, total), flush=True)
    with open(args.output, 'w', encoding='utf-8') as stream:
        json.dump({'pages': results}, stream, ensure_ascii=False, indent=2)
    print('COMPLETE|%d' % total, flush=True)
 
 
if __name__ == '__main__':
    main()