cognis 0.2.0

LLM application framework built on cognis-core
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
//! Enrichment transformers that add computed metadata to documents.
//!
//! These transformers analyze document content and attach useful metadata
//! such as word counts, character counts, language hints, keywords, and
//! summaries.

use std::collections::HashMap;

use async_trait::async_trait;
use serde_json::Value;

use cognis_core::documents::Document;
use cognis_core::error::Result;

use super::DocumentTransformer;

// ─── WordCountEnricher ───

/// Adds a `word_count` metadata field to each document.
///
/// Words are delimited by whitespace.
pub struct WordCountEnricher;

impl WordCountEnricher {
    /// Create a new word count enricher.
    pub fn new() -> Self {
        Self
    }
}

impl Default for WordCountEnricher {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl DocumentTransformer for WordCountEnricher {
    async fn transform_documents(&self, documents: &[Document]) -> Result<Vec<Document>> {
        Ok(documents
            .iter()
            .map(|doc| {
                let mut new_doc = doc.clone();
                let count = doc.page_content.split_whitespace().count();
                new_doc
                    .metadata
                    .insert("word_count".to_string(), Value::from(count as u64));
                new_doc
            })
            .collect())
    }

    fn name(&self) -> &str {
        "WordCountEnricher"
    }
}

// ─── CharCountEnricher ───

/// Adds a `char_count` metadata field to each document.
pub struct CharCountEnricher;

impl CharCountEnricher {
    /// Create a new character count enricher.
    pub fn new() -> Self {
        Self
    }
}

impl Default for CharCountEnricher {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl DocumentTransformer for CharCountEnricher {
    async fn transform_documents(&self, documents: &[Document]) -> Result<Vec<Document>> {
        Ok(documents
            .iter()
            .map(|doc| {
                let mut new_doc = doc.clone();
                let count = doc.page_content.chars().count();
                new_doc
                    .metadata
                    .insert("char_count".to_string(), Value::from(count as u64));
                new_doc
            })
            .collect())
    }

    fn name(&self) -> &str {
        "CharCountEnricher"
    }
}

// ─── LanguageDetector ───

/// Adds a `language` metadata field using heuristic Unicode script analysis.
///
/// Detects the predominant script family: `latin`, `cjk`, `cyrillic`,
/// `arabic`, or `unknown`.
pub struct LanguageDetector;

impl LanguageDetector {
    /// Create a new language detector.
    pub fn new() -> Self {
        Self
    }
}

impl Default for LanguageDetector {
    fn default() -> Self {
        Self::new()
    }
}

/// Simple language detection based on Unicode script analysis.
fn detect_language(text: &str) -> &'static str {
    let mut latin = 0u32;
    let mut cjk = 0u32;
    let mut cyrillic = 0u32;
    let mut arabic = 0u32;

    for ch in text.chars() {
        if ch.is_ascii_alphabetic() || matches!(ch, '\u{00C0}'..='\u{024F}') {
            latin += 1;
        } else if matches!(ch, '\u{4E00}'..='\u{9FFF}' | '\u{3040}'..='\u{30FF}') {
            cjk += 1;
        } else if matches!(ch, '\u{0400}'..='\u{04FF}') {
            cyrillic += 1;
        } else if matches!(ch, '\u{0600}'..='\u{06FF}') {
            arabic += 1;
        }
    }

    let max = latin.max(cjk).max(cyrillic).max(arabic);
    if max == 0 {
        return "unknown";
    }
    if max == cjk {
        "cjk"
    } else if max == cyrillic {
        "cyrillic"
    } else if max == arabic {
        "arabic"
    } else {
        "latin"
    }
}

#[async_trait]
impl DocumentTransformer for LanguageDetector {
    async fn transform_documents(&self, documents: &[Document]) -> Result<Vec<Document>> {
        Ok(documents
            .iter()
            .map(|doc| {
                let mut new_doc = doc.clone();
                let lang = detect_language(&doc.page_content);
                new_doc
                    .metadata
                    .insert("language".to_string(), Value::from(lang));
                new_doc
            })
            .collect())
    }

