QOSAI / app.py
QalamABD's picture
Upload 50 files
89712e8 verified
Raw History Blame Contribute Delete
11 kB
"""
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)