use serde::Serialize;
use crate::document_core::queries::structure::{build_structure, StructureMode, StructureNode};
use crate::document_core::queries::table_extract::{extract_tables, TableGrid};
use crate::model::document::Document;
pub const TOKEN_ESTIMATOR: &str = "cjk1-latin4-v1";
const DENSE_GRID_CELL_CAP: usize = 200_000;
#[derive(Debug, Clone, Copy)]
pub struct ChunkOptions {
pub max_tokens: usize,
pub mode: StructureMode,
}
impl Default for ChunkOptions {
fn default() -> Self {
Self {
max_tokens: 512,
mode: StructureMode::Auto,
}
}
}
fn is_cjk(c: char) -> bool {
matches!(c as u32,
0x1100..=0x11FF | 0x3040..=0x30FF | 0x3130..=0x318F | 0x3400..=0x4DBF | 0x4E00..=0x9FFF | 0xAC00..=0xD7A3 | 0xF900..=0xFAFF | 0xFF00..=0xFFEF )
}
pub fn estimate_tokens(text: &str) -> usize {
let mut cjk = 0usize;
let mut other = 0usize;
for c in text.chars() {
if is_cjk(c) {
cjk += 1;
} else if !c.is_whitespace() {
other += 1;
}
}
cjk + other.div_ceil(4)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ChunkKind {
Text,
Table,
Mixed,
}
#[derive(Debug, Clone, Serialize)]
pub struct ChunkTableRef {
pub index: usize,
pub section: usize,
pub paragraph: usize,
pub rows: u16,
pub cols: u16,
#[serde(rename = "headerRowCount")]
pub header_row_count: usize,
pub part: usize,
#[serde(rename = "partCount")]
pub part_count: usize,
#[serde(rename = "headerRepeated")]
pub header_repeated: bool,
}
#[derive(Debug, Clone, Serialize)]
pub struct LlmChunk {
#[serde(rename = "chunkIndex")]
pub chunk_index: usize,
#[serde(rename = "headingPath")]
pub heading_path: Vec<String>,
#[serde(rename = "headingLevel")]
pub heading_level: u8,
#[serde(skip_serializing_if = "Option::is_none")]
pub section: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub paragraph: Option<usize>,
pub kind: ChunkKind,
#[serde(rename = "tokenEstimate")]
pub token_estimate: usize,
pub part: usize,
#[serde(rename = "partCount")]
pub part_count: usize,
pub text: String,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub tables: Vec<ChunkTableRef>,
}
impl LlmChunk {
pub fn untrusted_fields(&self) -> Vec<&'static str> {
let mut fields = Vec::new();
if !self.heading_path.is_empty() {
fields.push("headingPath");
}
if !self.text.is_empty() {
fields.push("text");
}
fields
}
}
struct Segment {
heading_path: Vec<String>,
heading_level: u8,
section: Option<usize>,
paragraph: Option<usize>,
paras: Vec<String>,
tables: Vec<usize>,
}
impl Segment {
fn anchor(&self) -> (usize, usize) {
(self.section.unwrap_or(0), self.paragraph.unwrap_or(0))
}
}
fn flatten_nodes(nodes: &[StructureNode], path: &[String], out: &mut Vec<Segment>) {
for node in nodes {
let mut heading_path = path.to_vec();
heading_path.push(node.heading.clone());
out.push(Segment {
heading_path: heading_path.clone(),
heading_level: node.level,
section: Some(node.section),
paragraph: Some(node.paragraph),
paras: node.body.clone(),
tables: Vec::new(),
});
flatten_nodes(&node.children, &heading_path, out);
}
}
fn assign_tables(segments: &mut Vec<Segment>, tables: &[TableGrid]) {
if tables.is_empty() {
return;
}
let earliest = tables
.iter()
.map(|t| (t.section, t.paragraph))
.min()
.expect("tables non-empty");
let need_leading_preamble = segments
.first()
.is_none_or(|s| s.section.is_some() && earliest < s.anchor());
if need_leading_preamble {
segments.insert(
0,
Segment {
heading_path: Vec::new(),
heading_level: 0,
section: None,
paragraph: None,
paras: Vec::new(),
tables: Vec::new(),
},
);
}
for (table_index, table) in tables.iter().enumerate() {
let pos = (table.section, table.paragraph);
let owner = segments
.iter()
.rposition(|s| s.anchor() <= pos)
.unwrap_or(0);
segments[owner].tables.push(table_index);
}
}
fn sanitize_cell(text: &str) -> String {
text.replace('\r', "")
.replace('\n', " ")
.replace('|', "\\|")
.trim()
.to_string()
}
fn linearize_table_parts(
grid: &TableGrid,
max_tokens: usize,
) -> Vec<(String, ChunkTableRef, usize)> {
let rows = grid.rows as usize;
let cols = grid.cols as usize;
let caption = grid
.caption
.as_deref()
.map(sanitize_cell)
.filter(|s| !s.is_empty());
if rows == 0 || cols == 0 || rows.saturating_mul(cols) > DENSE_GRID_CELL_CAP {
let mut lines = Vec::new();
if let Some(cap) = &caption {
lines.push(format!("[표] {cap}"));
}
for cell in &grid.cells {
lines.push(format!(
"({}, {}) {}",
cell.row,
cell.col,
sanitize_cell(&cell.text)
));
}
let text = lines.join("\n");
let tokens = estimate_tokens(&text);
return vec![(
text,
ChunkTableRef {
index: grid.index,
section: grid.section,
paragraph: grid.paragraph,
rows: grid.rows,
cols: grid.cols,
header_row_count: 0,
part: 1,
part_count: 1,
header_repeated: false,
},
tokens,
)];
}
let mut dense = vec![vec![String::new(); cols]; rows];
let mut header_flags = vec![false; rows];
for cell in &grid.cells {
let r = cell.row as usize;
let c = cell.col as usize;
if r >= rows || c >= cols {
continue;
}
let mut text = sanitize_cell(&cell.text);
if cell.row_span > 1 || cell.col_span > 1 {
if !text.is_empty() {
text.push(' ');
}
text.push_str(&format!("[병합 {}×{}]", cell.row_span, cell.col_span));
}
dense[r][c] = text;
if cell.is_header {
let end = (r + cell.row_span as usize).min(rows);
for flag in header_flags.iter_mut().take(end).skip(r) {
*flag = true;
}
}
}
let row_line = |cells: &[String]| -> String { format!("| {} |", cells.join(" | ")) };
let all_rows: Vec<String> = dense.iter().map(|r| row_line(r)).collect();
let mut header_rows = 0usize;
while header_rows < rows && header_flags[header_rows] {
header_rows += 1;
}
if header_rows == 0 {
header_rows = 1; }
let separator = format!("| {} |", vec!["---"; cols].join(" | "));
let mut header_block: Vec<String> = Vec::new();
if let Some(cap) = &caption {
header_block.push(format!("[표] {cap}"));
}
header_block.extend(all_rows[..header_rows].iter().cloned());
header_block.push(separator);
let header_text = header_block.join("\n");
let header_tokens = estimate_tokens(&header_text);
let data_rows = &all_rows[header_rows..];
let mut parts_rows: Vec<Vec<String>> = Vec::new();
let mut cur: Vec<String> = Vec::new();
let mut cur_tokens = header_tokens;
for line in data_rows {
let line_tokens = estimate_tokens(line);
if !cur.is_empty() && cur_tokens + line_tokens > max_tokens {
parts_rows.push(std::mem::take(&mut cur));
cur_tokens = header_tokens;
}
cur.push(line.clone());
cur_tokens += line_tokens;
}
if !cur.is_empty() || parts_rows.is_empty() {
parts_rows.push(cur);
}
let part_count = parts_rows.len();
let header_repeated = part_count > 1;
parts_rows
.into_iter()
.enumerate()
.map(|(k, rows_slice)| {
let mut lines = header_block.clone();
lines.extend(rows_slice);
let text = lines.join("\n");
let tokens = estimate_tokens(&text);
(
text,
ChunkTableRef {
index: grid.index,
section: grid.section,
paragraph: grid.paragraph,
rows: grid.rows,
cols: grid.cols,
header_row_count: header_rows,
part: k + 1,
part_count,
header_repeated,
},
tokens,
)
})
.collect()
}
struct ChunkBuf {
heading_path: Vec<String>,
heading_level: u8,
section: Option<usize>,
paragraph: Option<usize>,
pieces: Vec<String>,
tokens: usize,
tables: Vec<ChunkTableRef>,
has_text: bool,
has_table: bool,
}
impl ChunkBuf {
fn new(seg: &Segment) -> Self {
Self {
heading_path: seg.heading_path.clone(),
heading_level: seg.heading_level,
section: seg.section,
paragraph: seg.paragraph,
pieces: Vec::new(),
tokens: 0,
tables: Vec::new(),
has_text: false,
has_table: false,
}
}
fn is_empty(&self) -> bool {
self.pieces.is_empty()
}
fn push_text(&mut self, text: String, tokens: usize) {
self.pieces.push(text);
self.tokens += tokens;
self.has_text = true;
}
fn push_table(&mut self, text: String, table_ref: ChunkTableRef, tokens: usize) {
self.pieces.push(text);
self.tokens += tokens;
self.tables.push(table_ref);
self.has_table = true;
}
fn flush(&mut self, out: &mut Vec<LlmChunk>) {
if self.is_empty() {
return;
}
let kind = match (self.has_text, self.has_table) {
(true, true) => ChunkKind::Mixed,
(false, true) => ChunkKind::Table,
_ => ChunkKind::Text,
};
let text = self.pieces.join("\n\n");
let token_estimate = estimate_tokens(&text);
out.push(LlmChunk {
chunk_index: 0,
heading_path: self.heading_path.clone(),
heading_level: self.heading_level,
section: self.section,
paragraph: self.paragraph,
kind,
token_estimate,
part: 0,
part_count: 0,
text,
tables: std::mem::take(&mut self.tables),
});
self.pieces.clear();
self.tokens = 0;
self.has_text = false;
self.has_table = false;
}
}
fn emit_segment(seg: &Segment, tables: &[TableGrid], max_tokens: usize, out: &mut Vec<LlmChunk>) {
let start = out.len();
let mut buf = ChunkBuf::new(seg);
for para in &seg.paras {
let trimmed = para.trim();
if trimmed.is_empty() {
continue;
}
let tokens = estimate_tokens(trimmed);
if !buf.is_empty() && buf.tokens + tokens > max_tokens {
buf.flush(out);
}
buf.push_text(trimmed.to_string(), tokens);
if buf.tokens > max_tokens {
buf.flush(out);
}
}
let mut table_indices = seg.tables.clone();
table_indices.sort_unstable();
for table_index in table_indices {
let parts = linearize_table_parts(&tables[table_index], max_tokens);
if parts.len() == 1 {
let (text, table_ref, tokens) = parts.into_iter().next().expect("one part");
if !buf.is_empty() && buf.tokens + tokens > max_tokens {
buf.flush(out);
}
buf.push_table(text, table_ref, tokens);
} else {
buf.flush(out);
for (text, table_ref, tokens) in parts {
let mut standalone = ChunkBuf::new(seg);
standalone.push_table(text, table_ref, tokens);
standalone.flush(out);
}
}
}
buf.flush(out);
let produced = out.len() - start;
for (k, chunk) in out[start..].iter_mut().enumerate() {
chunk.part = k + 1;
chunk.part_count = produced;
}
}
pub fn build_chunks(doc: &Document, opts: &ChunkOptions) -> Vec<LlmChunk> {
let max_tokens = opts.max_tokens.max(1);
let structure = build_structure(doc, opts.mode);
let tables = extract_tables(doc);
let mut segments: Vec<Segment> = Vec::new();
if !structure.preamble.is_empty() {
segments.push(Segment {
heading_path: Vec::new(),
heading_level: 0,
section: None,
paragraph: None,
paras: structure.preamble.clone(),
tables: Vec::new(),
});
}
flatten_nodes(&structure.roots, &[], &mut segments);
assign_tables(&mut segments, &tables);
let mut chunks: Vec<LlmChunk> = Vec::new();
for seg in &segments {
emit_segment(seg, &tables, max_tokens, &mut chunks);
}
for (i, chunk) in chunks.iter_mut().enumerate() {
chunk.chunk_index = i;
}
chunks
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::control::Control;
use crate::model::document::{Document, Section};
use crate::model::paragraph::Paragraph;
use crate::model::style::{HeadType, ParaShape};
use crate::model::table::{Cell, Table};
fn doc_with(paras: Vec<Paragraph>) -> Document {
let mut doc = Document::default();
doc.doc_info.para_shapes.push(ParaShape::default()); doc.doc_info.para_shapes.push(ParaShape {
head_type: HeadType::Outline,
para_level: 0,
..ParaShape::default()
}); doc.sections.push(Section {
paragraphs: paras,
..Section::default()
});
doc
}
fn para(text: &str, shape: u16) -> Paragraph {
Paragraph {
text: text.to_string(),
para_shape_id: shape,
..Paragraph::new_empty()
}
}
fn heading(text: &str) -> Paragraph {
para(text, 1)
}
fn body(text: &str) -> Paragraph {
para(text, 0)
}
fn para_with_table(rows: u16, cols: u16, cells: Vec<Cell>) -> Paragraph {
let table = Table {
row_count: rows,
col_count: cols,
cells,
..Table::default()
};
let mut p = Paragraph::new_empty();
p.controls.push(Control::Table(Box::new(table)));
p
}
fn cell(row: u16, col: u16, text: &str, is_header: bool) -> Cell {
Cell {
row,
col,
row_span: 1,
col_span: 1,
is_header,
paragraphs: vec![body(text)],
..Cell::default()
}
}
#[test]
fn empty_document_yields_no_chunks_without_panicking() {
let doc = Document::default();
let chunks = build_chunks(&doc, &ChunkOptions::default());
assert!(chunks.is_empty());
}
#[test]
fn degenerate_paragraphs_do_not_panic() {
let doc = doc_with(vec![body(""), body(" "), body("\n")]);
let chunks = build_chunks(&doc, &ChunkOptions::default());
assert!(chunks.iter().all(|c| !c.text.is_empty()));
}
#[test]
fn token_estimate_is_labelled_a_heuristic() {
assert_eq!(estimate_tokens("가나다"), 3);
assert_eq!(estimate_tokens("abcd"), 1);
assert_eq!(estimate_tokens("abcdefgh"), 2);
assert_eq!(estimate_tokens(""), 0);
assert_eq!(TOKEN_ESTIMATOR, "cjk1-latin4-v1");
}
#[test]
fn multi_paragraph_chunks_stay_within_budget() {
let mut paras = vec![heading("장")];
for _ in 0..20 {
paras.push(body("가나다라마")); }
let doc = doc_with(paras);
let opts = ChunkOptions {
max_tokens: 12,
mode: StructureMode::Auto,
};
let chunks = build_chunks(&doc, &opts);
assert!(chunks.len() > 1, "예산이 쪼개기를 유발해야 한다");
for c in &chunks {
if c.text.contains("\n\n") {
assert!(
c.token_estimate <= opts.max_tokens,
"묶인 청크가 예산 초과: {} > {}",
c.token_estimate,
opts.max_tokens
);
}
}
}
#[test]
fn chunk_boundaries_respect_headings() {
let doc = doc_with(vec![
heading("제1장 총칙"),
body("가나다라마바사"),
heading("제2장 벌칙"),
body("아자차카타파하"),
]);
let chunks = build_chunks(&doc, &ChunkOptions::default());
assert_eq!(chunks.len(), 2);
assert_eq!(chunks[0].heading_path, vec!["제1장 총칙"]);
assert!(chunks[0].text.contains("가나다라마바사"));
assert!(!chunks[0].text.contains("아자차카타파하"));
assert_eq!(chunks[1].heading_path, vec!["제2장 벌칙"]);
assert_eq!(chunks[0].chunk_index, 0);
assert_eq!(chunks[1].chunk_index, 1);
}
#[test]
fn nested_headings_build_a_path() {
let mut doc = doc_with(vec![heading("제1장"), heading("제1절"), body("본문")]);
doc.doc_info.para_shapes.push(ParaShape {
head_type: HeadType::Outline,
para_level: 1,
..ParaShape::default()
});
doc.sections[0].paragraphs[1].para_shape_id = 2;
let chunks = build_chunks(&doc, &ChunkOptions::default());
let deep = chunks
.iter()
.find(|c| c.text.contains("본문"))
.expect("본문 청크");
assert_eq!(deep.heading_path, vec!["제1장", "제1절"]);
assert_eq!(deep.heading_level, 2);
}
#[test]
fn large_section_splits_into_parts_with_repeated_heading_path() {
let doc = doc_with(vec![
heading("장"),
body("가나다라마바사아자차"), body("카타파하거너더러머버"), body("서어저처커터퍼허고노"), ]);
let opts = ChunkOptions {
max_tokens: 12,
mode: StructureMode::Auto,
};
let chunks = build_chunks(&doc, &opts);
assert!(chunks.len() >= 2, "쪼개져야 한다: {}", chunks.len());
for c in &chunks {
assert_eq!(c.heading_path, vec!["장"]);
}
assert_eq!(chunks[0].part, 1);
assert_eq!(chunks[0].part_count, chunks.len());
}
#[test]
fn table_never_splits_mid_row_and_repeats_header() {
let mut cells = vec![cell(0, 0, "이름", true), cell(0, 1, "값", true)];
for r in 1..=6u16 {
cells.push(cell(r, 0, &format!("행{r}"), false));
cells.push(cell(r, 1, &format!("데이터{r}"), false));
}
let doc = doc_with(vec![heading("표 절"), para_with_table(7, 2, cells)]);
let opts = ChunkOptions {
max_tokens: 20,
mode: StructureMode::Auto,
};
let chunks = build_chunks(&doc, &opts);
let table_chunks: Vec<&LlmChunk> = chunks.iter().filter(|c| !c.tables.is_empty()).collect();
assert!(table_chunks.len() >= 2, "표가 쪼개져야 한다");
for c in &table_chunks {
assert!(c.text.contains("이름"), "머리 반복 누락: {}", c.text);
assert!(c.tables[0].header_repeated);
for line in c.text.lines().filter(|l| l.contains("행")) {
if let Some(num) = line.split('행').nth(1).and_then(|s| s.chars().next()) {
assert!(
line.contains(&format!("데이터{num}")),
"행이 중간에서 잘렸다: {line}"
);
}
}
}
}
#[test]
fn merged_cells_are_annotated() {
let cells = vec![
Cell {
row: 0,
col: 0,
row_span: 1,
col_span: 2,
is_header: true,
paragraphs: vec![body("병합머리")],
..Cell::default()
},
cell(1, 0, "좌", false),
cell(1, 1, "우", false),
];
let doc = doc_with(vec![heading("표"), para_with_table(2, 2, cells)]);
let chunks = build_chunks(&doc, &ChunkOptions::default());
let table_chunk = chunks
.iter()
.find(|c| !c.tables.is_empty())
.expect("표 청크");
assert!(
table_chunk.text.contains("[병합 1×2]"),
"병합 주석 누락: {}",
table_chunk.text
);
}
#[test]
fn every_chunk_declares_untrusted_content() {
let doc = doc_with(vec![heading("장"), body("본문 텍스트")]);
let chunks = build_chunks(&doc, &ChunkOptions::default());
assert!(!chunks.is_empty());
for c in &chunks {
let fields = c.untrusted_fields();
assert!(fields.contains(&"text"), "text 표지 누락");
assert!(fields.contains(&"headingPath"), "headingPath 표지 누락");
}
}
#[test]
fn output_is_deterministic_byte_for_byte() {
let doc = doc_with(vec![
heading("제1장"),
body("가나다라마바사"),
para_with_table(
2,
2,
vec![cell(0, 0, "머리", true), cell(1, 0, "값", false)],
),
heading("제2장"),
body("아자차카타파하"),
]);
let opts = ChunkOptions::default();
let a = serde_json::to_string(&build_chunks(&doc, &opts)).unwrap();
let b = serde_json::to_string(&build_chunks(&doc, &opts)).unwrap();
assert_eq!(a, b);
}
#[test]
fn all_body_text_and_tables_are_covered() {
let doc = doc_with(vec![
body("서문문단"),
heading("제1장 제목"),
body("첫째 본문"),
body("둘째 본문"),
para_with_table(
2,
1,
vec![cell(0, 0, "표머리", true), cell(1, 0, "표값", false)],
),
]);
let chunks = build_chunks(&doc, &ChunkOptions::default());
let haystack: String = chunks
.iter()
.map(|c| format!("{} {}", c.heading_path.join(" "), c.text))
.collect::<Vec<_>>()
.join("\n");
for needle in [
"서문문단",
"제1장 제목",
"첫째 본문",
"둘째 본문",
"표머리",
"표값",
] {
assert!(haystack.contains(needle), "누락: {needle}");
}
}
#[test]
fn table_before_first_heading_lands_in_a_preamble_chunk() {
let doc = doc_with(vec![
para_with_table(1, 1, vec![cell(0, 0, "선행표", true)]),
heading("제1장"),
body("본문"),
]);
let chunks = build_chunks(&doc, &ChunkOptions::default());
let table_chunk = chunks
.iter()
.find(|c| !c.tables.is_empty())
.expect("표 청크");
assert!(
table_chunk.heading_path.is_empty(),
"서문 표는 제목 경로가 비어야 한다"
);
assert!(table_chunk.text.contains("선행표"));
}
}