    fn name(&self) -> &str {
        "LanguageDetector"
    }
}

// ─── KeywordExtractor ───

/// Extracts top-N keywords from document content using term frequency scoring.
///
/// Words are lowercased, and common English stop words are filtered out.
/// The resulting keywords are stored as a JSON array in the `keywords`
/// metadata field.
///
/// # Example
///
/// ```rust,ignore
/// use cognis::document_transformers::enrichment::KeywordExtractor;
///
/// let extractor = KeywordExtractor::new(5);
/// let docs = extractor.transform_documents(&docs).await?;
/// ```
pub struct KeywordExtractor {
    top_n: usize,
}

impl KeywordExtractor {
    /// Create a keyword extractor that keeps the top `n` keywords.
    pub fn new(top_n: usize) -> Self {
        Self { top_n }
    }
}

/// A small set of common English stop words.
const STOP_WORDS: &[&str] = &[
    "a", "an", "and", "are", "as", "at", "be", "but", "by", "for", "from", "has", "have", "he",
    "her", "his", "how", "i", "if", "in", "into", "is", "it", "its", "my", "no", "not", "of", "on",
    "or", "our", "she", "so", "that", "the", "their", "them", "then", "there", "these", "they",
    "this", "to", "up", "us", "was", "we", "what", "when", "which", "who", "will", "with", "you",
    "your",
];

/// Extract top-N keywords from text using term frequency.
fn extract_keywords(text: &str, top_n: usize) -> Vec<String> {
    let stop_words: std::collections::HashSet<&str> = STOP_WORDS.iter().copied().collect();
    let mut freq: HashMap<String, usize> = HashMap::new();

    for word in text.split_whitespace() {
        let cleaned: String = word
            .chars()
            .filter(|c| c.is_alphanumeric())
            .collect::<String>()
            .to_lowercase();
        if cleaned.len() < 2 || stop_words.contains(cleaned.as_str()) {
            continue;
        }
        *freq.entry(cleaned).or_insert(0) += 1;
    }

    let mut entries: Vec<(String, usize)> = freq.into_iter().collect();
    entries.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
    entries.into_iter().take(top_n).map(|(w, _)| w).collect()
}

#[async_trait]
impl DocumentTransformer for KeywordExtractor {
    async fn transform_documents(&self, documents: &[Document]) -> Result<Vec<Document>> {
        Ok(documents
            .iter()
            .map(|doc| {
                let mut new_doc = doc.clone();
                let keywords = extract_keywords(&doc.page_content, self.top_n);
                let kw_value: Vec<Value> = keywords.into_iter().map(Value::from).collect();
                new_doc
                    .metadata
                    .insert("keywords".to_string(), Value::from(kw_value));
                new_doc
            })
            .collect())
    }

    fn name(&self) -> &str {
        "KeywordExtractor"
    }
}

// ─── DocumentSummarizer ───

/// Adds a truncated summary of the document content to metadata.
///
/// The summary is simply the first `max_length` characters of the content,
/// with an ellipsis appended if truncated.
///
/// # Example
///
/// ```rust,ignore
/// use cognis::document_transformers::enrichment::DocumentSummarizer;
///
/// let summarizer = DocumentSummarizer::new(100);
/// let docs = summarizer.transform_documents(&docs).await?;
/// ```
pub struct DocumentSummarizer {
    max_length: usize,
}

impl DocumentSummarizer {
    /// Create a summarizer that truncates content to the given maximum length.
    pub fn new(max_length: usize) -> Self {
        Self { max_length }
    }
}

#[async_trait]
impl DocumentTransformer for DocumentSummarizer {
    async fn transform_documents(&self, documents: &[Document]) -> Result<Vec<Document>> {
        Ok(documents
            .iter()
            .map(|doc| {
                let mut new_doc = doc.clone();
                let content = &doc.page_content;
                let summary = if content.chars().count() > self.max_length {
                    let truncated: String = content.chars().take(self.max_length).collect();
                    format!("{}...", truncated)
                } else {
                    content.clone()
                };
                new_doc
                    .metadata
                    .insert("summary".to_string(), Value::from(summary));
                new_doc
            })
            .collect())
    }

    fn name(&self) -> &str {
        "DocumentSummarizer"
    }
}

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

    fn make_doc(content: &str) -> Document {
        Document::new(content)
    }

    // ─── WordCountEnricher tests ───

    #[tokio::test]
    async fn test_word_count_enricher() {
        let enricher = WordCountEnricher::new();
        let docs = vec![make_doc("the quick brown fox")];
        let result = enricher.transform_documents(&docs).await.unwrap();
        assert_eq!(
            result[0]
                .metadata
                .get("word_count")
                .and_then(|v| v.as_u64()),
            Some(4)
        );
    }

    #[tokio::test]
    async fn test_word_count_empty_content() {
        let enricher = WordCountEnricher::new();
        let docs = vec![make_doc("")];
        let result = enricher.transform_documents(&docs).await.unwrap();
        assert_eq!(
            result[0]
                .metadata
                .get("word_count")
                .and_then(|v| v.as_u64()),
            Some(0)
        );
    }

    // ─── CharCountEnricher tests ───

    #[tokio::test]
    async fn test_char_count_enricher() {
        let enricher = CharCountEnricher::new();
        let docs = vec![make_doc("hello")];
        let result = enricher.transform_documents(&docs).await.unwrap();
        assert_eq!(
            result[0]
                .metadata
                .get("char_count")
                .and_then(|v| v.as_u64()),
            Some(5)
        );
    }

