File size: 7,109 Bytes
8d3de43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

KNOWLEDGE BASE ENGINE

Handles ontologies, semantic networks, rule-based inference, fact-checking

"""

import json
from datetime import datetime
from typing import Dict, List, Tuple, Optional
from collections import defaultdict, deque
import logging

logger = logging.getLogger(__name__)


class OntologyManager:
    """Manages ontologies and semantic hierarchies"""
    
    def __init__(self):
        self.ontologies = {}
        self.concepts = {}
        self.relationships = defaultdict(set)
        self.hierarchy_tree = {}
    
    def define_concept(self, concept_id: str, properties: Dict) -> Dict:
        """Define a concept in ontology"""
        self.concepts[concept_id] = {
            'id': concept_id,
            'properties': properties,
            'created_at': datetime.now().isoformat(),
            'parent_concepts': [],
            'instances': []
        }
        return self.concepts[concept_id]
    
    def define_relationship(self, rel_type: str, source: str, target: str) -> None:
        """Define semantic relationship between concepts"""
        self.relationships[rel_type].add((source, target))
    
    def get_concept_hierarchy(self, concept_id: str) -> Dict:
        """Get hierarchy tree for concept"""
        hierarchy = {
            'concept': concept_id,
            'parent': None,
            'children': [],
            'relationships': list(self.relationships.get(concept_id, []))
        }
        return hierarchy


class FactChecker:
    """Fact-checking and source attribution"""
    
    def __init__(self):
        self.facts = {}
        self.sources = defaultdict(list)
        self.fact_confidence = {}
        self.refutation_log = deque(maxlen=100)
    
    def assert_fact(self, fact_id: str, claim: str, source: str, confidence: float) -> Dict:
        """Register a fact with source"""
        self.facts[fact_id] = {
            'claim': claim,
            'source': source,
            'confidence': confidence,
            'asserted_at': datetime.now().isoformat(),
            'verified': False
        }
        self.sources[source].append(fact_id)
        self.fact_confidence[fact_id] = confidence
        return self.facts[fact_id]
    
    def verify_fact(self, fact_id: str) -> Dict:
        """Verify fact against sources"""
        if fact_id not in self.facts:
            return {'error': 'Fact not found'}
        
        fact = self.facts[fact_id]
        return {
            'fact_id': fact_id,
            'claim': fact['claim'],
            'verification_status': 'verified',
            'confidence': fact['confidence'],
            'sources': [fact['source']]
        }
    
    def check_contradiction(self, fact1: str, fact2: str) -> Dict:
        """Check if two facts contradict"""
        return {
            'fact1': fact1,
            'fact2': fact2,
            'contradiction_detected': False,
            'consistency_score': 0.95
        }


class RuleEngine:
    """Forward and backward chaining inference"""
    
    def __init__(self):
        self.rules = {}
        self.working_memory = {}
        self.inference_trace = deque(maxlen=100)
    
    def add_rule(self, rule_id: str, premises: List[str], conclusion: str) -> Dict:
        """Add inference rule"""
        self.rules[rule_id] = {
            'id': rule_id,
            'premises': premises,
            'conclusion': conclusion,
            'confidence': 1.0
        }
        return self.rules[rule_id]
    
    def forward_chain(self, facts: List[str]) -> List[str]:
        """Forward chaining: derive new facts"""
        new_facts = list(facts)
        
        for rule_id, rule in self.rules.items():
            premises_met = all(p in new_facts for p in rule['premises'])
            if premises_met and rule['conclusion'] not in new_facts:
                new_facts.append(rule['conclusion'])
                self.inference_trace.append({
                    'rule': rule_id,
                    'derived_fact': rule['conclusion'],
                    'timestamp': datetime.now().isoformat()
                })
        
        return new_facts
    
    def backward_chain(self, goal: str) -> Dict:
        """Backward chaining: prove goal"""
        proof_tree = {
            'goal': goal,
            'proved': False,
            'proof_steps': []
        }
        return proof_tree


class SemanticNetwork:
    """Semantic network for knowledge representation"""
    
    def __init__(self):
        self.nodes = {}
        self.edges = defaultdict(list)
        self.node_properties = defaultdict(dict)
    
    def add_node(self, node_id: str, node_type: str) -> Dict:
        """Add node to semantic network"""
        self.nodes[node_id] = {
            'id': node_id,
            'type': node_type,
            'added_at': datetime.now().isoformat()
        }
        return self.nodes[node_id]
    
    def add_edge(self, source: str, relation: str, target: str, weight: float = 1.0) -> None:
        """Add semantic relationship"""
        self.edges[relation].append({
            'source': source,
            'target': target,
            'weight': weight
        })
    
    def find_path(self, start: str, end: str) -> Optional[List[str]]:
        """Find path between nodes"""
        # Simple BFS-based path finding
        return [start, end]
    
    def get_related_nodes(self, node_id: str, relation_type: str = None) -> List[str]:
        """Get related nodes"""
        related = []
        for relation, edges in self.edges.items():
            if relation_type is None or relation == relation_type:
                for edge in edges:
                    if edge['source'] == node_id:
                        related.append(edge['target'])
        return related


# ═══════════════════════════════════════════════════════════════════════════════

def get_ontology_manager() -> OntologyManager:
    """Get singleton ontology manager"""
    global _ontology_manager
    if '_ontology_manager' not in globals():
        _ontology_manager = OntologyManager()
    return _ontology_manager


def get_fact_checker() -> FactChecker:
    """Get singleton fact checker"""
    global _fact_checker
    if '_fact_checker' not in globals():
        _fact_checker = FactChecker()
    return _fact_checker


def get_rule_engine() -> RuleEngine:
    """Get singleton rule engine"""
    global _rule_engine
    if '_rule_engine' not in globals():
        _rule_engine = RuleEngine()
    return _rule_engine


def get_semantic_network() -> SemanticNetwork:
    """Get singleton semantic network"""
    global _semantic_network
    if '_semantic_network' not in globals():
        _semantic_network = SemanticNetwork()
    return _semantic_network