Spaces:
Runtime error
Runtime error
Commit ยท
197a96c
0
Parent(s):
Deploy Modrik RAG assistant
Browse files- .dockerignore +8 -0
- .gitattributes +1 -0
- .gitignore +11 -0
- .streamlit/config.toml +2 -0
- Dockerfile +19 -0
- README.md +272 -0
- app.py +215 -0
- assets/logo.jpeg +0 -0
- assets/logo.png +0 -0
- core/__init__.py +0 -0
- core/ai_service.py +45 -0
- core/file_service.py +37 -0
- core/pii_guard.py +22 -0
- core/vector_store.py +74 -0
- data/labor_law_active.xlsx +0 -0
- data/labor_law_amended.xlsx +0 -0
- data/labor_law_repealed.xlsx +0 -0
- docker-compose.yml +7 -0
- entrypoint.sh +9 -0
- requirements.txt +9 -0
- scripts/ingest_labor_law.py +101 -0
- tests/test_pipeline.py +363 -0
.dockerignore
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.git
|
| 2 |
+
.venv/
|
| 3 |
+
__pycache__/
|
| 4 |
+
*.pyc
|
| 5 |
+
*.log
|
| 6 |
+
.env
|
| 7 |
+
.streamlit/secrets.toml
|
| 8 |
+
test_output.txt
|
.gitattributes
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
*.sh text eol=lf
|
.gitignore
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.env
|
| 2 |
+
.venv/
|
| 3 |
+
venv/
|
| 4 |
+
__pycache__/
|
| 5 |
+
*.pyc
|
| 6 |
+
.streamlit/secrets.toml
|
| 7 |
+
streamlit.log
|
| 8 |
+
*.log
|
| 9 |
+
archive/
|
| 10 |
+
index/*.index
|
| 11 |
+
index/*.pkl
|
.streamlit/config.toml
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[theme]
|
| 2 |
+
primaryColor = "#1B4F72"
|
Dockerfile
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
COPY requirements.txt .
|
| 6 |
+
RUN pip install --no-cache-dir --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host files.pythonhosted.org -r requirements.txt
|
| 7 |
+
|
| 8 |
+
COPY . .
|
| 9 |
+
|
| 10 |
+
RUN python -c "from sentence_transformers import SentenceTransformer; SentenceTransformer('intfloat/multilingual-e5-large')"
|
| 11 |
+
|
| 12 |
+
RUN chmod +x entrypoint.sh
|
| 13 |
+
|
| 14 |
+
ENV HF_HUB_OFFLINE=1
|
| 15 |
+
ENV TRANSFORMERS_OFFLINE=1
|
| 16 |
+
|
| 17 |
+
EXPOSE 8501
|
| 18 |
+
|
| 19 |
+
ENTRYPOINT ["./entrypoint.sh"]
|
README.md
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Modrik
|
| 3 |
+
emoji: ๐ต
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: indigo
|
| 6 |
+
sdk: docker
|
| 7 |
+
app_port: 8501
|
| 8 |
+
pinned: false
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
## โฆ Built at SDA Himmah Hackathon 2026
|
| 12 |
+
|
| 13 |
+
> Participated โ Modrik Team
|
| 14 |
+
---
|
| 15 |
+
|
| 16 |
+
<div align="center">
|
| 17 |
+
|
| 18 |
+
```
|
| 19 |
+
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 20 |
+
โ โ
|
| 21 |
+
โ M O D R I K โ
|
| 22 |
+
โ ู
ุฏุฑู โ
|
| 23 |
+
โ โ
|
| 24 |
+
โ Every worker deserves to know their โ
|
| 25 |
+
โ rights. โ
|
| 26 |
+
โ โ
|
| 27 |
+
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
**An Arabic-first AI legal assistant for Saudi Labor Law.**
|
| 31 |
+
Ask in plain Arabic. Upload your contract. Get an answer cited by article.
|
| 32 |
+
|
| 33 |
+
<br/>
|
| 34 |
+
|
| 35 |
+

|
| 36 |
+

|
| 37 |
+

|
| 38 |
+

|
| 39 |
+

|
| 40 |
+
|
| 41 |
+
</div>
|
| 42 |
+
|
| 43 |
+
---
|
| 44 |
+
|
| 45 |
+
## โฆ What is Modrik?
|
| 46 |
+
|
| 47 |
+
Saudi Labor Law spans hundreds of articles across three states โ active, amended, and repealed โ and most workers never open it until they're already in a dispute.
|
| 48 |
+
|
| 49 |
+
**Modrik (ู
ุฏุฑู)** lets anyone ask about their rights in plain Arabic, upload their actual contract or case file, and get a personal answer grounded in the specific article that applies โ not a generic summary.
|
| 50 |
+
|
| 51 |
+
> *"ูู ุนูุฏู ูุทุงุจู ูุธุงู
ุงูุนู
ูุ"*
|
| 52 |
+
> Modrik reads your contract, retrieves the relevant articles โ whether still in force, amended, or repealed โ and tells you exactly where you stand, citing the law instead of guessing.
|
| 53 |
+
|
| 54 |
+
---
|
| 55 |
+
|
| 56 |
+
## โฆ How a question gets answered
|
| 57 |
+
|
| 58 |
+
```
|
| 59 |
+
USER ASKS A QUESTION (+ optional contract / case file)
|
| 60 |
+
โ
|
| 61 |
+
โผ
|
| 62 |
+
โโโโโโโโโโโโโโโโโโโโโ
|
| 63 |
+
โ PII GUARD โ redacts Saudi ID / IBAN
|
| 64 |
+
โ (regex) โ before anything is sent
|
| 65 |
+
โโโโโโโโโโโฌโโโโโโโโโโ
|
| 66 |
+
โ
|
| 67 |
+
โโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโ
|
| 68 |
+
โผ โผ
|
| 69 |
+
UPLOADED FILE FAISS RETRIEVAL
|
| 70 |
+
(txt / pdf extracted) query embedded with
|
| 71 |
+
multilingual-e5-large
|
| 72 |
+
โ top-k matching Labor
|
| 73 |
+
Law articles, local
|
| 74 |
+
โโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโ
|
| 75 |
+
โผ
|
| 76 |
+
โโโโโโโโโโโโโโโโโโโโโ
|
| 77 |
+
โ GPT-4o-mini โ streamed response,
|
| 78 |
+
โ (streamed) โ cites article numbers,
|
| 79 |
+
โโโโโโโโโโโฌโโโโโโโโโโ flags amended/repealed
|
| 80 |
+
โผ
|
| 81 |
+
ANSWER + SOURCES POPOVER
|
| 82 |
+
(article matches with similarity %)
|
| 83 |
+
```
|
| 84 |
+
|
| 85 |
+
| Step | What happens |
|
| 86 |
+
|------|---------------|
|
| 87 |
+
| **Input** | User types in Arabic (or English) and may attach a `.txt`/`.pdf` contract or case document |
|
| 88 |
+
| **Privacy guard** | Saudi National ID/Iqama numbers and IBANs are regex-redacted before anything leaves the session |
|
| 89 |
+
| **Retrieval** | The query is embedded locally with `multilingual-e5-large` and FAISS searches the Labor Law index (active + amended + repealed) for the top-k matching articles |
|
| 90 |
+
| **Generation** | GPT-4o-mini streams a personalized answer, always citing the article number and flagging amended/repealed status |
|
| 91 |
+
| **Transparency** | A sources popover shows the exact retrieved articles with similarity scores, plus the contract excerpt actually used |
|
| 92 |
+
|
| 93 |
+
---
|
| 94 |
+
|
| 95 |
+
## โฆ Tech stack
|
| 96 |
+
|
| 97 |
+
```
|
| 98 |
+
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 99 |
+
โ FRONTEND / UI โ
|
| 100 |
+
โ Streamlit ยท RTL Arabic chat interface โ
|
| 101 |
+
โโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 102 |
+
โ
|
| 103 |
+
โโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโ๏ฟฝ๏ฟฝโโโโ
|
| 104 |
+
โ core/ โ
|
| 105 |
+
โ โ
|
| 106 |
+
โ โโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โ
|
| 107 |
+
โ โ pii_guard โ โ file_service โ โ vector_storeโ โ
|
| 108 |
+
โ โ regex โ โ PyMuPDF โ โ FAISS, โ โ
|
| 109 |
+
โ โ redaction โ โ txt / pdf โ โ local, free โ โ
|
| 110 |
+
โ โโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ โโโโโโโโฌโโโโโโโ โ
|
| 111 |
+
โ โ โ
|
| 112 |
+
โ โโโโโโโโโผโโโโโโโโ โ
|
| 113 |
+
โ โ ai_service โ โ
|
| 114 |
+
โ โ OpenAI streamโ โ
|
| 115 |
+
โ โโโโโโโโโโโโโโโโโ โ
|
| 116 |
+
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 117 |
+
```
|
| 118 |
+
|
| 119 |
+
| Layer | Technology |
|
| 120 |
+
|-------|-----------|
|
| 121 |
+
| LLM | OpenAI GPT-4o-mini, streamed token-by-token |
|
| 122 |
+
| Embeddings | `intfloat/multilingual-e5-large`, run locally (see below) |
|
| 123 |
+
| Vector store | FAISS (`IndexFlatIP` over normalized vectors) |
|
| 124 |
+
| PDF / text extraction | PyMuPDF (`fitz`) |
|
| 125 |
+
| Law ingestion | pandas + openpyxl โ Excel โ smart-chunked articles |
|
| 126 |
+
| Privacy | regex-based PII redaction (Saudi ID/Iqama, IBAN) |
|
| 127 |
+
| UI | Streamlit, RTL layout, custom CSS, IBM Plex Sans Arabic |
|
| 128 |
+
| Deployment | Docker / docker-compose, Hugging Face Spaces |
|
| 129 |
+
|
| 130 |
+
---
|
| 131 |
+
|
| 132 |
+
## โฆ Why this embedding model
|
| 133 |
+
|
| 134 |
+
Most RAG demos default straight to an embedding API. Modrik instead runs `multilingual-e5-large` **locally** โ the multilingual E5 model โ picked after comparing leading multilingual embedding models against published Arabic retrieval benchmarks (MIRACL, MTEB), where it consistently ranks among the strongest open models for Arabic semantic search. That matters here specifically: Saudi Labor Law articles are dense, formal legal Arabic, not casual text.
|
| 135 |
+
|
| 136 |
+
The practical upside: embedding has zero per-query API cost, and the index โ active, amended, and repealed articles โ is pre-warmed at container startup, so retrieval is instant from the first question.
|
| 137 |
+
|
| 138 |
+
---
|
| 139 |
+
|
| 140 |
+
## โฆ Smart law ingestion
|
| 141 |
+
|
| 142 |
+
Saudi Labor Law isn't one flat document โ articles get amended or repealed, and the old text still matters for context. `scripts/ingest_labor_law.py` ingests three separate sources and tags each one:
|
| 143 |
+
|
| 144 |
+
| Source | Tag shown to the model |
|
| 145 |
+
|--------|------------------------|
|
| 146 |
+
| `labor_law_active.xlsx` | โ
ูุธุงู
ูุดุท ูุณุงุฑู ุญุงููุงู |
|
| 147 |
+
| `labor_law_amended.xlsx` | โ ๏ธ ูุฐู ุงูู
ุงุฏุฉ ู
ุนุฏููุฉ |
|
| 148 |
+
| `labor_law_repealed.xlsx` | ๐ซ ูุฐู ุงูู
ุงุฏุฉ ู
ูุบุงุฉ ููุง ุชูุทุจููู ุญุงููุงู |
|
| 149 |
+
|
| 150 |
+
Articles longer than 600 characters are split on definition markers or paragraph breaks first, then merged back up to the chunk limit โ so no sub-chunk ever loses its article header or keyword context.
|
| 151 |
+
|
| 152 |
+
---
|
| 153 |
+
|
| 154 |
+
## โฆ Project structure
|
| 155 |
+
|
| 156 |
+
```
|
| 157 |
+
Modrik/
|
| 158 |
+
โ
|
| 159 |
+
โโโ app.py โ Streamlit entry point (chat UI, RTL Arabic)
|
| 160 |
+
โโโ core/
|
| 161 |
+
โ โโโ ai_service.py โ OpenAI streaming + system prompt
|
| 162 |
+
โ โโโ file_service.py โ txt/pdf extraction + chunking
|
| 163 |
+
โ โโโ pii_guard.py โ Saudi ID / IBAN redaction
|
| 164 |
+
โ โโโ vector_store.py โ FAISS index, embed/retrieve
|
| 165 |
+
โโโ scripts/
|
| 166 |
+
โ โโโ ingest_labor_law.py โ builds the FAISS index from Excel sources
|
| 167 |
+
โโโ tests/
|
| 168 |
+
โ โโโ test_pipeline.py โ full unit test suite
|
| 169 |
+
โโโ data/ โ active / amended / repealed Labor Law (Excel)
|
| 170 |
+
โโโ index/ โ FAISS index + chunks (generated)
|
| 171 |
+
โโโ assets/ โ logo
|
| 172 |
+
โโโ Dockerfile / docker-compose.yml / entrypoint.sh
|
| 173 |
+
โโโ requirements.txt
|
| 174 |
+
```
|
| 175 |
+
|
| 176 |
+
---
|
| 177 |
+
|
| 178 |
+
## โฆ Tests
|
| 179 |
+
|
| 180 |
+
Every public function ships with a test: chunking edge cases, `.txt`/`.pdf` extraction (PDF mocked via `fitz`), the OpenAI streaming contract, vector store retrieval, and every PII redaction pattern.
|
| 181 |
+
|
| 182 |
+
```bash
|
| 183 |
+
python -m pytest tests/ -v
|
| 184 |
+
```
|
| 185 |
+
|
| 186 |
+
---
|
| 187 |
+
|
| 188 |
+
## โฆ Privacy by default
|
| 189 |
+
|
| 190 |
+
Before any text โ typed or uploaded โ reaches OpenAI or gets logged, `core/pii_guard.py` strips Saudi National ID/Iqama numbers and IBANs with a regex pass, replaces them with `[ุฑูู
ูููุฉ]` / `[ุฑูู
IBAN]`, and tells the user how many were redacted. No opt-in required, no configuration needed.
|
| 191 |
+
|
| 192 |
+
---
|
| 193 |
+
|
| 194 |
+
## โฆ Quick start
|
| 195 |
+
|
| 196 |
+
### Requirements
|
| 197 |
+
- [Docker Desktop](https://www.docker.com/products/docker-desktop/) installed and running
|
| 198 |
+
- An OpenAI API key
|
| 199 |
+
|
| 200 |
+
### 1 โ Copy the env file and add your key
|
| 201 |
+
|
| 202 |
+
```bash
|
| 203 |
+
cp .env.example .env
|
| 204 |
+
```
|
| 205 |
+
|
| 206 |
+
Open `.env` and fill in your key:
|
| 207 |
+
|
| 208 |
+
```
|
| 209 |
+
OPENAI_API_KEY=sk-...
|
| 210 |
+
```
|
| 211 |
+
|
| 212 |
+
### 2 โ Build and start
|
| 213 |
+
|
| 214 |
+
```bash
|
| 215 |
+
docker-compose up --build
|
| 216 |
+
```
|
| 217 |
+
|
| 218 |
+
On first run, the FAISS index is built automatically (~1-2 minutes). Subsequent starts are instant.
|
| 219 |
+
|
| 220 |
+
### 3 โ Open in browser
|
| 221 |
+
|
| 222 |
+
```
|
| 223 |
+
http://localhost:8501
|
| 224 |
+
```
|
| 225 |
+
|
| 226 |
+
### SSL error on corporate / university networks
|
| 227 |
+
|
| 228 |
+
```
|
| 229 |
+
SSLError: certificate verify failed
|
| 230 |
+
```
|
| 231 |
+
|
| 232 |
+
This is caused by a firewall or SSL-inspecting proxy. The fix is already included in the `Dockerfile` โ no extra steps needed.
|
| 233 |
+
|
| 234 |
+
### Useful commands
|
| 235 |
+
|
| 236 |
+
```bash
|
| 237 |
+
# Stream logs
|
| 238 |
+
docker-compose logs -f
|
| 239 |
+
|
| 240 |
+
# Stop the project
|
| 241 |
+
docker-compose down
|
| 242 |
+
|
| 243 |
+
# Rebuild after code or requirements.txt changes
|
| 244 |
+
docker-compose up --build
|
| 245 |
+
|
| 246 |
+
# Run the test suite
|
| 247 |
+
python -m pytest tests/ -v
|
| 248 |
+
```
|
| 249 |
+
|
| 250 |
+
---
|
| 251 |
+
|
| 252 |
+
## โฆ Roadmap
|
| 253 |
+
|
| 254 |
+
| Status | Feature |
|
| 255 |
+
|--------|---------|
|
| 256 |
+
| โ
| RAG over active / amended / repealed Labor Law articles |
|
| 257 |
+
| โ
| Contract & case file upload (`.txt`/`.pdf`) with personalized analysis |
|
| 258 |
+
| โ
| Automatic PII redaction (Saudi ID, IBAN) |
|
| 259 |
+
| โ
| Source transparency โ article + similarity score popover |
|
| 260 |
+
| โ
| Full automated test suite |
|
| 261 |
+
| โ
| Dockerized, one-command run |
|
| 262 |
+
| ๐ | More legal domains beyond Labor Law |
|
| 263 |
+
| ๐ | Multi-turn case memory across sessions |
|
| 264 |
+
| ๐ | Export consultation as PDF |
|
| 265 |
+
|
| 266 |
+
---
|
| 267 |
+
|
| 268 |
+
<div align="center">
|
| 269 |
+
|
| 270 |
+
*Every worker deserves to know where they stand.*
|
| 271 |
+
|
| 272 |
+
</div>
|
app.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dotenv import load_dotenv
|
| 2 |
+
import streamlit as st
|
| 3 |
+
from core.ai_service import stream_response
|
| 4 |
+
from core.file_service import extract_text
|
| 5 |
+
from core.vector_store import load_from_disk, retrieve_with_scores, is_loaded
|
| 6 |
+
from core.pii_guard import redact_pii
|
| 7 |
+
|
| 8 |
+
load_dotenv()
|
| 9 |
+
|
| 10 |
+
st.set_page_config(
|
| 11 |
+
page_title="Mudrik",
|
| 12 |
+
page_icon="๐ต",
|
| 13 |
+
layout="wide",
|
| 14 |
+
initial_sidebar_state="collapsed",
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
st.markdown("""
|
| 18 |
+
<style>
|
| 19 |
+
@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Sans+Arabic:wght@400;500;600;700&display=swap');
|
| 20 |
+
|
| 21 |
+
html, body, [class*="css"] { font-family: 'IBM Plex Sans Arabic', sans-serif; }
|
| 22 |
+
|
| 23 |
+
#MainMenu, footer, header { visibility: hidden; }
|
| 24 |
+
[data-testid="stSidebar"] { display: none; }
|
| 25 |
+
.block-container { padding-top: 2rem; padding-bottom: 7rem; max-width: 760px; }
|
| 26 |
+
[data-testid="stAppViewContainer"], body, html { background: #FAFEFE; direction: rtl; }
|
| 27 |
+
|
| 28 |
+
/* โโ Scrollbar styling only โ don't touch overflow/flex โโ */
|
| 29 |
+
::-webkit-scrollbar { width: 6px; }
|
| 30 |
+
::-webkit-scrollbar-track { background: transparent; }
|
| 31 |
+
::-webkit-scrollbar-thumb { background: #D0F0F3; border-radius: 4px; }
|
| 32 |
+
::-webkit-scrollbar-thumb:hover { background: #B2E8EC; }
|
| 33 |
+
|
| 34 |
+
/* โโ Header โโ */
|
| 35 |
+
.top-header { text-align: center; padding: 0 0 1.4rem; }
|
| 36 |
+
.top-header h1 { font-size: 2.4rem; font-weight: 700; color: #1A9AA8; margin: 0 0 0.2rem; }
|
| 37 |
+
.top-header p { font-size: 1rem; color: #8FC9CE; margin: 0; }
|
| 38 |
+
[data-testid="stHeaderActionElements"] { display: none !important; }
|
| 39 |
+
|
| 40 |
+
/* โโ File tag โโ */
|
| 41 |
+
.file-tag {
|
| 42 |
+
background: #E6F9FA;
|
| 43 |
+
border: 1px solid #B2E8EC;
|
| 44 |
+
border-radius: 8px;
|
| 45 |
+
padding: 0.3rem 0.8rem;
|
| 46 |
+
font-size: 0.8rem;
|
| 47 |
+
color: #1A9AA8;
|
| 48 |
+
display: inline-block;
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
/* โโ Chat messages โโ */
|
| 52 |
+
[data-testid="stChatMessage"] { gap: 0.7rem; }
|
| 53 |
+
[data-testid="stChatMessage"]:has([data-testid="stChatMessageAvatarUser"]) {
|
| 54 |
+
background: #E6F9FA;
|
| 55 |
+
border-radius: 1.1rem;
|
| 56 |
+
padding: 0.75rem 1.15rem;
|
| 57 |
+
max-width: 75%;
|
| 58 |
+
margin-left: auto;
|
| 59 |
+
margin-right: 0;
|
| 60 |
+
text-align: right;
|
| 61 |
+
}
|
| 62 |
+
[data-testid="stChatMessage"]:has([data-testid="stChatMessageAvatarAssistant"]) {
|
| 63 |
+
background: transparent;
|
| 64 |
+
padding: 0.3rem 0 0.6rem;
|
| 65 |
+
}
|
| 66 |
+
[data-testid="stChatMessageAvatarUser"], [data-testid="stChatMessageAvatarAssistant"] {
|
| 67 |
+
background: #1A9AA8 !important;
|
| 68 |
+
color: #fff !important;
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
/* โโ Chat input โโ */
|
| 72 |
+
[data-testid="stChatInput"] textarea {
|
| 73 |
+
border: 1.5px solid #D8F1F3 !important;
|
| 74 |
+
border-radius: 1.4rem !important;
|
| 75 |
+
background: #FFFFFF !important;
|
| 76 |
+
font-size: 0.95rem !important;
|
| 77 |
+
padding: 0.85rem 1.2rem !important;
|
| 78 |
+
}
|
| 79 |
+
[data-testid="stChatInput"] textarea:focus {
|
| 80 |
+
border-color: #4ECDD4 !important;
|
| 81 |
+
box-shadow: 0 0 0 3px rgba(78,205,212,0.15) !important;
|
| 82 |
+
}
|
| 83 |
+
[data-testid="stChatInputFileUploadButton"],
|
| 84 |
+
[data-testid="stChatInputSubmitButton"] {
|
| 85 |
+
color: #1A9AA8 !important;
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
/* โโ Sources expander scrollable โโ */
|
| 89 |
+
[data-testid="stExpanderDetails"] {
|
| 90 |
+
max-height: 420px;
|
| 91 |
+
overflow-y: auto;
|
| 92 |
+
overflow-x: hidden;
|
| 93 |
+
}
|
| 94 |
+
[data-testid="stExpanderDetails"]::-webkit-scrollbar { width: 6px; }
|
| 95 |
+
[data-testid="stExpanderDetails"]::-webkit-scrollbar-track { background: transparent; }
|
| 96 |
+
[data-testid="stExpanderDetails"]::-webkit-scrollbar-thumb {
|
| 97 |
+
background: #B2E8EC;
|
| 98 |
+
border-radius: 4px;
|
| 99 |
+
}
|
| 100 |
+
</style>
|
| 101 |
+
""", unsafe_allow_html=True)
|
| 102 |
+
|
| 103 |
+
# โโ Load vector index once per session โโโโโโโโโโโโโโโโโโโโโโโโ
|
| 104 |
+
if "rag_ready" not in st.session_state:
|
| 105 |
+
st.session_state.rag_ready = load_from_disk()
|
| 106 |
+
|
| 107 |
+
# โโ Session state โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 108 |
+
if "messages" not in st.session_state:
|
| 109 |
+
st.session_state.messages = []
|
| 110 |
+
if "file_text" not in st.session_state:
|
| 111 |
+
st.session_state.file_text = ""
|
| 112 |
+
if "file_name" not in st.session_state:
|
| 113 |
+
st.session_state.file_name = ""
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
# โโ Logo + title โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 117 |
+
col1, col2, col3 = st.columns([1, 1, 1])
|
| 118 |
+
with col2:
|
| 119 |
+
st.image("assets/logo.png", use_container_width=True)
|
| 120 |
+
|
| 121 |
+
st.markdown("""
|
| 122 |
+
<div class="top-header">
|
| 123 |
+
<h1>ู
ุฏุฑู</h1>
|
| 124 |
+
<p>ู
ุณุงุนุฏู ุงูุฐูู ูููู
ูุธุงู
ุงูุนู
ู ุงูุณุนูุฏู</p>
|
| 125 |
+
</div>
|
| 126 |
+
""", unsafe_allow_html=True)
|
| 127 |
+
|
| 128 |
+
# โโ Helper functions โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 129 |
+
def show_sources(scored_chunks: list[tuple[str, float]], file_text: str, msg_id: str):
|
| 130 |
+
parts = []
|
| 131 |
+
if scored_chunks:
|
| 132 |
+
parts.append(f"{len(scored_chunks)} ู
ูุงุฏ ู
ู ูุธุงู
ุงูุนู
ู")
|
| 133 |
+
if file_text:
|
| 134 |
+
parts.append("ู
ูู ุงูุนูุฏ")
|
| 135 |
+
if not parts:
|
| 136 |
+
return
|
| 137 |
+
with st.popover(f"ุงูู
ุตุงุฏุฑ โ {' ยท '.join(parts)}"):
|
| 138 |
+
if file_text:
|
| 139 |
+
st.markdown("**ู
ูู ุงูุนูุฏ ุงูู
ุฑููุน**")
|
| 140 |
+
preview = file_text[:2000] + ("โฆ" if len(file_text) > 2000 else "")
|
| 141 |
+
st.text_area("", value=preview, height=180, disabled=True, key=f"file_{msg_id}", label_visibility="collapsed")
|
| 142 |
+
if scored_chunks:
|
| 143 |
+
st.divider()
|
| 144 |
+
for i, (chunk, score) in enumerate(scored_chunks, 1):
|
| 145 |
+
pct = int(score * 100)
|
| 146 |
+
color = "#1A9AA8" if pct >= 70 else "#F39C12" if pct >= 50 else "#999"
|
| 147 |
+
st.markdown(
|
| 148 |
+
f"**ุงูู
ุงุฏุฉ {i}** "
|
| 149 |
+
f'<span style="font-size:0.75rem;color:{color};">ุชุทุงุจู {pct}%</span>',
|
| 150 |
+
unsafe_allow_html=True,
|
| 151 |
+
)
|
| 152 |
+
st.text_area("", value=chunk, height=130, disabled=True, key=f"chunk_{msg_id}_{i}", label_visibility="collapsed")
|
| 153 |
+
if i < len(scored_chunks):
|
| 154 |
+
st.divider()
|
| 155 |
+
|
| 156 |
+
def send(prompt: str):
|
| 157 |
+
clean_prompt, pii_count = redact_pii(prompt)
|
| 158 |
+
st.session_state.messages.append({"role": "user", "content": clean_prompt})
|
| 159 |
+
with st.chat_message("user"):
|
| 160 |
+
st.markdown(clean_prompt)
|
| 161 |
+
if pii_count:
|
| 162 |
+
st.caption(f"ุชู
ุฅุฎูุงุก {pii_count} ุจูุงูุงุช ุญุณุงุณุฉ ุชููุงุฆูุงู")
|
| 163 |
+
|
| 164 |
+
scored_chunks = retrieve_with_scores(clean_prompt, k=5) if is_loaded() else []
|
| 165 |
+
file_text = st.session_state.file_text
|
| 166 |
+
|
| 167 |
+
context_parts = []
|
| 168 |
+
if file_text:
|
| 169 |
+
context_parts.append(f"=== ู
ูู ุงููุถูุฉ ===\n{file_text}")
|
| 170 |
+
if scored_chunks:
|
| 171 |
+
law_text = "\n\n---\n\n".join(chunk for chunk, _ in scored_chunks)
|
| 172 |
+
context_parts.append(f"=== ู
ูุงุฏ ูุธุงู
ุงูุนู
ู ุฐุงุช ุงูุตูุฉ ===\n{law_text}")
|
| 173 |
+
context = "\n\n".join(context_parts)
|
| 174 |
+
|
| 175 |
+
with st.chat_message("assistant", avatar="โจ"):
|
| 176 |
+
response = st.write_stream(stream_response(prompt, context=context))
|
| 177 |
+
|
| 178 |
+
show_sources(scored_chunks, file_text, msg_id=f"live_{len(st.session_state.messages)}")
|
| 179 |
+
st.session_state.messages.append({
|
| 180 |
+
"role": "assistant",
|
| 181 |
+
"content": response,
|
| 182 |
+
"scored_chunks": scored_chunks,
|
| 183 |
+
"file_text": file_text,
|
| 184 |
+
})
|
| 185 |
+
|
| 186 |
+
# โโ Chat โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 187 |
+
for idx, msg in enumerate(st.session_state.messages):
|
| 188 |
+
with st.chat_message(msg["role"], avatar="โจ" if msg["role"] == "assistant" else None):
|
| 189 |
+
st.markdown(msg["content"])
|
| 190 |
+
if msg["role"] == "assistant":
|
| 191 |
+
show_sources(msg.get("scored_chunks", []), msg.get("file_text", ""), msg_id=f"hist_{idx}")
|
| 192 |
+
|
| 193 |
+
prompt = st.chat_input(
|
| 194 |
+
"ุงุณุฃููู ุนู ูุถุนู ูู ุงูุนูุฏโฆ",
|
| 195 |
+
accept_file=True,
|
| 196 |
+
file_type=["txt", "pdf"],
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
if prompt and prompt.files:
|
| 200 |
+
uploaded_file = prompt.files[0]
|
| 201 |
+
with st.spinner("ุฌุงุฑู ูุฑุงุกุฉ ุงูู
ููโฆ"):
|
| 202 |
+
raw_text = extract_text(uploaded_file)
|
| 203 |
+
redacted_text, pii_count = redact_pii(raw_text)
|
| 204 |
+
st.session_state.file_text = redacted_text
|
| 205 |
+
st.session_state.file_name = uploaded_file.name
|
| 206 |
+
if not prompt.text:
|
| 207 |
+
notice = f"ุชู
ุฅุฑูุงู ุงูู
ูู: {st.session_state.file_name}"
|
| 208 |
+
if pii_count:
|
| 209 |
+
notice += f"\n\nุชู
ุฅุฎูุงุก {pii_count} ุจูุงูุงุช ุญุณุงุณุฉ (ูููุฉ / IBAN) ุชููุงุฆูุงู"
|
| 210 |
+
st.session_state.messages.append({"role": "user", "content": notice})
|
| 211 |
+
with st.chat_message("user"):
|
| 212 |
+
st.markdown(notice)
|
| 213 |
+
|
| 214 |
+
if prompt and prompt.text:
|
| 215 |
+
send(prompt.text)
|
assets/logo.jpeg
ADDED
|
assets/logo.png
ADDED
|
core/__init__.py
ADDED
|
File without changes
|
core/ai_service.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Handles streaming LLM responses from OpenAI using retrieved labor law context.
|
| 2 |
+
import os
|
| 3 |
+
from openai import OpenAI
|
| 4 |
+
from dotenv import load_dotenv
|
| 5 |
+
|
| 6 |
+
load_dotenv()
|
| 7 |
+
|
| 8 |
+
SYSTEM_PROMPT = """ุฃูุช ู
ุณุชุดุงุฑ ูุงูููู ู
ุชุฎุตุต ูู ูุธุงู
ุงูุนู
ู ุงูุณุนูุฏู.
|
| 9 |
+
|
| 10 |
+
ู
ูู
ุชู:
|
| 11 |
+
1. ุฅุฐุง ุฑูุน ุงูู
ุณุชุฎุฏู
ุนูุฏ ุนู
ู ุฃู ูุซููุฉ ูุถูุฉุ ุงููู
ุชูุงุตููู ุงูุฎุงุตุฉ (ุงูุฑุงุชุจุ ุงูู
ุฏุฉุ ุงูุดุฑูุทุ ุฅูุฎ).
|
| 12 |
+
2. ุงุณุชุฎุฏู
ู
ูุงุฏ ูุธุงู
ุงูุนู
ู ุงูู
ูุฏู
ุฉ ูุชูููู
ูุถุนู ุงููุงูููู ุชุญุฏูุฏุงู.
|
| 13 |
+
3. ูุฏูู
ูู ูุตูุญุฉ ุดุฎุตูุฉ ุฏูููุฉ ุจูุงุกู ุนูู ุญุงูุชู ููุ ูุง ุฅุฌุงุจุฉ ุนุงู
ุฉ.
|
| 14 |
+
|
| 15 |
+
ููุงุนุฏ:
|
| 16 |
+
- ุงุณุชุดูุฏ ุฏุงุฆู
ุงู ุจุฑูู
ุงูู
ุงุฏุฉ ุงููุงููููุฉ ุนูุฏ ุงูุฅุฌุงุจุฉ.
|
| 17 |
+
- ูุถูุญ ุฅุฐุง ูุงู ุงูุนูุฏ ูุชูุงูู ุฃู ูุชุนุงุฑุถ ู
ุน ูุธุงู
ุงูุนู
ู.
|
| 18 |
+
- ุฅุฐุง ูุงู ููู
ุณุชุฎุฏู
ุญููู ู
ููุฏูุฑุฉุ ุงุฐูุฑูุง ุตุฑุงุญุฉู.
|
| 19 |
+
- ุฃุฌุจ ุจุงููุบุฉ ุงูุชู ููุชุจ ุจูุง ุงูู
ุณุชุฎุฏู
(ุนุฑุจู ุฃู ุฅูุฌููุฒู).
|
| 20 |
+
- ุฅุฐุง ูู
ุชููู ุงูู
ุนููู
ุงุช ุงูู
ุชุงุญุฉ ููุฅุฌุงุจุฉุ ูู ุฐูู ุจูุถูุญ."""
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def stream_response(prompt: str, context: str = ""):
|
| 24 |
+
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
| 25 |
+
|
| 26 |
+
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
|
| 27 |
+
|
| 28 |
+
if context:
|
| 29 |
+
messages.append({
|
| 30 |
+
"role": "system",
|
| 31 |
+
"content": f"ููู
ุง ููู ูุตูุต ุงูู
ูุงุฏ ุฐุงุช ุงูุตูุฉ ู
ู ูุธุงู
ุงูุนู
ู ุงูุณุนูุฏู:\n\n{context}",
|
| 32 |
+
})
|
| 33 |
+
|
| 34 |
+
messages.append({"role": "user", "content": prompt})
|
| 35 |
+
|
| 36 |
+
stream = client.chat.completions.create(
|
| 37 |
+
model="gpt-4o-mini",
|
| 38 |
+
messages=messages,
|
| 39 |
+
stream=True,
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
for chunk in stream:
|
| 43 |
+
delta = chunk.choices[0].delta
|
| 44 |
+
if delta.content is not None:
|
| 45 |
+
yield delta.content
|
core/file_service.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import fitz
|
| 2 |
+
import io
|
| 3 |
+
|
| 4 |
+
_CHUNK_SIZE = 1000
|
| 5 |
+
_CHUNK_OVERLAP = 100
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def _chunk(text: str, size: int = _CHUNK_SIZE, overlap: int = _CHUNK_OVERLAP) -> str:
|
| 9 |
+
"""Split long text into overlapping chunks separated by '---'."""
|
| 10 |
+
if not text or len(text) <= size:
|
| 11 |
+
return text
|
| 12 |
+
chunks: list[str] = []
|
| 13 |
+
start = 0
|
| 14 |
+
while start < len(text):
|
| 15 |
+
end = min(start + size, len(text))
|
| 16 |
+
chunks.append(text[start:end])
|
| 17 |
+
if end == len(text):
|
| 18 |
+
break
|
| 19 |
+
start = end - overlap
|
| 20 |
+
return "\n\n---\n\n".join(chunks)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def extract_text(file) -> str:
|
| 24 |
+
name = file.name.lower()
|
| 25 |
+
|
| 26 |
+
if name.endswith(".txt"):
|
| 27 |
+
raw = file.read().decode("utf-8")
|
| 28 |
+
return _chunk(raw)
|
| 29 |
+
|
| 30 |
+
if name.endswith(".pdf"):
|
| 31 |
+
data = file.read()
|
| 32 |
+
doc = fitz.open(stream=io.BytesIO(data), filetype="pdf")
|
| 33 |
+
pages = [page.get_text("text") for page in doc]
|
| 34 |
+
doc.close()
|
| 35 |
+
return "\n\n".join(p for p in pages if p.strip())
|
| 36 |
+
|
| 37 |
+
raise ValueError(f"Unsupported file type: {file.name}")
|
core/pii_guard.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
|
| 3 |
+
# Saudi National ID (10 digits, starts with 1) or Iqama (starts with 2)
|
| 4 |
+
_SAUDI_ID = re.compile(r'\b[12]\d{9}\b')
|
| 5 |
+
|
| 6 |
+
# Saudi IBAN: SA + 22 digits
|
| 7 |
+
_IBAN = re.compile(r'\bSA\d{22}\b', re.IGNORECASE)
|
| 8 |
+
|
| 9 |
+
_PATTERNS = [
|
| 10 |
+
(_SAUDI_ID, "[ุฑูู
ูููุฉ]"),
|
| 11 |
+
(_IBAN, "[ุฑูู
IBAN]"),
|
| 12 |
+
]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def redact_pii(text: str) -> tuple[str, int]:
|
| 16 |
+
"""Redact Saudi IDs and IBANs. Returns (redacted_text, count_redacted)."""
|
| 17 |
+
count = 0
|
| 18 |
+
for pattern, replacement in _PATTERNS:
|
| 19 |
+
matches = pattern.findall(text)
|
| 20 |
+
count += len(matches)
|
| 21 |
+
text = pattern.sub(replacement, text)
|
| 22 |
+
return text, count
|
core/vector_store.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pickle
|
| 3 |
+
import numpy as np
|
| 4 |
+
import faiss
|
| 5 |
+
from sentence_transformers import SentenceTransformer
|
| 6 |
+
|
| 7 |
+
_model: SentenceTransformer | None = None
|
| 8 |
+
_index: faiss.IndexFlatIP | None = None
|
| 9 |
+
_chunks: list[str] = []
|
| 10 |
+
|
| 11 |
+
DIMENSION = 1024
|
| 12 |
+
INDEX_PATH = "index/labor_law.index"
|
| 13 |
+
CHUNKS_PATH = "index/labor_law_chunks.pkl"
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _get_model() -> SentenceTransformer:
|
| 17 |
+
global _model
|
| 18 |
+
if _model is None:
|
| 19 |
+
_model = SentenceTransformer("intfloat/multilingual-e5-large")
|
| 20 |
+
return _model
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _embed(texts: list[str], is_query: bool = False) -> np.ndarray:
|
| 24 |
+
model = _get_model()
|
| 25 |
+
prefix = "query: " if is_query else "passage: "
|
| 26 |
+
prefixed = [prefix + t for t in texts]
|
| 27 |
+
vectors = model.encode(prefixed, normalize_embeddings=True, convert_to_numpy=True)
|
| 28 |
+
return vectors.astype("float32")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def embed_and_store(chunks: list[str]) -> None:
|
| 32 |
+
global _index, _chunks
|
| 33 |
+
vectors = _embed(chunks, is_query=False)
|
| 34 |
+
_index = faiss.IndexFlatIP(DIMENSION)
|
| 35 |
+
_index.add(vectors)
|
| 36 |
+
_chunks = chunks
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def save_to_disk() -> None:
|
| 40 |
+
assert _index is not None, "No index to save"
|
| 41 |
+
faiss.write_index(_index, INDEX_PATH)
|
| 42 |
+
with open(CHUNKS_PATH, "wb") as f:
|
| 43 |
+
pickle.dump(_chunks, f)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def load_from_disk() -> bool:
|
| 47 |
+
global _index, _chunks
|
| 48 |
+
if not os.path.exists(INDEX_PATH) or not os.path.exists(CHUNKS_PATH):
|
| 49 |
+
return False
|
| 50 |
+
_index = faiss.read_index(INDEX_PATH)
|
| 51 |
+
with open(CHUNKS_PATH, "rb") as f:
|
| 52 |
+
_chunks = pickle.load(f)
|
| 53 |
+
return True
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def is_loaded() -> bool:
|
| 57 |
+
return _index is not None and _index.ntotal > 0
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def retrieve_with_scores(query: str, k: int = 5) -> list[tuple[str, float]]:
|
| 61 |
+
if _index is None or _index.ntotal == 0:
|
| 62 |
+
return []
|
| 63 |
+
vector = _embed([query], is_query=True)
|
| 64 |
+
k = min(k, _index.ntotal)
|
| 65 |
+
scores, indices = _index.search(vector, k)
|
| 66 |
+
return [
|
| 67 |
+
(_chunks[idx], float(scores[0][rank]))
|
| 68 |
+
for rank, idx in enumerate(indices[0])
|
| 69 |
+
if idx < len(_chunks)
|
| 70 |
+
]
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def retrieve(query: str, k: int = 5) -> list[str]:
|
| 74 |
+
return [chunk for chunk, _ in retrieve_with_scores(query, k)]
|
data/labor_law_active.xlsx
ADDED
|
Binary file (67.2 kB). View file
|
|
|
data/labor_law_amended.xlsx
ADDED
|
Binary file (12.7 kB). View file
|
|
|
data/labor_law_repealed.xlsx
ADDED
|
Binary file (12.1 kB). View file
|
|
|
docker-compose.yml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
app:
|
| 3 |
+
build: .
|
| 4 |
+
ports:
|
| 5 |
+
- "8501:8501"
|
| 6 |
+
env_file:
|
| 7 |
+
- .env
|
entrypoint.sh
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/sh
|
| 2 |
+
mkdir -p index
|
| 3 |
+
if [ ! -f index/labor_law.index ]; then
|
| 4 |
+
echo "Building FAISS index..."
|
| 5 |
+
python -m scripts.ingest_labor_law
|
| 6 |
+
fi
|
| 7 |
+
echo "Pre-warming embedding model..."
|
| 8 |
+
python -c "from core.vector_store import load_from_disk, _get_model; load_from_disk(); _get_model()"
|
| 9 |
+
exec streamlit run app.py --server.address=0.0.0.0
|
requirements.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
streamlit
|
| 2 |
+
python-dotenv
|
| 3 |
+
openai
|
| 4 |
+
pymupdf
|
| 5 |
+
faiss-cpu
|
| 6 |
+
numpy
|
| 7 |
+
pandas
|
| 8 |
+
openpyxl
|
| 9 |
+
sentence-transformers
|
scripts/ingest_labor_law.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Run once to embed the labor law Excel files into a FAISS index saved to disk.
|
| 3 |
+
Usage: python3 ingest_labor_law.py
|
| 4 |
+
"""
|
| 5 |
+
import pandas as pd
|
| 6 |
+
from core.vector_store import embed_and_store, save_to_disk
|
| 7 |
+
|
| 8 |
+
DATA_DIR = "data"
|
| 9 |
+
# label โ (path, status_tag)
|
| 10 |
+
# Repealed articles are included so the AI can tell users the article is no longer in force
|
| 11 |
+
EXCEL_FILES = {
|
| 12 |
+
"active": (f"{DATA_DIR}/labor_law_active.xlsx", None),
|
| 13 |
+
"amended": (f"{DATA_DIR}/labor_law_amended.xlsx", "โ ๏ธ ูุฐู ุงูู
ุงุฏุฉ ู
ุนุฏููุฉ"),
|
| 14 |
+
"repealed": (f"{DATA_DIR}/labor_law_repealed.xlsx", "๐ซ ูุฐู ุงูู
ุงุฏุฉ ู
ูุบุงุฉ ููุง ุชูุทุจููู ุญุงููุงู"),
|
| 15 |
+
}
|
| 16 |
+
CHUNK_MAX = 600 # chars โ articles longer than this get split into sub-chunks
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def split_article(header: str, text: str, kw_suffix: str) -> list[str]:
|
| 20 |
+
"""
|
| 21 |
+
Split a long article into sub-chunks.
|
| 22 |
+
Prefers splitting on definition markers (-term: ...) then on paragraph breaks.
|
| 23 |
+
Each sub-chunk keeps the article header so retrieval context is clear.
|
| 24 |
+
"""
|
| 25 |
+
# Article 2-style: definitions separated by newline + dash
|
| 26 |
+
if "\n\n-" in text:
|
| 27 |
+
raw_parts = text.split("\n\n-")
|
| 28 |
+
parts = [raw_parts[0].strip()]
|
| 29 |
+
parts += [f"-{p.strip()}" for p in raw_parts[1:]]
|
| 30 |
+
else:
|
| 31 |
+
parts = [p.strip() for p in text.split("\n\n") if p.strip()]
|
| 32 |
+
|
| 33 |
+
# Merge consecutive short parts so we don't create too-tiny chunks
|
| 34 |
+
merged: list[str] = []
|
| 35 |
+
current = ""
|
| 36 |
+
for part in parts:
|
| 37 |
+
candidate = (current + "\n\n" + part).strip() if current else part
|
| 38 |
+
if len(candidate) <= CHUNK_MAX:
|
| 39 |
+
current = candidate
|
| 40 |
+
else:
|
| 41 |
+
if current:
|
| 42 |
+
merged.append(current)
|
| 43 |
+
current = part
|
| 44 |
+
if current:
|
| 45 |
+
merged.append(current)
|
| 46 |
+
|
| 47 |
+
if not merged:
|
| 48 |
+
return [text]
|
| 49 |
+
|
| 50 |
+
return [
|
| 51 |
+
f"{header} (ุฌุฒุก {i})\n{sub}{kw_suffix}"
|
| 52 |
+
for i, sub in enumerate(merged, 1)
|
| 53 |
+
]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def build_chunks(df: pd.DataFrame, status_tag: str | None = None) -> list[str]:
|
| 57 |
+
chunks = []
|
| 58 |
+
for _, row in df.iterrows():
|
| 59 |
+
article_num = str(row.get("ุฑูู
ุงูู
ุงุฏุฉ (ูุตู)", "")).strip()
|
| 60 |
+
chapter = str(row.get("ุงููุตู / ุงูู
ูุถูุน", "")).strip()
|
| 61 |
+
text = str(row.get("ูุต ุงูู
ุงุฏุฉ", "")).strip()
|
| 62 |
+
keywords = str(row.get("ุงูู
ูุถูุนุงุช (ููู
ุงุช ู
ูุชุงุญูุฉ)", "")).strip()
|
| 63 |
+
|
| 64 |
+
if not text or text == "nan":
|
| 65 |
+
continue
|
| 66 |
+
|
| 67 |
+
status_prefix = f"{status_tag}\n" if status_tag else ""
|
| 68 |
+
header = f"{status_prefix}{article_num} โ {chapter}"
|
| 69 |
+
kw_suffix = f"\nุงูููู
ุงุช ุงูู
ูุชุงุญูุฉ: {keywords}" if keywords and keywords != "nan" else ""
|
| 70 |
+
|
| 71 |
+
if len(text) > CHUNK_MAX:
|
| 72 |
+
chunks.extend(split_article(header, text, kw_suffix))
|
| 73 |
+
else:
|
| 74 |
+
chunks.append(f"{header}\n{text}{kw_suffix}")
|
| 75 |
+
|
| 76 |
+
return chunks
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def main():
|
| 80 |
+
print("Reading Excel filesโฆ")
|
| 81 |
+
all_chunks: list[str] = []
|
| 82 |
+
for label, (path, status_tag) in EXCEL_FILES.items():
|
| 83 |
+
df_part = pd.read_excel(path)
|
| 84 |
+
print(f" {path}: {len(df_part)} rows ({label})")
|
| 85 |
+
chunks = build_chunks(df_part, status_tag)
|
| 86 |
+
print(f" >> {len(chunks)} chunks")
|
| 87 |
+
all_chunks.extend(chunks)
|
| 88 |
+
|
| 89 |
+
print(f" {len(all_chunks)} total chunks after smart splitting")
|
| 90 |
+
|
| 91 |
+
print("Embedding with multilingual-e5-large (local, free)โฆ")
|
| 92 |
+
embed_and_store(all_chunks)
|
| 93 |
+
|
| 94 |
+
print("Saving index to diskโฆ")
|
| 95 |
+
save_to_disk()
|
| 96 |
+
|
| 97 |
+
print("Done. labor_law.index and labor_law_chunks.pkl are ready.")
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
if __name__ == "__main__":
|
| 101 |
+
main()
|
tests/test_pipeline.py
ADDED
|
@@ -0,0 +1,363 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Pipeline tests โ covers every public function in the project.
|
| 3 |
+
|
| 4 |
+
Modules tested:
|
| 5 |
+
- core.file_service._chunk
|
| 6 |
+
- core.file_service.extract_text (.txt, .pdf, unsupported)
|
| 7 |
+
- core.ai_service.stream_response
|
| 8 |
+
- core.vector_store.embed_and_store / retrieve
|
| 9 |
+
- core.pii_guard.redact_pii
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import io
|
| 13 |
+
import sys
|
| 14 |
+
import os
|
| 15 |
+
import unittest
|
| 16 |
+
from unittest.mock import patch, MagicMock
|
| 17 |
+
|
| 18 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 22 |
+
# 1. core.file_service._chunk
|
| 23 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 24 |
+
class TestChunk(unittest.TestCase):
|
| 25 |
+
|
| 26 |
+
def setUp(self):
|
| 27 |
+
from core.file_service import _chunk
|
| 28 |
+
self.chunk = _chunk
|
| 29 |
+
|
| 30 |
+
def test_short_text_single_chunk(self):
|
| 31 |
+
text = "Hello world"
|
| 32 |
+
result = self.chunk(text, size=500, overlap=50)
|
| 33 |
+
self.assertEqual(result, "Hello world")
|
| 34 |
+
|
| 35 |
+
def test_multiple_chunks_separator(self):
|
| 36 |
+
text = "A" * 600
|
| 37 |
+
result = self.chunk(text, size=500, overlap=50)
|
| 38 |
+
self.assertIn("---", result, "Chunks must be separated by ---")
|
| 39 |
+
parts = result.split("\n\n---\n\n")
|
| 40 |
+
self.assertEqual(len(parts), 2)
|
| 41 |
+
|
| 42 |
+
def test_overlap_produces_shared_content(self):
|
| 43 |
+
text = "X" * 100
|
| 44 |
+
result = self.chunk(text, size=60, overlap=20)
|
| 45 |
+
parts = result.split("\n\n---\n\n")
|
| 46 |
+
self.assertGreater(len(parts), 1)
|
| 47 |
+
|
| 48 |
+
def test_empty_string(self):
|
| 49 |
+
result = self.chunk("", size=500, overlap=50)
|
| 50 |
+
self.assertEqual(result, "")
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 54 |
+
# 2. core.file_service.extract_text โ .txt path
|
| 55 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 56 |
+
class TestExtractTxt(unittest.TestCase):
|
| 57 |
+
|
| 58 |
+
def setUp(self):
|
| 59 |
+
from core.file_service import extract_text
|
| 60 |
+
self.extract_text = extract_text
|
| 61 |
+
|
| 62 |
+
def _make_file(self, name: str, content: bytes):
|
| 63 |
+
f = io.BytesIO(content)
|
| 64 |
+
f.name = name
|
| 65 |
+
return f
|
| 66 |
+
|
| 67 |
+
def test_txt_extraction(self):
|
| 68 |
+
content = b"Hello from a text file."
|
| 69 |
+
f = self._make_file("sample.txt", content)
|
| 70 |
+
result = self.extract_text(f)
|
| 71 |
+
self.assertIn("Hello from a text file.", result)
|
| 72 |
+
|
| 73 |
+
def test_txt_long_content_is_chunked(self):
|
| 74 |
+
content = ("word " * 300).encode("utf-8") # ~1500 chars โ multiple chunks
|
| 75 |
+
f = self._make_file("long.txt", content)
|
| 76 |
+
result = self.extract_text(f)
|
| 77 |
+
self.assertIn("---", result)
|
| 78 |
+
|
| 79 |
+
def test_unsupported_type_raises(self):
|
| 80 |
+
f = self._make_file("doc.docx", b"binary data")
|
| 81 |
+
with self.assertRaises(ValueError):
|
| 82 |
+
self.extract_text(f)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 86 |
+
# 3. core.file_service.extract_text โ .pdf path (mocked via fitz)
|
| 87 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 88 |
+
class TestExtractPdf(unittest.TestCase):
|
| 89 |
+
|
| 90 |
+
def setUp(self):
|
| 91 |
+
from core.file_service import extract_text
|
| 92 |
+
self.extract_text = extract_text
|
| 93 |
+
|
| 94 |
+
def test_pdf_extraction(self):
|
| 95 |
+
fake_page = MagicMock()
|
| 96 |
+
fake_page.get_text.return_value = "PDF page text here."
|
| 97 |
+
|
| 98 |
+
fake_doc = MagicMock()
|
| 99 |
+
fake_doc.__iter__ = MagicMock(return_value=iter([fake_page]))
|
| 100 |
+
|
| 101 |
+
f = io.BytesIO(b"%PDF-1.4 fake")
|
| 102 |
+
f.name = "document.pdf"
|
| 103 |
+
|
| 104 |
+
with patch("core.file_service.fitz.open", return_value=fake_doc):
|
| 105 |
+
result = self.extract_text(f)
|
| 106 |
+
|
| 107 |
+
self.assertIn("PDF page text here.", result)
|
| 108 |
+
|
| 109 |
+
def test_pdf_empty_pages(self):
|
| 110 |
+
fake_page = MagicMock()
|
| 111 |
+
fake_page.get_text.return_value = "" # fitz returns "" for blank pages
|
| 112 |
+
|
| 113 |
+
fake_doc = MagicMock()
|
| 114 |
+
fake_doc.__iter__ = MagicMock(return_value=iter([fake_page]))
|
| 115 |
+
|
| 116 |
+
f = io.BytesIO(b"%PDF-1.4 fake")
|
| 117 |
+
f.name = "empty.pdf"
|
| 118 |
+
|
| 119 |
+
with patch("core.file_service.fitz.open", return_value=fake_doc):
|
| 120 |
+
result = self.extract_text(f)
|
| 121 |
+
|
| 122 |
+
self.assertEqual(result, "")
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 126 |
+
# 4. core.ai_service.stream_response
|
| 127 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 128 |
+
class TestStreamResponse(unittest.TestCase):
|
| 129 |
+
|
| 130 |
+
def _make_chunk(self, text):
|
| 131 |
+
chunk = MagicMock()
|
| 132 |
+
chunk.choices[0].delta.content = text
|
| 133 |
+
return chunk
|
| 134 |
+
|
| 135 |
+
def test_yields_content_tokens(self):
|
| 136 |
+
from core.ai_service import stream_response
|
| 137 |
+
|
| 138 |
+
fake_chunks = [self._make_chunk("Hello"), self._make_chunk(" world")]
|
| 139 |
+
|
| 140 |
+
mock_stream = MagicMock()
|
| 141 |
+
mock_stream.__iter__ = MagicMock(return_value=iter(fake_chunks))
|
| 142 |
+
|
| 143 |
+
mock_client = MagicMock()
|
| 144 |
+
mock_client.chat.completions.create.return_value = mock_stream
|
| 145 |
+
|
| 146 |
+
with patch("core.ai_service.OpenAI", return_value=mock_client):
|
| 147 |
+
tokens = list(stream_response("hi"))
|
| 148 |
+
|
| 149 |
+
self.assertEqual(tokens, ["Hello", " world"])
|
| 150 |
+
|
| 151 |
+
def test_none_content_skipped(self):
|
| 152 |
+
"""Chunks where delta.content is None must not be yielded."""
|
| 153 |
+
from core.ai_service import stream_response
|
| 154 |
+
|
| 155 |
+
chunk_none = MagicMock()
|
| 156 |
+
chunk_none.choices[0].delta.content = None
|
| 157 |
+
chunk_real = self._make_chunk("data")
|
| 158 |
+
|
| 159 |
+
mock_stream = MagicMock()
|
| 160 |
+
mock_stream.__iter__ = MagicMock(return_value=iter([chunk_none, chunk_real]))
|
| 161 |
+
|
| 162 |
+
mock_client = MagicMock()
|
| 163 |
+
mock_client.chat.completions.create.return_value = mock_stream
|
| 164 |
+
|
| 165 |
+
with patch("core.ai_service.OpenAI", return_value=mock_client):
|
| 166 |
+
tokens = list(stream_response("hi"))
|
| 167 |
+
|
| 168 |
+
self.assertEqual(tokens, ["data"])
|
| 169 |
+
|
| 170 |
+
def test_context_becomes_second_system_message(self):
|
| 171 |
+
"""Context must appear as a second system message, after SYSTEM_PROMPT."""
|
| 172 |
+
from core.ai_service import stream_response
|
| 173 |
+
|
| 174 |
+
mock_stream = MagicMock()
|
| 175 |
+
mock_stream.__iter__ = MagicMock(return_value=iter([self._make_chunk("ok")]))
|
| 176 |
+
|
| 177 |
+
mock_client = MagicMock()
|
| 178 |
+
mock_client.chat.completions.create.return_value = mock_stream
|
| 179 |
+
|
| 180 |
+
with patch("core.ai_service.OpenAI", return_value=mock_client):
|
| 181 |
+
list(stream_response("hello", context="some law context"))
|
| 182 |
+
|
| 183 |
+
call_kwargs = mock_client.chat.completions.create.call_args[1]
|
| 184 |
+
messages = call_kwargs["messages"]
|
| 185 |
+
self.assertEqual(messages[0]["role"], "system")
|
| 186 |
+
self.assertIn("some law context", messages[1]["content"])
|
| 187 |
+
self.assertEqual(messages[2]["role"], "user")
|
| 188 |
+
self.assertEqual(messages[2]["content"], "hello")
|
| 189 |
+
|
| 190 |
+
def test_no_context_sends_system_and_user(self):
|
| 191 |
+
"""Without context, exactly system prompt + user message are sent."""
|
| 192 |
+
from core.ai_service import stream_response
|
| 193 |
+
|
| 194 |
+
mock_stream = MagicMock()
|
| 195 |
+
mock_stream.__iter__ = MagicMock(return_value=iter([self._make_chunk("ok")]))
|
| 196 |
+
|
| 197 |
+
mock_client = MagicMock()
|
| 198 |
+
mock_client.chat.completions.create.return_value = mock_stream
|
| 199 |
+
|
| 200 |
+
with patch("core.ai_service.OpenAI", return_value=mock_client):
|
| 201 |
+
list(stream_response("hello"))
|
| 202 |
+
|
| 203 |
+
call_kwargs = mock_client.chat.completions.create.call_args[1]
|
| 204 |
+
messages = call_kwargs["messages"]
|
| 205 |
+
self.assertEqual(len(messages), 2)
|
| 206 |
+
self.assertEqual(messages[0]["role"], "system")
|
| 207 |
+
self.assertEqual(messages[1]["role"], "user")
|
| 208 |
+
self.assertEqual(messages[1]["content"], "hello")
|
| 209 |
+
|
| 210 |
+
def test_stream_flag_is_true(self):
|
| 211 |
+
"""The OpenAI call must always use stream=True."""
|
| 212 |
+
from core.ai_service import stream_response
|
| 213 |
+
|
| 214 |
+
mock_stream = MagicMock()
|
| 215 |
+
mock_stream.__iter__ = MagicMock(return_value=iter([]))
|
| 216 |
+
|
| 217 |
+
mock_client = MagicMock()
|
| 218 |
+
mock_client.chat.completions.create.return_value = mock_stream
|
| 219 |
+
|
| 220 |
+
with patch("core.ai_service.OpenAI", return_value=mock_client):
|
| 221 |
+
list(stream_response("test"))
|
| 222 |
+
|
| 223 |
+
call_kwargs = mock_client.chat.completions.create.call_args[1]
|
| 224 |
+
self.assertTrue(call_kwargs.get("stream"), "stream must be True")
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 228 |
+
# 5. core.vector_store.embed_and_store + retrieve
|
| 229 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 230 |
+
class TestVectorStore(unittest.TestCase):
|
| 231 |
+
|
| 232 |
+
def _fake_embed(self, texts, is_query=False):
|
| 233 |
+
"""Returns deterministic unit vectors without loading the real model."""
|
| 234 |
+
import numpy as np
|
| 235 |
+
rng = np.random.default_rng(seed=42)
|
| 236 |
+
vecs = rng.random((len(texts), 1024)).astype("float32")
|
| 237 |
+
norms = np.linalg.norm(vecs, axis=1, keepdims=True)
|
| 238 |
+
return vecs / norms
|
| 239 |
+
|
| 240 |
+
def test_embed_and_store_then_retrieve_returns_strings(self):
|
| 241 |
+
import core.vector_store as vs
|
| 242 |
+
|
| 243 |
+
chunks = ["cats are mammals", "dogs bark loudly", "fish live in water"]
|
| 244 |
+
|
| 245 |
+
with patch("core.vector_store._embed", side_effect=self._fake_embed):
|
| 246 |
+
vs.embed_and_store(chunks)
|
| 247 |
+
results = vs.retrieve("mammals", k=2)
|
| 248 |
+
|
| 249 |
+
self.assertIsInstance(results, list)
|
| 250 |
+
self.assertEqual(len(results), 2)
|
| 251 |
+
self.assertTrue(all(isinstance(r, str) for r in results))
|
| 252 |
+
self.assertTrue(all(r in chunks for r in results))
|
| 253 |
+
|
| 254 |
+
def test_retrieve_k_capped_to_index_size(self):
|
| 255 |
+
import core.vector_store as vs
|
| 256 |
+
|
| 257 |
+
chunks = ["only one chunk"]
|
| 258 |
+
|
| 259 |
+
with patch("core.vector_store._embed", side_effect=self._fake_embed):
|
| 260 |
+
vs.embed_and_store(chunks)
|
| 261 |
+
results = vs.retrieve("query", k=10)
|
| 262 |
+
|
| 263 |
+
self.assertEqual(len(results), 1)
|
| 264 |
+
|
| 265 |
+
def test_retrieve_before_store_returns_empty(self):
|
| 266 |
+
import core.vector_store as vs
|
| 267 |
+
vs._index = None
|
| 268 |
+
vs._chunks = []
|
| 269 |
+
|
| 270 |
+
results = vs.retrieve("anything")
|
| 271 |
+
self.assertEqual(results, [])
|
| 272 |
+
|
| 273 |
+
def test_embed_and_store_resets_previous_index(self):
|
| 274 |
+
import core.vector_store as vs
|
| 275 |
+
|
| 276 |
+
with patch("core.vector_store._embed", side_effect=self._fake_embed):
|
| 277 |
+
vs.embed_and_store(["first batch"])
|
| 278 |
+
vs.embed_and_store(["second batch A", "second batch B"])
|
| 279 |
+
results = vs.retrieve("query", k=5)
|
| 280 |
+
|
| 281 |
+
self.assertEqual(len(results), 2)
|
| 282 |
+
self.assertTrue(all("second" in r for r in results))
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 286 |
+
# 6. core.pii_guard.redact_pii
|
| 287 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 288 |
+
class TestPiiGuard(unittest.TestCase):
|
| 289 |
+
|
| 290 |
+
def setUp(self):
|
| 291 |
+
from core.pii_guard import redact_pii
|
| 292 |
+
self.redact_pii = redact_pii
|
| 293 |
+
|
| 294 |
+
def test_saudi_id_redacted(self):
|
| 295 |
+
text = "ุฑูู
ุงููููุฉ: 1234567890"
|
| 296 |
+
result, count = self.redact_pii(text)
|
| 297 |
+
self.assertNotIn("1234567890", result)
|
| 298 |
+
self.assertIn("[ุฑูู
ูููุฉ]", result)
|
| 299 |
+
self.assertEqual(count, 1)
|
| 300 |
+
|
| 301 |
+
def test_iqama_id_redacted(self):
|
| 302 |
+
text = "ุฑูู
ุงูุฅูุงู
ุฉ: 2987654321"
|
| 303 |
+
result, count = self.redact_pii(text)
|
| 304 |
+
self.assertNotIn("2987654321", result)
|
| 305 |
+
self.assertIn("[ุฑูู
ูููุฉ]", result)
|
| 306 |
+
self.assertEqual(count, 1)
|
| 307 |
+
|
| 308 |
+
def test_iban_redacted(self):
|
| 309 |
+
text = "ุฑูู
IBAN: SA1234567890123456789012"
|
| 310 |
+
result, count = self.redact_pii(text)
|
| 311 |
+
self.assertNotIn("SA1234567890123456789012", result)
|
| 312 |
+
self.assertIn("[ุฑูู
IBAN]", result)
|
| 313 |
+
self.assertEqual(count, 1)
|
| 314 |
+
|
| 315 |
+
def test_no_pii_returns_unchanged(self):
|
| 316 |
+
text = "ูุฐุง ูุต ุนุงุฏู ุจุฏูู ุจูุงูุงุช ุญุณุงุณุฉ"
|
| 317 |
+
result, count = self.redact_pii(text)
|
| 318 |
+
self.assertEqual(result, text)
|
| 319 |
+
self.assertEqual(count, 0)
|
| 320 |
+
|
| 321 |
+
def test_multiple_pii_all_redacted(self):
|
| 322 |
+
text = "ูููุฉ: 1234567890 ูIBAN: SA0987654321098765432109"
|
| 323 |
+
result, count = self.redact_pii(text)
|
| 324 |
+
self.assertEqual(count, 2)
|
| 325 |
+
self.assertNotIn("1234567890", result)
|
| 326 |
+
self.assertNotIn("SA0987654321098765432109", result)
|
| 327 |
+
|
| 328 |
+
def test_id_inside_longer_number_not_matched(self):
|
| 329 |
+
"""An 11-digit number must not be treated as a Saudi ID."""
|
| 330 |
+
text = "ุงูุฑูู
: 12345678901"
|
| 331 |
+
result, count = self.redact_pii(text)
|
| 332 |
+
self.assertEqual(count, 0)
|
| 333 |
+
self.assertEqual(result, text)
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 337 |
+
# 6. app.py โ show_sources widget keys must stay unique across messages
|
| 338 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 339 |
+
class TestShowSourcesUniqueKeys(unittest.TestCase):
|
| 340 |
+
"""Regression test for StreamlitDuplicateElementId when two chat
|
| 341 |
+
turns share the same uploaded file or the same retrieved article."""
|
| 342 |
+
|
| 343 |
+
def test_overlapping_sources_across_messages_do_not_crash(self):
|
| 344 |
+
from streamlit.testing.v1 import AppTest
|
| 345 |
+
|
| 346 |
+
app_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "app.py")
|
| 347 |
+
at = AppTest.from_file(app_path)
|
| 348 |
+
|
| 349 |
+
same_chunk = ("ูุต ุงูู
ุงุฏุฉ ุงูุฃููู ู
ู ูุธุงู
ุงูุนู
ู", 0.91)
|
| 350 |
+
same_file_text = "ูุต ู
ูู ุงูุนูุฏ ุงูู
ุฑููุน ููุงุฎุชุจุงุฑ"
|
| 351 |
+
at.session_state["messages"] = [
|
| 352 |
+
{"role": "user", "content": "ุณุคุงู 1"},
|
| 353 |
+
{"role": "assistant", "content": "ุฌูุงุจ 1", "scored_chunks": [same_chunk], "file_text": same_file_text},
|
| 354 |
+
{"role": "user", "content": "ุณุคุงู 2"},
|
| 355 |
+
{"role": "assistant", "content": "ุฌูุงุจ 2", "scored_chunks": [same_chunk], "file_text": same_file_text},
|
| 356 |
+
]
|
| 357 |
+
at.run(timeout=60)
|
| 358 |
+
|
| 359 |
+
self.assertEqual(at.exception, [], f"App crashed: {[e.value for e in at.exception]}")
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
if __name__ == "__main__":
|
| 363 |
+
unittest.main(verbosity=2)
|