File size: 8,751 Bytes
793d027
 
 
 
 
 
2cec50c
 
793d027
 
 
 
 
408e7e3
793d027
408e7e3
2cec50c
 
 
793d027
 
 
 
408e7e3
793d027
 
 
 
 
 
 
408e7e3
793d027
 
 
 
 
 
 
 
 
408e7e3
793d027
 
 
 
 
 
 
 
 
 
 
 
 
 
408e7e3
793d027
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
408e7e3
793d027
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
408e7e3
793d027
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""ChromaDB vector store for unstructured document RAG."""

from pathlib import Path
from typing import Optional
import hashlib

from ..config import get_settings

# Project paths
PROJECT_ROOT = Path(__file__).parent.parent.parent
DOCS_DIR = PROJECT_ROOT / "docs"


def get_chroma_client():
    """Get ChromaDB persistent client."""
    import chromadb
    chroma_dir = get_settings().chroma_db_dir
    chroma_dir.mkdir(parents=True, exist_ok=True)
    return chromadb.PersistentClient(path=str(chroma_dir))


def get_embedding_function():
    """Get the embedding function for ChromaDB."""
    from chromadb.utils import embedding_functions
    return embedding_functions.SentenceTransformerEmbeddingFunction(
        model_name="all-MiniLM-L6-v2"
    )


def extract_pdf_text(pdf_path: Path) -> str:
    """Extract text from PDF file."""
    from pypdf import PdfReader
    reader = PdfReader(pdf_path)
    text = ""
    for page in reader.pages:
        text += page.extract_text() + "\n\n"
    return text


def chunk_text(text: str, chunk_size: int = 1000, chunk_overlap: int = 200) -> list[str]:
    """Split text into chunks for embedding."""
    from langchain_text_splitters import RecursiveCharacterTextSplitter
    splitter = RecursiveCharacterTextSplitter(
        chunk_size=chunk_size,
        chunk_overlap=chunk_overlap,
        separators=["\n\n", "\n", ". ", " ", ""]
    )
    return splitter.split_text(text)


def generate_doc_id(text: str, index: int) -> str:
    """Generate a unique document ID."""
    hash_input = f"{text[:100]}_{index}"
    return hashlib.md5(hash_input.encode()).hexdigest()


def init_idsa_guidelines_collection():
    """Initialize the IDSA treatment guidelines collection."""
    client = get_chroma_client()
    ef = get_embedding_function()

    # Delete existing collection if exists
    try:
        client.delete_collection("idsa_treatment_guidelines")
    except Exception:
        pass

    collection = client.create_collection(
        name="idsa_treatment_guidelines",
        embedding_function=ef,
        metadata={
            "source": "IDSA 2024 Guidance",
            "doi": "10.1093/cid/ciae403",
            "description": "Antimicrobial-Resistant Gram-Negative Infections Treatment Guidelines"
        }
    )

    return collection


def init_mic_reference_collection():
    """Initialize the MIC reference documentation collection."""
    client = get_chroma_client()
    ef = get_embedding_function()

    # Delete existing collection if exists
    try:
        client.delete_collection("mic_reference_docs")
    except Exception:
        pass

    collection = client.create_collection(
        name="mic_reference_docs",
        embedding_function=ef,
        metadata={
            "source": "EUCAST Breakpoint Tables",
            "version": "16.0",
            "description": "MIC Breakpoint Reference Documentation"
        }
    )

    return collection


def classify_chunk_pathogen(text: str) -> str:
    """Classify which pathogen type a chunk relates to."""
    text_lower = text.lower()

    pathogen_keywords = {
        "ESBL-E": ["esbl", "extended-spectrum beta-lactamase", "esbl-e", "esbl-producing"],
        "CRE": ["carbapenem-resistant enterobacterales", "cre", "carbapenemase"],
        "CRAB": ["acinetobacter baumannii", "crab", "carbapenem-resistant acinetobacter"],
        "DTR-PA": ["pseudomonas aeruginosa", "dtr-p", "difficult-to-treat resistance"],
        "S.maltophilia": ["stenotrophomonas maltophilia", "s. maltophilia"],
        "AmpC-E": ["ampc", "ampc-e", "ampc-producing"],
    }

    for pathogen, keywords in pathogen_keywords.items():
        for keyword in keywords:
            if keyword in text_lower:
                return pathogen

    return "General"


def import_idsa_guidelines() -> int:
    """Import IDSA guidelines PDF into ChromaDB."""
    print("Importing IDSA guidelines into ChromaDB...")

    pdf_path = DOCS_DIR / "antibiotic_guidelines" / "ciae403.pdf"

    if not pdf_path.exists():
        print(f"  Warning: {pdf_path} not found, skipping...")
        return 0

    # Extract text from PDF
    print("  Extracting text from PDF...")
    text = extract_pdf_text(pdf_path)

    # Chunk the text
    print("  Chunking text...")
    chunks = chunk_text(text)

    # Initialize collection
    collection = init_idsa_guidelines_collection()

    # Prepare documents for insertion
    documents = []
    metadatas = []
    ids = []

    for i, chunk in enumerate(chunks):
        documents.append(chunk)
        metadatas.append({
            "source": "ciae403.pdf",
            "chunk_index": i,
            "pathogen_type": classify_chunk_pathogen(chunk),
            "page_estimate": i // 3  # Rough estimate
        })
        ids.append(generate_doc_id(chunk, i))

    # Add to collection
    print(f"  Adding {len(documents)} chunks to collection...")
    collection.add(
        documents=documents,
        metadatas=metadatas,
        ids=ids
    )

    print(f"  Imported {len(documents)} chunks from IDSA guidelines")
    return len(documents)


def import_mic_reference() -> int:
    """Import MIC breakpoint PDF into ChromaDB."""
    print("Importing MIC reference PDF into ChromaDB...")

    pdf_path = DOCS_DIR / "mic_breakpoints" / "v_16.0_Breakpoint_Tables.pdf"

    if not pdf_path.exists():
        print(f"  Warning: {pdf_path} not found, skipping...")
        return 0

    # Extract text from PDF
    print("  Extracting text from PDF...")
    text = extract_pdf_text(pdf_path)

    # Chunk the text
    print("  Chunking text...")
    chunks = chunk_text(text, chunk_size=800, chunk_overlap=150)

    # Initialize collection
    collection = init_mic_reference_collection()

    # Prepare documents for insertion
    documents = []
    metadatas = []
    ids = []

    for i, chunk in enumerate(chunks):
        documents.append(chunk)
        metadatas.append({
            "source": "v_16.0_Breakpoint_Tables.pdf",
            "chunk_index": i,
            "document_type": "mic_reference"
        })
        ids.append(generate_doc_id(chunk, i))

    # Add to collection
    print(f"  Adding {len(documents)} chunks to collection...")
    collection.add(
        documents=documents,
        metadatas=metadatas,
        ids=ids
    )

    print(f"  Imported {len(documents)} chunks from MIC reference")
    return len(documents)


def get_collection(name: str) -> Optional[object]:
    """Get a collection by name."""
    client = get_chroma_client()
    ef = get_embedding_function()

    try:
        return client.get_collection(name=name, embedding_function=ef)
    except Exception:
        return None


def search_guidelines(
    query: str,
    n_results: int = 5,
    pathogen_filter: str = None
) -> list[dict]:
    """Search the IDSA guidelines collection."""
    collection = get_collection("idsa_treatment_guidelines")

    if collection is None:
        return []

    where_filter = None
    if pathogen_filter:
        where_filter = {"pathogen_type": pathogen_filter}

    results = collection.query(
        query_texts=[query],
        n_results=n_results,
        where=where_filter,
        include=["documents", "metadatas", "distances"]
    )

    # Format results
    formatted = []
    for i in range(len(results['documents'][0])):
        formatted.append({
            "content": results['documents'][0][i],
            "metadata": results['metadatas'][0][i],
            "distance": results['distances'][0][i]
        })

    return formatted


def search_mic_reference(query: str, n_results: int = 3) -> list[dict]:
    """Search the MIC reference collection."""
    collection = get_collection("mic_reference_docs")

    if collection is None:
        return []

    results = collection.query(
        query_texts=[query],
        n_results=n_results,
        include=["documents", "metadatas", "distances"]
    )

    # Format results
    formatted = []
    for i in range(len(results['documents'][0])):
        formatted.append({
            "content": results['documents'][0][i],
            "metadata": results['metadatas'][0][i],
            "distance": results['distances'][0][i]
        })

    return formatted


def import_all_vectors() -> dict:
    """Import all PDFs into ChromaDB."""
    print(f"\n{'='*50}")
    print("ChromaDB Vector Import")
    print(f"{'='*50}\n")

    results = {
        "idsa_guidelines": import_idsa_guidelines(),
        "mic_reference": import_mic_reference(),
    }

    print(f"\n{'='*50}")
    print("Vector Import Summary:")
    for collection, count in results.items():
        print(f"  {collection}: {count} chunks")
    print(f"{'='*50}\n")

    return results


if __name__ == "__main__":
    import_all_vectors()