xberg 1.1.2

High-performance document intelligence library for Rust. Extract text, metadata, and structured data from PDFs, Office documents, images, and 107 formats and 371 programming languages via tree-sitter code intelligence with async/sync 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
429
430
431
432
//! Heuristic semantic classifier for text chunks.
//!
//! Assigns a [`ChunkType`] to each text chunk based on structural signals
//! (heading context, Markdown syntax) and content-level keyword patterns.
//! Rules are evaluated in priority order; the first match wins.
//!
//! # Design
//!
//! - **No ML**: fully deterministic, zero-latency overhead, no external deps.
//! - **Ordered rules**: higher-precision structural signals run before
//!   lower-precision keyword heuristics.
//! - **Extensible**: add new variants to [`ChunkType`] and insert new rules
//!   without breaking existing classifications.

use crate::types::{ChunkType, HeadingContext};

/// Classify a single chunk based on its content and optional heading context.
///
/// Rules are evaluated in priority order. The first matching rule determines
/// the returned [`ChunkType`]. When no rule matches, [`ChunkType::Unknown`]
/// is returned.
///
/// # Arguments
///
/// * `content` - The text content of the chunk (may be trimmed or raw).
/// * `heading_context` - Optional heading hierarchy this chunk falls under
///   (only available when using `ChunkerType::Markdown`).
///
/// # Examples
///
/// ```ignore
/// use xberg::chunking::classifier::classify_chunk;
/// use xberg::types::ChunkType;
///
/// assert_eq!(classify_chunk("# Introduction", None), ChunkType::Heading);
/// assert_eq!(
///     classify_chunk("The Investor shall subscribe for the Shares and agrees to pay the subscription price. The Company shall deliver the Share certificates upon receipt.", None),
///     ChunkType::OperativeClause,
/// );
/// assert_eq!(classify_chunk("Some unrecognized text.", None), ChunkType::Unknown);
/// ```
pub(crate) fn classify_chunk(content: &str, heading_context: Option<&HeadingContext>) -> ChunkType {
    let trimmed = content.trim();

    if is_heading(trimmed, heading_context) {
        return ChunkType::Heading;
    }

    if is_code_block(content) {
        return ChunkType::CodeBlock;
    }

    if is_table_like(trimmed) {
        return ChunkType::TableLike;
    }

    if is_formula(trimmed) {
        return ChunkType::Formula;
    }

    if is_schedule(trimmed, heading_context) {
        return ChunkType::Schedule;
    }

    if is_definitions(trimmed) {
        return ChunkType::Definitions;
    }

    if is_signature_block(trimmed) {
        return ChunkType::SignatureBlock;
    }

    if is_operative_clause(trimmed) {
        return ChunkType::OperativeClause;
    }

    if is_party_list(trimmed) {
        return ChunkType::PartyList;
    }

    ChunkType::Unknown
}

fn is_heading(content: &str, _ctx: Option<&HeadingContext>) -> bool {
    if content.starts_with('#') {
        return true;
    }
    let mut lines = content.lines();
    if let (Some(_title), Some(underline)) = (lines.next(), lines.next()) {
        let u = underline.trim();
        if !u.is_empty() && (u.chars().all(|c| c == '=') || u.chars().all(|c| c == '-')) {
            return true;
        }
    }
    false
}

fn is_code_block(content: &str) -> bool {
    if content.starts_with("```") || content.starts_with("~~~") {
        return true;
    }
    let lines: Vec<&str> = content.lines().collect();
    if lines.len() >= 2 {
        let all_indented = lines
            .iter()
            .filter(|l| !l.trim().is_empty())
            .all(|l| l.starts_with("    ") || l.starts_with('\t'));
        if all_indented {
            return true;
        }
    }
    false
}

fn is_table_like(content: &str) -> bool {
    let lines: Vec<&str> = content.lines().collect();
    if lines.len() < 2 {
        return false;
    }
    let pipe_lines = lines.iter().filter(|l| l.contains('|')).count();
    if pipe_lines >= 2 {
        return true;
    }
    let sep_lines = lines
        .iter()
        .filter(|l| {
            let t = l.trim();
            t.len() >= 4 && t.chars().all(|c| c == '-' || c == '+' || c == '|' || c == ' ')
        })
        .count();
    sep_lines >= 3
}

