use docling_core::chunker::{contextualize, DocChunk, HierarchicalChunker};
use docling_core::DoclingDocument;
fn records(chunks: &[DocChunk]) -> serde_json::Value {
serde_json::Value::Array(
chunks
.iter()
.map(|c| {
serde_json::json!({
"text": c.text,
"headings": c.headings,
"doc_items": c.doc_items.iter().map(|i| i.self_ref.clone()).collect::<Vec<_>>(),
"contextualize": contextualize(c),
})
})
.collect(),
)
}
pub fn chunk_records(
document: &DoclingDocument,
warn: &mut dyn FnMut(String),
) -> serde_json::Value {
let hierarchical = HierarchicalChunker.chunk(document);
#[cfg_attr(not(feature = "chunking"), allow(unused_mut, unused_variables))]
let mut out = serde_json::json!({ "hierarchical": records(&hierarchical) });
#[cfg(feature = "chunking")]
if let Some(tok_path) = docling_core::env::nonempty("DOCLING_CHUNK_TOKENIZER")
.or_else(|| docling_core::chunker::resolve_tokenizer_path(None).ok())
{
let max_tokens = docling_core::env::parse("DOCLING_CHUNK_MAX_TOKENS").unwrap_or(256);
match docling_core::chunker::HuggingFaceTokenizer::from_file(&tok_path, max_tokens) {
Ok(tok) => {
let hybrid = docling_core::chunker::HybridChunker::new(tok).chunk(document);
out["hybrid"] = records(&hybrid);
}
Err(e) => warn(e.to_string()),
}
}
#[cfg(not(feature = "chunking"))]
let _ = warn;
out
}