Spaces:
Sleeping

File size: 8,854 Bytes
7937092
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148cd91
 
 
8648980
148cd91
 
 
 
 
 
 
 
 
d426772
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7937092
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8648980
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
from langchain_groq import ChatGroq
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_chroma import Chroma
from langchain_classic.chains import ConversationalRetrievalChain
from langchain_classic.memory import ConversationBufferMemory
from langchain_core.prompts import PromptTemplate
from langchain_core.retrievers import BaseRetriever
from langchain_core.callbacks import CallbackManagerForRetrieverRun
from typing import List
from langchain_core.documents import Document
import os
import re

class MedicalChatbot:
    def __init__(self, vector_store_path=None):
        if vector_store_path is None:
            import os
            # Intelligently scan for the database (Local vs Hugging Face Dataset Mounts)
            possible_paths = [
                os.path.join(os.path.dirname(os.path.dirname(__file__)), "db", "vector_store"),
                "/data/TrinetraLabs/Placebo_AI_DB/db/vector_store",
                "/data/smart-models/Placebo_AI_DB/db/vector_store",
                "/data/db/vector_store"
            ]
            
            vector_store_path = possible_paths[0] # Default fallback
            for p in possible_paths:
                if os.path.exists(p):
                    vector_store_path = p
                    break
            
            # --- FUSE / NETWORK MOUNT FIX ---
            # SQLite struggles with file locks on HuggingFace Dataset mounts.
            # We copy the sqlite file to local fast storage and symlink the indices.
            if vector_store_path.startswith("/data/"):
                import shutil
                local_db_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "db", "vector_store")
                os.makedirs(local_db_path, exist_ok=True)
                
                print(f"Dataset mount detected. Copying SQLite DB to local storage to prevent locking timeout... (This may take a minute)")
                
                # Copy the sqlite file
                sqlite_src = os.path.join(vector_store_path, "chroma.sqlite3")
                sqlite_dst = os.path.join(local_db_path, "chroma.sqlite3")
                if os.path.exists(sqlite_src) and not os.path.exists(sqlite_dst):
                    shutil.copy2(sqlite_src, sqlite_dst)
                
                # Symlink all other directories (the heavy vector indices)
                for item in os.listdir(vector_store_path):
                    if item == "chroma.sqlite3":
                        continue
                    src_item = os.path.join(vector_store_path, item)
                    dst_item = os.path.join(local_db_path, item)
                    if os.path.isdir(src_item) and not os.path.exists(dst_item):
                        os.symlink(src_item, dst_item)
                        
                vector_store_path = local_db_path
                print("Database ready!")
        self.embeddings = HuggingFaceEmbeddings(
            model_name="nomic-ai/nomic-embed-text-v1.5",
            model_kwargs={'trust_remote_code': True}
        )
        
        # Connect to existing vector store
        if not os.path.exists(vector_store_path):
            raise FileNotFoundError(f"Vector store not found at {vector_store_path}. Please run indexer.py first.")
            
        self.vectorstore = Chroma(
            persist_directory=vector_store_path,
            embedding_function=self.embeddings
        )
        
        # Use Llama 3 for grounded inference via Groq
        self.llm = ChatGroq(
            model_name="llama-3.1-8b-instant",
            temperature=0.0, # Zero creativity for clinical safety
            streaming=True,
            groq_api_key=os.getenv("GROQ_API_KEY")
        )
        
        self.memory = ConversationBufferMemory(
            memory_key="chat_history",
            return_messages=True,
            output_key="answer"
        )
        
        self.prompt_template = """
        You are 'Placebo AI', a specialized Medical Knowledge Retrieval Assistant. 
        Your primary role is to extract and summarize medical information with 100% fidelity.

        STRICT CLINICAL PROTOCOLS:
        1. GROUNDING: Provide information ONLY from the provided CONTEXT. 
        2. DATA PRECISION: Preserve all numerical values, chemical formulas, and dosages EXACTLY as written.
        3. STRUCTURE & FORMATTING: 
           - **Pain Points & Symptoms**: Always bold key issues, pathological symptoms, patient pain points, or critical clinical risks (e.g., **severe nausea**, **respiratory depression**).
           - **Reactions & Mechanisms**: Stated clearly, using step-by-step reaction pathways, equations, or numbered sequences to detail chemical or physiological mechanisms.
           - Use Markdown Tables for data comparisons.
           - Use Bullet Points for lists.
        4. CITATION: You MUST end every factual statement with its source in [Book Name, Page #] format.
        5. FALLBACK: If the answer is truly not present in the context, say: "I'm sorry, but I couldn't find specific details on this topic in the current medical textbook library."

        CONTEXT: 
        {context}
        
        CHAT HISTORY: 
        {chat_history}
        
        QUESTION: 
        {question}
        
        PLACEBO AI RESPONSE (Start with 'Based on the clinical data in the textbooks:'):
        Based on the clinical data in the textbooks:
        """
        
        self.QA_PROMPT = PromptTemplate(
            template=self.prompt_template,
            input_variables=["context", "chat_history", "question"]
        )

        # Custom Retriever Logic for Exhaustive Reference Search
        class KeywordAugmentedRetriever(BaseRetriever):
            vectorstore: Chroma
            k: int = 10
            track_filter_state: str = "unified"
            
            def _get_relevant_documents(
                self, query: str, *, run_manager: CallbackManagerForRetrieverRun
            ) -> List[Document]:
                return self.get_relevant_documents_with_filter(query, track_filter=self.track_filter_state)

            def get_relevant_documents_with_filter(
                self, query: str, track_filter: str = "unified"
            ) -> List[Document]:
                # Build filter dictionary
                filter_dict = None
                if track_filter == "mbbs":
                    filter_dict = {"track": "mbbs"}
                elif track_filter == "pharmacy":
                    filter_dict = {"track": "pharmacy"}
                
                # 1. Vector Search (MMR for diversity)
                docs = self.vectorstore.max_marginal_relevance_search(
                    query, k=self.k, fetch_k=50, lambda_mult=0.3, filter=filter_dict
                )
                                    
                return docs

        self.custom_retriever = KeywordAugmentedRetriever(vectorstore=self.vectorstore, k=10)

        self.chain = ConversationalRetrievalChain.from_llm(
            llm=self.llm,
            retriever=self.custom_retriever,
            memory=self.memory,
            combine_docs_chain_kwargs={"prompt": self.QA_PROMPT},
            return_source_documents=True
        )

    def ask(self, query, mode="unified"):
        """
        Processes a medical query using exhaustive retrieval and returns a verified response.
        Routes to the correct domain track.
        """
        self.custom_retriever.track_filter_state = mode
        result = self.chain.invoke({"question": query})
        answer = result["answer"]
        
        # Deduplicate and format clinical sources
        seen_sources = set()
        formatted_sources = []
        
        for doc in result["source_documents"]:
            book = doc.metadata.get("book_name", "Unknown Source")
            page = doc.metadata.get("page_number", "N/A")
            source_key = f"{book}_P{page}"
            
            if source_key not in seen_sources:
                formatted_sources.append({
                    "book": book,
                    "page": page,
                    "subject": doc.metadata.get("subject", "General"),
                    "image_path": doc.metadata.get("image_path"),
                    "snippet": doc.page_content[:200] + "..."
                })
                seen_sources.add(source_key)
            
        return {
            "answer": answer,
            "sources": formatted_sources,
            "citation_footer": "\n\n---\n**Verified Clinical Sources:**\n" + \
                                "\n".join([f"- {s['book']} (Page {s['page']})" for s in formatted_sources])
        }

if __name__ == "__main__":
    # Internal test check
    try:
        bot = MedicalChatbot()
        print("Medical Chatbot Initialized Successfully.")
    except Exception as e:
        print(f"Chatbot wait-state: {e}")