feat(extract): support plain XML invoices and UBL syntax
/extract now accepts all EN 16931 e-invoices, not only ZUGFeRD PDFs:
- plain XML files via the new xml_base64 field; XML sent as pdf_base64
is detected from the content
- UBL 2.1 Invoice and CreditNote (XRechnung UBL, Peppol BIS Billing) via
the new src/ubl_parser.py, also when embedded in a PDF
- new response field xml_syntax ("CII" or "UBL")
- CII invoice dates are normalized to YYYY-MM-DD, matching UBL
- XRechnung profiles are detected from the specification identifier,
independent of the factur-x version (6.x reports them as EN16931)
- untrusted XML is parsed without entity or DTD resolution (XXE)
Fixtures: KoSIT XRechnung test-suite case 01.01a in CII and UBL.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
+241
-33
@@ -1,10 +1,16 @@
|
||||
"""ZUGFeRD/Factur-X extractor.
|
||||
"""E-invoice extractor.
|
||||
|
||||
Extracts structured invoice data from PDF files using the factur-x library.
|
||||
Supports ZUGFeRD 2.x profiles: MINIMUM, BASIC, BASIC WL, EN16931, EXTENDED.
|
||||
Extracts structured invoice data from EN 16931 e-invoices in both syntaxes:
|
||||
|
||||
- CII (UN/CEFACT Cross Industry Invoice): ZUGFeRD 2.x / Factur-X profiles
|
||||
MINIMUM, BASIC, BASIC WL, EN16931, EXTENDED and XRechnung CII
|
||||
- UBL 2.1 (Invoice and CreditNote): XRechnung UBL, Peppol BIS Billing
|
||||
|
||||
Input is either a hybrid PDF with embedded XML or the plain XML file.
|
||||
"""
|
||||
|
||||
import io
|
||||
import re
|
||||
import time
|
||||
|
||||
from facturx import get_flavor, get_level, get_xml_from_pdf
|
||||
@@ -23,8 +29,16 @@ from src.models import (
|
||||
VatBreakdown,
|
||||
XmlData,
|
||||
)
|
||||
from src.ubl_parser import UBL_NAMESPACES, is_ubl_root, parse_ubl_xml
|
||||
|
||||
|
||||
MAX_FILE_SIZE = 10 * 1024 * 1024
|
||||
|
||||
CII_ROOT_TAG = (
|
||||
"{urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100}"
|
||||
"CrossIndustryInvoice"
|
||||
)
|
||||
|
||||
NAMESPACES = {
|
||||
"rsm": "urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100",
|
||||
"ram": "urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100",
|
||||
@@ -42,6 +56,25 @@ class ExtractionError(Exception):
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
def _parse_xml(xml_bytes: bytes) -> etree._Element:
|
||||
"""Parse untrusted invoice XML without resolving entities or DTDs.
|
||||
|
||||
Invoice XML arrives from outside (API upload or PDF attachment), so
|
||||
external entities and network access are disabled (XXE protection).
|
||||
|
||||
Args:
|
||||
xml_bytes: Raw XML content
|
||||
|
||||
Returns:
|
||||
XML root element
|
||||
|
||||
Raises:
|
||||
etree.XMLSyntaxError: If the content is not well-formed XML
|
||||
"""
|
||||
parser = etree.XMLParser(resolve_entities=False, no_network=True, load_dtd=False)
|
||||
return etree.fromstring(xml_bytes, parser=parser)
|
||||
|
||||
|
||||
def extract_text_from_pdf(pdf_bytes: bytes) -> str:
|
||||
"""Extract text from PDF using pypdf.
|
||||
|
||||
@@ -368,6 +401,22 @@ def parse_payment_terms(xml_root: etree._Element) -> PaymentTerms | None:
|
||||
)
|
||||
|
||||
|
||||
def _normalize_cii_date(value: str) -> str:
|
||||
"""Convert a CII date in format 102 (YYYYMMDD) to ISO notation.
|
||||
|
||||
Args:
|
||||
value: Date string from a udt:DateTimeString element
|
||||
|
||||
Returns:
|
||||
Date as YYYY-MM-DD; values that are not eight digits are returned
|
||||
stripped but otherwise unchanged
|
||||
"""
|
||||
value = value.strip()
|
||||
if re.fullmatch(r"\d{8}", value):
|
||||
return f"{value[:4]}-{value[4:6]}-{value[6:]}"
|
||||
return value
|
||||
|
||||
|
||||
def parse_zugferd_xml(xml_bytes: bytes) -> XmlData:
|
||||
"""Parse ZUGFeRD XML bytes to structured XmlData.
|
||||
|
||||
@@ -377,7 +426,7 @@ def parse_zugferd_xml(xml_bytes: bytes) -> XmlData:
|
||||
Returns:
|
||||
XmlData model with all invoice fields
|
||||
"""
|
||||
xml_root = etree.fromstring(xml_bytes)
|
||||
xml_root = _parse_xml(xml_bytes)
|
||||
|
||||
invoice_number = xml_root.xpath(
|
||||
"//rsm:ExchangedDocument/ram:ID/text()", namespaces=NAMESPACES
|
||||
@@ -403,7 +452,7 @@ def parse_zugferd_xml(xml_bytes: bytes) -> XmlData:
|
||||
|
||||
return XmlData(
|
||||
invoice_number=invoice_number[0] if invoice_number else "",
|
||||
invoice_date=invoice_date[0] if invoice_date else "",
|
||||
invoice_date=_normalize_cii_date(invoice_date[0]) if invoice_date else "",
|
||||
due_date=due_date[0] if due_date else None,
|
||||
supplier=parse_supplier(xml_root),
|
||||
buyer=parse_buyer(xml_root),
|
||||
@@ -475,7 +524,7 @@ def _find_xml_attachment_fallback(pdf_bytes: bytes) -> tuple[str | None, bytes |
|
||||
|
||||
if subtype and ("xml" in str(subtype).lower() or "xml" in att.name.lower()):
|
||||
try:
|
||||
etree.fromstring(att.content)
|
||||
_parse_xml(att.content)
|
||||
logger.debug(
|
||||
"Found XML attachment via MIME fallback: %s",
|
||||
att.name,
|
||||
@@ -494,7 +543,7 @@ def _find_xml_attachment_fallback(pdf_bytes: bytes) -> tuple[str | None, bytes |
|
||||
continue
|
||||
if att.name.lower().endswith(".xml"):
|
||||
try:
|
||||
etree.fromstring(att.content)
|
||||
_parse_xml(att.content)
|
||||
logger.debug(
|
||||
"Found XML attachment via extension fallback: %s",
|
||||
att.name,
|
||||
@@ -527,8 +576,188 @@ def _profile_from_urn(urn: str) -> str:
|
||||
return urn.rsplit("#", maxsplit=1)[-1].rsplit(":", maxsplit=1)[-1]
|
||||
|
||||
|
||||
def _profile_from_customization_id(urn: str) -> str:
|
||||
"""Derive a readable profile name from a UBL CustomizationID (BT-24).
|
||||
|
||||
Args:
|
||||
urn: The specification identifier (e.g.
|
||||
'urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0')
|
||||
|
||||
Returns:
|
||||
Short profile name (e.g. 'xrechnung_3.0', 'peppol_bis_billing_3.0',
|
||||
'en16931'), or 'unknown'
|
||||
"""
|
||||
lowered = urn.strip().lower()
|
||||
|
||||
xrechnung = re.search(r"xrechnung_(\d+(?:\.\d+)*)", lowered)
|
||||
if xrechnung:
|
||||
return f"xrechnung_{xrechnung.group(1)}"
|
||||
|
||||
peppol = re.search(r"peppol.*billing:(\d+(?:\.\d+)*)", lowered)
|
||||
if peppol:
|
||||
return f"peppol_bis_billing_{peppol.group(1)}"
|
||||
|
||||
if lowered == "urn:cen.eu:en16931:2017":
|
||||
return "en16931"
|
||||
|
||||
return _profile_from_urn(lowered)
|
||||
|
||||
|
||||
def _interpret_invoice_xml(xml_bytes: bytes) -> tuple[str, str, XmlData]:
|
||||
"""Detect syntax and profile of invoice XML and parse it.
|
||||
|
||||
Args:
|
||||
xml_bytes: Raw invoice XML (CII or UBL)
|
||||
|
||||
Returns:
|
||||
Tuple of (syntax, profile, parsed data); syntax is 'CII' or 'UBL'
|
||||
"""
|
||||
xml_root = _parse_xml(xml_bytes)
|
||||
|
||||
if is_ubl_root(xml_root):
|
||||
urn_nodes = xml_root.xpath(
|
||||
"./cbc:CustomizationID/text()", namespaces=UBL_NAMESPACES
|
||||
)
|
||||
urn = urn_nodes[0] if urn_nodes else ""
|
||||
return "UBL", _profile_from_customization_id(urn), parse_ubl_xml(xml_root)
|
||||
|
||||
# GuidelineSpecifiedDocumentContextParameter uses ram: namespace
|
||||
urn_nodes = xml_root.xpath(
|
||||
"//rsm:ExchangedDocumentContext/"
|
||||
"ram:GuidelineSpecifiedDocumentContextParameter/ram:ID/text()",
|
||||
namespaces=NAMESPACES,
|
||||
)
|
||||
urn = urn_nodes[0] if urn_nodes else ""
|
||||
|
||||
# XRechnung first: depending on its version, factur-x either rejects the
|
||||
# XRechnung URN or reports it as plain EN16931.
|
||||
xrechnung = re.search(r"xrechnung_(\d+(?:\.\d+)*)", urn.lower())
|
||||
if xrechnung:
|
||||
level = f"xrechnung_{xrechnung.group(1)}"
|
||||
else:
|
||||
flavor = get_flavor(xml_root)
|
||||
try:
|
||||
level = get_level(xml_root, flavor)
|
||||
except ValueError:
|
||||
level = _profile_from_urn(urn)
|
||||
|
||||
return "CII", level, parse_zugferd_xml(xml_bytes)
|
||||
|
||||
|
||||
def _xml_to_text(xml_bytes: bytes) -> str:
|
||||
"""Decode raw XML bytes to a string for the xml_raw response field.
|
||||
|
||||
Args:
|
||||
xml_bytes: Raw XML content in any encoding XML allows
|
||||
|
||||
Returns:
|
||||
XML document as string
|
||||
"""
|
||||
try:
|
||||
return xml_bytes.decode("utf-8-sig")
|
||||
except UnicodeDecodeError:
|
||||
return etree.tostring(_parse_xml(xml_bytes), encoding="unicode")
|
||||
|
||||
|
||||
def _check_file_size(data: bytes) -> None:
|
||||
"""Reject uploads above the size limit.
|
||||
|
||||
Args:
|
||||
data: Raw file content
|
||||
|
||||
Raises:
|
||||
ExtractionError: If the file exceeds 10MB
|
||||
"""
|
||||
if len(data) > MAX_FILE_SIZE:
|
||||
raise ExtractionError(
|
||||
error_code="file_too_large",
|
||||
message="File exceeds 10MB limit",
|
||||
details=f"Size: {len(data)} bytes",
|
||||
)
|
||||
|
||||
|
||||
def extract_from_xml(xml_bytes: bytes) -> ExtractResponse:
|
||||
"""Extract invoice data from a plain e-invoice XML file.
|
||||
|
||||
Handles XRechnung and other EN 16931 invoices delivered without a PDF,
|
||||
in CII or UBL syntax.
|
||||
|
||||
Args:
|
||||
xml_bytes: Raw XML file content
|
||||
|
||||
Returns:
|
||||
ExtractResponse with is_zugferd, profile, xml_syntax and xml_data
|
||||
|
||||
Raises:
|
||||
ExtractionError: For malformed XML or unsupported document types
|
||||
"""
|
||||
start_time = time.time()
|
||||
_check_file_size(xml_bytes)
|
||||
|
||||
try:
|
||||
xml_root = _parse_xml(xml_bytes)
|
||||
except etree.XMLSyntaxError as e:
|
||||
raise ExtractionError(
|
||||
error_code="invalid_xml", message="Invalid XML file", details=str(e)
|
||||
) from e
|
||||
|
||||
if not is_ubl_root(xml_root) and xml_root.tag != CII_ROOT_TAG:
|
||||
raise ExtractionError(
|
||||
error_code="unsupported_xml_format",
|
||||
message="XML is not a supported e-invoice (CII or UBL)",
|
||||
details=f"Root element: {xml_root.tag}",
|
||||
)
|
||||
|
||||
syntax, level, xml_data = _interpret_invoice_xml(xml_bytes)
|
||||
|
||||
return ExtractResponse(
|
||||
is_zugferd=True,
|
||||
zugferd_profil=level.upper(),
|
||||
xml_syntax=syntax,
|
||||
xml_raw=_xml_to_text(xml_bytes),
|
||||
xml_data=xml_data,
|
||||
pdf_text=None,
|
||||
extraction_meta=ExtractionMeta(
|
||||
pages=0,
|
||||
xml_attachment_name=None,
|
||||
extraction_time_ms=int((time.time() - start_time) * 1000),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def extract_invoice(data: bytes) -> ExtractResponse:
|
||||
"""Extract invoice data from any supported e-invoice file.
|
||||
|
||||
The file type is detected from the content: PDFs (ZUGFeRD/Factur-X or
|
||||
any PDF with an embedded invoice XML) and plain XML files (CII or UBL).
|
||||
|
||||
Args:
|
||||
data: Raw file content (PDF or XML)
|
||||
|
||||
Returns:
|
||||
ExtractResponse with extraction results
|
||||
|
||||
Raises:
|
||||
ExtractionError: For unreadable or unsupported files
|
||||
"""
|
||||
_check_file_size(data)
|
||||
|
||||
if b"%PDF-" in data[:1024]:
|
||||
return extract_zugferd(data)
|
||||
|
||||
try:
|
||||
_parse_xml(data)
|
||||
except etree.XMLSyntaxError:
|
||||
if b"<" in data[:200]:
|
||||
return extract_from_xml(data)
|
||||
# Neither PDF nor XML: let the PDF path report the error
|
||||
return extract_zugferd(data)
|
||||
|
||||
return extract_from_xml(data)
|
||||
|
||||
|
||||
def extract_zugferd(pdf_bytes: bytes) -> ExtractResponse:
|
||||
"""Extract ZUGFeRD data from PDF bytes.
|
||||
"""Extract e-invoice data from PDF bytes.
|
||||
|
||||
Args:
|
||||
pdf_bytes: Raw PDF file content as bytes
|
||||
@@ -540,17 +769,10 @@ def extract_zugferd(pdf_bytes: bytes) -> ExtractResponse:
|
||||
ExtractionError: For PDF processing errors
|
||||
"""
|
||||
start_time = time.time()
|
||||
|
||||
if len(pdf_bytes) > 10 * 1024 * 1024:
|
||||
raise ExtractionError(
|
||||
error_code="file_too_large",
|
||||
message="File exceeds 10MB limit",
|
||||
details=f"Size: {len(pdf_bytes)} bytes",
|
||||
)
|
||||
_check_file_size(pdf_bytes)
|
||||
|
||||
xml_filename = None
|
||||
xml_bytes = None
|
||||
|
||||
try:
|
||||
xml_filename, xml_bytes = get_xml_from_pdf(pdf_bytes, check_xsd=False)
|
||||
except Exception as e:
|
||||
@@ -591,22 +813,7 @@ def extract_zugferd(pdf_bytes: bytes) -> ExtractResponse:
|
||||
),
|
||||
)
|
||||
|
||||
xml_root = etree.fromstring(xml_bytes)
|
||||
flavor = get_flavor(xml_root)
|
||||
|
||||
try:
|
||||
level = get_level(xml_root, flavor)
|
||||
except ValueError:
|
||||
# GuidelineSpecifiedDocumentContextParameter uses ram: namespace
|
||||
urn_nodes = xml_root.xpath(
|
||||
"//rsm:ExchangedDocumentContext/"
|
||||
"ram:GuidelineSpecifiedDocumentContextParameter/ram:ID/text()",
|
||||
namespaces=NAMESPACES,
|
||||
)
|
||||
urn = urn_nodes[0] if urn_nodes else ""
|
||||
level = _profile_from_urn(urn)
|
||||
|
||||
xml_data = parse_zugferd_xml(xml_bytes)
|
||||
syntax, level, xml_data = _interpret_invoice_xml(xml_bytes)
|
||||
pdf_text = extract_text_from_pdf(pdf_bytes)
|
||||
pages = get_pdf_page_count(pdf_bytes)
|
||||
extraction_time_ms = int((time.time() - start_time) * 1000)
|
||||
@@ -614,7 +821,8 @@ def extract_zugferd(pdf_bytes: bytes) -> ExtractResponse:
|
||||
return ExtractResponse(
|
||||
is_zugferd=True,
|
||||
zugferd_profil=level.upper(),
|
||||
xml_raw=xml_bytes.decode("utf-8"),
|
||||
xml_syntax=syntax,
|
||||
xml_raw=_xml_to_text(xml_bytes),
|
||||
xml_data=xml_data,
|
||||
pdf_text=pdf_text,
|
||||
extraction_meta=ExtractionMeta(
|
||||
|
||||
Reference in New Issue
Block a user