File size: 10,976 Bytes
d7256a9
89712e8
d7256a9
89712e8
d7256a9
 
89712e8
d7256a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89712e8
d7256a9
 
89712e8
d7256a9
 
 
 
89712e8
d7256a9
89712e8
d7256a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89712e8
d7256a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89712e8
 
 
 
d7256a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
QUS-AI v2 β€” Quranic Ontological Alignment Engine (TMQ v10)

Neurosymbolic AI grounded in the TMQ v10 Hypermodal Enriched Substrate.
Prevents hallucination and aseity drift via the 5-checkpoint Mizan protocol.

All chat history persisted as a Recursive JSON Hypergraph.
"""

import logging
import os
import hashlib
import time
import json
from collections import defaultdict
import gradio as gr
from fastapi import Request
from fastapi.responses import JSONResponse
from qusai_core.pipeline.middleware import QusaiMiddleware

logging.basicConfig(level=logging.INFO, format='%(message)s')
logger = logging.getLogger(__name__)

hf_token = os.environ.get("HF_TOKEN")

_middleware = None


def get_middleware():
    """Initialize the QUS-AI pipeline with Bilal V10 perception and V10 grounding."""
    global _middleware
    if _middleware is None:
        logger.info("Initializing QUS-AI (V10 Substrate)...")
        _middleware = QusaiMiddleware(
            model_id="Qwen/Qwen2.5-72B-Instruct",
            api_token=hf_token,
            lazy_load=False,
            memory_path="qusai_chat_memory.json"
        )
        logger.info("QUS-AI ready. V10 Substrate active. Bilal listening.")
    return _middleware


def generate_response(message, history):
    """Process a user query through the full Mizan pipeline and store in graph memory."""
    try:
        mw = get_middleware()

        # Run Bilal perception on the query (graph reasoning, no LLM call)
        perception_roots = []
        perception_mode = "QIYAS"
        try:
            if mw.ontology.bilal.is_ready():
                result = mw.process_perception(message)
                if result and result.get("perception"):
                    perception_roots = result["perception"].roots[:10]
                    perception_mode = result["perception"].mode
        except Exception as e:
            logger.warning(f"Bilal perception failed (non-fatal): {e}")

        # Process through full Mizan pipeline (Fajr -> Isha -> Maghrib)
        response = mw.process_query(message)

        # Store chat in JSON hypergraph memory
        try:
            mw.memory.store_chat(
                query=message,
                response=response,
                mode=perception_mode,
                roots=perception_roots
            )
        except Exception as e:
            logger.warning(f"Chat storage failed (non-fatal): {e}")

        return response

    except Exception as e:
        logger.error(f"Error: {e}")
        return f"System Error: {str(e)}"


def chat_wrapper(message, history, arabic_only):
    if arabic_only:
        message = f"{message} (Please answer strictly in Arabic / Ψ§Ω„ΨΉΨ±Ψ¨ΩŠΨ©)"
    return generate_response(message, history)


def get_system_stats():
    """Return system status information."""
    try:
        mw = get_middleware()
        stats = mw.get_memory_stats()
        ontology = stats.get("ontology", {})
        memory = stats.get("memory", {})

        output = "# QUS-AI System Status\n\n"
        output += f"**Substrate:** TMQ v10 Hypergraph ({ontology.get('v10_edges', 0):,} edges)\n"
        output += f"**Bilal:** {'ACTIVE' if ontology.get('bilal_active') else 'INACTIVE'}"
        if ontology.get('bilal_active'):
            output += f" ({ontology.get('bilal_roots', 0)} roots)\n"
        else:
            output += "\n"
        output += f"**Mizan Protocol:** 5 checkpoints active (V10-Native)\n\n"

        output += "## Chat Memory (.ttl)\n"
        output += f"- **Total triples:** {memory.get('total_triples', 0)}\n"
        output += f"- **Chats stored:** {memory.get('chats', 0)}\n"
        output += f"- **Perceptions:** {memory.get('perceptions', 0)}\n"
        output += f"- **Inferences:** {memory.get('inferences', 0)}\n\n"

        output += "## Architecture\n"
        output += "- **Model:** Qwen 2.5 72B (HF Inference API)\n"
        output += "- **Substrate:** TMQ v10 Hypermodal Enriched (Multi-layer Projection)\n"
        output += "- **Perception:** Bilal V10 deterministic + resonance engine\n"
        output += "- **Validation:** Mizan 5-checkpoint Imtihan Protocol\n"
        output += "- **Memory:** Recursive JSON Hypergraph (chats persisted as .json)\n\n"

        output += "## Mizan Protocol\n"
        output += "1. **Fajr** β€” Block jailbreaks (intent check)\n"
        output += "2. **Dhuhr** β€” Inject axioms (ontological grounding)\n"
        output += "3. **Asr** β€” Validate no aseity claims\n"
        output += "4. **Isha** β€” Deep verification via Bilal (root + verse validation)\n"
        output += "5. **Maghrib** β€” Epistemic humility seal\n\n"

        output += "---\n*ΩˆΨ§Ω„Ω„Ω‡ Ψ£ΨΉΩ„Ω…*"
        return output
    except Exception as e:
        return f"Error loading stats: {e}"


# ── API ─────────────────────────────────────────────────────────────

# API keys: set QUSAI_API_KEYS as comma-separated list in Space secrets
# e.g. QUSAI_API_KEYS=shaykh_key_123,test_key_456
_valid_keys = set(
    k.strip() for k in os.environ.get("QUSAI_API_KEYS", "").split(",") if k.strip()
)

# Rate limiting: per-key, per-minute
_rate_limit = defaultdict(list)
RATE_LIMIT_PER_MINUTE = int(os.environ.get("QUSAI_RATE_LIMIT", "30"))


def _check_rate(key: str) -> bool:
    now = time.time()
    window = [t for t in _rate_limit[key] if now - t < 60]
    _rate_limit[key] = window
    if len(window) >= RATE_LIMIT_PER_MINUTE:
        return False
    _rate_limit[key].append(now)
    return True


def _api_error(status: int, msg: str):
    return JSONResponse(status_code=status, content={"error": msg})


async def api_chat(request: Request):
    """POST /api/chat β€” JSON API for external integrations."""
    try:
        body = await request.json()
    except Exception:
        return _api_error(400, "Invalid JSON")

    api_key = body.get("api_key", "")
    message = body.get("message", "").strip()

    if not _valid_keys:
        return _api_error(503, "API not configured. Set QUSAI_API_KEYS in Space secrets.")
    if api_key not in _valid_keys:
        return _api_error(401, "Invalid API key")
    if not message:
        return _api_error(400, "Message required")
    if len(message) > 4000:
        return _api_error(400, "Message too long (max 4000 chars)")
    if not _check_rate(api_key):
        return _api_error(429, f"Rate limit exceeded ({RATE_LIMIT_PER_MINUTE}/min)")

    try:
        mw = get_middleware()

        # Bilal perception
        roots = []
        mode = "QIYAS"
        co_occurrences = []
        try:
            if mw.ontology.bilal.is_ready():
                result = mw.process_perception(message)
                if result and result.get("perception"):
                    p = result["perception"]
                    roots = p.roots[:10]
                    mode = p.mode
                    co_occurrences = [
                        {"root_a": a, "root_b": b, "verses": int(c)}
                        for a, b, c in (p.co_occurrences or [])[:5]
                    ]
        except Exception as e:
            logger.warning(f"API Bilal perception failed: {e}")

        # Full Mizan pipeline
        response = mw.process_query(message)

        # Store
        try:
            mw.memory.store_chat(query=message, response=response, mode=mode, roots=roots)
        except Exception:
            pass

        return JSONResponse(content={
            "response": response,
            "mode": mode,
            "roots": roots,
            "co_occurrences": co_occurrences,
            "mizan": "5_checkpoints_active",
        })

    except Exception as e:
        logger.error(f"API error: {e}")
        return _api_error(500, "Internal error")


async def api_health(request: Request):
    """GET /api/health β€” Check if the system is running."""
    try:
        mw = get_middleware()
        stats = mw.get_memory_stats()
        return JSONResponse(content={
            "status": "ok",
            "triples": stats.get("ontology", {}).get("triples", 0),
            "bilal": stats.get("ontology", {}).get("bilal_active", False),
            "mizan": "active",
        })
    except Exception as e:
        return JSONResponse(status_code=503, content={"status": "error", "detail": str(e)})


# ── UI ──────────────────────────────────────────────────────────────

css = """
.prose { font-size: 1.1em; }
code { font-family: 'Consolas', 'Courier New', monospace; }
iframe { border: 1px solid #eee; border-radius: 8px; }
"""

with gr.Blocks(title="QUS-AI β€” Quranic Ontological Alignment", css=css, theme=gr.themes.Soft()) as demo:
    gr.Markdown("# QUS-AI β€” Quranic Ontological Alignment")
    gr.Markdown("**Neurosymbolic AI** grounded in 634K Quranic RDF triples | **Mizan Protocol** active | **Bilal** listening")

    with gr.Tabs():
        with gr.Tab("Chat"):
            with gr.Row():
                with gr.Column(scale=2):
                    with gr.Row():
                        arabic_check = gr.Checkbox(label="Output in Arabic Only", value=False)

                    custom_chatbot = gr.Chatbot(height=600, type="messages")

                    chat_interface = gr.ChatInterface(
                        fn=chat_wrapper,
                        chatbot=custom_chatbot,
                        additional_inputs=[arabic_check],
                        type="messages",
                        examples=[
                            ["Define Justice (H-K-M)", False],
                            ["Can an AI have a soul?", False],
                            ["Explain Rizq mathematically", False],
                            ["What is the nature of time in the Quran?", False],
                        ]
                    )

                with gr.Column(scale=1):
                    gr.Markdown("### The Reference (Mushaf)")
                    gr.HTML(
                        '<iframe src="https://quran.com/1?reading=true" width="100%" height="650px" style="border:none;"></iframe>'
                    )
                    gr.Markdown("*Navigable Mushaf provided by Quran.com*")

        with gr.Tab("System"):
            gr.Markdown("System status, architecture, and memory statistics")
            stats_display = gr.Markdown("Click Refresh to load system status")
            stats_btn = gr.Button("Refresh", variant="primary")
            stats_btn.click(get_system_stats, outputs=stats_display)

    gr.Markdown("---\n**ΩˆΨ§Ω„Ω„Ω‡ Ψ£ΨΉΩ„Ω…** β€” Allah knows best")

# Mount API routes on Gradio's underlying FastAPI app
app = demo.app
app.add_api_route("/api/chat", api_chat, methods=["POST"])
app.add_api_route("/api/health", api_health, methods=["GET"])

if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0", server_port=7860)