fn is_formula(content: &str) -> bool {
    const MATH_SYMBOLS: &[char] = &['', '', '', '', '', '', '', '', '', '', '', ''];
    if content.chars().any(|c| MATH_SYMBOLS.contains(&c)) {
        return true;
    }
    let lower = content.to_lowercase();
    let latex_patterns = [
        r"\frac", r"\sum", r"\int", r"\sqrt", r"\alpha", r"\beta", r"\delta", r"$$", r"\[",
    ];
    if latex_patterns.iter().any(|p| lower.contains(p)) {
        return true;
    }
    false
}

fn is_schedule(content: &str, ctx: Option<&HeadingContext>) -> bool {
    const KEYWORDS: &[&str] = &["schedule", "annex", "appendix", "exhibit"];
    let lower = content.to_lowercase();

    if let Some(ctx) = ctx {
        for h in &ctx.headings {
            let hl = h.text.to_lowercase();
            if KEYWORDS.iter().any(|k| hl.contains(k)) {
                return true;
            }
        }
    }
    let first_line = content.lines().next().unwrap_or("").to_lowercase();
    if KEYWORDS.iter().any(|k| first_line.starts_with(k)) {
        return true;
    }

    KEYWORDS.iter().any(|k| {
        if let Some(idx) = lower.find(k) {
            let rest = &lower[idx + k.len()..];
            rest.starts_with(' ')
                && rest
                    .trim_start()
                    .chars()
                    .next()
                    .map(|c| c.is_alphanumeric())
                    .unwrap_or(false)
        } else {
            false
        }
    })
}

fn is_definitions(content: &str) -> bool {
    let lower = content.to_lowercase();
    let patterns = [
        "\" means ",
        "\" shall mean ",
        "\" has the meaning",
        "' means ",
        "' shall mean ",
        "means, for purposes",
        "is defined as",
        "shall be construed as",
    ];
    patterns.iter().any(|p| lower.contains(p))
}

fn is_signature_block(content: &str) -> bool {
    let lower = content.to_lowercase();
    let keywords = [
        "signature",
        "signed by",
        "witnessed by",
        "date:",
        "in witness whereof",
        "authorized signatory",
        "duly authorized",
        "____",
    ];
    let hits = keywords.iter().filter(|k| lower.contains(*k)).count();
    hits >= 2
}

fn is_operative_clause(content: &str) -> bool {
    let lower = content.to_lowercase();
    let verbs = [
        "shall ",
        "agree ",
        "agrees ",
        "transfer",
        "grant ",
        "grants ",
        "undertake",
        "obligat",
        "covenant",
        "warrant",
        "represent",
        "indemnif",
        "assign ",
        "assigns ",
        "license ",
        "licenses ",
        "purchase",
        "sell ",
        "sells ",
        "pay ",
        "pays ",
        "deliver",
    ];
    let hits = verbs.iter().filter(|v| lower.contains(*v)).count();
    hits >= 3
}

fn is_party_list(content: &str) -> bool {
    let lines: Vec<&str> = content.lines().map(|l| l.trim()).filter(|l| !l.is_empty()).collect();

    if lines.len() < 3 {
        return false;
    }

    let party_like = lines.iter().filter(|l| is_party_line(l)).count();
    party_like >= (lines.len() * 2 / 3).max(2)
}

