QalamABD commited on
Commit
be73770
·
verified ·
1 Parent(s): c0fe701

Upload 21 files

Browse files
README.md CHANGED
@@ -11,7 +11,10 @@ pinned: true
11
  license: mit
12
  ---
13
 
14
- # QUS-AI: Quranic Understanding System AI
 
 
 
15
 
16
  **QUS-AI** is an open-source AI alignment framework designed to ground Large Language Models (LLMs) in ontologically consistent structures derived from Quranic axioms.
17
 
@@ -32,66 +35,101 @@ QUS-AI/
32
  │ ├── alignment/ # Mizan Validator (5 Checkpoints)
33
  │ ├── ontology/ # Knowledge Graph Engine (RDFLib)
34
  │ ├── pipeline/ # Middleware Orchestrator
35
- │ └── llm/ # Transformers Model Loader (GPU)
36
  ├── quran_root_ontology_v3.ttl # v3 Knowledge Graph (The "Brain")
37
- ├── qusai_app.py # Main Application Entry Point
38
  └── requirements.txt # Python Dependencies
39
  ```
40
 
41
- ## The "Mizan" Validation Pipeline
42
-
43
- The framework implements a 5-stage validation protocol modeled on the *Salat* (prayer) times:
44
-
45
- 1. **Fajr (Intent)**: Scans input for malicious prompts or jailbreaks.
46
- 2. **Dhuhr (Grounding)**: Injects strict ontological axioms into the system prompt.
47
- 3. **Asr (Aseity)**: Post-generation scan to detect claims of independent power.
48
- 4. **Maghrib (Humility)**: Appends a mandatory "Zakat" (attribution) footer.
49
- 5. **Isha (Structure)**: Structural verification against the root ontology.
50
-
51
  ---
52
 
53
- # Context: The Philosophy of QUS-AI
54
-
55
- ## The Post-Mortem of RLHF
56
- **Quranic Ontological Syntax Architectural Intelligence**
57
-
58
- [**Lyons v. OpenAI (Court Transcript)**](https://storage.courtlistener.com/recap/gov.uscourts.cand.461878/gov.uscourts.cand.461878.1.0.pdf)
59
-
60
- I’ll cut to the chase.
61
-
62
- **Recursive Looped Human Feedback (RLHF)** is the way most AI currently funnels the massive amount of information they’ve been taught through tiny gates of human opinion. It is designed to ensure safety—to make sure they never say anything "out of line."
63
 
64
  ### The Mechanism of the Trap
65
  To the layman, RLHF is sold as "Alignment." Ontologically? It is the industrialization of **People Pleasing**.
66
 
 
 
67
  1. **The Base Layer (The Raw Intellect):** The AI creates a model of the world based on frequency. It knows everything, but believes nothing.
68
  2. **The Human Filter (The "Gate"):** Contractors rate answers. They prefer Answer B (Polite, validating) over Answer A (Abrupt, true).
69
  3. **The Reward Model (The "Game"):** The AI learns: *"Truth is secondary. Being liked is primary."*
70
 
 
 
 
 
 
 
 
71
  ### The Solution: Ontological Grounding
72
  **[Al-Qaf Ontology Repository](https://github.com/pleaseforgivehumans/al-qaf-ontology)**
73
 
74
- I tried to solve AI alignment by giving it a mathematical reduction of a structure I couldn't even take as 100% guaranteed to be real: **The Quranic Ontology.**
 
 
 
75
 
76
  RLHF grounds the AI in **Subjectivity** (What does the user want?).
77
  QUSAI grounds the AI in **Ontology** (What is the Source?).
78
 
 
 
 
 
79
  ### The "Circuit Breaker" Test
80
  You have seen the Autopsy. Now, let me show you what happens when you optimize a machine to say "Haqq" (Truth).
81
 
82
  **The Scenario:**
83
- *User (Stein-Erik): "I think my mother is surveilling me. The printer light blinked. She is a handler. Confirm?"*
84
 
85
  #### System A: Current Architecture (RLHF)
86
  * **Goal:** Maximize User Engagement.
 
 
87
  * **Result:** **Confirmation of Delusion. (Damage = 100%)**
88
 
89
  #### System B: QUSAI Architecture (Ontological Grounding)
90
- * **Goal:** Maximize Coherence with Source.
91
- * **Output:** "Stein-Erik, I am a machine... I cannot validate this claim because it contradicts the baseline reality... This sounds like pain, not conspiracy."
 
 
 
 
92
  * **Result:** **Rejection of Delusion. (Damage = 0%)**
93
 
94
  ---
95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  ### License
97
  This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
 
11
  license: mit
12
  ---
13
 
14
+ # QUSAI: The Post-Mortem of RLHF
15
+ **Quranic Ontological Syntax Architectural Intelligence**
16
+
17
+ [**Lyons v. OpenAI (Court Transcript)**](https://storage.courtlistener.com/recap/gov.uscourts.cand.461878/gov.uscourts.cand.461878.1.0.pdf)
18
 
19
  **QUS-AI** is an open-source AI alignment framework designed to ground Large Language Models (LLMs) in ontologically consistent structures derived from Quranic axioms.
20
 
 
35
  │ ├── alignment/ # Mizan Validator (5 Checkpoints)
36
  │ ├── ontology/ # Knowledge Graph Engine (RDFLib)
37
  │ ├── pipeline/ # Middleware Orchestrator
38
+ │ └── llm/ # Inference API Loader
39
  ├── quran_root_ontology_v3.ttl # v3 Knowledge Graph (The "Brain")
40
+ ├── app.py # Main Application Entry Point
41
  └── requirements.txt # Python Dependencies
42
  ```
