oxirs-core 0.2.2

Core RDF and SPARQL functionality for OxiRS - native Rust implementation with zero dependencies
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
//! Relation Extraction from Text using NLP
//!
//! This module provides automated relation extraction capabilities to build
//! knowledge graphs from unstructured text data.

use crate::ai::AiConfig;
use crate::model::{Literal, NamedNode, Triple};
use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Relation extraction module
pub struct RelationExtractor {
    /// Configuration
    config: ExtractionConfig,

    /// Named Entity Recognition model
    ner_model: Box<dyn NamedEntityRecognizer>,

    /// Relation classification model
    relation_model: Box<dyn RelationClassifier>,

    /// Entity linking module
    entity_linker: Box<dyn EntityLinker>,

    /// Confidence threshold
    confidence_threshold: f32,
}

/// Relation extraction configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExtractionConfig {
    /// Enable named entity recognition
    pub enable_ner: bool,

    /// Enable relation classification
    pub enable_relation_classification: bool,

    /// Enable entity linking
    pub enable_entity_linking: bool,

    /// Confidence threshold for extractions
    pub confidence_threshold: f32,

    /// Maximum sentence length
    pub max_sentence_length: usize,

    /// Language model to use
    pub language_model: String,

    /// Enable coreference resolution
    pub enable_coreference: bool,

    /// Supported languages
    pub supported_languages: Vec<String>,
}

impl Default for ExtractionConfig {
    fn default() -> Self {
        Self {
            enable_ner: true,
            enable_relation_classification: true,
            enable_entity_linking: true,
            confidence_threshold: 0.7,
            max_sentence_length: 512,
            language_model: "bert-base-uncased".to_string(),
            enable_coreference: true,
            supported_languages: vec!["en".to_string()],
        }
    }
}

/// Extracted relation from text
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExtractedRelation {
    /// Subject entity
    pub subject: ExtractedEntity,

    /// Predicate/relation type
    pub predicate: String,

    /// Object entity
    pub object: ExtractedEntity,

    /// Confidence score
    pub confidence: f32,

    /// Source text span
    pub source_span: TextSpan,

    /// Context sentence
    pub context: String,

    /// Additional metadata
    pub metadata: HashMap<String, String>,
}

/// Extracted entity
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExtractedEntity {
    /// Entity text
    pub text: String,

    /// Entity type
    pub entity_type: EntityType,

    /// Linked knowledge base ID (if available)
    pub kb_id: Option<String>,

    /// Confidence score
    pub confidence: f32,

    /// Text span in original document
    pub span: TextSpan,
}

/// Entity types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum EntityType {
    Person,
    Organization,
    Location,
    Date,
    Time,
    Money,
    Percent,
    Product,
    Event,
    Concept,
    Other(String),
}

/// Text span
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TextSpan {
    /// Start position
    pub start: usize,

    /// End position
    pub end: usize,

    /// Text content
    pub text: String,
}

/// Named Entity Recognition trait
pub trait NamedEntityRecognizer: Send + Sync {
    /// Extract named entities from text
    fn extract_entities(&self, text: &str) -> Result<Vec<ExtractedEntity>>;

    /// Get supported entity types
    fn supported_types(&self) -> Vec<EntityType>;
}

/// Relation classification trait
pub trait RelationClassifier: Send + Sync {
    /// Classify relation between two entities
    fn classify_relation(
        &self,
        text: &str,
        subject: &ExtractedEntity,
        object: &ExtractedEntity,
    ) -> Result<Option<(String, f32)>>;

    /// Get supported relation types
    fn supported_relations(&self) -> Vec<String>;
}

/// Entity linking trait
pub trait EntityLinker: Send + Sync {
    /// Link entity to knowledge base
    fn link_entity(&self, entity: &ExtractedEntity, context: &str) -> Result<Option<String>>;

    /// Get knowledge base info
    fn kb_info(&self) -> KnowledgeBaseInfo;
}

/// Knowledge base information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KnowledgeBaseInfo {
    /// Knowledge base name
    pub name: String,

    /// Base URI
    pub base_uri: String,

    /// Version
    pub version: String,

    /// Entity count
    pub entity_count: usize,
}

impl RelationExtractor {
    /// Create new relation extractor
    pub fn new(_config: &AiConfig) -> Result<Self> {
        let extraction_config = ExtractionConfig::default();

        // Create NER model
        let ner_model = Box::new(DummyNER::new());

        // Create relation classifier
        let relation_model = Box::new(DummyRelationClassifier::new());

        // Create entity linker
        let entity_linker = Box::new(DummyEntityLinker::new());

        Ok(Self {
            config: extraction_config,
            ner_model,
            relation_model,
            entity_linker,
            confidence_threshold: 0.7,
        })
    }