    #[tokio::test]
    async fn test_char_count_unicode() {
        let enricher = CharCountEnricher::new();
        let docs = vec![make_doc("\u{4F60}\u{597D}")]; // 2 CJK characters
        let result = enricher.transform_documents(&docs).await.unwrap();
        assert_eq!(
            result[0]
                .metadata
                .get("char_count")
                .and_then(|v| v.as_u64()),
            Some(2)
        );
    }

    // ─── LanguageDetector tests ───

    #[tokio::test]
    async fn test_language_detector_latin() {
        let detector = LanguageDetector::new();
        let docs = vec![make_doc("Hello world, this is English text")];
        let result = detector.transform_documents(&docs).await.unwrap();
        assert_eq!(
            result[0].metadata.get("language").and_then(|v| v.as_str()),
            Some("latin")
        );
    }

    #[tokio::test]
    async fn test_language_detector_cjk() {
        let detector = LanguageDetector::new();
        let docs = vec![make_doc("\u{4F60}\u{597D}\u{4E16}\u{754C}")];
        let result = detector.transform_documents(&docs).await.unwrap();
        assert_eq!(
            result[0].metadata.get("language").and_then(|v| v.as_str()),
            Some("cjk")
        );
    }

    #[tokio::test]
    async fn test_language_detector_unknown() {
        let detector = LanguageDetector::new();
        let docs = vec![make_doc("123 456 789")];
        let result = detector.transform_documents(&docs).await.unwrap();
        assert_eq!(
            result[0].metadata.get("language").and_then(|v| v.as_str()),
            Some("unknown")
        );
    }

    // ─── KeywordExtractor tests ───

    #[tokio::test]
    async fn test_keyword_extractor() {
        let extractor = KeywordExtractor::new(3);
        let docs = vec![make_doc("rust rust rust programming programming language")];
        let result = extractor.transform_documents(&docs).await.unwrap();
        let keywords = result[0]
            .metadata
            .get("keywords")
            .and_then(|v| v.as_array())
            .unwrap();
        // "rust" has freq 3, "programming" has freq 2, "language" has freq 1
        assert_eq!(keywords.len(), 3);
        assert_eq!(keywords[0].as_str().unwrap(), "rust");
        assert_eq!(keywords[1].as_str().unwrap(), "programming");
        assert_eq!(keywords[2].as_str().unwrap(), "language");
    }

    #[tokio::test]
    async fn test_keyword_extractor_filters_stop_words() {
        let extractor = KeywordExtractor::new(5);
        let docs = vec![make_doc("the the the and and or but is are was")];
        let result = extractor.transform_documents(&docs).await.unwrap();
        let keywords = result[0]
            .metadata
            .get("keywords")
            .and_then(|v| v.as_array())
            .unwrap();
        assert!(keywords.is_empty());
    }

    #[tokio::test]
    async fn test_keyword_extractor_top_n_limit() {
        let extractor = KeywordExtractor::new(2);
        let docs = vec![make_doc("alpha beta gamma delta epsilon")];
        let result = extractor.transform_documents(&docs).await.unwrap();
        let keywords = result[0]
            .metadata
            .get("keywords")
            .and_then(|v| v.as_array())
            .unwrap();
        assert_eq!(keywords.len(), 2);
    }

    // ─── DocumentSummarizer tests ───

    #[tokio::test]
    async fn test_summarizer_truncates() {
        let summarizer = DocumentSummarizer::new(10);
        let docs = vec![make_doc("This is a long document that should be truncated")];
        let result = summarizer.transform_documents(&docs).await.unwrap();
        let summary = result[0]
            .metadata
            .get("summary")
            .and_then(|v| v.as_str())
            .unwrap();
        assert!(summary.ends_with("..."));
        // 10 chars + "..."
        assert_eq!(summary.len(), 13);
    }

    #[tokio::test]
    async fn test_summarizer_short_content_no_truncation() {
        let summarizer = DocumentSummarizer::new(100);
        let docs = vec![make_doc("short")];
        let result = summarizer.transform_documents(&docs).await.unwrap();
        let summary = result[0]
            .metadata
            .get("summary")
            .and_then(|v| v.as_str())
            .unwrap();
        assert_eq!(summary, "short");
        assert!(!summary.ends_with("..."));
    }

    #[tokio::test]
    async fn test_summarizer_preserves_existing_metadata() {
        let summarizer = DocumentSummarizer::new(5);
        let mut meta = HashMap::new();
        meta.insert("source".to_string(), Value::from("test"));
        let docs = vec![Document::new("hello world").with_metadata(meta)];
        let result = summarizer.transform_documents(&docs).await.unwrap();
        assert_eq!(
            result[0].metadata.get("source").and_then(|v| v.as_str()),
            Some("test")
        );
        assert!(result[0].metadata.contains_key("summary"));
    }
}