import re from functools import lru_cache import grapheme from cross.tokens import LinkToken, TagToken, TextToken, Token from util.util import Result def canonical_label(label: str | None, href: str): if not label or label == href: return True split = href.split("://", 1) return len(split) > 1 and split[1] == label @lru_cache(maxsize=1024) def _grapheme_length(text: str) -> int: return int(grapheme.length(text)) TEXT_SPLITTER = re.compile(r"(\n{2,}|[!.,;:]+|\s+|[^\s!.,;:\n]+)") class TokenSplitter: def __init__(self, max_chars: int, max_link_len: int = 35): self.max_chars = max_chars self.max_link_len = max_link_len self.blocks: list[list[Token]] = [] self.current_block: list[Token] = [] self.current_length = 0 self.best_split_idx: tuple[int, int, int] | None = None def _save_block(self): if self.current_block: self.blocks.append(self.current_block) self.current_block = [] self.current_length = 0 self.best_split_idx = None def _get_token_length(self, token: Token) -> int: if isinstance(token, TextToken): return _grapheme_length(token.text) elif isinstance(token, LinkToken): if token.label: return ( min(_grapheme_length(token.label), self.max_link_len) if canonical_label(token.label, token.href) else _grapheme_length(token.label) ) return min(_grapheme_length(token.href), self.max_link_len) elif isinstance(token, TagToken): return 1 + _grapheme_length(token.tag) return 0 def _classify_segment(self, seg: str) -> tuple[bool, bool, bool, bool]: is_paragraph = bool(re.match(r"^\n{2,}$", seg)) is_sentence = bool(re.match(r"^[!.,;:]+$", seg)) is_word = bool(re.match(r"^\s+$", seg)) and not is_paragraph is_content = not is_paragraph and not is_sentence and not is_word return is_paragraph, is_sentence, is_word, is_content def _maybe_update_split_point(self, priority: int): should_update = ( self.best_split_idx is None or priority > self.best_split_idx[2] or ( priority == self.best_split_idx[2] and self.current_length > self.best_split_idx[1] and self.current_length <= self.max_chars ) ) if should_update: self.best_split_idx = ( len(self.current_block) - 1, self.current_length, priority, ) def _add_segment(self, seg: str): self.current_block.append(TextToken(text=seg)) self.current_length += _grapheme_length(seg) def _split_oversized_text(self, seg: str) -> list[list[Token]]: result: list[list[Token]] = [] remaining = seg while remaining: remaining_len = _grapheme_length(remaining) if remaining_len <= self.max_chars: result.append([TextToken(text=remaining)]) break chunk_size = self.max_chars - 1 chunk = grapheme.slice(remaining, 0, chunk_size) + "-" result.append([TextToken(text=chunk)]) remaining = grapheme.slice(remaining, chunk_size, remaining_len) if remaining.startswith(" ") and not remaining.startswith(" "): remaining = remaining[1:] return result def _strip_leading_space(self): if self.current_block and isinstance(self.current_block[0], TextToken): first_token = self.current_block[0] if first_token.text == " ": self.current_block.pop(0) self.current_length -= 1 elif first_token.text.startswith(" ") and not first_token.text.startswith( " " ): self.current_block[0] = TextToken(text=first_token.text[1:]) self.current_length -= 1 def _split_at_boundary(self): if self.best_split_idx: idx, split_length, _ = self.best_split_idx self.blocks.append(self.current_block[: idx + 1]) self.current_block = self.current_block[idx + 1 :] self.current_length = self.current_length - split_length self.best_split_idx = None self._strip_leading_space() return True elif self.current_block: self.blocks.append(self.current_block) self.current_block = [] self.current_length = 0 return True return False def _process_text_token(self, token: TextToken): segments = [s for s in TEXT_SPLITTER.findall(token.text) if s] for seg in segments: seg_len = _grapheme_length(seg) is_paragraph, is_sentence, is_word, is_content = self._classify_segment(seg) while self.current_length + seg_len > self.max_chars: if self._split_at_boundary(): pass else: if self.current_block: self.blocks.append(self.current_block) self.current_block = [] self.current_length = 0 for block in self._split_oversized_text(seg): self.blocks.append(block) seg = "" seg_len = 0 break if seg: self._add_segment(seg) if is_paragraph: self._maybe_update_split_point(3) elif is_sentence: self._maybe_update_split_point(2) elif is_word: self._maybe_update_split_point(1) elif is_content: self._maybe_update_split_point(0) def _process_token(self, token: Token) -> bool: if isinstance(token, TextToken): self._process_text_token(token) return True token_len = self._get_token_length(token) if token_len > self.max_chars: return False if self.current_length + token_len > self.max_chars and self.current_block: self.blocks.append(self.current_block) self.current_block = [] self.current_length = 0 self.best_split_idx = None self.current_block.append(token) self.current_length += token_len if self.best_split_idx is None or self.best_split_idx[2] < 0: self.best_split_idx = (len(self.current_block) - 1, self.current_length, 0) return True def split(self, tokens: list[Token]) -> Result[list[list[Token]], str]: for token in tokens: if not self._process_token(token): return Result.err("token larger than character limit") self._save_block() return Result.ok(self.blocks)