Spaces:
Sleeping
Sleeping
File size: 6,696 Bytes
1cbec06 bbbfba8 1cbec06 bbbfba8 1cbec06 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 | """ALTO XML serializer β deterministic conversion from CanonicalDocument to ALTO v4.
This serializer is a pure output transformation. It MUST NOT:
- Call any model or provider
- Reconstruct segmentation
- Correct text
- Invent coordinates
- Make export eligibility decisions
It receives a validated CanonicalDocument and produces ALTO XML bytes.
ALTO mapping:
Page β <Page>
TextRegion β <TextBlock>
TextLine β <TextLine>
Word β <String>
Coordinate mapping:
bbox[0] β HPOS
bbox[1] β VPOS
bbox[2] β WIDTH
bbox[3] β HEIGHT
text β CONTENT
confidence β WC
hyphenation.part=1 β SUBS_TYPE="HypPart1"
hyphenation.part=2 β SUBS_TYPE="HypPart2"
hyphenation.full_form β SUBS_CONTENT
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from lxml import etree
from src.app.geometry.quantization import RoundingStrategy, quantize_bbox
if TYPE_CHECKING:
from src.app.domain.models import CanonicalDocument, Page, TextLine, TextRegion, Word
ALTO_NS = "http://www.loc.gov/standards/alto/ns-v4#"
XSI_NS = "http://www.w3.org/2001/XMLSchema-instance"
SCHEMA_LOCATION = (
"http://www.loc.gov/standards/alto/ns-v4# "
"http://www.loc.gov/standards/alto/v4/alto-4-2.xsd"
)
NSMAP = {
None: ALTO_NS,
"xsi": XSI_NS,
}
def serialize_alto(
doc: CanonicalDocument,
*,
rounding: RoundingStrategy = RoundingStrategy.ROUND,
pretty_print: bool = True,
encoding: str = "UTF-8",
) -> bytes:
"""Serialize a CanonicalDocument to ALTO v4 XML bytes.
Args:
doc: The validated canonical document.
rounding: Strategy for converting float coordinates to integers.
pretty_print: Whether to indent the XML output.
encoding: Output encoding.
Returns:
The ALTO XML as bytes.
"""
root = _build_alto_tree(doc, rounding)
return etree.tostring(
root,
pretty_print=pretty_print,
xml_declaration=True,
encoding=encoding,
)
def serialize_alto_to_string(
doc: CanonicalDocument,
*,
rounding: RoundingStrategy = RoundingStrategy.ROUND,
) -> str:
"""Serialize to a UTF-8 string (convenience for tests)."""
return serialize_alto(doc, rounding=rounding).decode("utf-8")
# -- Tree construction --------------------------------------------------------
def _build_alto_tree(
doc: CanonicalDocument, rounding: RoundingStrategy
) -> etree._Element:
root = etree.Element(f"{{{ALTO_NS}}}alto", nsmap=NSMAP)
root.set(f"{{{XSI_NS}}}schemaLocation", SCHEMA_LOCATION)
# <Description>
desc = etree.SubElement(root, f"{{{ALTO_NS}}}Description")
_add_description(desc, doc)
# <Layout>
layout = etree.SubElement(root, f"{{{ALTO_NS}}}Layout")
for page in doc.pages:
_add_page(layout, page, rounding)
return root
def _add_description(desc: etree._Element, doc: CanonicalDocument) -> None:
"""Add <Description> metadata."""
measurement = etree.SubElement(desc, f"{{{ALTO_NS}}}MeasurementUnit")
measurement.text = "pixel"
src_info = etree.SubElement(desc, f"{{{ALTO_NS}}}sourceImageInformation")
file_name = etree.SubElement(src_info, f"{{{ALTO_NS}}}fileName")
file_name.text = doc.source.filename or doc.document_id
# Processing info
processing = etree.SubElement(desc, f"{{{ALTO_NS}}}Processing")
processing.set("ID", "proc_1")
sw = etree.SubElement(processing, f"{{{ALTO_NS}}}processingSoftware")
sw_name = etree.SubElement(sw, f"{{{ALTO_NS}}}softwareName")
sw_name.text = "XmLLM"
sw_version = etree.SubElement(sw, f"{{{ALTO_NS}}}softwareVersion")
sw_version.text = doc.schema_version
def _add_page(
layout: etree._Element, page: Page, rounding: RoundingStrategy
) -> None:
"""Add a <Page> with its <PrintSpace> and blocks."""
page_el = etree.SubElement(layout, f"{{{ALTO_NS}}}Page")
page_el.set("ID", page.id)
page_el.set("PHYSICAL_IMG_NR", str(page.page_index + 1))
page_el.set("WIDTH", str(int(page.width)))
page_el.set("HEIGHT", str(int(page.height)))
# <PrintSpace> covers the entire page
ps = etree.SubElement(page_el, f"{{{ALTO_NS}}}PrintSpace")
ps.set("HPOS", "0")
ps.set("VPOS", "0")
ps.set("WIDTH", str(int(page.width)))
ps.set("HEIGHT", str(int(page.height)))
for region in page.text_regions:
_add_text_block(ps, region, rounding)
def _add_text_block(
parent: etree._Element, region: TextRegion, rounding: RoundingStrategy
) -> None:
"""Add a <TextBlock> with its lines."""
tb = etree.SubElement(parent, f"{{{ALTO_NS}}}TextBlock")
tb.set("ID", region.id)
_set_bbox_attrs(tb, region.geometry.bbox, rounding)
if region.lang:
tb.set("LANG", region.lang)
for line in region.lines:
_add_text_line(tb, line, rounding)
def _add_text_line(
parent: etree._Element, line: TextLine, rounding: RoundingStrategy
) -> None:
"""Add a <TextLine> with its strings."""
tl = etree.SubElement(parent, f"{{{ALTO_NS}}}TextLine")
tl.set("ID", line.id)
_set_bbox_attrs(tl, line.geometry.bbox, rounding)
for i, word in enumerate(line.words):
if i > 0:
_add_sp(tl)
_add_string(tl, word, rounding)
def _add_string(
parent: etree._Element, word: Word, rounding: RoundingStrategy
) -> None:
"""Add a <String> element for a word."""
s = etree.SubElement(parent, f"{{{ALTO_NS}}}String")
s.set("ID", word.id)
_set_bbox_attrs(s, word.geometry.bbox, rounding)
s.set("CONTENT", word.text)
if word.confidence is not None:
s.set("WC", f"{word.confidence:.2f}")
if word.lang:
s.set("LANG", word.lang)
# Hyphenation
if word.hyphenation and word.hyphenation.is_hyphenated:
if word.hyphenation.part == 1:
s.set("SUBS_TYPE", "HypPart1")
elif word.hyphenation.part == 2:
s.set("SUBS_TYPE", "HypPart2")
if word.hyphenation.full_form:
s.set("SUBS_CONTENT", word.hyphenation.full_form)
def _add_sp(parent: etree._Element) -> None:
"""Add a <SP> (space) element between words."""
etree.SubElement(parent, f"{{{ALTO_NS}}}SP")
# -- Helpers ------------------------------------------------------------------
def _set_bbox_attrs(
el: etree._Element,
bbox: tuple[float, float, float, float],
rounding: RoundingStrategy,
) -> None:
"""Set HPOS, VPOS, WIDTH, HEIGHT attributes from a canonical bbox."""
hpos, vpos, width, height = quantize_bbox(bbox, rounding)
el.set("HPOS", str(hpos))
el.set("VPOS", str(vpos))
el.set("WIDTH", str(width))
el.set("HEIGHT", str(height))
|