File size: 1,344 Bytes
8f6d79d | 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 | """Rebuild document text from processed blocks."""
from __future__ import annotations
from app.engine.models import DocumentBlock
def stitch_blocks(blocks: list[DocumentBlock]) -> str:
"""Join blocks preserving blank lines and non-rewriteable sections."""
if not blocks:
return ""
parts: list[str] = []
for i, block in enumerate(blocks):
if block.kind == "blank":
# Represented as paragraph separator; avoid stacking too many
if parts and not parts[-1].endswith("\n\n"):
if parts[-1] and not parts[-1].endswith("\n"):
parts.append("\n\n")
elif parts[-1].endswith("\n") and not parts[-1].endswith("\n\n"):
parts.append("\n")
continue
text = block.text or ""
if i > 0 and parts and not parts[-1].endswith("\n"):
# Separate consecutive non-blank blocks with blank line if both are paras/headings
prev = blocks[i - 1]
if prev.kind != "blank":
parts.append("\n\n")
parts.append(text)
out = "".join(parts)
out = out.replace("\n\n\n\n", "\n\n").strip()
return out
def join_sentences(sentences: list[str]) -> str:
return " ".join(s.strip() for s in sentences if s and s.strip())
|