# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. # Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). # This is not open-source software: see the license for permitted uses. """Layout elements of a raw ocria answer: the character spans that each get one box, with a type. The answer is ocria's no-layout transcription (markdown, HTML tables, ``/``/`` furniture tags, `![label: description]` image references, ```mermaid diagrams). Each element becomes one `` marker, so the types are the box-mode vocabulary the layout scorer already reads (`layout_score._BOX_TYPE_TO_REGION_LABEL`): text, heading, list, table, image, code, header, footer. Granularity (one element per ...): paragraph (blank-line separated), heading line, list item (with its indented continuation lines), whole table, image reference, fenced block, display-math block, furniture band. A standalone `` gets type "page_number" and is resolved to header/footer from its box (`resolve_page_numbers`). Offsets index the raw answer, fence included, so they line up with the teacher-forced tokens. """ from __future__ import annotations import re from collections.abc import Callable from dataclasses import dataclass from .tune import FLAGS _OPEN_FENCE = re.compile(r"\A\s*```(?:markdown|md)?[ \t]*\n") _FURN_OPEN = re.compile(r"<(page_header|page_footer|watermark)>") _PAGE_NUMBER = re.compile(r"^\s*.*?\s*$") _HEADING = re.compile(r"^\s{0,3}#{1,6}\s") _IMAGE = re.compile(r"^\s*!\[") _FENCE = re.compile(r"^\s*```") _MATH = re.compile(r"^\s*\$\$") _PIPE_ROW = re.compile(r"^\s*\|") _TABLE_OPEN = re.compile(r"<(table|rcl)\b", re.I) # HTML table, or ocria-1.5's RCL grid _LIST_ITEM = re.compile( r"^(\s*)(?:[*\-+•▪◦»]\s|\d{1,3}[.)]\s|\(?[a-zA-Z][.)]\s|\[[ xX_]*\]\s)" ) _QUOTE_PREFIX = re.compile(r"^(?: {0,3}>[ \t]?)+") _BOLD_LINE = re.compile(r"^\s*\*\*[^*]+\*\*:?\s*$") _TYPES_FOR_FURN = { "page_header": "header", "page_footer": "footer", "watermark": "text", } @dataclass class Block: type: str start: int end: int def _lines(text: str, lo: int, hi: int) -> list[tuple[int, int, str]]: """(start, end, line) for each line of text[lo:hi]; end excludes the newline.""" out, pos = [], lo while pos < hi: nl = text.find("\n", pos, hi) end = hi if nl < 0 else nl out.append((pos, end, text[pos:end])) pos = end + 1 return out def body_span(text: str) -> tuple[int, int]: """The transcription inside the ```markdown fence (the whole answer when there is none).""" lo, hi = 0, len(text) m = _OPEN_FENCE.match(text) if m: lo = m.end() close = text.rfind("```") if close >= lo: hi = close return lo, hi def _starts_construct(line: str) -> bool: return bool( _HEADING.match(line) or _IMAGE.match(line) or _FENCE.match(line) or _MATH.match(line) or _PIPE_ROW.match(line) or _TABLE_OPEN.search(line) or _FURN_OPEN.search(line) or _PAGE_NUMBER.match(line) or _LIST_ITEM.match(line) ) def split_blocks(text: str) -> list[Block]: """Layout elements of one page's raw answer, in reading order.""" lo, hi = body_span(text) lines = _lines(text, lo, hi) blocks: list[Block] = [] i = 0 def until(j: int, pred: Callable[[str], bool]) -> int: """Index of the first line from j on for which pred holds (the last line when none does).""" while j < len(lines) and not pred(lines[j][2]): j += 1 return min(j, len(lines) - 1) while i < len(lines): s, e, line = lines[i] if not line.strip(): i += 1 continue m = _FURN_OPEN.search(line) if m: tag = m.group(1) close = f"" j = i if close in line else until(i + 1, lambda x: close in x) blocks.append(Block(_TYPES_FOR_FURN[tag], s, lines[j][1])) i = j + 1 continue if _PAGE_NUMBER.match(line): blocks.append(Block("page_number", s, e)) i += 1 continue tm = _TABLE_OPEN.search(line) if tm: close = "" if tm.group(1).lower() == "table" else "" j = ( i if close in line.lower() else until(i + 1, lambda x: close in x.lower()) ) if "split_layout_tables" in FLAGS and _is_layout_table( text[s : lines[j][1]] ): blocks.extend(_layout_table_blocks(text, s, lines[j][1])) else: blocks.append(Block("table", s, lines[j][1])) i = j + 1 continue if _FENCE.match(line): j = until(i + 1, lambda x: _FENCE.match(x) is not None) kind = "image" if "mermaid" in line.lower() else "code" blocks.append(Block(kind, s, lines[j][1])) i = j + 1 continue if _MATH.match(line): rest = line.strip()[2:] j = i if "$$" in rest else until(i + 1, lambda x: "$$" in x) blocks.append(Block("text", s, lines[j][1])) i = j + 1 continue if _HEADING.match(line): blocks.append(Block("heading", s, e)) i += 1 continue if _IMAGE.match(line): blocks.append(Block("image", s, e)) i += 1 continue if _PIPE_ROW.match(line): j = i while j + 1 < len(lines) and _PIPE_ROW.match(lines[j + 1][2]): j += 1 blocks.append(Block("table", s, lines[j][1])) i = j + 1 continue lm = _LIST_ITEM.match(line) if lm: indent = len(lm.group(1)) j = i while j + 1 < len(lines): nxt = lines[j + 1][2] if not nxt.strip() or _starts_construct(nxt): break if ( len(nxt) - len(nxt.lstrip()) <= indent ): # a continuation line is indented under the marker break j += 1 blocks.append(Block("list", s, lines[j][1])) i = j + 1 continue if ( "split_lines" in FLAGS ): # each line its own element; a bold-only line is a heading blocks.append(Block("heading" if _BOLD_LINE.match(line) else "text", s, e)) i += 1 continue j = i # paragraph: until a blank line or a line that opens another element while ( j + 1 < len(lines) and lines[j + 1][2].strip() and not _starts_construct(lines[j + 1][2]) ): j += 1 blocks.append(Block("text", s, lines[j][1])) i = j + 1 blocks = [piece for block in blocks for piece in _split_quoted_list(text, block)] if "inline_images" in FLAGS: blocks = [p for b in blocks for p in _split_inline_images(text, b)] return blocks def _split_quoted_list(text: str, block: Block) -> list[Block]: """Expose quoted list items while retaining raw offsets and continuation lines. Quote prefixes are ignored only for recognizing markers. Keeping the raw spans preserves the word sequence used by cached sparse attention maps. """ if block.type != "text" or ">" not in text[block.start : block.end]: return [block] result: list[Block] = [] start, kind = block.start, block.type for line_start, _, line in _lines(text, block.start, block.end): prefix = _QUOTE_PREFIX.match(line) if prefix is None or not _LIST_ITEM.match(line[prefix.end() :]): continue if line_start > start and text[start:line_start].strip(" >\t\r\n"): result.append(Block(kind, start, line_start)) start, kind = line_start, "list" result.append(Block(kind, start, block.end)) return result _INLINE_IMAGE = re.compile(r"!\[[^\]\n]*\](?:\([^)\s]*\))?") def _split_inline_images(text: str, b: Block) -> list[Block]: """An image reference inside a text-like element (an icon after a heading, a logo next to a footer's page number) is a picture of its own on the page: the element is cut into the text before it, the image, and the text after.""" if b.type in ("image", "table", "code") or "![" not in text[b.start : b.end]: return [b] out, pos = [], b.start for m in _INLINE_IMAGE.finditer(text, b.start, b.end): if _TAGS.sub("", text[pos : m.start()]).strip(" \t\n|*#-"): out.append(Block(b.type, pos, m.start())) out.append(Block("image", m.start(), m.end())) pos = m.end() if _TAGS.sub("", text[pos : b.end]).strip(" \t\n|*#-"): out.append(Block(b.type, pos, b.end)) return out or [b] def resolve_page_numbers(blocks: list[Block], boxes: list, page_height: float) -> None: """A standalone page number is furniture: header when its box sits in the top half, else footer.""" for b, box in zip(blocks, boxes): if b.type == "page_number": b.type = ( "header" if box is not None and (box[1] + box[3]) / 2 < page_height / 2 else "footer" ) _CELL = re.compile(r"]*>(.*?)", re.S | re.I) _TAGS = re.compile(r"<[^>]+>") def _is_layout_table(html: str) -> bool: """A table used to lay out a page (people grids, card layouts), not data: it holds image references, or its cells hold prose (mean >= 8 words).""" if "![" in html: return True words = [len(_TAGS.sub(" ", c).split()) for c in _CELL.findall(html) if c.strip()] return bool(words) and sum(words) / len(words) >= 8 def _layout_table_blocks(text: str, lo: int, hi: int) -> list[Block]: """One element per segment of each cell: segments split at blank lines (two or more
, or any
with split_br), an image reference is its own element.""" sep = re.compile( r"(?:\s*)+" if "split_br" in FLAGS else r"(?:\s*){2,}", re.I ) out: list[Block] = [] for m in _CELL.finditer(text, lo, hi): a, b = m.start(1), m.end(1) pos = a for cut in [*sep.finditer(text, a, b), None]: end = cut.start() if cut else b seg = text[pos:end] if _TAGS.sub("", seg).strip(): k = pos + (len(seg) - len(seg.lstrip())) origin = k for im in re.finditer(r"!\[[^\]]*\]", text[origin:end]): start, stop = origin + im.start(), origin + im.end() if text[k:start].strip(): out.append(Block("text", k, start)) out.append(Block("image", start, stop)) k = stop if _TAGS.sub("", text[k:end]).strip(): out.append(Block("text", k, end)) pos = cut.end() if cut else b return out