    /// Extract relations from text
    pub async fn extract_relations(&self, text: &str) -> Result<Vec<ExtractedRelation>> {
        // Step 1: Sentence segmentation
        let sentences = self.segment_sentences(text);

        let mut all_relations = Vec::new();

        for sentence in sentences {
            // Step 2: Named Entity Recognition
            let entities = if self.config.enable_ner {
                self.ner_model.extract_entities(&sentence)?
            } else {
                Vec::new()
            };

            // Step 3: Entity Linking
            let linked_entities = if self.config.enable_entity_linking {
                self.link_entities(&entities, &sentence).await?
            } else {
                entities
            };

            // Step 4: Relation Classification
            if self.config.enable_relation_classification {
                let relations =
                    self.extract_relations_from_entities(&sentence, &linked_entities)?;
                all_relations.extend(relations);
            }
        }

        // Step 5: Filter by confidence
        let filtered_relations = all_relations
            .into_iter()
            .filter(|r| r.confidence >= self.confidence_threshold)
            .collect();

        Ok(filtered_relations)
    }

    /// Convert extracted relations to RDF triples
    pub fn to_triples(&self, relations: &[ExtractedRelation]) -> Result<Vec<Triple>> {
        let mut triples = Vec::new();

        for relation in relations {
            // Create subject
            let subject = if let Some(kb_id) = &relation.subject.kb_id {
                NamedNode::new(kb_id)?
            } else {
                // Use text as identifier (simplified)
                NamedNode::new(format!(
                    "http://example.org/entity/{}",
                    relation.subject.text.replace(' ', "_")
                ))?
            };

            // Create predicate
            let predicate = NamedNode::new(format!(
                "http://example.org/relation/{}",
                relation.predicate.replace(' ', "_")
            ))?;

            // Create object
            let object = if let Some(kb_id) = &relation.object.kb_id {
                crate::model::Object::NamedNode(NamedNode::new(kb_id)?)
            } else {
                // Determine if it's a literal or named node
                match relation.object.entity_type {
                    EntityType::Date
                    | EntityType::Time
                    | EntityType::Money
                    | EntityType::Percent => {
                        crate::model::Object::Literal(Literal::new(&relation.object.text))
                    }
                    _ => crate::model::Object::NamedNode(NamedNode::new(format!(
                        "http://example.org/entity/{}",
                        relation.object.text.replace(' ', "_")
                    ))?),
                }
            };

            let triple = Triple::new(subject, predicate, object);
            triples.push(triple);
        }

        Ok(triples)
    }

    /// Segment text into sentences
    fn segment_sentences(&self, text: &str) -> Vec<String> {
        // Simplified sentence segmentation
        text.split(". ")
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect()
    }

    /// Link entities to knowledge base
    async fn link_entities(
        &self,
        entities: &[ExtractedEntity],
        context: &str,
    ) -> Result<Vec<ExtractedEntity>> {
        let mut linked_entities = Vec::new();

        for entity in entities {
            let mut linked_entity = entity.clone();

            if let Ok(Some(kb_id)) = self.entity_linker.link_entity(entity, context) {
                linked_entity.kb_id = Some(kb_id);
            }

            linked_entities.push(linked_entity);
        }

        Ok(linked_entities)
    }

    /// Extract relations from entities in a sentence
    fn extract_relations_from_entities(
        &self,
        sentence: &str,
        entities: &[ExtractedEntity],
    ) -> Result<Vec<ExtractedRelation>> {
        let mut relations = Vec::new();

        // Try all pairs of entities
        for (i, subject) in entities.iter().enumerate() {
            for (j, object) in entities.iter().enumerate() {
                if i != j {
                    if let Ok(Some((relation_type, confidence))) = self
                        .relation_model
                        .classify_relation(sentence, subject, object)
                    {
                        let relation = ExtractedRelation {
                            subject: subject.clone(),
                            predicate: relation_type,
                            object: object.clone(),
                            confidence,
                            source_span: TextSpan {
                                start: 0,
                                end: sentence.len(),
                                text: sentence.to_string(),
                            },
                            context: sentence.to_string(),
                            metadata: HashMap::new(),
                        };

                        relations.push(relation);
                    }
                }
            }
        }

        Ok(relations)
    }
}

/// Dummy NER implementation (placeholder)
struct DummyNER;

impl DummyNER {
    fn new() -> Self {
        Self
    }
}

impl NamedEntityRecognizer for DummyNER {
    fn extract_entities(&self, text: &str) -> Result<Vec<ExtractedEntity>> {
        // Placeholder implementation
        // In real implementation, would use NLP models like spaCy, BERT-NER, etc.

        let words: Vec<&str> = text.split_whitespace().collect();
        let mut entities = Vec::new();

        for (i, word) in words.iter().enumerate() {
            // Simple heuristics (placeholder)
            if word.chars().next().unwrap_or(' ').is_uppercase() {
                let entity = ExtractedEntity {
                    text: word.to_string(),
                    entity_type: EntityType::Person, // Simplified
                    kb_id: None,
                    confidence: 0.8,
                    span: TextSpan {
                        start: i * 5, // Simplified
                        end: (i + 1) * 5,
                        text: word.to_string(),
                    },
                };
                entities.push(entity);
            }
        }

        Ok(entities)
    }

