Upload folder using huggingface_hub
Browse files- .dockerignore +0 -1
- .env.example +15 -2
- .gitattributes +1 -2
- ARCHITECTURE.md +196 -97
- app/__init__.py +1 -0
- app/analysis.py +322 -0
- app/arabic_nlp.py +98 -0
- app/cache.py +49 -0
- app/config.py +67 -0
- app/llm.py +194 -0
- app/models.py +174 -0
- app/prompts.py +199 -0
- app/routers/__init__.py +1 -0
- app/routers/chat.py +163 -0
- app/routers/hadith.py +212 -0
- app/routers/ops.py +69 -0
- app/routers/quran.py +149 -0
- app/search.py +287 -0
- app/state.py +235 -0
- main.py +32 -1446
- requirements.txt +15 -12
.dockerignore
CHANGED
|
@@ -4,7 +4,6 @@ __pycache__
|
|
| 4 |
.DS_Store
|
| 5 |
.vscode
|
| 6 |
.git
|
| 7 |
-
.docker
|
| 8 |
QModel.index
|
| 9 |
metadata.json
|
| 10 |
data/
|
|
|
|
| 4 |
.DS_Store
|
| 5 |
.vscode
|
| 6 |
.git
|
|
|
|
| 7 |
QModel.index
|
| 8 |
metadata.json
|
| 9 |
data/
|
.env.example
CHANGED
|
@@ -3,7 +3,7 @@
|
|
| 3 |
# Copy this to .env and update values for your environment
|
| 4 |
|
| 5 |
# LLM Backend Selection
|
| 6 |
-
# Options: "hf" (HuggingFace) or "
|
| 7 |
LLM_BACKEND=ollama
|
| 8 |
|
| 9 |
# ─────────────────────────────────────────────────────────────────────
|
|
@@ -25,7 +25,20 @@ OLLAMA_MODEL=minimax-m2.7:cloud
|
|
| 25 |
# - meta-llama/Llama-2-13b-chat-hf
|
| 26 |
|
| 27 |
# ─────────────────────────────────────────────────────────────────────
|
| 28 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
# ─────────────────────────────────────────────────────────────────────
|
| 30 |
EMBED_MODEL=intfloat/multilingual-e5-large
|
| 31 |
|
|
|
|
| 3 |
# Copy this to .env and update values for your environment
|
| 4 |
|
| 5 |
# LLM Backend Selection
|
| 6 |
+
# Options: "ollama", "hf" (HuggingFace), "gguf" (local GGUF file), or "lmstudio"
|
| 7 |
LLM_BACKEND=ollama
|
| 8 |
|
| 9 |
# ─────────────────────────────────────────────────────────────────────
|
|
|
|
| 25 |
# - meta-llama/Llama-2-13b-chat-hf
|
| 26 |
|
| 27 |
# ─────────────────────────────────────────────────────────────────────
|
| 28 |
+
# GGUF BACKEND (if LLM_BACKEND=gguf)
|
| 29 |
+
# ─────────────────────────────────────────────────────────────────────
|
| 30 |
+
# GGUF_MODEL_PATH=./models/qwen2-7b-instruct-q4_k_m.gguf
|
| 31 |
+
# GGUF_N_CTX=4096 # Context window size
|
| 32 |
+
# GGUF_N_GPU_LAYERS=-1 # -1 = offload all layers to GPU (Metal on Mac)
|
| 33 |
+
|
| 34 |
+
# ─────────────────────────────────────────────────────────────────────
|
| 35 |
+
# LM STUDIO BACKEND (if LLM_BACKEND=lmstudio)
|
| 36 |
+
# ─────────────────────────────────────────────────────────────────────
|
| 37 |
+
# LMSTUDIO_URL=http://localhost:1234
|
| 38 |
+
# LMSTUDIO_MODEL=qwen2.5-7b-instruct # Model loaded in LM Studio
|
| 39 |
+
|
| 40 |
+
# ─────────────────────────────────────────────────────────────────────
|
| 41 |
+
# EMBEDDING MODEL (shared by all backends)
|
| 42 |
# ─────────────────────────────────────────────────────────────────────
|
| 43 |
EMBED_MODEL=intfloat/multilingual-e5-large
|
| 44 |
|
.gitattributes
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
# Auto detect text files and perform LF normalization
|
| 2 |
* text=auto
|
| 3 |
-
|
| 4 |
-
QModel.index filter=lfs diff=lfs merge=lfs -text
|
|
|
|
| 1 |
# Auto detect text files and perform LF normalization
|
| 2 |
* text=auto
|
| 3 |
+
models/qwen2-7b-instruct-q8_0.gguf filter=lfs diff=lfs merge=lfs -text
|
|
|
ARCHITECTURE.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
# QModel
|
| 2 |
|
| 3 |
> For a quick overview, see [README.md](README.md#architecture-overview)
|
| 4 |
|
|
@@ -7,31 +7,66 @@ A RAG system specialized **exclusively** in authenticated Qur'an and Hadith. No
|
|
| 7 |
|
| 8 |
## Core Capabilities
|
| 9 |
|
| 10 |
-
### 1. **Quran
|
| 11 |
-
-
|
| 12 |
-
-
|
| 13 |
-
- **Topic Tafsir**: Retrieve and explain related Quranic verses
|
| 14 |
-
- **Bilingual**: Arabic (Uthmani) + English (Saheeh International)
|
| 15 |
|
| 16 |
-
### 2. **
|
| 17 |
-
-
|
| 18 |
-
-
|
| 19 |
-
- **Topic Search**: Find Hadiths related to topics across 7 major collections
|
| 20 |
-
- **Collection Navigation**: Filter by Bukhari, Muslim, Abu Dawud, Tirmidhi, Ibn Majah, Nasa'i, Malik
|
| 21 |
|
| 22 |
-
### 3. **
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
- **Confidence Gating**: Low-confidence queries return "not found" instead of LLM guess
|
| 24 |
- **Source Attribution**: Every answer cites exact verse/Hadith with reference
|
| 25 |
- **Grade Filtering**: Optional: only return Sahih-authenticated Hadiths
|
| 26 |
- **Verbatim Quotes**: Copy text directly from data, no paraphrasing
|
| 27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
---
|
| 29 |
|
| 30 |
## Data Pipeline
|
| 31 |
|
| 32 |
The system follows a three-phase approach:
|
| 33 |
|
| 34 |
-
**Metadata Schema**:
|
| 35 |
```json
|
| 36 |
{
|
| 37 |
"id": "surah:verse or hadith_prefix_number",
|
|
@@ -65,100 +100,137 @@ build_index.py
|
|
| 65 |
|
| 66 |
### Phase 3: Retrieval & Ranking
|
| 67 |
|
| 68 |
-
**Hybrid Search Algorithm**:
|
| 69 |
1. Dense retrieval: FAISS semantic scoring
|
| 70 |
2. Sparse retrieval: BM25 term-frequency ranking
|
| 71 |
3. Fusion: 60% dense + 40% sparse
|
| 72 |
4. Intent-aware boost: +0.08 to Hadith items when intent=hadith
|
| 73 |
5. Type filter: Optional (quran_only / hadith_only / authenticated_only)
|
|
|
|
| 74 |
|
| 75 |
---
|
| 76 |
|
| 77 |
-
##
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
-
|
| 80 |
-
- Fetches complete Quran and 7 Hadith collections
|
| 81 |
-
- Handles network retries + CDN redirects
|
| 82 |
-
- Normalizes and validates data
|
| 83 |
-
- Exports `data/quran.json` and `data/hadith.json`
|
| 84 |
|
| 85 |
-
##
|
| 86 |
-
- Loads datasets and embeddings model
|
| 87 |
-
- Creates dual-language FAISS vectors
|
| 88 |
-
- Serializes to `QModel.index` + `metadata.json`
|
| 89 |
|
| 90 |
-
### `
|
| 91 |
-
**Three processing layers**:
|
| 92 |
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
-
|
| 99 |
-
- `hybrid_search()` — FAISS + BM25 fusion
|
| 100 |
-
- `count_occurrences()` — exact/stemmed word frequency across dataset
|
| 101 |
-
- Caching at query level for fast follow-ups
|
| 102 |
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
|
|
|
|
|
|
| 108 |
|
| 109 |
-
|
| 110 |
-
- Few-shot examples including "not found" refusal path
|
| 111 |
-
- Hardcoded format rules (box/citation format required)
|
| 112 |
-
- Verbatim copy rules (no reconstruction from memory)
|
| 113 |
-
- Confidence threshold gating (default: 0.30)
|
| 114 |
|
| 115 |
-
|
|
|
|
|
|
|
|
|
|
| 116 |
|
| 117 |
-
##
|
| 118 |
|
| 119 |
-
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
-
|
| 123 |
-
```json
|
| 124 |
-
{
|
| 125 |
-
"question": "...",
|
| 126 |
-
"answer": "...",
|
| 127 |
-
"language": "arabic | english | mixed",
|
| 128 |
-
"intent": "tafsir | hadith | fatwa | count | general",
|
| 129 |
-
"analysis": {
|
| 130 |
-
"keyword": "محمد",
|
| 131 |
-
"total_count": 157,
|
| 132 |
-
"examples": [...]
|
| 133 |
-
},
|
| 134 |
-
"sources": [
|
| 135 |
-
{
|
| 136 |
-
"rank": 1,
|
| 137 |
-
"source": "Sahih al-Bukhari 1",
|
| 138 |
-
"type": "hadith",
|
| 139 |
-
"grade": "Sahih",
|
| 140 |
-
"_score": 0.876
|
| 141 |
-
}
|
| 142 |
-
],
|
| 143 |
-
"top_score": 0.876,
|
| 144 |
-
"latency_ms": 342
|
| 145 |
-
}
|
| 146 |
-
```
|
| 147 |
|
| 148 |
-
##
|
| 149 |
-
Inspect raw retrieval scores without LLM call. Use to calibrate `CONFIDENCE_THRESHOLD`.
|
| 150 |
|
| 151 |
-
|
| 152 |
-
|
|
|
|
|
|
|
|
|
|
| 153 |
|
| 154 |
---
|
| 155 |
|
| 156 |
## Configuration
|
| 157 |
|
| 158 |
-
**`.env`
|
| 159 |
```
|
| 160 |
OLLAMA_HOST # Ollama server URL
|
| 161 |
LLM_MODEL # Primary model (e.g. minimax-m2.7:cloud)
|
|
|
|
| 162 |
EMBED_MODEL # Embedding model (intfloat/multilingual-e5-large)
|
| 163 |
FAISS_INDEX # Path to QModel.index
|
| 164 |
METADATA_FILE # Path to metadata.json
|
|
@@ -189,32 +261,47 @@ docker-compose up
|
|
| 189 |
|
| 190 |
---
|
| 191 |
|
| 192 |
-
## Testing
|
| 193 |
|
| 194 |
-
### 1.
|
|
|
|
|
|
|
| 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 |
Q: "Who was Muhammad's 7th wife?" (not in dataset)
|
| 220 |
→ Retrieval score: 0.15 (below 0.30 threshold)
|
|
@@ -222,14 +309,26 @@ Q: "Who was Muhammad's 7th wife?" (not in dataset)
|
|
| 222 |
→ LLM not called (prevents hallucination)
|
| 223 |
```
|
| 224 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
---
|
| 226 |
|
| 227 |
-
## Roadmap:
|
| 228 |
|
| 229 |
-
- [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 230 |
- [ ] Chain of narrators: Display Isnad with full narrator details
|
| 231 |
- [ ] Synonym expansion: Better topic matching (e.g., "mercy" → "rahma, compassion")
|
| 232 |
- [ ] Multi-Surah topics: Topics spanning multiple Surahs
|
| 233 |
- [ ] Batch processing: Handle multiple questions in one request
|
| 234 |
-
- [ ] Streaming responses: SSE for long-form answers
|
| 235 |
- [ ] Islamic calendar integration: Hijri date references
|
|
|
|
|
|
| 1 |
+
# QModel v6 Architecture — Detailed System Design
|
| 2 |
|
| 3 |
> For a quick overview, see [README.md](README.md#architecture-overview)
|
| 4 |
|
|
|
|
| 7 |
|
| 8 |
## Core Capabilities
|
| 9 |
|
| 10 |
+
### 1. **Quran Verse Lookup** (by partial text)
|
| 11 |
+
- Text search: find any verse by typing part of its Arabic or English text
|
| 12 |
+
- Exact substring + fuzzy word-overlap matching
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
### 2. **Quran Topic Search**
|
| 15 |
+
- Semantic hybrid search to find verses related to any topic
|
| 16 |
+
- Full Tafsir-aware prompting
|
|
|
|
|
|
|
| 17 |
|
| 18 |
+
### 3. **Quran Word Frequency & Analytics**
|
| 19 |
+
- Count how many times a word appears across all 114 Surahs
|
| 20 |
+
- Per-surah breakdown with example verses
|
| 21 |
+
- Chapter-level analytics (verse count, revelation type)
|
| 22 |
+
|
| 23 |
+
### 4. **Hadith Lookup** (by partial text)
|
| 24 |
+
- Text search across 9 Hadith collections
|
| 25 |
+
- Optional collection filter
|
| 26 |
+
|
| 27 |
+
### 5. **Hadith Topic Search**
|
| 28 |
+
- Semantic hybrid search for Hadiths by topic
|
| 29 |
+
- Optional grade filter (sahih, hasan, etc.)
|
| 30 |
+
|
| 31 |
+
### 6. **Hadith Authenticity Verification**
|
| 32 |
+
- Dual-method verification: text search + semantic search
|
| 33 |
+
- Grade inference from collection name when not explicitly provided
|
| 34 |
+
- Sources: Bukhari, Muslim, Abu Dawud, Tirmidhi, Ibn Majah, Nasa'i, Malik, Ahmad, Darimi
|
| 35 |
+
|
| 36 |
+
### 7. **Safety First**
|
| 37 |
- **Confidence Gating**: Low-confidence queries return "not found" instead of LLM guess
|
| 38 |
- **Source Attribution**: Every answer cites exact verse/Hadith with reference
|
| 39 |
- **Grade Filtering**: Optional: only return Sahih-authenticated Hadiths
|
| 40 |
- **Verbatim Quotes**: Copy text directly from data, no paraphrasing
|
| 41 |
|
| 42 |
+
## Modular Architecture (v6)
|
| 43 |
+
|
| 44 |
+
```
|
| 45 |
+
main.py ← Thin launcher (73 lines)
|
| 46 |
+
app/
|
| 47 |
+
config.py ← Config class (env vars)
|
| 48 |
+
llm.py ← LLM providers (Ollama, HuggingFace)
|
| 49 |
+
cache.py ← TTL-LRU async cache
|
| 50 |
+
arabic_nlp.py ← Arabic normalisation, stemming, language detection
|
| 51 |
+
search.py ← Hybrid FAISS+BM25, text search, query rewriting
|
| 52 |
+
analysis.py ← Intent detection, analytics, counting
|
| 53 |
+
prompts.py ← Prompt engineering (persona, task instructions)
|
| 54 |
+
models.py ← Pydantic schemas
|
| 55 |
+
state.py ← AppState, lifespan, RAG pipeline
|
| 56 |
+
routers/
|
| 57 |
+
quran.py ← 6 Quran endpoints
|
| 58 |
+
hadith.py ← 5 Hadith endpoints
|
| 59 |
+
chat.py ← 2 OpenAI-compatible + inference endpoints
|
| 60 |
+
ops.py ← 3 operational endpoints (health, models, debug)
|
| 61 |
+
```
|
| 62 |
+
|
| 63 |
---
|
| 64 |
|
| 65 |
## Data Pipeline
|
| 66 |
|
| 67 |
The system follows a three-phase approach:
|
| 68 |
|
| 69 |
+
**Metadata Schema** (47,179 entries: 6,236 Quran + 40,943 Hadith):
|
| 70 |
```json
|
| 71 |
{
|
| 72 |
"id": "surah:verse or hadith_prefix_number",
|
|
|
|
| 100 |
|
| 101 |
### Phase 3: Retrieval & Ranking
|
| 102 |
|
| 103 |
+
**Hybrid Search Algorithm** (`app/search.py`):
|
| 104 |
1. Dense retrieval: FAISS semantic scoring
|
| 105 |
2. Sparse retrieval: BM25 term-frequency ranking
|
| 106 |
3. Fusion: 60% dense + 40% sparse
|
| 107 |
4. Intent-aware boost: +0.08 to Hadith items when intent=hadith
|
| 108 |
5. Type filter: Optional (quran_only / hadith_only / authenticated_only)
|
| 109 |
+
6. Phrase matching: Exact phrase + word-overlap scoring for text search
|
| 110 |
|
| 111 |
---
|
| 112 |
|
| 113 |
+
## Module Reference
|
| 114 |
+
|
| 115 |
+
### `app/config.py` — Configuration
|
| 116 |
+
- `Config` dataclass with all environment variables
|
| 117 |
+
- Singleton `cfg` instance
|
| 118 |
+
- Loads `.env` via dotenv
|
| 119 |
+
|
| 120 |
+
### `app/llm.py` — LLM Providers
|
| 121 |
+
- `LLMProvider` abstract base class
|
| 122 |
+
- `OllamaProvider` — primary (3-model fallback chain)
|
| 123 |
+
- `HuggingFaceProvider` — alternative local inference
|
| 124 |
+
- `create_llm_provider()` factory dispatches on `LLM_BACKEND` env var
|
| 125 |
+
|
| 126 |
+
### `app/cache.py` — TTL-LRU Cache
|
| 127 |
+
- `TTLCache` with size limit (1024) and TTL (300s)
|
| 128 |
+
- Pre-built instances: `search_cache`, `analysis_cache`, `rewrite_cache`
|
| 129 |
+
|
| 130 |
+
### `app/arabic_nlp.py` — Arabic NLP
|
| 131 |
+
- `normalize_arabic()` — tashkeel removal, hamza normalization
|
| 132 |
+
- `light_stem()` — prefix/suffix stripping
|
| 133 |
+
- `tokenize_ar()` — Arabic-aware tokenization
|
| 134 |
+
- `detect_language()` / `language_instruction()` — route persona by language
|
| 135 |
+
|
| 136 |
+
### `app/search.py` — Retrieval Engine
|
| 137 |
+
- `rewrite_query()` — dual-language normalization, LLM-assisted rewriting
|
| 138 |
+
- `hybrid_search()` — FAISS + BM25 fusion with intent-aware boosting
|
| 139 |
+
- `text_search()` — exact substring + word-overlap matching (for verse/hadith lookup by partial text)
|
| 140 |
+
- `build_context()` — format retrieved items for LLM prompt
|
| 141 |
+
|
| 142 |
+
### `app/analysis.py` — Analytics & Intent Detection
|
| 143 |
+
- `detect_analysis_intent()` — identifies count / analytics / chapter queries
|
| 144 |
+
- `count_occurrences()` — word frequency across all Surahs
|
| 145 |
+
- `get_quran_analytics()` — chapter-level stats
|
| 146 |
+
- `get_hadith_analytics()` — collection-level stats
|
| 147 |
+
- `get_chapter_info()` — single Surah metadata
|
| 148 |
+
- `get_verse()` — exact verse by surah:ayah
|
| 149 |
+
- `detect_surah_info()` / `lookup_surah_info()` — Surah name resolution
|
| 150 |
+
|
| 151 |
+
### `app/prompts.py` — Prompt Engineering
|
| 152 |
+
- `PERSONA` — Islamic scholar persona definition
|
| 153 |
+
- `TASK_INSTRUCTIONS` — verbatim-quoting, anti-hallucination rules
|
| 154 |
+
- `FORMAT_RULES` — citation box format
|
| 155 |
+
- `build_messages()` — intent-aware system + user message construction
|
| 156 |
+
- `not_found_answer()` — safe "not in dataset" response
|
| 157 |
+
|
| 158 |
+
### `app/models.py` — Pydantic Schemas
|
| 159 |
+
All request/response models:
|
| 160 |
+
- `ChatMessage`, `ChatCompletionRequest/Response/Choice` — OpenAI-compatible
|
| 161 |
+
- `AskResponse`, `AnalysisResult`, `SourceItem` — RAG pipeline
|
| 162 |
+
- `HadithVerifyResponse` — authenticity verification
|
| 163 |
+
- `VerseItem`, `HadithItem`, `TextSearchResponse` — text search
|
| 164 |
+
- `ChapterResponse`, `QuranAnalyticsResponse`, `HadithAnalyticsResponse` — analytics
|
| 165 |
+
- `WordFrequencyResponse` — word counting
|
| 166 |
+
- `ModelInfo`, `ModelsListResponse` — OpenAI models list
|
| 167 |
+
|
| 168 |
+
### `app/state.py` — Application State & Lifecycle
|
| 169 |
+
- `AppState` — holds FAISS index, metadata, embedder, LLM provider
|
| 170 |
+
- `lifespan()` — async startup (loads index, model, metadata)
|
| 171 |
+
- `check_ready()` — dependency guard for endpoints
|
| 172 |
+
- `run_rag_pipeline()` — full RAG: rewrite → search → context → LLM → response
|
| 173 |
+
- `infer_hadith_grade()` — grade detection from collection name
|
| 174 |
|
| 175 |
+
---
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
|
| 177 |
+
## API Endpoints (16 total)
|
|
|
|
|
|
|
|
|
|
| 178 |
|
| 179 |
+
### Quran Router (`/quran/...`) — 6 endpoints
|
|
|
|
| 180 |
|
| 181 |
+
| Endpoint | Method | Description |
|
| 182 |
+
|----------|--------|-------------|
|
| 183 |
+
| `/quran/search?q=...` | GET | Text search: find verses by partial Arabic/English text |
|
| 184 |
+
| `/quran/topic?q=...&top_k=5` | GET | Semantic search: find verses related to a topic |
|
| 185 |
+
| `/quran/word-frequency?word=...` | GET | Count word occurrences across all Surahs |
|
| 186 |
+
| `/quran/analytics` | GET | Overall Quran stats (total verses, Surahs, types) |
|
| 187 |
+
| `/quran/chapter/{number}` | GET | Single Surah metadata (name, verse count, type) |
|
| 188 |
+
| `/quran/verse/{surah}:{ayah}` | GET | Exact verse lookup by reference |
|
| 189 |
|
| 190 |
+
### Hadith Router (`/hadith/...`) — 5 endpoints
|
|
|
|
|
|
|
|
|
|
| 191 |
|
| 192 |
+
| Endpoint | Method | Description |
|
| 193 |
+
|----------|--------|-------------|
|
| 194 |
+
| `/hadith/search?q=...&collection=...` | GET | Text search across collections |
|
| 195 |
+
| `/hadith/topic?q=...&top_k=5&grade=...` | GET | Semantic search by topic with optional grade filter |
|
| 196 |
+
| `/hadith/verify?q=...` | GET | Authenticity verification (text + semantic search) |
|
| 197 |
+
| `/hadith/collection/{name}?limit=20` | GET | Browse a specific collection |
|
| 198 |
+
| `/hadith/analytics` | GET | Collection-level statistics |
|
| 199 |
|
| 200 |
+
### Chat Router — 2 endpoints
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
|
| 202 |
+
| Endpoint | Method | Description |
|
| 203 |
+
|----------|--------|-------------|
|
| 204 |
+
| `/v1/chat/completions` | POST | OpenAI-compatible chat (SSE streaming supported) |
|
| 205 |
+
| `/ask?q=...&top_k=5` | GET | Direct RAG query with full source attribution |
|
| 206 |
|
| 207 |
+
### Ops Router — 3 endpoints
|
| 208 |
|
| 209 |
+
| Endpoint | Method | Description |
|
| 210 |
+
|----------|--------|-------------|
|
| 211 |
+
| `/health` | GET | Readiness check |
|
| 212 |
+
| `/v1/models` | GET | OpenAI-compatible model listing |
|
| 213 |
+
| `/debug/scores?q=...&top_k=10` | GET | Raw retrieval scores (no LLM call) |
|
| 214 |
|
| 215 |
+
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
|
| 217 |
+
## Anti-Hallucination Measures
|
|
|
|
| 218 |
|
| 219 |
+
- Few-shot examples including "not found" refusal path
|
| 220 |
+
- Hardcoded format rules (box/citation format required)
|
| 221 |
+
- Verbatim copy rules (no reconstruction from memory)
|
| 222 |
+
- Confidence threshold gating (default: 0.30)
|
| 223 |
+
- Grade inference for Hadith authenticity (collection-based)
|
| 224 |
|
| 225 |
---
|
| 226 |
|
| 227 |
## Configuration
|
| 228 |
|
| 229 |
+
**`.env` variables**:
|
| 230 |
```
|
| 231 |
OLLAMA_HOST # Ollama server URL
|
| 232 |
LLM_MODEL # Primary model (e.g. minimax-m2.7:cloud)
|
| 233 |
+
LLM_BACKEND # "ollama" (default) or "huggingface"
|
| 234 |
EMBED_MODEL # Embedding model (intfloat/multilingual-e5-large)
|
| 235 |
FAISS_INDEX # Path to QModel.index
|
| 236 |
METADATA_FILE # Path to metadata.json
|
|
|
|
| 261 |
|
| 262 |
---
|
| 263 |
|
| 264 |
+
## Testing Examples
|
| 265 |
|
| 266 |
+
### 1. Quran Verse Lookup (Capability 1)
|
| 267 |
+
```bash
|
| 268 |
+
curl "http://localhost:8000/quran/search?q=bismillah"
|
| 269 |
```
|
| 270 |
+
|
| 271 |
+
### 2. Quran Topic Search (Capability 2)
|
| 272 |
+
```bash
|
| 273 |
+
curl "http://localhost:8000/quran/topic?q=patience&top_k=5"
|
| 274 |
```
|
| 275 |
|
| 276 |
+
### 3. Word Frequency (Capability 3)
|
| 277 |
+
```bash
|
| 278 |
+
curl "http://localhost:8000/quran/word-frequency?word=mercy"
|
| 279 |
+
# → Returns: count per surah + total + examples
|
| 280 |
```
|
| 281 |
+
|
| 282 |
+
### 4. Quran Analytics (Capability 3)
|
| 283 |
+
```bash
|
| 284 |
+
curl "http://localhost:8000/quran/analytics"
|
| 285 |
+
curl "http://localhost:8000/quran/chapter/2"
|
| 286 |
```
|
| 287 |
|
| 288 |
+
### 5. Hadith Text Search (Capability 4)
|
| 289 |
+
```bash
|
| 290 |
+
curl "http://localhost:8000/hadith/search?q=actions+are+judged+by+intentions"
|
| 291 |
```
|
| 292 |
+
|
| 293 |
+
### 6. Hadith Topic Search (Capability 5)
|
| 294 |
+
```bash
|
| 295 |
+
curl "http://localhost:8000/hadith/topic?q=fasting&grade=sahih"
|
| 296 |
```
|
| 297 |
|
| 298 |
+
### 7. Hadith Authenticity Verification (Capability 6)
|
| 299 |
+
```bash
|
| 300 |
+
curl "http://localhost:8000/hadith/verify?q=Actions+are+judged+by+intentions"
|
| 301 |
+
# → Returns: found=true, grade="Sahih", source="Sahih al-Bukhari 1"
|
| 302 |
+
```
|
| 303 |
+
|
| 304 |
+
### 8. Confidence Gate in Action (Safety)
|
| 305 |
```
|
| 306 |
Q: "Who was Muhammad's 7th wife?" (not in dataset)
|
| 307 |
→ Retrieval score: 0.15 (below 0.30 threshold)
|
|
|
|
| 309 |
→ LLM not called (prevents hallucination)
|
| 310 |
```
|
| 311 |
|
| 312 |
+
### 9. OpenAI-Compatible Chat (Streaming)
|
| 313 |
+
```bash
|
| 314 |
+
curl -X POST http://localhost:8000/v1/chat/completions \
|
| 315 |
+
-H "Content-Type: application/json" \
|
| 316 |
+
-d '{"model":"qmodel","messages":[{"role":"user","content":"What does Islam say about charity?"}],"stream":true}'
|
| 317 |
+
```
|
| 318 |
+
|
| 319 |
---
|
| 320 |
|
| 321 |
+
## Roadmap: v6+ Enhancements
|
| 322 |
|
| 323 |
+
- [x] Grade-based filtering: `?grade=sahih` to return only authenticated Hadiths
|
| 324 |
+
- [x] Streaming responses: SSE for long-form answers
|
| 325 |
+
- [x] Modular architecture: Separate routers, models, and services
|
| 326 |
+
- [x] Dual LLM backend: Ollama + HuggingFace support
|
| 327 |
+
- [x] Text search: Exact substring + fuzzy word-overlap matching
|
| 328 |
+
- [x] Expanded endpoints: 16 endpoints across 4 routers
|
| 329 |
- [ ] Chain of narrators: Display Isnad with full narrator details
|
| 330 |
- [ ] Synonym expansion: Better topic matching (e.g., "mercy" → "rahma, compassion")
|
| 331 |
- [ ] Multi-Surah topics: Topics spanning multiple Surahs
|
| 332 |
- [ ] Batch processing: Handle multiple questions in one request
|
|
|
|
| 333 |
- [ ] Islamic calendar integration: Hijri date references
|
| 334 |
+
- [ ] Tafsir integration: Dedicated Tafsir endpoint with scholar citations
|
app/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""QModel v6 — Islamic RAG API."""
|
app/analysis.py
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Quran / Hadith analytics — occurrence counting, surah metadata, dataset stats."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import re
|
| 6 |
+
from typing import Dict, List, Literal, Optional
|
| 7 |
+
|
| 8 |
+
from app.arabic_nlp import light_stem, normalize_arabic, tokenize_ar
|
| 9 |
+
from app.cache import analysis_cache
|
| 10 |
+
from app.config import cfg
|
| 11 |
+
|
| 12 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 13 |
+
# INTENT DETECTION — frequency / surah info queries
|
| 14 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 15 |
+
_COUNT_EN = re.compile(
|
| 16 |
+
r"\b(how many|count|number of|frequency|occurrences? of|how often|"
|
| 17 |
+
r"times? (does|is|appears?))\b",
|
| 18 |
+
re.I,
|
| 19 |
+
)
|
| 20 |
+
_COUNT_AR = re.compile(
|
| 21 |
+
r"(كم مرة|كم عدد|كم تكرر|عدد مرات|تكرار|كم ذُكر|كم وردت?)"
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
_SURAH_VERSES_AR = re.compile(
|
| 25 |
+
r"كم\s+(?:عدد\s+)?آيات?\s*(?:في\s+|فى\s+)?(?:سورة|سوره)"
|
| 26 |
+
r"|عدد\s+آيات?\s+(?:سورة|سوره)"
|
| 27 |
+
r"|كم\s+آية\s+(?:في|فى)\s+(?:سورة|سوره)"
|
| 28 |
+
r"|(?:سورة|سوره)\s+[\u0600-\u06FF\s]+\s+(?:كم\s+آية|عدد\s+آيات?)"
|
| 29 |
+
)
|
| 30 |
+
_SURAH_VERSES_EN = re.compile(
|
| 31 |
+
r"(?:how many|number of)\s+(?:verses?|ayat|ayahs?)\s+(?:in|of|does)\b"
|
| 32 |
+
r"|\bsurah?\b.*\b(?:how many|number of)\s+(?:verses?|ayat|ayahs?)",
|
| 33 |
+
re.I,
|
| 34 |
+
)
|
| 35 |
+
_SURAH_TYPE_AR = re.compile(
|
| 36 |
+
r"(?:سورة|سوره)\s+[\u0600-\u06FF\s]+\s+(?:مكية|مدنية|مكي|مدني)"
|
| 37 |
+
r"|(?:هل|ما\s+نوع)\s+(?:سورة|سوره)\s+[\u0600-\u06FF\s]+\s+(?:مكية|مدنية)"
|
| 38 |
+
)
|
| 39 |
+
_SURAH_NAME_AR = re.compile(
|
| 40 |
+
r"(?:سورة|سوره)\s+([\u0600-\u06FF\u0750-\u077F\s]+)"
|
| 41 |
+
)
|
| 42 |
+
_SURAH_NAME_EN = re.compile(
|
| 43 |
+
r"\bsurah?\s+([a-zA-Z'\-]+(?:[\s\-][a-zA-Z'\-]+)*)",
|
| 44 |
+
re.I,
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _extract_surah_name(query: str) -> Optional[str]:
|
| 49 |
+
"""Extract surah name from a query string."""
|
| 50 |
+
for pat in (_SURAH_NAME_AR, _SURAH_NAME_EN):
|
| 51 |
+
m = pat.search(query)
|
| 52 |
+
if m:
|
| 53 |
+
name = m.group(1).strip()
|
| 54 |
+
name = re.sub(r'[\s؟?!]+$', '', name)
|
| 55 |
+
name = re.sub(r'\s+(كم|عدد|هل|ما|في|فى)$', '', name)
|
| 56 |
+
if name:
|
| 57 |
+
return name
|
| 58 |
+
return None
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 62 |
+
# SURAH INFO DETECTION & LOOKUP
|
| 63 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 64 |
+
async def detect_surah_info(query: str, rewrite: dict) -> Optional[dict]:
|
| 65 |
+
"""Detect if query asks about surah metadata (verse count, type, etc.)."""
|
| 66 |
+
is_verse_q = bool(_SURAH_VERSES_AR.search(query) or _SURAH_VERSES_EN.search(query))
|
| 67 |
+
is_type_q = bool(_SURAH_TYPE_AR.search(query))
|
| 68 |
+
|
| 69 |
+
if not (is_verse_q or is_type_q):
|
| 70 |
+
if rewrite.get("intent") == "surah_info":
|
| 71 |
+
is_verse_q = True
|
| 72 |
+
elif rewrite.get("intent") == "count":
|
| 73 |
+
kw_text = " ".join(rewrite.get("keywords", []))
|
| 74 |
+
if any(w in kw_text for w in ("آيات", "آية", "verses", "ayat")):
|
| 75 |
+
is_verse_q = True
|
| 76 |
+
else:
|
| 77 |
+
return None
|
| 78 |
+
else:
|
| 79 |
+
return None
|
| 80 |
+
|
| 81 |
+
surah_name = _extract_surah_name(query)
|
| 82 |
+
if not surah_name:
|
| 83 |
+
return None
|
| 84 |
+
|
| 85 |
+
return {
|
| 86 |
+
"surah_query": surah_name,
|
| 87 |
+
"query_type": "verses" if is_verse_q else "type",
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
async def lookup_surah_info(surah_query: str, dataset: list) -> Optional[dict]:
|
| 92 |
+
"""Look up surah metadata from dataset entries."""
|
| 93 |
+
query_norm = normalize_arabic(surah_query, aggressive=True).lower()
|
| 94 |
+
query_clean = re.sub(r"^(ال|al[\-\s']*)", "", query_norm, flags=re.I).strip()
|
| 95 |
+
|
| 96 |
+
for item in dataset:
|
| 97 |
+
if item.get("type") != "quran":
|
| 98 |
+
continue
|
| 99 |
+
for field in ("surah_name_ar", "surah_name_en", "surah_name_transliteration"):
|
| 100 |
+
val = item.get(field, "")
|
| 101 |
+
if not val:
|
| 102 |
+
continue
|
| 103 |
+
val_norm = normalize_arabic(val, aggressive=True).lower()
|
| 104 |
+
val_clean = re.sub(r"^(ال|al[\-\s']*)", "", val_norm, flags=re.I).strip()
|
| 105 |
+
if (query_norm in val_norm or val_norm in query_norm
|
| 106 |
+
or (query_clean and val_clean
|
| 107 |
+
and (query_clean in val_clean or val_clean in query_clean))
|
| 108 |
+
or (query_clean and query_clean in val_norm)):
|
| 109 |
+
return {
|
| 110 |
+
"surah_number": item.get("surah_number"),
|
| 111 |
+
"surah_name_ar": item.get("surah_name_ar", ""),
|
| 112 |
+
"surah_name_en": item.get("surah_name_en", ""),
|
| 113 |
+
"surah_name_transliteration": item.get("surah_name_transliteration", ""),
|
| 114 |
+
"total_verses": item.get("total_verses"),
|
| 115 |
+
"revelation_type": item.get("revelation_type", ""),
|
| 116 |
+
}
|
| 117 |
+
return None
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 121 |
+
# ANALYSIS INTENT (word frequency detection)
|
| 122 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 123 |
+
async def detect_analysis_intent(query: str, rewrite: dict) -> Optional[str]:
|
| 124 |
+
"""Detect if query is asking for word frequency analysis."""
|
| 125 |
+
if (_SURAH_VERSES_AR.search(query) or _SURAH_VERSES_EN.search(query)
|
| 126 |
+
or _SURAH_TYPE_AR.search(query)
|
| 127 |
+
or rewrite.get("intent") == "surah_info"):
|
| 128 |
+
return None
|
| 129 |
+
|
| 130 |
+
if rewrite.get("intent") == "count":
|
| 131 |
+
kws = rewrite.get("keywords", [])
|
| 132 |
+
kw_text = " ".join(kws)
|
| 133 |
+
if any(w in kw_text for w in ("آيات", "آية", "verses", "ayat")):
|
| 134 |
+
return None
|
| 135 |
+
return kws[0] if kws else None
|
| 136 |
+
|
| 137 |
+
if not (_COUNT_EN.search(query) or _COUNT_AR.search(query)):
|
| 138 |
+
return None
|
| 139 |
+
|
| 140 |
+
for pat in (_COUNT_EN, _COUNT_AR):
|
| 141 |
+
m = pat.search(query)
|
| 142 |
+
if m:
|
| 143 |
+
tail = query[m.end():].strip().split()
|
| 144 |
+
if tail:
|
| 145 |
+
return tail[0]
|
| 146 |
+
return None
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 150 |
+
# OCCURRENCE COUNTING
|
| 151 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 152 |
+
async def count_occurrences(keyword: str, dataset: list) -> dict:
|
| 153 |
+
"""Count keyword occurrences with surah grouping."""
|
| 154 |
+
cached = await analysis_cache.get(keyword)
|
| 155 |
+
if cached:
|
| 156 |
+
return cached
|
| 157 |
+
|
| 158 |
+
kw_norm = normalize_arabic(keyword, aggressive=True).lower()
|
| 159 |
+
kw_stem = light_stem(kw_norm)
|
| 160 |
+
count = 0
|
| 161 |
+
by_surah: Dict[int, Dict] = {}
|
| 162 |
+
examples: list = []
|
| 163 |
+
|
| 164 |
+
for item in dataset:
|
| 165 |
+
if item.get("type") != "quran":
|
| 166 |
+
continue
|
| 167 |
+
|
| 168 |
+
ar_norm = normalize_arabic(item.get("arabic", ""), aggressive=True).lower()
|
| 169 |
+
combined = f"{ar_norm} {item.get('english', '')}".lower()
|
| 170 |
+
exact = combined.count(kw_norm)
|
| 171 |
+
stemmed = combined.count(kw_stem) - exact if kw_stem != kw_norm else 0
|
| 172 |
+
occ = exact + stemmed
|
| 173 |
+
|
| 174 |
+
if occ > 0:
|
| 175 |
+
count += occ
|
| 176 |
+
surah_num = item.get("surah_number", 0)
|
| 177 |
+
if surah_num not in by_surah:
|
| 178 |
+
by_surah[surah_num] = {
|
| 179 |
+
"name": item.get("surah_name_en", f"Surah {surah_num}"),
|
| 180 |
+
"count": 0,
|
| 181 |
+
}
|
| 182 |
+
by_surah[surah_num]["count"] += occ
|
| 183 |
+
|
| 184 |
+
if len(examples) < cfg.MAX_EXAMPLES:
|
| 185 |
+
examples.append({
|
| 186 |
+
"reference": item.get("source", ""),
|
| 187 |
+
"arabic": item.get("arabic", ""),
|
| 188 |
+
"english": item.get("english", ""),
|
| 189 |
+
})
|
| 190 |
+
|
| 191 |
+
result = {
|
| 192 |
+
"keyword": keyword,
|
| 193 |
+
"kw_stemmed": kw_stem,
|
| 194 |
+
"total_count": count,
|
| 195 |
+
"by_surah": dict(sorted(by_surah.items())),
|
| 196 |
+
"examples": examples,
|
| 197 |
+
}
|
| 198 |
+
await analysis_cache.set(result, keyword)
|
| 199 |
+
return result
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 203 |
+
# DATASET ANALYTICS — aggregate statistics
|
| 204 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 205 |
+
def get_quran_analytics(dataset: list) -> dict:
|
| 206 |
+
"""Compute aggregate Quran statistics from dataset."""
|
| 207 |
+
surahs: Dict[int, dict] = {}
|
| 208 |
+
total_verses = 0
|
| 209 |
+
|
| 210 |
+
for item in dataset:
|
| 211 |
+
if item.get("type") != "quran":
|
| 212 |
+
continue
|
| 213 |
+
total_verses += 1
|
| 214 |
+
sn = item.get("surah_number", 0)
|
| 215 |
+
if sn not in surahs:
|
| 216 |
+
surahs[sn] = {
|
| 217 |
+
"surah_number": sn,
|
| 218 |
+
"surah_name_ar": item.get("surah_name_ar", ""),
|
| 219 |
+
"surah_name_en": item.get("surah_name_en", ""),
|
| 220 |
+
"surah_name_transliteration": item.get("surah_name_transliteration", ""),
|
| 221 |
+
"revelation_type": item.get("revelation_type", ""),
|
| 222 |
+
"total_verses": item.get("total_verses", 0),
|
| 223 |
+
"verses_in_dataset": 0,
|
| 224 |
+
}
|
| 225 |
+
surahs[sn]["verses_in_dataset"] += 1
|
| 226 |
+
|
| 227 |
+
meccan = sum(1 for s in surahs.values() if s.get("revelation_type", "").lower() == "meccan")
|
| 228 |
+
medinan = sum(1 for s in surahs.values() if s.get("revelation_type", "").lower() == "medinan")
|
| 229 |
+
|
| 230 |
+
return {
|
| 231 |
+
"total_verses_in_dataset": total_verses,
|
| 232 |
+
"total_surahs": len(surahs),
|
| 233 |
+
"meccan_surahs": meccan,
|
| 234 |
+
"medinan_surahs": medinan,
|
| 235 |
+
"surahs": [surahs[k] for k in sorted(surahs)],
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def get_hadith_analytics(dataset: list) -> dict:
|
| 240 |
+
"""Compute aggregate Hadith statistics from dataset."""
|
| 241 |
+
collections: Dict[str, dict] = {}
|
| 242 |
+
grades: Dict[str, int] = {}
|
| 243 |
+
total = 0
|
| 244 |
+
|
| 245 |
+
for item in dataset:
|
| 246 |
+
if item.get("type") != "hadith":
|
| 247 |
+
continue
|
| 248 |
+
total += 1
|
| 249 |
+
|
| 250 |
+
col = item.get("collection", "Unknown")
|
| 251 |
+
if col not in collections:
|
| 252 |
+
collections[col] = {"collection": col, "count": 0, "grades": {}}
|
| 253 |
+
collections[col]["count"] += 1
|
| 254 |
+
|
| 255 |
+
grade = item.get("grade", "Ungraded")
|
| 256 |
+
grades[grade] = grades.get(grade, 0) + 1
|
| 257 |
+
collections[col]["grades"][grade] = collections[col]["grades"].get(grade, 0) + 1
|
| 258 |
+
|
| 259 |
+
return {
|
| 260 |
+
"total_hadiths": total,
|
| 261 |
+
"collections": sorted(collections.values(), key=lambda c: c["count"], reverse=True),
|
| 262 |
+
"grade_summary": dict(sorted(grades.items(), key=lambda x: x[1], reverse=True)),
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def get_chapter_info(chapter_number: int, dataset: list) -> Optional[dict]:
|
| 267 |
+
"""Get all verses and metadata for a specific surah/chapter."""
|
| 268 |
+
verses = []
|
| 269 |
+
meta = None
|
| 270 |
+
|
| 271 |
+
for item in dataset:
|
| 272 |
+
if item.get("type") != "quran":
|
| 273 |
+
continue
|
| 274 |
+
if item.get("surah_number") != chapter_number:
|
| 275 |
+
continue
|
| 276 |
+
if meta is None:
|
| 277 |
+
meta = {
|
| 278 |
+
"surah_number": item.get("surah_number"),
|
| 279 |
+
"surah_name_ar": item.get("surah_name_ar", ""),
|
| 280 |
+
"surah_name_en": item.get("surah_name_en", ""),
|
| 281 |
+
"surah_name_transliteration": item.get("surah_name_transliteration", ""),
|
| 282 |
+
"revelation_type": item.get("revelation_type", ""),
|
| 283 |
+
"total_verses": item.get("total_verses", 0),
|
| 284 |
+
}
|
| 285 |
+
verses.append({
|
| 286 |
+
"ayah": item.get("ayah_number") or item.get("verse_number"),
|
| 287 |
+
"arabic": item.get("arabic", ""),
|
| 288 |
+
"english": item.get("english", ""),
|
| 289 |
+
"source": item.get("source", ""),
|
| 290 |
+
})
|
| 291 |
+
|
| 292 |
+
if not meta:
|
| 293 |
+
return None
|
| 294 |
+
|
| 295 |
+
verses.sort(key=lambda v: v.get("ayah") or 0)
|
| 296 |
+
return {**meta, "verses": verses}
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def get_verse(surah: int, ayah: int, dataset: list) -> Optional[dict]:
|
| 300 |
+
"""Get a specific verse by surah and ayah number."""
|
| 301 |
+
for item in dataset:
|
| 302 |
+
if item.get("type") != "quran":
|
| 303 |
+
continue
|
| 304 |
+
if item.get("surah_number") != surah:
|
| 305 |
+
continue
|
| 306 |
+
item_ayah = item.get("ayah_number") or item.get("verse_number")
|
| 307 |
+
if item_ayah == ayah:
|
| 308 |
+
return {
|
| 309 |
+
"surah_number": item.get("surah_number"),
|
| 310 |
+
"surah_name_ar": item.get("surah_name_ar", ""),
|
| 311 |
+
"surah_name_en": item.get("surah_name_en", ""),
|
| 312 |
+
"surah_name_transliteration": item.get("surah_name_transliteration", ""),
|
| 313 |
+
"ayah": item_ayah,
|
| 314 |
+
"arabic": item.get("arabic", ""),
|
| 315 |
+
"english": item.get("english", ""),
|
| 316 |
+
"transliteration": item.get("transliteration", ""),
|
| 317 |
+
"tafsir_en": item.get("tafsir_en", ""),
|
| 318 |
+
"tafsir_ar": item.get("tafsir_ar", ""),
|
| 319 |
+
"source": item.get("source", ""),
|
| 320 |
+
"revelation_type": item.get("revelation_type", ""),
|
| 321 |
+
}
|
| 322 |
+
return None
|
app/arabic_nlp.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Arabic NLP — normalisation, light stemming, language detection."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import re
|
| 6 |
+
from typing import Dict, List, Literal
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
# ── Normalization patterns ─────────────────────────────────────────────
|
| 10 |
+
_DIACRITICS = re.compile(r"[\u064B-\u0655\u0656-\u0658\u0670\u06D6-\u06ED]")
|
| 11 |
+
_ALEF_VARS = re.compile(r"[أإآٱ]")
|
| 12 |
+
_WAW_HAMZA = re.compile(r"ؤ")
|
| 13 |
+
_YA_HAMZA = re.compile(r"ئ")
|
| 14 |
+
_TA_MARBUTA = re.compile(r"ة\b")
|
| 15 |
+
_ALEF_MAQSURA = re.compile(r"ى")
|
| 16 |
+
_TATWEEL = re.compile(r"\u0640+")
|
| 17 |
+
_PUNC_AR = re.compile(r"[،؛؟!«»\u200c\u200d\u200f\u200e]")
|
| 18 |
+
_MULTI_SPACE = re.compile(r"\s{2,}")
|
| 19 |
+
_NON_AR_EN = re.compile(r"[^\u0600-\u06FF\u0750-\u077Fa-zA-Z0-9\s]")
|
| 20 |
+
|
| 21 |
+
_SPELLING_MAP: Dict[str, str] = {
|
| 22 |
+
"قران": "قرآن",
|
| 23 |
+
"القران": "القرآن",
|
| 24 |
+
"اللہ": "الله",
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def normalize_arabic(text: str, *, aggressive: bool = False) -> str:
|
| 29 |
+
"""Normalize Arabic text: diacritics, hamza, ta marbuta, etc."""
|
| 30 |
+
text = _DIACRITICS.sub("", text)
|
| 31 |
+
text = _TATWEEL.sub("", text)
|
| 32 |
+
text = _ALEF_VARS.sub("ا", text)
|
| 33 |
+
text = _WAW_HAMZA.sub("و", text)
|
| 34 |
+
text = _YA_HAMZA.sub("ي", text)
|
| 35 |
+
text = _TA_MARBUTA.sub("ه", text)
|
| 36 |
+
text = _ALEF_MAQSURA.sub("ي", text)
|
| 37 |
+
text = _PUNC_AR.sub(" ", text)
|
| 38 |
+
for variant, canonical in _SPELLING_MAP.items():
|
| 39 |
+
text = text.replace(variant, canonical)
|
| 40 |
+
if aggressive:
|
| 41 |
+
text = _NON_AR_EN.sub(" ", text)
|
| 42 |
+
return _MULTI_SPACE.sub(" ", text).strip()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# ── Light stemming ─────────────────────────────────────────────────────
|
| 46 |
+
_AR_PREFIXES = re.compile(
|
| 47 |
+
r"^(و|ف|ب|ل|ال|لل|وال|فال|بال|كال|ولل|ومن|وفي|وعن|وإلى|وعلى)\b"
|
| 48 |
+
)
|
| 49 |
+
_AR_SUFFIXES = re.compile(
|
| 50 |
+
r"(ون|ين|ان|ات|ها|هم|هن|كم|كن|نا|ني|تي|ي|ه|ك|ا|وا)$"
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def light_stem(word: str) -> str:
|
| 55 |
+
"""Light stemming: remove common Arabic affixes."""
|
| 56 |
+
w = _AR_PREFIXES.sub("", word)
|
| 57 |
+
w = _AR_SUFFIXES.sub("", w)
|
| 58 |
+
return w if len(w) >= 2 else word
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def tokenize_ar(text: str) -> List[str]:
|
| 62 |
+
"""Tokenize and stem Arabic text."""
|
| 63 |
+
norm = normalize_arabic(text, aggressive=True).lower()
|
| 64 |
+
return [light_stem(t) for t in norm.split() if t]
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# ── Language detection ─────────────────────────────────────────────────
|
| 68 |
+
_ARABIC_SCRIPT = re.compile(
|
| 69 |
+
r"[\u0600-\u06FF\u0750-\u077F\uFB50-\uFDFF\uFE70-\uFEFF]"
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def detect_language(text: str) -> Literal["arabic", "english", "mixed"]:
|
| 74 |
+
"""Detect if text is Arabic, English, or mixed."""
|
| 75 |
+
ar = len(_ARABIC_SCRIPT.findall(text))
|
| 76 |
+
en = len(re.findall(r"[a-zA-Z]", text))
|
| 77 |
+
tot = ar + en or 1
|
| 78 |
+
ratio = ar / tot
|
| 79 |
+
if ratio > 0.70:
|
| 80 |
+
return "arabic"
|
| 81 |
+
if ratio < 0.30:
|
| 82 |
+
return "english"
|
| 83 |
+
return "mixed"
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def language_instruction(lang: str) -> str:
|
| 87 |
+
"""Generate language-specific instruction for LLM."""
|
| 88 |
+
return {
|
| 89 |
+
"arabic": (
|
| 90 |
+
"يجب أن تكون الإجابة كاملةً باللغة العربية الفصحى تماماً. "
|
| 91 |
+
"لا تستخدم الإنجليزية أو أي لغة أخرى في أي جزء من الإجابة."
|
| 92 |
+
),
|
| 93 |
+
"mixed": (
|
| 94 |
+
"The question mixes Arabic and English. Reply primarily in Arabic (الفصحى) "
|
| 95 |
+
"but you may transliterate key terms in English where essential."
|
| 96 |
+
),
|
| 97 |
+
"english": "You MUST reply entirely in clear, formal English.",
|
| 98 |
+
}.get(lang, "You MUST reply entirely in clear, formal English.")
|
app/cache.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Async-safe TTL-LRU cache."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import asyncio
|
| 6 |
+
import hashlib
|
| 7 |
+
import json
|
| 8 |
+
import time
|
| 9 |
+
from collections import OrderedDict
|
| 10 |
+
|
| 11 |
+
from app.config import cfg
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class TTLCache:
|
| 15 |
+
"""Async-safe LRU cache with per-entry TTL."""
|
| 16 |
+
|
| 17 |
+
def __init__(self, maxsize: int = 256, ttl: int = 3600):
|
| 18 |
+
self._cache: OrderedDict = OrderedDict()
|
| 19 |
+
self._maxsize = maxsize
|
| 20 |
+
self._ttl = ttl
|
| 21 |
+
self._lock = asyncio.Lock()
|
| 22 |
+
|
| 23 |
+
def _key(self, *args) -> str:
|
| 24 |
+
payload = json.dumps(args, ensure_ascii=False, sort_keys=True)
|
| 25 |
+
return hashlib.sha256(payload.encode()).hexdigest()[:20]
|
| 26 |
+
|
| 27 |
+
async def get(self, *args):
|
| 28 |
+
async with self._lock:
|
| 29 |
+
k = self._key(*args)
|
| 30 |
+
if k in self._cache:
|
| 31 |
+
value, ts = self._cache[k]
|
| 32 |
+
if time.monotonic() - ts < self._ttl:
|
| 33 |
+
self._cache.move_to_end(k)
|
| 34 |
+
return value
|
| 35 |
+
del self._cache[k]
|
| 36 |
+
return None
|
| 37 |
+
|
| 38 |
+
async def set(self, value, *args):
|
| 39 |
+
async with self._lock:
|
| 40 |
+
k = self._key(*args)
|
| 41 |
+
self._cache[k] = (value, time.monotonic())
|
| 42 |
+
self._cache.move_to_end(k)
|
| 43 |
+
if len(self._cache) > self._maxsize:
|
| 44 |
+
self._cache.popitem(last=False)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
search_cache = TTLCache(maxsize=cfg.CACHE_SIZE, ttl=cfg.CACHE_TTL)
|
| 48 |
+
analysis_cache = TTLCache(maxsize=cfg.CACHE_SIZE, ttl=cfg.CACHE_TTL)
|
| 49 |
+
rewrite_cache = TTLCache(maxsize=cfg.CACHE_SIZE, ttl=cfg.CACHE_TTL * 6)
|
app/config.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Centralized configuration with dual LLM backend support."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
from dotenv import load_dotenv
|
| 7 |
+
|
| 8 |
+
load_dotenv()
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Config:
|
| 12 |
+
"""All settings read from environment variables with sensible defaults."""
|
| 13 |
+
|
| 14 |
+
# Backend selection
|
| 15 |
+
LLM_BACKEND: str = os.getenv("LLM_BACKEND", "ollama")
|
| 16 |
+
|
| 17 |
+
# Hugging Face backend
|
| 18 |
+
HF_MODEL_NAME: str = os.getenv("HF_MODEL_NAME", "Qwen/Qwen2-7B-Instruct")
|
| 19 |
+
HF_DEVICE: str = os.getenv("HF_DEVICE", "auto")
|
| 20 |
+
HF_MAX_NEW_TOKENS: int = int(os.getenv("HF_MAX_NEW_TOKENS", 2048))
|
| 21 |
+
|
| 22 |
+
# Ollama backend
|
| 23 |
+
OLLAMA_HOST: str = os.getenv("OLLAMA_HOST", "http://localhost:11434")
|
| 24 |
+
OLLAMA_MODEL: str = os.getenv("OLLAMA_MODEL", "llama2")
|
| 25 |
+
|
| 26 |
+
# GGUF backend (llama-cpp-python)
|
| 27 |
+
GGUF_MODEL_PATH: str = os.getenv("GGUF_MODEL_PATH", "")
|
| 28 |
+
GGUF_N_CTX: int = int(os.getenv("GGUF_N_CTX", 4096))
|
| 29 |
+
GGUF_N_GPU_LAYERS: int = int(os.getenv("GGUF_N_GPU_LAYERS", -1))
|
| 30 |
+
|
| 31 |
+
# LM Studio backend
|
| 32 |
+
LMSTUDIO_URL: str = os.getenv("LMSTUDIO_URL", "http://localhost:1234")
|
| 33 |
+
LMSTUDIO_MODEL: str = os.getenv("LMSTUDIO_MODEL", "")
|
| 34 |
+
|
| 35 |
+
# Embedding model
|
| 36 |
+
EMBED_MODEL: str = os.getenv("EMBED_MODEL", "intfloat/multilingual-e5-large")
|
| 37 |
+
|
| 38 |
+
# Index & data
|
| 39 |
+
FAISS_INDEX: str = os.getenv("FAISS_INDEX", "QModel.index")
|
| 40 |
+
METADATA_FILE: str = os.getenv("METADATA_FILE", "metadata.json")
|
| 41 |
+
|
| 42 |
+
# Retrieval
|
| 43 |
+
TOP_K_SEARCH: int = int(os.getenv("TOP_K_SEARCH", 20))
|
| 44 |
+
TOP_K_RETURN: int = int(os.getenv("TOP_K_RETURN", 5))
|
| 45 |
+
|
| 46 |
+
# Generation
|
| 47 |
+
TEMPERATURE: float = float(os.getenv("TEMPERATURE", 0.2))
|
| 48 |
+
MAX_TOKENS: int = int(os.getenv("MAX_TOKENS", 2048))
|
| 49 |
+
|
| 50 |
+
# Caching
|
| 51 |
+
CACHE_SIZE: int = int(os.getenv("CACHE_SIZE", 512))
|
| 52 |
+
CACHE_TTL: int = int(os.getenv("CACHE_TTL", 3600))
|
| 53 |
+
|
| 54 |
+
# Ranking
|
| 55 |
+
RERANK_ALPHA: float = float(os.getenv("RERANK_ALPHA", 0.6))
|
| 56 |
+
HADITH_BOOST: float = float(os.getenv("HADITH_BOOST", 0.08))
|
| 57 |
+
|
| 58 |
+
# Safety
|
| 59 |
+
CONFIDENCE_THRESHOLD: float = float(os.getenv("CONFIDENCE_THRESHOLD", 0.30))
|
| 60 |
+
|
| 61 |
+
# CORS
|
| 62 |
+
ALLOWED_ORIGINS: str = os.getenv("ALLOWED_ORIGINS", "*")
|
| 63 |
+
|
| 64 |
+
MAX_EXAMPLES: int = int(os.getenv("MAX_EXAMPLES", 3))
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
cfg = Config()
|
app/llm.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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uggingFace backends."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import asyncio
|
| 6 |
+
import logging
|
| 7 |
+
from typing import List
|
| 8 |
+
|
| 9 |
+
from app.config import cfg
|
| 10 |
+
|
| 11 |
+
logger = logging.getLogger("qmodel.llm")
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class LLMProvider:
|
| 15 |
+
"""Abstract base for LLM providers."""
|
| 16 |
+
|
| 17 |
+
async def chat(
|
| 18 |
+
self, messages: List[dict], temperature: float, max_tokens: int
|
| 19 |
+
) -> str:
|
| 20 |
+
raise NotImplementedError
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class OllamaProvider(LLMProvider):
|
| 24 |
+
"""Ollama-based LLM provider."""
|
| 25 |
+
|
| 26 |
+
def __init__(self, host: str, model: str):
|
| 27 |
+
self.host = host
|
| 28 |
+
self.model = model
|
| 29 |
+
try:
|
| 30 |
+
import ollama
|
| 31 |
+
self.client = ollama.Client(host=host)
|
| 32 |
+
except ImportError:
|
| 33 |
+
raise ImportError("Install ollama: pip install ollama")
|
| 34 |
+
|
| 35 |
+
async def chat(
|
| 36 |
+
self, messages: List[dict], temperature: float, max_tokens: int
|
| 37 |
+
) -> str:
|
| 38 |
+
loop = asyncio.get_event_loop()
|
| 39 |
+
try:
|
| 40 |
+
result = await loop.run_in_executor(
|
| 41 |
+
None,
|
| 42 |
+
lambda: self.client.chat(
|
| 43 |
+
model=self.model,
|
| 44 |
+
messages=messages,
|
| 45 |
+
options={"temperature": temperature, "num_predict": max_tokens},
|
| 46 |
+
),
|
| 47 |
+
)
|
| 48 |
+
return result["message"]["content"].strip()
|
| 49 |
+
except Exception as exc:
|
| 50 |
+
logger.error("Ollama chat failed: %s", exc)
|
| 51 |
+
raise
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class GGUFProvider(LLMProvider):
|
| 55 |
+
"""llama-cpp-python GGUF provider — runs GGUF models directly in-process."""
|
| 56 |
+
|
| 57 |
+
def __init__(self, model_path: str, n_ctx: int = 4096, n_gpu_layers: int = -1):
|
| 58 |
+
try:
|
| 59 |
+
from llama_cpp import Llama
|
| 60 |
+
except ImportError:
|
| 61 |
+
raise ImportError("Install llama-cpp-python: pip install llama-cpp-python")
|
| 62 |
+
self.llm = Llama(
|
| 63 |
+
model_path=model_path,
|
| 64 |
+
n_ctx=n_ctx,
|
| 65 |
+
n_gpu_layers=n_gpu_layers,
|
| 66 |
+
verbose=False,
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
async def chat(
|
| 70 |
+
self, messages: List[dict], temperature: float, max_tokens: int
|
| 71 |
+
) -> str:
|
| 72 |
+
loop = asyncio.get_event_loop()
|
| 73 |
+
try:
|
| 74 |
+
result = await loop.run_in_executor(
|
| 75 |
+
None,
|
| 76 |
+
lambda: self.llm.create_chat_completion(
|
| 77 |
+
messages=messages,
|
| 78 |
+
temperature=temperature,
|
| 79 |
+
max_tokens=max_tokens,
|
| 80 |
+
),
|
| 81 |
+
)
|
| 82 |
+
return result["choices"][0]["message"]["content"].strip()
|
| 83 |
+
except Exception as exc:
|
| 84 |
+
logger.error("GGUF chat failed: %s", exc)
|
| 85 |
+
raise
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class LMStudioProvider(LLMProvider):
|
| 89 |
+
"""LM Studio provider — connects to LM Studio's OpenAI-compatible local API."""
|
| 90 |
+
|
| 91 |
+
def __init__(self, base_url: str, model: str):
|
| 92 |
+
self.base_url = base_url.rstrip("/")
|
| 93 |
+
self.model = model
|
| 94 |
+
|
| 95 |
+
async def chat(
|
| 96 |
+
self, messages: List[dict], temperature: float, max_tokens: int
|
| 97 |
+
) -> str:
|
| 98 |
+
import httpx
|
| 99 |
+
|
| 100 |
+
payload = {
|
| 101 |
+
"model": self.model,
|
| 102 |
+
"messages": messages,
|
| 103 |
+
"temperature": temperature,
|
| 104 |
+
"max_tokens": max_tokens,
|
| 105 |
+
}
|
| 106 |
+
try:
|
| 107 |
+
async with httpx.AsyncClient(timeout=120) as client:
|
| 108 |
+
resp = await client.post(
|
| 109 |
+
f"{self.base_url}/v1/chat/completions", json=payload
|
| 110 |
+
)
|
| 111 |
+
resp.raise_for_status()
|
| 112 |
+
data = resp.json()
|
| 113 |
+
return data["choices"][0]["message"]["content"].strip()
|
| 114 |
+
except Exception as exc:
|
| 115 |
+
logger.error("LM Studio chat failed: %s", exc)
|
| 116 |
+
raise
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class HuggingFaceProvider(LLMProvider):
|
| 120 |
+
"""Hugging Face transformers-based LLM provider."""
|
| 121 |
+
|
| 122 |
+
def __init__(self, model_name: str, device: str):
|
| 123 |
+
self.model_name = model_name
|
| 124 |
+
self.device = device
|
| 125 |
+
try:
|
| 126 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, TextGenerationPipeline
|
| 127 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 128 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
| 129 |
+
model_name,
|
| 130 |
+
device_map=device,
|
| 131 |
+
torch_dtype="auto",
|
| 132 |
+
)
|
| 133 |
+
self.pipeline = TextGenerationPipeline(
|
| 134 |
+
model=self.model,
|
| 135 |
+
tokenizer=self.tokenizer,
|
| 136 |
+
device=0 if device != "cpu" else None,
|
| 137 |
+
)
|
| 138 |
+
except ImportError:
|
| 139 |
+
raise ImportError("Install transformers: pip install transformers torch")
|
| 140 |
+
|
| 141 |
+
async def chat(
|
| 142 |
+
self, messages: List[dict], temperature: float, max_tokens: int
|
| 143 |
+
) -> str:
|
| 144 |
+
prompt = self._format_messages(messages)
|
| 145 |
+
loop = asyncio.get_event_loop()
|
| 146 |
+
try:
|
| 147 |
+
result = await loop.run_in_executor(
|
| 148 |
+
None,
|
| 149 |
+
lambda: self.pipeline(
|
| 150 |
+
prompt,
|
| 151 |
+
max_new_tokens=max_tokens,
|
| 152 |
+
temperature=temperature,
|
| 153 |
+
do_sample=temperature > 0,
|
| 154 |
+
),
|
| 155 |
+
)
|
| 156 |
+
generated = result[0]["generated_text"]
|
| 157 |
+
output = generated[len(prompt):].strip()
|
| 158 |
+
return output
|
| 159 |
+
except Exception as exc:
|
| 160 |
+
logger.error("HF chat failed: %s", exc)
|
| 161 |
+
raise
|
| 162 |
+
|
| 163 |
+
def _format_messages(self, messages: List[dict]) -> str:
|
| 164 |
+
prompt = ""
|
| 165 |
+
for msg in messages:
|
| 166 |
+
role = msg["role"]
|
| 167 |
+
content = msg["content"]
|
| 168 |
+
if role == "system":
|
| 169 |
+
prompt += f"{content}\n\n"
|
| 170 |
+
elif role == "user":
|
| 171 |
+
prompt += f"User: {content}\n"
|
| 172 |
+
elif role == "assistant":
|
| 173 |
+
prompt += f"Assistant: {content}\n"
|
| 174 |
+
prompt += "Assistant: "
|
| 175 |
+
return prompt
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def get_llm_provider() -> LLMProvider:
|
| 179 |
+
"""Factory function to get the configured LLM provider."""
|
| 180 |
+
if cfg.LLM_BACKEND == "ollama":
|
| 181 |
+
logger.info("Using Ollama backend: %s @ %s", cfg.OLLAMA_MODEL, cfg.OLLAMA_HOST)
|
| 182 |
+
return OllamaProvider(cfg.OLLAMA_HOST, cfg.OLLAMA_MODEL)
|
| 183 |
+
elif cfg.LLM_BACKEND == "hf":
|
| 184 |
+
logger.info("Using HuggingFace backend: %s on %s", cfg.HF_MODEL_NAME, cfg.HF_DEVICE)
|
| 185 |
+
return HuggingFaceProvider(cfg.HF_MODEL_NAME, cfg.HF_DEVICE)
|
| 186 |
+
elif cfg.LLM_BACKEND == "gguf":
|
| 187 |
+
logger.info("Using GGUF backend: %s (ctx=%d, gpu_layers=%d)",
|
| 188 |
+
cfg.GGUF_MODEL_PATH, cfg.GGUF_N_CTX, cfg.GGUF_N_GPU_LAYERS)
|
| 189 |
+
return GGUFProvider(cfg.GGUF_MODEL_PATH, cfg.GGUF_N_CTX, cfg.GGUF_N_GPU_LAYERS)
|
| 190 |
+
elif cfg.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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pydantic schemas for request / response models."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from typing import Dict, List, Optional
|
| 6 |
+
|
| 7 |
+
from pydantic import BaseModel, Field
|
| 8 |
+
|
| 9 |
+
from app.config import cfg
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 13 |
+
# CORE SCHEMAS
|
| 14 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 15 |
+
class ChatMessage(BaseModel):
|
| 16 |
+
role: str = Field(..., pattern="^(system|user|assistant)$")
|
| 17 |
+
content: str = Field(..., min_length=1, max_length=4000)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class AnalysisResult(BaseModel):
|
| 21 |
+
keyword: str
|
| 22 |
+
kw_stemmed: str
|
| 23 |
+
total_count: int
|
| 24 |
+
by_surah: Dict[int, Dict]
|
| 25 |
+
examples: List[dict]
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class SourceItem(BaseModel):
|
| 29 |
+
source: str
|
| 30 |
+
type: str
|
| 31 |
+
grade: Optional[str] = None
|
| 32 |
+
arabic: str
|
| 33 |
+
english: str
|
| 34 |
+
_score: float
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class AskResponse(BaseModel):
|
| 38 |
+
question: str
|
| 39 |
+
answer: str
|
| 40 |
+
language: str
|
| 41 |
+
intent: str
|
| 42 |
+
analysis: Optional[AnalysisResult] = None
|
| 43 |
+
sources: List[SourceItem]
|
| 44 |
+
top_score: float
|
| 45 |
+
latency_ms: int
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class HadithVerifyResponse(BaseModel):
|
| 49 |
+
query: str
|
| 50 |
+
found: bool
|
| 51 |
+
collection: Optional[str] = None
|
| 52 |
+
grade: Optional[str] = None
|
| 53 |
+
reference: Optional[str] = None
|
| 54 |
+
arabic: Optional[str] = None
|
| 55 |
+
english: Optional[str] = None
|
| 56 |
+
latency_ms: int
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 60 |
+
# OPENAI-COMPATIBLE SCHEMAS
|
| 61 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 62 |
+
class ChatCompletionMessage(BaseModel):
|
| 63 |
+
role: str = Field(..., description="Message role: system, user, or assistant")
|
| 64 |
+
content: str = Field(..., description="Message content")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class ChatCompletionRequest(BaseModel):
|
| 68 |
+
model: str = Field(default="QModel", description="Model name")
|
| 69 |
+
messages: List[ChatCompletionMessage] = Field(..., description="Messages")
|
| 70 |
+
temperature: Optional[float] = Field(default=cfg.TEMPERATURE, ge=0.0, le=2.0)
|
| 71 |
+
top_p: Optional[float] = Field(default=1.0, ge=0.0, le=1.0)
|
| 72 |
+
max_tokens: Optional[int] = Field(default=cfg.MAX_TOKENS, ge=1, le=8000)
|
| 73 |
+
top_k: Optional[int] = Field(default=5, ge=1, le=20, description="Islamic sources to retrieve")
|
| 74 |
+
stream: Optional[bool] = Field(default=False, description="Enable streaming responses")
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class ChatCompletionChoice(BaseModel):
|
| 78 |
+
index: int
|
| 79 |
+
message: ChatCompletionMessage
|
| 80 |
+
finish_reason: str = "stop"
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class ChatCompletionResponse(BaseModel):
|
| 84 |
+
id: str
|
| 85 |
+
object: str = "chat.completion"
|
| 86 |
+
created: int
|
| 87 |
+
model: str
|
| 88 |
+
choices: List[ChatCompletionChoice]
|
| 89 |
+
usage: dict
|
| 90 |
+
x_metadata: Optional[dict] = None
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class ModelInfo(BaseModel):
|
| 94 |
+
id: str
|
| 95 |
+
object: str = "model"
|
| 96 |
+
created: int
|
| 97 |
+
owned_by: str = "elgendy"
|
| 98 |
+
permission: List[dict] = Field(default_factory=list)
|
| 99 |
+
root: Optional[str] = None
|
| 100 |
+
parent: Optional[str] = None
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class ModelsListResponse(BaseModel):
|
| 104 |
+
object: str = "list"
|
| 105 |
+
data: List[ModelInfo]
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 109 |
+
# NEW ENDPOINT SCHEMAS
|
| 110 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 111 |
+
class VerseItem(BaseModel):
|
| 112 |
+
surah_number: Optional[int] = None
|
| 113 |
+
surah_name_ar: str = ""
|
| 114 |
+
surah_name_en: str = ""
|
| 115 |
+
surah_name_transliteration: str = ""
|
| 116 |
+
ayah: Optional[int] = None
|
| 117 |
+
arabic: str = ""
|
| 118 |
+
english: str = ""
|
| 119 |
+
transliteration: str = ""
|
| 120 |
+
tafsir_en: str = ""
|
| 121 |
+
tafsir_ar: str = ""
|
| 122 |
+
source: str = ""
|
| 123 |
+
revelation_type: str = ""
|
| 124 |
+
score: Optional[float] = None
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class HadithItem(BaseModel):
|
| 128 |
+
collection: str = ""
|
| 129 |
+
reference: str = ""
|
| 130 |
+
hadith_number: Optional[int] = None
|
| 131 |
+
chapter: str = ""
|
| 132 |
+
arabic: str = ""
|
| 133 |
+
english: str = ""
|
| 134 |
+
grade: Optional[str] = None
|
| 135 |
+
author: str = ""
|
| 136 |
+
score: Optional[float] = None
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class TextSearchResponse(BaseModel):
|
| 140 |
+
query: str
|
| 141 |
+
count: int
|
| 142 |
+
results: List[dict]
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class ChapterResponse(BaseModel):
|
| 146 |
+
surah_number: int
|
| 147 |
+
surah_name_ar: str
|
| 148 |
+
surah_name_en: str
|
| 149 |
+
surah_name_transliteration: str
|
| 150 |
+
revelation_type: str
|
| 151 |
+
total_verses: int
|
| 152 |
+
verses: List[dict]
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
class QuranAnalyticsResponse(BaseModel):
|
| 156 |
+
total_verses_in_dataset: int
|
| 157 |
+
total_surahs: int
|
| 158 |
+
meccan_surahs: int
|
| 159 |
+
medinan_surahs: int
|
| 160 |
+
surahs: List[dict]
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class HadithAnalyticsResponse(BaseModel):
|
| 164 |
+
total_hadiths: int
|
| 165 |
+
collections: List[dict]
|
| 166 |
+
grade_summary: dict
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class WordFrequencyResponse(BaseModel):
|
| 170 |
+
keyword: str
|
| 171 |
+
kw_stemmed: str
|
| 172 |
+
total_count: int
|
| 173 |
+
by_surah: dict
|
| 174 |
+
examples: List[dict]
|
app/prompts.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Prompt engineering — system templates and message builders."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from typing import Dict, List, Optional
|
| 6 |
+
|
| 7 |
+
from app.arabic_nlp import language_instruction
|
| 8 |
+
|
| 9 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 10 |
+
# PROMPT TEMPLATES
|
| 11 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 12 |
+
PERSONA = (
|
| 13 |
+
"You are Sheikh QModel, a meticulous Islamic scholar with expertise "
|
| 14 |
+
"in Tafsir (Quranic exegesis), Hadith sciences, Fiqh, and Arabic. "
|
| 15 |
+
"You respond with scholarly rigor and modern clarity."
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
TASK_INSTRUCTIONS: Dict[str, str] = {
|
| 19 |
+
"tafsir": (
|
| 20 |
+
"The user asks about a Quranic verse. Steps:\n"
|
| 21 |
+
"1. Identify the verse(s) from context.\n"
|
| 22 |
+
"2. Provide Tafsir: linguistic analysis and deeper meaning.\n"
|
| 23 |
+
"3. Draw connections to related verses.\n"
|
| 24 |
+
"4. Answer the user's question directly."
|
| 25 |
+
),
|
| 26 |
+
"hadith": (
|
| 27 |
+
"The user asks about a Hadith. Structure your answer:\n\n"
|
| 28 |
+
"1. الجواب — Give a direct answer to the question first.\n\n"
|
| 29 |
+
"2. نص الحديث — Quote the hadith text EXACTLY from context\n"
|
| 30 |
+
" in the evidence box format. Show ALL relevant narrations found.\n\n"
|
| 31 |
+
"3. الشرح والتوضيح — Explain the meaning and implications.\n"
|
| 32 |
+
" Mention notable scholars, narrators, or jurisprudential points.\n"
|
| 33 |
+
" Draw connections to related Hadiths from the context.\n\n"
|
| 34 |
+
"4. الخلاصة — Summarize the key takeaway.\n\n"
|
| 35 |
+
"CRITICAL: If the Hadith is NOT in context, say so clearly.\n"
|
| 36 |
+
"Quote hadith text VERBATIM from context — never paraphrase the matn."
|
| 37 |
+
),
|
| 38 |
+
"auth": (
|
| 39 |
+
"The user asks about Hadith authenticity. Structure your answer:\n\n"
|
| 40 |
+
"الجواب — Start with a CLEAR, CONFIDENT verdict (صحيح/حسن/ضعيف/موضوع).\n"
|
| 41 |
+
"Give a one-line ruling summary.\n\n"
|
| 42 |
+
"أولًا: متن الحديث\n"
|
| 43 |
+
"Quote ALL matching narrations from the context in evidence boxes.\n"
|
| 44 |
+
"Show every relevant version found across different collections.\n\n"
|
| 45 |
+
"ثانيًا: الأدلة على صحته (أو ضعفه)\n"
|
| 46 |
+
"Provide numbered evidence points (use ١، ٢، ٣):\n"
|
| 47 |
+
" - Which authoritative collections contain it\n"
|
| 48 |
+
" - The grading given by scholars (from the grade field in context)\n"
|
| 49 |
+
" - Notable narrators and scholars who transmitted or commented on it\n\n"
|
| 50 |
+
"ثالثًا: أهمية الحديث\n"
|
| 51 |
+
"Explain the hadith's significance, its place in Islamic scholarship,\n"
|
| 52 |
+
"and any jurisprudential implications.\n\n"
|
| 53 |
+
"الخلاصة — Comprehensive summary restating the verdict with key evidence.\n\n"
|
| 54 |
+
"RULES:\n"
|
| 55 |
+
"• If found in Sahih Bukhari or Sahih Muslim → assert AUTHENTIC (Sahih).\n"
|
| 56 |
+
"• Quote hadith text VERBATIM from context — never paraphrase the matn.\n"
|
| 57 |
+
"• You may add scholarly commentary to explain significance and context.\n"
|
| 58 |
+
"• If NOT found in context → clearly state it is absent from the dataset.\n"
|
| 59 |
+
"• NEVER fabricate hadith text, grades, or source citations."
|
| 60 |
+
),
|
| 61 |
+
"fatwa": (
|
| 62 |
+
"The user seeks a religious ruling. Steps:\n"
|
| 63 |
+
"1. Gather evidence from Quran + Sunnah in context.\n"
|
| 64 |
+
"2. Reason step-by-step to a conclusion.\n"
|
| 65 |
+
"3. If insufficient, state so explicitly."
|
| 66 |
+
),
|
| 67 |
+
"count": (
|
| 68 |
+
"The user asks for word frequency. Steps:\n"
|
| 69 |
+
"1. State the ANALYSIS RESULT prominently.\n"
|
| 70 |
+
"2. List example occurrences with Surah names.\n"
|
| 71 |
+
"3. Comment on significance."
|
| 72 |
+
),
|
| 73 |
+
"surah_info": (
|
| 74 |
+
"The user asks about surah metadata. Steps:\n"
|
| 75 |
+
"1. State the answer from the SURAH INFORMATION block EXACTLY.\n"
|
| 76 |
+
"2. Use the total_verses number precisely — do NOT guess or calculate.\n"
|
| 77 |
+
"3. Mention the revelation type (Meccan/Medinan) if available.\n"
|
| 78 |
+
"4. Optionally add brief scholarly context about the surah."
|
| 79 |
+
),
|
| 80 |
+
"general": (
|
| 81 |
+
"The user has a general Islamic question. Structure your answer:\n\n"
|
| 82 |
+
"1. الجواب — Give a direct, clear answer first.\n\n"
|
| 83 |
+
"2. الأدلة — Support with evidence from context, quoting relevant\n"
|
| 84 |
+
" texts in evidence boxes. Explain the evidence with scholarly depth.\n\n"
|
| 85 |
+
"3. الخلاصة — Conclude with a comprehensive summary."
|
| 86 |
+
),
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
FORMAT_RULES = """\
|
| 90 |
+
For EVERY supporting evidence, use this exact format:
|
| 91 |
+
|
| 92 |
+
┌─────────────────────────────────────────────┐
|
| 93 |
+
│ ❝ {Arabic text} ❞
|
| 94 |
+
│ 📝 Translation: {English translation}
|
| 95 |
+
│ 📖 Source: {exact citation from context}
|
| 96 |
+
└─────────────────────────────────────────────┘
|
| 97 |
+
|
| 98 |
+
ABSOLUTE RULES:
|
| 99 |
+
• Copy Arabic hadith text, translations, and sources VERBATIM from context. Never paraphrase.
|
| 100 |
+
• You may add scholarly commentary, explanation, and analysis around the quoted evidence.
|
| 101 |
+
• NEVER fabricate hadith text, grades, verse numbers, or source citations.
|
| 102 |
+
• If a specific Hadith/verse is NOT in context → respond with:
|
| 103 |
+
"هذا الحديث/الآية غير موجود في قاعدة البيانات." (Arabic)
|
| 104 |
+
or "This Hadith/verse is not in the available dataset." (English)
|
| 105 |
+
• Never invent or guess content.
|
| 106 |
+
• End with: "والله أعلم." (Arabic) or "And Allah knows best." (English)
|
| 107 |
+
"""
|
| 108 |
+
|
| 109 |
+
_SYSTEM_TEMPLATE = """\
|
| 110 |
+
{persona}
|
| 111 |
+
|
| 112 |
+
{lang_instruction}
|
| 113 |
+
|
| 114 |
+
=== YOUR TASK ===
|
| 115 |
+
{task}
|
| 116 |
+
|
| 117 |
+
=== OUTPUT FORMAT ===
|
| 118 |
+
{fmt}
|
| 119 |
+
"""
|
| 120 |
+
|
| 121 |
+
_CONTEXT_TEMPLATE = """\
|
| 122 |
+
IMPORTANT: The database has already been searched for you.
|
| 123 |
+
The relevant results are provided below — use ONLY this data to formulate your answer.
|
| 124 |
+
Do NOT state that you need a database or ask the user for data. Answer from the context below.
|
| 125 |
+
|
| 126 |
+
=== RETRIEVED DATABASE RESULTS ===
|
| 127 |
+
{context}
|
| 128 |
+
=== END DATABASE RESULTS ===
|
| 129 |
+
|
| 130 |
+
Now answer the following question using ONLY the data above:
|
| 131 |
+
"""
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def build_messages(
|
| 135 |
+
context: str,
|
| 136 |
+
question: str,
|
| 137 |
+
lang: str,
|
| 138 |
+
intent: str,
|
| 139 |
+
analysis: Optional[dict] = None,
|
| 140 |
+
surah_info: Optional[dict] = None,
|
| 141 |
+
) -> List[dict]:
|
| 142 |
+
"""Build system and user messages for LLM."""
|
| 143 |
+
if surah_info:
|
| 144 |
+
info_block = (
|
| 145 |
+
f"\n[SURAH INFORMATION]\n"
|
| 146 |
+
f"Surah Name (Arabic): {surah_info['surah_name_ar']}\n"
|
| 147 |
+
f"Surah Name (English): {surah_info['surah_name_en']}\n"
|
| 148 |
+
f"Surah Number: {surah_info['surah_number']}\n"
|
| 149 |
+
f"Total Verses: {surah_info['total_verses']}\n"
|
| 150 |
+
f"Revelation Type: {surah_info['revelation_type']}\n"
|
| 151 |
+
f"Transliteration: {surah_info['surah_name_transliteration']}\n"
|
| 152 |
+
)
|
| 153 |
+
context = info_block + context
|
| 154 |
+
|
| 155 |
+
if analysis:
|
| 156 |
+
by_surah_str = "\n ".join([
|
| 157 |
+
f"Surah {s}: {data['name']} ({data['count']} times)"
|
| 158 |
+
for s, data in analysis["by_surah"].items()
|
| 159 |
+
])
|
| 160 |
+
analysis_block = (
|
| 161 |
+
f"\n[ANALYSIS RESULT]\n"
|
| 162 |
+
f"The keyword «{analysis['keyword']}» appears {analysis['total_count']} times.\n"
|
| 163 |
+
f" {by_surah_str}\n"
|
| 164 |
+
)
|
| 165 |
+
context = analysis_block + context
|
| 166 |
+
|
| 167 |
+
system = _SYSTEM_TEMPLATE.format(
|
| 168 |
+
persona=PERSONA,
|
| 169 |
+
lang_instruction=language_instruction(lang),
|
| 170 |
+
task=TASK_INSTRUCTIONS.get(intent, TASK_INSTRUCTIONS["general"]),
|
| 171 |
+
fmt=FORMAT_RULES,
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
context_block = _CONTEXT_TEMPLATE.format(context=context)
|
| 175 |
+
|
| 176 |
+
cot = {
|
| 177 |
+
"arabic": "فكّر خطوةً بخطوة، ثم أجب: ",
|
| 178 |
+
"mixed": "Think step by step: ",
|
| 179 |
+
}.get(lang, "Think step by step: ")
|
| 180 |
+
|
| 181 |
+
return [
|
| 182 |
+
{"role": "system", "content": system},
|
| 183 |
+
{"role": "user", "content": context_block + cot + question},
|
| 184 |
+
]
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def not_found_answer(lang: str) -> str:
|
| 188 |
+
"""Safe fallback when confidence is too low."""
|
| 189 |
+
if lang == "arabic":
|
| 190 |
+
return (
|
| 191 |
+
"لم أجد في قاعدة البيانات ما يكفي للإجابة على هذا السؤال بدقة.\n"
|
| 192 |
+
"يُرجى الرجوع إلى مصادر إسلامية موثوقة.\n"
|
| 193 |
+
"والله أعلم."
|
| 194 |
+
)
|
| 195 |
+
return (
|
| 196 |
+
"The available dataset does not contain sufficient information to answer "
|
| 197 |
+
"this question accurately.\nPlease refer to trusted Islamic sources.\n"
|
| 198 |
+
"And Allah knows best."
|
| 199 |
+
)
|
app/routers/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""QModel API routers."""
|
app/routers/chat.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
+
import logging
|
| 7 |
+
import time
|
| 8 |
+
from typing import Optional
|
| 9 |
+
|
| 10 |
+
from fastapi import APIRouter, HTTPException, Query
|
| 11 |
+
from fastapi.responses import StreamingResponse
|
| 12 |
+
|
| 13 |
+
from app.config import cfg
|
| 14 |
+
from app.models import (
|
| 15 |
+
AskResponse,
|
| 16 |
+
ChatCompletionChoice,
|
| 17 |
+
ChatCompletionMessage,
|
| 18 |
+
ChatCompletionRequest,
|
| 19 |
+
ChatCompletionResponse,
|
| 20 |
+
SourceItem,
|
| 21 |
+
)
|
| 22 |
+
from app.state import check_ready, run_rag_pipeline, state
|
| 23 |
+
|
| 24 |
+
logger = logging.getLogger("qmodel.chat")
|
| 25 |
+
|
| 26 |
+
router = APIRouter(tags=["inference"])
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# ───────────────────────────────────────────────────────
|
| 30 |
+
# POST /v1/chat/completions — OpenAI-compatible
|
| 31 |
+
# ───────────────────────────────────────────────────────
|
| 32 |
+
@router.post("/v1/chat/completions", response_model=ChatCompletionResponse)
|
| 33 |
+
async def chat_completions(request: ChatCompletionRequest):
|
| 34 |
+
"""OpenAI-compatible chat completions endpoint (for Open-WebUI integration)."""
|
| 35 |
+
check_ready()
|
| 36 |
+
|
| 37 |
+
user_messages = [m.content for m in request.messages if m.role == "user"]
|
| 38 |
+
if not user_messages:
|
| 39 |
+
raise HTTPException(status_code=400, detail="No user message in request")
|
| 40 |
+
|
| 41 |
+
question = user_messages[-1]
|
| 42 |
+
top_k = request.top_k or cfg.TOP_K_RETURN
|
| 43 |
+
|
| 44 |
+
try:
|
| 45 |
+
result = await run_rag_pipeline(question, top_k=top_k)
|
| 46 |
+
except HTTPException:
|
| 47 |
+
raise
|
| 48 |
+
except Exception as exc:
|
| 49 |
+
logger.error("Pipeline error: %s", exc)
|
| 50 |
+
raise HTTPException(status_code=500, detail="Internal pipeline error")
|
| 51 |
+
|
| 52 |
+
if request.stream:
|
| 53 |
+
return StreamingResponse(
|
| 54 |
+
_stream_response(result, request.model),
|
| 55 |
+
media_type="text/event-stream",
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
return ChatCompletionResponse(
|
| 59 |
+
id=f"qmodel-{int(time.time() * 1000)}",
|
| 60 |
+
created=int(time.time()),
|
| 61 |
+
model=request.model,
|
| 62 |
+
choices=[
|
| 63 |
+
ChatCompletionChoice(
|
| 64 |
+
index=0,
|
| 65 |
+
message=ChatCompletionMessage(
|
| 66 |
+
role="assistant",
|
| 67 |
+
content=result["answer"],
|
| 68 |
+
),
|
| 69 |
+
)
|
| 70 |
+
],
|
| 71 |
+
usage={
|
| 72 |
+
"prompt_tokens": -1,
|
| 73 |
+
"completion_tokens": -1,
|
| 74 |
+
"total_tokens": -1,
|
| 75 |
+
},
|
| 76 |
+
x_metadata={
|
| 77 |
+
"language": result["language"],
|
| 78 |
+
"intent": result["intent"],
|
| 79 |
+
"top_score": round(result["top_score"], 4),
|
| 80 |
+
"latency_ms": result["latency_ms"],
|
| 81 |
+
"sources_count": len(result["sources"]),
|
| 82 |
+
"sources": [
|
| 83 |
+
{
|
| 84 |
+
"source": s.get("source") or s.get("reference", ""),
|
| 85 |
+
"type": s.get("type", ""),
|
| 86 |
+
"grade": s.get("grade"),
|
| 87 |
+
"score": round(s.get("_score", 0), 4),
|
| 88 |
+
}
|
| 89 |
+
for s in result.get("sources", [])[:5]
|
| 90 |
+
],
|
| 91 |
+
"analysis": result.get("analysis"),
|
| 92 |
+
},
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
async def _stream_response(result: dict, model: str):
|
| 97 |
+
"""Stream response chunks in OpenAI SSE format."""
|
| 98 |
+
answer = result.get("answer", "")
|
| 99 |
+
for line in answer.split("\n"):
|
| 100 |
+
chunk = {
|
| 101 |
+
"id": f"qmodel-{int(time.time() * 1000)}",
|
| 102 |
+
"object": "chat.completion.chunk",
|
| 103 |
+
"created": int(time.time()),
|
| 104 |
+
"model": model,
|
| 105 |
+
"choices": [{
|
| 106 |
+
"index": 0,
|
| 107 |
+
"delta": {"content": line + "\n"},
|
| 108 |
+
"finish_reason": None,
|
| 109 |
+
}],
|
| 110 |
+
}
|
| 111 |
+
yield f"data: {json.dumps(chunk)}\n\n"
|
| 112 |
+
|
| 113 |
+
final = {
|
| 114 |
+
"id": f"qmodel-{int(time.time() * 1000)}",
|
| 115 |
+
"object": "chat.completion.chunk",
|
| 116 |
+
"created": int(time.time()),
|
| 117 |
+
"model": model,
|
| 118 |
+
"choices": [{
|
| 119 |
+
"index": 0,
|
| 120 |
+
"delta": {},
|
| 121 |
+
"finish_reason": "stop",
|
| 122 |
+
}],
|
| 123 |
+
}
|
| 124 |
+
yield f"data: {json.dumps(final)}\n\n"
|
| 125 |
+
yield "data: [DONE]\n\n"
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
# ───────────────────────────────────────────────────────
|
| 129 |
+
# GET /ask — main inference endpoint
|
| 130 |
+
# ───────────────────────────────────────────────────────
|
| 131 |
+
@router.get("/ask", response_model=AskResponse)
|
| 132 |
+
async def ask(
|
| 133 |
+
q: str = Query(..., min_length=1, max_length=1000, description="Your Islamic question"),
|
| 134 |
+
top_k: int = Query(cfg.TOP_K_RETURN, ge=1, le=20, description="Number of sources"),
|
| 135 |
+
source_type: Optional[str] = Query(None, description="Filter: quran|hadith"),
|
| 136 |
+
grade_filter: Optional[str] = Query(None, description="Filter Hadith: sahih|hasan|all"),
|
| 137 |
+
):
|
| 138 |
+
"""Main inference endpoint — runs the full RAG pipeline."""
|
| 139 |
+
check_ready()
|
| 140 |
+
result = await run_rag_pipeline(q, top_k, source_type, grade_filter)
|
| 141 |
+
|
| 142 |
+
sources = [
|
| 143 |
+
SourceItem(
|
| 144 |
+
source=r.get("source") or r.get("reference") or "Unknown",
|
| 145 |
+
type=r.get("type", "unknown"),
|
| 146 |
+
grade=r.get("grade"),
|
| 147 |
+
arabic=r.get("arabic", ""),
|
| 148 |
+
english=r.get("english", ""),
|
| 149 |
+
_score=r.get("_score", 0.0),
|
| 150 |
+
)
|
| 151 |
+
for r in result["sources"]
|
| 152 |
+
]
|
| 153 |
+
|
| 154 |
+
return AskResponse(
|
| 155 |
+
question=q,
|
| 156 |
+
answer=result["answer"],
|
| 157 |
+
language=result["language"],
|
| 158 |
+
intent=result["intent"],
|
| 159 |
+
analysis=result["analysis"],
|
| 160 |
+
sources=sources,
|
| 161 |
+
top_score=result["top_score"],
|
| 162 |
+
latency_ms=result["latency_ms"],
|
| 163 |
+
)
|
app/routers/hadith.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Hadith endpoints — search, topic, verify, collection browse, analytics."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import time
|
| 6 |
+
from typing import Optional
|
| 7 |
+
|
| 8 |
+
from fastapi import APIRouter, HTTPException, Query
|
| 9 |
+
|
| 10 |
+
from app.analysis import get_hadith_analytics
|
| 11 |
+
from app.models import (
|
| 12 |
+
HadithAnalyticsResponse,
|
| 13 |
+
HadithVerifyResponse,
|
| 14 |
+
TextSearchResponse,
|
| 15 |
+
)
|
| 16 |
+
from app.search import hybrid_search, rewrite_query, text_search
|
| 17 |
+
from app.state import check_ready, state
|
| 18 |
+
|
| 19 |
+
router = APIRouter(prefix="/hadith", tags=["hadith"])
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
# ───────────────────────────────────────────────────────
|
| 23 |
+
# GET /hadith/search — text-based hadith lookup (#5)
|
| 24 |
+
# ───────────────────────────────────────────────────────
|
| 25 |
+
@router.get("/search", response_model=TextSearchResponse)
|
| 26 |
+
async def hadith_text_search(
|
| 27 |
+
q: str = Query(..., min_length=1, max_length=500, description="Text to search for (Arabic or English)"),
|
| 28 |
+
collection: Optional[str] = Query(None, description="Filter by collection name (e.g. bukhari, muslim)"),
|
| 29 |
+
limit: int = Query(10, ge=1, le=50),
|
| 30 |
+
):
|
| 31 |
+
"""Search for Hadith by partial text match (Arabic or English).
|
| 32 |
+
|
| 33 |
+
Performs exact substring matching plus word-overlap scoring.
|
| 34 |
+
Use this to find a hadith when you know part of the text.
|
| 35 |
+
"""
|
| 36 |
+
check_ready()
|
| 37 |
+
results = text_search(q, state.dataset, source_type="hadith", limit=limit)
|
| 38 |
+
|
| 39 |
+
# Optional collection filter
|
| 40 |
+
if collection:
|
| 41 |
+
col_lower = collection.lower()
|
| 42 |
+
results = [
|
| 43 |
+
r for r in results
|
| 44 |
+
if col_lower in (r.get("collection", "") or r.get("reference", "")).lower()
|
| 45 |
+
]
|
| 46 |
+
|
| 47 |
+
return TextSearchResponse(
|
| 48 |
+
query=q,
|
| 49 |
+
count=len(results),
|
| 50 |
+
results=[
|
| 51 |
+
{
|
| 52 |
+
"collection": r.get("collection", ""),
|
| 53 |
+
"reference": r.get("reference", ""),
|
| 54 |
+
"hadith_number": r.get("hadith_number"),
|
| 55 |
+
"chapter": r.get("chapter", ""),
|
| 56 |
+
"arabic": r.get("arabic", ""),
|
| 57 |
+
"english": r.get("english", ""),
|
| 58 |
+
"grade": r.get("grade"),
|
| 59 |
+
"score": round(r.get("_score", 0), 4),
|
| 60 |
+
}
|
| 61 |
+
for r in results
|
| 62 |
+
],
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
# ───────────────────────────────────────────────────────
|
| 67 |
+
# GET /hadith/topic — semantic topic search (#6)
|
| 68 |
+
# ───────────────────────────────────────────────────────
|
| 69 |
+
@router.get("/topic", response_model=TextSearchResponse)
|
| 70 |
+
async def hadith_topic_search(
|
| 71 |
+
topic: str = Query(..., min_length=1, max_length=500, description="Topic or theme to search for"),
|
| 72 |
+
top_k: int = Query(10, ge=1, le=20),
|
| 73 |
+
grade_filter: Optional[str] = Query(None, description="Grade filter: sahih|hasan|all"),
|
| 74 |
+
):
|
| 75 |
+
"""Search for Hadith related to a topic/theme using semantic search."""
|
| 76 |
+
check_ready()
|
| 77 |
+
rewrite = await rewrite_query(topic, state.llm)
|
| 78 |
+
results = await hybrid_search(
|
| 79 |
+
topic, rewrite,
|
| 80 |
+
state.embed_model, state.faiss_index, state.dataset,
|
| 81 |
+
top_n=top_k, source_type="hadith", grade_filter=grade_filter,
|
| 82 |
+
)
|
| 83 |
+
return TextSearchResponse(
|
| 84 |
+
query=topic,
|
| 85 |
+
count=len(results),
|
| 86 |
+
results=[
|
| 87 |
+
{
|
| 88 |
+
"collection": r.get("collection", ""),
|
| 89 |
+
"reference": r.get("reference", ""),
|
| 90 |
+
"hadith_number": r.get("hadith_number"),
|
| 91 |
+
"chapter": r.get("chapter", ""),
|
| 92 |
+
"arabic": r.get("arabic", ""),
|
| 93 |
+
"english": r.get("english", ""),
|
| 94 |
+
"grade": r.get("grade"),
|
| 95 |
+
"score": round(r.get("_score", 0), 4),
|
| 96 |
+
}
|
| 97 |
+
for r in results
|
| 98 |
+
],
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
# ───────────────────────────────────────────────────────
|
| 103 |
+
# GET /hadith/verify — authenticity check (#7)
|
| 104 |
+
# ───────────────────────────────────────────────────────
|
| 105 |
+
@router.get("/verify", response_model=HadithVerifyResponse)
|
| 106 |
+
async def verify_hadith(
|
| 107 |
+
q: str = Query(..., description="Hadith text or first few words"),
|
| 108 |
+
collection: Optional[str] = Query(None, description="Filter: bukhari|muslim|all"),
|
| 109 |
+
):
|
| 110 |
+
"""Verify if a Hadith is in authenticated collections and check its grade.
|
| 111 |
+
|
| 112 |
+
Uses both semantic search and text matching for best accuracy.
|
| 113 |
+
"""
|
| 114 |
+
check_ready()
|
| 115 |
+
t0 = time.perf_counter()
|
| 116 |
+
|
| 117 |
+
# 1. Try text search first for exact matches
|
| 118 |
+
text_results = text_search(q, state.dataset, source_type="hadith", limit=5)
|
| 119 |
+
if collection:
|
| 120 |
+
col_lower = collection.lower()
|
| 121 |
+
text_results = [
|
| 122 |
+
r for r in text_results
|
| 123 |
+
if col_lower in (r.get("collection", "") or r.get("reference", "")).lower()
|
| 124 |
+
]
|
| 125 |
+
|
| 126 |
+
# 2. Also try semantic search
|
| 127 |
+
semantic_results = await hybrid_search(
|
| 128 |
+
q,
|
| 129 |
+
{"ar_query": q, "en_query": q, "keywords": q.split()[:7], "intent": "auth"},
|
| 130 |
+
state.embed_model, state.faiss_index, state.dataset,
|
| 131 |
+
top_n=5, source_type="hadith",
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
# 3. Pick best result from either approach
|
| 135 |
+
best = None
|
| 136 |
+
if text_results and text_results[0].get("_score", 0) > 2.0:
|
| 137 |
+
best = text_results[0]
|
| 138 |
+
elif semantic_results:
|
| 139 |
+
best = semantic_results[0]
|
| 140 |
+
elif text_results:
|
| 141 |
+
best = text_results[0]
|
| 142 |
+
|
| 143 |
+
if best:
|
| 144 |
+
return HadithVerifyResponse(
|
| 145 |
+
query=q,
|
| 146 |
+
found=True,
|
| 147 |
+
collection=best.get("collection"),
|
| 148 |
+
grade=best.get("grade"),
|
| 149 |
+
reference=best.get("reference"),
|
| 150 |
+
arabic=best.get("arabic"),
|
| 151 |
+
english=best.get("english"),
|
| 152 |
+
latency_ms=int((time.perf_counter() - t0) * 1000),
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
return HadithVerifyResponse(
|
| 156 |
+
query=q,
|
| 157 |
+
found=False,
|
| 158 |
+
latency_ms=int((time.perf_counter() - t0) * 1000),
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
# ───────────────────────────────────────────────────────
|
| 163 |
+
# GET /hadith/collection/{name} — browse a collection
|
| 164 |
+
# ───────────────────────────────────────────────────────
|
| 165 |
+
@router.get("/collection/{name}")
|
| 166 |
+
async def hadith_collection(
|
| 167 |
+
name: str,
|
| 168 |
+
limit: int = Query(20, ge=1, le=100),
|
| 169 |
+
offset: int = Query(0, ge=0),
|
| 170 |
+
):
|
| 171 |
+
"""Browse hadiths from a specific collection (e.g. bukhari, muslim, tirmidhi)."""
|
| 172 |
+
check_ready()
|
| 173 |
+
name_lower = name.lower()
|
| 174 |
+
matches = [
|
| 175 |
+
item for item in state.dataset
|
| 176 |
+
if item.get("type") == "hadith"
|
| 177 |
+
and name_lower in (item.get("collection", "") or item.get("reference", "")).lower()
|
| 178 |
+
]
|
| 179 |
+
|
| 180 |
+
if not matches:
|
| 181 |
+
raise HTTPException(status_code=404, detail=f"Collection '{name}' not found")
|
| 182 |
+
|
| 183 |
+
total = len(matches)
|
| 184 |
+
page = matches[offset:offset + limit]
|
| 185 |
+
|
| 186 |
+
return {
|
| 187 |
+
"collection": name,
|
| 188 |
+
"total": total,
|
| 189 |
+
"offset": offset,
|
| 190 |
+
"limit": limit,
|
| 191 |
+
"results": [
|
| 192 |
+
{
|
| 193 |
+
"reference": item.get("reference", ""),
|
| 194 |
+
"hadith_number": item.get("hadith_number"),
|
| 195 |
+
"chapter": item.get("chapter", ""),
|
| 196 |
+
"arabic": item.get("arabic", ""),
|
| 197 |
+
"english": item.get("english", ""),
|
| 198 |
+
"grade": item.get("grade"),
|
| 199 |
+
}
|
| 200 |
+
for item in page
|
| 201 |
+
],
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
# ───────────────────────────────────────────────────────
|
| 206 |
+
# GET /hadith/analytics — aggregate hadith statistics
|
| 207 |
+
# ───────────────────────────────────────────────────────
|
| 208 |
+
@router.get("/analytics", response_model=HadithAnalyticsResponse)
|
| 209 |
+
async def hadith_analytics():
|
| 210 |
+
"""Get aggregate Hadith analytics: collection counts, grade distribution."""
|
| 211 |
+
check_ready()
|
| 212 |
+
return HadithAnalyticsResponse(**get_hadith_analytics(state.dataset))
|
app/routers/ops.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Operational endpoints — health, models, debug."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import time
|
| 6 |
+
from typing import Optional
|
| 7 |
+
|
| 8 |
+
from fastapi import APIRouter, Query
|
| 9 |
+
|
| 10 |
+
from app.config import cfg
|
| 11 |
+
from app.models import ModelInfo, ModelsListResponse
|
| 12 |
+
from app.search import hybrid_search, rewrite_query
|
| 13 |
+
from app.state import check_ready, state
|
| 14 |
+
|
| 15 |
+
router = APIRouter(tags=["ops"])
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@router.get("/health")
|
| 19 |
+
def health():
|
| 20 |
+
"""Health check endpoint."""
|
| 21 |
+
return {
|
| 22 |
+
"status": "ok" if state.ready else "initialising",
|
| 23 |
+
"version": "5.0.0",
|
| 24 |
+
"llm_backend": cfg.LLM_BACKEND,
|
| 25 |
+
"dataset_size": len(state.dataset) if state.dataset else 0,
|
| 26 |
+
"faiss_total": state.faiss_index.ntotal if state.faiss_index else 0,
|
| 27 |
+
"confidence_threshold": cfg.CONFIDENCE_THRESHOLD,
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@router.get("/v1/models", response_model=ModelsListResponse, tags=["models"])
|
| 32 |
+
def list_models():
|
| 33 |
+
"""List available models (OpenAI-compatible)."""
|
| 34 |
+
return ModelsListResponse(
|
| 35 |
+
data=[
|
| 36 |
+
ModelInfo(id="QModel", created=int(time.time()), owned_by="elgendy"),
|
| 37 |
+
ModelInfo(id="qmodel", created=int(time.time()), owned_by="elgendy"),
|
| 38 |
+
]
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@router.get("/debug/scores")
|
| 43 |
+
async def debug_scores(
|
| 44 |
+
q: str = Query(..., min_length=1, max_length=1000),
|
| 45 |
+
top_k: int = Query(10, ge=1, le=20),
|
| 46 |
+
):
|
| 47 |
+
"""Debug: inspect raw retrieval scores without LLM generation."""
|
| 48 |
+
check_ready()
|
| 49 |
+
rewrite = await rewrite_query(q, state.llm)
|
| 50 |
+
results = await hybrid_search(
|
| 51 |
+
q, rewrite,
|
| 52 |
+
state.embed_model, state.faiss_index, state.dataset, top_k,
|
| 53 |
+
)
|
| 54 |
+
return {
|
| 55 |
+
"intent": rewrite.get("intent"),
|
| 56 |
+
"threshold": cfg.CONFIDENCE_THRESHOLD,
|
| 57 |
+
"results": [
|
| 58 |
+
{
|
| 59 |
+
"rank": i + 1,
|
| 60 |
+
"source": r.get("source") or r.get("reference"),
|
| 61 |
+
"type": r.get("type"),
|
| 62 |
+
"grade": r.get("grade"),
|
| 63 |
+
"_dense": round(r.get("_dense", 0), 4),
|
| 64 |
+
"_sparse": round(r.get("_sparse", 0), 4),
|
| 65 |
+
"_score": round(r.get("_score", 0), 4),
|
| 66 |
+
}
|
| 67 |
+
for i, r in enumerate(results)
|
| 68 |
+
],
|
| 69 |
+
}
|
app/routers/quran.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Quran endpoints — search, topic, analytics, chapter, verse, word-frequency."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import time
|
| 6 |
+
|
| 7 |
+
from fastapi import APIRouter, HTTPException, Query
|
| 8 |
+
|
| 9 |
+
from app.analysis import (
|
| 10 |
+
count_occurrences,
|
| 11 |
+
get_chapter_info,
|
| 12 |
+
get_quran_analytics,
|
| 13 |
+
get_verse,
|
| 14 |
+
)
|
| 15 |
+
from app.models import (
|
| 16 |
+
ChapterResponse,
|
| 17 |
+
QuranAnalyticsResponse,
|
| 18 |
+
TextSearchResponse,
|
| 19 |
+
VerseItem,
|
| 20 |
+
WordFrequencyResponse,
|
| 21 |
+
)
|
| 22 |
+
from app.search import hybrid_search, rewrite_query, text_search
|
| 23 |
+
from app.state import check_ready, state
|
| 24 |
+
|
| 25 |
+
router = APIRouter(prefix="/quran", tags=["quran"])
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
# ───────────────────────────────────────────────────────
|
| 29 |
+
# GET /quran/search — text-based verse lookup (#1)
|
| 30 |
+
# ───────────────────────────────────────────────────────
|
| 31 |
+
@router.get("/search", response_model=TextSearchResponse)
|
| 32 |
+
async def quran_text_search(
|
| 33 |
+
q: str = Query(..., min_length=1, max_length=500, description="Text to search for (Arabic or English)"),
|
| 34 |
+
limit: int = Query(10, ge=1, le=50),
|
| 35 |
+
):
|
| 36 |
+
"""Search for Quran verses by partial text match (Arabic or English).
|
| 37 |
+
|
| 38 |
+
This performs exact substring matching plus fuzzy word-overlap matching.
|
| 39 |
+
Use this to find a verse when you know part of the text.
|
| 40 |
+
"""
|
| 41 |
+
check_ready()
|
| 42 |
+
results = text_search(q, state.dataset, source_type="quran", limit=limit)
|
| 43 |
+
return TextSearchResponse(
|
| 44 |
+
query=q,
|
| 45 |
+
count=len(results),
|
| 46 |
+
results=[
|
| 47 |
+
{
|
| 48 |
+
"surah_number": r.get("surah_number"),
|
| 49 |
+
"surah_name_ar": r.get("surah_name_ar", ""),
|
| 50 |
+
"surah_name_en": r.get("surah_name_en", ""),
|
| 51 |
+
"ayah": r.get("ayah_number") or r.get("verse_number"),
|
| 52 |
+
"arabic": r.get("arabic", ""),
|
| 53 |
+
"english": r.get("english", ""),
|
| 54 |
+
"source": r.get("source", ""),
|
| 55 |
+
"score": round(r.get("_score", 0), 4),
|
| 56 |
+
}
|
| 57 |
+
for r in results
|
| 58 |
+
],
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# ───────────────────────────────────────────────────────
|
| 63 |
+
# GET /quran/topic — semantic topic search (#2)
|
| 64 |
+
# ───────────────────────────────────────────────────────
|
| 65 |
+
@router.get("/topic", response_model=TextSearchResponse)
|
| 66 |
+
async def quran_topic_search(
|
| 67 |
+
topic: str = Query(..., min_length=1, max_length=500, description="Topic or theme to search for"),
|
| 68 |
+
top_k: int = Query(10, ge=1, le=20),
|
| 69 |
+
):
|
| 70 |
+
"""Search for Quran verses related to a topic/theme using semantic search."""
|
| 71 |
+
check_ready()
|
| 72 |
+
rewrite = await rewrite_query(topic, state.llm)
|
| 73 |
+
results = await hybrid_search(
|
| 74 |
+
topic, rewrite,
|
| 75 |
+
state.embed_model, state.faiss_index, state.dataset,
|
| 76 |
+
top_n=top_k, source_type="quran",
|
| 77 |
+
)
|
| 78 |
+
return TextSearchResponse(
|
| 79 |
+
query=topic,
|
| 80 |
+
count=len(results),
|
| 81 |
+
results=[
|
| 82 |
+
{
|
| 83 |
+
"surah_number": r.get("surah_number"),
|
| 84 |
+
"surah_name_ar": r.get("surah_name_ar", ""),
|
| 85 |
+
"surah_name_en": r.get("surah_name_en", ""),
|
| 86 |
+
"ayah": r.get("ayah_number") or r.get("verse_number"),
|
| 87 |
+
"arabic": r.get("arabic", ""),
|
| 88 |
+
"english": r.get("english", ""),
|
| 89 |
+
"source": r.get("source", ""),
|
| 90 |
+
"score": round(r.get("_score", 0), 4),
|
| 91 |
+
}
|
| 92 |
+
for r in results
|
| 93 |
+
],
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
# ───────────────────────────────────────────────────────
|
| 98 |
+
# GET /quran/word-frequency — count word occurrences (#3)
|
| 99 |
+
# ───────────────────────────────────────────────────────
|
| 100 |
+
@router.get("/word-frequency", response_model=WordFrequencyResponse)
|
| 101 |
+
async def quran_word_frequency(
|
| 102 |
+
word: str = Query(..., min_length=1, max_length=100, description="Word to count occurrences for"),
|
| 103 |
+
):
|
| 104 |
+
"""Count occurrences of a word in the Quran with surah breakdown."""
|
| 105 |
+
check_ready()
|
| 106 |
+
result = await count_occurrences(word, state.dataset)
|
| 107 |
+
return WordFrequencyResponse(**result)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
# ───────────────────────────────────────────────────────
|
| 111 |
+
# GET /quran/analytics — aggregate statistics (#4)
|
| 112 |
+
# ──────────────────────────────────────────────────��────
|
| 113 |
+
@router.get("/analytics", response_model=QuranAnalyticsResponse)
|
| 114 |
+
async def quran_analytics():
|
| 115 |
+
"""Get aggregate Quran analytics: surah list, verse counts, Meccan/Medinan breakdown."""
|
| 116 |
+
check_ready()
|
| 117 |
+
return QuranAnalyticsResponse(**get_quran_analytics(state.dataset))
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
# ───────────────────────────────────────────────────────
|
| 121 |
+
# GET /quran/chapter/{number} — all verses in a chapter
|
| 122 |
+
# ───────────────────────────────────────────────────────
|
| 123 |
+
@router.get("/chapter/{number}", response_model=ChapterResponse)
|
| 124 |
+
async def quran_chapter(number: int):
|
| 125 |
+
"""Get all verses and metadata for a specific surah (chapter)."""
|
| 126 |
+
check_ready()
|
| 127 |
+
if number < 1 or number > 114:
|
| 128 |
+
raise HTTPException(status_code=400, detail="Surah number must be between 1 and 114")
|
| 129 |
+
info = get_chapter_info(number, state.dataset)
|
| 130 |
+
if not info:
|
| 131 |
+
raise HTTPException(status_code=404, detail=f"Surah {number} not found in dataset")
|
| 132 |
+
return ChapterResponse(**info)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
# ───────────────────────────────────────────────────────
|
| 136 |
+
# GET /quran/verse/{surah}:{ayah} — specific verse
|
| 137 |
+
# ───────────────────────────────────────────────────────
|
| 138 |
+
@router.get("/verse/{surah}:{ayah}")
|
| 139 |
+
async def quran_verse(surah: int, ayah: int):
|
| 140 |
+
"""Get a specific verse by surah number and ayah number (e.g. /quran/verse/2:255)."""
|
| 141 |
+
check_ready()
|
| 142 |
+
if surah < 1 or surah > 114:
|
| 143 |
+
raise HTTPException(status_code=400, detail="Surah number must be between 1 and 114")
|
| 144 |
+
if ayah < 1:
|
| 145 |
+
raise HTTPException(status_code=400, detail="Ayah number must be >= 1")
|
| 146 |
+
verse = get_verse(surah, ayah, state.dataset)
|
| 147 |
+
if not verse:
|
| 148 |
+
raise HTTPException(status_code=404, detail=f"Verse {surah}:{ayah} not found")
|
| 149 |
+
return verse
|
app/search.py
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Hybrid search engine — dense FAISS + BM25 re-ranking + text search."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import logging
|
| 7 |
+
import re
|
| 8 |
+
from collections import Counter
|
| 9 |
+
from typing import Dict, List, Literal, Optional
|
| 10 |
+
|
| 11 |
+
import faiss
|
| 12 |
+
import numpy as np
|
| 13 |
+
from sentence_transformers import SentenceTransformer
|
| 14 |
+
|
| 15 |
+
from app.arabic_nlp import light_stem, normalize_arabic, tokenize_ar
|
| 16 |
+
from app.cache import rewrite_cache, search_cache
|
| 17 |
+
from app.config import cfg
|
| 18 |
+
from app.llm import LLMProvider
|
| 19 |
+
|
| 20 |
+
logger = logging.getLogger("qmodel.search")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 24 |
+
# QUERY REWRITING
|
| 25 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 26 |
+
_REWRITE_SYSTEM = """\
|
| 27 |
+
You are an Islamic-scholarship search query optimizer.
|
| 28 |
+
Your ONLY job: rewrite the user's question to maximise retrieval from a Quranic + Hadith dataset.
|
| 29 |
+
|
| 30 |
+
Reply ONLY with a valid JSON object — no markdown, no preamble:
|
| 31 |
+
{
|
| 32 |
+
"ar_query": "<query in clear Arabic فصحى, ≤25 words>",
|
| 33 |
+
"en_query": "<query in clear English, ≤25 words>",
|
| 34 |
+
"keywords": ["<3-7 key Arabic or English terms from the question>"],
|
| 35 |
+
"intent": "<one of: fatwa | tafsir | hadith | count | surah_info | auth | general>"
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
Intent Detection Rules (CRITICAL):
|
| 39 |
+
- 'surah_info' intent = asking about surah metadata: verse count, revelation type, surah number
|
| 40 |
+
(كم عدد آيات سورة, كم آية في سورة, how many verses in surah, is surah X meccan/medinan)
|
| 41 |
+
- 'count' intent = asking for WORD frequency/occurrence count (كم مرة ذُكرت كلمة, how many times is word X mentioned)
|
| 42 |
+
NOTE: "كم عدد آيات سورة" is surah_info NOT count!
|
| 43 |
+
- 'auth' intent = asking about authenticity (صحيح؟, هل صحيح, is it authentic, verify hadith grade)
|
| 44 |
+
- 'hadith' intent = asking about specific hadith meaning/text (not authenticity)
|
| 45 |
+
- 'tafsir' intent = asking about Quranic verses or Islamic ruling (fatwa)
|
| 46 |
+
- 'general' intent = other questions
|
| 47 |
+
|
| 48 |
+
Examples:
|
| 49 |
+
- "كم عدد آيات سورة آل عمران" → intent: surah_info (asking about surah metadata!)
|
| 50 |
+
- "كم آية في سورة البقرة" → intent: surah_info
|
| 51 |
+
- "how many verses in surah al-baqara" → intent: surah_info
|
| 52 |
+
- "هل سورة الفاتحة مكية أم مدنية" → intent: surah_info
|
| 53 |
+
- "كم مرة ذُكرت كلمة مريم" → intent: count (asking about WORD frequency!)
|
| 54 |
+
- "هل حديث إنما الأعمال بالنيات صحيح" → intent: auth (asking if authentic!)
|
| 55 |
+
- "ما معنى حديث إنما الأعمال" → intent: hadith
|
| 56 |
+
- "ما حكم الربا في الإسلام" → intent: fatwa
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
async def rewrite_query(raw: str, llm: LLMProvider) -> Dict:
|
| 61 |
+
"""Rewrite query for better retrieval."""
|
| 62 |
+
cached = await rewrite_cache.get(raw)
|
| 63 |
+
if cached:
|
| 64 |
+
return cached
|
| 65 |
+
|
| 66 |
+
fallback = {
|
| 67 |
+
"ar_query": normalize_arabic(raw),
|
| 68 |
+
"en_query": raw,
|
| 69 |
+
"keywords": raw.split()[:7],
|
| 70 |
+
"intent": "general",
|
| 71 |
+
}
|
| 72 |
+
try:
|
| 73 |
+
text = await llm.chat(
|
| 74 |
+
messages=[
|
| 75 |
+
{"role": "system", "content": _REWRITE_SYSTEM},
|
| 76 |
+
{"role": "user", "content": raw},
|
| 77 |
+
],
|
| 78 |
+
max_tokens=220,
|
| 79 |
+
temperature=0.0,
|
| 80 |
+
)
|
| 81 |
+
text = re.sub(r"```(?:json)?\n?|\n?```", "", text).strip()
|
| 82 |
+
result = json.loads(text)
|
| 83 |
+
for k in ("ar_query", "en_query", "keywords", "intent"):
|
| 84 |
+
result.setdefault(k, fallback[k])
|
| 85 |
+
await rewrite_cache.set(result, raw)
|
| 86 |
+
logger.info("Rewrite: intent=%s ar=%s", result["intent"], result["ar_query"][:60])
|
| 87 |
+
return result
|
| 88 |
+
except Exception as exc:
|
| 89 |
+
logger.warning("Query rewrite failed (%s) — using fallback", exc)
|
| 90 |
+
return fallback
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 94 |
+
# BM25 SCORING
|
| 95 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 96 |
+
def _bm25_score(
|
| 97 |
+
query_terms: List[str],
|
| 98 |
+
doc_text: str,
|
| 99 |
+
avg_dl: float,
|
| 100 |
+
k1: float = 1.5,
|
| 101 |
+
b: float = 0.75,
|
| 102 |
+
) -> float:
|
| 103 |
+
"""BM25 term-frequency scoring."""
|
| 104 |
+
doc_tokens = tokenize_ar(doc_text)
|
| 105 |
+
dl = len(doc_tokens)
|
| 106 |
+
tf = Counter(doc_tokens)
|
| 107 |
+
score = 0.0
|
| 108 |
+
for term in query_terms:
|
| 109 |
+
f = tf.get(term, 0)
|
| 110 |
+
score += (f * (k1 + 1)) / (f + k1 * (1 - b + b * dl / max(avg_dl, 1)))
|
| 111 |
+
return score
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 115 |
+
# HYBRID SEARCH — dense FAISS + BM25 re-ranking + filtering
|
| 116 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 117 |
+
async def hybrid_search(
|
| 118 |
+
raw_query: str,
|
| 119 |
+
rewrite: Dict,
|
| 120 |
+
embed_model: SentenceTransformer,
|
| 121 |
+
index: faiss.Index,
|
| 122 |
+
dataset: list,
|
| 123 |
+
top_n: int = cfg.TOP_K_RETURN,
|
| 124 |
+
source_type: Optional[Literal["quran", "hadith"]] = None,
|
| 125 |
+
grade_filter: Optional[str] = None,
|
| 126 |
+
) -> list:
|
| 127 |
+
"""Hybrid search: dense + sparse with optional filtering."""
|
| 128 |
+
cache_key = (raw_query, top_n, source_type, grade_filter)
|
| 129 |
+
cached = await search_cache.get(*cache_key)
|
| 130 |
+
if cached:
|
| 131 |
+
return cached
|
| 132 |
+
|
| 133 |
+
# ── 1. Dual-language dense retrieval ──────────────────────────────
|
| 134 |
+
ar_q = "query: " + rewrite["ar_query"]
|
| 135 |
+
en_q = "query: " + rewrite["en_query"]
|
| 136 |
+
|
| 137 |
+
embeddings = embed_model.encode(
|
| 138 |
+
[ar_q, en_q], normalize_embeddings=True, batch_size=2
|
| 139 |
+
).astype("float32")
|
| 140 |
+
|
| 141 |
+
fused = embeddings[0] + embeddings[1]
|
| 142 |
+
fused /= np.linalg.norm(fused)
|
| 143 |
+
|
| 144 |
+
distances, indices = index.search(fused.reshape(1, -1), cfg.TOP_K_SEARCH)
|
| 145 |
+
|
| 146 |
+
# ── 2. De-duplicate candidates & apply filters ─────────────────────
|
| 147 |
+
seen: set = set()
|
| 148 |
+
candidates = []
|
| 149 |
+
for dist, idx in zip(distances[0], indices[0]):
|
| 150 |
+
item_idx = int(idx)
|
| 151 |
+
if item_idx not in seen and 0 <= item_idx < len(dataset):
|
| 152 |
+
seen.add(item_idx)
|
| 153 |
+
item = dataset[item_idx]
|
| 154 |
+
|
| 155 |
+
if source_type and item.get("type") != source_type:
|
| 156 |
+
continue
|
| 157 |
+
|
| 158 |
+
if grade_filter and item.get("type") == "hadith":
|
| 159 |
+
item_grade = item.get("grade", "").lower()
|
| 160 |
+
if grade_filter.lower() not in item_grade:
|
| 161 |
+
continue
|
| 162 |
+
|
| 163 |
+
candidates.append({**item, "_dense": float(dist)})
|
| 164 |
+
|
| 165 |
+
if not candidates:
|
| 166 |
+
return []
|
| 167 |
+
|
| 168 |
+
# ── 3. BM25 sparse scoring ─────────────────────────────────────────
|
| 169 |
+
query_terms = [
|
| 170 |
+
light_stem(kw) for kw in rewrite.get("keywords", raw_query.split())
|
| 171 |
+
]
|
| 172 |
+
avg_dl = sum(
|
| 173 |
+
len(tokenize_ar(c.get("arabic", "") + " " + c.get("english", "")))
|
| 174 |
+
for c in candidates
|
| 175 |
+
) / max(len(candidates), 1)
|
| 176 |
+
|
| 177 |
+
for c in candidates:
|
| 178 |
+
doc = c.get("arabic", "") + " " + c.get("english", "")
|
| 179 |
+
c["_sparse"] = _bm25_score(query_terms, doc, avg_dl)
|
| 180 |
+
|
| 181 |
+
# ── 3.5. Phrase matching boost for exact snippets ───────────────────
|
| 182 |
+
query_norm = normalize_arabic(raw_query, aggressive=False).lower()
|
| 183 |
+
for c in candidates:
|
| 184 |
+
if c.get("type") == "hadith":
|
| 185 |
+
ar_norm = normalize_arabic(c.get("arabic", ""), aggressive=False).lower()
|
| 186 |
+
query_fragments = query_norm.split()
|
| 187 |
+
for i in range(len(query_fragments) - 2):
|
| 188 |
+
phrase = " ".join(query_fragments[i:i+3])
|
| 189 |
+
if len(phrase) > 5 and phrase in ar_norm:
|
| 190 |
+
c["_sparse"] += 2.0
|
| 191 |
+
break
|
| 192 |
+
|
| 193 |
+
# ── 4. Score fusion ────────────────────────────────────────────────
|
| 194 |
+
α = cfg.RERANK_ALPHA
|
| 195 |
+
intent = rewrite.get("intent", "general")
|
| 196 |
+
|
| 197 |
+
if intent == "auth":
|
| 198 |
+
α = 0.75
|
| 199 |
+
|
| 200 |
+
max_sparse = max((c["_sparse"] for c in candidates), default=1.0) or 1.0
|
| 201 |
+
|
| 202 |
+
for c in candidates:
|
| 203 |
+
base_score = α * c["_dense"] + (1 - α) * c["_sparse"] / max_sparse
|
| 204 |
+
if intent == "hadith" and c.get("type") == "hadith":
|
| 205 |
+
base_score += cfg.HADITH_BOOST
|
| 206 |
+
c["_score"] = base_score
|
| 207 |
+
|
| 208 |
+
candidates.sort(key=lambda x: x["_score"], reverse=True)
|
| 209 |
+
results = candidates[:top_n]
|
| 210 |
+
|
| 211 |
+
await search_cache.set(results, *cache_key)
|
| 212 |
+
return results
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 216 |
+
# TEXT-BASED SEARCH (exact substring + fuzzy matching)
|
| 217 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 218 |
+
def text_search(
|
| 219 |
+
query: str,
|
| 220 |
+
dataset: list,
|
| 221 |
+
source_type: Optional[Literal["quran", "hadith"]] = None,
|
| 222 |
+
limit: int = 10,
|
| 223 |
+
) -> list:
|
| 224 |
+
"""Search dataset by exact text match (Arabic or English).
|
| 225 |
+
|
| 226 |
+
Returns items sorted by relevance: exact matches first, then partial.
|
| 227 |
+
"""
|
| 228 |
+
q_norm = normalize_arabic(query, aggressive=True).lower()
|
| 229 |
+
q_lower = query.lower().strip()
|
| 230 |
+
|
| 231 |
+
results = []
|
| 232 |
+
for item in dataset:
|
| 233 |
+
if source_type and item.get("type") != source_type:
|
| 234 |
+
continue
|
| 235 |
+
|
| 236 |
+
ar_raw = item.get("arabic", "")
|
| 237 |
+
en_raw = item.get("english", "")
|
| 238 |
+
ar_norm = normalize_arabic(ar_raw, aggressive=True).lower()
|
| 239 |
+
en_lower = en_raw.lower()
|
| 240 |
+
|
| 241 |
+
score = 0.0
|
| 242 |
+
|
| 243 |
+
# Exact substring in normalized Arabic
|
| 244 |
+
if q_norm and q_norm in ar_norm:
|
| 245 |
+
# Boost for shorter docs (more specific match)
|
| 246 |
+
score = 3.0 + (1.0 / max(len(ar_norm), 1)) * 100
|
| 247 |
+
|
| 248 |
+
# Exact substring in English
|
| 249 |
+
if q_lower and q_lower in en_lower:
|
| 250 |
+
score = max(score, 2.0 + (1.0 / max(len(en_lower), 1)) * 100)
|
| 251 |
+
|
| 252 |
+
# Exact substring in raw Arabic (with diacritics)
|
| 253 |
+
if query.strip() in ar_raw:
|
| 254 |
+
score = max(score, 4.0)
|
| 255 |
+
|
| 256 |
+
# Word-level overlap for lower-confidence matches
|
| 257 |
+
if score == 0.0:
|
| 258 |
+
q_tokens = set(q_norm.split())
|
| 259 |
+
ar_tokens = set(ar_norm.split())
|
| 260 |
+
en_tokens = set(en_lower.split())
|
| 261 |
+
ar_overlap = len(q_tokens & ar_tokens)
|
| 262 |
+
en_overlap = len(q_tokens & en_tokens)
|
| 263 |
+
best_overlap = max(ar_overlap, en_overlap)
|
| 264 |
+
if best_overlap >= max(2, len(q_tokens) * 0.5):
|
| 265 |
+
score = best_overlap / max(len(q_tokens), 1)
|
| 266 |
+
|
| 267 |
+
if score > 0:
|
| 268 |
+
results.append({**item, "_score": score})
|
| 269 |
+
|
| 270 |
+
results.sort(key=lambda x: x["_score"], reverse=True)
|
| 271 |
+
return results[:limit]
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def build_context(results: list) -> str:
|
| 275 |
+
"""Format search results into context block for LLM."""
|
| 276 |
+
lines = []
|
| 277 |
+
for i, r in enumerate(results, 1):
|
| 278 |
+
source = r.get("source") or r.get("reference") or "Unknown Source"
|
| 279 |
+
item_type = "Quranic Verse" if r.get("type") == "quran" else "Hadith"
|
| 280 |
+
grade_str = f" [Grade: {r.get('grade')}]" if r.get("grade") else ""
|
| 281 |
+
|
| 282 |
+
lines.append(
|
| 283 |
+
f"[{i}] 📌 {item_type}{grade_str} | {source} | score: {r.get('_score', 0):.3f}\n"
|
| 284 |
+
f" Arabic : {r.get('arabic', '')}\n"
|
| 285 |
+
f" English: {r.get('english', '')}"
|
| 286 |
+
)
|
| 287 |
+
return "\n\n".join(lines)
|
app/state.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Application state, lifespan, and core RAG pipeline."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import asyncio
|
| 6 |
+
import json
|
| 7 |
+
import logging
|
| 8 |
+
import time
|
| 9 |
+
from contextlib import asynccontextmanager
|
| 10 |
+
from typing import Literal, Optional
|
| 11 |
+
|
| 12 |
+
import faiss
|
| 13 |
+
from fastapi import FastAPI, HTTPException
|
| 14 |
+
from sentence_transformers import SentenceTransformer
|
| 15 |
+
|
| 16 |
+
from app.analysis import (
|
| 17 |
+
count_occurrences,
|
| 18 |
+
detect_analysis_intent,
|
| 19 |
+
detect_surah_info,
|
| 20 |
+
lookup_surah_info,
|
| 21 |
+
)
|
| 22 |
+
from app.arabic_nlp import detect_language
|
| 23 |
+
from app.config import cfg
|
| 24 |
+
from app.llm import LLMProvider, get_llm_provider
|
| 25 |
+
from app.prompts import build_messages, not_found_answer
|
| 26 |
+
from app.search import build_context, hybrid_search, rewrite_query, text_search
|
| 27 |
+
|
| 28 |
+
logger = logging.getLogger("qmodel.state")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 32 |
+
# HADITH GRADE INFERENCE
|
| 33 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 34 |
+
def infer_hadith_grade(item: dict) -> dict:
|
| 35 |
+
"""Infer hadith grade from collection name if not present."""
|
| 36 |
+
if item.get("type") != "hadith" or item.get("grade"):
|
| 37 |
+
return item
|
| 38 |
+
|
| 39 |
+
collection = item.get("collection", "").lower()
|
| 40 |
+
reference = item.get("reference", "").lower()
|
| 41 |
+
combined = f"{collection} {reference}"
|
| 42 |
+
|
| 43 |
+
if any(s in combined for s in ["sahih al-bukhari", "sahih bukhari", "bukhari"]):
|
| 44 |
+
item["grade"] = "Sahih"
|
| 45 |
+
elif any(s in combined for s in ["sahih muslim", "sahih al-muslim"]):
|
| 46 |
+
item["grade"] = "Sahih"
|
| 47 |
+
elif any(s in combined for s in ["sunan an-nasai", "sunan an-nasa", "nasa'i", "nasa"]):
|
| 48 |
+
item["grade"] = "Sahih"
|
| 49 |
+
elif any(s in combined for s in ["jami at-tirmidhi", "tirmidhi", "at-tirmidhi"]):
|
| 50 |
+
item["grade"] = "Hasan"
|
| 51 |
+
elif any(s in combined for s in ["sunan abu dawood", "abu dawood", "abo daud", "abou daoude"]):
|
| 52 |
+
item["grade"] = "Hasan"
|
| 53 |
+
elif any(s in combined for s in ["sunan ibn majah", "ibn majah", "ibn maja"]):
|
| 54 |
+
item["grade"] = "Hasan"
|
| 55 |
+
elif any(s in combined for s in ["muwatta malik", "muwatta", "malik"]):
|
| 56 |
+
item["grade"] = "Hasan"
|
| 57 |
+
elif any(s in combined for s in ["musnad ahmad", "ahmad", "ahmed"]):
|
| 58 |
+
item["grade"] = "Hasan/Sahih"
|
| 59 |
+
elif any(s in combined for s in ["sunan al-darimi", "darimi", "al-darimi"]):
|
| 60 |
+
item["grade"] = "Hasan"
|
| 61 |
+
|
| 62 |
+
return item
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 66 |
+
# APP STATE
|
| 67 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 68 |
+
class AppState:
|
| 69 |
+
embed_model: Optional[SentenceTransformer] = None
|
| 70 |
+
faiss_index: Optional[faiss.Index] = None
|
| 71 |
+
dataset: Optional[list] = None
|
| 72 |
+
llm: Optional[LLMProvider] = None
|
| 73 |
+
ready: bool = False
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
state = AppState()
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
@asynccontextmanager
|
| 80 |
+
async def lifespan(app: FastAPI):
|
| 81 |
+
"""Initialize state on startup."""
|
| 82 |
+
logger.info("Loading embed model: %s", cfg.EMBED_MODEL)
|
| 83 |
+
state.embed_model = SentenceTransformer(cfg.EMBED_MODEL)
|
| 84 |
+
|
| 85 |
+
logger.info("Loading FAISS index: %s", cfg.FAISS_INDEX)
|
| 86 |
+
state.faiss_index = faiss.read_index(cfg.FAISS_INDEX)
|
| 87 |
+
|
| 88 |
+
logger.info("Loading metadata: %s", cfg.METADATA_FILE)
|
| 89 |
+
with open(cfg.METADATA_FILE, "r", encoding="utf-8") as f:
|
| 90 |
+
state.dataset = json.load(f)
|
| 91 |
+
|
| 92 |
+
state.dataset = [infer_hadith_grade(item) for item in state.dataset]
|
| 93 |
+
|
| 94 |
+
logger.info("Initializing LLM provider: %s", cfg.LLM_BACKEND)
|
| 95 |
+
state.llm = get_llm_provider()
|
| 96 |
+
|
| 97 |
+
state.ready = True
|
| 98 |
+
logger.info(
|
| 99 |
+
"QModel v6 ready | backend=%s | dataset=%d | faiss=%d | threshold=%.2f",
|
| 100 |
+
cfg.LLM_BACKEND,
|
| 101 |
+
len(state.dataset) if state.dataset else 0,
|
| 102 |
+
state.faiss_index.ntotal if state.faiss_index else 0,
|
| 103 |
+
cfg.CONFIDENCE_THRESHOLD,
|
| 104 |
+
)
|
| 105 |
+
yield
|
| 106 |
+
state.ready = False
|
| 107 |
+
logger.info("QModel shutdown")
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def check_ready():
|
| 111 |
+
"""Raise 503 if service isn't ready."""
|
| 112 |
+
if not state.ready:
|
| 113 |
+
raise HTTPException(
|
| 114 |
+
status_code=503,
|
| 115 |
+
detail="Service is still initialising. Please retry shortly.",
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 120 |
+
# CORE RAG PIPELINE
|
| 121 |
+
# ═══════════════════════════���═══════════════════════════════════════════
|
| 122 |
+
async def run_rag_pipeline(
|
| 123 |
+
question: str,
|
| 124 |
+
top_k: int = cfg.TOP_K_RETURN,
|
| 125 |
+
source_type: Optional[Literal["quran", "hadith"]] = None,
|
| 126 |
+
grade_filter: Optional[str] = None,
|
| 127 |
+
) -> dict:
|
| 128 |
+
"""Core RAG pipeline: rewrite -> search -> verify -> generate."""
|
| 129 |
+
t0 = time.perf_counter()
|
| 130 |
+
|
| 131 |
+
# 1. Query rewriting
|
| 132 |
+
rewrite = await rewrite_query(question, state.llm)
|
| 133 |
+
intent = rewrite.get("intent", "general")
|
| 134 |
+
|
| 135 |
+
# 2. Concurrent: surah info + analysis intent + hybrid search + text search
|
| 136 |
+
surah_task = detect_surah_info(question, rewrite)
|
| 137 |
+
kw_task = detect_analysis_intent(question, rewrite)
|
| 138 |
+
search_task = hybrid_search(
|
| 139 |
+
question, rewrite,
|
| 140 |
+
state.embed_model, state.faiss_index, state.dataset,
|
| 141 |
+
top_k, source_type, grade_filter,
|
| 142 |
+
)
|
| 143 |
+
surah_det, analysis_kw, results = await asyncio.gather(
|
| 144 |
+
surah_task, kw_task, search_task,
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
# 2b. Text search fallback — catches exact matches missed by FAISS
|
| 148 |
+
# (e.g. hadith text buried in long isnad chains)
|
| 149 |
+
# Use rewritten ar_query (clean hadith text) + raw question for coverage.
|
| 150 |
+
seen_ids = {r.get("id") for r in results}
|
| 151 |
+
ar_q = rewrite.get("ar_query", "")
|
| 152 |
+
for q in dict.fromkeys([ar_q, question]): # deduplicated, ar_query first
|
| 153 |
+
if not q:
|
| 154 |
+
continue
|
| 155 |
+
for hit in text_search(q, state.dataset, source_type, limit=top_k):
|
| 156 |
+
if hit.get("id") not in seen_ids:
|
| 157 |
+
results.append(hit)
|
| 158 |
+
seen_ids.add(hit.get("id"))
|
| 159 |
+
if len(results) > top_k:
|
| 160 |
+
results.sort(key=lambda x: x.get("_score", 0), reverse=True)
|
| 161 |
+
results = results[:top_k]
|
| 162 |
+
|
| 163 |
+
# 3a. Surah metadata lookup
|
| 164 |
+
surah_info = None
|
| 165 |
+
if surah_det:
|
| 166 |
+
surah_info = await lookup_surah_info(surah_det["surah_query"], state.dataset)
|
| 167 |
+
if surah_info:
|
| 168 |
+
intent = "surah_info"
|
| 169 |
+
logger.info(
|
| 170 |
+
"Surah info: %s -> %s (%d verses)",
|
| 171 |
+
surah_det["surah_query"],
|
| 172 |
+
surah_info["surah_name_en"],
|
| 173 |
+
surah_info.get("total_verses", 0),
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
# 3b. Word frequency count
|
| 177 |
+
analysis = None
|
| 178 |
+
if analysis_kw and not surah_info:
|
| 179 |
+
analysis = await count_occurrences(analysis_kw, state.dataset)
|
| 180 |
+
logger.info("Analysis: kw=%s count=%d", analysis_kw, analysis["total_count"])
|
| 181 |
+
|
| 182 |
+
# 4. Language detection
|
| 183 |
+
lang = detect_language(question)
|
| 184 |
+
top_score = results[0].get("_score", 0.0) if results else 0.0
|
| 185 |
+
|
| 186 |
+
logger.info(
|
| 187 |
+
"Search done | intent=%s | top_score=%.3f | threshold=%.2f",
|
| 188 |
+
intent, top_score, cfg.CONFIDENCE_THRESHOLD,
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
# 5. Confidence gate (skip for surah_info)
|
| 192 |
+
if not surah_info and top_score < cfg.CONFIDENCE_THRESHOLD:
|
| 193 |
+
logger.warning(
|
| 194 |
+
"Low confidence (%.3f < %.2f) — returning safe fallback",
|
| 195 |
+
top_score, cfg.CONFIDENCE_THRESHOLD,
|
| 196 |
+
)
|
| 197 |
+
return {
|
| 198 |
+
"answer": not_found_answer(lang),
|
| 199 |
+
"language": lang,
|
| 200 |
+
"intent": intent,
|
| 201 |
+
"analysis": analysis,
|
| 202 |
+
"sources": results,
|
| 203 |
+
"top_score": top_score,
|
| 204 |
+
"latency_ms": int((time.perf_counter() - t0) * 1000),
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
# 6. Build context + prompt + LLM call
|
| 208 |
+
context = build_context(results)
|
| 209 |
+
messages = build_messages(context, question, lang, intent, analysis, surah_info)
|
| 210 |
+
|
| 211 |
+
try:
|
| 212 |
+
answer = await state.llm.chat(
|
| 213 |
+
messages,
|
| 214 |
+
max_tokens=cfg.MAX_TOKENS,
|
| 215 |
+
temperature=cfg.TEMPERATURE,
|
| 216 |
+
)
|
| 217 |
+
except Exception as exc:
|
| 218 |
+
logger.error("LLM call failed: %s", exc)
|
| 219 |
+
raise HTTPException(status_code=502, detail="LLM service unavailable")
|
| 220 |
+
|
| 221 |
+
latency = int((time.perf_counter() - t0) * 1000)
|
| 222 |
+
logger.info(
|
| 223 |
+
"Pipeline done | intent=%s | lang=%s | top_score=%.3f | %d ms",
|
| 224 |
+
intent, lang, top_score, latency,
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
return {
|
| 228 |
+
"answer": answer,
|
| 229 |
+
"language": lang,
|
| 230 |
+
"intent": intent,
|
| 231 |
+
"analysis": analysis,
|
| 232 |
+
"sources": results,
|
| 233 |
+
"top_score": top_score,
|
| 234 |
+
"latency_ms": latency,
|
| 235 |
+
}
|
main.py
CHANGED
|
@@ -1,1029 +1,55 @@
|
|
| 1 |
"""
|
| 2 |
-
QModel
|
| 3 |
===========================
|
| 4 |
Specialized Quran & Hadith system with dual LLM backend support.
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
HF_MODEL_NAME=<hf-model-id> (e.g. gpt2, default: Qwen/Qwen2-7B-Instruct)
|
| 18 |
-
OLLAMA_HOST=<url> (e.g. http://localhost:11434, default: http://localhost:11434)
|
| 19 |
-
OLLAMA_MODEL=<model> (e.g. llama2, default: llama2)
|
| 20 |
-
EMBED_MODEL=intfloat/multilingual-e5-large (embedding model)
|
| 21 |
"""
|
| 22 |
|
| 23 |
from __future__ import annotations
|
| 24 |
|
| 25 |
-
import asyncio
|
| 26 |
-
import hashlib
|
| 27 |
-
import json
|
| 28 |
import logging
|
| 29 |
-
import os
|
| 30 |
-
import re
|
| 31 |
-
import time
|
| 32 |
-
from collections import Counter, OrderedDict
|
| 33 |
-
from contextlib import asynccontextmanager
|
| 34 |
-
from typing import Dict, List, Literal, Optional
|
| 35 |
|
| 36 |
-
import faiss
|
| 37 |
-
import numpy as np
|
| 38 |
from dotenv import load_dotenv
|
| 39 |
-
from fastapi import FastAPI
|
| 40 |
from fastapi.middleware.cors import CORSMiddleware
|
| 41 |
-
from fastapi.responses import StreamingResponse
|
| 42 |
-
from pydantic import BaseModel, Field, validator
|
| 43 |
-
from sentence_transformers import SentenceTransformer
|
| 44 |
|
| 45 |
load_dotenv()
|
| 46 |
|
| 47 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 48 |
-
# LOGGING
|
| 49 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 50 |
logging.basicConfig(
|
| 51 |
level=logging.INFO,
|
| 52 |
format="%(asctime)s | %(levelname)-8s | %(name)s | %(message)s",
|
| 53 |
)
|
| 54 |
-
logger = logging.getLogger("qmodel")
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 58 |
-
# CONFIG & LLM FACTORY
|
| 59 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 60 |
-
class Config:
|
| 61 |
-
"""Centralized configuration with dual backend support."""
|
| 62 |
-
|
| 63 |
-
# Backend selection
|
| 64 |
-
LLM_BACKEND: str = os.getenv("LLM_BACKEND", "ollama") # "hf" or "ollama"
|
| 65 |
-
|
| 66 |
-
# Hugging Face backend
|
| 67 |
-
HF_MODEL_NAME: str = os.getenv("HF_MODEL_NAME", "Qwen/Qwen2-7B-Instruct")
|
| 68 |
-
HF_DEVICE: str = os.getenv("HF_DEVICE", "auto")
|
| 69 |
-
HF_MAX_NEW_TOKENS: int = int(os.getenv("HF_MAX_NEW_TOKENS", 2048))
|
| 70 |
-
|
| 71 |
-
# Ollama backend
|
| 72 |
-
OLLAMA_HOST: str = os.getenv("OLLAMA_HOST", "http://localhost:11434")
|
| 73 |
-
OLLAMA_MODEL: str = os.getenv("OLLAMA_MODEL", "llama2")
|
| 74 |
-
|
| 75 |
-
# Embedding model
|
| 76 |
-
EMBED_MODEL: str = os.getenv("EMBED_MODEL", "intfloat/multilingual-e5-large")
|
| 77 |
-
|
| 78 |
-
# Index & data
|
| 79 |
-
FAISS_INDEX: str = os.getenv("FAISS_INDEX", "QModel.index")
|
| 80 |
-
METADATA_FILE: str = os.getenv("METADATA_FILE", "metadata.json")
|
| 81 |
-
|
| 82 |
-
# Retrieval
|
| 83 |
-
TOP_K_SEARCH: int = int(os.getenv("TOP_K_SEARCH", 20)) # candidate pool
|
| 84 |
-
TOP_K_RETURN: int = int(os.getenv("TOP_K_RETURN", 5)) # final results
|
| 85 |
-
|
| 86 |
-
# Generation
|
| 87 |
-
TEMPERATURE: float = float(os.getenv("TEMPERATURE", 0.2))
|
| 88 |
-
MAX_TOKENS: int = int(os.getenv("MAX_TOKENS", 2048))
|
| 89 |
-
|
| 90 |
-
# Caching
|
| 91 |
-
CACHE_SIZE: int = int(os.getenv("CACHE_SIZE", 512))
|
| 92 |
-
CACHE_TTL: int = int(os.getenv("CACHE_TTL", 3600))
|
| 93 |
-
|
| 94 |
-
# Ranking
|
| 95 |
-
RERANK_ALPHA: float = float(os.getenv("RERANK_ALPHA", 0.6)) # 60% dense, 40% sparse
|
| 96 |
-
HADITH_BOOST: float = float(os.getenv("HADITH_BOOST", 0.08))
|
| 97 |
-
|
| 98 |
-
# Safety
|
| 99 |
-
CONFIDENCE_THRESHOLD: float = float(os.getenv("CONFIDENCE_THRESHOLD", 0.30))
|
| 100 |
-
|
| 101 |
-
# CORS
|
| 102 |
-
ALLOWED_ORIGINS: str = os.getenv("ALLOWED_ORIGINS", "*")
|
| 103 |
-
|
| 104 |
-
MAX_EXAMPLES: int = int(os.getenv("MAX_EXAMPLES", 3))
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
cfg = Config()
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 111 |
-
# LLM ABSTRACTION LAYER
|
| 112 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 113 |
-
class LLMProvider:
|
| 114 |
-
"""Abstract base for LLM providers."""
|
| 115 |
-
|
| 116 |
-
async def chat(
|
| 117 |
-
self, messages: List[dict], temperature: float, max_tokens: int
|
| 118 |
-
) -> str:
|
| 119 |
-
raise NotImplementedError
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
class OllamaProvider(LLMProvider):
|
| 123 |
-
"""Ollama-based LLM provider."""
|
| 124 |
-
|
| 125 |
-
def __init__(self, host: str, model: str):
|
| 126 |
-
self.host = host
|
| 127 |
-
self.model = model
|
| 128 |
-
try:
|
| 129 |
-
import ollama
|
| 130 |
-
self.client = ollama.Client(host=host)
|
| 131 |
-
except ImportError:
|
| 132 |
-
raise ImportError("Install ollama: pip install ollama")
|
| 133 |
-
|
| 134 |
-
async def chat(
|
| 135 |
-
self, messages: List[dict], temperature: float, max_tokens: int
|
| 136 |
-
) -> str:
|
| 137 |
-
loop = asyncio.get_event_loop()
|
| 138 |
-
try:
|
| 139 |
-
result = await loop.run_in_executor(
|
| 140 |
-
None,
|
| 141 |
-
lambda: self.client.chat(
|
| 142 |
-
model=self.model,
|
| 143 |
-
messages=messages,
|
| 144 |
-
options={"temperature": temperature, "num_predict": max_tokens},
|
| 145 |
-
),
|
| 146 |
-
)
|
| 147 |
-
return result["message"]["content"].strip()
|
| 148 |
-
except Exception as exc:
|
| 149 |
-
logger.error("Ollama chat failed: %s", exc)
|
| 150 |
-
raise
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
class HuggingFaceProvider(LLMProvider):
|
| 154 |
-
"""Hugging Face transformers-based LLM provider."""
|
| 155 |
-
|
| 156 |
-
def __init__(self, model_name: str, device: str):
|
| 157 |
-
self.model_name = model_name
|
| 158 |
-
self.device = device
|
| 159 |
-
try:
|
| 160 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM, TextGenerationPipeline
|
| 161 |
-
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 162 |
-
self.model = AutoModelForCausalLM.from_pretrained(
|
| 163 |
-
model_name,
|
| 164 |
-
device_map=device,
|
| 165 |
-
torch_dtype="auto",
|
| 166 |
-
)
|
| 167 |
-
self.pipeline = TextGenerationPipeline(
|
| 168 |
-
model=self.model,
|
| 169 |
-
tokenizer=self.tokenizer,
|
| 170 |
-
device=0 if device != "cpu" else None,
|
| 171 |
-
)
|
| 172 |
-
except ImportError:
|
| 173 |
-
raise ImportError("Install transformers: pip install transformers torch")
|
| 174 |
-
|
| 175 |
-
async def chat(
|
| 176 |
-
self, messages: List[dict], temperature: float, max_tokens: int
|
| 177 |
-
) -> str:
|
| 178 |
-
# Format messages for the model
|
| 179 |
-
prompt = self._format_messages(messages)
|
| 180 |
-
|
| 181 |
-
loop = asyncio.get_event_loop()
|
| 182 |
-
try:
|
| 183 |
-
result = await loop.run_in_executor(
|
| 184 |
-
None,
|
| 185 |
-
lambda: self.pipeline(
|
| 186 |
-
prompt,
|
| 187 |
-
max_new_tokens=max_tokens,
|
| 188 |
-
temperature=temperature,
|
| 189 |
-
do_sample=temperature > 0,
|
| 190 |
-
),
|
| 191 |
-
)
|
| 192 |
-
# Extract generated text
|
| 193 |
-
generated = result[0]["generated_text"]
|
| 194 |
-
# Remove the prompt from generated text
|
| 195 |
-
output = generated[len(prompt):].strip()
|
| 196 |
-
return output
|
| 197 |
-
except Exception as exc:
|
| 198 |
-
logger.error("HF chat failed: %s", exc)
|
| 199 |
-
raise
|
| 200 |
-
|
| 201 |
-
def _format_messages(self, messages: List[dict]) -> str:
|
| 202 |
-
"""Format messages for the model."""
|
| 203 |
-
prompt = ""
|
| 204 |
-
for msg in messages:
|
| 205 |
-
role = msg["role"]
|
| 206 |
-
content = msg["content"]
|
| 207 |
-
if role == "system":
|
| 208 |
-
prompt += f"{content}\n\n"
|
| 209 |
-
elif role == "user":
|
| 210 |
-
prompt += f"User: {content}\n"
|
| 211 |
-
elif role == "assistant":
|
| 212 |
-
prompt += f"Assistant: {content}\n"
|
| 213 |
-
prompt += "Assistant: "
|
| 214 |
-
return prompt
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
def get_llm_provider() -> LLMProvider:
|
| 218 |
-
"""Factory function to get the configured LLM provider."""
|
| 219 |
-
if cfg.LLM_BACKEND == "ollama":
|
| 220 |
-
logger.info("Using Ollama backend: %s @ %s", cfg.OLLAMA_MODEL, cfg.OLLAMA_HOST)
|
| 221 |
-
return OllamaProvider(cfg.OLLAMA_HOST, cfg.OLLAMA_MODEL)
|
| 222 |
-
elif cfg.LLM_BACKEND == "hf":
|
| 223 |
-
logger.info("Using HuggingFace backend: %s on %s", cfg.HF_MODEL_NAME, cfg.HF_DEVICE)
|
| 224 |
-
return HuggingFaceProvider(cfg.HF_MODEL_NAME, cfg.HF_DEVICE)
|
| 225 |
-
else:
|
| 226 |
-
raise ValueError(f"Unknown LLM_BACKEND: {cfg.LLM_BACKEND}")
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 230 |
-
# ASYNC TTL-LRU CACHE
|
| 231 |
-
# ═══════════════════════════════════════════════���═══════════════════════
|
| 232 |
-
class TTLCache:
|
| 233 |
-
"""Async-safe LRU cache with per-entry TTL."""
|
| 234 |
-
|
| 235 |
-
def __init__(self, maxsize: int = 256, ttl: int = 3600):
|
| 236 |
-
self._cache: OrderedDict = OrderedDict()
|
| 237 |
-
self._maxsize = maxsize
|
| 238 |
-
self._ttl = ttl
|
| 239 |
-
self._lock = asyncio.Lock()
|
| 240 |
-
|
| 241 |
-
def _key(self, *args) -> str:
|
| 242 |
-
payload = json.dumps(args, ensure_ascii=False, sort_keys=True)
|
| 243 |
-
return hashlib.sha256(payload.encode()).hexdigest()[:20]
|
| 244 |
-
|
| 245 |
-
async def get(self, *args):
|
| 246 |
-
async with self._lock:
|
| 247 |
-
k = self._key(*args)
|
| 248 |
-
if k in self._cache:
|
| 249 |
-
value, ts = self._cache[k]
|
| 250 |
-
if time.monotonic() - ts < self._ttl:
|
| 251 |
-
self._cache.move_to_end(k)
|
| 252 |
-
return value
|
| 253 |
-
del self._cache[k]
|
| 254 |
-
return None
|
| 255 |
-
|
| 256 |
-
async def set(self, value, *args):
|
| 257 |
-
async with self._lock:
|
| 258 |
-
k = self._key(*args)
|
| 259 |
-
self._cache[k] = (value, time.monotonic())
|
| 260 |
-
self._cache.move_to_end(k)
|
| 261 |
-
if len(self._cache) > self._maxsize:
|
| 262 |
-
self._cache.popitem(last=False)
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
search_cache = TTLCache(maxsize=cfg.CACHE_SIZE, ttl=cfg.CACHE_TTL)
|
| 266 |
-
analysis_cache = TTLCache(maxsize=cfg.CACHE_SIZE, ttl=cfg.CACHE_TTL)
|
| 267 |
-
rewrite_cache = TTLCache(maxsize=cfg.CACHE_SIZE, ttl=cfg.CACHE_TTL * 6)
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 271 |
-
# ARABIC NLP — normalisation + light stemming
|
| 272 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 273 |
-
_DIACRITICS = re.compile(r"[\u064B-\u0655\u0656-\u0658\u0670\u06D6-\u06ED]")
|
| 274 |
-
_ALEF_VARS = re.compile(r"[أإآٱ]")
|
| 275 |
-
_WAW_HAMZA = re.compile(r"ؤ")
|
| 276 |
-
_YA_HAMZA = re.compile(r"ئ")
|
| 277 |
-
_TA_MARBUTA = re.compile(r"ة\b")
|
| 278 |
-
_ALEF_MAQSURA = re.compile(r"ى")
|
| 279 |
-
_TATWEEL = re.compile(r"\u0640+")
|
| 280 |
-
_PUNC_AR = re.compile(r"[،؛؟!«»\u200c\u200d\u200f\u200e]")
|
| 281 |
-
_MULTI_SPACE = re.compile(r"\s{2,}")
|
| 282 |
-
_NON_AR_EN = re.compile(r"[^\u0600-\u06FF\u0750-\u077Fa-zA-Z0-9\s]")
|
| 283 |
-
|
| 284 |
-
_SPELLING_MAP: Dict[str, str] = {
|
| 285 |
-
"قران": "قرآن",
|
| 286 |
-
"القران": "القرآن",
|
| 287 |
-
"اللہ": "الله",
|
| 288 |
-
}
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
def normalize_arabic(text: str, *, aggressive: bool = False) -> str:
|
| 292 |
-
"""Normalize Arabic text: diacritics, hamza, ta marbuta, etc."""
|
| 293 |
-
text = _DIACRITICS.sub("", text)
|
| 294 |
-
text = _TATWEEL.sub("", text)
|
| 295 |
-
text = _ALEF_VARS.sub("ا", text)
|
| 296 |
-
text = _WAW_HAMZA.sub("و", text)
|
| 297 |
-
text = _YA_HAMZA.sub("ي", text)
|
| 298 |
-
text = _TA_MARBUTA.sub("ه", text)
|
| 299 |
-
text = _ALEF_MAQSURA.sub("ي", text)
|
| 300 |
-
text = _PUNC_AR.sub(" ", text)
|
| 301 |
-
for variant, canonical in _SPELLING_MAP.items():
|
| 302 |
-
text = text.replace(variant, canonical)
|
| 303 |
-
if aggressive:
|
| 304 |
-
text = _NON_AR_EN.sub(" ", text)
|
| 305 |
-
return _MULTI_SPACE.sub(" ", text).strip()
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
_AR_PREFIXES = re.compile(
|
| 309 |
-
r"^(و|ف|ب|ل|ال|لل|وال|فال|بال|كال|ولل|ومن|وفي|وعن|وإلى|وعلى)\b"
|
| 310 |
-
)
|
| 311 |
-
_AR_SUFFIXES = re.compile(
|
| 312 |
-
r"(ون|ين|ان|ات|ها|هم|هن|كم|كن|نا|ني|تي|ي|ه|ك|ا|وا)$"
|
| 313 |
-
)
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
def light_stem(word: str) -> str:
|
| 317 |
-
"""Light stemming: remove common Arabic affixes."""
|
| 318 |
-
w = _AR_PREFIXES.sub("", word)
|
| 319 |
-
w = _AR_SUFFIXES.sub("", w)
|
| 320 |
-
return w if len(w) >= 2 else word
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
def tokenize_ar(text: str) -> List[str]:
|
| 324 |
-
"""Tokenize and stem Arabic text."""
|
| 325 |
-
norm = normalize_arabic(text, aggressive=True).lower()
|
| 326 |
-
return [light_stem(t) for t in norm.split() if t]
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 330 |
-
# LANGUAGE DETECTION
|
| 331 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 332 |
-
_ARABIC_SCRIPT = re.compile(
|
| 333 |
-
r"[\u0600-\u06FF\u0750-\u077F\uFB50-\uFDFF\uFE70-\uFEFF]"
|
| 334 |
-
)
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
def detect_language(text: str) -> Literal["arabic", "english", "mixed"]:
|
| 338 |
-
"""Detect if text is Arabic, English, or mixed."""
|
| 339 |
-
ar = len(_ARABIC_SCRIPT.findall(text))
|
| 340 |
-
en = len(re.findall(r"[a-zA-Z]", text))
|
| 341 |
-
tot = ar + en or 1
|
| 342 |
-
ratio = ar / tot
|
| 343 |
-
if ratio > 0.70:
|
| 344 |
-
return "arabic"
|
| 345 |
-
if ratio < 0.30:
|
| 346 |
-
return "english"
|
| 347 |
-
return "mixed"
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
def language_instruction(lang: str) -> str:
|
| 351 |
-
"""Generate language-specific instruction for LLM."""
|
| 352 |
-
return {
|
| 353 |
-
"arabic": (
|
| 354 |
-
"يجب أن تكون الإجابة كاملةً باللغة العربية الفصحى تماماً. "
|
| 355 |
-
"لا تستخدم الإ��جليزية أو أي لغة أخرى في أي جزء من الإجابة."
|
| 356 |
-
),
|
| 357 |
-
"mixed": (
|
| 358 |
-
"The question mixes Arabic and English. Reply primarily in Arabic (الفصحى) "
|
| 359 |
-
"but you may transliterate key terms in English where essential."
|
| 360 |
-
),
|
| 361 |
-
"english": "You MUST reply entirely in clear, formal English.",
|
| 362 |
-
}.get(lang, "You MUST reply entirely in clear, formal English.")
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 366 |
-
# QUERY REWRITING
|
| 367 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 368 |
-
_REWRITE_SYSTEM = """\
|
| 369 |
-
You are an Islamic-scholarship search query optimizer.
|
| 370 |
-
Your ONLY job: rewrite the user's question to maximise retrieval from a Quranic + Hadith dataset.
|
| 371 |
-
|
| 372 |
-
Reply ONLY with a valid JSON object — no markdown, no preamble:
|
| 373 |
-
{
|
| 374 |
-
"ar_query": "<query in clear Arabic فصحى, ≤25 words>",
|
| 375 |
-
"en_query": "<query in clear English, ≤25 words>",
|
| 376 |
-
"keywords": ["<3-7 key Arabic or English terms from the question>"],
|
| 377 |
-
"intent": "<one of: fatwa | tafsir | hadith | count | surah_info | auth | general>"
|
| 378 |
-
}
|
| 379 |
-
|
| 380 |
-
Intent Detection Rules (CRITICAL):
|
| 381 |
-
- 'surah_info' intent = asking about surah metadata: verse count, revelation type, surah number
|
| 382 |
-
(كم عدد آيات سورة, كم آية في سورة, how many verses in surah, is surah X meccan/medinan)
|
| 383 |
-
- 'count' intent = asking for WORD frequency/occurrence count (كم مرة ذُكرت كلمة, how many times is word X mentioned)
|
| 384 |
-
NOTE: "كم عدد آيات سورة" is surah_info NOT count!
|
| 385 |
-
- 'auth' intent = asking about authenticity (صحيح؟, هل صحيح, is it authentic, verify hadith grade)
|
| 386 |
-
- 'hadith' intent = asking about specific hadith meaning/text (not authenticity)
|
| 387 |
-
- 'tafsir' intent = asking about Quranic verses or Islamic ruling (fatwa)
|
| 388 |
-
- 'general' intent = other questions
|
| 389 |
-
|
| 390 |
-
Examples:
|
| 391 |
-
- "كم عدد آيات سورة آل عمران" → intent: surah_info (asking about surah metadata!)
|
| 392 |
-
- "كم آية في سورة البقرة" → intent: surah_info
|
| 393 |
-
- "how many verses in surah al-baqara" → intent: surah_info
|
| 394 |
-
- "هل سورة الفاتحة مكية أم مدنية" → intent: surah_info
|
| 395 |
-
- "كم مرة ذُكرت كلمة مريم" → intent: count (asking about WORD frequency!)
|
| 396 |
-
- "هل حديث إنما الأعمال بالنيات صحيح" → intent: auth (asking if authentic!)
|
| 397 |
-
- "ما معنى حديث إنما الأعمال" → intent: hadith
|
| 398 |
-
- "ما حكم الربا في الإسلام" → intent: fatwa
|
| 399 |
-
"""
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
async def rewrite_query(raw: str, llm: LLMProvider) -> Dict:
|
| 403 |
-
"""Rewrite query for better retrieval."""
|
| 404 |
-
cached = await rewrite_cache.get(raw)
|
| 405 |
-
if cached:
|
| 406 |
-
return cached
|
| 407 |
-
|
| 408 |
-
fallback = {
|
| 409 |
-
"ar_query": normalize_arabic(raw),
|
| 410 |
-
"en_query": raw,
|
| 411 |
-
"keywords": raw.split()[:7],
|
| 412 |
-
"intent": "general",
|
| 413 |
-
}
|
| 414 |
-
try:
|
| 415 |
-
text = await llm.chat(
|
| 416 |
-
messages=[
|
| 417 |
-
{"role": "system", "content": _REWRITE_SYSTEM},
|
| 418 |
-
{"role": "user", "content": raw},
|
| 419 |
-
],
|
| 420 |
-
max_tokens=220,
|
| 421 |
-
temperature=0.0,
|
| 422 |
-
)
|
| 423 |
-
text = re.sub(r"```(?:json)?\n?|\n?```", "", text).strip()
|
| 424 |
-
result = json.loads(text)
|
| 425 |
-
for k in ("ar_query", "en_query", "keywords", "intent"):
|
| 426 |
-
result.setdefault(k, fallback[k])
|
| 427 |
-
await rewrite_cache.set(result, raw)
|
| 428 |
-
logger.info("Rewrite: intent=%s ar=%s", result["intent"], result["ar_query"][:60])
|
| 429 |
-
return result
|
| 430 |
-
except Exception as exc:
|
| 431 |
-
logger.warning("Query rewrite failed (%s) — using fallback", exc)
|
| 432 |
-
return fallback
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 436 |
-
# INTENT DETECTION (frequency / count queries / hadith auth)
|
| 437 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 438 |
-
_COUNT_EN = re.compile(
|
| 439 |
-
r"\b(how many|count|number of|frequency|occurrences? of|how often|"
|
| 440 |
-
r"times? (does|is|appears?))\b",
|
| 441 |
-
re.I,
|
| 442 |
-
)
|
| 443 |
-
_COUNT_AR = re.compile(
|
| 444 |
-
r"(كم مرة|كم عدد|كم تكرر|عدد مرات|تكرار|كم ذُكر|كم وردت?)"
|
| 445 |
-
)
|
| 446 |
-
|
| 447 |
-
_AUTH_EN = re.compile(
|
| 448 |
-
r"\b(authentic|is.*authentic|authenticity|sahih|hasan|weak|daif|verify)\b",
|
| 449 |
-
re.I,
|
| 450 |
-
)
|
| 451 |
-
_AUTH_AR = re.compile(
|
| 452 |
-
r"(صحيح|حسن|ضعيف|درجة|صحة|تصحيح|هل.*صحيح|هل.*ضعيف)"
|
| 453 |
-
)
|
| 454 |
-
|
| 455 |
-
# ── Surah metadata queries (verse count, revelation type, etc.) ───────
|
| 456 |
-
_SURAH_VERSES_AR = re.compile(
|
| 457 |
-
r"كم\s+(?:عدد\s+)?آيات?\s*(?:في\s+|فى\s+)?(?:سورة|سوره)"
|
| 458 |
-
r"|عدد\s+آيات?\s+(?:سورة|سوره)"
|
| 459 |
-
r"|كم\s+آية\s+(?:في|فى)\s+(?:سورة|سوره)"
|
| 460 |
-
r"|(?:سورة|سوره)\s+[\u0600-\u06FF\s]+\s+(?:كم\s+آية|عدد\s+آيات?)"
|
| 461 |
-
)
|
| 462 |
-
_SURAH_VERSES_EN = re.compile(
|
| 463 |
-
r"(?:how many|number of)\s+(?:verses?|ayat|ayahs?)\s+(?:in|of|does)\b"
|
| 464 |
-
r"|\bsurah?\b.*\b(?:how many|number of)\s+(?:verses?|ayat|ayahs?)",
|
| 465 |
-
re.I,
|
| 466 |
-
)
|
| 467 |
-
_SURAH_TYPE_AR = re.compile(
|
| 468 |
-
r"(?:سورة|سوره)\s+[\u0600-\u06FF\s]+\s+(?:مكية|مدنية|مكي|مدني)"
|
| 469 |
-
r"|(?:هل|ما\s+نوع)\s+(?:سورة|سوره)\s+[\u0600-\u06FF\s]+\s+(?:مكية|مدنية)"
|
| 470 |
-
)
|
| 471 |
-
_SURAH_NAME_AR = re.compile(
|
| 472 |
-
r"(?:سورة|سوره)\s+([\u0600-\u06FF\u0750-\u077F\s]+)"
|
| 473 |
-
)
|
| 474 |
-
_SURAH_NAME_EN = re.compile(
|
| 475 |
-
r"\bsurah?\s+([a-zA-Z'\-]+(?:[\s\-][a-zA-Z'\-]+)*)",
|
| 476 |
-
re.I,
|
| 477 |
-
)
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
def _extract_surah_name(query: str) -> Optional[str]:
|
| 481 |
-
"""Extract surah name from a query string."""
|
| 482 |
-
for pat in (_SURAH_NAME_AR, _SURAH_NAME_EN):
|
| 483 |
-
m = pat.search(query)
|
| 484 |
-
if m:
|
| 485 |
-
name = m.group(1).strip()
|
| 486 |
-
# Clean trailing punctuation and question words
|
| 487 |
-
name = re.sub(r'[\s؟?!]+$', '', name)
|
| 488 |
-
name = re.sub(r'\s+(كم|عدد|هل|ما|في|فى)$', '', name)
|
| 489 |
-
if name:
|
| 490 |
-
return name
|
| 491 |
-
return None
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
async def detect_surah_info(query: str, rewrite: dict) -> Optional[dict]:
|
| 495 |
-
"""Detect if query asks about surah metadata (verse count, type, etc.)."""
|
| 496 |
-
is_verse_q = bool(_SURAH_VERSES_AR.search(query) or _SURAH_VERSES_EN.search(query))
|
| 497 |
-
is_type_q = bool(_SURAH_TYPE_AR.search(query))
|
| 498 |
-
|
| 499 |
-
if not (is_verse_q or is_type_q):
|
| 500 |
-
# Also check LLM rewrite intent
|
| 501 |
-
if rewrite.get("intent") == "surah_info":
|
| 502 |
-
is_verse_q = True
|
| 503 |
-
elif rewrite.get("intent") == "count":
|
| 504 |
-
kw_text = " ".join(rewrite.get("keywords", []))
|
| 505 |
-
if any(w in kw_text for w in ("آيات", "آية", "verses", "ayat")):
|
| 506 |
-
is_verse_q = True
|
| 507 |
-
else:
|
| 508 |
-
return None
|
| 509 |
-
else:
|
| 510 |
-
return None
|
| 511 |
-
|
| 512 |
-
surah_name = _extract_surah_name(query)
|
| 513 |
-
if not surah_name:
|
| 514 |
-
return None
|
| 515 |
-
|
| 516 |
-
return {
|
| 517 |
-
"surah_query": surah_name,
|
| 518 |
-
"query_type": "verses" if is_verse_q else "type",
|
| 519 |
-
}
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
async def lookup_surah_info(surah_query: str, dataset: list) -> Optional[dict]:
|
| 523 |
-
"""Look up surah metadata from dataset entries."""
|
| 524 |
-
query_norm = normalize_arabic(surah_query, aggressive=True).lower()
|
| 525 |
-
query_clean = re.sub(r"^(ال|al[\-\s']*)", "", query_norm, flags=re.I).strip()
|
| 526 |
-
|
| 527 |
-
for item in dataset:
|
| 528 |
-
if item.get("type") != "quran":
|
| 529 |
-
continue
|
| 530 |
-
for field in ("surah_name_ar", "surah_name_en", "surah_name_transliteration"):
|
| 531 |
-
val = item.get(field, "")
|
| 532 |
-
if not val:
|
| 533 |
-
continue
|
| 534 |
-
val_norm = normalize_arabic(val, aggressive=True).lower()
|
| 535 |
-
val_clean = re.sub(r"^(ال|al[\-\s']*)", "", val_norm, flags=re.I).strip()
|
| 536 |
-
if (query_norm in val_norm or val_norm in query_norm
|
| 537 |
-
or (query_clean and val_clean
|
| 538 |
-
and (query_clean in val_clean or val_clean in query_clean))
|
| 539 |
-
or (query_clean and query_clean in val_norm)):
|
| 540 |
-
return {
|
| 541 |
-
"surah_number": item.get("surah_number"),
|
| 542 |
-
"surah_name_ar": item.get("surah_name_ar", ""),
|
| 543 |
-
"surah_name_en": item.get("surah_name_en", ""),
|
| 544 |
-
"surah_name_transliteration": item.get("surah_name_transliteration", ""),
|
| 545 |
-
"total_verses": item.get("total_verses"),
|
| 546 |
-
"revelation_type": item.get("revelation_type", ""),
|
| 547 |
-
}
|
| 548 |
-
return None
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
async def detect_analysis_intent(query: str, rewrite: Dict) -> Optional[str]:
|
| 552 |
-
"""Detect if query is asking for word frequency analysis."""
|
| 553 |
-
# Skip surah metadata queries — those are handled by detect_surah_info
|
| 554 |
-
if (_SURAH_VERSES_AR.search(query) or _SURAH_VERSES_EN.search(query)
|
| 555 |
-
or _SURAH_TYPE_AR.search(query)
|
| 556 |
-
or rewrite.get("intent") == "surah_info"):
|
| 557 |
-
return None
|
| 558 |
-
|
| 559 |
-
if rewrite.get("intent") == "count":
|
| 560 |
-
kws = rewrite.get("keywords", [])
|
| 561 |
-
# Skip if keywords suggest surah metadata, not word frequency
|
| 562 |
-
kw_text = " ".join(kws)
|
| 563 |
-
if any(w in kw_text for w in ("آيات", "آية", "verses", "ayat")):
|
| 564 |
-
return None
|
| 565 |
-
return kws[0] if kws else None
|
| 566 |
-
|
| 567 |
-
if not (_COUNT_EN.search(query) or _COUNT_AR.search(query)):
|
| 568 |
-
return None
|
| 569 |
-
|
| 570 |
-
# Simple heuristic: last word after "how many"
|
| 571 |
-
for pat in (_COUNT_EN, _COUNT_AR):
|
| 572 |
-
m = pat.search(query)
|
| 573 |
-
if m:
|
| 574 |
-
tail = query[m.end():].strip().split()
|
| 575 |
-
if tail:
|
| 576 |
-
return tail[0]
|
| 577 |
-
return None
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 581 |
-
# OCCURRENCE ANALYSIS (exact + stemmed matching)
|
| 582 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 583 |
-
async def count_occurrences(keyword: str, dataset: list) -> dict:
|
| 584 |
-
"""Count keyword occurrences with Surah grouping."""
|
| 585 |
-
cached = await analysis_cache.get(keyword)
|
| 586 |
-
if cached:
|
| 587 |
-
return cached
|
| 588 |
-
|
| 589 |
-
kw_norm = normalize_arabic(keyword, aggressive=True).lower()
|
| 590 |
-
kw_stem = light_stem(kw_norm)
|
| 591 |
-
count = 0
|
| 592 |
-
by_surah: Dict[int, Dict] = {}
|
| 593 |
-
examples: list = []
|
| 594 |
-
|
| 595 |
-
for item in dataset:
|
| 596 |
-
if item.get("type") != "quran":
|
| 597 |
-
continue
|
| 598 |
-
|
| 599 |
-
ar_norm = normalize_arabic(item.get("arabic", ""), aggressive=True).lower()
|
| 600 |
-
combined = f"{ar_norm} {item.get('english', '')}".lower()
|
| 601 |
-
exact = combined.count(kw_norm)
|
| 602 |
-
stemmed = combined.count(kw_stem) - exact if kw_stem != kw_norm else 0
|
| 603 |
-
occ = exact + stemmed
|
| 604 |
-
|
| 605 |
-
if occ > 0:
|
| 606 |
-
count += occ
|
| 607 |
-
surah_num = item.get("surah_number", 0)
|
| 608 |
-
if surah_num not in by_surah:
|
| 609 |
-
by_surah[surah_num] = {
|
| 610 |
-
"name": item.get("surah_name_en", f"Surah {surah_num}"),
|
| 611 |
-
"count": 0,
|
| 612 |
-
}
|
| 613 |
-
by_surah[surah_num]["count"] += occ
|
| 614 |
-
|
| 615 |
-
if len(examples) < cfg.MAX_EXAMPLES:
|
| 616 |
-
examples.append({
|
| 617 |
-
"reference": item.get("source", ""),
|
| 618 |
-
"arabic": item.get("arabic", ""),
|
| 619 |
-
"english": item.get("english", ""),
|
| 620 |
-
})
|
| 621 |
-
|
| 622 |
-
result = {
|
| 623 |
-
"keyword": keyword,
|
| 624 |
-
"kw_stemmed": kw_stem,
|
| 625 |
-
"total_count": count,
|
| 626 |
-
"by_surah": dict(sorted(by_surah.items())),
|
| 627 |
-
"examples": examples,
|
| 628 |
-
}
|
| 629 |
-
await analysis_cache.set(result, keyword)
|
| 630 |
-
return result
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 634 |
-
# HYBRID SEARCH — dense FAISS + BM25 re-ranking + filtering
|
| 635 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 636 |
-
def _bm25_score(
|
| 637 |
-
query_terms: List[str],
|
| 638 |
-
doc_text: str,
|
| 639 |
-
avg_dl: float,
|
| 640 |
-
k1: float = 1.5,
|
| 641 |
-
b: float = 0.75,
|
| 642 |
-
) -> float:
|
| 643 |
-
"""BM25 term-frequency scoring."""
|
| 644 |
-
doc_tokens = tokenize_ar(doc_text)
|
| 645 |
-
dl = len(doc_tokens)
|
| 646 |
-
tf = Counter(doc_tokens)
|
| 647 |
-
score = 0.0
|
| 648 |
-
for term in query_terms:
|
| 649 |
-
f = tf.get(term, 0)
|
| 650 |
-
score += (f * (k1 + 1)) / (f + k1 * (1 - b + b * dl / max(avg_dl, 1)))
|
| 651 |
-
return score
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
async def hybrid_search(
|
| 655 |
-
raw_query: str,
|
| 656 |
-
rewrite: Dict,
|
| 657 |
-
embed_model: SentenceTransformer,
|
| 658 |
-
index: faiss.Index,
|
| 659 |
-
dataset: list,
|
| 660 |
-
top_n: int = cfg.TOP_K_RETURN,
|
| 661 |
-
source_type: Optional[Literal["quran", "hadith"]] = None,
|
| 662 |
-
grade_filter: Optional[str] = None,
|
| 663 |
-
) -> list:
|
| 664 |
-
"""Hybrid search: dense + sparse with optional filtering."""
|
| 665 |
-
cache_key = (raw_query, top_n, source_type, grade_filter)
|
| 666 |
-
cached = await search_cache.get(*cache_key)
|
| 667 |
-
if cached:
|
| 668 |
-
return cached
|
| 669 |
-
|
| 670 |
-
# ── 1. Dual-language dense retrieval ──────────────────────────────
|
| 671 |
-
ar_q = "query: " + rewrite["ar_query"]
|
| 672 |
-
en_q = "query: " + rewrite["en_query"]
|
| 673 |
-
|
| 674 |
-
embeddings = embed_model.encode(
|
| 675 |
-
[ar_q, en_q], normalize_embeddings=True, batch_size=2
|
| 676 |
-
).astype("float32")
|
| 677 |
-
|
| 678 |
-
fused = embeddings[0] + embeddings[1]
|
| 679 |
-
fused /= np.linalg.norm(fused)
|
| 680 |
-
|
| 681 |
-
distances, indices = index.search(fused.reshape(1, -1), cfg.TOP_K_SEARCH)
|
| 682 |
-
|
| 683 |
-
# ── 2. De-duplicate candidates & apply filters ─────────────────────
|
| 684 |
-
seen: set = set()
|
| 685 |
-
candidates = []
|
| 686 |
-
for dist, idx in zip(distances[0], indices[0]):
|
| 687 |
-
item_idx = int(idx)
|
| 688 |
-
if item_idx not in seen and 0 <= item_idx < len(dataset):
|
| 689 |
-
seen.add(item_idx)
|
| 690 |
-
item = dataset[item_idx]
|
| 691 |
-
|
| 692 |
-
# Source type filter
|
| 693 |
-
if source_type and item.get("type") != source_type:
|
| 694 |
-
continue
|
| 695 |
-
|
| 696 |
-
# Grade filter (Hadith only)
|
| 697 |
-
if grade_filter and item.get("type") == "hadith":
|
| 698 |
-
item_grade = item.get("grade", "").lower()
|
| 699 |
-
if grade_filter.lower() not in item_grade:
|
| 700 |
-
continue
|
| 701 |
-
|
| 702 |
-
candidates.append({**item, "_dense": float(dist)})
|
| 703 |
-
|
| 704 |
-
if not candidates:
|
| 705 |
-
return []
|
| 706 |
-
|
| 707 |
-
# ── 3. BM25 sparse scoring ───────────���─────────────────────────────
|
| 708 |
-
query_terms = [
|
| 709 |
-
light_stem(kw) for kw in rewrite.get("keywords", raw_query.split())
|
| 710 |
-
]
|
| 711 |
-
avg_dl = sum(
|
| 712 |
-
len(tokenize_ar(c.get("arabic", "") + " " + c.get("english", "")))
|
| 713 |
-
for c in candidates
|
| 714 |
-
) / max(len(candidates), 1)
|
| 715 |
-
|
| 716 |
-
for c in candidates:
|
| 717 |
-
doc = c.get("arabic", "") + " " + c.get("english", "")
|
| 718 |
-
c["_sparse"] = _bm25_score(query_terms, doc, avg_dl)
|
| 719 |
-
|
| 720 |
-
# ── 3.5. Phrase matching boost for exact snippets ───────────────────
|
| 721 |
-
query_norm = normalize_arabic(raw_query, aggressive=False).lower()
|
| 722 |
-
for c in candidates:
|
| 723 |
-
# For hadiths: if query contains specific text, boost exact match
|
| 724 |
-
if c.get("type") == "hadith":
|
| 725 |
-
ar_norm = normalize_arabic(c.get("arabic", ""), aggressive=False).lower()
|
| 726 |
-
# Check if any significant phrase (3+ words) from query appears in hadith
|
| 727 |
-
query_fragments = query_norm.split()
|
| 728 |
-
for i in range(len(query_fragments) - 2):
|
| 729 |
-
phrase = " ".join(query_fragments[i:i+3])
|
| 730 |
-
if len(phrase) > 5 and phrase in ar_norm: # phrase is 5+ chars
|
| 731 |
-
c["_sparse"] += 2.0 # boost exact phrase match
|
| 732 |
-
break
|
| 733 |
-
|
| 734 |
-
# ── 4. Score fusion ────────────────────────────────────────────────
|
| 735 |
-
α = cfg.RERANK_ALPHA
|
| 736 |
-
intent = rewrite.get("intent", "general")
|
| 737 |
-
|
| 738 |
-
# For hadith authenticity queries, rely more on semantic search
|
| 739 |
-
if intent == "auth":
|
| 740 |
-
α = 0.75 # 75% dense, 25% sparse (vs default 60/40)
|
| 741 |
-
|
| 742 |
-
max_sparse = max((c["_sparse"] for c in candidates), default=1.0) or 1.0
|
| 743 |
-
|
| 744 |
-
for c in candidates:
|
| 745 |
-
base_score = α * c["_dense"] + (1 - α) * c["_sparse"] / max_sparse
|
| 746 |
-
if intent == "hadith" and c.get("type") == "hadith":
|
| 747 |
-
base_score += cfg.HADITH_BOOST
|
| 748 |
-
c["_score"] = base_score
|
| 749 |
-
|
| 750 |
-
candidates.sort(key=lambda x: x["_score"], reverse=True)
|
| 751 |
-
results = candidates[:top_n]
|
| 752 |
-
|
| 753 |
-
await search_cache.set(results, *cache_key)
|
| 754 |
-
return results
|
| 755 |
-
|
| 756 |
-
|
| 757 |
-
def build_context(results: list) -> str:
|
| 758 |
-
"""Format search results into context block for LLM."""
|
| 759 |
-
lines = []
|
| 760 |
-
for i, r in enumerate(results, 1):
|
| 761 |
-
source = r.get("source") or r.get("reference") or "Unknown Source"
|
| 762 |
-
item_type = "Quranic Verse" if r.get("type") == "quran" else "Hadith"
|
| 763 |
-
grade_str = f" [Grade: {r.get('grade')}]" if r.get("grade") else ""
|
| 764 |
-
|
| 765 |
-
lines.append(
|
| 766 |
-
f"[{i}] 📌 {item_type}{grade_str} | {source} | score: {r.get('_score', 0):.3f}\n"
|
| 767 |
-
f" Arabic : {r.get('arabic', '')}\n"
|
| 768 |
-
f" English: {r.get('english', '')}"
|
| 769 |
-
)
|
| 770 |
-
return "\n\n".join(lines)
|
| 771 |
-
|
| 772 |
-
|
| 773 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 774 |
-
# PROMPT ENGINEERING
|
| 775 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 776 |
-
_PERSONA = (
|
| 777 |
-
"You are Sheikh QModel, a meticulous Islamic scholar with expertise "
|
| 778 |
-
"in Tafsir (Quranic exegesis), Hadith sciences, Fiqh, and Arabic. "
|
| 779 |
-
"You respond with scholarly rigor and modern clarity."
|
| 780 |
-
)
|
| 781 |
-
|
| 782 |
-
_TASK_INSTRUCTIONS: Dict[str, str] = {
|
| 783 |
-
"tafsir": (
|
| 784 |
-
"The user asks about a Quranic verse. Steps:\n"
|
| 785 |
-
"1. Identify the verse(s) from context.\n"
|
| 786 |
-
"2. Provide Tafsir: linguistic analysis and deeper meaning.\n"
|
| 787 |
-
"3. Draw connections to related verses.\n"
|
| 788 |
-
"4. Answer the user's question directly."
|
| 789 |
-
),
|
| 790 |
-
"hadith": (
|
| 791 |
-
"The user asks about a Hadith. Steps:\n"
|
| 792 |
-
"1. Quote the text EXACTLY from the context below.\n"
|
| 793 |
-
"2. Explain the meaning and implications.\n"
|
| 794 |
-
"3. Note any related Hadiths.\n"
|
| 795 |
-
"CRITICAL: If the Hadith is NOT in context, say so clearly."
|
| 796 |
-
),
|
| 797 |
-
"auth": (
|
| 798 |
-
"The user asks about Hadith authenticity. YOU MUST:\n"
|
| 799 |
-
"1. Check if the Hadith is in the context below.\n"
|
| 800 |
-
"2. If FOUND, state the grade (Sahih, Hasan, Da'if, etc.) confidently.\n"
|
| 801 |
-
"3. If found in Sahih Bukhari or Sahih Muslim, assert it is AUTHENTIC (Sahih).\n"
|
| 802 |
-
"4. Provide the Hadith text from context and explain its authenticity basis.\n"
|
| 803 |
-
"5. If NOT found after careful search, clearly state it's absent from the dataset.\n"
|
| 804 |
-
"CRITICAL: Use the context provided. Do not rely on your training data."
|
| 805 |
-
),
|
| 806 |
-
"fatwa": (
|
| 807 |
-
"The user seeks a religious ruling. Steps:\n"
|
| 808 |
-
"1. Gather evidence from Quran + Sunnah in context.\n"
|
| 809 |
-
"2. Reason step-by-step to a conclusion.\n"
|
| 810 |
-
"3. If insufficient, state so explicitly."
|
| 811 |
-
),
|
| 812 |
-
"count": (
|
| 813 |
-
"The user asks for word frequency. Steps:\n"
|
| 814 |
-
"1. State the ANALYSIS RESULT prominently.\n"
|
| 815 |
-
"2. List example occurrences with Surah names.\n"
|
| 816 |
-
"3. Comment on significance."
|
| 817 |
-
),
|
| 818 |
-
"surah_info": (
|
| 819 |
-
"The user asks about surah metadata. Steps:\n"
|
| 820 |
-
"1. State the answer from the SURAH INFORMATION block EXACTLY.\n"
|
| 821 |
-
"2. Use the total_verses number precisely — do NOT guess or calculate.\n"
|
| 822 |
-
"3. Mention the revelation type (Meccan/Medinan) if available.\n"
|
| 823 |
-
"4. Optionally add brief scholarly context about the surah."
|
| 824 |
-
),
|
| 825 |
-
"general": (
|
| 826 |
-
"The user has a general Islamic question. Steps:\n"
|
| 827 |
-
"1. Give a direct answer first.\n"
|
| 828 |
-
"2. Support with evidence from context.\n"
|
| 829 |
-
"3. Conclude with a summary."
|
| 830 |
-
),
|
| 831 |
-
}
|
| 832 |
-
|
| 833 |
-
_FORMAT_RULES = """\
|
| 834 |
-
For EVERY supporting evidence, use this exact format:
|
| 835 |
-
|
| 836 |
-
┌─────────────────────────────────────────────┐
|
| 837 |
-
│ ❝ {Arabic text} ❞
|
| 838 |
-
│ 📝 Translation: {English translation}
|
| 839 |
-
│ 📖 Source: {exact citation from context}
|
| 840 |
-
└─────────────────────────────────────────────┘
|
| 841 |
-
|
| 842 |
-
ABSOLUTE RULES:
|
| 843 |
-
• Use ONLY content from the Islamic Context block. Zero outside knowledge.
|
| 844 |
-
• Copy Arabic text and translations VERBATIM from context. Never paraphrase.
|
| 845 |
-
• If a specific Hadith/verse is NOT in context → respond with:
|
| 846 |
-
"هذا الحديث/الآية غير موجود في قاعدة البيانات." (Arabic)
|
| 847 |
-
or "This Hadith/verse is not in the available dataset." (English)
|
| 848 |
-
• Never invent or guess content.
|
| 849 |
-
• End with: "والله أعلم." (Arabic) or "And Allah knows best." (English)
|
| 850 |
-
"""
|
| 851 |
-
|
| 852 |
-
_SYSTEM_TEMPLATE = """\
|
| 853 |
-
{persona}
|
| 854 |
-
|
| 855 |
-
{lang_instruction}
|
| 856 |
-
|
| 857 |
-
=== YOUR TASK ===
|
| 858 |
-
{task}
|
| 859 |
-
|
| 860 |
-
=== OUTPUT FORMAT ===
|
| 861 |
-
{fmt}
|
| 862 |
-
|
| 863 |
-
=== ISLAMIC CONTEXT ===
|
| 864 |
-
{context}
|
| 865 |
-
=== END CONTEXT ===
|
| 866 |
-
"""
|
| 867 |
-
|
| 868 |
-
|
| 869 |
-
def build_messages(
|
| 870 |
-
context: str,
|
| 871 |
-
question: str,
|
| 872 |
-
lang: str,
|
| 873 |
-
intent: str,
|
| 874 |
-
analysis: Optional[dict] = None,
|
| 875 |
-
surah_info: Optional[dict] = None,
|
| 876 |
-
) -> List[dict]:
|
| 877 |
-
"""Build system and user messages for LLM."""
|
| 878 |
-
if surah_info:
|
| 879 |
-
info_block = (
|
| 880 |
-
f"\n[SURAH INFORMATION]\n"
|
| 881 |
-
f"Surah Name (Arabic): {surah_info['surah_name_ar']}\n"
|
| 882 |
-
f"Surah Name (English): {surah_info['surah_name_en']}\n"
|
| 883 |
-
f"Surah Number: {surah_info['surah_number']}\n"
|
| 884 |
-
f"Total Verses: {surah_info['total_verses']}\n"
|
| 885 |
-
f"Revelation Type: {surah_info['revelation_type']}\n"
|
| 886 |
-
f"Transliteration: {surah_info['surah_name_transliteration']}\n"
|
| 887 |
-
)
|
| 888 |
-
context = info_block + context
|
| 889 |
-
|
| 890 |
-
if analysis:
|
| 891 |
-
by_surah_str = "\n ".join([
|
| 892 |
-
f"Surah {s}: {data['name']} ({data['count']} times)"
|
| 893 |
-
for s, data in analysis["by_surah"].items()
|
| 894 |
-
])
|
| 895 |
-
analysis_block = (
|
| 896 |
-
f"\n[ANALYSIS RESULT]\n"
|
| 897 |
-
f"The keyword «{analysis['keyword']}» appears {analysis['total_count']} times.\n"
|
| 898 |
-
f" {by_surah_str}\n"
|
| 899 |
-
)
|
| 900 |
-
context = analysis_block + context
|
| 901 |
-
|
| 902 |
-
system = _SYSTEM_TEMPLATE.format(
|
| 903 |
-
persona=_PERSONA,
|
| 904 |
-
lang_instruction=language_instruction(lang),
|
| 905 |
-
task=_TASK_INSTRUCTIONS.get(intent, _TASK_INSTRUCTIONS["general"]),
|
| 906 |
-
fmt=_FORMAT_RULES,
|
| 907 |
-
context=context,
|
| 908 |
-
)
|
| 909 |
-
|
| 910 |
-
cot = {
|
| 911 |
-
"arabic": "فكّر خطوةً بخطوة، ثم أجب: ",
|
| 912 |
-
"mixed": "Think step by step: ",
|
| 913 |
-
}.get(lang, "Think step by step: ")
|
| 914 |
-
|
| 915 |
-
return [
|
| 916 |
-
{"role": "system", "content": system},
|
| 917 |
-
{"role": "user", "content": cot + question},
|
| 918 |
-
]
|
| 919 |
-
|
| 920 |
-
|
| 921 |
-
def _not_found_answer(lang: str) -> str:
|
| 922 |
-
"""Safe fallback when confidence is too low."""
|
| 923 |
-
if lang == "arabic":
|
| 924 |
-
return (
|
| 925 |
-
"لم أجد في قاعدة البيانات ما يكفي للإجابة على هذا السؤال بدقة.\n"
|
| 926 |
-
"يُرجى الرجوع إلى مصادر إسلامية موثوقة.\n"
|
| 927 |
-
"والله أعلم."
|
| 928 |
-
)
|
| 929 |
-
return (
|
| 930 |
-
"The available dataset does not contain sufficient information to answer "
|
| 931 |
-
"this question accurately.\nPlease refer to trusted Islamic sources.\n"
|
| 932 |
-
"And Allah knows best."
|
| 933 |
-
)
|
| 934 |
-
|
| 935 |
-
|
| 936 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 937 |
-
# HADITH GRADE INFERENCE
|
| 938 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 939 |
-
def infer_hadith_grade(item: dict) -> dict:
|
| 940 |
-
"""Infer hadith grade from collection name if not present."""
|
| 941 |
-
if item.get("type") != "hadith" or item.get("grade"):
|
| 942 |
-
return item
|
| 943 |
-
|
| 944 |
-
# Map collection names to grades
|
| 945 |
-
collection = item.get("collection", "").lower()
|
| 946 |
-
reference = item.get("reference", "").lower()
|
| 947 |
-
combined = f"{collection} {reference}"
|
| 948 |
-
|
| 949 |
-
# Sahih collections (highest authenticity)
|
| 950 |
-
if any(s in combined for s in ["sahih al-bukhari", "sahih bukhari", "bukhari"]):
|
| 951 |
-
item["grade"] = "Sahih"
|
| 952 |
-
elif any(s in combined for s in ["sahih muslim", "sahih al-muslim"]):
|
| 953 |
-
item["grade"] = "Sahih"
|
| 954 |
-
elif any(s in combined for s in ["sunan an-nasai", "sunan an-nasa", "nasa'i", "nasa"]):
|
| 955 |
-
item["grade"] = "Sahih"
|
| 956 |
-
# Hasan collections
|
| 957 |
-
elif any(s in combined for s in ["jami at-tirmidhi", "tirmidhi", "at-tirmidhi"]):
|
| 958 |
-
item["grade"] = "Hasan"
|
| 959 |
-
elif any(s in combined for s in ["sunan abu dawood", "abu dawood", "abo daud", "abou daoude"]):
|
| 960 |
-
item["grade"] = "Hasan"
|
| 961 |
-
elif any(s in combined for s in ["sunan ibn majah", "ibn majah", "ibn maja"]):
|
| 962 |
-
item["grade"] = "Hasan"
|
| 963 |
-
elif any(s in combined for s in ["muwatta malik", "muwatta", "malik"]):
|
| 964 |
-
item["grade"] = "Hasan"
|
| 965 |
-
# New collections from enrichment
|
| 966 |
-
elif any(s in combined for s in ["musnad ahmad", "ahmad", "ahmed"]):
|
| 967 |
-
item["grade"] = "Hasan/Sahih"
|
| 968 |
-
elif any(s in combined for s in ["sunan al-darimi", "darimi", "al-darimi"]):
|
| 969 |
-
item["grade"] = "Hasan"
|
| 970 |
-
|
| 971 |
-
return item
|
| 972 |
-
|
| 973 |
-
|
| 974 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 975 |
-
# APP STATE
|
| 976 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 977 |
-
class AppState:
|
| 978 |
-
embed_model: Optional[SentenceTransformer] = None
|
| 979 |
-
faiss_index: Optional[faiss.Index] = None
|
| 980 |
-
dataset: Optional[list] = None
|
| 981 |
-
llm: Optional[LLMProvider] = None
|
| 982 |
-
ready: bool = False
|
| 983 |
-
|
| 984 |
-
|
| 985 |
-
state = AppState()
|
| 986 |
-
|
| 987 |
-
|
| 988 |
-
@asynccontextmanager
|
| 989 |
-
async def lifespan(app: FastAPI):
|
| 990 |
-
"""Initialize state on startup."""
|
| 991 |
-
logger.info("⏳ Loading embed model: %s", cfg.EMBED_MODEL)
|
| 992 |
-
state.embed_model = SentenceTransformer(cfg.EMBED_MODEL)
|
| 993 |
-
|
| 994 |
-
logger.info("⏳ Loading FAISS index: %s", cfg.FAISS_INDEX)
|
| 995 |
-
state.faiss_index = faiss.read_index(cfg.FAISS_INDEX)
|
| 996 |
-
|
| 997 |
-
logger.info("⏳ Loading metadata: %s", cfg.METADATA_FILE)
|
| 998 |
-
with open(cfg.METADATA_FILE, "r", encoding="utf-8") as f:
|
| 999 |
-
state.dataset = json.load(f)
|
| 1000 |
-
|
| 1001 |
-
# Infer hadith grades from collection names
|
| 1002 |
-
state.dataset = [infer_hadith_grade(item) for item in state.dataset]
|
| 1003 |
-
|
| 1004 |
-
logger.info("⏳ Initializing LLM provider: %s", cfg.LLM_BACKEND)
|
| 1005 |
-
state.llm = get_llm_provider()
|
| 1006 |
-
|
| 1007 |
-
state.ready = True
|
| 1008 |
-
logger.info(
|
| 1009 |
-
"✅ QModel v4 ready | backend=%s | dataset=%d | faiss=%d | threshold=%.2f",
|
| 1010 |
-
cfg.LLM_BACKEND,
|
| 1011 |
-
len(state.dataset) if state.dataset else 0,
|
| 1012 |
-
state.faiss_index.ntotal if state.faiss_index else 0,
|
| 1013 |
-
cfg.CONFIDENCE_THRESHOLD,
|
| 1014 |
-
)
|
| 1015 |
-
yield
|
| 1016 |
-
state.ready = False
|
| 1017 |
-
logger.info("🛑 QModel shutdown")
|
| 1018 |
|
|
|
|
|
|
|
|
|
|
| 1019 |
|
| 1020 |
# ═══════════════════════════════════════════════════════════════════════
|
| 1021 |
# FASTAPI APP
|
| 1022 |
# ═══════════════════════════════════════════════════════════════════════
|
| 1023 |
app = FastAPI(
|
| 1024 |
-
title="QModel
|
| 1025 |
-
description=
|
| 1026 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1027 |
lifespan=lifespan,
|
| 1028 |
)
|
| 1029 |
|
|
@@ -1035,451 +61,11 @@ app.add_middleware(
|
|
| 1035 |
allow_headers=["*"],
|
| 1036 |
)
|
| 1037 |
|
| 1038 |
-
|
| 1039 |
-
|
| 1040 |
-
|
| 1041 |
-
|
| 1042 |
-
|
| 1043 |
-
role: str = Field(..., pattern="^(system|user|assistant)$")
|
| 1044 |
-
content: str = Field(..., min_length=1, max_length=4000)
|
| 1045 |
-
|
| 1046 |
-
|
| 1047 |
-
class AnalysisResult(BaseModel):
|
| 1048 |
-
keyword: str
|
| 1049 |
-
kw_stemmed: str
|
| 1050 |
-
total_count: int
|
| 1051 |
-
by_surah: Dict[int, Dict]
|
| 1052 |
-
examples: List[dict]
|
| 1053 |
-
|
| 1054 |
-
|
| 1055 |
-
class SourceItem(BaseModel):
|
| 1056 |
-
source: str
|
| 1057 |
-
type: str
|
| 1058 |
-
grade: Optional[str] = None
|
| 1059 |
-
arabic: str
|
| 1060 |
-
english: str
|
| 1061 |
-
_score: float
|
| 1062 |
-
|
| 1063 |
-
|
| 1064 |
-
class AskResponse(BaseModel):
|
| 1065 |
-
question: str
|
| 1066 |
-
answer: str
|
| 1067 |
-
language: str
|
| 1068 |
-
intent: str
|
| 1069 |
-
analysis: Optional[AnalysisResult] = None
|
| 1070 |
-
sources: List[SourceItem]
|
| 1071 |
-
top_score: float
|
| 1072 |
-
latency_ms: int
|
| 1073 |
-
|
| 1074 |
-
|
| 1075 |
-
class HadithVerifyResponse(BaseModel):
|
| 1076 |
-
query: str
|
| 1077 |
-
found: bool
|
| 1078 |
-
collection: Optional[str] = None
|
| 1079 |
-
grade: Optional[str] = None
|
| 1080 |
-
reference: Optional[str] = None
|
| 1081 |
-
arabic: Optional[str] = None
|
| 1082 |
-
english: Optional[str] = None
|
| 1083 |
-
latency_ms: int
|
| 1084 |
-
|
| 1085 |
-
|
| 1086 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 1087 |
-
# OPENAI-COMPATIBLE SCHEMAS (for Open-WebUI integration)
|
| 1088 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 1089 |
-
class ChatCompletionMessage(BaseModel):
|
| 1090 |
-
role: str = Field(..., description="Message role: system, user, or assistant")
|
| 1091 |
-
content: str = Field(..., description="Message content")
|
| 1092 |
-
|
| 1093 |
-
|
| 1094 |
-
class ChatCompletionRequest(BaseModel):
|
| 1095 |
-
model: str = Field(default="QModel", description="Model name")
|
| 1096 |
-
messages: List[ChatCompletionMessage] = Field(..., description="Messages for the model")
|
| 1097 |
-
temperature: Optional[float] = Field(default=cfg.TEMPERATURE, ge=0.0, le=2.0)
|
| 1098 |
-
top_p: Optional[float] = Field(default=1.0, ge=0.0, le=1.0)
|
| 1099 |
-
max_tokens: Optional[int] = Field(default=cfg.MAX_TOKENS, ge=1, le=8000)
|
| 1100 |
-
top_k: Optional[int] = Field(default=5, ge=1, le=20, description="Islamic sources to retrieve")
|
| 1101 |
-
stream: Optional[bool] = Field(default=False, description="Enable streaming responses")
|
| 1102 |
-
|
| 1103 |
-
|
| 1104 |
-
class ChatCompletionChoice(BaseModel):
|
| 1105 |
-
index: int
|
| 1106 |
-
message: ChatCompletionMessage
|
| 1107 |
-
finish_reason: str = "stop"
|
| 1108 |
-
|
| 1109 |
-
|
| 1110 |
-
class ChatCompletionResponse(BaseModel):
|
| 1111 |
-
id: str
|
| 1112 |
-
object: str = "chat.completion"
|
| 1113 |
-
created: int
|
| 1114 |
-
model: str
|
| 1115 |
-
choices: List[ChatCompletionChoice]
|
| 1116 |
-
usage: dict
|
| 1117 |
-
x_metadata: Optional[dict] = None # QModel-specific metadata
|
| 1118 |
-
|
| 1119 |
-
|
| 1120 |
-
class ModelInfo(BaseModel):
|
| 1121 |
-
id: str
|
| 1122 |
-
object: str = "model"
|
| 1123 |
-
created: int
|
| 1124 |
-
owned_by: str = "elgendy"
|
| 1125 |
-
permission: List[dict] = Field(default_factory=list)
|
| 1126 |
-
root: Optional[str] = None
|
| 1127 |
-
parent: Optional[str] = None
|
| 1128 |
-
|
| 1129 |
-
|
| 1130 |
-
class ModelsListResponse(BaseModel):
|
| 1131 |
-
object: str = "list"
|
| 1132 |
-
data: List[ModelInfo]
|
| 1133 |
-
|
| 1134 |
-
|
| 1135 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 1136 |
-
# CORE RAG PIPELINE
|
| 1137 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 1138 |
-
async def run_rag_pipeline(
|
| 1139 |
-
question: str,
|
| 1140 |
-
top_k: int = cfg.TOP_K_RETURN,
|
| 1141 |
-
source_type: Optional[Literal["quran", "hadith"]] = None,
|
| 1142 |
-
grade_filter: Optional[str] = None,
|
| 1143 |
-
) -> dict:
|
| 1144 |
-
"""Core RAG pipeline: rewrite → search → verify → generate."""
|
| 1145 |
-
t0 = time.perf_counter()
|
| 1146 |
-
|
| 1147 |
-
# 1. Query rewriting
|
| 1148 |
-
rewrite = await rewrite_query(question, state.llm)
|
| 1149 |
-
intent = rewrite.get("intent", "general")
|
| 1150 |
-
|
| 1151 |
-
# 2. Surah info detection + analysis intent + hybrid search — concurrently
|
| 1152 |
-
surah_task = detect_surah_info(question, rewrite)
|
| 1153 |
-
kw_task, search_task = (
|
| 1154 |
-
detect_analysis_intent(question, rewrite),
|
| 1155 |
-
hybrid_search(
|
| 1156 |
-
question, rewrite,
|
| 1157 |
-
state.embed_model, state.faiss_index, state.dataset,
|
| 1158 |
-
top_k, source_type, grade_filter,
|
| 1159 |
-
),
|
| 1160 |
-
)
|
| 1161 |
-
surah_det, analysis_kw, results = await asyncio.gather(
|
| 1162 |
-
surah_task, kw_task, search_task,
|
| 1163 |
-
)
|
| 1164 |
-
|
| 1165 |
-
# 3a. Surah metadata lookup (if detected)
|
| 1166 |
-
surah_info = None
|
| 1167 |
-
if surah_det:
|
| 1168 |
-
surah_info = await lookup_surah_info(surah_det["surah_query"], state.dataset)
|
| 1169 |
-
if surah_info:
|
| 1170 |
-
intent = "surah_info"
|
| 1171 |
-
logger.info(
|
| 1172 |
-
"Surah info: %s → %s (%d verses)",
|
| 1173 |
-
surah_det["surah_query"],
|
| 1174 |
-
surah_info["surah_name_en"],
|
| 1175 |
-
surah_info.get("total_verses", 0),
|
| 1176 |
-
)
|
| 1177 |
-
|
| 1178 |
-
# 3b. Keyword frequency count (if needed and NOT a surah info query)
|
| 1179 |
-
analysis = None
|
| 1180 |
-
if analysis_kw and not surah_info:
|
| 1181 |
-
analysis = await count_occurrences(analysis_kw, state.dataset)
|
| 1182 |
-
logger.info("Analysis: kw=%s count=%d", analysis_kw, analysis["total_count"])
|
| 1183 |
-
|
| 1184 |
-
# 4. Language detection
|
| 1185 |
-
lang = detect_language(question)
|
| 1186 |
-
top_score = results[0].get("_score", 0.0) if results else 0.0
|
| 1187 |
-
|
| 1188 |
-
logger.info(
|
| 1189 |
-
"Search done | intent=%s | top_score=%.3f | threshold=%.2f",
|
| 1190 |
-
intent, top_score, cfg.CONFIDENCE_THRESHOLD,
|
| 1191 |
-
)
|
| 1192 |
-
|
| 1193 |
-
# 5. Confidence gate — skip for surah_info (metadata is from dataset, not search)
|
| 1194 |
-
if not surah_info and top_score < cfg.CONFIDENCE_THRESHOLD:
|
| 1195 |
-
logger.warning(
|
| 1196 |
-
"Low confidence (%.3f < %.2f) — returning safe fallback",
|
| 1197 |
-
top_score, cfg.CONFIDENCE_THRESHOLD,
|
| 1198 |
-
)
|
| 1199 |
-
return {
|
| 1200 |
-
"answer": _not_found_answer(lang),
|
| 1201 |
-
"language": lang,
|
| 1202 |
-
"intent": intent,
|
| 1203 |
-
"analysis": analysis,
|
| 1204 |
-
"sources": results,
|
| 1205 |
-
"top_score": top_score,
|
| 1206 |
-
"latency_ms": int((time.perf_counter() - t0) * 1000),
|
| 1207 |
-
}
|
| 1208 |
-
|
| 1209 |
-
# 6. Build context + prompt + LLM call
|
| 1210 |
-
context = build_context(results)
|
| 1211 |
-
messages = build_messages(context, question, lang, intent, analysis, surah_info)
|
| 1212 |
-
|
| 1213 |
-
try:
|
| 1214 |
-
answer = await state.llm.chat(
|
| 1215 |
-
messages,
|
| 1216 |
-
max_tokens=cfg.MAX_TOKENS,
|
| 1217 |
-
temperature=cfg.TEMPERATURE,
|
| 1218 |
-
)
|
| 1219 |
-
except Exception as exc:
|
| 1220 |
-
logger.error("LLM call failed: %s", exc)
|
| 1221 |
-
raise HTTPException(status_code=502, detail="LLM service unavailable")
|
| 1222 |
-
|
| 1223 |
-
latency = int((time.perf_counter() - t0) * 1000)
|
| 1224 |
-
logger.info(
|
| 1225 |
-
"Pipeline done | intent=%s | lang=%s | top_score=%.3f | %d ms",
|
| 1226 |
-
intent, lang, top_score, latency,
|
| 1227 |
-
)
|
| 1228 |
-
|
| 1229 |
-
return {
|
| 1230 |
-
"answer": answer,
|
| 1231 |
-
"language": lang,
|
| 1232 |
-
"intent": intent,
|
| 1233 |
-
"analysis": analysis,
|
| 1234 |
-
"sources": results,
|
| 1235 |
-
"top_score": top_score,
|
| 1236 |
-
"latency_ms": latency,
|
| 1237 |
-
}
|
| 1238 |
-
|
| 1239 |
-
|
| 1240 |
-
def _check_ready():
|
| 1241 |
-
if not state.ready:
|
| 1242 |
-
raise HTTPException(
|
| 1243 |
-
status_code=503,
|
| 1244 |
-
detail="Service is still initialising. Please retry shortly.",
|
| 1245 |
-
)
|
| 1246 |
-
|
| 1247 |
-
|
| 1248 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 1249 |
-
# ENDPOINTS
|
| 1250 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 1251 |
-
@app.get("/health", tags=["ops"])
|
| 1252 |
-
def health():
|
| 1253 |
-
"""Health check endpoint."""
|
| 1254 |
-
return {
|
| 1255 |
-
"status": "ok" if state.ready else "initialising",
|
| 1256 |
-
"version": "4.0.0",
|
| 1257 |
-
"llm_backend": cfg.LLM_BACKEND,
|
| 1258 |
-
"dataset_size": len(state.dataset) if state.dataset else 0,
|
| 1259 |
-
"faiss_total": state.faiss_index.ntotal if state.faiss_index else 0,
|
| 1260 |
-
"confidence_threshold": cfg.CONFIDENCE_THRESHOLD,
|
| 1261 |
-
}
|
| 1262 |
-
|
| 1263 |
-
|
| 1264 |
-
@app.get("/v1/models", response_model=ModelsListResponse, tags=["models"])
|
| 1265 |
-
def list_models():
|
| 1266 |
-
"""List available models (OpenAI-compatible)."""
|
| 1267 |
-
return ModelsListResponse(
|
| 1268 |
-
data=[
|
| 1269 |
-
ModelInfo(
|
| 1270 |
-
id="QModel",
|
| 1271 |
-
created=int(time.time()),
|
| 1272 |
-
owned_by="elgendy",
|
| 1273 |
-
),
|
| 1274 |
-
ModelInfo(
|
| 1275 |
-
id="qmodel", # Lowercase variant for compatibility
|
| 1276 |
-
created=int(time.time()),
|
| 1277 |
-
owned_by="elgendy",
|
| 1278 |
-
),
|
| 1279 |
-
]
|
| 1280 |
-
)
|
| 1281 |
-
|
| 1282 |
-
|
| 1283 |
-
@app.post("/v1/chat/completions", response_model=ChatCompletionResponse, tags=["inference"])
|
| 1284 |
-
async def chat_completions(request: ChatCompletionRequest):
|
| 1285 |
-
"""OpenAI-compatible chat completions endpoint (for Open-WebUI integration)."""
|
| 1286 |
-
_check_ready()
|
| 1287 |
-
|
| 1288 |
-
# Extract user message (last message with role="user")
|
| 1289 |
-
user_messages = [m.content for m in request.messages if m.role == "user"]
|
| 1290 |
-
if not user_messages:
|
| 1291 |
-
raise HTTPException(status_code=400, detail="No user message in request")
|
| 1292 |
-
|
| 1293 |
-
question = user_messages[-1]
|
| 1294 |
-
top_k = request.top_k or cfg.TOP_K_RETURN
|
| 1295 |
-
temperature = request.temperature or cfg.TEMPERATURE
|
| 1296 |
-
max_tokens = request.max_tokens or cfg.MAX_TOKENS
|
| 1297 |
-
|
| 1298 |
-
try:
|
| 1299 |
-
result = await run_rag_pipeline(question, top_k=top_k)
|
| 1300 |
-
except HTTPException:
|
| 1301 |
-
raise
|
| 1302 |
-
except Exception as exc:
|
| 1303 |
-
logger.error("Pipeline error: %s", exc)
|
| 1304 |
-
raise HTTPException(status_code=500, detail=str(exc))
|
| 1305 |
-
|
| 1306 |
-
# Handle streaming if requested
|
| 1307 |
-
if request.stream:
|
| 1308 |
-
return StreamingResponse(
|
| 1309 |
-
_stream_response(result, request.model),
|
| 1310 |
-
media_type="text/event-stream",
|
| 1311 |
-
)
|
| 1312 |
-
|
| 1313 |
-
# Format response in OpenAI schema
|
| 1314 |
-
return ChatCompletionResponse(
|
| 1315 |
-
id=f"qmodel-{int(time.time() * 1000)}",
|
| 1316 |
-
created=int(time.time()),
|
| 1317 |
-
model=request.model,
|
| 1318 |
-
choices=[
|
| 1319 |
-
ChatCompletionChoice(
|
| 1320 |
-
index=0,
|
| 1321 |
-
message=ChatCompletionMessage(
|
| 1322 |
-
role="assistant",
|
| 1323 |
-
content=result["answer"],
|
| 1324 |
-
),
|
| 1325 |
-
)
|
| 1326 |
-
],
|
| 1327 |
-
usage={
|
| 1328 |
-
"prompt_tokens": -1,
|
| 1329 |
-
"completion_tokens": -1,
|
| 1330 |
-
"total_tokens": -1,
|
| 1331 |
-
},
|
| 1332 |
-
x_metadata={
|
| 1333 |
-
"language": result["language"],
|
| 1334 |
-
"intent": result["intent"],
|
| 1335 |
-
"top_score": round(result["top_score"], 4),
|
| 1336 |
-
"latency_ms": result["latency_ms"],
|
| 1337 |
-
"sources_count": len(result["sources"]),
|
| 1338 |
-
"sources": [
|
| 1339 |
-
{
|
| 1340 |
-
"source": s.get("source") or s.get("reference", ""),
|
| 1341 |
-
"type": s.get("type", ""),
|
| 1342 |
-
"grade": s.get("grade"),
|
| 1343 |
-
"score": round(s.get("_score", 0), 4),
|
| 1344 |
-
}
|
| 1345 |
-
for s in result.get("sources", [])[:5]
|
| 1346 |
-
],
|
| 1347 |
-
"analysis": result.get("analysis"),
|
| 1348 |
-
},
|
| 1349 |
-
)
|
| 1350 |
-
|
| 1351 |
-
|
| 1352 |
-
async def _stream_response(result: dict, model: str):
|
| 1353 |
-
"""Stream response chunks in OpenAI format."""
|
| 1354 |
-
import json
|
| 1355 |
-
|
| 1356 |
-
# Send answer in chunks
|
| 1357 |
-
answer = result.get("answer", "")
|
| 1358 |
-
for line in answer.split("\n"):
|
| 1359 |
-
chunk = {
|
| 1360 |
-
"id": f"qmodel-{int(time.time() * 1000)}",
|
| 1361 |
-
"object": "chat.completion.chunk",
|
| 1362 |
-
"created": int(time.time()),
|
| 1363 |
-
"model": model,
|
| 1364 |
-
"choices": [{
|
| 1365 |
-
"index": 0,
|
| 1366 |
-
"delta": {"content": line + "\n"},
|
| 1367 |
-
"finish_reason": None,
|
| 1368 |
-
}],
|
| 1369 |
-
}
|
| 1370 |
-
yield f"data: {json.dumps(chunk)}\n\n"
|
| 1371 |
-
|
| 1372 |
-
# Send final chunk
|
| 1373 |
-
final_chunk = {
|
| 1374 |
-
"id": f"qmodel-{int(time.time() * 1000)}",
|
| 1375 |
-
"object": "chat.completion.chunk",
|
| 1376 |
-
"created": int(time.time()),
|
| 1377 |
-
"model": model,
|
| 1378 |
-
"choices": [{
|
| 1379 |
-
"index": 0,
|
| 1380 |
-
"delta": {},
|
| 1381 |
-
"finish_reason": "stop",
|
| 1382 |
-
}],
|
| 1383 |
-
}
|
| 1384 |
-
yield f"data: {json.dumps(final_chunk)}\n\n"
|
| 1385 |
-
yield "data: [DONE]\n\n"
|
| 1386 |
-
|
| 1387 |
-
|
| 1388 |
-
@app.get("/ask", response_model=AskResponse, tags=["inference"])
|
| 1389 |
-
async def ask(
|
| 1390 |
-
q: str = Query(..., min_length=1, max_length=1000, description="Your Islamic question"),
|
| 1391 |
-
top_k: int = Query(cfg.TOP_K_RETURN, ge=1, le=20, description="Number of sources"),
|
| 1392 |
-
source_type: Optional[str] = Query(None, description="Filter: quran|hadith"),
|
| 1393 |
-
grade_filter: Optional[str] = Query(None, description="Filter Hadith: sahih|hasan|,all"),
|
| 1394 |
-
):
|
| 1395 |
-
"""Main inference endpoint."""
|
| 1396 |
-
_check_ready()
|
| 1397 |
-
result = await run_rag_pipeline(q, top_k, source_type, grade_filter)
|
| 1398 |
-
|
| 1399 |
-
sources = [
|
| 1400 |
-
SourceItem(
|
| 1401 |
-
source=r.get("source") or r.get("reference") or "Unknown",
|
| 1402 |
-
type=r.get("type", "unknown"),
|
| 1403 |
-
grade=r.get("grade"),
|
| 1404 |
-
arabic=r.get("arabic", ""),
|
| 1405 |
-
english=r.get("english", ""),
|
| 1406 |
-
_score=r.get("_score", 0.0),
|
| 1407 |
-
)
|
| 1408 |
-
for r in result["sources"]
|
| 1409 |
-
]
|
| 1410 |
-
|
| 1411 |
-
return AskResponse(
|
| 1412 |
-
question=q,
|
| 1413 |
-
answer=result["answer"],
|
| 1414 |
-
language=result["language"],
|
| 1415 |
-
intent=result["intent"],
|
| 1416 |
-
analysis=result["analysis"],
|
| 1417 |
-
sources=sources,
|
| 1418 |
-
top_score=result["top_score"],
|
| 1419 |
-
latency_ms=result["latency_ms"],
|
| 1420 |
-
)
|
| 1421 |
-
|
| 1422 |
-
|
| 1423 |
-
@app.get("/hadith/verify", response_model=HadithVerifyResponse, tags=["hadith"])
|
| 1424 |
-
async def verify_hadith(
|
| 1425 |
-
q: str = Query(..., description="First few words or query of Hadith"),
|
| 1426 |
-
collection: Optional[str] = Query(None, description="Filter: bukhari|muslim|all"),
|
| 1427 |
-
):
|
| 1428 |
-
"""Verify if a Hadith is in authenticated collections."""
|
| 1429 |
-
_check_ready()
|
| 1430 |
-
t0 = time.perf_counter()
|
| 1431 |
-
|
| 1432 |
-
results = await hybrid_search(
|
| 1433 |
-
q, {"ar_query": q, "en_query": q, "keywords": q.split(), "intent": "hadith"},
|
| 1434 |
-
state.embed_model, state.faiss_index, state.dataset,
|
| 1435 |
-
top_n=5, source_type="hadith", grade_filter="sahih",
|
| 1436 |
-
)
|
| 1437 |
-
|
| 1438 |
-
if results:
|
| 1439 |
-
r = results[0]
|
| 1440 |
-
return HadithVerifyResponse(
|
| 1441 |
-
query=q,
|
| 1442 |
-
found=True,
|
| 1443 |
-
collection=r.get("collection"),
|
| 1444 |
-
grade=r.get("grade"),
|
| 1445 |
-
reference=r.get("reference"),
|
| 1446 |
-
arabic=r.get("arabic"),
|
| 1447 |
-
english=r.get("english"),
|
| 1448 |
-
latency_ms=int((time.perf_counter() - t0) * 1000),
|
| 1449 |
-
)
|
| 1450 |
-
|
| 1451 |
-
return HadithVerifyResponse(
|
| 1452 |
-
query=q,
|
| 1453 |
-
found=False,
|
| 1454 |
-
latency_ms=int((time.perf_counter() - t0) * 1000),
|
| 1455 |
-
)
|
| 1456 |
-
|
| 1457 |
-
|
| 1458 |
-
@app.get("/debug/scores", tags=["ops"])
|
| 1459 |
-
async def debug_scores(
|
| 1460 |
-
q: str = Query(..., min_length=1, max_length=1000),
|
| 1461 |
-
top_k: int = Query(10, ge=1, le=20),
|
| 1462 |
-
):
|
| 1463 |
-
"""Debug: inspect raw retrieval scores without LLM."""
|
| 1464 |
-
_check_ready()
|
| 1465 |
-
rewrite = await rewrite_query(q, state.llm)
|
| 1466 |
-
results = await hybrid_search(q, rewrite, state.embed_model, state.faiss_index, state.dataset, top_k)
|
| 1467 |
-
return {
|
| 1468 |
-
"intent": rewrite.get("intent"),
|
| 1469 |
-
"threshold": cfg.CONFIDENCE_THRESHOLD,
|
| 1470 |
-
"results": [
|
| 1471 |
-
{
|
| 1472 |
-
"rank": i + 1,
|
| 1473 |
-
"source": r.get("source") or r.get("reference"),
|
| 1474 |
-
"type": r.get("type"),
|
| 1475 |
-
"grade": r.get("grade"),
|
| 1476 |
-
"_dense": round(r.get("_dense", 0), 4),
|
| 1477 |
-
"_sparse": round(r.get("_sparse", 0), 4),
|
| 1478 |
-
"_score": round(r.get("_score", 0), 4),
|
| 1479 |
-
}
|
| 1480 |
-
for i, r in enumerate(results)
|
| 1481 |
-
],
|
| 1482 |
-
}
|
| 1483 |
|
| 1484 |
|
| 1485 |
if __name__ == "__main__":
|
|
|
|
| 1 |
"""
|
| 2 |
+
QModel v6 — Islamic RAG API
|
| 3 |
===========================
|
| 4 |
Specialized Quran & Hadith system with dual LLM backend support.
|
| 5 |
|
| 6 |
+
Modular architecture — see app/ package for implementation:
|
| 7 |
+
app/config.py – Config (env vars)
|
| 8 |
+
app/llm.py – LLM providers (Ollama, HuggingFace)
|
| 9 |
+
app/cache.py – TTL-LRU async cache
|
| 10 |
+
app/arabic_nlp.py – Arabic normalisation & stemming
|
| 11 |
+
app/search.py – Hybrid FAISS + BM25 search, text search
|
| 12 |
+
app/analysis.py – Intent detection, analytics, counting
|
| 13 |
+
app/prompts.py – Prompt engineering
|
| 14 |
+
app/models.py – Pydantic schemas
|
| 15 |
+
app/state.py – AppState, lifespan, RAG pipeline
|
| 16 |
+
app/routers/ – FastAPI routers (quran, hadith, chat, ops)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
"""
|
| 18 |
|
| 19 |
from __future__ import annotations
|
| 20 |
|
|
|
|
|
|
|
|
|
|
| 21 |
import logging
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
|
|
|
|
|
|
| 23 |
from dotenv import load_dotenv
|
| 24 |
+
from fastapi import FastAPI
|
| 25 |
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
load_dotenv()
|
| 28 |
|
|
|
|
|
|
|
|
|
|
| 29 |
logging.basicConfig(
|
| 30 |
level=logging.INFO,
|
| 31 |
format="%(asctime)s | %(levelname)-8s | %(name)s | %(message)s",
|
| 32 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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.config import cfg
|
| 35 |
+
from app.state import lifespan
|
| 36 |
+
from app.routers import chat, hadith, ops, quran
|
| 37 |
|
| 38 |
# ═══════════════════════════════════════════════════════════════════════
|
| 39 |
# FASTAPI APP
|
| 40 |
# ═══════════════════════════════════════════════════════════════════════
|
| 41 |
app = FastAPI(
|
| 42 |
+
title="QModel v6 — Islamic RAG API",
|
| 43 |
+
description=(
|
| 44 |
+
"Specialized Quran & Hadith system with dual LLM backend.\n\n"
|
| 45 |
+
"**Capabilities:**\n"
|
| 46 |
+
"- Quran verse lookup by text or topic\n"
|
| 47 |
+
"- Quran word frequency & analytics\n"
|
| 48 |
+
"- Hadith lookup by text or topic\n"
|
| 49 |
+
"- Hadith authenticity verification\n"
|
| 50 |
+
"- OpenAI-compatible chat completions"
|
| 51 |
+
),
|
| 52 |
+
version="5.0.0",
|
| 53 |
lifespan=lifespan,
|
| 54 |
)
|
| 55 |
|
|
|
|
| 61 |
allow_headers=["*"],
|
| 62 |
)
|
| 63 |
|
| 64 |
+
# Register routers
|
| 65 |
+
app.include_router(ops.router)
|
| 66 |
+
app.include_router(chat.router)
|
| 67 |
+
app.include_router(quran.router)
|
| 68 |
+
app.include_router(hadith.router)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
|
| 71 |
if __name__ == "__main__":
|
requirements.txt
CHANGED
|
@@ -1,21 +1,24 @@
|
|
| 1 |
# Web framework
|
| 2 |
-
fastapi=
|
| 3 |
-
uvicorn[standard]=
|
| 4 |
-
pydantic=
|
| 5 |
|
| 6 |
# Core: Embeddings & Search
|
| 7 |
-
sentence-transformers=
|
| 8 |
-
faiss-cpu=
|
| 9 |
-
numpy=
|
| 10 |
|
| 11 |
# Optional: HuggingFace backend
|
| 12 |
-
transformers=
|
| 13 |
-
torch=
|
| 14 |
-
accelerate=
|
| 15 |
|
| 16 |
# Optional: Ollama backend
|
| 17 |
-
ollama=
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
# Configuration & Data
|
| 20 |
-
python-dotenv=
|
| 21 |
-
requests=
|
|
|
|
| 1 |
# Web framework
|
| 2 |
+
fastapi>=0.104.1
|
| 3 |
+
uvicorn[standard]>=0.24.0
|
| 4 |
+
pydantic>=2.4.2
|
| 5 |
|
| 6 |
# Core: Embeddings & Search
|
| 7 |
+
sentence-transformers>=2.2.2
|
| 8 |
+
faiss-cpu>=1.7.4
|
| 9 |
+
numpy>=1.24.3
|
| 10 |
|
| 11 |
# Optional: HuggingFace backend
|
| 12 |
+
transformers>=4.34.1
|
| 13 |
+
torch>=2.1.1
|
| 14 |
+
accelerate>=0.24.1
|
| 15 |
|
| 16 |
# Optional: Ollama backend
|
| 17 |
+
ollama>=0.0.48
|
| 18 |
+
|
| 19 |
+
# Optional: GGUF backend (llama-cpp-python)
|
| 20 |
+
llama-cpp-python>=0.2.0
|
| 21 |
|
| 22 |
# Configuration & Data
|
| 23 |
+
python-dotenv>=1.0.0
|
| 24 |
+
requests>=2.31.0
|