"""Shared text span and offset-alignment utilities across detectors.""" from __future__ import annotations def spans_overlap(a_start: int, a_end: int, b_start: int, b_end: int) -> bool: """Return True when two half-open character intervals [start, end) intersect.""" return a_start < b_end and a_end > b_start def _word_spans(text: str, tokens: list[str]) -> list[tuple[int, int]]: spans: list[tuple[int, int]] = [] pos = 0 for tok in tokens: idx = text.find(tok, pos) if idx < 0: idx = pos spans.append((idx, idx + len(tok))) pos = idx + len(tok) return spans def align_norm_span(m_start: int, m_end: int, src: str, orig: str) -> tuple[int, int]: """Map a character span in 1-to-1 normalized text back to the original text via word indices.""" src_toks = src.split() orig_toks = orig.split() if not src_toks or not orig_toks: return 0, 0 src_spans = _word_spans(src, src_toks) first_i = next((i for i, (_, e) in enumerate(src_spans) if e > m_start), 0) last_i = first_i for i, (s, _) in enumerate(src_spans): if s < m_end: last_i = i max_idx = len(orig_toks) - 1 first_i = min(first_i, max_idx) last_i = min(last_i, max_idx) orig_spans = _word_spans(orig, orig_toks) return orig_spans[first_i][0], orig_spans[last_i][1] def apply_replacements(text: str, replacements: list[tuple[int, int, str]]) -> str: """Apply span replacements from right to left so earlier character offsets remain valid.""" if not replacements: return text chars = list(text) for start, end, repl in sorted(replacements, key=lambda item: item[0], reverse=True): chars[start:end] = list(repl) return "".join(chars)