/// Heuristic for a single "party-like" line.
///
/// A line looks like a party entry when it:
/// - Is short (≤ 120 chars), AND
/// - Starts with an uppercase letter (Title Case name or role), AND
/// - Contains at least one of: a comma, a digit (address), or a role keyword.
fn is_party_line(line: &str) -> bool {
    if line.len() > 120 {
        return false;
    }
    let starts_upper = line.chars().next().map(|c| c.is_uppercase()).unwrap_or(false);
    if !starts_upper {
        return false;
    }
    let has_digit = line.chars().any(|c| c.is_ascii_digit());
    let has_comma = line.contains(',');
    let lower = line.to_lowercase();
    let has_role = [
        "investor",
        "company",
        "borrower",
        "lender",
        "seller",
        "buyer",
        "party",
        "subscriber",
        "guarantor",
    ]
    .iter()
    .any(|r| lower.contains(r));
    has_digit || has_comma || has_role
}

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

    fn classify(content: &str) -> ChunkType {
        classify_chunk(content, None)
    }

    #[test]
    fn test_heading_atx() {
        assert_eq!(classify("# Introduction"), ChunkType::Heading);
        assert_eq!(classify("## Section 2"), ChunkType::Heading);
        assert_eq!(classify("### Sub-section"), ChunkType::Heading);
    }

    #[test]
    fn test_heading_setext() {
        assert_eq!(classify("Introduction\n============"), ChunkType::Heading);
        assert_eq!(classify("Section 2\n---------"), ChunkType::Heading);
    }

    #[test]
    fn test_not_heading_plain_text() {
        assert_ne!(classify("This is plain paragraph text."), ChunkType::Heading);
    }

    #[test]
    fn test_code_block_fenced() {
        assert_eq!(classify("```rust\nfn main() {}\n```"), ChunkType::CodeBlock);
        assert_eq!(classify("~~~python\nprint('hi')\n~~~"), ChunkType::CodeBlock);
    }

    #[test]
    fn test_code_block_indented() {
        let indented = "    fn main() {\n        println!(\"hello\");\n    }";
        assert_eq!(classify(indented), ChunkType::CodeBlock);
    }

    #[test]
    fn test_table_markdown() {
        let table = "| Name | Age |\n|------|-----|\n| Alice | 30 |";
        assert_eq!(classify(table), ChunkType::TableLike);
    }

    #[test]
    fn test_table_single_pipe_line_not_table() {
        assert_ne!(classify("Just one | separator here"), ChunkType::TableLike);
    }

    #[test]
    fn test_formula_unicode_symbols() {
        assert_eq!(classify("The total ∑ of all values equals 1."), ChunkType::Formula);
        assert_eq!(classify("∫ f(x) dx from 0 to ∞"), ChunkType::Formula);
    }

    #[test]
    fn test_formula_latex() {
        assert_eq!(classify(r"The result is $\frac{a}{b}$"), ChunkType::Formula);
        assert_eq!(classify(r"$$\sum_{i=0}^{n} x_i$$"), ChunkType::Formula);
    }

    #[test]
    fn test_schedule_first_line() {
        assert_eq!(
            classify("Schedule 1 – Definitions\n\nThis schedule sets out..."),
            ChunkType::Schedule
        );
        assert_eq!(classify("annex A: Technical Specifications"), ChunkType::Schedule);
    }

    #[test]
    fn test_definitions_means() {
        assert_eq!(
            classify("\"Agreement\" means this Investment and Subscription Agreement."),
            ChunkType::Definitions
        );
        assert_eq!(
            classify("\"Closing Date\" shall mean the date on which..."),
            ChunkType::Definitions
        );
    }

    #[test]
    fn test_definitions_is_defined_as() {
        assert_eq!(
            classify("The term 'Net Revenue' is defined as all revenue..."),
            ChunkType::Definitions
        );
    }

    #[test]
    fn test_signature_block() {
        let sig = "Signed by: John Smith\nDate: 2026-03-30\nWitnessed by: Jane Doe";
        assert_eq!(classify(sig), ChunkType::SignatureBlock);
    }

    #[test]
    fn test_signature_block_in_witness() {
        let sig = "In witness whereof the parties have duly authorized this agreement.\n____________________\nDate: ___________";
        assert_eq!(classify(sig), ChunkType::SignatureBlock);
    }

    #[test]
    fn test_operative_clause_basic() {
        let clause = "The Investor shall subscribe for the Shares and agrees to pay the subscription price. The Company shall deliver the Share certificates upon receipt.";
        assert_eq!(classify(clause), ChunkType::OperativeClause);
    }

    #[test]
    fn test_operative_clause_grant() {
        let clause = "The Licensor hereby grants, assigns, and transfers all right, title, and interest. The Licensee shall pay and deliver consideration.";
        assert_eq!(classify(clause), ChunkType::OperativeClause);
    }

    #[test]
    fn test_party_list_basic() {
        let parties = "Gregor Guggisberg, Winkelstrasse 12, Zurich\nInvestor\nAlpha Capital AG, Bahnhofstrasse 1, Zurich\nSubscriber\nBeta Holdings Ltd, 10 City Road, London\nBorrower";
        assert_eq!(classify(parties), ChunkType::PartyList);
    }

    #[test]
    fn test_unknown_plain_text() {
        assert_eq!(
            classify("This document contains general information."),
            ChunkType::Unknown
        );
    }

    #[test]
    fn test_unknown_empty() {
        assert_eq!(classify(""), ChunkType::Unknown);
    }

    #[test]
    fn test_heading_context_schedule() {
        use crate::types::{HeadingContext, HeadingLevel};
        let ctx = HeadingContext {
            headings: vec![HeadingLevel {
                level: 1,
                text: "Schedule 1 – Definitions".to_string(),
            }],
        };
        let result = classify_chunk("This schedule sets out the defined terms.", Some(&ctx));
        assert_eq!(result, ChunkType::Schedule);
    }
}