ebook-rs 0.16.0

Pure Rust multi-format eBook engine (EPUB2/3, MOBI, AZW3, FB2, LIT, CBZ, PDF, ODT, DOCX, RTF, TXT, MD) with SpeechSynthesis TTS Word Synchronizer, Legacy Charset Decoding, Auto Language Detection, Zstd State Caching, Universal EPUB3 Exporter, Zero-Copy mmap, and Readium LCP/Locator APIs.
Documentation
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
use crate::book::Book;
use crate::cfi::Cfi;
use crate::section::Section;
use roxmltree::Document;
use serde::{Deserialize, Serialize};

/// Configuration options for the AI / RAG document chunking engine.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RagChunkConfig {
    /// Maximum estimated tokens per chunk (1 token ≈ 4 characters / ~0.75 words). Default: 512.
    pub max_tokens: usize,
    /// Overlap estimated tokens between consecutive chunks. Default: 64.
    pub overlap_tokens: usize,
    /// Preserve heading hierarchy context (e.g., "# Chapter 1 > ## Section 2") in markdown output. Default: true.
    pub preserve_headings: bool,
    /// Include EPUB CFI citation anchors for each chunk. Default: true.
    pub include_cfi: bool,
    /// Minimum character length required for a chunk to be retained. Default: 50.
    pub min_chunk_size: usize,
}

impl Default for RagChunkConfig {
    fn default() -> Self {
        Self {
            max_tokens: 512,
            overlap_tokens: 64,
            preserve_headings: true,
            include_cfi: true,
            min_chunk_size: 50,
        }
    }
}

/// A semantic document chunk ready for AI embeddings, Vector DBs, and RAG retrieval.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RagChunk {
    /// Unique chunk identifier (e.g., `chunk-sec-0-0`).
    pub id: String,
    /// Index of the section/spine item in the book.
    pub spine_index: usize,
    /// Chapter title or section label.
    pub chapter_title: String,
    /// Heading hierarchy trail (e.g., `["Chapter 1: Introduction", "1.1 Overview"]`).
    pub heading_hierarchy: Vec<String>,
    /// EPUB CFI citation anchor pointing to the chunk's start location.
    pub cfi: String,
    /// Clean plain text content of the chunk.
    pub text: String,
    /// Contextual markdown representation including heading trail for LLM prompt ingestion.
    pub markdown: String,
    /// Estimated token count for LLM context window calculations.
    pub token_count_estimate: usize,
    /// Book title metadata.
    pub book_title: String,
    /// Creator / Author metadata.
    pub book_author: String,
}

/// AI & RAG document chunking implementation.
pub struct RagChunker;

impl RagChunker {
    /// Chunk an entire book into AI-ready semantic RAG chunks.
    pub fn chunk_book(book: &Book, config: &RagChunkConfig) -> Vec<RagChunk> {
        let meta = book.metadata();
        let book_title = meta.title.clone();
        let book_author = meta.creators.join(", ");
        #[cfg(feature = "parallel")]
        {
            use rayon::prelude::*;
            (0..book.spine().len())
                .into_par_iter()
                .filter_map(|idx| {
                    book.get_section(idx).ok().map(|sec| {
                        let chapter_title = book
                            .toc()
                            .iter()
                            .find(|t| t.href.contains(&sec.href))
                            .map(|t| t.label.clone())
                            .unwrap_or_else(|| format!("Section {}", idx + 1));

                        Self::chunk_section(
                            &sec,
                            idx,
                            &chapter_title,
                            &book_title,
                            &book_author,
                            config,
                        )
                    })
                })
                .flatten()
                .collect()
        }

        #[cfg(not(feature = "parallel"))]
        {
            let mut all_chunks = Vec::new();
            for idx in 0..book.spine().len() {
                if let Ok(sec) = book.get_section(idx) {
                    let chapter_title = book
                        .toc()
                        .iter()
                        .find(|t| t.href.contains(&sec.href))
                        .map(|t| t.label.clone())
                        .unwrap_or_else(|| format!("Section {}", idx + 1));

                    let section_chunks = Self::chunk_section(
                        &sec,
                        idx,
                        &chapter_title,
                        &book_title,
                        &book_author,
                        config,
                    );
                    all_chunks.extend(section_chunks);
                }
            }
            all_chunks
        }
    }

