erenyanic commited on
Commit
696f782
·
verified ·
1 Parent(s): c36f620

Add README.md

Browse files
Files changed (1) hide show
  1. README.md +394 -0
README.md ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ language:
4
+ - tr
5
+ task_categories:
6
+ - question-answering
7
+ - sentence-similarity
8
+ tags:
9
+ - medical
10
+ - rag
11
+ - semantic-search
12
+ - turkish
13
+ - chromadb
14
+ size_categories:
15
+ - 1K<n<10K
16
+ configs:
17
+ - config_name: chunks
18
+ default: true
19
+ data_files:
20
+ - split: train
21
+ path: data/ehekim_chunks.parquet
22
+ - config_name: benchmark
23
+ data_files:
24
+ - split: test
25
+ path: data/benchmark_questions.parquet
26
+ ---
27
+
28
+ # e-hekim — Turkish Medical Semantic Search + RAG
29
+
30
+ An end-to-end system for **semantic search** and **retrieval-augmented generation**
31
+ over a vector database built from health articles published by 14 Turkish hospitals.
32
+
33
+ Two modes are selectable from a single interface:
34
+
35
+ | Mode | API key | What it does |
36
+ |---|---|---|
37
+ | **Semantic search** | **not required** | Vectorizes the question and returns chunks ranked by cosine similarity. This mode alone is enough to evaluate the project without any credentials. |
38
+ | **RAG** | the user's own key | Passes the chunks that clear the threshold to an LLM and produces a Turkish answer with `[1]`, `[2]` citations. |
39
+
40
+ The corpus and the user interface are Turkish, because the source articles are
41
+ Turkish; this document is in English.
42
+
43
+ ---
44
+
45
+ ## Two independent refusal layers
46
+
47
+ Preventing hallucination needs more than a similarity cut-off, so the system refuses
48
+ in two distinct places and reports which one fired via `refusal_reason`.
49
+
50
+ **Layer 1 — retrieval gate (`below_threshold`).** If the best-matching chunk scores
51
+ below the cosine threshold, our own code emits the refusal and **the LLM is never
52
+ called at all**. No prompt can talk the system out of this, because no prompt is
53
+ ever sent.
54
+
55
+ > `Bu sorunun cevabı belgelerimde bulunmamaktadır.`
56
+ > *("The answer to this question is not found in my documents.")*
57
+
58
+ **Layer 2 — model gate (`model_insufficient_context`).** A similarity score cannot
59
+ tell whether a passage actually *answers* a question, only that it is on the same
60
+ topic. "What is Hodgkin lymphoma?" and "What is the five-year survival rate in
61
+ Hodgkin lymphoma?" retrieve the same chunk with a high score, yet only the first is
62
+ answerable from it. The model is therefore instructed — as the opening principle of
63
+ its system prompt — that it has **no knowledge of its own** for this task, and must
64
+ decline rather than fill the gap from its pretrained knowledge:
65
+
66
+ > `Bu bilgiyi bilmiyorum; bu konuda size yardımcı olamıyorum.`
67
+ > *("I do not know this information; I cannot help you with this.")*
68
+
69
+ Partial answers, hedges such as "the documents do not say, but generally…", and
70
+ adding even a single detail absent from the passages are all forbidden. Measured
71
+ behaviour on the live system:
72
+
73
+ | Question | Best similarity | Outcome |
74
+ |---|---:|---|
75
+ | "Bitcoin bugün kaç dolar?" | 0.4298 | Layer 1 — LLM never invoked |
76
+ | "Hodgkin lenfomada 5 yıllık sağkalım oranı yüzde kaç?" | 0.6153 | Layer 2 — passages passed, model declined |
77
+ | "Eritrositler nerede üretilir ve nerede yıkılır?" | 0.5931 | Answered, with citation |
78
+
79
+ ---
80
+
81
+ ## Technology stack
82
+
83
+ | Layer | Choice | Note |
84
+ |---|---|---|
85
+ | Vector database | **ChromaDB** 1.5 (`PersistentClient`) | Collection created with `hnsw:space=cosine`; distance = `1 − cosine`. |
86
+ | Embeddings | **`magibu/embeddingmagibu-200m`** | 768 dimensions, 8,192-token context, L2-normalized output. |
87
+ | Backend | **FastAPI** + Uvicorn | Binds to `127.0.0.1` only. |
88
+ | Frontend | Dependency-free HTML/CSS/JS | Strict CSP; no inline script or style. |
89
+ | LLM access | **OpenAI SDK** | Every provider speaks the OpenAI wire format; only `base_url` changes. |
90
+ | Data | [`umutertugrul/turkish-hospital-medical-articles`](https://huggingface.co/datasets/umutertugrul/turkish-hospital-medical-articles) | CC BY 4.0, ~25K articles, 14 hospitals. |
91
+
92
+ **Supported models** — DeepSeek (direct) and OpenRouter (multi-provider):
93
+
94
+ - `deepseek-v4-flash` (default, thinking enabled), `deepseek-v4-pro`
95
+ - Via OpenRouter: `anthropic/claude-haiku-4.5`, `openai/gpt-4.1-mini`,
96
+ `google/gemini-2.5-flash`, `meta-llama/llama-3.3-70b-instruct`
97
+
98
+ ---
99
+
100
+ ## Quick start
101
+
102
+ Requirements: Python ≥ 3.11 and [uv](https://docs.astral.sh/uv/). A GPU is optional —
103
+ everything runs on CPU, only the initial indexing is slower.
104
+
105
+ ```bash
106
+ git clone https://huggingface.co/datasets/erenyanic/e-hekim && cd e-hekim
107
+ uv venv && uv pip install -e ".[dev]"
108
+
109
+ cp .env.example .env # add HUGGINGFACE_TOKEN (the source dataset is gated)
110
+
111
+ uv run python scripts/ingest.py # ~5 min on GPU — 1,000 articles to 2,714 chunks
112
+ uv run python scripts/benchmark.py # threshold analysis (optional, writes a report)
113
+ uv run python -m ehekim.api # http://127.0.0.1:8000
114
+ ```
115
+
116
+ Open `http://127.0.0.1:8000`. **Semantic search** works immediately. For RAG, paste
117
+ your own API key into the field in the interface.
118
+
119
+ Tests: `uv run pytest -q` (104 tests).
120
+
121
+ > **Note:** `.env` is used **only by the offline scripts** (downloading the source
122
+ > data and uploading to the Hub). The web application never reads an LLM provider key
123
+ > from the environment under any circumstances.
124
+
125
+ ---
126
+
127
+ ## 1. Article selection and chunking
128
+
129
+ **Selection.** 24,612 raw articles, then cleaning (empty bodies, texts shorter than
130
+ 400 characters, non-`http` URLs, cookie/KVKK boilerplate, **duplicate URLs and
131
+ byte-identical bodies**), leaves 20,549 eligible articles, from which **1,000 are
132
+ selected**.
133
+
134
+ Rather than mirroring the raw distribution, selection is **balanced across the 14
135
+ hospitals** (71–72 articles per source). In the raw data Acıbadem (6,071) and
136
+ Memorial (5,264) alone make up half the eligible pool; proportional sampling would
137
+ have handed half the index to two institutions' house style and topic choices. An
138
+ equal quota buys wider medical coverage for the same 1,000 documents, which is what
139
+ makes both the positive and the negative benchmark questions meaningful. Selection is
140
+ **deterministic** under `seed=42`.
141
+
142
+ **Chunking strategy: paragraph-aware, token-bounded, with overlap (hybrid).**
143
+
144
+ - **Target 512 tokens, 64-token overlap**, 32-token minimum.
145
+ - Paragraph integrity comes first: whole paragraphs are packed greedily until the
146
+ token budget is exhausted.
147
+ - A paragraph that overflows the budget is split into **sentences** (Turkish
148
+ abbreviations such as `Dr.`, `vb.`, `mg.` and initials such as `M. Ali` are not
149
+ treated as sentence ends).
150
+ - If a single sentence still overflows, it is split on a **token window** as a last
151
+ resort.
152
+
153
+ *Why this strategy?* The corpus is hospital patient-education prose: short titled
154
+ sections ("Belirtileri nelerdir?", "Nasıl tedavi edilir?"). Paragraph boundaries are
155
+ genuine semantic boundaries, and blind N-token splitting routinely severs a symptom
156
+ list from the condition it belongs to. But paragraph lengths are wildly uneven — a
157
+ one-line introduction next to a 900-token procedure description — so splitting on
158
+ `\n\n` alone yields chunks that are both too small to stand alone and too large to be
159
+ precise. The hybrid approach avoids both failure modes.
160
+
161
+ > **A corpus-specific detail:** only **35%** of the articles contain blank lines
162
+ > (`\n\n`); the rest separate paragraphs with a **single `\n`** (about 44 line breaks
163
+ > per article on average). The chunker therefore treats any run of newlines as a
164
+ > paragraph boundary. Had it looked for `\n\n` only, two thirds of the corpus would
165
+ > have been processed as one enormous paragraph.
166
+
167
+ **Result:** 1,000 articles produce **2,714 chunks** (2.71 per article).
168
+ Tokens: mean 420, median 477, p95 534, max 586.
169
+
170
+ ## 2. Vector database schema
171
+
172
+ `data/ehekim_chunks.parquet` — the required delivery schema plus auxiliary metadata:
173
+
174
+ | Column | Type | Description |
175
+ |---|---|---|
176
+ | `url` | string | Source link of the article the chunk belongs to |
177
+ | `chunk_text` | string | The chunked text |
178
+ | `chunk_vector` | list\<float32\>[768] | Embedding vector (L2-normalized) |
179
+ | `chunk_id` | string | `{parent_id}-{index}` |
180
+ | `parent_id` | string | Article identifier (first 16 hex of the URL's SHA-1), the parent-child link |
181
+ | `title` | string | Article title |
182
+ | `__source` | string | Source hospital (one of 14) |
183
+ | `chunk_index` | int | Position within the article |
184
+ | `token_count` | int | Token count of the chunk |
185
+
186
+ The same data is stored in ChromaDB in the `ehekim_chunks` collection in cosine space.
187
+
188
+ ## 3. Embedding model
189
+
190
+ **`magibu/embeddingmagibu-200m` — 768 dimensions, 8,192-token context, ~200M parameters.**
191
+
192
+ Why it was chosen:
193
+
194
+ - **Turkish-focused.** Adapted from a multilingual teacher through *tokenizer surgery*
195
+ and *offline distillation*; its TR-MTEB average of 69.5 and STSbTR Spearman of 0.798
196
+ put it close to `ytu-ce-cosmos/turkish-e5-large` at a substantially smaller size.
197
+ - **Long context.** 8,192 tokens is far more than 512-token chunks need, so moving to
198
+ larger chunks later would not force a change of model.
199
+ - **Size/quality balance.** 768 dimensions give 2,714 × 768 float32 ≈ 8 MB, and the
200
+ whole corpus vectorizes in about 4.5 minutes on a laptop GPU (GTX 1650).
201
+ - **L2-normalized output.** The dot product equals cosine similarity directly, so
202
+ Chroma's cosine distance is exactly `1 − similarity`.
203
+
204
+ > ⚠️ **The model is asymmetric.** Queries and documents must be encoded with different
205
+ > prefixes: `task: search result | query: ` and `title: <title> | text: `. The wrong
206
+ > prefix silently depresses similarities and invalidates the threshold calibration.
207
+ > All encoding therefore goes through a single class (`ehekim.embedding.Embedder`),
208
+ > and a test asserts that the string we build is **byte-identical** to the model's own
209
+ > registered prompts. The article title is written into the document prefix with its
210
+ > real value.
211
+
212
+ ## 4. Evaluation set (30 questions)
213
+
214
+ The repository ships two viewable tables, selectable in the dataset viewer:
215
+
216
+ | Config | Split | Rows | Contents |
217
+ |---|---|---:|---|
218
+ | `chunks` (default) | `train` | 2,714 | The vector database: `url`, `chunk_text`, `chunk_vector` + metadata |
219
+ | `benchmark` | `test` | 30 | The evaluation set with its measured outcomes |
220
+
221
+ ```python
222
+ from datasets import load_dataset
223
+
224
+ chunks = load_dataset("erenyanic/e-hekim", "chunks", split="train")
225
+ tests = load_dataset("erenyanic/e-hekim", "benchmark", split="test")
226
+ ```
227
+
228
+ The benchmark table holds **20 positive** questions, each written by reading an actual
229
+ indexed chunk and paired with the URL of the article that answers it, and **10
230
+ negative** questions whose answers are certainly absent from the corpus (software,
231
+ sport, finance, history, space, automotive, veterinary medicine). Columns:
232
+
233
+ | Column | Description |
234
+ |---|---|
235
+ | `id`, `label` | `P01`–`P20` / `N01`–`N10`; `positive` or `negative` |
236
+ | `question` | The question put to the system |
237
+ | `topic`, `expected_answer`, `expected_url` | Ground truth for positives |
238
+ | `rationale` | Why a negative is out of scope |
239
+ | `best_similarity` | Highest cosine similarity actually retrieved |
240
+ | `expected_source_rank` | Rank at which the expected article was retrieved |
241
+ | `top_match_title`, `top_match_url` | What the retriever returned first |
242
+ | `system_decision`, `expected_decision`, `correct` | Answer/refuse outcome at the 0.53 threshold |
243
+
244
+ **Result: 30/30 correct** — all 20 positives answered, all 10 negatives refused.
245
+
246
+ ## 5. Threshold analysis
247
+
248
+ `scripts/benchmark.py` runs that 30-question set through the real retrieval path and
249
+ sweeps the threshold from 0.20 to 0.90, regenerating both the report and the benchmark
250
+ table above. Full report: [`data/threshold_report.md`](data/threshold_report.md).
251
+
252
+ **Separation is decisive:**
253
+
254
+ | Group | Mean | Min | Max |
255
+ |---|---:|---:|---:|
256
+ | Positive (20) | 0.7376 | **0.5819** | 0.8784 |
257
+ | Negative (10) | 0.2749 | 0.1615 | **0.4777** |
258
+
259
+ There is a **0.1042** gap between the lowest positive and the highest negative, so
260
+ **every** threshold in `[0.50, 0.58]` separates the two sets perfectly (F1 = 1.000,
261
+ accuracy = 1.000, zero false answers on negatives).
262
+
263
+ **Chosen threshold: `0.53`** — the midpoint of that plateau. Picking either edge would
264
+ leave the system on a cliff: at 0.50 the highest negative (the Bitcoin question,
265
+ 0.4777) is only 0.02 away, and at 0.58 the lowest positive (pharyngeal cancer, 0.5819)
266
+ is a mere 0.002 away. The midpoint maximizes the margin against both failure modes.
267
+
268
+ | Threshold | Positives answered | False answers on negatives | F1 |
269
+ |---:|---:|---:|---:|
270
+ | 0.30 | 20/20 | 2/10 | 0.952 |
271
+ | 0.45 | 20/20 | 1/10 | 0.976 |
272
+ | **0.53** | **20/20** | **0/10** | **1.000** |
273
+ | 0.65 | 17/20 | 0/10 | 0.919 |
274
+ | 0.80 | 5/20 | 0/10 | 0.333 |
275
+
276
+ **Source recall:** the expected article appears in the top 5 for 20/20 questions, and
277
+ ranks first for 15/20.
278
+
279
+ **An honest caveat.** This measurement is at the *article (URL)* level. Retrieving the
280
+ right article does not guarantee retrieving the *chunk* that carries the answer, and
281
+ the distinction bites in practice, which is what motivated the next section.
282
+
283
+ ## 6. Parent-context expansion
284
+
285
+ Chunking necessarily cuts articles at arbitrary points, and the highest-scoring chunk
286
+ is not always the one holding the answer sentence. Observed case: for "Eritrositler
287
+ nerede üretilir ve nerede yıkılır?", chunk 1 of the RBC article scores 0.5931 (it
288
+ discusses low counts) while chunk 0 — which states verbatim that erythrocytes are
289
+ produced in red bone marrow and broken down in the spleen — scores 0.5176 and falls
290
+ **below** the threshold. Given only the passing chunk, the model correctly refused a
291
+ question the corpus genuinely answers.
292
+
293
+ So once the threshold gate has decided the query *is* in scope, each passing chunk
294
+ brings its immediate siblings (`chunk_index ± 1`, via `parent_id`) along as context.
295
+
296
+ - The gate is not weakened: expansion happens strictly **after** it and only around
297
+ chunks that already cleared it, so it can never turn an out-of-scope question into
298
+ an answered one.
299
+ - The cosine values shown in the interface remain the **real, unexpanded** scores.
300
+ - The numbering given to the model and the list rendered in the interface are
301
+ identical, and siblings added purely for context are marked `—` ("komşu bölüm"), so
302
+ a `[1]` citation always points at the `[1]` the user can see.
303
+
304
+ ## 7. Security
305
+
306
+ Because the user types an API key into the browser, credential handling is the central
307
+ design constraint of the project:
308
+
309
+ - **The server never stores a key.** It arrives in the `X-Provider-Key` **header**
310
+ (not the URL — Uvicorn's access log records paths, so a key in a query string would
311
+ leak into our own logs), is used for exactly one call, and then goes out of scope.
312
+ - **No persistence in the browser.** No `localStorage`, `sessionStorage`, cookie or
313
+ URL is used; the key lives only in the input value and for the duration of a single
314
+ `fetch`. Reloading the page discards it.
315
+ - **Structural validation.** Before a key is placed in an `Authorization` header it is
316
+ checked to be a single line of printable ASCII, which stops CRLF header injection at
317
+ the door.
318
+ - **Log and error sanitization.** Providers echo the submitted key back in 401 bodies
319
+ (DeepSeek does). Every log record passes through a scrubbing filter, and every error
320
+ relayed to the client passes through the same scrubber, which replaces
321
+ credential-shaped substrings with `[REDACTED]`.
322
+ - **Response models cannot carry a key.** No Pydantic model has such a field, and
323
+ tests assert the key never appears in a response body.
324
+ - **No CORS, bound to `127.0.0.1`, strict CSP** (`default-src 'self'`, no inline script
325
+ or style), `nosniff`, `frame-ancestors 'none'`, `Cache-Control: no-store` on API
326
+ responses, and a 64 KB request-body cap.
327
+ - **Prompt injection.** Retrieved text is fenced inside a `<belgeler>` element and
328
+ declared untrusted in the system prompt; the model is told to execute no instruction
329
+ found inside it.
330
+ - **Upload protection.** `scripts/push_to_hub.py` works from an explicit allow-list,
331
+ then applies a deny-list and a secret scan; on any finding it aborts **before sending
332
+ a single byte**, and after uploading it re-lists the remote repository to verify both
333
+ that nothing sensitive leaked and that every expected file arrived.
334
+
335
+ ## 8. LLM configuration
336
+
337
+ ```python
338
+ client.chat.completions.create(
339
+ model="deepseek-v4-flash",
340
+ messages=...,
341
+ reasoning_effort="medium", # as specified in the brief
342
+ extra_body={"thinking": {"type": "enabled"}}, # thinking enabled
343
+ )
344
+ ```
345
+
346
+ > DeepSeek's documentation defines `low | high | max` for `reasoning_effort` and, for
347
+ > compatibility, **maps `medium` onto `high`**. The requested value (`medium`) is sent
348
+ > verbatim; this provider-side mapping is recorded here rather than silently worked
349
+ > around.
350
+
351
+ OpenRouter models are called with plain completions (no thinking parameters).
352
+
353
+ ## 9. Project structure
354
+
355
+ ```
356
+ src/ehekim/
357
+ config.py Settings, prompts, threshold and refusal constants (holds no secrets)
358
+ chunking.py Paragraph-aware, token-bounded, overlapping chunker
359
+ corpus.py Article cleaning, balanced selection, chunk records
360
+ embedding.py SentenceTransformer wrapper with the asymmetric prompts
361
+ vectorstore.py ChromaDB (cosine) plus sibling-chunk access
362
+ retrieval.py Threshold gate, context expansion, RAG prompt, refusal detection
363
+ llm.py Provider catalogue, OpenAI SDK call, error normalization
364
+ security.py Key validation and credential scrubbing
365
+ api.py FastAPI application, security headers, endpoints
366
+ scripts/ ingest.py, benchmark.py, push_to_hub.py
367
+ frontend/ index.html, app.js, styles.css (no dependencies)
368
+ tests/ 104 tests — security, chunking, selection, retrieval, HTTP
369
+ data/ benchmark_questions.json, threshold_report.md,
370
+ benchmark_results.json, ingest_manifest.json, *.parquet
371
+ ```
372
+
373
+ ## 10. API
374
+
375
+ | Endpoint | Key | Description |
376
+ |---|---|---|
377
+ | `GET /api/health` | — | Readiness and chunk count |
378
+ | `GET /api/config` | — | Threshold/top-k defaults, provider catalogue, refusal messages |
379
+ | `POST /api/search` | **no** | Semantic search; chunks with their cosine values |
380
+ | `POST /api/ask` | `X-Provider-Key` | RAG; refuses below the threshold without calling the model |
381
+ | `GET /api/docs` | — | OpenAPI interface |
382
+
383
+ ```bash
384
+ curl -X POST http://127.0.0.1:8000/api/search \
385
+ -H 'Content-Type: application/json' \
386
+ -d '{"query":"Hodgkin lenfomayı ayıran hücre tipi nedir?","top_k":3,"threshold":0.53}'
387
+ ```
388
+
389
+ ## Licence and disclaimer
390
+
391
+ The code is MIT. The source data is CC BY 4.0
392
+ ([umutertugrul/turkish-hospital-medical-articles](https://huggingface.co/datasets/umutertugrul/turkish-hospital-medical-articles)).
393
+ This system is **for information only**; it is not medical diagnosis, treatment or
394
+ prescribing advice.