Spaces:
Running

File size: 1,783 Bytes
8f3b9c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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)