    /// Chunk a single section into AI-ready semantic RAG chunks.
    pub fn chunk_section(
        sec: &Section,
        spine_index: usize,
        chapter_title: &str,
        book_title: &str,
        book_author: &str,
        config: &RagChunkConfig,
    ) -> Vec<RagChunk> {
        let max_chars = config.max_tokens * 4;
        let overlap_chars = config.overlap_tokens * 4;
        let mut chunks = Vec::new();

        // Extract heading stack and paragraphs from raw HTML
        let (_headings, paragraphs) = Self::extract_elements(&sec.raw_html);
        if paragraphs.is_empty() {
            // Fallback to plain text if HTML parsing yields no paragraph nodes
            let text = sec.plain_text.trim();
            if text.len() >= config.min_chunk_size {
                let cfi = Cfi::from_spine_index(spine_index, None, 0).to_string();
                let markdown = if config.preserve_headings && !chapter_title.is_empty() {
                    format!("# {}\n\n{}", chapter_title, text)
                } else {
                    text.to_string()
                };
                chunks.push(RagChunk {
                    id: format!("chunk-sec-{}-0", spine_index),
                    spine_index,
                    chapter_title: chapter_title.to_string(),
                    heading_hierarchy: vec![chapter_title.to_string()],
                    cfi,
                    text: text.to_string(),
                    markdown,
                    token_count_estimate: text.len().div_ceil(4),
                    book_title: book_title.to_string(),
                    book_author: book_author.to_string(),
                });
            }
            return chunks;
        }

        let mut current_chunk_text = String::new();
        let mut current_char_offset = 0;
        let mut chunk_start_offset = 0;
        let current_headings: Vec<String> = if !chapter_title.is_empty() {
            vec![chapter_title.to_string()]
        } else {
            Vec::new()
        };

        for para in paragraphs.iter() {
            let p_len = para.len();
            if current_chunk_text.is_empty() {
                chunk_start_offset = current_char_offset;
            }

            if !current_chunk_text.is_empty()
                && current_chunk_text.len() + p_len > max_chars
                && current_chunk_text.len() >= config.min_chunk_size
            {
                let cfi = Cfi::from_spine_index(spine_index, None, chunk_start_offset).to_string();
                let markdown = Self::build_markdown(&current_headings, &current_chunk_text, config);

                chunks.push(RagChunk {
                    id: format!("chunk-sec-{}-{}", spine_index, chunks.len()),
                    spine_index,
                    chapter_title: chapter_title.to_string(),
                    heading_hierarchy: current_headings.clone(),
                    cfi,
                    text: current_chunk_text.trim().to_string(),
                    markdown,
                    token_count_estimate: current_chunk_text.len().div_ceil(4),
                    book_title: book_title.to_string(),
                    book_author: book_author.to_string(),
                });

                // Apply overlap
                let keep_start = current_chunk_text.len().saturating_sub(overlap_chars);
                current_chunk_text = current_chunk_text[keep_start..].to_string();
            }

            if !current_chunk_text.is_empty() && !current_chunk_text.ends_with('\n') {
                current_chunk_text.push('\n');
            }
            current_chunk_text.push_str(para);
            current_char_offset += p_len + 1;
        }

        // Flush final chunk
        let final_text = current_chunk_text.trim();
        if final_text.len() >= config.min_chunk_size {
            let cfi = Cfi::from_spine_index(spine_index, None, chunk_start_offset).to_string();
            let markdown = Self::build_markdown(&current_headings, final_text, config);

            chunks.push(RagChunk {
                id: format!("chunk-sec-{}-{}", spine_index, chunks.len()),
                spine_index,
                chapter_title: chapter_title.to_string(),
                heading_hierarchy: current_headings,
                cfi,
                text: final_text.to_string(),
                markdown,
                token_count_estimate: final_text.len().div_ceil(4),
                book_title: book_title.to_string(),
                book_author: book_author.to_string(),
            });
        }

        chunks
    }

    fn build_markdown(headings: &[String], body: &str, config: &RagChunkConfig) -> String {
        if !config.preserve_headings || headings.is_empty() {
            return body.to_string();
        }
        let header_trail = headings.join(" > ");
        format!("# {}\n\n{}", header_trail, body)
    }

    fn extract_elements(raw_html: &str) -> (Vec<String>, Vec<String>) {
        let mut headings = Vec::new();
        let mut paragraphs = Vec::new();

        if let Ok(doc) = Document::parse(raw_html) {
            for node in doc.descendants() {
                if node.is_element() {
                    let name = node.tag_name().name().to_lowercase();
                    if name.starts_with('h') && name.len() == 2 {
                        let text: String = node.text().unwrap_or_default().trim().to_string();
                        if !text.is_empty() {
                            headings.push(text);
                        }
                    } else if matches!(name.as_str(), "p" | "div" | "blockquote" | "li" | "section")
                    {
                        let text: String = node
                            .descendants()
                            .filter_map(|n| n.text())
                            .collect::<Vec<_>>()
                            .join(" ");
                        let clean = text.split_whitespace().collect::<Vec<_>>().join(" ");
                        if !clean.is_empty() {
                            paragraphs.push(clean);
                        }
                    }
                }
            }
        }
        (headings, paragraphs)
    }

