""" Generate an executive, publication-grade Architecture & Workflow Specification PDF for Sahih Islam. Uses WeasyPrint to render clean HTML5/CSS3 into a high-resolution PDF. """ import os import sys sys.stdout.reconfigure(encoding='utf-8') from pathlib import Path import weasyprint OUTPUT_PDF = Path("D:/Project-x/SahihIslam_Architecture_Workflow.pdf") HTML_CONTENT = """
Sahih Islam is engineered as a high-precision, low-latency, distributed Islamic intelligence ecosystem. It integrates an offline-capable cross-platform mobile client with an asynchronous backend, distributed object storage, in-memory caching, double-entry financial ledger accounting, and a pure cloud high-performance semantic search and RAG engine.
Every tier in the stack serves a strictly defined, non-overlapping architectural purpose:
| Technology | Role in Stack | Actual Real-World Function & Responsibilities |
|---|---|---|
| FastAPI Backend Gateway |
Asynchronous Python REST & SSE Server |
• Routes all client requests (auth, hadith, quran, payments, ads, masjids). • Serves non-blocking Server-Sent Events (SSE) and NDJSON for real-time AI token streaming. • Orchestrates cloud neural inference bridges (BGE-M3 bi-encoder + cross-encoder reranker). • Validates JWTs, processes Razorpay/Google Play webhooks, orchestrates background jobs. |
| MongoDB Atlas Primary Database |
Multi-Collection Document & Vector Store |
• Stores structured relational-like data: 24,356 Hadiths, 114 Surahs, 6,236 Ayahs, Users. • Runs Atlas Vector Search ( $vectorSearch) using 1024-dim HNSW cosine index.• Stores double-entry financial ledgers (Wallets, Transactions, Invoices). • Geospatial queries for Masjids (2dsphere index for nearby prayer facilities). |
| Cloudflare R2 Object Storage |
S3-Compatible Zero-Egress Storage & Edge CDN |
• Stores large binary assets outside MongoDB to prevent database bloat. • Houses complete 114 Surah recitations (Mishary Alafasy high-quality audio files). • Hosts Urdu & English Tafseer audio libraries (Dr. Israr Ahmed, Maududi). • Distributes 8 multi-language Quran translation bundles (EN, UR, HI, FR, ES, ID, TR, BN). • Caches and streams 16-line Mushaf Hafizi PDFs and advertiser media creatives globally with zero egress bandwidth fees. |
| Redis / Upstash In-Memory Cache |
Sub-millisecond State & Distributed Cache |
• Caches repetitive, read-heavy data (Prayer calculation parameters, daily Hadith pool). • Rate limiting & IP throttling to safeguard expensive AI vector inference endpoints. • Distributed locks for atomic wallet debit operations (prevents race-condition double spends). • Caches active user tokens and real-time ad impression frequency counters. |
| Flutter Client Frontend Application |
Multi-Platform UI (Android, iOS, Web) |
• Renders responsive interfaces for Quran, Hadith, Tasbeeh, Ads Marketplace, and Masjid Finder. • Offline-first capabilities: Local SQLite/Hive caches recent Quran, Tasbeeh counts, and settings. • Executes high-precision astronomical prayer calculation algorithms locally on device. • Native audio player engine with background playback, seek bars, and auto-scrolling Ayah markers. |
| SuperAdmin Control Plane |
Enterprise Operations & Moderation Portal |
• Real-time financial telemetry (Wallet flows, platform earnings, payment gateway health). • Ad review pipeline (Approve, reject, or pause advertisers' commercial campaigns). • Mufti verification, Masjid claim dispute resolution, and audit log inspection. |
Unlike traditional synchronous frameworks (e.g. Django, Flask), FastAPI runs on top of Starlette
and Uvicorn utilizing Python's asynchronous event loop (asyncio).
In Sahih Islam, every database call uses Motor (non-blocking async MongoDB driver) so a single server process can sustain thousands of concurrent connections without thread exhaustion.
Key Internal Engines inside FastAPI:
/api/hadith/ask), FastAPI streams AI responses word-by-word as NDJSON chunks. This eliminates user perceived latency.BackgroundTasks so the HTTP response returns immediately.MongoDB acts as the permanent system of record. It is structured into high-performance collections with targeted indexes:
hadiths (24,356 items): Contains the Arabic Matn, English translation, Urdu translation, Sanad (narrator chain), grade, and pre-computed 1024-dimensional embedding_1024 vectors.quran & quran_verses (114 Surahs / 6,236 Ayahs): Verse-level records indexed by Surah number and Ayah number with linguistic tafseer references.wallets & transactions: Implements transactional double-entry accounting. Wallets store available balance, locked balance, and currency. Every credit or debit logs an immutable transaction record.ads & ad_analytics: Stores advertiser campaigns, targeting parameters, daily budget, remaining wallet balance, and real-time impression counts.vector_memory: Stores past user conversations embedded into vector space so the AI can recall previous discussions in follow-up queries.Storing gigabytes of audio and PDF files inside MongoDB would degrade database performance, bloat backups, and skyrocket RAM costs. Sahih Islam solves this by offloading all static media to Cloudflare R2:
/surah_audio/: 114 recitations in 128kbps/64kbps MP3.
/tafseer_audio/: Thousands of detailed Tafseer lectures.
/quran_translations/: Clean JSON translation files across 8 major world languages.
/mushaf_pdfs/: 16-line and 15-line high-resolution Mushaf pages.
Redis operates entirely in RAM. It handles functions where a disk-based database would be too slow:
DECRBY) to prevent balance underflow or race conditions.How the system processes an Islamic question through neural retrieval, verification, and streaming:
/api/hadith/ask. FastAPI analyzes the intent using a local Intent Classifier.
StreamingResponse(media_type="application/x-ndjson").
The Flutter UI paints the words in real time with clickable source badges, audio player controls, and transliterations.
How the system serves ads, protects advertiser budgets, and handles usage-based wallet deduction:
wallets covers the campaign total.
If balance is insufficient, creation is rejected with an instant top-up modal.
Flutter requests translations for a Surah.
Instead of burdening MongoDB with repetitive full-text pulls, requests are routed directly to
Cloudflare R2 (/quran_translations/{lang}.json).
Cloudflare's CDN caches the response at the edge, serving 114 Surahs across 8 languages in < 30ms.
When a user taps play on Ayah recitation or Tafseer, Flutter connects to Cloudflare R2's streaming endpoints.
The native just_audio plugin handles chunked buffering, background lock-screen notifications,
and emits Ayah completion events to automatically highlight the current verse.