| 1 | //! 分块:text-splitter 语义分块(段落/句子边界优先),字符预算 + 重叠。 |
| 2 | |
| 3 | use text_splitter::{ChunkConfig, TextSplitter}; |
| 4 | |
| 5 | #[derive(Debug, Clone)] |
| 6 | pub struct ChunkPiece { |
| 7 | pub seq: i32, |
| 8 | pub text: String, |
| 9 | pub char_start: i32, |
| 10 | pub char_end: i32, |
| 11 | } |
| 12 | |
| 13 | /// 默认预算:1200 字符(中文约等于 1000+ token),重叠 150。 |
| 14 | pub fn chunk_text(text: &str) -> Vec<ChunkPiece> { |
| 15 | let config = ChunkConfig::new(1200) |
| 16 | .with_overlap(150) |
| 17 | .expect("overlap < capacity"); |
| 18 | let splitter = TextSplitter::new(config); |
| 19 | splitter |
| 20 | .chunk_indices(text) |
| 21 | .enumerate() |
| 22 | .map(|(i, (offset, chunk))| ChunkPiece { |
| 23 | seq: i as i32, |
| 24 | text: chunk.to_string(), |
| 25 | char_start: offset as i32, |
| 26 | char_end: (offset + chunk.len()) as i32, |
| 27 | }) |
| 28 | .collect() |
| 29 | } |