diff --git a/.dockerignore b/.dockerignore index 9105f1a..3e246e2 100644 --- a/.dockerignore +++ b/.dockerignore @@ -14,3 +14,6 @@ docs backend/venv venv .venv +**/*.egg-info +packages/*/build +packages/*/dist diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml index 9cae94e..45587ec 100644 --- a/.github/workflows/docker-publish.yml +++ b/.github/workflows/docker-publish.yml @@ -11,6 +11,24 @@ permissions: contents: read jobs: + core-test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + + - name: Install invoice-core and pytest + run: | + python -m pip install --upgrade pip + pip install ./packages/invoice-core pytest + + - name: Run invoice-core tests + run: pytest packages/invoice-core/tests -v + test: runs-on: ubuntu-latest steps: @@ -45,8 +63,11 @@ jobs: - name: Run backend tests run: docker run --rm invoice-manager:ci-test python -m pytest -q + - name: Run invoice-core tests in backend image + run: docker run --rm invoice-manager:ci-test python -m pytest /packages/invoice-core/tests -v + image: - needs: test + needs: [core-test, test] runs-on: ubuntu-latest permissions: contents: read diff --git a/Dockerfile b/Dockerfile index 8e71d80..5d88795 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,7 +10,7 @@ RUN npm run build FROM python:3.11-slim-bookworm AS backend WORKDIR /app -# Install system dependencies for PaddleOCR and PDF rendering with retry +# Install system dependencies for PaddleOCR with retry RUN for i in 1 2 3 4 5; do \ apt-get update && apt-get install -y --no-install-recommends \ libgomp1 \ @@ -19,16 +19,16 @@ RUN for i in 1 2 3 4 5; do \ libsm6 \ libxext6 \ libxrender1 \ - poppler-utils \ && rm -rf /var/lib/apt/lists/* \ && break; \ if [ "$i" -eq 5 ]; then exit 1; fi; \ sleep 15; \ done -# Install Python dependencies +# Install Python dependencies in a single pass so pip resolves all constraints together COPY backend/requirements.txt . -RUN pip install --no-cache-dir -r requirements.txt +COPY packages/invoice-core /packages/invoice-core +RUN pip install --no-cache-dir -r requirements.txt /packages/invoice-core # Copy backend application COPY backend/ . diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..24ba890 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 stone16 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index ce71409..03b4275 100644 --- a/README.md +++ b/README.md @@ -475,7 +475,7 @@ invoice_manager/ cd backend python -m venv venv source venv/bin/activate # Windows: venv\Scripts\activate -pip install -r requirements.txt +pip install -r requirements.txt -e ../packages/invoice-core uvicorn app.main:app --reload # 前端 | Frontend diff --git a/backend/app/services/invoice_service.py b/backend/app/services/invoice_service.py index 41bb6e6..efb2329 100644 --- a/backend/app/services/invoice_service.py +++ b/backend/app/services/invoice_service.py @@ -3,7 +3,7 @@ import asyncio import logging from concurrent.futures import ThreadPoolExecutor -from typing import Optional, Dict, Any, List, Tuple +from typing import Dict, Any, Tuple from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import select, delete @@ -11,6 +11,14 @@ from app.services.ocr_service import get_ocr_service, get_field_extractor from app.services.llm_service import get_llm_service from app.config import get_settings +from invoice_core.parsers.pdf_text import render_pdf_pages +from invoice_core.reconcile import ( + COMPARABLE_FIELDS, + NUMERIC_FIELDS, + _compare_and_resolve, + _normalize_value, + _values_are_equal, +) logger = logging.getLogger(__name__) settings = get_settings() @@ -22,21 +30,6 @@ _llm_executor = ThreadPoolExecutor(max_workers=settings.llm_max_workers) logger.info(f"Initialized thread pools: OCR={settings.ocr_max_workers}, LLM={settings.llm_max_workers}") -# Fields to compare between OCR and LLM -COMPARABLE_FIELDS = [ - 'invoice_number', - 'issue_date', - 'buyer_name', - 'buyer_tax_id', - 'seller_name', - 'seller_tax_id', - 'item_name', - 'total_with_tax', - 'amount', - 'tax_amount', - 'tax_rate', -] - def _reset_extracted_fields(invoice: Invoice) -> None: """Reset extracted fields to avoid stale values on reprocess.""" @@ -93,12 +86,11 @@ def _run_llm_vision(file_data: bytes, file_type: str) -> Dict[str, Any]: # For PDF, we need to convert first page to image if file_type == 'pdf': try: - from pdf2image import convert_from_bytes from io import BytesIO # Use higher DPI (300) for better text recognition in PDFs # Some PDFs have text rendered as graphics which need higher resolution - images = convert_from_bytes(file_data, dpi=300, first_page=1, last_page=1) + images = render_pdf_pages(file_data, dpi=300, first_page=1, last_page=1) if images: # Convert PIL Image to bytes with high quality buffer = BytesIO() @@ -278,122 +270,6 @@ async def process_invoice(invoice_id: int, db: AsyncSession) -> bool: return False -def _compare_and_resolve( - ocr_fields: Dict[str, Any], - llm_fields: Dict[str, Any], - has_llm: bool -) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: - """Compare OCR and LLM results, resolve differences. - - Args: - ocr_fields: Fields extracted by OCR - llm_fields: Fields extracted by LLM - has_llm: Whether LLM results are available - - Returns: - Tuple of (final_fields, diffs_list) - """ - final_fields = {} - diffs = [] - - for field_name in COMPARABLE_FIELDS: - ocr_value = _normalize_value(ocr_fields.get(field_name)) - llm_value = _normalize_value(llm_fields.get(field_name)) if has_llm else None - - # Determine final value and whether review is needed - if not has_llm: - # No LLM available, use OCR value directly - final_value = ocr_value - source = 'ocr' - needs_review = False - elif _values_are_equal(field_name, ocr_value, llm_value): - # Values match (including numeric equivalence like 330.00 == 330) - final_value = ocr_value or llm_value - source = 'matched' - needs_review = False - elif ocr_value and llm_value: - # Both have values but they differ - needs manual review - final_value = None # Leave blank for manual review - source = 'conflict' - needs_review = True - elif llm_value and not ocr_value: - # LLM found something OCR missed - prefer LLM - final_value = llm_value - source = 'llm' - needs_review = False - else: - # OCR found something LLM missed - prefer OCR - final_value = ocr_value - source = 'ocr' - needs_review = False - - final_fields[field_name] = final_value - - # Record diff if there's a discrepancy or both have values - if has_llm and (ocr_value or llm_value): - diffs.append({ - 'field_name': field_name, - 'ocr_value': ocr_value, - 'llm_value': llm_value, - 'final_value': final_value, - 'source': source, - 'needs_review': needs_review, - }) - - return final_fields, diffs - - -def _normalize_value(value: Any) -> Optional[str]: - """Normalize a value to string for comparison.""" - if value is None: - return None - value_str = str(value).strip() - if not value_str: - return None - return value_str - - -# Fields that should be compared as numbers -NUMERIC_FIELDS = ['total_with_tax', 'amount', 'tax_amount'] - - -def _values_are_equal(field_name: str, value1: Optional[str], value2: Optional[str]) -> bool: - """Compare two values, using numeric comparison for numeric fields. - - Args: - field_name: Name of the field being compared - value1: First value (normalized string) - value2: Second value (normalized string) - - Returns: - True if values are considered equal - """ - # If both are None or empty, they're equal - if not value1 and not value2: - return True - - # If only one is None/empty, they're not equal - if not value1 or not value2: - return False - - # For numeric fields, compare as numbers - if field_name in NUMERIC_FIELDS: - try: - from decimal import Decimal, InvalidOperation - # Remove any currency symbols and whitespace - clean1 = value1.replace('¥', '').replace('¥', '').replace(',', '').strip() - clean2 = value2.replace('¥', '').replace('¥', '').replace(',', '').strip() - num1 = Decimal(clean1) - num2 = Decimal(clean2) - return num1 == num2 - except (InvalidOperation, ValueError): - # Fall back to string comparison if not valid numbers - pass - - # Default to string comparison - return value1 == value2 - - def _update_invoice_from_fields(invoice: Invoice, fields: dict) -> None: """Update invoice fields from extracted data.""" from datetime import datetime diff --git a/backend/app/services/llm_service.py b/backend/app/services/llm_service.py index d31c594..793387f 100644 --- a/backend/app/services/llm_service.py +++ b/backend/app/services/llm_service.py @@ -3,19 +3,18 @@ import base64 import json import logging -import re import threading from abc import ABC, abstractmethod from typing import Optional, Dict, Any from app.config import get_settings +from invoice_core.llm_json import normalize_field_value, parse_json_response # Thread lock for singleton initialization _llm_lock = threading.Lock() from app.services.prompts import ( INVOICE_VISION_PROMPT, INVOICE_VISION_SYSTEM_PROMPT, - REQUIRED_FIELDS, ) logger = logging.getLogger(__name__) @@ -589,79 +588,11 @@ def parse_invoice_from_image(self, image_data: bytes, mime_type: str = "image/pn def _normalize_field_value(self, field_name: str, value: Any) -> Optional[str]: """Normalize and validate a single field value.""" - if value is None: - return None - - if isinstance(value, (int, float)): - value = str(value) - if not isinstance(value, str): - return None - - cleaned = value.strip() - if not cleaned: - return None - - if field_name in ['total_with_tax', 'amount', 'tax_amount']: - cleaned = re.sub(r'[¥¥$€,,\s]', '', cleaned) - match = re.search(r'(\d+(?:\.\d{1,2})?)', cleaned) - return match.group(1) if match else None - - if field_name == 'issue_date': - match = re.search(r'(\d{4})[年/-](\d{1,2})[月/-](\d{1,2})', cleaned) - if match: - year, month, day = match.groups() - return f"{int(year):04d}-{int(month):02d}-{int(day):02d}" - if re.fullmatch(r'\d{4}-\d{2}-\d{2}', cleaned): - return cleaned - return None - - if field_name == 'invoice_number': - cleaned = re.sub(r'[\s-]+', '', cleaned) - return cleaned if re.fullmatch(r'\d{8,20}', cleaned) else None - - if field_name == 'invoice_code': - cleaned = re.sub(r'[\s-]+', '', cleaned) - return cleaned if re.fullmatch(r'\d{10,12}', cleaned) else None - - if field_name in ['buyer_tax_id', 'seller_tax_id']: - cleaned = re.sub(r'\s+', '', cleaned.upper()) - return cleaned if re.fullmatch(r'[A-Z0-9]{15,20}', cleaned) else None - - if field_name == 'tax_rate': - if cleaned == '免税': - return cleaned - return cleaned if re.fullmatch(r'\d+%', cleaned) else None - - return cleaned + return normalize_field_value(field_name, value) def _parse_json_response(self, content: str, provider_name: str) -> Dict[str, Any]: - """Parse JSON from LLM response with schema validation and data cleaning. - - Args: - content: Raw response content from LLM - provider_name: Name of the provider for logging - - Returns: - Parsed and validated dictionary of fields - """ - # Try to extract JSON from response - if content.startswith("```"): - # Remove markdown code blocks - content = content.split("```")[1] - if content.startswith("json"): - content = content[4:] - content = content.strip() - - raw_fields = json.loads(content) - if not isinstance(raw_fields, dict): - raise json.JSONDecodeError("LLM response is not a JSON object", content, 0) - - fields: Dict[str, Optional[str]] = {} - for field in REQUIRED_FIELDS: - fields[field] = self._normalize_field_value(field, raw_fields.get(field)) - - logger.info(f"LLM ({provider_name}) extracted fields: {list(fields.keys())}") - return fields + """Parse JSON from LLM response with schema validation and data cleaning.""" + return parse_json_response(content, provider_name) # Singleton instance diff --git a/backend/app/services/ocr_service.py b/backend/app/services/ocr_service.py index c5d44b8..489c073 100644 --- a/backend/app/services/ocr_service.py +++ b/backend/app/services/ocr_service.py @@ -1,20 +1,20 @@ """OCR processing service for invoice images using PaddleOCR.""" -import re import logging import threading from io import BytesIO -from typing import Optional, Dict, Any, List, Tuple -from datetime import datetime, date +from typing import Any, Dict, List, Optional, Tuple -from PIL import Image import numpy as np +from PIL import Image + +from invoice_core.extract import FieldExtractor, get_field_extractor +from invoice_core.parsers.pdf_text import extract_pdf_text_layer, render_pdf_pages logger = logging.getLogger(__name__) # Thread lock for singleton initialization _ocr_lock = threading.Lock() -_extractor_lock = threading.Lock() class OCRService: @@ -124,59 +124,8 @@ def process_image(self, image_data: bytes) -> Tuple[str, float, List[Dict[str, A raise def _extract_pdf_text_layer(self, pdf_data: bytes) -> tuple[str, bool]: - """Try to extract embedded text from PDF using pdfplumber. - - pdfplumber is more robust than pdftotext for complex PDF structures, - especially Chinese e-invoices which often have unusual text layouts. - - Args: - pdf_data: Raw PDF bytes - - Returns: - Tuple of (extracted_text, has_useful_text) - """ - try: - import pdfplumber - import tempfile - import os - - # Write PDF to temp file - with tempfile.NamedTemporaryFile(suffix='.pdf', delete=False) as f: - f.write(pdf_data) - temp_pdf = f.name - - try: - all_text = [] - with pdfplumber.open(temp_pdf) as pdf: - for page in pdf.pages: - text = page.extract_text() - if text: - all_text.append(text) - - combined_text = "\n".join(all_text) - - # Check if we got meaningful invoice data - # Look for actual invoice content: numbers, dates, amounts - has_invoice_number = bool(re.search(r'\d{10,20}', combined_text)) # Long number (invoice number) - has_tax_id = bool(re.search(r'[A-Z0-9]{15,20}', combined_text)) # Tax ID pattern - has_amount = bool(re.search(r'[¥¥]?\s*\d+\.\d{2}', combined_text)) # Currency amount - has_keywords = any(kw in combined_text for kw in ['发票', '税', '金额', '合计', '购买方', '销售方']) - - # Consider useful if has invoice-like content - has_useful = len(combined_text) > 100 and has_keywords and (has_invoice_number or has_tax_id or has_amount) - - if has_useful: - logger.info(f"PDF text layer extraction successful (pdfplumber): {len(combined_text)} chars") - else: - logger.debug(f"PDF text extraction got {len(combined_text)} chars but no useful invoice data") - - return combined_text, has_useful - finally: - os.unlink(temp_pdf) - - except Exception as e: - logger.warning(f"PDF text layer extraction failed: {e}") - return "", False + """Try to extract embedded text from PDF using invoice_core.""" + return extract_pdf_text_layer(pdf_data) def process_pdf(self, pdf_data: bytes) -> Tuple[str, float, List[Dict[str, Any]]]: """Process PDF and extract text from all pages. @@ -202,11 +151,9 @@ def process_pdf(self, pdf_data: bytes) -> Tuple[str, float, List[Dict[str, Any]] logger.info("PDF has no useful text layer, falling back to OCR") try: - from pdf2image import convert_from_bytes - # Use higher DPI (300) for better text recognition # Some PDFs have text rendered as graphics which need higher resolution - images = convert_from_bytes(pdf_data, dpi=300) + images = render_pdf_pages(pdf_data, dpi=300) logger.info(f"PDF converted to {len(images)} images at 300 DPI") all_text = [] @@ -237,620 +184,8 @@ def process_pdf(self, pdf_data: bytes) -> Tuple[str, float, List[Dict[str, Any]] raise -class FieldExtractor: - """Extracts structured fields from invoice text (Chinese and English).""" - - # Regex patterns for Chinese invoice fields - # Note: PaddleOCR often reads two-column invoices in interleaved order - # This causes buyer/seller info to be mixed. We use position-based extraction. - PATTERNS_CN = { - 'invoice_number': r'发票号码[::]\s*(\d+)', - 'invoice_code': r'发票代码[::]\s*(\d+)', - 'issue_date': r'开票日期[::]\s*(\d{4}年\d{1,2}月\d{1,2}日|\d{4}-\d{1,2}-\d{1,2})', - # For buyer/seller, we use special extraction in extract_fields() method - # These patterns are placeholders - actual extraction uses _extract_buyer_seller() - 'buyer_name': None, # Extracted specially - 'buyer_tax_id': None, # Extracted specially - 'seller_name': None, # Extracted specially - 'seller_tax_id': None, # Extracted specially - # Match items with * markers in Chinese invoices - # Format is typically *类别*商品名称, we want to capture "类别*商品名称" - # Example: *家具*办公椅 → captures "家具*办公椅" - 'item_name': r'\*([^*\n]+(?:\*[^*\n]+)*)', - 'total_with_tax': r'(?:小写|价税合计)[))((]*\s*[¥¥]\s*([\d,.]+)', - 'amount': r'(?:合\s*计|金\s*额)\s*[¥¥]?\s*([\d,.]+)', - 'tax_amount': r'(?:税\s*额\s*[¥¥]?\s*([\d,.]+)|[¥¥]\s*[\d,.]+\s*[¥¥]\s*([\d,.]+))', - 'tax_rate': r'(?:税率[//征收率]*[::]?\s*|金额\n)(\d+%?|免税)', - } - - # Regex patterns for English invoice fields - PATTERNS_EN = { - 'invoice_number': r'(?:Invoice\s*#?|INV[_-]?|#)\s*[:#]?\s*([A-Z0-9_-]+)', - 'issue_date': r'(?:Date|Invoice\s+Date)[:\s]+([A-Za-z]+\s+\d{1,2},?\s+\d{4}|\d{1,2}[/-]\d{1,2}[/-]\d{2,4}|\d{4}[/-]\d{1,2}[/-]\d{1,2})', - 'buyer_name': r'Bill\s*To[:\s]*\n(?:.*\n)*?([A-Za-z][A-Za-z0-9\s]+?)(?:\n\d|\n[A-Z][a-z])', - 'seller_name': r'INVOICE\n#[^\n]+\n([A-Za-z][A-Za-z\s]+)', - 'total_with_tax': r'(?:Total|Balance\s+Due|Amount\s+Due)[:\s]*\$?\s*([\d,.]+)', - 'amount': r'(?:Subtotal)[:\s]*\$?\s*([\d,.]+)', - } - - def _is_chinese_invoice(self, text: str) -> bool: - """Detect if the invoice is in Chinese.""" - chinese_keywords = ['发票', '购买方', '销售方', '税额', '价税合计', '纳税人'] - return any(kw in text for kw in chinese_keywords) - - def _find_label_positions(self, text: str) -> Dict[str, list[int]]: - """Find positions of buyer/seller label markers in text. - - Returns: - Dictionary with 'buyer' and 'seller' keys, each containing - list of character positions where labels were found. - """ - # Define label markers for buyer and seller - buyer_labels = ['购买方', '购方', '购货单位'] - # Seller labels include contextual markers that only appear in seller section - seller_labels = ['销售方', '销方', '销货单位', '开票人', '收款人', '复核'] - - positions: Dict[str, list[int]] = {'buyer': [], 'seller': []} - - for label in buyer_labels: - for match in re.finditer(re.escape(label), text): - positions['buyer'].append(match.start()) - - for label in seller_labels: - for match in re.finditer(re.escape(label), text): - positions['seller'].append(match.start()) - - # Handle vertical text format: 购/买/方 or 销/售/方 (with spaces/newlines) - vertical_buyer = re.finditer(r'购\s*买\s*方', text) - for match in vertical_buyer: - positions['buyer'].append(match.start()) - - vertical_seller = re.finditer(r'销\s*售\s*方', text) - for match in vertical_seller: - positions['seller'].append(match.start()) - - # Handle spaced labels like "购 名称" / "销 名称" and "买 方" / "售 方" - for match in re.finditer(r'购\s*名\s*称', text): - positions['buyer'].append(match.start()) - for match in re.finditer(r'销\s*名\s*称', text): - positions['seller'].append(match.start()) - for match in re.finditer(r'买\s*方', text): - positions['buyer'].append(match.start()) - for match in re.finditer(r'售\s*方', text): - positions['seller'].append(match.start()) - - return positions - - def _find_label_positions_from_lines(self, lines: List[Dict[str, Any]]) -> Dict[str, List[Dict[str, Any]]]: - """Find buyer/seller label lines using OCR line metadata.""" - buyer_labels = ['购买方', '购方', '购货单位'] - seller_labels = ['销售方', '销方', '销货单位', '开票人', '收款人', '复核'] - buyer_patterns = [ - r'购\s*买\s*方', - r'购\s*名\s*称', - r'买\s*方', - ] - seller_patterns = [ - r'销\s*售\s*方', - r'销\s*名\s*称', - r'售\s*方', - ] - - positions: Dict[str, List[Dict[str, Any]]] = {'buyer': [], 'seller': []} - - for line in lines: - text = line.get("text", "") - if any(label in text for label in buyer_labels) or any(re.search(pat, text) for pat in buyer_patterns): - positions['buyer'].append(line) - if any(label in text for label in seller_labels) or any(re.search(pat, text) for pat in seller_patterns): - positions['seller'].append(line) - - return positions - - def _line_distance(self, line: Dict[str, Any], label_line: Dict[str, Any]) -> float: - """Calculate weighted distance between a line and a label line.""" - dy = abs(line["center_y"] - label_line["center_y"]) - dx = abs(line["center_x"] - label_line["center_x"]) - return dy + (dx * 0.3) - - def _classify_line_by_labels(self, line: Dict[str, Any], label_lines: Dict[str, List[Dict[str, Any]]]) -> Optional[str]: - """Classify a line as buyer or seller based on nearest label line.""" - buyer_lines = label_lines.get("buyer", []) - seller_lines = label_lines.get("seller", []) - - def min_distance(lines: List[Dict[str, Any]]) -> float: - if not lines: - return float('inf') - return min(self._line_distance(line, label) for label in lines) - - buyer_dist = min_distance(buyer_lines) - seller_dist = min_distance(seller_lines) - - if buyer_dist == float('inf') and seller_dist == float('inf'): - return None - - max_dist = max(buyer_dist, seller_dist) - if max_dist and abs(buyer_dist - seller_dist) / max_dist < 0.15: - return None - - return 'buyer' if buyer_dist < seller_dist else 'seller' - - def _min_label_distance( - self, - line: Dict[str, Any], - label_lines: Dict[str, List[Dict[str, Any]]], - label_key: str - ) -> float: - lines = label_lines.get(label_key, []) - if not lines: - return float('inf') - return min(self._line_distance(line, label) for label in lines) - - def _normalize_line_text(self, text: str) -> str: - """Normalize OCR line text for matching.""" - return re.sub(r'\s+', '', text or '') - - def _parse_inline_buyer_seller_names(self, text: str) -> Tuple[Optional[str], Optional[str]]: - """Parse buyer/seller names from inline label text.""" - match = re.search(r'购\s*名\s*称[::]\s*(.+?)\s*销\s*名\s*称[::]\s*(.+)', text) - if not match: - return None, None - buyer_name = self._clean_chinese_spaces(match.group(1)) - seller_name = self._clean_chinese_spaces(match.group(2)) - return buyer_name, seller_name - - def _find_line_for_value(self, value: str, lines: List[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - """Find the line containing the given value.""" - if not value: - return None - normalized_value = self._normalize_line_text(value) - for line in lines: - line_text = line.get("text", "") - if value in line_text: - return line - if normalized_value and normalized_value in self._normalize_line_text(line_text): - return line - return None - - def _classify_by_proximity(self, item_pos: int, label_positions: Dict[str, list[int]]) -> str: - """Classify an item as 'buyer' or 'seller' based on nearest label. - - Args: - item_pos: Character position of the item (company name or tax ID) - label_positions: Dictionary from _find_label_positions() - - Returns: - 'buyer' or 'seller' based on which label is closer - """ - def min_distance(positions: list[int]) -> float: - if not positions: - return float('inf') - return min(abs(item_pos - pos) for pos in positions) - - buyer_dist = min_distance(label_positions['buyer']) - seller_dist = min_distance(label_positions['seller']) - - return 'buyer' if buyer_dist < seller_dist else 'seller' - - def _extract_buyer_seller(self, text: str, lines: Optional[List[Dict[str, Any]]] = None) -> Dict[str, Optional[str]]: - """Extract buyer and seller info using label proximity. - - Uses context-aware extraction based on proximity to label markers - (购买方/销售方) rather than relying on match order. This handles - PaddleOCR's interleaved column reading correctly. - - Args: - text: OCR extracted text - - Returns: - Dictionary with buyer_name, buyer_tax_id, seller_name, seller_tax_id - """ - result = { - 'buyer_name': None, - 'buyer_tax_id': None, - 'seller_name': None, - 'seller_tax_id': None, - } - - label_positions = self._find_label_positions(text) - has_labels = bool(label_positions['buyer'] or label_positions['seller']) - - line_labels = None - if lines: - line_labels = self._find_label_positions_from_lines(lines) - - if line_labels and line_labels['buyer'] and line_labels['seller']: - line_result = self._extract_buyer_seller_from_lines(lines, line_labels) - result.update({k: v for k, v in line_result.items() if v}) - - if has_labels: - text_result = self._extract_buyer_seller_from_text(text, label_positions) - for key, value in text_result.items(): - if not result.get(key) and value: - result[key] = value - - if not all(result.values()): - fallback = self._extract_buyer_seller_fallback(text) - for key, value in fallback.items(): - if not result.get(key) and value: - result[key] = value - - if line_labels and (line_labels['buyer'] and line_labels['seller']): - result = self._swap_if_needed(result, lines, line_labels) - - if not has_labels and not (line_labels and (line_labels['buyer'] or line_labels['seller'])): - logger.info("No buyer/seller labels found, using position-based fallback") - - return result - - def _extract_buyer_seller_from_text( - self, - text: str, - label_positions: Dict[str, list[int]] - ) -> Dict[str, Optional[str]]: - """Extract buyer/seller using label proximity in text.""" - result = { - 'buyer_name': None, - 'buyer_tax_id': None, - 'seller_name': None, - 'seller_tax_id': None, - } - - for line in text.splitlines(): - if '购' in line and '销' in line: - buyer_name, seller_name = self._parse_inline_buyer_seller_names(line) - if buyer_name: - result['buyer_name'] = buyer_name - if seller_name: - result['seller_name'] = seller_name - if result['buyer_name'] or result['seller_name']: - break - - name_pattern = r'(?:名\s*)?称[::]\s*(.+)$' - name_matches = [(m.start(), m.group(1)) for m in re.finditer(name_pattern, text, re.MULTILINE)] - - if name_matches and not (result['buyer_name'] and result['seller_name']): - buyers = [] - sellers = [] - - for pos, name in name_matches: - classification = self._classify_by_proximity(pos, label_positions) - cleaned_name = self._clean_chinese_spaces(name) - if classification == 'buyer': - buyers.append(cleaned_name) - else: - sellers.append(cleaned_name) - - if buyers: - result['buyer_name'] = buyers[0] - if sellers: - result['seller_name'] = sellers[0] - - logger.info(f"Label-based extraction: buyer={result['buyer_name']}, seller={result['seller_name']}") - - tax_id_pattern = r'(?:纳税人识别号|统一社会信用代码|税号)[::]\s*([A-Z0-9]{15,20})' - if not result['buyer_tax_id'] and not result['seller_tax_id']: - for line in text.splitlines(): - line_matches = re.findall(tax_id_pattern, line, re.IGNORECASE) - if len(line_matches) >= 2: - result['buyer_tax_id'] = line_matches[0].strip() - result['seller_tax_id'] = line_matches[1].strip() - break - - tax_matches = [(m.start(), m.group(1)) for m in re.finditer(tax_id_pattern, text, re.IGNORECASE)] - - if tax_matches and not (result['buyer_tax_id'] and result['seller_tax_id']): - buyer_tax_ids = [] - seller_tax_ids = [] - - for pos, tax_id in tax_matches: - classification = self._classify_by_proximity(pos, label_positions) - if classification == 'buyer': - buyer_tax_ids.append(tax_id.strip()) - else: - seller_tax_ids.append(tax_id.strip()) - - if buyer_tax_ids: - result['buyer_tax_id'] = buyer_tax_ids[0] - if seller_tax_ids: - result['seller_tax_id'] = seller_tax_ids[0] - - return result - - def _extract_buyer_seller_from_lines( - self, - lines: List[Dict[str, Any]], - label_lines: Dict[str, List[Dict[str, Any]]] - ) -> Dict[str, Optional[str]]: - """Extract buyer/seller fields from OCR lines using label proximity.""" - result = { - 'buyer_name': None, - 'buyer_tax_id': None, - 'seller_name': None, - 'seller_tax_id': None, - } - - buyers: List[Tuple[float, str]] = [] - sellers: List[Tuple[float, str]] = [] - buyer_tax_ids: List[Tuple[float, str]] = [] - seller_tax_ids: List[Tuple[float, str]] = [] - - name_pattern = r'(?:名\s*)?称[::]\s*(.+)$' - tax_id_pattern = r'(?:纳税人识别号|统一社会信用代码|税号)[::]\s*([A-Z0-9]{15,20})' - - for line in lines: - text = line.get("text", "") - inline_buyer, inline_seller = self._parse_inline_buyer_seller_names(text) - if inline_buyer or inline_seller: - if inline_buyer and not result['buyer_name']: - result['buyer_name'] = inline_buyer - if inline_seller and not result['seller_name']: - result['seller_name'] = inline_seller - name_match = re.search(name_pattern, text) - tax_match = re.search(tax_id_pattern, text, re.IGNORECASE) - - classification = self._classify_line_by_labels(line, label_lines) - if name_match and classification: - cleaned_name = self._clean_chinese_spaces(name_match.group(1)) - if classification == 'buyer': - buyers.append((self._min_label_distance(line, label_lines, 'buyer'), cleaned_name)) - else: - sellers.append((self._min_label_distance(line, label_lines, 'seller'), cleaned_name)) - - if tax_match and classification: - tax_id = tax_match.group(1).strip() - if classification == 'buyer': - buyer_tax_ids.append((self._min_label_distance(line, label_lines, 'buyer'), tax_id)) - else: - seller_tax_ids.append((self._min_label_distance(line, label_lines, 'seller'), tax_id)) - - if buyers: - result['buyer_name'] = sorted(buyers, key=lambda x: x[0])[0][1] - if sellers: - result['seller_name'] = sorted(sellers, key=lambda x: x[0])[0][1] - if buyer_tax_ids: - result['buyer_tax_id'] = sorted(buyer_tax_ids, key=lambda x: x[0])[0][1] - if seller_tax_ids: - result['seller_tax_id'] = sorted(seller_tax_ids, key=lambda x: x[0])[0][1] - - return result - - def _swap_if_needed( - self, - result: Dict[str, Optional[str]], - lines: List[Dict[str, Any]], - label_lines: Dict[str, List[Dict[str, Any]]] - ) -> Dict[str, Optional[str]]: - """Swap buyer/seller fields when label proximity indicates reversal.""" - buyer_name = result.get("buyer_name") - seller_name = result.get("seller_name") - - if buyer_name and seller_name: - buyer_line = self._find_line_for_value(buyer_name, lines) - seller_line = self._find_line_for_value(seller_name, lines) - if buyer_line and seller_line: - buyer_class = self._classify_line_by_labels(buyer_line, label_lines) - seller_class = self._classify_line_by_labels(seller_line, label_lines) - if buyer_class == 'seller' and seller_class == 'buyer': - result["buyer_name"], result["seller_name"] = seller_name, buyer_name - logger.info("Swapped buyer/seller names based on label proximity") - - buyer_tax = result.get("buyer_tax_id") - seller_tax = result.get("seller_tax_id") - if buyer_tax and seller_tax: - buyer_line = self._find_line_for_value(buyer_tax, lines) - seller_line = self._find_line_for_value(seller_tax, lines) - if buyer_line and seller_line: - buyer_class = self._classify_line_by_labels(buyer_line, label_lines) - seller_class = self._classify_line_by_labels(seller_line, label_lines) - if buyer_class == 'seller' and seller_class == 'buyer': - result["buyer_tax_id"], result["seller_tax_id"] = seller_tax, buyer_tax - logger.info("Swapped buyer/seller tax IDs based on label proximity") - - return result - - def _extract_buyer_seller_fallback(self, text: str) -> Dict[str, Optional[str]]: - """Fallback position-based extraction when no labels found. - - Uses original logic: first company name = buyer, second = seller. - """ - result = { - 'buyer_name': None, - 'buyer_tax_id': None, - 'seller_name': None, - 'seller_tax_id': None, - } - - # Pattern to match company names - name_pattern = r'(?:名\s*)?称[::]\s*([^销购\n]*?(?:有限公司|股份公司|集团|公司))' - name_matches = re.findall(name_pattern, text) - - if len(name_matches) >= 2: - result['buyer_name'] = self._clean_chinese_spaces(name_matches[0]) - result['seller_name'] = self._clean_chinese_spaces(name_matches[1]) - logger.info(f"Position-based fallback: buyer={result['buyer_name']}, seller={result['seller_name']}") - elif len(name_matches) == 1: - cleaned_name = self._clean_chinese_spaces(name_matches[0]) - # Try to determine from context - if '购' in text[:text.find(name_matches[0])] if name_matches[0] in text else False: - result['buyer_name'] = cleaned_name - else: - result['seller_name'] = cleaned_name - - # Tax IDs - position based - tax_id_pattern = r'(?:纳税人识别号|统一社会信用代码|税号)[::]\s*([A-Z0-9]{15,20})' - tax_matches = re.findall(tax_id_pattern, text, re.IGNORECASE) - - if len(tax_matches) >= 2: - result['buyer_tax_id'] = tax_matches[0].strip() - result['seller_tax_id'] = tax_matches[1].strip() - elif len(tax_matches) == 1: - if result['buyer_name'] and not result['seller_name']: - result['buyer_tax_id'] = tax_matches[0].strip() - elif result['seller_name'] and not result['buyer_name']: - result['seller_tax_id'] = tax_matches[0].strip() - - # Ultimate fallback: simpler pattern - if not result['buyer_name'] and not result['seller_name']: - simple_pattern = r'([^\n]*(?:有限公司|股份公司))' - simple_matches = re.findall(simple_pattern, text) - if len(simple_matches) >= 2: - result['buyer_name'] = self._clean_chinese_spaces(simple_matches[0]) - result['seller_name'] = self._clean_chinese_spaces(simple_matches[1]) - logger.info(f"Ultimate fallback: buyer={result['buyer_name']}, seller={result['seller_name']}") - - return result - - def extract_fields(self, text: str, lines: Optional[List[Dict[str, Any]]] = None) -> Dict[str, Any]: - """Extract all invoice fields from OCR text. - - Args: - text: OCR extracted text - lines: OCR line metadata (with bounding boxes) - - Returns: - Dictionary of extracted fields - """ - fields = {} - - # Log OCR text for debugging (first 500 chars) - logger.debug(f"OCR text (first 500 chars): {text[:500]}") - - is_chinese = self._is_chinese_invoice(text) - - # Choose pattern set based on language detection - if is_chinese: - patterns = self.PATTERNS_CN - else: - patterns = self.PATTERNS_EN - - for field_name, pattern in patterns.items(): - # Skip fields with None pattern (they need special extraction) - if pattern is None: - fields[field_name] = None - continue - - try: - match = re.search(pattern, text, re.IGNORECASE | re.MULTILINE) - if match: - # Handle patterns with multiple capture groups (alternation) - # Use the first non-None group - value = None - for i in range(1, len(match.groups()) + 1): - if match.group(i): - value = match.group(i).strip() - break - fields[field_name] = self._clean_value(value, field_name) if value else None - else: - fields[field_name] = None - except Exception as e: - logger.warning(f"Failed to extract {field_name}: {e}") - fields[field_name] = None - - # For Chinese invoices, use position-based extraction for buyer/seller - if is_chinese: - buyer_seller = self._extract_buyer_seller(text, lines) - fields['buyer_name'] = buyer_seller['buyer_name'] - fields['buyer_tax_id'] = buyer_seller['buyer_tax_id'] - fields['seller_name'] = buyer_seller['seller_name'] - fields['seller_tax_id'] = buyer_seller['seller_tax_id'] - - # Log extraction results for debugging - logger.info(f"OCR extracted: buyer={fields.get('buyer_name')}, seller={fields.get('seller_name')}") - - return fields - - def _clean_chinese_spaces(self, text: str) -> str: - """Remove extra spaces between Chinese characters. - - PDF text extraction often adds spaces between Chinese characters - due to font/layout issues. This function removes those spaces - while preserving spaces around English text. - - Examples: - "深圳那时餐 饮管理有限公司" → "深圳那时餐饮管理有限公司" - "餐 饮服 务" → "餐饮服务" - """ - if not text: - return text - - # Pattern: Chinese char + space(s) + Chinese char - # Remove spaces between Chinese characters - # Chinese Unicode range: \u4e00-\u9fff (CJK Unified Ideographs) - cleaned = re.sub(r'([\u4e00-\u9fff])\s+([\u4e00-\u9fff])', r'\1\2', text) - - # May need multiple passes for consecutive spaces - while re.search(r'[\u4e00-\u9fff]\s+[\u4e00-\u9fff]', cleaned): - cleaned = re.sub(r'([\u4e00-\u9fff])\s+([\u4e00-\u9fff])', r'\1\2', cleaned) - - return cleaned.strip() - - def _clean_value(self, value: str, field_name: str) -> Any: - """Clean and convert field value to appropriate type.""" - if not value: - return None - - # Parse date fields - if field_name == 'issue_date': - return self._parse_date(value) - - # Parse currency fields - if field_name in ['total_with_tax', 'amount', 'tax_amount']: - return self._parse_currency(value) - - # Clean Chinese text fields (remove extra spaces) - if field_name in ['buyer_name', 'seller_name', 'item_name']: - return self._clean_chinese_spaces(value) - - return value - - def _parse_date(self, date_str: str) -> Optional[str]: - """Parse date string to ISO format (supports Chinese and English).""" - if not date_str: - return None - - # Handle Chinese date format (年月日) - date_str = date_str.replace("年", "-").replace("月", "-").replace("日", "") - date_str = date_str.replace("/", "-") - - # Try various date formats - formats = [ - "%Y-%m-%d", # 2018-08-13 - "%m-%d-%Y", # 08-13-2018 - "%d-%m-%Y", # 13-08-2018 - "%B %d, %Y", # August 13, 2018 - "%b %d, %Y", # Aug 13, 2018 - "%B %d %Y", # August 13 2018 - "%b %d %Y", # Aug 13 2018 - ] - - for fmt in formats: - try: - parsed = datetime.strptime(date_str.strip(), fmt) - return parsed.strftime("%Y-%m-%d") - except ValueError: - continue - - return date_str - - def _parse_currency(self, currency_str: str) -> Optional[str]: - """Parse currency string, return as string to preserve precision.""" - if not currency_str: - return None - - # Remove currency symbols and formatting - cleaned = re.sub(r'[$¥¥,\s]', '', currency_str) - - try: - float(cleaned) - return cleaned - except ValueError: - return currency_str - - -# Singleton instances +# Singleton instance _ocr_service: Optional[OCRService] = None -_field_extractor: Optional[FieldExtractor] = None def get_ocr_service() -> OCRService: @@ -864,12 +199,9 @@ def get_ocr_service() -> OCRService: return _ocr_service -def get_field_extractor() -> FieldExtractor: - """Get thread-safe FieldExtractor singleton.""" - global _field_extractor - if _field_extractor is None: - with _extractor_lock: - # Double-check after acquiring lock - if _field_extractor is None: - _field_extractor = FieldExtractor() - return _field_extractor +__all__ = [ + "OCRService", + "FieldExtractor", + "get_ocr_service", + "get_field_extractor", +] diff --git a/backend/app/services/prompts.py b/backend/app/services/prompts.py index 52079cb..293abd3 100644 --- a/backend/app/services/prompts.py +++ b/backend/app/services/prompts.py @@ -1,133 +1,15 @@ -"""Prompts for LLM-based invoice parsing.""" +"""Prompts for LLM-based invoice parsing (re-exported from invoice_core).""" -import json - -# JSON Schema definition for strict output format -INVOICE_JSON_SCHEMA = { - "type": "object", - "properties": { - "invoice_number": { - "type": ["string", "null"], - "description": "发票号码,通常为8-20位数字" - }, - "invoice_code": { - "type": ["string", "null"], - "description": "发票代码,通常为10-12位数字(如有)" - }, - "issue_date": { - "type": ["string", "null"], - "pattern": "^\\d{4}-\\d{2}-\\d{2}$", - "description": "开票日期,格式必须为YYYY-MM-DD" - }, - "buyer_name": { - "type": ["string", "null"], - "description": "购买方名称(公司全称)" - }, - "buyer_tax_id": { - "type": ["string", "null"], - "pattern": "^[A-Z0-9]{15,20}$", - "description": "购买方纳税人识别号,15-20位字母数字" - }, - "seller_name": { - "type": ["string", "null"], - "description": "销售方名称(公司全称)" - }, - "seller_tax_id": { - "type": ["string", "null"], - "pattern": "^[A-Z0-9]{15,20}$", - "description": "销售方纳税人识别号,15-20位字母数字" - }, - "item_name": { - "type": ["string", "null"], - "description": "项目名称/货物名称,如有类别标记(*类别*商品)则保留" - }, - "total_with_tax": { - "type": ["string", "null"], - "pattern": "^\\d+(\\.\\d{1,2})?$", - "description": "价税合计金额,纯数字不含货币符号" - }, - "amount": { - "type": ["string", "null"], - "pattern": "^\\d+(\\.\\d{1,2})?$", - "description": "金额(不含税),纯数字" - }, - "tax_amount": { - "type": ["string", "null"], - "pattern": "^\\d+(\\.\\d{1,2})?$", - "description": "税额,纯数字(免税发票返回\"0\")" - }, - "tax_rate": { - "type": ["string", "null"], - "description": "税率,如\"6%\"、\"13%\"、\"免税\"" - } - }, - "required": [ - "invoice_number", "invoice_code", "issue_date", - "buyer_name", "buyer_tax_id", "seller_name", "seller_tax_id", - "item_name", "total_with_tax", "amount", "tax_amount", "tax_rate" - ], - "additionalProperties": False -} - -# Required fields list for validation -REQUIRED_FIELDS = list(INVOICE_JSON_SCHEMA["required"]) - -# Vision-based system prompt (for direct image analysis) -INVOICE_VISION_SYSTEM_PROMPT = """你是一个专业的中国发票信息提取助手。 -你必须严格按照JSON Schema格式返回结果,无法识别的字段返回null。 -只返回JSON对象,不要包含任何其他文字、解释或markdown代码块标记。""" - -# Build field descriptions for the prompt -_field_descriptions = json.dumps( - {k: v["description"] for k, v in INVOICE_JSON_SCHEMA["properties"].items()}, - ensure_ascii=False, - indent=2 +from invoice_core.prompts import ( + INVOICE_JSON_SCHEMA, + INVOICE_VISION_PROMPT, + INVOICE_VISION_SYSTEM_PROMPT, + REQUIRED_FIELDS, ) -# Vision-based extraction prompt (for direct image analysis) -INVOICE_VISION_PROMPT = f"""请分析这张中国发票图片,提取发票信息。 - -## 输出格式要求(必须严格遵守) - -返回一个JSON对象,必须包含以下12个字段(不能多也不能少): -{_field_descriptions} - -字段类型规则: -- 所有字段值必须是 string 或 null(数值也用字符串表示) -- 日期格式必须是 YYYY-MM-DD -- 金额字段仅包含数字和小数点 -- 税率字段格式如 \"6%\"、\"13%\" 或 \"免税\" -- 不能返回空字符串,用 null 表示缺失 - -## 购买方与销售方识别规则(最重要) - -根据标签文字识别,不要依赖位置: -- 购买方 = 标注为"购买方"、"购方"、"购货单位"的区域 -- 销售方 = 标注为"销售方"、"销方"、"销货单位"的区域 -- 销售方区域通常还有"开票人"、"收款人"、"复核"等字样 - -中国发票格式说明: -- 标准增值税发票:购买方在左上,销售方在左下 -- 电子普通发票:购买方在上部,销售方在底部(价税合计下方) -- 全电发票:购买方和销售方可能左右并排 - -## 字段提取规则 - -1. invoice_number: 查找"发票号码"标签后的数字 -2. invoice_code: 查找"发票代码"标签后的数字(如无则返回null) -3. issue_date: 查找"开票日期",转换为YYYY-MM-DD格式 -4. buyer_name/seller_name: 查找"名称"标签后的公司全称 -5. buyer_tax_id/seller_tax_id: 查找"纳税人识别号"后的15-20位编码 -6. item_name: 查找商品行中的项目名称(可能有*分类*前缀) -7. total_with_tax: 查找"价税合计"或"小写"金额,只返回数字 -8. amount: 查找"金额"或"合计"行的不含税金额 -9. tax_amount: 查找"税额",免税发票返回"0" -10. tax_rate: 查找"税率"列的值,如"6%"、"免税" - -## 数据清洗规则 - -- 金额字段去除¥、¥、$、逗号,只保留数字和小数点 -- 日期统一转换为YYYY-MM-DD -- 无法识别的字段返回null,不要猜测 - -请直接返回JSON对象:""" +__all__ = [ + "INVOICE_JSON_SCHEMA", + "INVOICE_VISION_PROMPT", + "INVOICE_VISION_SYSTEM_PROMPT", + "REQUIRED_FIELDS", +] diff --git a/backend/requirements.txt b/backend/requirements.txt index 5e6d666..97f2ae6 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -24,8 +24,7 @@ python-dotenv==1.0.0 pydantic==2.5.3 pydantic-settings==2.1.0 Pillow==10.2.0 -pdf2image==1.17.0 -pdfplumber==0.10.3 +pdfplumber==0.11.9 openpyxl==3.1.2 # Rate limiting diff --git a/backend/tests/test_core_reexports.py b/backend/tests/test_core_reexports.py new file mode 100644 index 0000000..d4ef137 --- /dev/null +++ b/backend/tests/test_core_reexports.py @@ -0,0 +1,29 @@ +"""Compatibility tests verifying backend re-exports from invoice_core.""" + +import invoice_core +from app.services import invoice_service, ocr_service, prompts +from invoice_core import extract as core_extract +from invoice_core import prompts as core_prompts +from invoice_core import reconcile as core_reconcile + + +def test_ocr_service_reexports_field_extractor(): + assert ocr_service.FieldExtractor is core_extract.FieldExtractor + assert ocr_service.get_field_extractor is core_extract.get_field_extractor + assert ocr_service.get_field_extractor() is core_extract.get_field_extractor() + + +def test_invoice_service_reexports_reconcile_helpers(): + assert invoice_service.COMPARABLE_FIELDS is core_reconcile.COMPARABLE_FIELDS + assert invoice_service.NUMERIC_FIELDS is core_reconcile.NUMERIC_FIELDS + assert invoice_service._normalize_value is core_reconcile.normalize_value + assert invoice_service._values_are_equal is core_reconcile.values_are_equal + assert invoice_service._compare_and_resolve is core_reconcile.compare_and_resolve + + +def test_prompts_module_reexports_core_prompts(): + assert prompts.INVOICE_JSON_SCHEMA is core_prompts.INVOICE_JSON_SCHEMA + assert prompts.REQUIRED_FIELDS is core_prompts.REQUIRED_FIELDS + assert prompts.INVOICE_VISION_SYSTEM_PROMPT is core_prompts.INVOICE_VISION_SYSTEM_PROMPT + assert prompts.INVOICE_VISION_PROMPT is core_prompts.INVOICE_VISION_PROMPT + assert isinstance(invoice_core.__version__, str) and invoice_core.__version__ diff --git a/deploy/README.md b/deploy/README.md index eb48fb0..91d036c 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -93,9 +93,10 @@ ports: - 若维护者已开启 Docker Hub 同步,可将 `image:` 替换为对应的 Docker Hub 镜像地址(或设置环境变量 `INVOICE_IMAGE=/invoice-manager:latest`)。 ### 3. PDF 电子发票能识别,但手机拍的图片 / 扫描件识别失败或进程崩溃? -部分老旧低功耗 NAS CPU(如 Intel J4125、N5105 等赛扬处理器)不支持 AVX 指令集,PaddlePaddle 预编译包在图片 OCR 时可能会因缺少 AVX 报错。 -- **数电 PDF 发票不受影响**:系统会优先通过 `pdfplumber` 直接读取 PDF 文字层,无需触发 PaddleOCR。 -- 若需处理图片/扫描件,建议在「设置」中配置支持看图(Vision)的 LLM 模型,或在支持 AVX 的设备上运行。 +这主要与 **x86 架构** 下部分老旧低功耗 NAS CPU(如 Intel J4125、N5105 等赛扬处理器)不支持 AVX 指令集有关,PaddlePaddle 预编译包在 x86 无 AVX 环境下执行图片 OCR 可能会报错或崩溃: +- **数电 PDF 发票不受 AVX 限制**:系统会优先通过 `pdfplumber` 直接读取 PDF 文字层,无需触发 PaddleOCR,在无 AVX 的 x86 设备上也可正常识别。 +- **x86 无 AVX 设备的纯图片 / 扫描件识别受限**:当前版本图片 / 扫描件识别仍依赖本地 PaddleOCR,在 x86 平台上需要带 AVX 指令集的 CPU,后续版本将补齐无 AVX 降级方案。 +- **ARM64 设备不受 AVX 限制**:ARM64 架构不存在 x86 AVX 概念,已实测可正常拉取运行镜像并执行数电 PDF 文本提取与图片 / 扫描件 OCR。 ### 4. 忘记了设置的 `LLM_CONFIG_TOKEN` 管理员口令怎么重置? - 如果口令写在 Compose 的 `environment` 中:直接修改或注释 `LLM_CONFIG_TOKEN` 一行,然后重建 `app` 容器。 diff --git a/docker-compose.yml b/docker-compose.yml index ca064a1..9235820 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -28,8 +28,10 @@ services: environment: DATABASE_URL: postgresql+asyncpg://postgres:postgres@db:5432/invoice_db DEBUG: "true" + PYTHONPATH: /packages/invoice-core/src volumes: - ./backend:/app + - ./packages/invoice-core:/packages/invoice-core - paddleocr_models:/root/.paddleocr ports: - "18080:18080" @@ -42,7 +44,7 @@ services: timeout: 5s retries: 5 start_period: 30s - command: uvicorn app.main:app --host 0.0.0.0 --port 18080 --reload + command: uvicorn app.main:app --host 0.0.0.0 --port 18080 --reload --reload-dir /app --reload-dir /packages/invoice-core/src frontend: build: diff --git a/packages/invoice-core/pyproject.toml b/packages/invoice-core/pyproject.toml new file mode 100644 index 0000000..056b750 --- /dev/null +++ b/packages/invoice-core/pyproject.toml @@ -0,0 +1,17 @@ +[build-system] +requires = ["setuptools>=68"] +build-backend = "setuptools.build_meta" + +[project] +name = "invoice-core" +version = "0.1.0" +description = "Pure-Python invoice parsing, field extraction, and reconciliation core" +requires-python = ">=3.10" +dependencies = [ + "pdfplumber==0.11.9", + "pypdfium2>=4.30,<6", + "Pillow>=10.0,<13", +] + +[tool.setuptools.packages.find] +where = ["src"] diff --git a/packages/invoice-core/src/invoice_core/__init__.py b/packages/invoice-core/src/invoice_core/__init__.py new file mode 100644 index 0000000..b11a6e0 --- /dev/null +++ b/packages/invoice-core/src/invoice_core/__init__.py @@ -0,0 +1,52 @@ +"""Pure-Python core package for invoice parsing, field extraction, and reconciliation.""" + +from invoice_core.extract import FieldExtractor, get_field_extractor +from invoice_core.llm_json import ( + _normalize_field_value, + _parse_json_response, + normalize_field_value, + parse_json_response, +) +from invoice_core.parsers.pdf_text import extract_pdf_text_layer, render_pdf_pages +from invoice_core.prompts import ( + INVOICE_JSON_SCHEMA, + INVOICE_VISION_PROMPT, + INVOICE_VISION_SYSTEM_PROMPT, + REQUIRED_FIELDS, +) +from invoice_core.reconcile import ( + COMPARABLE_FIELDS, + NUMERIC_FIELDS, + _compare_and_resolve, + _normalize_value, + _values_are_equal, + compare_and_resolve, + normalize_value, + values_are_equal, +) + +__version__ = "0.1.0" + +__all__ = [ + "__version__", + "FieldExtractor", + "get_field_extractor", + "COMPARABLE_FIELDS", + "NUMERIC_FIELDS", + "compare_and_resolve", + "normalize_value", + "values_are_equal", + "_compare_and_resolve", + "_normalize_value", + "_values_are_equal", + "normalize_field_value", + "parse_json_response", + "_normalize_field_value", + "_parse_json_response", + "INVOICE_JSON_SCHEMA", + "REQUIRED_FIELDS", + "INVOICE_VISION_SYSTEM_PROMPT", + "INVOICE_VISION_PROMPT", + "extract_pdf_text_layer", + "render_pdf_pages", +] diff --git a/packages/invoice-core/src/invoice_core/extract.py b/packages/invoice-core/src/invoice_core/extract.py new file mode 100644 index 0000000..a6cb912 --- /dev/null +++ b/packages/invoice-core/src/invoice_core/extract.py @@ -0,0 +1,637 @@ +"""Structured field extraction from invoice text and OCR line metadata.""" + +import logging +import re +import threading +from datetime import datetime +from typing import Any, Dict, List, Optional, Tuple + +logger = logging.getLogger(__name__) + +# Thread lock for singleton initialization +_extractor_lock = threading.Lock() + + +class FieldExtractor: + """Extracts structured fields from invoice text (Chinese and English).""" + + # Regex patterns for Chinese invoice fields + # Note: OCR engines often read two-column invoices in interleaved order + # This causes buyer/seller info to be mixed. We use position-based extraction. + PATTERNS_CN = { + 'invoice_number': r'发票号码[::]\s*(\d+)', + 'invoice_code': r'发票代码[::]\s*(\d+)', + 'issue_date': r'开票日期[::]\s*(\d{4}年\d{1,2}月\d{1,2}日|\d{4}-\d{1,2}-\d{1,2})', + # For buyer/seller, we use special extraction in extract_fields() method + # These patterns are placeholders - actual extraction uses _extract_buyer_seller() + 'buyer_name': None, # Extracted specially + 'buyer_tax_id': None, # Extracted specially + 'seller_name': None, # Extracted specially + 'seller_tax_id': None, # Extracted specially + # Match items with * markers in Chinese invoices + # Format is typically *类别*商品名称, we want to capture "类别*商品名称" + # Example: *家具*办公椅 → captures "家具*办公椅" + 'item_name': r'\*([^*\n]+(?:\*[^*\n]+)*)', + 'total_with_tax': r'(?:小写|价税合计)[))((]*\s*[¥¥]\s*([\d,.]+)', + 'amount': r'(?:合\s*计|金\s*额)\s*[¥¥]?\s*([\d,.]+)', + 'tax_amount': r'(?:税\s*额\s*[¥¥]?\s*([\d,.]+)|[¥¥]\s*[\d,.]+\s*[¥¥]\s*([\d,.]+))', + 'tax_rate': r'(?:税率[//征收率]*[::]?\s*|金额\n)(\d+%?|免税)', + } + + # Regex patterns for English invoice fields + PATTERNS_EN = { + 'invoice_number': r'(?:Invoice\s*#?|INV[_-]?|#)\s*[:#]?\s*([A-Z0-9_-]+)', + 'issue_date': r'(?:Date|Invoice\s+Date)[:\s]+([A-Za-z]+\s+\d{1,2},?\s+\d{4}|\d{1,2}[/-]\d{1,2}[/-]\d{2,4}|\d{4}[/-]\d{1,2}[/-]\d{1,2})', + 'buyer_name': r'Bill\s*To[:\s]*\n(?:.*\n)*?([A-Za-z][A-Za-z0-9\s]+?)(?:\n\d|\n[A-Z][a-z])', + 'seller_name': r'INVOICE\n#[^\n]+\n([A-Za-z][A-Za-z\s]+)', + 'total_with_tax': r'(?:Total|Balance\s+Due|Amount\s+Due)[:\s]*\$?\s*([\d,.]+)', + 'amount': r'(?:Subtotal)[:\s]*\$?\s*([\d,.]+)', + } + + def _is_chinese_invoice(self, text: str) -> bool: + """Detect if the invoice is in Chinese.""" + chinese_keywords = ['发票', '购买方', '销售方', '税额', '价税合计', '纳税人'] + return any(kw in text for kw in chinese_keywords) + + def _find_label_positions(self, text: str) -> Dict[str, list[int]]: + """Find positions of buyer/seller label markers in text. + + Returns: + Dictionary with 'buyer' and 'seller' keys, each containing + list of character positions where labels were found. + """ + # Define label markers for buyer and seller + buyer_labels = ['购买方', '购方', '购货单位'] + # Seller labels include contextual markers that only appear in seller section + seller_labels = ['销售方', '销方', '销货单位', '开票人', '收款人', '复核'] + + positions: Dict[str, list[int]] = {'buyer': [], 'seller': []} + + for label in buyer_labels: + for match in re.finditer(re.escape(label), text): + positions['buyer'].append(match.start()) + + for label in seller_labels: + for match in re.finditer(re.escape(label), text): + positions['seller'].append(match.start()) + + # Handle vertical text format: 购/买/方 or 销/售/方 (with spaces/newlines) + vertical_buyer = re.finditer(r'购\s*买\s*方', text) + for match in vertical_buyer: + positions['buyer'].append(match.start()) + + vertical_seller = re.finditer(r'销\s*售\s*方', text) + for match in vertical_seller: + positions['seller'].append(match.start()) + + # Handle spaced labels like "购 名称" / "销 名称" and "买 方" / "售 方" + for match in re.finditer(r'购\s*名\s*称', text): + positions['buyer'].append(match.start()) + for match in re.finditer(r'销\s*名\s*称', text): + positions['seller'].append(match.start()) + for match in re.finditer(r'买\s*方', text): + positions['buyer'].append(match.start()) + for match in re.finditer(r'售\s*方', text): + positions['seller'].append(match.start()) + + return positions + + def _find_label_positions_from_lines(self, lines: List[Dict[str, Any]]) -> Dict[str, List[Dict[str, Any]]]: + """Find buyer/seller label lines using OCR line metadata.""" + buyer_labels = ['购买方', '购方', '购货单位'] + seller_labels = ['销售方', '销方', '销货单位', '开票人', '收款人', '复核'] + buyer_patterns = [ + r'购\s*买\s*方', + r'购\s*名\s*称', + r'买\s*方', + ] + seller_patterns = [ + r'销\s*售\s*方', + r'销\s*名\s*称', + r'售\s*方', + ] + + positions: Dict[str, List[Dict[str, Any]]] = {'buyer': [], 'seller': []} + + for line in lines: + text = line.get("text", "") + if any(label in text for label in buyer_labels) or any(re.search(pat, text) for pat in buyer_patterns): + positions['buyer'].append(line) + if any(label in text for label in seller_labels) or any(re.search(pat, text) for pat in seller_patterns): + positions['seller'].append(line) + + return positions + + def _line_distance(self, line: Dict[str, Any], label_line: Dict[str, Any]) -> float: + """Calculate weighted distance between a line and a label line.""" + dy = abs(line["center_y"] - label_line["center_y"]) + dx = abs(line["center_x"] - label_line["center_x"]) + return dy + (dx * 0.3) + + def _classify_line_by_labels(self, line: Dict[str, Any], label_lines: Dict[str, List[Dict[str, Any]]]) -> Optional[str]: + """Classify a line as buyer or seller based on nearest label line.""" + buyer_lines = label_lines.get("buyer", []) + seller_lines = label_lines.get("seller", []) + + def min_distance(lines: List[Dict[str, Any]]) -> float: + if not lines: + return float('inf') + return min(self._line_distance(line, label) for label in lines) + + buyer_dist = min_distance(buyer_lines) + seller_dist = min_distance(seller_lines) + + if buyer_dist == float('inf') and seller_dist == float('inf'): + return None + + max_dist = max(buyer_dist, seller_dist) + if max_dist and abs(buyer_dist - seller_dist) / max_dist < 0.15: + return None + + return 'buyer' if buyer_dist < seller_dist else 'seller' + + def _min_label_distance( + self, + line: Dict[str, Any], + label_lines: Dict[str, List[Dict[str, Any]]], + label_key: str + ) -> float: + lines = label_lines.get(label_key, []) + if not lines: + return float('inf') + return min(self._line_distance(line, label) for label in lines) + + def _normalize_line_text(self, text: str) -> str: + """Normalize OCR line text for matching.""" + return re.sub(r'\s+', '', text or '') + + def _parse_inline_buyer_seller_names(self, text: str) -> Tuple[Optional[str], Optional[str]]: + """Parse buyer/seller names from inline label text.""" + match = re.search(r'购\s*名\s*称[::]\s*(.+?)\s*销\s*名\s*称[::]\s*(.+)', text) + if not match: + return None, None + buyer_name = self._clean_chinese_spaces(match.group(1)) + seller_name = self._clean_chinese_spaces(match.group(2)) + return buyer_name, seller_name + + def _find_line_for_value(self, value: str, lines: List[Dict[str, Any]]) -> Optional[Dict[str, Any]]: + """Find the line containing the given value.""" + if not value: + return None + normalized_value = self._normalize_line_text(value) + for line in lines: + line_text = line.get("text", "") + if value in line_text: + return line + if normalized_value and normalized_value in self._normalize_line_text(line_text): + return line + return None + + def _classify_by_proximity(self, item_pos: int, label_positions: Dict[str, list[int]]) -> str: + """Classify an item as 'buyer' or 'seller' based on nearest label. + + Args: + item_pos: Character position of the item (company name or tax ID) + label_positions: Dictionary from _find_label_positions() + + Returns: + 'buyer' or 'seller' based on which label is closer + """ + def min_distance(positions: list[int]) -> float: + if not positions: + return float('inf') + return min(abs(item_pos - pos) for pos in positions) + + buyer_dist = min_distance(label_positions['buyer']) + seller_dist = min_distance(label_positions['seller']) + + return 'buyer' if buyer_dist < seller_dist else 'seller' + + def _extract_buyer_seller(self, text: str, lines: Optional[List[Dict[str, Any]]] = None) -> Dict[str, Optional[str]]: + """Extract buyer and seller info using label proximity. + + Uses context-aware extraction based on proximity to label markers + (购买方/销售方) rather than relying on match order. This handles + interleaved column reading correctly. + + Args: + text: OCR extracted text + + Returns: + Dictionary with buyer_name, buyer_tax_id, seller_name, seller_tax_id + """ + result = { + 'buyer_name': None, + 'buyer_tax_id': None, + 'seller_name': None, + 'seller_tax_id': None, + } + + label_positions = self._find_label_positions(text) + has_labels = bool(label_positions['buyer'] or label_positions['seller']) + + line_labels = None + if lines: + line_labels = self._find_label_positions_from_lines(lines) + + if line_labels and line_labels['buyer'] and line_labels['seller']: + line_result = self._extract_buyer_seller_from_lines(lines, line_labels) + result.update({k: v for k, v in line_result.items() if v}) + + if has_labels: + text_result = self._extract_buyer_seller_from_text(text, label_positions) + for key, value in text_result.items(): + if not result.get(key) and value: + result[key] = value + + if not all(result.values()): + fallback = self._extract_buyer_seller_fallback(text) + for key, value in fallback.items(): + if not result.get(key) and value: + result[key] = value + + if line_labels and (line_labels['buyer'] and line_labels['seller']): + result = self._swap_if_needed(result, lines, line_labels) + + if not has_labels and not (line_labels and (line_labels['buyer'] or line_labels['seller'])): + logger.info("No buyer/seller labels found, using position-based fallback") + + return result + + def _extract_buyer_seller_from_text( + self, + text: str, + label_positions: Dict[str, list[int]] + ) -> Dict[str, Optional[str]]: + """Extract buyer/seller using label proximity in text.""" + result = { + 'buyer_name': None, + 'buyer_tax_id': None, + 'seller_name': None, + 'seller_tax_id': None, + } + + for line in text.splitlines(): + if '购' in line and '销' in line: + buyer_name, seller_name = self._parse_inline_buyer_seller_names(line) + if buyer_name: + result['buyer_name'] = buyer_name + if seller_name: + result['seller_name'] = seller_name + if result['buyer_name'] or result['seller_name']: + break + + name_pattern = r'(?:名\s*)?称[::]\s*(.+)$' + name_matches = [(m.start(), m.group(1)) for m in re.finditer(name_pattern, text, re.MULTILINE)] + + if name_matches and not (result['buyer_name'] and result['seller_name']): + buyers = [] + sellers = [] + + for pos, name in name_matches: + classification = self._classify_by_proximity(pos, label_positions) + cleaned_name = self._clean_chinese_spaces(name) + if classification == 'buyer': + buyers.append(cleaned_name) + else: + sellers.append(cleaned_name) + + if buyers: + result['buyer_name'] = buyers[0] + if sellers: + result['seller_name'] = sellers[0] + + logger.info(f"Label-based extraction: buyer={result['buyer_name']}, seller={result['seller_name']}") + + tax_id_pattern = r'(?:纳税人识别号|统一社会信用代码|税号)[::]\s*([A-Z0-9]{15,20})' + if not result['buyer_tax_id'] and not result['seller_tax_id']: + for line in text.splitlines(): + line_matches = re.findall(tax_id_pattern, line, re.IGNORECASE) + if len(line_matches) >= 2: + result['buyer_tax_id'] = line_matches[0].strip() + result['seller_tax_id'] = line_matches[1].strip() + break + + tax_matches = [(m.start(), m.group(1)) for m in re.finditer(tax_id_pattern, text, re.IGNORECASE)] + + if tax_matches and not (result['buyer_tax_id'] and result['seller_tax_id']): + buyer_tax_ids = [] + seller_tax_ids = [] + + for pos, tax_id in tax_matches: + classification = self._classify_by_proximity(pos, label_positions) + if classification == 'buyer': + buyer_tax_ids.append(tax_id.strip()) + else: + seller_tax_ids.append(tax_id.strip()) + + if buyer_tax_ids: + result['buyer_tax_id'] = buyer_tax_ids[0] + if seller_tax_ids: + result['seller_tax_id'] = seller_tax_ids[0] + + return result + + def _extract_buyer_seller_from_lines( + self, + lines: List[Dict[str, Any]], + label_lines: Dict[str, List[Dict[str, Any]]] + ) -> Dict[str, Optional[str]]: + """Extract buyer/seller fields from OCR lines using label proximity.""" + result = { + 'buyer_name': None, + 'buyer_tax_id': None, + 'seller_name': None, + 'seller_tax_id': None, + } + + buyers: List[Tuple[float, str]] = [] + sellers: List[Tuple[float, str]] = [] + buyer_tax_ids: List[Tuple[float, str]] = [] + seller_tax_ids: List[Tuple[float, str]] = [] + + name_pattern = r'(?:名\s*)?称[::]\s*(.+)$' + tax_id_pattern = r'(?:纳税人识别号|统一社会信用代码|税号)[::]\s*([A-Z0-9]{15,20})' + + for line in lines: + text = line.get("text", "") + inline_buyer, inline_seller = self._parse_inline_buyer_seller_names(text) + if inline_buyer or inline_seller: + if inline_buyer and not result['buyer_name']: + result['buyer_name'] = inline_buyer + if inline_seller and not result['seller_name']: + result['seller_name'] = inline_seller + name_match = re.search(name_pattern, text) + tax_match = re.search(tax_id_pattern, text, re.IGNORECASE) + + classification = self._classify_line_by_labels(line, label_lines) + if name_match and classification: + cleaned_name = self._clean_chinese_spaces(name_match.group(1)) + if classification == 'buyer': + buyers.append((self._min_label_distance(line, label_lines, 'buyer'), cleaned_name)) + else: + sellers.append((self._min_label_distance(line, label_lines, 'seller'), cleaned_name)) + + if tax_match and classification: + tax_id = tax_match.group(1).strip() + if classification == 'buyer': + buyer_tax_ids.append((self._min_label_distance(line, label_lines, 'buyer'), tax_id)) + else: + seller_tax_ids.append((self._min_label_distance(line, label_lines, 'seller'), tax_id)) + + if buyers: + result['buyer_name'] = sorted(buyers, key=lambda x: x[0])[0][1] + if sellers: + result['seller_name'] = sorted(sellers, key=lambda x: x[0])[0][1] + if buyer_tax_ids: + result['buyer_tax_id'] = sorted(buyer_tax_ids, key=lambda x: x[0])[0][1] + if seller_tax_ids: + result['seller_tax_id'] = sorted(seller_tax_ids, key=lambda x: x[0])[0][1] + + return result + + def _swap_if_needed( + self, + result: Dict[str, Optional[str]], + lines: List[Dict[str, Any]], + label_lines: Dict[str, List[Dict[str, Any]]] + ) -> Dict[str, Optional[str]]: + """Swap buyer/seller fields when label proximity indicates reversal.""" + buyer_name = result.get("buyer_name") + seller_name = result.get("seller_name") + + if buyer_name and seller_name: + buyer_line = self._find_line_for_value(buyer_name, lines) + seller_line = self._find_line_for_value(seller_name, lines) + if buyer_line and seller_line: + buyer_class = self._classify_line_by_labels(buyer_line, label_lines) + seller_class = self._classify_line_by_labels(seller_line, label_lines) + if buyer_class == 'seller' and seller_class == 'buyer': + result["buyer_name"], result["seller_name"] = seller_name, buyer_name + logger.info("Swapped buyer/seller names based on label proximity") + + buyer_tax = result.get("buyer_tax_id") + seller_tax = result.get("seller_tax_id") + if buyer_tax and seller_tax: + buyer_line = self._find_line_for_value(buyer_tax, lines) + seller_line = self._find_line_for_value(seller_tax, lines) + if buyer_line and seller_line: + buyer_class = self._classify_line_by_labels(buyer_line, label_lines) + seller_class = self._classify_line_by_labels(seller_line, label_lines) + if buyer_class == 'seller' and seller_class == 'buyer': + result["buyer_tax_id"], result["seller_tax_id"] = seller_tax, buyer_tax + logger.info("Swapped buyer/seller tax IDs based on label proximity") + + return result + + def _extract_buyer_seller_fallback(self, text: str) -> Dict[str, Optional[str]]: + """Fallback position-based extraction when no labels found. + + Uses original logic: first company name = buyer, second = seller. + """ + result = { + 'buyer_name': None, + 'buyer_tax_id': None, + 'seller_name': None, + 'seller_tax_id': None, + } + + # Pattern to match company names + name_pattern = r'(?:名\s*)?称[::]\s*([^销购\n]*?(?:有限公司|股份公司|集团|公司))' + name_matches = re.findall(name_pattern, text) + + if len(name_matches) >= 2: + result['buyer_name'] = self._clean_chinese_spaces(name_matches[0]) + result['seller_name'] = self._clean_chinese_spaces(name_matches[1]) + logger.info(f"Position-based fallback: buyer={result['buyer_name']}, seller={result['seller_name']}") + elif len(name_matches) == 1: + cleaned_name = self._clean_chinese_spaces(name_matches[0]) + # Try to determine from context + if '购' in text[:text.find(name_matches[0])] if name_matches[0] in text else False: + result['buyer_name'] = cleaned_name + else: + result['seller_name'] = cleaned_name + + # Tax IDs - position based + tax_id_pattern = r'(?:纳税人识别号|统一社会信用代码|税号)[::]\s*([A-Z0-9]{15,20})' + tax_matches = re.findall(tax_id_pattern, text, re.IGNORECASE) + + if len(tax_matches) >= 2: + result['buyer_tax_id'] = tax_matches[0].strip() + result['seller_tax_id'] = tax_matches[1].strip() + elif len(tax_matches) == 1: + if result['buyer_name'] and not result['seller_name']: + result['buyer_tax_id'] = tax_matches[0].strip() + elif result['seller_name'] and not result['buyer_name']: + result['seller_tax_id'] = tax_matches[0].strip() + + # Ultimate fallback: simpler pattern + if not result['buyer_name'] and not result['seller_name']: + simple_pattern = r'([^\n]*(?:有限公司|股份公司))' + simple_matches = re.findall(simple_pattern, text) + if len(simple_matches) >= 2: + result['buyer_name'] = self._clean_chinese_spaces(simple_matches[0]) + result['seller_name'] = self._clean_chinese_spaces(simple_matches[1]) + logger.info(f"Ultimate fallback: buyer={result['buyer_name']}, seller={result['seller_name']}") + + return result + + def extract_fields(self, text: str, lines: Optional[List[Dict[str, Any]]] = None) -> Dict[str, Any]: + """Extract all invoice fields from OCR text. + + Args: + text: OCR extracted text + lines: OCR line metadata (with bounding boxes) + + Returns: + Dictionary of extracted fields + """ + fields = {} + + # Log OCR text for debugging (first 500 chars) + logger.debug(f"OCR text (first 500 chars): {text[:500]}") + + is_chinese = self._is_chinese_invoice(text) + + # Choose pattern set based on language detection + if is_chinese: + patterns = self.PATTERNS_CN + else: + patterns = self.PATTERNS_EN + + for field_name, pattern in patterns.items(): + # Skip fields with None pattern (they need special extraction) + if pattern is None: + fields[field_name] = None + continue + + try: + match = re.search(pattern, text, re.IGNORECASE | re.MULTILINE) + if match: + # Handle patterns with multiple capture groups (alternation) + # Use the first non-None group + value = None + for i in range(1, len(match.groups()) + 1): + if match.group(i): + value = match.group(i).strip() + break + fields[field_name] = self._clean_value(value, field_name) if value else None + else: + fields[field_name] = None + except Exception as e: + logger.warning(f"Failed to extract {field_name}: {e}") + fields[field_name] = None + + # For Chinese invoices, use position-based extraction for buyer/seller + if is_chinese: + buyer_seller = self._extract_buyer_seller(text, lines) + fields['buyer_name'] = buyer_seller['buyer_name'] + fields['buyer_tax_id'] = buyer_seller['buyer_tax_id'] + fields['seller_name'] = buyer_seller['seller_name'] + fields['seller_tax_id'] = buyer_seller['seller_tax_id'] + + # Log extraction results for debugging + logger.info(f"OCR extracted: buyer={fields.get('buyer_name')}, seller={fields.get('seller_name')}") + + return fields + + def _clean_chinese_spaces(self, text: str) -> str: + """Remove extra spaces between Chinese characters. + + PDF text extraction often adds spaces between Chinese characters + due to font/layout issues. This function removes those spaces + while preserving spaces around English text. + + Examples: + "深圳那时餐 饮管理有限公司" → "深圳那时餐饮管理有限公司" + "餐 饮服 务" → "餐饮服务" + """ + if not text: + return text + + # Pattern: Chinese char + space(s) + Chinese char + # Remove spaces between Chinese characters + # Chinese Unicode range: \u4e00-\u9fff (CJK Unified Ideographs) + cleaned = re.sub(r'([\u4e00-\u9fff])\s+([\u4e00-\u9fff])', r'\1\2', text) + + # May need multiple passes for consecutive spaces + while re.search(r'[\u4e00-\u9fff]\s+[\u4e00-\u9fff]', cleaned): + cleaned = re.sub(r'([\u4e00-\u9fff])\s+([\u4e00-\u9fff])', r'\1\2', cleaned) + + return cleaned.strip() + + def _clean_value(self, value: str, field_name: str) -> Any: + """Clean and convert field value to appropriate type.""" + if not value: + return None + + # Parse date fields + if field_name == 'issue_date': + return self._parse_date(value) + + # Parse currency fields + if field_name in ['total_with_tax', 'amount', 'tax_amount']: + return self._parse_currency(value) + + # Clean Chinese text fields (remove extra spaces) + if field_name in ['buyer_name', 'seller_name', 'item_name']: + return self._clean_chinese_spaces(value) + + return value + + def _parse_date(self, date_str: str) -> Optional[str]: + """Parse date string to ISO format (supports Chinese and English).""" + if not date_str: + return None + + # Handle Chinese date format (年月日) + date_str = date_str.replace("年", "-").replace("月", "-").replace("日", "") + date_str = date_str.replace("/", "-") + + # Try various date formats + formats = [ + "%Y-%m-%d", # 2018-08-13 + "%m-%d-%Y", # 08-13-2018 + "%d-%m-%Y", # 13-08-2018 + "%B %d, %Y", # August 13, 2018 + "%b %d, %Y", # Aug 13, 2018 + "%B %d %Y", # August 13 2018 + "%b %d %Y", # Aug 13 2018 + ] + + for fmt in formats: + try: + parsed = datetime.strptime(date_str.strip(), fmt) + return parsed.strftime("%Y-%m-%d") + except ValueError: + continue + + return date_str + + def _parse_currency(self, currency_str: str) -> Optional[str]: + """Parse currency string, return as string to preserve precision.""" + if not currency_str: + return None + + # Remove currency symbols and formatting + cleaned = re.sub(r'[$¥¥,\s]', '', currency_str) + + try: + float(cleaned) + return cleaned + except ValueError: + return currency_str + + +_field_extractor: Optional[FieldExtractor] = None + + +def get_field_extractor() -> FieldExtractor: + """Get thread-safe FieldExtractor singleton.""" + global _field_extractor + if _field_extractor is None: + with _extractor_lock: + # Double-check after acquiring lock + if _field_extractor is None: + _field_extractor = FieldExtractor() + return _field_extractor diff --git a/packages/invoice-core/src/invoice_core/llm_json.py b/packages/invoice-core/src/invoice_core/llm_json.py new file mode 100644 index 0000000..20ddca9 --- /dev/null +++ b/packages/invoice-core/src/invoice_core/llm_json.py @@ -0,0 +1,93 @@ +"""JSON parsing and field normalization for LLM invoice responses.""" + +import json +import logging +import re +from typing import Any, Dict, Optional + +from invoice_core.prompts import REQUIRED_FIELDS + +logger = logging.getLogger(__name__) + + +def normalize_field_value(field_name: str, value: Any) -> Optional[str]: + """Normalize and validate a single field value.""" + if value is None: + return None + + if isinstance(value, (int, float)): + value = str(value) + if not isinstance(value, str): + return None + + cleaned = value.strip() + if not cleaned: + return None + + if field_name in ['total_with_tax', 'amount', 'tax_amount']: + cleaned = re.sub(r'[¥¥$€,,\s]', '', cleaned) + match = re.search(r'(\d+(?:\.\d{1,2})?)', cleaned) + return match.group(1) if match else None + + if field_name == 'issue_date': + match = re.search(r'(\d{4})[年/-](\d{1,2})[月/-](\d{1,2})', cleaned) + if match: + year, month, day = match.groups() + return f"{int(year):04d}-{int(month):02d}-{int(day):02d}" + if re.fullmatch(r'\d{4}-\d{2}-\d{2}', cleaned): + return cleaned + return None + + if field_name == 'invoice_number': + cleaned = re.sub(r'[\s-]+', '', cleaned) + return cleaned if re.fullmatch(r'\d{8,20}', cleaned) else None + + if field_name == 'invoice_code': + cleaned = re.sub(r'[\s-]+', '', cleaned) + return cleaned if re.fullmatch(r'\d{10,12}', cleaned) else None + + if field_name in ['buyer_tax_id', 'seller_tax_id']: + cleaned = re.sub(r'\s+', '', cleaned.upper()) + return cleaned if re.fullmatch(r'[A-Z0-9]{15,20}', cleaned) else None + + if field_name == 'tax_rate': + if cleaned == '免税': + return cleaned + return cleaned if re.fullmatch(r'\d+%', cleaned) else None + + return cleaned + + +def parse_json_response(content: str, provider_name: str = "llm") -> Dict[str, Any]: + """Parse JSON from LLM response by verifying a JSON object, ignoring unknown keys, and normalizing expected fields. + + Args: + content: Raw response content from LLM + provider_name: Name of the provider for logging + + Returns: + Normalized dictionary of expected invoice fields + """ + # Try to extract JSON from response + if content.startswith("```"): + # Remove markdown code blocks + content = content.split("```")[1] + if content.startswith("json"): + content = content[4:] + content = content.strip() + + raw_fields = json.loads(content) + if not isinstance(raw_fields, dict): + raise json.JSONDecodeError("LLM response is not a JSON object", content, 0) + + fields: Dict[str, Optional[str]] = {} + for field in REQUIRED_FIELDS: + fields[field] = normalize_field_value(field, raw_fields.get(field)) + + logger.info(f"LLM ({provider_name}) extracted fields: {list(fields.keys())}") + return fields + + +# Compatibility aliases matching original backend method/helper names +_normalize_field_value = normalize_field_value +_parse_json_response = parse_json_response diff --git a/packages/invoice-core/src/invoice_core/parsers/__init__.py b/packages/invoice-core/src/invoice_core/parsers/__init__.py new file mode 100644 index 0000000..dc0facd --- /dev/null +++ b/packages/invoice-core/src/invoice_core/parsers/__init__.py @@ -0,0 +1,8 @@ +"""Document parsers for invoice-core.""" + +from invoice_core.parsers.pdf_text import extract_pdf_text_layer, render_pdf_pages + +__all__ = [ + "extract_pdf_text_layer", + "render_pdf_pages", +] diff --git a/packages/invoice-core/src/invoice_core/parsers/pdf_text.py b/packages/invoice-core/src/invoice_core/parsers/pdf_text.py new file mode 100644 index 0000000..a9770a2 --- /dev/null +++ b/packages/invoice-core/src/invoice_core/parsers/pdf_text.py @@ -0,0 +1,125 @@ +"""PDF text-layer extraction (pdfplumber) and page rendering (pypdfium2).""" + +import logging +import re +import threading +from io import BytesIO +from typing import List, Optional + +from PIL import Image + +logger = logging.getLogger(__name__) + +# PDFium is not thread-safe; serialize all pypdfium2 calls within the process. +_PDFIUM_LOCK = threading.Lock() + + +def extract_pdf_text_layer(pdf_data: bytes) -> tuple[str, bool]: + """Try to extract embedded text from PDF using pdfplumber. + + pdfplumber is more robust than pdftotext for complex PDF structures, + especially Chinese e-invoices which often have unusual text layouts. + + Args: + pdf_data: Raw PDF bytes + + Returns: + Tuple of (extracted_text, has_useful_text) + """ + try: + import pdfplumber + + all_text = [] + with pdfplumber.open(BytesIO(pdf_data)) as pdf: + for page in pdf.pages: + text = page.extract_text() + if text: + all_text.append(text) + + combined_text = "\n".join(all_text) + + # Check if we got meaningful invoice data + # Look for actual invoice content: numbers, dates, amounts + has_invoice_number = bool(re.search(r'\d{10,20}', combined_text)) # Long number (invoice number) + has_tax_id = bool(re.search(r'[A-Z0-9]{15,20}', combined_text)) # Tax ID pattern + has_amount = bool(re.search(r'[¥¥]?\s*\d+\.\d{2}', combined_text)) # Currency amount + has_keywords = any(kw in combined_text for kw in ['发票', '税', '金额', '合计', '购买方', '销售方']) + + # Consider useful if has invoice-like content + has_useful = len(combined_text) > 100 and has_keywords and (has_invoice_number or has_tax_id or has_amount) + + if has_useful: + logger.info(f"PDF text layer extraction successful (pdfplumber): {len(combined_text)} chars") + else: + logger.debug(f"PDF text extraction got {len(combined_text)} chars but no useful invoice data") + + return combined_text, has_useful + + except Exception as e: + logger.warning(f"PDF text layer extraction failed: {e}") + return "", False + + +def render_pdf_pages( + pdf_data: bytes, + dpi: int = 300, + first_page: Optional[int] = None, + last_page: Optional[int] = None, +) -> List[Image.Image]: + """Render PDF pages to RGB PIL Images using pypdfium2. + + Args: + pdf_data: Raw PDF bytes + dpi: Rendering resolution in dots per inch (default 300) + first_page: Optional 1-based inclusive start page + last_page: Optional 1-based inclusive end page + + Returns: + List of rendered PIL.Image.Image instances in RGB mode + """ + import pypdfium2 as pdfium + + scale = dpi / 72.0 + images: List[Image.Image] = [] + with _PDFIUM_LOCK: + pdf = pdfium.PdfDocument(pdf_data) + try: + total_pages = len(pdf) + if total_pages == 0: + return images + + start_idx = max(0, (first_page - 1) if first_page is not None else 0) + end_idx = min(total_pages, last_page if last_page is not None else total_pages) + + for idx in range(start_idx, end_idx): + page = pdf[idx] + bitmap = None + try: + # Align CropBox with MediaBox to match pdftoppm/pdf2image default geometry. + mediabox = page.get_mediabox(fallback_ok=False) + cropbox = page.get_cropbox(fallback_ok=False) + if ( + mediabox is not None + and len(mediabox) == 4 + and mediabox[2] > mediabox[0] + and mediabox[3] > mediabox[1] + and cropbox is not None + and cropbox != mediabox + ): + page.set_cropbox(*mediabox) + + bitmap = page.render(scale=scale) + pil_image = bitmap.to_pil() + if pil_image.mode != "RGB": + pil_image = pil_image.convert("RGB") + else: + pil_image = pil_image.copy() + images.append(pil_image) + finally: + if bitmap is not None: + bitmap.close() + page.close() + finally: + pdf.close() + + return images diff --git a/packages/invoice-core/src/invoice_core/prompts.py b/packages/invoice-core/src/invoice_core/prompts.py new file mode 100644 index 0000000..52079cb --- /dev/null +++ b/packages/invoice-core/src/invoice_core/prompts.py @@ -0,0 +1,133 @@ +"""Prompts for LLM-based invoice parsing.""" + +import json + +# JSON Schema definition for strict output format +INVOICE_JSON_SCHEMA = { + "type": "object", + "properties": { + "invoice_number": { + "type": ["string", "null"], + "description": "发票号码,通常为8-20位数字" + }, + "invoice_code": { + "type": ["string", "null"], + "description": "发票代码,通常为10-12位数字(如有)" + }, + "issue_date": { + "type": ["string", "null"], + "pattern": "^\\d{4}-\\d{2}-\\d{2}$", + "description": "开票日期,格式必须为YYYY-MM-DD" + }, + "buyer_name": { + "type": ["string", "null"], + "description": "购买方名称(公司全称)" + }, + "buyer_tax_id": { + "type": ["string", "null"], + "pattern": "^[A-Z0-9]{15,20}$", + "description": "购买方纳税人识别号,15-20位字母数字" + }, + "seller_name": { + "type": ["string", "null"], + "description": "销售方名称(公司全称)" + }, + "seller_tax_id": { + "type": ["string", "null"], + "pattern": "^[A-Z0-9]{15,20}$", + "description": "销售方纳税人识别号,15-20位字母数字" + }, + "item_name": { + "type": ["string", "null"], + "description": "项目名称/货物名称,如有类别标记(*类别*商品)则保留" + }, + "total_with_tax": { + "type": ["string", "null"], + "pattern": "^\\d+(\\.\\d{1,2})?$", + "description": "价税合计金额,纯数字不含货币符号" + }, + "amount": { + "type": ["string", "null"], + "pattern": "^\\d+(\\.\\d{1,2})?$", + "description": "金额(不含税),纯数字" + }, + "tax_amount": { + "type": ["string", "null"], + "pattern": "^\\d+(\\.\\d{1,2})?$", + "description": "税额,纯数字(免税发票返回\"0\")" + }, + "tax_rate": { + "type": ["string", "null"], + "description": "税率,如\"6%\"、\"13%\"、\"免税\"" + } + }, + "required": [ + "invoice_number", "invoice_code", "issue_date", + "buyer_name", "buyer_tax_id", "seller_name", "seller_tax_id", + "item_name", "total_with_tax", "amount", "tax_amount", "tax_rate" + ], + "additionalProperties": False +} + +# Required fields list for validation +REQUIRED_FIELDS = list(INVOICE_JSON_SCHEMA["required"]) + +# Vision-based system prompt (for direct image analysis) +INVOICE_VISION_SYSTEM_PROMPT = """你是一个专业的中国发票信息提取助手。 +你必须严格按照JSON Schema格式返回结果,无法识别的字段返回null。 +只返回JSON对象,不要包含任何其他文字、解释或markdown代码块标记。""" + +# Build field descriptions for the prompt +_field_descriptions = json.dumps( + {k: v["description"] for k, v in INVOICE_JSON_SCHEMA["properties"].items()}, + ensure_ascii=False, + indent=2 +) + +# Vision-based extraction prompt (for direct image analysis) +INVOICE_VISION_PROMPT = f"""请分析这张中国发票图片,提取发票信息。 + +## 输出格式要求(必须严格遵守) + +返回一个JSON对象,必须包含以下12个字段(不能多也不能少): +{_field_descriptions} + +字段类型规则: +- 所有字段值必须是 string 或 null(数值也用字符串表示) +- 日期格式必须是 YYYY-MM-DD +- 金额字段仅包含数字和小数点 +- 税率字段格式如 \"6%\"、\"13%\" 或 \"免税\" +- 不能返回空字符串,用 null 表示缺失 + +## 购买方与销售方识别规则(最重要) + +根据标签文字识别,不要依赖位置: +- 购买方 = 标注为"购买方"、"购方"、"购货单位"的区域 +- 销售方 = 标注为"销售方"、"销方"、"销货单位"的区域 +- 销售方区域通常还有"开票人"、"收款人"、"复核"等字样 + +中国发票格式说明: +- 标准增值税发票:购买方在左上,销售方在左下 +- 电子普通发票:购买方在上部,销售方在底部(价税合计下方) +- 全电发票:购买方和销售方可能左右并排 + +## 字段提取规则 + +1. invoice_number: 查找"发票号码"标签后的数字 +2. invoice_code: 查找"发票代码"标签后的数字(如无则返回null) +3. issue_date: 查找"开票日期",转换为YYYY-MM-DD格式 +4. buyer_name/seller_name: 查找"名称"标签后的公司全称 +5. buyer_tax_id/seller_tax_id: 查找"纳税人识别号"后的15-20位编码 +6. item_name: 查找商品行中的项目名称(可能有*分类*前缀) +7. total_with_tax: 查找"价税合计"或"小写"金额,只返回数字 +8. amount: 查找"金额"或"合计"行的不含税金额 +9. tax_amount: 查找"税额",免税发票返回"0" +10. tax_rate: 查找"税率"列的值,如"6%"、"免税" + +## 数据清洗规则 + +- 金额字段去除¥、¥、$、逗号,只保留数字和小数点 +- 日期统一转换为YYYY-MM-DD +- 无法识别的字段返回null,不要猜测 + +请直接返回JSON对象:""" diff --git a/packages/invoice-core/src/invoice_core/reconcile.py b/packages/invoice-core/src/invoice_core/reconcile.py new file mode 100644 index 0000000..e162dda --- /dev/null +++ b/packages/invoice-core/src/invoice_core/reconcile.py @@ -0,0 +1,139 @@ +"""Dual-source (OCR vs LLM) field comparison and reconciliation.""" + +from decimal import Decimal, InvalidOperation +from typing import Any, Dict, List, Optional, Tuple + +# Fields to compare between OCR and LLM +COMPARABLE_FIELDS = [ + 'invoice_number', + 'issue_date', + 'buyer_name', + 'buyer_tax_id', + 'seller_name', + 'seller_tax_id', + 'item_name', + 'total_with_tax', + 'amount', + 'tax_amount', + 'tax_rate', +] + +# Fields that should be compared as numbers +NUMERIC_FIELDS = ['total_with_tax', 'amount', 'tax_amount'] + + +def normalize_value(value: Any) -> Optional[str]: + """Normalize a value to string for comparison.""" + if value is None: + return None + value_str = str(value).strip() + if not value_str: + return None + return value_str + + +def values_are_equal(field_name: str, value1: Optional[str], value2: Optional[str]) -> bool: + """Compare two values, using numeric comparison for numeric fields. + + Args: + field_name: Name of the field being compared + value1: First value (normalized string) + value2: Second value (normalized string) + + Returns: + True if values are considered equal + """ + # If both are None or empty, they're equal + if not value1 and not value2: + return True + + # If only one is None/empty, they're not equal + if not value1 or not value2: + return False + + # For numeric fields, compare as numbers + if field_name in NUMERIC_FIELDS: + try: + # Remove any currency symbols and whitespace + clean1 = value1.replace('¥', '').replace('¥', '').replace(',', '').strip() + clean2 = value2.replace('¥', '').replace('¥', '').replace(',', '').strip() + num1 = Decimal(clean1) + num2 = Decimal(clean2) + return num1 == num2 + except (InvalidOperation, ValueError): + # Fall back to string comparison if not valid numbers + pass + + # Default to string comparison + return value1 == value2 + + +def compare_and_resolve( + ocr_fields: Dict[str, Any], + llm_fields: Dict[str, Any], + has_llm: bool +) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: + """Compare OCR and LLM results, resolve differences. + + Args: + ocr_fields: Fields extracted by OCR + llm_fields: Fields extracted by LLM + has_llm: Whether LLM results are available + + Returns: + Tuple of (final_fields, diffs_list) + """ + final_fields = {} + diffs = [] + + for field_name in COMPARABLE_FIELDS: + ocr_value = normalize_value(ocr_fields.get(field_name)) + llm_value = normalize_value(llm_fields.get(field_name)) if has_llm else None + + # Determine final value and whether review is needed + if not has_llm: + # No LLM available, use OCR value directly + final_value = ocr_value + source = 'ocr' + needs_review = False + elif values_are_equal(field_name, ocr_value, llm_value): + # Values match (including numeric equivalence like 330.00 == 330) + final_value = ocr_value or llm_value + source = 'matched' + needs_review = False + elif ocr_value and llm_value: + # Both have values but they differ - needs manual review + final_value = None # Leave blank for manual review + source = 'conflict' + needs_review = True + elif llm_value and not ocr_value: + # LLM found something OCR missed - prefer LLM + final_value = llm_value + source = 'llm' + needs_review = False + else: + # OCR found something LLM missed - prefer OCR + final_value = ocr_value + source = 'ocr' + needs_review = False + + final_fields[field_name] = final_value + + # Record diff if there's a discrepancy or both have values + if has_llm and (ocr_value or llm_value): + diffs.append({ + 'field_name': field_name, + 'ocr_value': ocr_value, + 'llm_value': llm_value, + 'final_value': final_value, + 'source': source, + 'needs_review': needs_review, + }) + + return final_fields, diffs + + +# Compatibility aliases matching original backend private names +_normalize_value = normalize_value +_values_are_equal = values_are_equal +_compare_and_resolve = compare_and_resolve diff --git a/packages/invoice-core/tests/test_extract_snapshot.py b/packages/invoice-core/tests/test_extract_snapshot.py new file mode 100644 index 0000000..5f9a011 --- /dev/null +++ b/packages/invoice-core/tests/test_extract_snapshot.py @@ -0,0 +1,217 @@ +"""Baseline snapshot tests for FieldExtractor (recorded verbatim from c1ca829).""" + +from invoice_core.extract import FieldExtractor, get_field_extractor + +SYNTH_INV_NUM_1 = "0" * 16 + "0001" +SYNTH_INV_NUM_2 = "0" * 16 + "0002" + + +def _line(text: str, x: float, y: float, width: float = 200, height: float = 12) -> dict: + return { + "text": text, + "min_x": x, + "max_x": x + width, + "min_y": y, + "max_y": y + height, + "center_x": x + width / 2, + "center_y": y + height / 2, + } + + +def test_get_field_extractor_singleton(): + first = get_field_extractor() + second = get_field_extractor() + assert isinstance(first, FieldExtractor) + assert first is second + + +def test_extract_cn_standard_text_snapshot(): + text = ( + "电子发票(普通发票)\n" + "发票代码:012345678901\n" + f"发票号码:{SYNTH_INV_NUM_1}\n" + "开票日期:2025年11月05日\n" + "购买方信息\n" + "名称:示例 买方 科技有限公司\n" + "统一社会信用代码/纳税人识别号:TESTBUYER000000001\n" + "*信息技术服务*云主机租用费\n" + "税率:6%\n" + "合计 ¥1,000.00 ¥60.00\n" + "价税合计(小写)¥1,060.00\n" + "销售方信息\n" + "名称:示例 卖方 服务有限公司\n" + "统一社会信用代码/纳税人识别号:TESTSELLER00000001\n" + "开票人:张三\n" + ) + assert FieldExtractor().extract_fields(text) == { + "invoice_number": SYNTH_INV_NUM_1, + "invoice_code": "012345678901", + "issue_date": "2025-11-05", + "buyer_name": "示例买方科技有限公司", + "buyer_tax_id": "TESTBUYER000000001", + "seller_name": "示例卖方服务有限公司", + "seller_tax_id": "TESTSELLER00000001", + "item_name": "信息技术服务*云主机租用费", + "total_with_tax": "1060.00", + "amount": "1000.00", + "tax_amount": "60.00", + "tax_rate": "6%", + } + + +def test_extract_cn_spaced_inline_text_snapshot(): + text = ( + "电子发票(普通发票)\n" + f"发票号码:{SYNTH_INV_NUM_2}\n" + "开票日期:2025-12-01\n" + "购 名称:示例买方科技有限公司 销 名称:示例卖方服务有限公司分公司\n" + "买 售\n" + "方 方\n" + "信 统一社会信用代码/纳税人识别号:123456789012345 " + "信 统一社会信用代码/纳税人识别号:DEMOSELLER00000001\n" + "*餐饮服务*工作餐\n" + "金额\n免税\n" + "金额 ¥200.00 税额 ¥0.00\n" + "小写)¥200.00\n" + ) + assert FieldExtractor().extract_fields(text) == { + "invoice_number": SYNTH_INV_NUM_2, + "invoice_code": None, + "issue_date": "2025-12-01", + "buyer_name": "示例买方科技有限公司", + "buyer_tax_id": "123456789012345", + "seller_name": "示例卖方服务有限公司分公司", + "seller_tax_id": "DEMOSELLER00000001", + "item_name": "餐饮服务*工作餐", + "total_with_tax": "200.00", + "amount": "200.00", + "tax_amount": "0.00", + "tax_rate": "免税", + } + + +def test_extract_cn_ocr_lines_spaced_snapshot(): + lines = [ + _line("电子发票(普通发票)", x=100, y=0), + _line("购 名称:示例买方科技有限公司", x=10, y=20), + _line("统一社会信用代码/纳税人识别号:123456789012345", x=10, y=34), + _line("销 名称:示例卖方服务有限公司分公司", x=10, y=80), + _line("统一社会信用代码/纳税人识别号:DEMOSELLER00000001", x=10, y=94), + _line("价税合计(小写)¥520.50", x=10, y=120), + ] + text = "\n".join(line["text"] for line in lines) + assert FieldExtractor().extract_fields(text, lines) == { + "invoice_number": None, + "invoice_code": None, + "issue_date": None, + "buyer_name": "示例买方科技有限公司", + "buyer_tax_id": "123456789012345", + "seller_name": "示例卖方服务有限公司分公司", + "seller_tax_id": "DEMOSELLER00000001", + "item_name": None, + "total_with_tax": "520.50", + "amount": None, + "tax_amount": None, + "tax_rate": None, + } + + +def test_extract_cn_ocr_lines_swap_reversed_snapshot(): + lines = [ + _line("发票", x=10, y=0), + _line("销售方", x=10, y=20), + _line("名称:示例卖方有限公司", x=10, y=32), + _line("税号:DEMOSELLER00000001", x=10, y=44), + _line("购买方", x=10, y=100), + _line("名称:示例买方有限公司", x=10, y=112), + _line("税号:DEMOBUYER000000001", x=10, y=124), + ] + text = "\n".join(line["text"] for line in lines) + assert FieldExtractor().extract_fields(text, lines) == { + "invoice_number": None, + "invoice_code": None, + "issue_date": None, + "buyer_name": "示例买方有限公司", + "buyer_tax_id": "DEMOBUYER000000001", + "seller_name": "示例卖方有限公司", + "seller_tax_id": "DEMOSELLER00000001", + "item_name": None, + "total_with_tax": None, + "amount": None, + "tax_amount": None, + "tax_rate": None, + } + + +def test_extract_cn_fallback_no_labels_snapshot(): + text = ( + "电子发票\n" + "名称:甲测试有限公司\n" + "纳税人识别号:123456789012345\n" + "名称:乙演示股份公司\n" + "纳税人识别号:DEMOSELLER00000001\n" + "价税合计(小写)¥88.80\n" + ) + assert FieldExtractor().extract_fields(text) == { + "invoice_number": None, + "invoice_code": None, + "issue_date": None, + "buyer_name": "甲测试有限公司", + "buyer_tax_id": "123456789012345", + "seller_name": "乙演示股份公司", + "seller_tax_id": "DEMOSELLER00000001", + "item_name": None, + "total_with_tax": "88.80", + "amount": None, + "tax_amount": None, + "tax_rate": None, + } + + +def test_extract_cn_red_invoice_preserves_c1ca829_behavior(): + """M2-0 is a pure move: negative amount handling remains untouched until M2-C.""" + text = ( + "电子发票(普通发票)\n" + f"发票号码:{SYNTH_INV_NUM_1}\n" + "开票日期:2025年11月09日\n" + "购买方\n名称:示例买方有限公司\n" + "销售方\n名称:示例卖方有限公司\n" + "合计 ¥-100.00 ¥-6.00\n" + "价税合计(小写)¥-106.00\n" + ) + assert FieldExtractor().extract_fields(text) == { + "invoice_number": SYNTH_INV_NUM_1, + "invoice_code": None, + "issue_date": "2025-11-09", + "buyer_name": "示例买方有限公司", + "buyer_tax_id": None, + "seller_name": "示例卖方有限公司", + "seller_tax_id": None, + "item_name": None, + "total_with_tax": None, + "amount": None, + "tax_amount": None, + "tax_rate": None, + } + + +def test_extract_en_invoice_text_snapshot(): + text = ( + "INVOICE\n" + "#INV-2025-001\n" + "Acme Services LLC\n" + "Date: August 13, 2025\n" + "Bill To:\n" + "Demo Buyer Inc\n" + "123 Main St\n" + "Subtotal: $1,200.00\n" + "Total: $1,320.00\n" + ) + assert FieldExtractor().extract_fields(text) == { + "invoice_number": "INV-2025-001", + "issue_date": "2025-08-13", + "buyer_name": "Demo Buyer Inc", + "seller_name": "Acme Services LLC\nDate", + "total_with_tax": "1200.00", + "amount": "1200.00", + } diff --git a/packages/invoice-core/tests/test_import_guard.py b/packages/invoice-core/tests/test_import_guard.py new file mode 100644 index 0000000..8981f4e --- /dev/null +++ b/packages/invoice-core/tests/test_import_guard.py @@ -0,0 +1,78 @@ +"""Import guard tests ensuring invoice_core stays pure Python without web/DB/OCR deps.""" + +import ast +import subprocess +import sys +from pathlib import Path + +FORBIDDEN_ROOT_MODULES = frozenset( + { + "fastapi", + "sqlalchemy", + "paddleocr", + "paddle", + "app", + "pdf2image", + "uvicorn", + "alembic", + } +) + + +def _package_source_dir() -> Path: + return Path(__file__).resolve().parent.parent / "src" / "invoice_core" + + +def test_static_ast_forbids_backend_and_heavy_imports(): + """Every Python module in invoice_core must not import forbidden dependencies.""" + src_dir = _package_source_dir() + py_files = sorted(src_dir.rglob("*.py")) + assert py_files, f"No source files found under {src_dir}" + + violations: list[str] = [] + for py_file in py_files: + tree = ast.parse(py_file.read_text(encoding="utf-8"), filename=str(py_file)) + for node in ast.walk(tree): + if isinstance(node, ast.Import): + for alias in node.names: + root = alias.name.split(".")[0] + if root in FORBIDDEN_ROOT_MODULES: + violations.append(f"{py_file.relative_to(src_dir)}:{node.lineno}: import {alias.name}") + elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module: + root = node.module.split(".")[0] + if root in FORBIDDEN_ROOT_MODULES: + violations.append(f"{py_file.relative_to(src_dir)}:{node.lineno}: from {node.module} import ...") + + assert not violations, "Forbidden imports found in invoice_core:\n" + "\n".join(violations) + + +def test_runtime_sys_modules_forbids_backend_and_heavy_imports(): + """Importing every invoice_core module in a clean interpreter loads no forbidden modules.""" + script = ( + "import importlib, json, pkgutil, sys\n" + "import invoice_core\n" + "loaded = ['invoice_core']\n" + "for info in pkgutil.walk_packages(invoice_core.__path__, invoice_core.__name__ + '.'):\n" + " importlib.import_module(info.name)\n" + " loaded.append(info.name)\n" + "forbidden = " + + repr(sorted(FORBIDDEN_ROOT_MODULES)) + + "\n" + "hits = sorted(m for m in sys.modules if m.split('.')[0] in forbidden)\n" + "print(json.dumps({'loaded': loaded, 'hits': hits}))\n" + ) + proc = subprocess.run( + [sys.executable, "-c", script], + capture_output=True, + text=True, + check=True, + ) + import json + + result = json.loads(proc.stdout) + assert "invoice_core.extract" in result["loaded"] + assert "invoice_core.reconcile" in result["loaded"] + assert "invoice_core.llm_json" in result["loaded"] + assert "invoice_core.prompts" in result["loaded"] + assert "invoice_core.parsers.pdf_text" in result["loaded"] + assert result["hits"] == [], f"Forbidden modules loaded at runtime: {result['hits']}" diff --git a/packages/invoice-core/tests/test_llm_json.py b/packages/invoice-core/tests/test_llm_json.py new file mode 100644 index 0000000..3724d3f --- /dev/null +++ b/packages/invoice-core/tests/test_llm_json.py @@ -0,0 +1,104 @@ +"""Baseline snapshot tests for llm_json parsing and normalization (recorded from c1ca829).""" + +import json + +import pytest + +from invoice_core.llm_json import ( + _normalize_field_value, + _parse_json_response, + normalize_field_value, + parse_json_response, +) + +SYNTH_INV_NUM_1 = "0" * 16 + "0001" + +VALID_PAYLOAD = { + "invoice_number": f" {SYNTH_INV_NUM_1} ", + "invoice_code": "1234-5678-9012", + "issue_date": "2025年11月5日", + "buyer_name": " 示例买方科技有限公司 ", + "buyer_tax_id": " testbuyer000000001 ", + "seller_name": "示例卖方服务有限公司", + "seller_tax_id": "TESTSELLER00000001", + "item_name": "*技术服务*咨询费", + "total_with_tax": "¥8,600.00", + "amount": 8600, + "tax_amount": 0.0, + "tax_rate": "免税", + "extra_ignored": "should-be-dropped", +} + +EXPECTED_VALID = { + "invoice_number": SYNTH_INV_NUM_1, + "invoice_code": "123456789012", + "issue_date": "2025-11-05", + "buyer_name": "示例买方科技有限公司", + "buyer_tax_id": "TESTBUYER000000001", + "seller_name": "示例卖方服务有限公司", + "seller_tax_id": "TESTSELLER00000001", + "item_name": "*技术服务*咨询费", + "total_with_tax": "8600.00", + "amount": "8600", + "tax_amount": "0.0", + "tax_rate": "免税", +} + + +def test_aliases(): + assert _normalize_field_value is normalize_field_value + assert _parse_json_response is parse_json_response + + +def test_parse_bare_and_fenced_json_snapshot(): + raw_json = json.dumps(VALID_PAYLOAD, ensure_ascii=False) + assert parse_json_response(raw_json, "test") == EXPECTED_VALID + assert parse_json_response(f"```json\n{raw_json}\n```", "test") == EXPECTED_VALID + assert parse_json_response(f"```\n{raw_json}\n```", "test") == EXPECTED_VALID + + +def test_parse_invalid_fields_normalized_to_none_snapshot(): + content = json.dumps( + { + "invoice_number": "ABC", + "invoice_code": "123", + "issue_date": "2025/1/9", + "buyer_name": "", + "buyer_tax_id": "123", + "seller_name": None, + "seller_tax_id": "SHORT", + "item_name": ["not-a-str"], + "total_with_tax": "not-a-number", + "amount": " ", + "tax_amount": None, + "tax_rate": "6 %", + } + ) + assert parse_json_response(content, "test") == { + "invoice_number": None, + "invoice_code": None, + "issue_date": "2025-01-09", + "buyer_name": None, + "buyer_tax_id": None, + "seller_name": None, + "seller_tax_id": None, + "item_name": None, + "total_with_tax": None, + "amount": None, + "tax_amount": None, + "tax_rate": None, + } + + +@pytest.mark.parametrize( + "raw", + [ + f"Here is the JSON:\n{json.dumps(VALID_PAYLOAD, ensure_ascii=False)}\nThanks!", + "[1, 2, 3]", + "{bad json", + ], +) +def test_parse_non_json_object_raises_json_decode_error(raw: str): + """Preserves c1ca829 behavior: surrounding text, non-dict JSON, and malformed JSON raise JSONDecodeError.""" + with pytest.raises(json.JSONDecodeError): + parse_json_response(raw, "test") diff --git a/packages/invoice-core/tests/test_pdf_text.py b/packages/invoice-core/tests/test_pdf_text.py new file mode 100644 index 0000000..fb334f5 --- /dev/null +++ b/packages/invoice-core/tests/test_pdf_text.py @@ -0,0 +1,233 @@ +"""Tests for pdf_text extraction (pdfplumber via BytesIO) and pypdfium2 rendering.""" + +from concurrent.futures import ThreadPoolExecutor +import hashlib +from io import BytesIO +from typing import Optional + +from PIL import Image +import pytest + +from invoice_core.parsers.pdf_text import extract_pdf_text_layer, render_pdf_pages + +SYNTH_INV_NUM_1 = "0" * 16 + "0001" + + +def _build_synthetic_pdf( + pages: list[list[str]], + page_rects: Optional[list[tuple[float, float, float, float, float, float, float]]] = None, + cropbox: Optional[tuple[int, int, int, int]] = None, +) -> bytes: + """Build a minimal valid multi-page PDF with an embedded ToUnicode text layer.""" + unique_chars: list[str] = [] + char_to_byte: dict[str, int] = {} + for page_lines in pages: + for line in page_lines: + for ch in line: + if ch not in char_to_byte: + code = len(unique_chars) + 1 + assert code < 255 + char_to_byte[ch] = code + unique_chars.append(ch) + + bfchar_lines = [f"<{char_to_byte[ch]:02X}> <{ord(ch):04X}>" for ch in unique_chars] + cmap = ( + "/CIDInit /ProcSet findresource begin\n" + "12 dict begin\n" + "begincmap\n" + "/CIDSystemInfo << /Registry (Demo) /Ordering (UCS) /Supplement 0 >> def\n" + "/CMapName /Demo-UCS def\n" + "/CMapType 2 def\n" + "1 begincodespacerange\n" + "<01> \n" + "endcodespacerange\n" + f"{len(bfchar_lines)} beginbfchar\n" + + "\n".join(bfchar_lines) + + "\nendbfchar\n" + "endcmap\n" + "CMapName currentdict /CMap defineresource pop\n" + "end\n" + "end\n" + ).encode("ascii") + + # Object IDs: + # 1: Catalog, 2: Pages, 3: Font, 4: ToUnicode CMap + # For each page i: (5 + 2*i) = Page, (6 + 2*i) = Content stream + page_obj_ids = [5 + 2 * i for i in range(len(pages))] + kids_str = " ".join(f"{pid} 0 R" for pid in page_obj_ids) + + objects: list[bytes] = [ + b"<< /Type /Catalog /Pages 2 0 R >>", + f"<< /Type /Pages /Kids [{kids_str}] /Count {len(pages)} >>".encode("ascii"), + b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /ToUnicode 4 0 R >>", + b"<< /Length " + str(len(cmap)).encode("ascii") + b" >>\nstream\n" + cmap + b"endstream", + ] + + for idx, page_lines in enumerate(pages): + content_id = 6 + 2 * idx + content_ops: list[str] = [] + if page_rects is not None and idx < len(page_rects): + r, g, b, x, y_rect, w, h = page_rects[idx] + content_ops.append(f"{r} {g} {b} rg {x} {y_rect} {w} {h} re f") + content_ops.extend(["BT", "/F1 12 Tf"]) + y = 750 + for line in page_lines: + hex_str = "".join(f"{char_to_byte[ch]:02X}" for ch in line) + content_ops.append(f"1 0 0 1 50 {y} Tm <{hex_str}> Tj") + y -= 18 + content_ops.append("ET") + content_stream = ("\n".join(content_ops) + "\n").encode("ascii") + + cropbox_entry = ( + f" /CropBox [{cropbox[0]} {cropbox[1]} {cropbox[2]} {cropbox[3]}]" + if cropbox is not None + else "" + ) + objects.append( + f"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842]{cropbox_entry} " + f"/Resources << /Font << /F1 3 0 R >> >> /Contents {content_id} 0 R >>".encode("ascii") + ) + objects.append( + b"<< /Length " + str(len(content_stream)).encode("ascii") + b" >>\nstream\n" + content_stream + b"endstream" + ) + + buf = BytesIO() + buf.write(b"%PDF-1.4\n") + offsets = [0] + for obj_num, obj in enumerate(objects, start=1): + offsets.append(buf.tell()) + buf.write(f"{obj_num} 0 obj\n".encode("ascii")) + buf.write(obj) + buf.write(b"\nendobj\n") + + xref_pos = buf.tell() + buf.write(f"xref\n0 {len(objects) + 1}\n".encode("ascii")) + buf.write(b"0000000000 65535 f \n") + for off in offsets[1:]: + buf.write(f"{off:010d} 00000 n \n".encode("ascii")) + buf.write( + f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\nstartxref\n{xref_pos}\n%%EOF\n".encode("ascii") + ) + return buf.getvalue() + + +def test_extract_pdf_text_layer_invoice_snapshot(): + lines = [ + "电子发票(普通发票)", + f"发票号码:{SYNTH_INV_NUM_1}", + "开票日期:2025年11月05日", + "购买方名称:示例买方科技有限公司", + "统一社会信用代码:TESTBUYER000000001", + "销售方名称:示例卖方服务有限公司", + "统一社会信用代码:TESTSELLER00000001", + "价税合计(小写)¥1060.00", + "备注:这是一份用于确定性快照验证的合成电子发票文本层样本数据。", + ] + pdf_bytes = _build_synthetic_pdf([lines]) + extracted, has_useful = extract_pdf_text_layer(pdf_bytes) + + assert has_useful is True + assert extracted == "\n".join(lines) + + +def test_extract_pdf_text_layer_short_non_invoice(): + pdf_bytes = _build_synthetic_pdf([["Hello World", "Short doc"]]) + extracted, has_useful = extract_pdf_text_layer(pdf_bytes) + + assert has_useful is False + assert extracted == "Hello World\nShort doc" + + +def test_extract_pdf_text_layer_invalid_bytes_returns_empty(): + extracted, has_useful = extract_pdf_text_layer(b"not a valid pdf") + assert extracted == "" + assert has_useful is False + + +def test_render_pdf_pages_all_and_range(): + page_rects = [ + (0.1, 0.2, 0.85, 40, 620, 140, 100), # Page 1: blue marker top-left + (0.85, 0.15, 0.15, 360, 140, 160, 120), # Page 2: red marker bottom-right + ] + pdf_bytes = _build_synthetic_pdf([["Page 1"], ["Page 2"]], page_rects=page_rects) + + all_images = render_pdf_pages(pdf_bytes, dpi=72) + assert len(all_images) == 2 + for img in all_images: + assert isinstance(img, Image.Image) + assert img.mode == "RGB" + assert img.size == (595, 842) + # Ensure rendered output is not a blank white page + assert img.convert("L").getextrema()[0] < 255 + + page1_bytes = all_images[0].tobytes() + page2_bytes = all_images[1].tobytes() + assert page1_bytes != page2_bytes + + first_only = render_pdf_pages(pdf_bytes, dpi=144, first_page=1, last_page=1) + assert len(first_only) == 1 + assert first_only[0].mode == "RGB" + assert first_only[0].size == (1190, 1684) + assert first_only[0].convert("L").getextrema()[0] < 255 + + second_only = render_pdf_pages(pdf_bytes, dpi=72, first_page=2, last_page=2) + assert len(second_only) == 1 + assert second_only[0].size == (595, 842) + assert second_only[0].tobytes() == page2_bytes + assert second_only[0].tobytes() != page1_bytes + + +def test_render_pdf_pages_invalid_bytes_raises(): + with pytest.raises(Exception): + render_pdf_pages(b"not-a-pdf") + + +def test_render_pdf_pages_aligns_cropbox_to_mediabox(): + # Marker placed outside narrow CropBox [0, 0, 300, 400], inside MediaBox [0, 0, 595, 842] + pdf_bytes = _build_synthetic_pdf( + [["CropBox Test"]], + page_rects=[(0.0, 0.5, 0.2, 380, 520, 120, 120)], + cropbox=(0, 0, 300, 400), + ) + + images = render_pdf_pages(pdf_bytes, dpi=72) + assert len(images) == 1 + assert images[0].mode == "RGB" + assert images[0].size == (595, 842) + # In top-left PIL coordinates at 72dpi, PDF rect (380..500, 520..640) maps to (380..500, 202..322) + assert images[0].getpixel((440, 260)) != (255, 255, 255) + + +def test_render_pdf_pages_concurrent_thread_safety(): + page_rects = [ + (0.1, 0.2, 0.85, 50, 650, 120, 90), + (0.85, 0.15, 0.15, 220, 400, 130, 100), + (0.1, 0.7, 0.2, 380, 120, 140, 110), + ] + pdf_bytes = _build_synthetic_pdf( + [["Page 1"], ["Page 2"], ["Page 3"]], + page_rects=page_rects, + ) + + baseline_images = render_pdf_pages(pdf_bytes, dpi=100) + assert len(baseline_images) == 3 + baseline_signature = [ + (img.mode, img.size, hashlib.sha256(img.tobytes()).hexdigest()) + for img in baseline_images + ] + assert len({sig[2] for sig in baseline_signature}) == 3 + + def _render_once() -> list[tuple[str, tuple[int, int], str]]: + imgs = render_pdf_pages(pdf_bytes, dpi=100) + return [ + (img.mode, img.size, hashlib.sha256(img.tobytes()).hexdigest()) + for img in imgs + ] + + with ThreadPoolExecutor(max_workers=8) as executor: + futures = [executor.submit(_render_once) for _ in range(48)] + results = [future.result() for future in futures] + + assert len(results) == 48 + for sig in results: + assert sig == baseline_signature diff --git a/packages/invoice-core/tests/test_reconcile.py b/packages/invoice-core/tests/test_reconcile.py new file mode 100644 index 0000000..4cfc109 --- /dev/null +++ b/packages/invoice-core/tests/test_reconcile.py @@ -0,0 +1,216 @@ +"""Baseline snapshot tests for reconcile functions (recorded verbatim from c1ca829).""" + +from invoice_core.reconcile import ( + COMPARABLE_FIELDS, + NUMERIC_FIELDS, + _compare_and_resolve, + _normalize_value, + _values_are_equal, + compare_and_resolve, + normalize_value, + values_are_equal, +) + +SYNTH_INV_NUM_1 = "0" * 16 + "0001" +SYNTH_INV_NUM_2 = "0" * 16 + "0002" + + +def test_constants_and_aliases(): + assert COMPARABLE_FIELDS == [ + "invoice_number", + "issue_date", + "buyer_name", + "buyer_tax_id", + "seller_name", + "seller_tax_id", + "item_name", + "total_with_tax", + "amount", + "tax_amount", + "tax_rate", + ] + assert NUMERIC_FIELDS == ["total_with_tax", "amount", "tax_amount"] + assert _normalize_value is normalize_value + assert _values_are_equal is values_are_equal + assert _compare_and_resolve is compare_and_resolve + + +def test_normalize_value_snapshot(): + assert normalize_value(None) is None + assert normalize_value("") is None + assert normalize_value(" ") is None + assert normalize_value(" abc ") == "abc" + assert normalize_value(123) == "123" + assert normalize_value(12.5) == "12.5" + + +def test_values_are_equal_snapshot(): + assert values_are_equal("buyer_name", None, None) is True + assert values_are_equal("buyer_name", "A", None) is False + assert values_are_equal("buyer_name", "示例公司", "示例公司") is True + assert values_are_equal("buyer_name", "甲公司", "乙公司") is False + assert values_are_equal("total_with_tax", "330.00", "330") is True + assert values_are_equal("amount", "¥1,234.50", "1234.5") is True + assert values_are_equal("tax_amount", "¥0.00", "0") is True + assert values_are_equal("total_with_tax", "100.00", "100.01") is False + assert values_are_equal("amount", "N/A", "N/A") is True + assert values_are_equal("amount", "N/A", "NONE") is False + assert values_are_equal("invoice_number", "00123", "123") is False + + +def test_compare_and_resolve_no_llm_snapshot(): + final_fields, diffs = compare_and_resolve( + {"invoice_number": SYNTH_INV_NUM_1, "total_with_tax": "100.00", "buyer_name": "甲公司"}, + {"invoice_number": SYNTH_INV_NUM_2, "total_with_tax": "999.00"}, + has_llm=False, + ) + assert final_fields == { + "invoice_number": SYNTH_INV_NUM_1, + "issue_date": None, + "buyer_name": "甲公司", + "buyer_tax_id": None, + "seller_name": None, + "seller_tax_id": None, + "item_name": None, + "total_with_tax": "100.00", + "amount": None, + "tax_amount": None, + "tax_rate": None, + } + assert diffs == [] + + +def test_compare_and_resolve_with_llm_mixed_snapshot(): + final_fields, diffs = compare_and_resolve( + { + "invoice_number": SYNTH_INV_NUM_1, + "issue_date": "2025-11-05", + "buyer_name": "示例买方公司", + "buyer_tax_id": None, + "seller_name": "示例卖方公司", + "seller_tax_id": "TESTSELLER00000001", + "item_name": "OCR项目", + "total_with_tax": "¥1,060.00", + "amount": "1000.00", + "tax_amount": "60.00", + "tax_rate": "6%", + }, + { + "invoice_number": SYNTH_INV_NUM_1, + "issue_date": "2025-11-06", + "buyer_name": "示例买方公司", + "buyer_tax_id": "TESTBUYER000000001", + "seller_name": None, + "seller_tax_id": "TESTSELLER00000001", + "item_name": "LLM项目", + "total_with_tax": "1060", + "amount": "1000.0", + "tax_amount": "60", + "tax_rate": None, + }, + has_llm=True, + ) + + assert final_fields == { + "invoice_number": SYNTH_INV_NUM_1, + "issue_date": None, + "buyer_name": "示例买方公司", + "buyer_tax_id": "TESTBUYER000000001", + "seller_name": "示例卖方公司", + "seller_tax_id": "TESTSELLER00000001", + "item_name": None, + "total_with_tax": "¥1,060.00", + "amount": "1000.00", + "tax_amount": "60.00", + "tax_rate": "6%", + } + assert diffs == [ + { + "field_name": "invoice_number", + "ocr_value": SYNTH_INV_NUM_1, + "llm_value": SYNTH_INV_NUM_1, + "final_value": SYNTH_INV_NUM_1, + "source": "matched", + "needs_review": False, + }, + { + "field_name": "issue_date", + "ocr_value": "2025-11-05", + "llm_value": "2025-11-06", + "final_value": None, + "source": "conflict", + "needs_review": True, + }, + { + "field_name": "buyer_name", + "ocr_value": "示例买方公司", + "llm_value": "示例买方公司", + "final_value": "示例买方公司", + "source": "matched", + "needs_review": False, + }, + { + "field_name": "buyer_tax_id", + "ocr_value": None, + "llm_value": "TESTBUYER000000001", + "final_value": "TESTBUYER000000001", + "source": "llm", + "needs_review": False, + }, + { + "field_name": "seller_name", + "ocr_value": "示例卖方公司", + "llm_value": None, + "final_value": "示例卖方公司", + "source": "ocr", + "needs_review": False, + }, + { + "field_name": "seller_tax_id", + "ocr_value": "TESTSELLER00000001", + "llm_value": "TESTSELLER00000001", + "final_value": "TESTSELLER00000001", + "source": "matched", + "needs_review": False, + }, + { + "field_name": "item_name", + "ocr_value": "OCR项目", + "llm_value": "LLM项目", + "final_value": None, + "source": "conflict", + "needs_review": True, + }, + { + "field_name": "total_with_tax", + "ocr_value": "¥1,060.00", + "llm_value": "1060", + "final_value": "¥1,060.00", + "source": "matched", + "needs_review": False, + }, + { + "field_name": "amount", + "ocr_value": "1000.00", + "llm_value": "1000.0", + "final_value": "1000.00", + "source": "matched", + "needs_review": False, + }, + { + "field_name": "tax_amount", + "ocr_value": "60.00", + "llm_value": "60", + "final_value": "60.00", + "source": "matched", + "needs_review": False, + }, + { + "field_name": "tax_rate", + "ocr_value": "6%", + "llm_value": None, + "final_value": "6%", + "source": "ocr", + "needs_review": False, + }, + ]