    /// Rank RAG chunks using Okapi BM25 relevance scoring algorithm for a search query.
    pub fn rank_chunks_bm25(chunks: &[RagChunk], query: &str, top_k: usize) -> Vec<ScoredRagChunk> {
        let query_terms: Vec<String> = query
            .to_lowercase()
            .split_whitespace()
            .map(|s| s.trim_matches(|c: char| !c.is_alphanumeric()).to_string())
            .filter(|s| !s.is_empty())
            .collect();

        if query_terms.is_empty() || chunks.is_empty() {
            return Vec::new();
        }

        let num_docs = chunks.len() as f32;
        let avg_doc_len = chunks
            .iter()
            .map(|c| c.text.split_whitespace().count())
            .sum::<usize>() as f32
            / num_docs.max(1.0);

        // Compute Inverse Document Frequency (IDF) for query terms
        let mut idf_map = ahash::AHashMap::new();
        for term in &query_terms {
            let doc_freq = chunks
                .iter()
                .filter(|c| c.text.to_lowercase().contains(term))
                .count() as f32;
            let idf = ((num_docs - doc_freq + 0.5) / (doc_freq + 0.5) + 1.0).ln();
            idf_map.insert(term.clone(), idf.max(0.0));
        }

        let k1 = 1.2f32;
        let b = 0.75f32;

        let mut scored_chunks: Vec<ScoredRagChunk> = chunks
            .iter()
            .map(|chunk| {
                let doc_words: Vec<String> = chunk
                    .text
                    .to_lowercase()
                    .split_whitespace()
                    .map(|s| s.trim_matches(|c: char| !c.is_alphanumeric()).to_string())
                    .collect();

                let doc_len = doc_words.len() as f32;
                let mut score = 0.0f32;

                for term in &query_terms {
                    let tf = doc_words.iter().filter(|w| w == &term).count() as f32;
                    if tf > 0.0 {
                        let idf = idf_map.get(term).cloned().unwrap_or(0.0);
                        let num = tf * (k1 + 1.0);
                        let den = tf + k1 * (1.0 - b + b * (doc_len / avg_doc_len.max(1.0)));
                        score += idf * (num / den);
                    }
                }

                ScoredRagChunk {
                    chunk: chunk.clone(),
                    bm25_score: score,
                }
            })
            .filter(|sc| sc.bm25_score > 0.0)
            .collect();

        scored_chunks.sort_by(|a, b| {
            b.bm25_score
                .partial_cmp(&a.bm25_score)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        if top_k > 0 && scored_chunks.len() > top_k {
            scored_chunks.truncate(top_k);
        }

        scored_chunks
    }
}

/// A RAG document chunk with Okapi BM25 relevance score.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScoredRagChunk {
    pub chunk: RagChunk,
    pub bm25_score: f32,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_rag_chunker_basic() {
        let html = "<html><body><h1>Introduction</h1><p>First paragraph text of the book.</p><p>Second paragraph with more content for AI embedding.</p></body></html>";
        let sec = Section {
            index: 0,
            idref: "sec1".to_string(),
            href: "sec1.html".to_string(),
            full_path: "sec1.html".to_string(),
            raw_html: html.to_string(),
            processed_html: html.to_string(),
            plain_text: "Introduction First paragraph text of the book. Second paragraph with more content for AI embedding.".to_string(),
            plain_text_lower: "introduction first paragraph text of the book. second paragraph with more content for ai embedding.".to_string(),
            char_count: 100,
            viewport_width: None,
            viewport_height: None,
        };

        let config = RagChunkConfig {
            max_tokens: 100,
            overlap_tokens: 10,
            preserve_headings: true,
            include_cfi: true,
            min_chunk_size: 10,
        };

        let chunks =
            RagChunker::chunk_section(&sec, 0, "Chapter 1", "Test Book", "Author", &config);
        assert!(!chunks.is_empty());
        assert!(chunks[0].markdown.contains("# Chapter 1"));
        assert!(chunks[0].text.contains("First paragraph"));
        assert!(chunks[0].cfi.contains("epubcfi"));
    }

    #[test]
    fn test_bm25_ranking() {
        let chunk1 = RagChunk {
            id: "c1".to_string(),
            spine_index: 0,
            chapter_title: "Ch 1".to_string(),
            heading_hierarchy: vec![],
            cfi: "epubcfi(/6/2)".to_string(),
            text: "Quantum computing uses qubits for quantum algorithms.".to_string(),
            markdown: "Quantum computing uses qubits for quantum algorithms.".to_string(),
            token_count_estimate: 10,
            book_title: "Physics".to_string(),
            book_author: "Author".to_string(),
        };
        let chunk2 = RagChunk {
            id: "c2".to_string(),
            spine_index: 1,
            chapter_title: "Ch 2".to_string(),
            heading_hierarchy: vec![],
            cfi: "epubcfi(/6/4)".to_string(),
            text: "Classical computers use binary bits.".to_string(),
            markdown: "Classical computers use binary bits.".to_string(),
            token_count_estimate: 8,
            book_title: "Physics".to_string(),
            book_author: "Author".to_string(),
        };

        let ranked = RagChunker::rank_chunks_bm25(&[chunk1, chunk2], "quantum qubits", 10);
        assert!(!ranked.is_empty());
        assert_eq!(ranked[0].chunk.id, "c1");
        assert!(ranked[0].bm25_score > 0.0);
    }
}