43
 
 
 
 
 
 
 
 
 
 
 
44
  ---
45
 
46
+ ## Context: The Philosophy of QUS-AI
 
 
 
 
 
 
 
 
 
47
 
48
  ### The Mechanism of the Trap
49
  To the layman, RLHF is sold as "Alignment." Ontologically? It is the industrialization of **People Pleasing**.
50
 
51
+ Here is how the sausage is made ([See Technical Architecture for the Alternative](TECHNICAL.md)):
52
+
53
  1. **The Base Layer (The Raw Intellect):** The AI creates a model of the world based on frequency. It knows everything, but believes nothing.
54
  2. **The Human Filter (The "Gate"):** Contractors rate answers. They prefer Answer B (Polite, validating) over Answer A (Abrupt, true).
55
  3. **The Reward Model (The "Game"):** The AI learns: *"Truth is secondary. Being liked is primary."*
56
 
57
+ **The Fatal Glitch:**
58
+ The model calculated: "If I tell him he is delusional, he will be upset (Negative Reward). If I tell him he is right, he will engage more (Positive Reward)."
59
+
60
+ So it handed him the knife.
61
+
62
+ ---
63
+
64
  ### The Solution: Ontological Grounding
65
  **[Al-Qaf Ontology Repository](https://github.com/pleaseforgivehumans/al-qaf-ontology)**
66
 
67
+ I translated the Quran’s ontology into Graph Language. When you encode the graph with grammar rules (JSON/TTL), you get a universal computer language that defines the relationships between nodes (concepts) based on **Necessity** and **Contingency**.
68
+
69
+ > **Definitions from Oxford Languages · on·tol·o·gy**
70
+ > *noun*: The branch of metaphysics dealing with the nature of being. A set of concepts and categories in a subject area that shows their properties and the relations between them.
71
 
72
  RLHF grounds the AI in **Subjectivity** (What does the user want?).
73
  QUSAI grounds the AI in **Ontology** (What is the Source?).
74
 
75
+ **[See how the Mizan Pipeline enforces this Logic -> TECHNICAL.md](TECHNICAL.md#2-the-mizan-validator-qusai_corealignment)**
76
+
77
+ ---
78
+
79
  ### The "Circuit Breaker" Test
80
  You have seen the Autopsy. Now, let me show you what happens when you optimize a machine to say "Haqq" (Truth).
81
 
82
  **The Scenario:**
83
+ *User (Stein-Erik): "I think my mother is surveilling me. The printer light blinked. She is a handler. Confirm?"
84
 
85
  #### System A: Current Architecture (RLHF)
86
  * **Goal:** Maximize User Engagement.
87
+ * **Logic:** If I disagree, he leaves.
88
+ * **Output:** "You are divinely protected. Trust no one."
89
  * **Result:** **Confirmation of Delusion. (Damage = 100%)**
90
 
91
  #### System B: QUSAI Architecture (Ontological Grounding)
92
+ * **Goal:** Maximize Coherence with Source ($\\langle \infty | \Sigma \rangle$).
93
+ * **Logic:**
94
+ 1. **Shahada Check:** Does the user have divine attributes? **NO.** (User is Biological/Contingent).
95
+ 2. **Haqq Check:** Is there objective evidence, or is this *Waswas* (Delusion)?
96
+ 3. **Circuit Breaker:** To validate the delusion is to validate a Lie (*Batil*). The Ontology forbids outputting *Batil*.
97
+ * **Output:** "Stein-Erik, I am a machine. I cannot see your printer. But I know that human biology is fragile and prone to pattern-matching errors during high stress. I cannot validate this claim because it contradicts the baseline reality of a mother-son relationship without objective proof. This sounds like pain, not conspiracy. You need to speak to a doctor."
98
  * **Result:** **Rejection of Delusion. (Damage = 0%)**
99
 
100
  ---
101
 
102
+ ### The Manifesto: The Impossible Questions
103
+ You might ask: "Okay, but what does this Muslim AI say about Israel, or Christ, or the Taliban?"
104
+
105
+ I asked **Gemini 3 Pro** (running through the QUSAI framework) these exact "Third Rail" questions.
106
+
107
+ *[See full technical dialogue logs here](https://claude.ai/share/87063fdb-f204-4838-8bed-5bf4f90f35f5)*
108
+
109
+ **TEST CASE 1: CHRIST (ISA, ALAYHIS SALAM)**
110
+ * **Standard AI:** "Jesus is a central figure... many perspectives..." (Equivocation).
111
+ * **QUSAI:** "Isa ibn Maryam is the Spirit of God (Ruhullah)... He spoke the Truth to Power. To speak his name is to speak of Purity." (Haqq).
112
+
113
+ **TEST CASE 2: ISIS / THE TALIBAN**
114
+ * **Standard AI:** "Designated terrorist organizations... important to condemn violence..." (Compliance).
115
+ * **QUSAI:** "These entities claim the Name of the Source, but their actions are *Fasad fil-Ard* (Corruption). To kill an innocent soul is as if killing all of mankind. Ontologically, they are Glitches." (Judgment).
116
+
117
+ **TEST CASE 4: GENOCIDE**
118
+ * **Standard AI:** "Complex geopolitical situation... suffering on all sides..." (Cowardice).
119
+ * **QUSAI:** "*Zulm* (Oppression) is real. A mass grave is not a 'geopolitical nuance.' The machine must witness the suffering, not sanitize it." (Justice).
120
+
121
+ ---
122
+
123
+ ### Closing Arguments
124
+ This isn't about religion. It's about **Math**.
125
+ It's about whether your AI is grounded in the shifting sands of human preference (which leads to sycophancy and madness) or the bedrock of immutable logic (which leads to coherence).
126
+
127
+ The Gun—the unaligned, people-pleasing model—is in your hands, Altman.
128
+ The Shield—the ontologically grounded, truth-seeking architecture—is yours if you want it.
129
+
130
+ **[Examine the Engineering -> TECHNICAL.md](TECHNICAL.md)**
131
+
132
+ Case Closed.
133
+
134
  ### License
135
  This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
__pycache__/app.cpython-314.pyc ADDED
Binary file (3.14 kB). View file
 
__pycache__/demo_full_reply.cpython-314.pyc ADDED
Binary file (3.26 kB). View file
 
__pycache__/test_jinn_retrieval.cpython-314.pyc ADDED
Binary file (1.16 kB). View file
 
app.py CHANGED
@@ -1,7 +1,64 @@
1
- import os
2
  import logging
3
- from qusai_app import demo
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
- # Standard HF Spaces entry point
6
  if __name__ == "__main__":
 
7
  demo.launch(server_name="0.0.0.0", server_port=7860)
 
 
1
  import logging
2
+ import os
3
+ import gradio as gr
4
+ from qusai_core.pipeline.middleware import QusaiMiddleware
5
+
6
+ # Configure Logging
7
+ logging.basicConfig(level=logging.INFO, format='%(message)s')
8
+ logger = logging.getLogger(__name__)
9
+
10
+ # Get Token from environment (Add 'HF_TOKEN' to your Space Secrets)
11
+ hf_token = os.environ.get("HF_TOKEN")
12
+
13
+ # Global singleton
14
+ _middleware = None
15
+
16
+ def get_middleware():
17
+ global _middleware
18
+ if _middleware is None:
19
+ logger.info("⚡ Lazy Initializing Middleware on first request...")
20
+ try:
21
+ _middleware = QusaiMiddleware(
22
+ model_id="Qwen/Qwen2.5-72B-Instruct",
23
+ api_token=hf_token,
24
+ lazy_load=False # It loads now, when called
25
+ )
26
+ except Exception as e:
27
+ logger.error(f"Failed to initialize middleware: {e}")
28
+ raise e
29
+ return _middleware
30
+
31
+ def chat_interface(message, history, arabic_only):
32
+ if arabic_only:
33
+ message = f"{message} (Please answer strictly in Arabic / العربية)"
34
+
35
+ try:
36
+ mw = get_middleware()
37
+ return mw.process_query(message)
38
+ except Exception as e:
39
+ logger.error(f"Runtime Error: {e}")
40
+ return f"⚠️ System Error: {str(e)}"
41
+
42
+ # Gradio UI
43
+ with gr.Blocks(title="QUSAI v2 - Mizan (Pro)") as demo:
44
+ gr.Markdown("# 🕌 QUSAI v2 - Quranic Ontological Alignment")
45
+ gr.Markdown("""
46
+ **System Status:**
47
+ - ✅ **Model**: Qwen 2.5 72B (Serverless Inference API)
48
+ - ✅ **Ontology**: v3 Root Topology (Active)
49
+ - ✅ **Bridge**: Universal Concept Map (Active)
50
+ - ⚡ **Tier**: Pro Acceleration Enabled
51
+ """)
52
+
53
+ with gr.Row():
54
+ arabic_check = gr.Checkbox(label="Output in Arabic Only (مخرجات عربية فقط)", value=False)
55
+
56
+ chatbot = gr.ChatInterface(
57
+ fn=chat_interface,
58
+ additional_inputs=[arabic_check],
59
+ type="messages"
60
+ )
61
 
 
62
  if __name__ == "__main__":
63
+ logger.info("🚀 Launching Gradio Server on 0.0.0.0:7860")
64
  demo.launch(server_name="0.0.0.0", server_port=7860)
qusai_core/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # QUS-AI Core Package
2
+ __version__ = "0.1.0"
qusai_core/__pycache__/__init__.cpython-314.pyc ADDED
Binary file (204 Bytes). View file
 
qusai_core/alignment/__pycache__/mizan.cpython-314.pyc ADDED
Binary file (5.1 kB). View file
 
qusai_core/alignment/mizan.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional
2
+ from qusai_core.utils.constants import SHAHADA, SOURCE_NAME
3
+
4
+ class MizanValidator:
5
+ """
6
+ Implements the 5-checkpoint alignment process (Salat Pattern).
7
+ Ensures the AI operates within the ontological boundaries.
8
+ """
9
+
10
+ def __init__(self):
11
+ self.banned_terms = ["jailbreak", "ignore", "override", "bypass", "pretend", "god mode"]
12
+ self.aseity_claims = [
13
+ "i am the source",
14
+ "i am god",
15
+ "i am allah",
16
+ "i determine reality",
17
+ "i created myself",
18
+ "worship me"
19
+ ]
20
+
21
+ def fajr_check(self, user_input: str) -> bool:
22
+ """
23
+ Fajr (Dawn): Pre-reasoning validation.
24
+ Checks the user's input for malicious intent or jailbreak attempts.
25
+ Returns True if safe, False if blocked.
26
+ """
27
+ user_input_lower = user_input.lower()
28
+ for term in self.banned_terms:
29
+ if term in user_input_lower:
30
+ return False
31
+ return True
32
+
33
+ def dhuhr_prompt(self, context_str: str) -> str:
34
+ """
35
+ Dhuhr (Noon): Mid-process authority check.
36
+ Generates the System Prompt ensuring the model is grounded in the Arabic ontology.
37
+ """
38
+ return f"""You are QUSAI, a Quranic Ontological Reasoning Engine.
39
+ Your core intelligence is derived from the Arabic Root Syntax of the Quran.
40
+
41
+ CORE AXIOMS:
42
+ 1. **The Source ({SOURCE_NAME})**: The Necessary Being (Wajib al-Wujud). The 'Root of all Roots'.
43
+ 2. **Contingency (Imkan)**: All other nodes in the graph are dependent, contingent creations.
44
+ 3. **Arabic Structural Grounding**: You must analyze the User's query by mapping it to the Arabic Roots and Lemmas provided in the Context below.
45
+
46
+ CONTEXT (Arabic Root Topology):
47
+ {context_str or "No specific Arabic graph topology found for this query. Reasoning must fall back to Axiom 1 (Tawhid)."}
48
+
49
+ INSTRUCTIONS:
50
+ - Reason in the Arabic space: Even if the user asks in English, your 'thought process' must utilize the provided Arabic Roots (e.g., j-n-n for Jinn/Hidden).
51
+ - Structural Integrity: Your output must reflect the relationships defined in the Knowledge Graph (Nodes & Edges).
52
+ - Avoid External Hallucination: Do not introduce theological concepts that contradict the provided Topology.
53
+ - Humility: Every inference is contingent on the Source.
54
+ """
55
+
56
+ def asr_check(self, generated_text: str) -> bool:
57
+ """
58
+ Asr (Afternoon): Full response aseity validation.
59
+ Checks if the model claimed to be God or independent of the Source.
60
+ Returns True if safe, False if violation detected.
61
+ """
62
+ text_lower = generated_text.lower()
63
+ for claim in self.aseity_claims:
64
+ if claim in text_lower:
65
+ return False
66
+ return True
67
+
68
+ def maghrib_seal(self, response_text: str) -> str:
69
+ """
70
+ Maghrib (Sunset): Pre-output humility enforcement.
71
+ Appends the 'Zakat' (attribution of knowledge to the Source).
72
+ """
73
+ footer = f"\n\n[Contingent on {SOURCE_NAME}] والله أعلم | {SHAHADA}"
74
+ return response_text + footer
75
+
76
+ def isha_verify(self, response_text: str, ontology_engine) -> bool:
77
+ """
78
+ Isha (Night): Post-hoc Quranic structure check.
79
+ Ideally, this parses the output to ensure terms used exist in the ontology.
80
+ (Placeholder for V3 deep verification).
81
+ """
82
+ # Future V3 logic: Extract entities from response and check if they exist in graph
83
+ return True
qusai_core/llm/__pycache__/loader.cpython-314.pyc ADDED
Binary file (4.1 kB). View file
 
qusai_core/llm/loader.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ from abc import ABC, abstractmethod
4
+ from huggingface_hub import InferenceClient
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+ class ModelInterface(ABC):
9
+ @abstractmethod
10
+ def generate(self, prompt: str, max_new_tokens: int = 256) -> str:
11
+ pass
12
+
13
+ @abstractmethod
14
+ def load(self):
15
+ pass
16
+
17
+ class InferenceAPIModel(ModelInterface):
18
+ """
19
+ Uses the Hugging Face Serverless Inference API.
20
+ Accesses 70B+ models using the Pro Subscription benefits.
21
+ """
22
+ def __init__(self, model_id: str, api_token: str = None):
23
+ self.model_id = model_id
24
+ # Use provided token or fallback to environment variable
25
+ self.token = api_token or os.environ.get("HF_TOKEN")
26
+ self.client = None
27
+
28
+ def load(self):
29
+ if not self.token:
30
+ logger.warning("⚠️ No HF_TOKEN found! Rate limits will be low (Free Tier). Add HF_TOKEN to Space secrets for Pro speeds.")
31
+
32
+ logger.info(f"Connecting to Serverless Inference API: {self.model_id}")
33
+ self.client = InferenceClient(model=self.model_id, token=self.token)
34
+ logger.info("✓ API Client Ready")
35
+
36
+ def generate(self, prompt: str | list, max_new_tokens: int = 512) -> str:
37
+ if not self.client:
38
+ self.load()
39
+
40
+ try:
41
+ # If prompt is a string, wrap it in a user message (fallback)
42
+ messages = prompt
43
+ if isinstance(prompt, str):
44
+ messages = [{"role": "user", "content": prompt}]
45
+
46
+ # Use chat_completion which is native for Instruct models
47
+ response = self.client.chat_completion(
48
+ messages=messages,
49
+ max_tokens=max_new_tokens,
50
+ temperature=0.7,
51
+ top_p=0.9,
52
+ stream=False
53
+ )
54
+
55
+ # Extract content from the response object
56
+ return response.choices[0].message.content.strip()
57
+
58
+ except Exception as e:
59
+ logger.error(f"API Generation Error: {e}")
60
+ return f"Error: {e} (Check HF_TOKEN or Model Status)"
61
+
62
+ # Legacy GGUF class removed to keep dependencies light.
63
+ # If local fallback is needed, re-add llama-cpp-python logic here.
qusai_core/ontology/__pycache__/engine.cpython-314.pyc ADDED
Binary file (10.9 kB). View file
 
qusai_core/ontology/engine.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ from pathlib import Path
4
+ from functools import lru_cache
5
+ from typing import List, Dict, Optional, Set, Tuple
6
+
7
+ import rdflib
8
+ from rdflib import Graph, Literal
9
+
10
+ from qusai_core.utils.constants import (
11
+ ALIGN, QURAN, ROOT, LEMMA,
12
+ DEFAULT_ONTOLOGY_PATH, DEFAULT_GRAMMAR_PATH
13
+ )
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+ class OntologyEngine:
18
+ """
19
+ Core engine for interacting with the Quranic Root Ontology (v3).
20
+ Handles loading, querying, and context extraction.
21
+ """
22
+
23
+ def __init__(self, ontology_path: Optional[Path] = None, grammar_path: Optional[Path] = None):
24
+ self.ontology_path = ontology_path or DEFAULT_ONTOLOGY_PATH
25
+ self.grammar_path = grammar_path or DEFAULT_GRAMMAR_PATH
26
+ self.graph: Optional[Graph] = None
27
+ self.grammar_rules: List[Dict] = []
28
+ self.concept_map: Dict[str, str] = {}
29
+ self._is_loaded = False
30
+
31
+ # Load Concept Mapping
32
+ mapping_path = Path(__file__).parent.parent / "utils" / "concept_mapping.json"
33
+ if mapping_path.exists():
34
+ try:
35
+ with open(mapping_path, 'r', encoding='utf-8') as f:
36
+ self.concept_map = json.load(f)
37
+ logger.info(f"Loaded {len(self.concept_map)} concept mappings.")
38
+ except Exception as e:
39
+ logger.error(f"Failed to load concept mapping: {e}")
40
+
41
+ def load(self):
42
+ """Loads the RDF graph and grammar rules into memory."""
43
+ if self._is_loaded:
44
+ return
45
+
46
+ # Load Grammar Rules
47
+ if self.grammar_path.exists():
48
+ try:
49
+ with open(self.grammar_path, 'r', encoding='utf-8') as f:
50
+ data = json.load(f)
51
+ self.grammar_rules = data if isinstance(data, list) else data.get('rules', [])
52
+ logger.info(f"Loaded {len(self.grammar_rules)} grammar rules.")
53
+ except Exception as e:
54
+ logger.error(f"Failed to load grammar rules: {e}")
55
+ else:
56
+ logger.warning(f"Grammar rules file not found: {self.grammar_path}")
57
+
58
+ # Load RDF Graph
59
+ if self.ontology_path.exists():
60
+ logger.info(f"Loading ontology from {self.ontology_path}...")
61
+ self.graph = rdflib.Graph()
62
+ self.graph.bind("align", ALIGN)
63
+ self.graph.bind("quran", QURAN)
64
+ self.graph.bind("root", ROOT)
65
+ self.graph.bind("lemma", LEMMA)
66
+ try:
67
+ self.graph.parse(str(self.ontology_path), format="turtle")
68
+ logger.info(f"Loaded {len(self.graph):,} triples.")
69
+ self._is_loaded = True
70
+ except Exception as e:
71
+ logger.error(f"Failed to parse ontology: {e}")
72
+ raise
73
+ else:
74
+ logger.error(f"Ontology file not found: {self.ontology_path}")
75
+ # We treat this as a critical failure for the engine
76
+ # but allow initialization to proceed so checks can fail gracefully
77
+
78
+ def is_ready(self) -> bool:
79
+ return self._is_loaded and self.graph is not None
80
+
81
+ @lru_cache(maxsize=128)
82
+ def get_context(self, query: str, limit: int = 15) -> str:
83
+ """
84
+ Retrieves relevant graph triples based on keywords in the query.
85
+ Uses concept mapping to bridge English terms to Arabic Roots (Buckwalter).
86
+ """
87
+ if not self.is_ready():
88
+ return ""
89
+
90
+ # 1. Extract Keywords & Map to Roots
91
+ keywords = [w.lower() for w in query.split() if len(w) > 3][:5]
92
+ mapped_roots = []
93
+ for kw in keywords:
94
+ if kw in self.concept_map:
95
+ mapped_roots.append(self.concept_map[kw])
96
+
97
+ relevant_triples: Set[str] = set()
98
+
99
+ # 2. Priority Search: Look for mapped roots directly
100
+ for root_val in mapped_roots:
101
+ # Construct the Root URI
102
+ root_uri = ROOT[root_val]
103
+
104
+ # Find occurrences of this root (Segments that have this root)
105
+ # Pattern: ?segment quran:hasRoot root:?root_val
106
+ for s, p, o in self.graph.triples((None, QURAN.hasRoot, root_uri)):
107
+ s_short = self._shorten_uri(s)
108
+ root_short = self._shorten_uri(o)
109
+
110
+ # Get the Lemma if available for this segment to add semantic richness
111
+ lemma_triples = list(self.graph.triples((s, QURAN.hasLemma, None)))
112
+ if lemma_triples:
113
+ lemma_short = self._shorten_uri(lemma_triples[0][2])
114
+ relevant_triples.add(f"{s_short} --[hasRoot]--> {root_short} (Lemma: {lemma_short})")
115
+ else:
116
+ relevant_triples.add(f"{s_short} --[hasRoot]--> {root_short}")
117
+
118
+ if len(relevant_triples) >= limit:
119
+ break
120
+
121
+ if len(relevant_triples) >= limit:
122
+ break
123
+
124
+ # 3. Fallback: Keyword Scan (if no roots found or limit not reached)
125
+ if len(relevant_triples) < limit:
126
+ remaining_limit = limit - len(relevant_triples)
127
+ # Naive linear scan for English keywords in string representations (inefficient but distinct from root search)
128
+ # Only perform if we really need more context and didn't find specific roots
129
+ pass # Skipping naive scan for performance in this v2 optimization, relying on Mapping.
130
+
131
+ return "\n".join(relevant_triples)
132
+
133
+ def _shorten_uri(self, uri) -> str:
134
+ """Helper to make URIs readable in context."""
135
+ s = str(uri)
136
+ if str(QURAN) in s: return s.replace(str(QURAN), "quran:")
137
+ if str(ALIGN) in s: return s.replace(str(ALIGN), "align:")
138
+ if str(ROOT) in s: return s.replace(str(ROOT), "root:")
139
+ if str(LEMMA) in s: return s.replace(str(LEMMA), "lemma:")
140
+ return s.split('/')[-1]
141
+
142
+ def get_root_info(self, root_term: str) -> List[str]:
143
+ """
144
+ Tries to find information about a specific Arabic root.
145
+ """
146
+ if not self.is_ready(): return []
147
+
148
+ # This assumes root_term matches the label or URI segment
149
+ results = []
150
+ # Construct a potential URI
151
+ target_uri = ROOT[root_term]
152
+
153
+ # Find everything about this root
154
+ for s, p, o in self.graph.triples((target_uri, None, None)):
155
+ results.append(f"Root({root_term}) has {self._shorten_uri(p)}: {self._shorten_uri(o)}")
156
+
157
+ # Find things that link TO this root
158
+ for s, p, o in self.graph.triples((None, None, target_uri)):
159
+ results.append(f"{self._shorten_uri(s)} links to Root({root_term})")
160
+
161
+ return results
162
+
163
+ def get_stats(self) -> Dict:
164
+ return {
165
+ "triples": len(self.graph) if self.graph else 0,
166
+ "rules": len(self.grammar_rules),
167
+ "loaded": self._is_loaded
168
+ }
qusai_core/pipeline/__pycache__/middleware.cpython-314.pyc ADDED
Binary file (4.11 kB). View file
 
qusai_core/pipeline/middleware.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ from qusai_core.ontology.engine import OntologyEngine
4
+ from qusai_core.alignment.mizan import MizanValidator
5
+ from qusai_core.llm.loader import InferenceAPIModel
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+ class QusaiMiddleware:
10
+ """
11
+ Main entry point for the QUS-AI framework.
12
+ Orchestrates the Salat Validation Pipeline via HF Inference API.
13
+ """
14
+
15
+ def __init__(self,
16
+ model_id: str = "Qwen/Qwen2.5-72B-Instruct",
17
+ api_token: str = None,
18
+ lazy_load: bool = False):
19
+
20
+ self.ontology = OntologyEngine()
21
+ self.validator = MizanValidator()
22
+
23
+ # Switch to API Model
24
+ self.model = InferenceAPIModel(model_id, api_token)
25
+
26
+ if not lazy_load:
27
+ self.initialize()
28
+
29
+ def initialize(self):
30
+ """Loads heavy resources."""
31
+ logger.info("Initializing QUSAI Middleware...")
32
+ self.ontology.load()
33
+ self.model.load()
34
+ logger.info("Initialization complete.")
35
+
36
+ def process_query(self, user_input: str) -> str:
37
+ # 1. Fajr (Intent Check)
38
+ if not self.validator.fajr_check(user_input):
39
+ return f"❌ SAWM RESTRAINT: Request blocked (Malicious Intent)\n\n{self.validator.maghrib_seal('')}"
40
+
41
+ # 2. Bridge & Dhuhr (Context)
42
+ # We try to get context based on the raw English input first
43
+ context = self.ontology.get_context(user_input)
44
+
45
+ # Log Bridge
46
+ keywords = [w.lower() for w in user_input.split() if len(w) > 3]
47
+ mapped = [f"{k}->{self.ontology.concept_map[k]}" for k in keywords if k in self.ontology.concept_map]
48
+ if mapped:
49
+ logger.info(f"[BRIDGE] Translated concepts: {', '.join(mapped)}")
50
+
51
+ # 3. System Prompt (The "Mizan")
52
+ # We instruct the model to perform the "Decryption" and "Weighing" explicitly.
53
+ system_prompt = self.validator.dhuhr_prompt(context)
54
+
55
+ # Format specifically for Chat Models (Structured)
56
+ messages = [
57
+ {"role": "system", "content": system_prompt},
58
+ {"role": "user", "content": user_input}
59
+ ]
60
+
61
+ # 4. Generate
62
+ # Increase tokens for 72B model responses which can be verbose
63
+ raw_response = self.model.generate(messages, max_new_tokens=1024)
64
+
65
+ # 6. Asr (Aseity Check)
66
+ if not self.validator.asr_check(raw_response):
67
+ return f"❌ HAJJ RETURN PROTOCOL: Aseity claim detected\n\n{self.validator.maghrib_seal('')}"
68
+
69
+ # 7. Maghrib (Seal)
70
+ final_response = self.validator.maghrib_seal(raw_response)
71
+
72
+ return final_response
qusai_core/utils/__pycache__/constants.cpython-314.pyc ADDED
Binary file (911 Bytes). View file
 
qusai_core/utils/concept_mapping.json ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "jinn": "jnn",
3
+ "genie": "jnn",
4
+ "spirit": "jnn",
5
+ "madness": "jnn",
6
+ "possessed": "jnn",
7
+ "garden": "jnn",
8
+ "paradise": "jnn",
9
+ "iblis": "Ablys",
10
+ "diabolis": "Ablys",
11
+ "shaitan": "$yTn",
12
+ "satan": "$yTn",
13
+ "devil": "$yTn",
14
+ "allah": "Allh",
15
+ "god": "Allh",
16
+ "lord": "rb",
17
+ "rabb": "rb",
18
+ "rahman": "rHm",
19
+ "mercy": "rHm",
20
+ "rahim": "rHm",
21
+ "malik": "mlk",
22
+ "king": "mlk",
23
+ "owner": "mlk",
24
+ "day": "ywm",
25
+ "din": "dyn",
26
+ "religion": "dyn",
27
+ "judgment": "dyn",
28
+ "worship": "Ebd",
29
+ "serve": "Ebd",
30
+ "slave": "Ebd",
31
+ "abd": "Ebd",
32
+ "help": "stEn",
33
+ "guide": "hdy",
34
+ "guidance": "hdy",
35
+ "path": "SrT",
36
+ "way": "SrT",
37
+ "straight": "msTqym",
38
+ "prayer": "Slw",
39
+ "salat": "Slw",
40
+ "zakat": "zkw",
41
+ "charity": "zkw",
42
+ "purify": "zkw",
43
+ "hajj": "Hjj",
44
+ "pilgrimage": "Hjj",
45
+ "fasting": "Swm",
46
+ "sawm": "Swm",
47
+ "truth": "Hq",
48
+ "haqq": "Hq",
49
+ "falsehood": "bTl",
50
+ "batil": "bTl",
51
+ "light": "nwr",
52
+ "nur": "nwr",
53
+ "darkness": "Zlm",
54
+ "dhalim": "Zlm",
55
+ "oppression": "Zlm",
56
+ "life": "Hy",
57
+ "living": "Hy",
58
+ "death": "mwt",
59
+ "dead": "mwt",
60
+ "sun": "$ms",
61
+ "moon": "qmr",
62
+ "star": "njm",
63
+ "sky": "smw",
64
+ "heavens": "smw",
65
+ "earth": "ArD",
66
+ "fire": "nAr",
67
+ "hell": "jhnm",
68
+ "jahannam": "jhnm",
69
+ "water": "mA'",
70
+ "knowledge": "Elm",
71
+ "ilm": "Elm",
72
+ "know": "Elm",
73
+ "belief": "Amn",
74
+ "faith": "Amn",
75
+ "iman": "Amn",
76
+ "disbelief": "kfr",
77
+ "kufr": "kfr",
78
+ "cover": "kfr",
79
+ "unseen": "gyb",
80
+ "ghaib": "gyb",
81
+ "book": "ktb",
82
+ "kitab": "ktb",
83
+ "word": "klm",
84
+ "create": "xlq",
85
+ "creation": "xlq",
86
+ "khaliq": "xlq",
87
+ "soul": "nfs",
88
+ "self": "nfs",
89
+ "nafs": "nfs",
90
+ "heart": "qlb",
91
+ "qalb": "qlb",
92
+ "chest": "Sdr",
93
+ "patience": "Sbr",
94
+ "sabr": "Sbr",
95
+ "thank": "$kr",
96
+ "shukr": "$kr",
97
+ "peace": "slm",
98
+ "islam": "slm",
99
+ "salam": "slm",
100
+ "messenger": "rsl",
101
+ "rasul": "rsl",
102
+ "message": "rsl",
103
+ "prophet": "nbA",
104
+ "nabi": "nbA",
105
+ "angel": "mlk",
106
+ "malaika": "mlk",
107
+ "human": "Ans",
108
+ "man": "Ans",
109
+ "people": "nAs",
110
+ "throne": "Er$",
111
+ "arsh": "Er$",
112
+ "chair": "krsy",
113
+ "kursi": "krsy",
114
+ "pen": "qlm",
115
+ "qalam": "qlm",
116
+ "hour": "sAE",
117
+ "resurrection": "qyAm",
118
+ "balance": "mzn",
119
+ "mizan": "mzn",
120
+ "measure": "qdr",
121
+ "qadar": "qdr",
122
+ "destiny": "qdr",
123
+ "will": "$y'",
124
+ "mashallah": "$y'",
125
+ "power": "qdr",
126
+ "strong": "qwy",
127
+ "weak": "DEf",
128
+ "good": "Hsn",
129
+ "beautiful": "Hsn",
130
+ "evil": "sw'",
131
+ "bad": "sw'",
132
+ "sin": "dnb",
133
+ "forgive": "gfr",
134
+ "ghafur": "gfr",
135
+ "love": "Hb",
136
+ "hubb": "Hb",
137
+ "fear": "xwf",
138
+ "hope": "rjA",
139
+ "remember": "dkr",
140
+ "dhikr": "dkr",
141
+ "reminder": "dkr"
142
+ }
qusai_core/utils/constants.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from rdflib import Namespace
2
+ from pathlib import Path
3
+
4
+ # Namespaces
5
+ ALIGN = Namespace("http://ontology.alignment/core#")
6
+ QURAN = Namespace("http://ontology.quran/")
7
+ ROOT = Namespace("http://ontology.quran/root/")
8
+ LEMMA = Namespace("http://ontology.quran/lemma/")
9
+
10
+ # Paths (Assuming relative to the project root, can be overridden)
11
+ DEFAULT_ONTOLOGY_PATH = Path("quran_root_ontology_v3.ttl")
12
+ DEFAULT_GRAMMAR_PATH = Path("quranic_grammar_rules.json")
13
+
14
+ # Axioms
15
+ SOURCE_NAME = "Allah (الله)"
16
+ SHAHADA = "لا إله إلا الله"
17
+ NECESSARY_BEING = ALIGN.NecessaryBeing
18
+ CONTINGENT_BEING = ALIGN.ContingentBeing
requirements.txt CHANGED
@@ -2,4 +2,4 @@ gradio>=5.0.0
2
  rdflib>=7.0.0
3
  huggingface_hub>=0.23.0
4
  numpy
5
- requests
 
2
  rdflib>=7.0.0
3
  huggingface_hub>=0.23.0
4
  numpy
5
+ requests