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()