"""DLA prompt, HTML block parsing, and document outline helpers.""" import re from html.parser import HTMLParser TAG = re.compile(r"<[^>]+>") FURNITURE_LABELS = {"Header", "Footer"} PROMPT = """OCR this image to HTML, arranged as layout blocks. Each layout block must be a div with a data-bbox attribute in x0 y0 x1 y1 format. Bounding boxes are normalized to the 0-1000 range. The data-label attribute must contain exactly one of these labels: - Title: the main title of the document - Section Header: a heading that introduces a section - Header: repeated or auxiliary content at the top of a page - Footer: repeated or auxiliary content at the bottom of a page - Paragraph: normal textual content that does not belong to another label - Table: a table, preserving rows, columns, colspan, and rowspan in HTML - Barcode: a one-dimensional barcode - QR Code: a QR code - Signature: a handwritten signature - Stamp: an ink or digital stamp/seal - Image: any other image, figure, photo, chart, or diagram Preserve the natural reading order. Preserve all visible text accurately. Use HTML inside each block; tables must remain HTML tables. Use the simplest HTML structure that accurately represents the content. Return only the HTML layout blocks, without Markdown fences, explanations, JSON, or a surrounding html/body tag. """ class LayoutParser(HTMLParser): def __init__(self): super().__init__(convert_charrefs=True) self.blocks, self.depth, self.current = [], 0, None def handle_starttag(self, tag, attrs): if tag == "div": self.depth += 1 if self.depth == 1: values = dict(attrs) self.current = {"bbox_raw": values.get("data-bbox"), "label": values.get("data-label", "Unknown"), "html": []} return if self.current is not None: attr_str = "".join(f' {k}="{v}"' for k, v in attrs if v is not None) self.current["html"].append(f"<{tag}{attr_str}>") def handle_startendtag(self, tag, attrs): if self.current is not None: attr_str = "".join(f' {k}="{v}"' for k, v in attrs if v is not None) self.current["html"].append(f"<{tag}{attr_str}/>") def handle_data(self, data): if self.current is not None: self.current["html"].append(data) def handle_endtag(self, tag): if tag == "div": if self.depth == 1 and self.current is not None: self._flush() self.depth = 0 return self.depth = max(0, self.depth - 1) if self.current is not None: self.current["html"].append(f"") def _flush(self): block = self.current self.current = None bbox = None if block["bbox_raw"]: try: parts = [round(float(v)) for v in block["bbox_raw"].replace(",", " ").split()] if len(parts) == 4: bbox = parts except ValueError: pass self.blocks.append({"bbox": bbox, "label": block["label"], "html": "".join(block["html"]).strip()}) def close(self): super().close() if self.current is not None: self._flush() def parse_blocks(raw: str): parser = LayoutParser() parser.feed(raw) parser.close() return parser.blocks def plain_text(html: str) -> str: return re.sub(r"\s+", " ", TAG.sub(" ", html or "")).strip() def build_outline(pages: list) -> list: sections, current, counter = [], None, 0 def open_section(header=None): nonlocal counter if header is not None: counter += 1 section = {"section_no": str(counter) if header is not None else "0", "heading_block_id": header["block_id"] if header else None, "heading": plain_text(header["html"]) if header else None, "block_ids": []} sections.append(section) return section for page in pages: for block in page["blocks"]: if block["label"] in FURNITURE_LABELS: block["outline_no"] = None continue if block["label"] == "Section Header": current = open_section(block) block["outline_no"] = current["section_no"] continue if current is None: current = open_section() current["block_ids"].append(block["block_id"]) block["outline_no"] = f"{current['section_no']}.{len(current['block_ids'])}" return sections