Files
2026-05-12 08:16:42 +08:00

91 lines
2.5 KiB
Python

from __future__ import annotations
import hashlib
import re
from edkb_system.contracts import Chunk, Context
HEAD_RE = re.compile(r"^(#{1,6})\s+(.*)$")
def _chunk_id(source: str, heading: str, index: int, text: str) -> str:
raw = f"{source}|{heading}|{index}|{text}"
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
def run(
input_data: dict,
context: Context,
max_chars: int = 1200,
overlap_chars: int = 150,
add_heading_path_prefix: bool = True,
) -> list[Chunk]:
source = input_data["source"]
md = input_data["text"]
lines = md.splitlines()
stack: list[str] = []
sections: list[tuple[str, str]] = []
buf: list[str] = []
def heading() -> str:
return " > ".join(stack) if stack else "ROOT"
for ln in lines:
m = HEAD_RE.match(ln.strip())
if m:
if buf:
sections.append((heading(), "\n".join(buf).strip()))
buf = []
level = len(m.group(1))
text = m.group(2).strip()
while len(stack) >= level:
stack.pop()
stack.append(text)
else:
buf.append(ln)
if buf:
sections.append((heading(), "\n".join(buf).strip()))
out: list[Chunk] = []
idx = 0
for hp, body in sections:
paras = [p.strip() for p in body.split("\n\n") if p.strip()]
acc = ""
for p in paras:
cand = (acc + "\n\n" + p).strip() if acc else p
if len(cand) <= max_chars:
acc = cand
continue
if acc:
txt = f"# {hp}\n{acc}" if add_heading_path_prefix else acc
out.append(
Chunk(
id=_chunk_id(source, hp, idx, txt),
heading_path=hp,
text=txt,
index=idx,
source=source,
)
)
idx += 1
overlap = txt[-overlap_chars:] if overlap_chars > 0 else ""
acc = (overlap + "\n\n" + p).strip()
else:
acc = p[:max_chars]
if acc:
txt = f"# {hp}\n{acc}" if add_heading_path_prefix else acc
out.append(
Chunk(
id=_chunk_id(source, hp, idx, txt),
heading_path=hp,
text=txt,
index=idx,
source=source,
)
)
idx += 1
return out