Coverage for app / util / text_pages.py: 97%
30 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""A long text read in parts: where a part ends, and how the reader is told.
3``read_attachment`` read an attached document a part at a time from the
4start. ``read_document`` returned up to 60,000 characters of a stored
5document on every call, so a turn that read four guidance pages carried all
6of them on every later round of its tool loop: run 4's DPIA question grew
7from 30,000 to 116,000 input tokens a round. Both now read a part from an
8offset, ending at a paragraph, and say where the next begins.
9"""
11from __future__ import annotations
13from dataclasses import dataclass
16def boundary(text: str, start: int, limit: int, snap: int) -> int:
17 """Where a part that may run to ``limit`` ends: after the last paragraph,
18 line, sentence or word break within ``snap`` characters of it."""
19 if limit >= len(text):
20 return len(text)
21 floor = max(start + 1, limit - snap)
22 window = text[floor:limit]
23 for brk in ("\n\n", "\n", ". ", " "):
24 at = window.rfind(brk)
25 if at != -1:
26 return floor + at + len(brk)
27 return limit
30@dataclass(frozen=True)
31class Part:
32 """``text[start:end]`` of a text ``size`` characters long."""
34 text: str
35 start: int
36 end: int
37 size: int
39 @property
40 def more(self) -> bool:
41 return self.end < self.size
43 def where(self) -> str:
44 return f"characters {self.start:,}–{self.end:,} of {self.size:,}"
47def part(text: str, offset: int, size: int) -> Part | None:
48 """The part of ``text`` from ``offset`` running to about ``size``
49 characters, ending at a break; None when ``offset`` is past the end (an
50 empty text has one empty part)."""
51 offset = max(0, int(offset or 0))
52 total = len(text)
53 if offset >= total and total:
54 return None
55 end = boundary(text, offset, offset + size, size // 10)
56 return Part(text[offset:end], offset, end, total)