feat(补贴审核): 新增补贴材料读取与OCR识别组件
| | |
| | | <version>${easyexcel.version}</version> |
| | | </dependency> |
| | | <dependency> |
| | | <groupId>org.apache.pdfbox</groupId> |
| | | <artifactId>pdfbox</artifactId> |
| | | <version>2.0.22</version> |
| | | </dependency> |
| | | <dependency> |
| | | <groupId>io.jsonwebtoken</groupId> |
| | | <artifactId>jjwt</artifactId> |
| | | <version>${jjwt.version}</version> |
| New file |
| | |
| | | package com.trafficaudit.subsidyaudit.dto; |
| | | |
| | | import lombok.Data; |
| | | |
| | | @Data |
| | | public class SubsidyApplicationRow { |
| | | private int excelRow; |
| | | private String plateNumber; |
| | | private String vin; |
| | | private double subsidyStandard; |
| | | private String applicationType; |
| | | } |
| New file |
| | |
| | | package com.trafficaudit.subsidyaudit.dto; |
| | | |
| | | import lombok.Data; |
| | | |
| | | import java.util.ArrayList; |
| | | import java.util.List; |
| | | |
| | | @Data |
| | | public class SubsidyAuditResult { |
| | | private int applicationCount; |
| | | private int invoicePageCount; |
| | | private int passCount; |
| | | private int reviewCount; |
| | | private int failCount; |
| | | private long elapsedMs; |
| | | private List<SubsidyVehicleResult> vehicles = new ArrayList<>(); |
| | | private List<String> globalIssues = new ArrayList<>(); |
| | | } |
| New file |
| | |
| | | package com.trafficaudit.subsidyaudit.dto; |
| | | |
| | | import lombok.Data; |
| | | |
| | | @Data |
| | | public class SubsidyAuditTask { |
| | | private String id; |
| | | private String status; |
| | | private int progress; |
| | | private String message; |
| | | private long createdAt; |
| | | private Long finishedAt; |
| | | private SubsidyAuditResult result; |
| | | } |
| New file |
| | |
| | | package com.trafficaudit.subsidyaudit.dto; |
| | | |
| | | import lombok.Data; |
| | | |
| | | @Data |
| | | public class SubsidyInvoicePage { |
| | | private String sourceFile; |
| | | private int pageNumber; |
| | | private String pageType; |
| | | private String vin; |
| | | private String vinCandidate; |
| | | private String vinMatch; |
| | | private double vinScore; |
| | | private boolean vinEnhanced; |
| | | private Double priceTaxTotal; |
| | | private Double taxAmount; |
| | | private Double amountExcludingTax; |
| | | private String taxRate; |
| | | private java.util.List<String> warnings; |
| | | private String rawText; |
| | | } |
| New file |
| | |
| | | package com.trafficaudit.subsidyaudit.dto; |
| | | |
| | | import lombok.Data; |
| | | |
| | | import java.util.ArrayList; |
| | | import java.util.List; |
| | | |
| | | @Data |
| | | public class SubsidyOcrResponse { |
| | | private List<SubsidyInvoicePage> pages = new ArrayList<>(); |
| | | } |
| New file |
| | |
| | | package com.trafficaudit.subsidyaudit.dto; |
| | | |
| | | import lombok.Data; |
| | | |
| | | import java.util.ArrayList; |
| | | import java.util.List; |
| | | |
| | | @Data |
| | | public class SubsidyVehicleResult { |
| | | private int excelRow; |
| | | private String plateNumber; |
| | | private String applicationVin; |
| | | private double subsidyStandard; |
| | | private String applicationType; |
| | | private String invoiceFile; |
| | | private Integer invoicePage; |
| | | private String invoiceVin; |
| | | private String invoiceVinCandidate; |
| | | private String vinCheck; |
| | | private String amountCheck; |
| | | private Double priceTaxTotal; |
| | | private Double taxAmount; |
| | | private Double amountExcludingTax; |
| | | private String taxRate; |
| | | private String overallStatus; |
| | | private List<String> issues = new ArrayList<>(); |
| | | } |
| New file |
| | |
| | | package com.trafficaudit.subsidyaudit.service; |
| | | |
| | | import com.trafficaudit.subsidyaudit.dto.SubsidyApplicationRow; |
| | | import org.apache.poi.ss.usermodel.Cell; |
| | | import org.apache.poi.ss.usermodel.DataFormatter; |
| | | import org.apache.poi.ss.usermodel.Row; |
| | | import org.apache.poi.ss.usermodel.Sheet; |
| | | import org.apache.poi.ss.usermodel.Workbook; |
| | | import org.apache.poi.ss.usermodel.WorkbookFactory; |
| | | import org.springframework.stereotype.Component; |
| | | import org.springframework.web.multipart.MultipartFile; |
| | | |
| | | import java.io.InputStream; |
| | | import java.util.ArrayList; |
| | | import java.util.Arrays; |
| | | import java.util.HashMap; |
| | | import java.util.HashSet; |
| | | import java.util.List; |
| | | import java.util.Locale; |
| | | import java.util.Map; |
| | | import java.util.Set; |
| | | |
| | | @Component |
| | | public class SubsidyApplicationExcelReader { |
| | | |
| | | private static final List<String> PLATE_HEADERS = Arrays.asList( |
| | | "车牌号码", "车牌号", "号牌号码", "新增车辆号牌", "车辆号牌"); |
| | | private static final List<String> VIN_HEADERS = Arrays.asList( |
| | | "车辆识别代号", "车架号", "VIN", "新增车辆车架号"); |
| | | private static final List<String> STANDARD_HEADERS = Arrays.asList( |
| | | "补贴标准", "申请补贴标准", "补贴金额标准", "补贴标准万元"); |
| | | private static final List<String> TYPE_HEADERS = Arrays.asList( |
| | | "申请资金类型", "申请类型", "资金类型", "补贴类型"); |
| | | |
| | | public List<SubsidyApplicationRow> read(MultipartFile file) { |
| | | if (file == null || file.isEmpty()) { |
| | | throw new IllegalArgumentException("请上传申请表 Excel"); |
| | | } |
| | | String filename = file.getOriginalFilename() == null ? "" : file.getOriginalFilename().toLowerCase(Locale.ROOT); |
| | | if (!filename.endsWith(".xlsx") && !filename.endsWith(".xls")) { |
| | | throw new IllegalArgumentException("申请表必须是 .xlsx 或 .xls 文件"); |
| | | } |
| | | try (InputStream input = file.getInputStream(); Workbook workbook = WorkbookFactory.create(input)) { |
| | | Map<Integer, Integer> columns = null; |
| | | Sheet targetSheet = null; |
| | | int headerRowIndex = -1; |
| | | for (int sheetIndex = 0; sheetIndex < workbook.getNumberOfSheets(); sheetIndex++) { |
| | | Sheet sheet = workbook.getSheetAt(sheetIndex); |
| | | HeaderMatch match = findHeader(sheet); |
| | | if (match != null) { |
| | | targetSheet = sheet; |
| | | columns = match.columns; |
| | | headerRowIndex = match.rowIndex; |
| | | break; |
| | | } |
| | | } |
| | | if (targetSheet == null) { |
| | | throw new IllegalArgumentException("未找到申请表表头,至少需要车牌号码、车辆识别代号、补贴标准三列"); |
| | | } |
| | | return readRows(targetSheet, headerRowIndex, columns); |
| | | } catch (IllegalArgumentException e) { |
| | | throw e; |
| | | } catch (Exception e) { |
| | | throw new IllegalArgumentException("读取申请表失败: " + e.getMessage(), e); |
| | | } |
| | | } |
| | | |
| | | private HeaderMatch findHeader(Sheet sheet) { |
| | | int last = Math.min(sheet.getLastRowNum(), 50); |
| | | DataFormatter formatter = new DataFormatter(Locale.CHINA); |
| | | for (int rowIndex = 0; rowIndex <= last; rowIndex++) { |
| | | Row row = sheet.getRow(rowIndex); |
| | | if (row == null) continue; |
| | | Map<String, Integer> found = new HashMap<>(); |
| | | for (Cell cell : row) { |
| | | String value = normalizeHeader(formatter.formatCellValue(cell)); |
| | | if (value.isEmpty()) continue; |
| | | matchHeader(found, "plate", value, PLATE_HEADERS, cell.getColumnIndex()); |
| | | matchHeader(found, "vin", value, VIN_HEADERS, cell.getColumnIndex()); |
| | | matchHeader(found, "standard", value, STANDARD_HEADERS, cell.getColumnIndex()); |
| | | matchHeader(found, "type", value, TYPE_HEADERS, cell.getColumnIndex()); |
| | | } |
| | | if (found.containsKey("plate") && found.containsKey("vin") && found.containsKey("standard")) { |
| | | Map<Integer, Integer> columns = new HashMap<>(); |
| | | columns.put(0, found.get("plate")); |
| | | columns.put(1, found.get("vin")); |
| | | columns.put(2, found.get("standard")); |
| | | if (found.containsKey("type")) columns.put(3, found.get("type")); |
| | | return new HeaderMatch(rowIndex, columns); |
| | | } |
| | | } |
| | | return null; |
| | | } |
| | | |
| | | private void matchHeader(Map<String, Integer> found, String key, String value, List<String> headers, int columnIndex) { |
| | | if (found.containsKey(key)) return; |
| | | for (String header : headers) { |
| | | String normalized = normalizeHeader(header); |
| | | if (value.equals(normalized) || value.contains(normalized)) { |
| | | found.put(key, columnIndex); |
| | | return; |
| | | } |
| | | } |
| | | } |
| | | |
| | | private List<SubsidyApplicationRow> readRows(Sheet sheet, int headerRowIndex, Map<Integer, Integer> columns) { |
| | | DataFormatter formatter = new DataFormatter(Locale.CHINA); |
| | | List<SubsidyApplicationRow> rows = new ArrayList<>(); |
| | | List<String> errors = new ArrayList<>(); |
| | | Set<String> seenVins = new HashSet<>(); |
| | | for (int rowIndex = headerRowIndex + 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) { |
| | | Row row = sheet.getRow(rowIndex); |
| | | if (row == null) continue; |
| | | String plate = text(row, columns.get(0), formatter); |
| | | String vin = normalizeVin(text(row, columns.get(1), formatter)); |
| | | String standardText = text(row, columns.get(2), formatter); |
| | | String type = columns.containsKey(3) ? text(row, columns.get(3), formatter) : ""; |
| | | if (plate.isEmpty() && vin.isEmpty() && standardText.isEmpty() && type.isEmpty()) continue; |
| | | int excelRow = rowIndex + 1; |
| | | if (!includeNewVehicle(type)) continue; |
| | | if (plate.isEmpty()) errors.add("第 " + excelRow + " 行:车牌号码为空"); |
| | | if (!isValidVin(vin)) errors.add("第 " + excelRow + " 行:车辆识别代号不是 17 位有效 VIN"); |
| | | if (!seenVins.add(vin)) errors.add("第 " + excelRow + " 行:车辆识别代号重复"); |
| | | Double standard = parseSubsidyStandard(standardText); |
| | | if (standard == null) errors.add("第 " + excelRow + " 行:补贴标准无法识别(支持 5.5万元 或 55000元)"); |
| | | SubsidyApplicationRow item = new SubsidyApplicationRow(); |
| | | item.setExcelRow(excelRow); |
| | | item.setPlateNumber(plate.replaceAll("\\s+", "").toUpperCase(Locale.ROOT)); |
| | | item.setVin(vin); |
| | | item.setSubsidyStandard(standard == null ? 0.0 : standard); |
| | | item.setApplicationType(type); |
| | | rows.add(item); |
| | | } |
| | | if (!errors.isEmpty()) { |
| | | throw new IllegalArgumentException(joinErrors(errors)); |
| | | } |
| | | if (rows.isEmpty()) { |
| | | throw new IllegalArgumentException("申请表未读取到新增车辆数据"); |
| | | } |
| | | return rows; |
| | | } |
| | | |
| | | private boolean includeNewVehicle(String type) { |
| | | String value = type == null ? "" : type.replaceAll("\\s+", ""); |
| | | if (value.isEmpty()) return true; |
| | | boolean newVehicle = value.contains("更新") || value.contains("新增") || value.contains("新购") || value.contains("新购置"); |
| | | if (newVehicle) return true; |
| | | return !value.contains("报废"); |
| | | } |
| | | |
| | | private Double parseSubsidyStandard(String raw) { |
| | | if (raw == null || raw.trim().isEmpty()) return null; |
| | | String value = raw.replace(",", "").replace(",", "").trim(); |
| | | boolean tenThousand = value.contains("万"); |
| | | value = value.replace("万元", "").replace("万", "").replace("元", "").trim(); |
| | | try { |
| | | double number = Double.parseDouble(value); |
| | | if (tenThousand || number < 10000.0) number *= 10000.0; |
| | | return number; |
| | | } catch (NumberFormatException e) { |
| | | return null; |
| | | } |
| | | } |
| | | |
| | | private String text(Row row, Integer column, DataFormatter formatter) { |
| | | if (column == null || column < 0) return ""; |
| | | Cell cell = row.getCell(column); |
| | | return cell == null ? "" : formatter.formatCellValue(cell).trim(); |
| | | } |
| | | |
| | | private String normalizeHeader(String value) { |
| | | return value == null ? "" : value.replaceAll("[\\s\\p{Punct}()()【】\\[\\]]", "") |
| | | .replace("(", "").replace(")", "").toUpperCase(Locale.ROOT); |
| | | } |
| | | |
| | | private String normalizeVin(String value) { |
| | | return value == null ? "" : value.replaceAll("[^A-Za-z0-9]", "").toUpperCase(Locale.ROOT); |
| | | } |
| | | |
| | | private boolean isValidVin(String vin) { |
| | | return vin != null && vin.matches("[A-HJ-NPR-Z0-9]{17}"); |
| | | } |
| | | |
| | | private String joinErrors(List<String> errors) { |
| | | int limit = Math.min(errors.size(), 100); |
| | | StringBuilder builder = new StringBuilder("申请表存在错误:"); |
| | | for (int i = 0; i < limit; i++) builder.append("\n").append(errors.get(i)); |
| | | if (errors.size() > limit) builder.append("\n……共 ").append(errors.size()).append(" 行错误"); |
| | | return builder.toString(); |
| | | } |
| | | |
| | | private static class HeaderMatch { |
| | | private final int rowIndex; |
| | | private final Map<Integer, Integer> columns; |
| | | |
| | | private HeaderMatch(int rowIndex, Map<Integer, Integer> columns) { |
| | | this.rowIndex = rowIndex; |
| | | this.columns = columns; |
| | | } |
| | | } |
| | | } |
| New file |
| | |
| | | package com.trafficaudit.subsidyaudit.service; |
| | | |
| | | import org.apache.pdfbox.pdmodel.PDDocument; |
| | | import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException; |
| | | import org.apache.pdfbox.rendering.ImageType; |
| | | import org.apache.pdfbox.rendering.PDFRenderer; |
| | | import org.slf4j.Logger; |
| | | import org.slf4j.LoggerFactory; |
| | | import org.springframework.stereotype.Component; |
| | | |
| | | import javax.imageio.ImageIO; |
| | | import java.awt.image.BufferedImage; |
| | | import java.io.IOException; |
| | | import java.nio.file.Files; |
| | | import java.nio.file.Path; |
| | | import java.util.ArrayList; |
| | | import java.util.List; |
| | | import java.util.Locale; |
| | | import java.util.UUID; |
| | | |
| | | @Component |
| | | public class SubsidyDocumentRenderer { |
| | | private static final Logger log = LoggerFactory.getLogger(SubsidyDocumentRenderer.class); |
| | | private static final int MAX_PAGES = 120; |
| | | private static final float PDF_DPI = 200f; |
| | | |
| | | public List<RenderedPage> render(List<Path> sourceFiles, Path outputDir) throws IOException { |
| | | Files.createDirectories(outputDir); |
| | | List<RenderedPage> pages = new ArrayList<>(); |
| | | for (Path source : sourceFiles) { |
| | | String filename = source.getFileName().toString(); |
| | | String lower = filename.toLowerCase(Locale.ROOT); |
| | | if (lower.endsWith(".pdf")) { |
| | | renderPdf(source, outputDir, pages); |
| | | } else { |
| | | renderImage(source, outputDir, pages); |
| | | } |
| | | if (pages.size() > MAX_PAGES) { |
| | | throw new IllegalArgumentException("证明材料超过 " + MAX_PAGES + " 页,请拆分后上传"); |
| | | } |
| | | } |
| | | return pages; |
| | | } |
| | | |
| | | private void renderPdf(Path source, Path outputDir, List<RenderedPage> pages) throws IOException { |
| | | try (PDDocument document = PDDocument.load(source.toFile())) { |
| | | if (document.isEncrypted()) { |
| | | throw new IllegalArgumentException("PDF 已加密,无法读取: " + source.getFileName()); |
| | | } |
| | | PDFRenderer renderer = new PDFRenderer(document); |
| | | for (int pageIndex = 0; pageIndex < document.getNumberOfPages(); pageIndex++) { |
| | | if (pages.size() >= MAX_PAGES) { |
| | | throw new IllegalArgumentException("证明材料超过 " + MAX_PAGES + " 页,请拆分后上传"); |
| | | } |
| | | BufferedImage image = renderer.renderImageWithDPI(pageIndex, PDF_DPI, ImageType.RGB); |
| | | Path imagePath = outputDir.resolve(String.format(Locale.ROOT, "page-%04d.png", pages.size() + 1)); |
| | | ImageIO.write(image, "png", imagePath.toFile()); |
| | | pages.add(new RenderedPage(imagePath, source.getFileName().toString(), pageIndex + 1)); |
| | | log.info("Rendered subsidy material page {}/{} from {}", pages.size(), document.getNumberOfPages(), source.getFileName()); |
| | | } |
| | | } catch (InvalidPasswordException e) { |
| | | throw new IllegalArgumentException("PDF 已加密,无法读取: " + source.getFileName(), e); |
| | | } |
| | | } |
| | | |
| | | private void renderImage(Path source, Path outputDir, List<RenderedPage> pages) throws IOException { |
| | | BufferedImage image = ImageIO.read(source.toFile()); |
| | | if (image == null) { |
| | | throw new IllegalArgumentException("不支持的图片格式: " + source.getFileName()); |
| | | } |
| | | if (image.getWidth() > 12000 || image.getHeight() > 12000) { |
| | | throw new IllegalArgumentException("图片尺寸过大,请压缩后上传: " + source.getFileName()); |
| | | } |
| | | Path imagePath = outputDir.resolve(String.format(Locale.ROOT, "image-%s.png", UUID.randomUUID().toString().replace("-", ""))); |
| | | ImageIO.write(image, "png", imagePath.toFile()); |
| | | pages.add(new RenderedPage(imagePath, source.getFileName().toString(), 1)); |
| | | } |
| | | |
| | | public static class RenderedPage { |
| | | private final Path imagePath; |
| | | private final String sourceFile; |
| | | private final int pageNumber; |
| | | |
| | | public RenderedPage(Path imagePath, String sourceFile, int pageNumber) { |
| | | this.imagePath = imagePath; |
| | | this.sourceFile = sourceFile; |
| | | this.pageNumber = pageNumber; |
| | | } |
| | | |
| | | public Path getImagePath() { |
| | | return imagePath; |
| | | } |
| | | |
| | | public String getSourceFile() { |
| | | return sourceFile; |
| | | } |
| | | |
| | | public int getPageNumber() { |
| | | return pageNumber; |
| | | } |
| | | } |
| | | } |
| New file |
| | |
| | | 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() |