Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,6 @@ docs
backend/venv
venv
.venv
**/*.egg-info
packages/*/build
packages/*/dist
23 changes: 22 additions & 1 deletion .github/workflows/docker-publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down
8 changes: 4 additions & 4 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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 \
Expand All @@ -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/ .
Expand Down
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
144 changes: 10 additions & 134 deletions backend/app/services/invoice_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,22 @@
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

from app.models.invoice import Invoice, OcrResult, LlmResult, ParsingDiff, InvoiceStatus
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()
Expand All @@ -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."""
Expand Down Expand Up @@ -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)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if images:
# Convert PIL Image to bytes with high quality
buffer = BytesIO()
Expand Down Expand Up @@ -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
Expand Down
77 changes: 4 additions & 73 deletions backend/app/services/llm_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading