File size: 9,820 Bytes
5dec856
006e0a7
 
798760b
006e0a7
5dec856
798760b
 
 
 
 
 
 
 
006e0a7
 
 
5dec856
 
798760b
006e0a7
 
 
5dec856
006e0a7
798760b
 
5dec856
 
798760b
5dec856
 
798760b
 
 
006e0a7
798760b
006e0a7
 
798760b
5dec856
798760b
 
006e0a7
798760b
006e0a7
798760b
5dec856
798760b
006e0a7
798760b
006e0a7
798760b
5dec856
006e0a7
 
798760b
006e0a7
5dec856
 
 
 
 
 
798760b
5dec856
798760b
5dec856
 
798760b
5dec856
 
 
798760b
 
 
 
 
5dec856
 
798760b
5dec856
 
 
 
 
006e0a7
 
798760b
5dec856
798760b
 
006e0a7
798760b
006e0a7
798760b
006e0a7
 
5dec856
798760b
006e0a7
 
 
5dec856
 
 
798760b
5dec856
 
798760b
 
 
 
 
006e0a7
 
5dec856
798760b
 
 
 
 
5dec856
006e0a7
 
 
 
798760b
006e0a7
 
798760b
 
 
 
006e0a7
5dec856
798760b
5dec856
 
798760b
 
5dec856
798760b
006e0a7
798760b
006e0a7
798760b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
006e0a7
5dec856
798760b
 
 
5dec856
006e0a7
798760b
006e0a7
798760b
 
 
 
 
 
 
 
006e0a7
 
 
5dec856
 
798760b
5dec856
 
 
 
 
798760b
 
 
 
 
5dec856
 
 
 
 
798760b
5dec856
 
798760b
 
5dec856
798760b
5dec856
798760b
 
5dec856
798760b
 
5dec856
798760b
 
 
 
 
 
5dec856
798760b
5dec856
 
006e0a7
 
798760b
006e0a7
 
798760b
 
 
 
 
 
 
 
99ffdec
5dec856
 
 
798760b
5dec856
798760b
5dec856
 
 
798760b
5dec856
798760b
 
 
5dec856
 
798760b
5dec856
 
798760b
5dec856
 
 
798760b
5dec856
 
798760b
5dec856
798760b
5dec856
006e0a7
798760b
 
006e0a7
798760b
 
 
006e0a7
798760b
006e0a7
 
798760b
5dec856
798760b
5dec856
798760b
5dec856
006e0a7
 
798760b
 
 
 
006e0a7
798760b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
006e0a7
798760b
006e0a7
798760b
 
006e0a7
5dec856
798760b
5dec856
 
 
 
 
798760b
5dec856
 
006e0a7
 
5dec856
 
798760b
006e0a7
32b2efb
5dec856
798760b
5dec856
798760b
5dec856
798760b
5dec856
 
 
 
 
 
798760b
5dec856
 
 
798760b
5dec856
006e0a7
798760b
 
 
 
99ffdec
 
 
798760b
99ffdec
32b2efb
798760b
 
 
 
 
 
 
 
006e0a7
 
 
 
5dec856
798760b
006e0a7
 
 
798760b
 
 
 
006e0a7
798760b
006e0a7
798760b
006e0a7
 
798760b
 
 
 
006e0a7
5dec856
798760b
 
 
006e0a7
5dec856
798760b
 
5dec856
006e0a7
798760b
5dec856
006e0a7
99e8a15
3b63721
798760b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
#!/usr/bin/env python3
"""
Complete Medical RAG Pipeline

Query → Hybrid Retrieval → Cross-Encoder Rerank → Gemini Answer

Features
--------
• FAISS semantic retrieval
• BM25 keyword retrieval
• Hybrid score fusion
• Cross-encoder reranking
• Gemini medical QA generation
• Report specific filtering (dropdown support)
"""

import os
import re
import pickle
import time
import numpy as np
from pathlib import Path
from datetime import datetime
from typing import List, Dict, Optional

import faiss
from rank_bm25 import BM25Okapi

from sentence_transformers import SentenceTransformer, CrossEncoder
from google import genai


# ============================================
# CONFIG
# ============================================

DEFAULT_TOP_K = 5


# ============================================
# QUERY PROCESSOR
# ============================================

class MedicalQueryProcessor:

    def __init__(self, embedding_model: str):

        print(f"Loading embedding model: {embedding_model}")

        self.model = SentenceTransformer(embedding_model)

        self.dim = self.model.get_sentence_embedding_dimension()

        print(f"Embedding dimension: {self.dim}")

    def extract_keywords(self, query: str) -> List[str]:

        patterns = [
            r"\b(cancer|carcinoma|tumor|neoplasm)\b",
            r"\b(ER|PR|HER2)\b",
            r"\b(stage\s*[IVX]+)\b",
            r"\b(grade\s*[123])\b",
            r"\b(lymph\s*node)\b",
        ]

        found = []

        for p in patterns:
            found.extend(re.findall(p, query, flags=re.I))

        return list(set(found))

    def embed(self, text: str) -> np.ndarray:

        return self.model.encode(
            text,
            normalize_embeddings=True
        )

    def process(self, query: str) -> Dict:

        return {
            "query": query,
            "keywords": self.extract_keywords(query),
            "embedding": self.embed(query),
        }


# ============================================
# HYBRID RETRIEVER
# ============================================

class HybridRetriever:

    def __init__(self, faiss_db_path: str):

        db = Path(faiss_db_path)

        print(f"Loading FAISS index from: {db}")

        self.index = faiss.read_index(str(db / "faiss.index"))

        with open(db / "metadata.pkl", "rb") as f:
            data = pickle.load(f)

        self.chunks = data["chunks"]

        print(f"Loaded {len(self.chunks)} chunks")

        tokenized = [
            c["text"].lower().split()
            for c in self.chunks
        ]

        self.bm25 = BM25Okapi(tokenized)

    def get_available_reports(self) -> List[str]:

        return sorted({
            c["filename"]
            for c in self.chunks
        })

    def search(
        self,
        query_embedding: np.ndarray,
        query_text: str,
        top_k: int = 40
    ) -> List[Dict]:

        # -----------------------------------
        # FAISS SEMANTIC SEARCH
        # -----------------------------------

        distances, indices = self.index.search(
            query_embedding.reshape(1, -1).astype("float32"),
            top_k
        )

        faiss_scores = {}

        for idx, dist in zip(indices[0], distances[0]):

            if idx >= 0:
                faiss_scores[int(idx)] = float(dist)

        if not faiss_scores:
            return []

        # -----------------------------------
        # BM25 KEYWORD SEARCH
        # -----------------------------------

        tokens = query_text.lower().split()

        bm25_raw = self.bm25.get_scores(tokens)

        bm25_max = max(bm25_raw) if max(bm25_raw) > 0 else 1.0

        bm25_scores = {
            i: bm25_raw[i] / bm25_max
            for i in faiss_scores.keys()
        }

        # -----------------------------------
        # HYBRID SCORE FUSION
        # -----------------------------------

        fused_scores = {}

        for idx in faiss_scores.keys():

            faiss_score = faiss_scores.get(idx, 0)

            bm25_score = bm25_scores.get(idx, 0)

            fused_scores[idx] = (
                0.7 * faiss_score +
                0.3 * bm25_score
            )

        ranked = sorted(
            fused_scores.items(),
            key=lambda x: x[1],
            reverse=True
        )

        results = []

        for idx, score in ranked:

            results.append(
                {
                    "chunk": self.chunks[idx],
                    "score": score
                }
            )

        return results


# ============================================
# CROSS ENCODER RERANKER
# ============================================

class MedicalReranker:

    def __init__(self):

        print("Loading cross-encoder reranker...")

        self.model = CrossEncoder(
            "cross-encoder/ms-marco-MiniLM-L-6-v2"
        )

        print("Cross-encoder ready")

    def rerank(
        self,
        query: str,
        candidates: List[Dict],
        top_k: int = DEFAULT_TOP_K
    ) -> List[Dict]:

        if not candidates:
            return []

        pairs = [
            (query, c["chunk"]["text"])
            for c in candidates
        ]

        scores = self.model.predict(pairs)

        for c, s in zip(candidates, scores):
            c["ce_score"] = float(s)

        ranked = sorted(
            candidates,
            key=lambda x: x["ce_score"],
            reverse=True
        )

        return ranked[:top_k]


# ============================================
# GEMINI GENERATOR
# ============================================

class GeminiGenerator:

    def __init__(
        self,
        model_name="models/gemini-flash-lite-latest"
    ):

        api_key = os.getenv("GOOGLE_API_KEY")

        if not api_key:
            raise RuntimeError("GOOGLE_API_KEY not set")

        self.client = genai.Client(api_key=api_key)

        self.model_name = model_name

        print(f"Using Gemini model: {model_name}")

    def generate(
        self,
        query: str,
        chunks: List[Dict]
    ) -> str:

        if not chunks:
            return "No relevant information found."

        context = ""

        for i, c in enumerate(chunks, 1):

            context += f"[{i}] {c['chunk']['text']}\n\n"

        prompt = f"""
Answer the medical question using ONLY the sources below.

Cite sources using [1], [2], etc.

SOURCES
{context}

QUESTION
{query}

ANSWER
"""

        try:

            response = self.client.models.generate_content(
                model=self.model_name,
                contents=prompt
            )

            return response.text

        except Exception as e:

            if "RESOURCE_EXHAUSTED" in str(e):

                print("Rate limit reached. Waiting 30 seconds...")

                time.sleep(30)

                response = self.client.models.generate_content(
                    model=self.model_name,
                    contents=prompt
                )

                return response.text

            raise


# ============================================
# COMPLETE RAG PIPELINE
# ============================================

class CompleteRAGPipeline:

    def __init__(
        self,
        faiss_db_path: str,
        embedding_model: str
    ):

        print("\nInitializing Medical RAG Pipeline\n")

        self.query_processor = MedicalQueryProcessor(
            embedding_model
        )

        self.retriever = HybridRetriever(
            faiss_db_path
        )

        self.reranker = MedicalReranker()

        self.llm = GeminiGenerator()

        print("\nPipeline ready\n")

    def get_available_reports(self) -> List[str]:

        return self.retriever.get_available_reports()

    def ask(
        self,
        query: str,
        report_name: Optional[str] = None
    ) -> Dict:

        processed = self.query_processor.process(query)

        candidates = self.retriever.search(
            processed["embedding"],
            query
        )

        # ----------------------------------
        # REPORT FILTERING
        # ----------------------------------

        if report_name:

            candidates = [
                c for c in candidates
                if c["chunk"].get("filename") == report_name
            ]

            if not candidates:

                return {
                    "query": query,
                    "answer": f"No information found for report: {report_name}",
                    "timestamp": datetime.now().isoformat()
                }

        # ----------------------------------
        # RERANK
        # ----------------------------------

        top_chunks = self.reranker.rerank(
            query,
            candidates,
            top_k=DEFAULT_TOP_K
        )

        # ----------------------------------
        # GENERATE ANSWER
        # ----------------------------------

        answer = self.llm.generate(
            query,
            top_chunks
        )

        return {
            "query": query,
            "answer": answer,
            "sources": top_chunks,
            "timestamp": datetime.now().isoformat()
        }


# ============================================
# MAIN TEST
# ============================================

def main():

    FAISS_DB = "output/biomedbert_vector_db"

    EMB_MODEL = "microsoft/BiomedNLP-BiomedBERT-base-uncased-abstract-fulltext"

    pipeline = CompleteRAGPipeline(
        FAISS_DB,
        EMB_MODEL
    )

    reports = pipeline.get_available_reports()

    print("\nAvailable reports:")
    print(reports)

    result = pipeline.ask(
        "What abnormal findings are present?",
        report_name=reports[0] if reports else None
    )

    print("\nAnswer:\n")
    print(result["answer"])


if __name__ == "__main__":
    main()