    fn supported_types(&self) -> Vec<EntityType> {
        vec![
            EntityType::Person,
            EntityType::Organization,
            EntityType::Location,
        ]
    }
}

/// Dummy relation classifier (placeholder)
struct DummyRelationClassifier;

impl DummyRelationClassifier {
    fn new() -> Self {
        Self
    }
}

impl RelationClassifier for DummyRelationClassifier {
    fn classify_relation(
        &self,
        text: &str,
        _subject: &ExtractedEntity,
        _object: &ExtractedEntity,
    ) -> Result<Option<(String, f32)>> {
        // Placeholder implementation
        // In real implementation, would use relation classification models

        if text.contains("work") || text.contains("employ") {
            Ok(Some(("worksFor".to_string(), 0.85)))
        } else if text.contains("live") || text.contains("reside") {
            Ok(Some(("livesIn".to_string(), 0.80)))
        } else if text.contains("born") || text.contains("birth") {
            Ok(Some(("bornIn".to_string(), 0.90)))
        } else {
            Ok(None)
        }
    }

    fn supported_relations(&self) -> Vec<String> {
        vec![
            "worksFor".to_string(),
            "livesIn".to_string(),
            "bornIn".to_string(),
            "marriedTo".to_string(),
            "locatedIn".to_string(),
        ]
    }
}

/// Dummy entity linker (placeholder)
struct DummyEntityLinker;

impl DummyEntityLinker {
    fn new() -> Self {
        Self
    }
}

impl EntityLinker for DummyEntityLinker {
    fn link_entity(&self, entity: &ExtractedEntity, _context: &str) -> Result<Option<String>> {
        // Placeholder implementation
        // In real implementation, would use entity linking systems like DBpedia Spotlight

        match entity.entity_type {
            EntityType::Person => Ok(Some(format!(
                "http://dbpedia.org/resource/{}",
                entity.text.replace(' ', "_")
            ))),
            EntityType::Location => Ok(Some(format!(
                "http://dbpedia.org/resource/{}",
                entity.text.replace(' ', "_")
            ))),
            _ => Ok(None),
        }
    }

    fn kb_info(&self) -> KnowledgeBaseInfo {
        KnowledgeBaseInfo {
            name: "DBpedia".to_string(),
            base_uri: "http://dbpedia.org/resource/".to_string(),
            version: "2023-09".to_string(),
            entity_count: 6_000_000,
        }
    }
}

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

    #[tokio::test]
    async fn test_relation_extractor_creation() {
        let config = AiConfig::default();
        let extractor = RelationExtractor::new(&config);
        assert!(extractor.is_ok());
    }

    #[tokio::test]
    async fn test_relation_extraction() {
        let config = AiConfig::default();
        let extractor = RelationExtractor::new(&config).expect("construction should succeed");

        let text = "John works for Microsoft. He lives in Seattle.";
        let relations = extractor
            .extract_relations(text)
            .await
            .expect("async operation should succeed");

        // Should extract some relations (depends on dummy implementation)
        assert!(!relations.is_empty());
    }

    #[test]
    fn test_sentence_segmentation() {
        let config = AiConfig::default();
        let extractor = RelationExtractor::new(&config).expect("construction should succeed");

        let text = "First sentence. Second sentence. Third sentence.";
        let sentences = extractor.segment_sentences(text);

        assert_eq!(sentences.len(), 3);
        assert_eq!(sentences[0], "First sentence");
    }

    #[test]
    fn test_to_triples() {
        let config = AiConfig::default();
        let extractor = RelationExtractor::new(&config).expect("construction should succeed");

        let relation = ExtractedRelation {
            subject: ExtractedEntity {
                text: "John".to_string(),
                entity_type: EntityType::Person,
                kb_id: None,
                confidence: 0.9,
                span: TextSpan {
                    start: 0,
                    end: 4,
                    text: "John".to_string(),
                },
            },
            predicate: "worksFor".to_string(),
            object: ExtractedEntity {
                text: "Microsoft".to_string(),
                entity_type: EntityType::Organization,
                kb_id: None,
                confidence: 0.85,
                span: TextSpan {
                    start: 15,
                    end: 24,
                    text: "Microsoft".to_string(),
                },
            },
            confidence: 0.8,
            source_span: TextSpan {
                start: 0,
                end: 25,
                text: "John works for Microsoft.".to_string(),
            },
            context: "John works for Microsoft.".to_string(),
            metadata: HashMap::new(),
        };

        let triples = extractor
            .to_triples(&[relation])
            .expect("operation should succeed");
        assert_eq!(triples.len(), 1);
    }
}