Upload 46 files
Browse files
qusai_core/ontology/projection.py
CHANGED
|
@@ -7,6 +7,7 @@ Maps natural language β Quranic roots with provenance tracking.
|
|
| 7 |
import json
|
| 8 |
import re
|
| 9 |
import logging
|
|
|
|
| 10 |
from typing import List, Dict, Set, Optional, Tuple
|
| 11 |
from dataclasses import dataclass, field
|
| 12 |
from collections import Counter
|
|
@@ -38,6 +39,7 @@ class ProjectionService:
|
|
| 38 |
"""
|
| 39 |
Multi-layer semantic projection engine.
|
| 40 |
Deterministically maps natural language onto Quranic root hypergraph.
|
|
|
|
| 41 |
"""
|
| 42 |
|
| 43 |
def __init__(self,
|
|
@@ -57,6 +59,7 @@ class ProjectionService:
|
|
| 57 |
# Optional: sentence-transformers fallback (lazy load)
|
| 58 |
self._resonance_model = None
|
| 59 |
self._resonance_embeddings = None
|
|
|
|
| 60 |
|
| 61 |
logger.info(f"ProjectionService initialized: {len(self.english_to_root)} terms β {len(self.root_to_english)} roots")
|
| 62 |
|
|
@@ -83,8 +86,8 @@ class ProjectionService:
|
|
| 83 |
cooccur = self._discover_cooccurrences(high_conf_roots)
|
| 84 |
all_candidates.extend(cooccur)
|
| 85 |
|
| 86 |
-
# Layer 4: Resonance Fallback (only if all else fails)
|
| 87 |
-
if len(all_candidates) == 0 and self.use_resonance_fallback:
|
| 88 |
resonance = self._resonance_fallback(query.text)
|
| 89 |
all_candidates.extend(resonance)
|
| 90 |
|
|
@@ -120,7 +123,6 @@ class ProjectionService:
|
|
| 120 |
def _semantic_expansion(self, text: str, context: Dict) -> List[RootCandidate]:
|
| 121 |
"""
|
| 122 |
Layer 2: Context-aware synonym expansion.
|
| 123 |
-
Uses simple heuristics (can be extended with WordNet).
|
| 124 |
"""
|
| 125 |
candidates = []
|
| 126 |
|
|
@@ -128,8 +130,10 @@ class ProjectionService:
|
|
| 128 |
synonyms = {
|
| 129 |
"oppression": ["tyranny", "injustice", "persecution"],
|
| 130 |
"injustice": ["oppression", "wrongdoing"],
|
| 131 |
-
"darkness": ["oppression"],
|
| 132 |
"tyrant": ["oppressor", "pharaoh"],
|
|
|
|
|
|
|
| 133 |
}
|
| 134 |
|
| 135 |
words = self._tokenize(text)
|
|
@@ -143,48 +147,28 @@ class ProjectionService:
|
|
| 143 |
gloss = ", ".join(self.root_to_english.get(root, [""])[:5])
|
| 144 |
candidates.append(RootCandidate(
|
| 145 |
root=root,
|
| 146 |
-
confidence=0.7,
|
| 147 |
method="semantic_expansion",
|
| 148 |
provenance=f"synonym:{syn}",
|
| 149 |
source_span=word,
|
| 150 |
gloss=gloss
|
| 151 |
))
|
| 152 |
|
| 153 |
-
# Context boosting
|
| 154 |
-
if context.get("domain") == "political":
|
| 155 |
-
# Boost Zlm, Tgy, qsT, Hkm for political queries
|
| 156 |
-
political_roots = ["Zlm", "Tgy", "qsT", "Hkm", "Edl"]
|
| 157 |
-
for root in political_roots:
|
| 158 |
-
if not any(c.root == root for c in candidates):
|
| 159 |
-
gloss = ", ".join(self.root_to_english.get(root, [""])[:5])
|
| 160 |
-
candidates.append(RootCandidate(
|
| 161 |
-
root=root,
|
| 162 |
-
confidence=0.5,
|
| 163 |
-
method="context_inference",
|
| 164 |
-
provenance=f"domain:{context['domain']}",
|
| 165 |
-
source_span="(implicit)",
|
| 166 |
-
gloss=gloss
|
| 167 |
-
))
|
| 168 |
-
|
| 169 |
return candidates
|
| 170 |
|
| 171 |
def _discover_cooccurrences(self, roots: List[str]) -> List[RootCandidate]:
|
| 172 |
"""
|
| 173 |
Layer 3: Find roots that co-occur with detected roots in Qur'an.
|
| 174 |
-
Captures semantic fields.
|
| 175 |
"""
|
| 176 |
candidates = []
|
| 177 |
|
| 178 |
if not self.tmq_index:
|
| 179 |
return candidates
|
| 180 |
|
| 181 |
-
# For each detected root, find related roots
|
| 182 |
related_counter = Counter()
|
| 183 |
|
| 184 |
-
for root in roots[:3]:
|
| 185 |
verses = self.tmq_index.get_verse_set(root)
|
| 186 |
-
|
| 187 |
-
# Sample verses
|
| 188 |
for surah, ayah in list(verses)[:30]:
|
| 189 |
verse_edges = self.tmq_index.get_edges_for_ayah(surah, ayah)
|
| 190 |
for key, edge in verse_edges:
|
|
@@ -193,13 +177,12 @@ class ProjectionService:
|
|
| 193 |
if related_root != root:
|
| 194 |
related_counter[related_root] += 1
|
| 195 |
|
| 196 |
-
# Convert to candidates
|
| 197 |
for related_root, count in related_counter.items():
|
| 198 |
-
if count >= 5:
|
| 199 |
gloss = ", ".join(self.root_to_english.get(related_root, [""])[:5])
|
| 200 |
candidates.append(RootCandidate(
|
| 201 |
root=related_root,
|
| 202 |
-
confidence=min(0.8, count / 30),
|
| 203 |
method="cooccurrence",
|
| 204 |
provenance=f"tmq_graph:co-occurs_{count}x",
|
| 205 |
source_span="(discovered)",
|
|
@@ -211,16 +194,62 @@ class ProjectionService:
|
|
| 211 |
def _resonance_fallback(self, text: str) -> List[RootCandidate]:
|
| 212 |
"""
|
| 213 |
Layer 4: Vector embedding fallback (sentence-transformers).
|
| 214 |
-
|
| 215 |
"""
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
|
| 220 |
def _rank_and_deduplicate(self, candidates: List[RootCandidate]) -> List[RootCandidate]:
|
| 221 |
"""
|
| 222 |
Combine duplicate roots, keeping highest confidence.
|
| 223 |
-
Sort by confidence descending.
|
| 224 |
"""
|
| 225 |
best = {}
|
| 226 |
for c in candidates:
|
|
@@ -231,14 +260,9 @@ class ProjectionService:
|
|
| 231 |
|
| 232 |
def _tokenize(self, text: str) -> List[str]:
|
| 233 |
"""Simple word tokenization."""
|
| 234 |
-
# Remove punctuation, split on whitespace
|
| 235 |
cleaned = re.sub(r'[.,;:!?()\[\]{}"\']', ' ', text)
|
| 236 |
return [w.strip() for w in cleaned.split() if len(w.strip()) > 2]
|
| 237 |
|
| 238 |
-
def _contains_arabic(self, text: str) -> bool:
|
| 239 |
-
"""Check if text contains Arabic script."""
|
| 240 |
-
return bool(re.search(r'[\u0600-\u06FF]', text))
|
| 241 |
-
|
| 242 |
|
| 243 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 244 |
# Integration with Bilal
|
|
@@ -261,7 +285,6 @@ class BilalV2:
|
|
| 261 |
def listen(self, text: str):
|
| 262 |
"""
|
| 263 |
Main perception loop using ProjectionService.
|
| 264 |
-
Returns Perception object compatible with existing pipeline.
|
| 265 |
"""
|
| 266 |
from datetime import datetime, timezone
|
| 267 |
from dataclasses import dataclass
|
|
@@ -270,7 +293,7 @@ class BilalV2:
|
|
| 270 |
query = ProjectionQuery(text=text, language="en", context={})
|
| 271 |
root_candidates = self.projection_service.project(query)
|
| 272 |
|
| 273 |
-
# Convert to RootSignals
|
| 274 |
@dataclass
|
| 275 |
class RootSignal:
|
| 276 |
root: str
|
|
@@ -291,7 +314,7 @@ class BilalV2:
|
|
| 291 |
definition=candidate.gloss
|
| 292 |
))
|
| 293 |
|
| 294 |
-
# Co-occurrence discovery
|
| 295 |
unique_roots = list({s.root for s in signals})
|
| 296 |
cooccurrences = self._discover_cooccurrences_tmq(unique_roots)
|
| 297 |
|
|
@@ -304,6 +327,14 @@ class BilalV2:
|
|
| 304 |
cooccurrences: List
|
| 305 |
mode: str
|
| 306 |
timestamp: str
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 307 |
|
| 308 |
return Perception(
|
| 309 |
source_text=text,
|
|
@@ -329,7 +360,7 @@ class BilalV2:
|
|
| 329 |
return []
|
| 330 |
|
| 331 |
results = []
|
| 332 |
-
for r1, r2 in combinations(roots, 2):
|
| 333 |
v1 = self.hypermode_index.get_verse_set(r1)
|
| 334 |
v2 = self.hypermode_index.get_verse_set(r2)
|
| 335 |
shared = v1 & v2
|
|
@@ -341,7 +372,7 @@ class BilalV2:
|
|
| 341 |
count=len(shared)
|
| 342 |
))
|
| 343 |
|
| 344 |
-
results.sort(key=lambda c: c.count)
|
| 345 |
return results
|
| 346 |
|
| 347 |
def _confidence_to_mode(self, score: float) -> str:
|
|
|
|
| 7 |
import json
|
| 8 |
import re
|
| 9 |
import logging
|
| 10 |
+
import numpy as np
|
| 11 |
from typing import List, Dict, Set, Optional, Tuple
|
| 12 |
from dataclasses import dataclass, field
|
| 13 |
from collections import Counter
|
|
|
|
| 39 |
"""
|
| 40 |
Multi-layer semantic projection engine.
|
| 41 |
Deterministically maps natural language onto Quranic root hypergraph.
|
| 42 |
+
Uses vector resonance as a non-deterministic fallback to break silence.
|
| 43 |
"""
|
| 44 |
|
| 45 |
def __init__(self,
|
|
|
|
| 59 |
# Optional: sentence-transformers fallback (lazy load)
|
| 60 |
self._resonance_model = None
|
| 61 |
self._resonance_embeddings = None
|
| 62 |
+
self._root_keys = []
|
| 63 |
|
| 64 |
logger.info(f"ProjectionService initialized: {len(self.english_to_root)} terms β {len(self.root_to_english)} roots")
|
| 65 |
|
|
|
|
| 86 |
cooccur = self._discover_cooccurrences(high_conf_roots)
|
| 87 |
all_candidates.extend(cooccur)
|
| 88 |
|
| 89 |
+
# Layer 4: Resonance Fallback (only if all else fails or signal is weak)
|
| 90 |
+
if (len(all_candidates) == 0 or max([c.confidence for c in all_candidates], default=0) < 0.4) and self.use_resonance_fallback:
|
| 91 |
resonance = self._resonance_fallback(query.text)
|
| 92 |
all_candidates.extend(resonance)
|
| 93 |
|
|
|
|
| 123 |
def _semantic_expansion(self, text: str, context: Dict) -> List[RootCandidate]:
|
| 124 |
"""
|
| 125 |
Layer 2: Context-aware synonym expansion.
|
|
|
|
| 126 |
"""
|
| 127 |
candidates = []
|
| 128 |
|
|
|
|
| 130 |
synonyms = {
|
| 131 |
"oppression": ["tyranny", "injustice", "persecution"],
|
| 132 |
"injustice": ["oppression", "wrongdoing"],
|
| 133 |
+
"darkness": ["oppression"],
|
| 134 |
"tyrant": ["oppressor", "pharaoh"],
|
| 135 |
+
"faith": ["belief", "trust", "iman"],
|
| 136 |
+
"patience": ["perseverance", "endurance", "sabr"],
|
| 137 |
}
|
| 138 |
|
| 139 |
words = self._tokenize(text)
|
|
|
|
| 147 |
gloss = ", ".join(self.root_to_english.get(root, [""])[:5])
|
| 148 |
candidates.append(RootCandidate(
|
| 149 |
root=root,
|
| 150 |
+
confidence=0.7,
|
| 151 |
method="semantic_expansion",
|
| 152 |
provenance=f"synonym:{syn}",
|
| 153 |
source_span=word,
|
| 154 |
gloss=gloss
|
| 155 |
))
|
| 156 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
return candidates
|
| 158 |
|
| 159 |
def _discover_cooccurrences(self, roots: List[str]) -> List[RootCandidate]:
|
| 160 |
"""
|
| 161 |
Layer 3: Find roots that co-occur with detected roots in Qur'an.
|
|
|
|
| 162 |
"""
|
| 163 |
candidates = []
|
| 164 |
|
| 165 |
if not self.tmq_index:
|
| 166 |
return candidates
|
| 167 |
|
|
|
|
| 168 |
related_counter = Counter()
|
| 169 |
|
| 170 |
+
for root in roots[:3]:
|
| 171 |
verses = self.tmq_index.get_verse_set(root)
|
|
|
|
|
|
|
| 172 |
for surah, ayah in list(verses)[:30]:
|
| 173 |
verse_edges = self.tmq_index.get_edges_for_ayah(surah, ayah)
|
| 174 |
for key, edge in verse_edges:
|
|
|
|
| 177 |
if related_root != root:
|
| 178 |
related_counter[related_root] += 1
|
| 179 |
|
|
|
|
| 180 |
for related_root, count in related_counter.items():
|
| 181 |
+
if count >= 5:
|
| 182 |
gloss = ", ".join(self.root_to_english.get(related_root, [""])[:5])
|
| 183 |
candidates.append(RootCandidate(
|
| 184 |
root=related_root,
|
| 185 |
+
confidence=min(0.8, count / 30),
|
| 186 |
method="cooccurrence",
|
| 187 |
provenance=f"tmq_graph:co-occurs_{count}x",
|
| 188 |
source_span="(discovered)",
|
|
|
|
| 194 |
def _resonance_fallback(self, text: str) -> List[RootCandidate]:
|
| 195 |
"""
|
| 196 |
Layer 4: Vector embedding fallback (sentence-transformers).
|
| 197 |
+
The 'Quantum Compass' for breaking silence.
|
| 198 |
"""
|
| 199 |
+
if not self._resonance_model:
|
| 200 |
+
try:
|
| 201 |
+
from sentence_transformers import SentenceTransformer
|
| 202 |
+
logger.info("Loading SentenceTransformer (all-MiniLM-L6-v2) for resonance fallback...")
|
| 203 |
+
self._resonance_model = SentenceTransformer('all-MiniLM-L6-v2')
|
| 204 |
+
|
| 205 |
+
# Pre-compute root embeddings
|
| 206 |
+
self._root_keys = list(self.root_to_english.keys())
|
| 207 |
+
# Use first 3 gloss terms for each root to define its vector space
|
| 208 |
+
root_texts = [" ".join(self.root_to_english[k][:3]) for k in self._root_keys]
|
| 209 |
+
self._resonance_embeddings = self._resonance_model.encode(root_texts, normalize_embeddings=True)
|
| 210 |
+
logger.info(f"Resonance matrix ready: {len(self._root_keys)} roots")
|
| 211 |
+
except Exception as e:
|
| 212 |
+
logger.error(f"Failed to load resonance model: {e}")
|
| 213 |
+
return []
|
| 214 |
+
|
| 215 |
+
try:
|
| 216 |
+
query_vec = self._resonance_model.encode([text], normalize_embeddings=True)[0]
|
| 217 |
+
# Add a small amount of "non-deterministic" noise to the query vector to vary results slightly
|
| 218 |
+
# (as requested: non-deterministic vector mapping)
|
| 219 |
+
noise = np.random.normal(0, 0.01, query_vec.shape)
|
| 220 |
+
query_vec = (query_vec + noise)
|
| 221 |
+
query_vec /= np.linalg.norm(query_vec)
|
| 222 |
+
|
| 223 |
+
scores = np.dot(self._resonance_embeddings, query_vec)
|
| 224 |
+
|
| 225 |
+
# Get top 5 matches
|
| 226 |
+
top_indices = np.argsort(scores)[::-1][:5]
|
| 227 |
+
candidates = []
|
| 228 |
+
|
| 229 |
+
for idx in top_indices:
|
| 230 |
+
score = float(scores[idx])
|
| 231 |
+
if score < 0.25: # Minimum resonance threshold
|
| 232 |
+
break
|
| 233 |
+
|
| 234 |
+
root = self._root_keys[idx]
|
| 235 |
+
gloss = ", ".join(self.root_to_english.get(root, [""])[:5])
|
| 236 |
+
candidates.append(RootCandidate(
|
| 237 |
+
root=root,
|
| 238 |
+
confidence=score,
|
| 239 |
+
method="resonance",
|
| 240 |
+
provenance=f"vector_sim:{score:.2f}",
|
| 241 |
+
source_span=text,
|
| 242 |
+
gloss=gloss
|
| 243 |
+
))
|
| 244 |
+
|
| 245 |
+
return candidates
|
| 246 |
+
except Exception as e:
|
| 247 |
+
logger.error(f"Resonance fallback failed: {e}")
|
| 248 |
+
return []
|
| 249 |
|
| 250 |
def _rank_and_deduplicate(self, candidates: List[RootCandidate]) -> List[RootCandidate]:
|
| 251 |
"""
|
| 252 |
Combine duplicate roots, keeping highest confidence.
|
|
|
|
| 253 |
"""
|
| 254 |
best = {}
|
| 255 |
for c in candidates:
|
|
|
|
| 260 |
|
| 261 |
def _tokenize(self, text: str) -> List[str]:
|
| 262 |
"""Simple word tokenization."""
|
|
|
|
| 263 |
cleaned = re.sub(r'[.,;:!?()\[\]{}"\']', ' ', text)
|
| 264 |
return [w.strip() for w in cleaned.split() if len(w.strip()) > 2]
|
| 265 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 266 |
|
| 267 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 268 |
# Integration with Bilal
|
|
|
|
| 285 |
def listen(self, text: str):
|
| 286 |
"""
|
| 287 |
Main perception loop using ProjectionService.
|
|
|
|
| 288 |
"""
|
| 289 |
from datetime import datetime, timezone
|
| 290 |
from dataclasses import dataclass
|
|
|
|
| 293 |
query = ProjectionQuery(text=text, language="en", context={})
|
| 294 |
root_candidates = self.projection_service.project(query)
|
| 295 |
|
| 296 |
+
# Convert to RootSignals
|
| 297 |
@dataclass
|
| 298 |
class RootSignal:
|
| 299 |
root: str
|
|
|
|
| 314 |
definition=candidate.gloss
|
| 315 |
))
|
| 316 |
|
| 317 |
+
# Co-occurrence discovery
|
| 318 |
unique_roots = list({s.root for s in signals})
|
| 319 |
cooccurrences = self._discover_cooccurrences_tmq(unique_roots)
|
| 320 |
|
|
|
|
| 327 |
cooccurrences: List
|
| 328 |
mode: str
|
| 329 |
timestamp: str
|
| 330 |
+
|
| 331 |
+
@property
|
| 332 |
+
def roots(self):
|
| 333 |
+
seen = {}
|
| 334 |
+
for s in self.signals:
|
| 335 |
+
if s.root not in seen or s.score > seen[s.root]:
|
| 336 |
+
seen[s.root] = s.score
|
| 337 |
+
return sorted(seen.keys(), key=lambda r: seen[r], reverse=True)
|
| 338 |
|
| 339 |
return Perception(
|
| 340 |
source_text=text,
|
|
|
|
| 360 |
return []
|
| 361 |
|
| 362 |
results = []
|
| 363 |
+
for r1, r2 in combinations(roots[:5], 2):
|
| 364 |
v1 = self.hypermode_index.get_verse_set(r1)
|
| 365 |
v2 = self.hypermode_index.get_verse_set(r2)
|
| 366 |
shared = v1 & v2
|
|
|
|
| 372 |
count=len(shared)
|
| 373 |
))
|
| 374 |
|
| 375 |
+
results.sort(key=lambda c: c.count, reverse=True)
|
| 376 |
return results
|
| 377 |
|
| 378 |
def _confidence_to_mode(self, score: float) -> str:
|