# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: OpenMDW-1.1 """Shared block grammar: an invalid block cannot consume the following block.""" import re # A class terminator ends a block even when its coordinates are malformed. BODY = r'((?:(?!]*>]*>).)*?)' NUMBER = r'(\d+(?:\.\d+)?)' BLOCK_RE = re.compile( r'' + BODY + r']+)>', re.DOTALL) TEXT_BLOCK_RE = re.compile( r']*)>]*)>' + BODY + r']*)>]*)>]+)>', re.DOTALL) CLASS_RE = re.compile(r']*)>') OPEN_PAIR_RE = re.compile(r'^\s*]*>]*>') CLOSE_PAIR_RE = re.compile(r']*>]*>\s*$') PAIR_RE = re.compile(r']*>]*>') COORDINATE_RE = re.compile(r'<[xy]_[^<>]*(?:>|(?=<)|$)') CONTROL_RE = re.compile(r'|||||<\|[^>]+\|>|<(?:predict|output)_[^>]*>') def visible_text(raw): """Remove serialization controls, including incomplete coordinate tokens.""" return CONTROL_RE.sub('', COORDINATE_RE.sub('', raw)).strip() def text_blocks(raw): """Read text independently of whether coordinates are valid numerical values.""" cursor = 0 for match in CLASS_RE.finditer(raw or ''): segment = raw[cursor:match.start()] pairs = list(PAIR_RE.finditer(segment)) opening = pairs[-2] if len(pairs) >= 2 else None closing = pairs[-1] if pairs and not segment[pairs[-1].end():].strip() else None # A dangling preceding block must not become the body of a later, # completed block (for example after inserting a valid crop result). body = (segment[opening.end():closing.start()].strip() if opening and closing and opening.end() <= closing.start() else visible_text(segment)) if body: yield match.group(1), body cursor = match.end() raw_tail = (raw or '')[cursor:] tail = visible_text(raw_tail) # An unfinished serialized block is retained in raw output, not presented as # a successfully decoded text/chart/table block. if tail and cursor == 0 and not any(token in raw_tail for token in ['