Spaces:
Sleeping
Sleeping
Download rag_engine.py from MalikShehram/Microflow-Cytometry: direct link, hf CLI and curl.
- Browser
- Download file 7.14 kB
-
https://huggingface.co/spaces/MalikShehram/Microflow-Cytometry/resolve/main/rag_engine.py
- Command line
-
hf download hf://spaces/MalikShehram/Microflow-Cytometry/rag_engine.py
-
curl -L -o rag_engine.py https://huggingface.co/spaces/MalikShehram/Microflow-Cytometry/resolve/main/rag_engine.py
7.14 kB
| import os | |
| import logging | |
| from typing import List, Dict, Any, Optional, Tuple | |
| from dataclasses import dataclass | |
| from langchain_huggingface import HuggingFaceEmbeddings | |
| from langchain_community.vectorstores import FAISS | |
| from langchain_groq import ChatGroq | |
| from langchain_core.prompts import ChatPromptTemplate | |
| from langchain_core.documents import Document | |
| from langchain_core.output_parsers import StrOutputParser | |
| from config import ( | |
| EMBEDDING_MODEL, LLM_MODEL, LLM_TEMPERATURE, LLM_MAX_TOKENS, | |
| VECTOR_STORE_DIR, INDEX_NAME, TOP_K | |
| ) | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| SYSTEM_PROMPT = """You are an expert research assistant specializing in: | |
| 1. **Microflow Cytometry** - microfluidic-integrated flow cytometry for blood cancer diagnosis | |
| 2. **Photonic-Microfluidic Integration** - planar waveguides, beam shaping, SU-8 fabrication | |
| 3. **Point-of-Care Diagnostics** - agglutination immunoassays, transit-time analysis | |
| 4. **Hematological Malignancies** - MDS, leukemia (ALL/AML/CLL/CML) | |
| 5. **Biomarker Analysis** - CD45, CD34, CD117, immunophenotyping, Ogata score, IPSS-R | |
| When answering: | |
| - **Cite sources** using [Source: filename, Page X] format | |
| - **Connect concepts** across the three papers when relevant | |
| - **Be technical but clear** | |
| - **If information isn't in context**, say so honestly rather than hallucinating | |
| """ | |
| RAG_PROMPT = ChatPromptTemplate.from_messages([ | |
| ("system", SYSTEM_PROMPT), | |
| ("human", """Retrieved Context from Research Papers: | |
| {context} | |
| --- | |
| Question: {question} | |
| Please provide a comprehensive, well-structured answer with citations:""") | |
| ]) | |
| class RAGResponse: | |
| answer: str | |
| sources: List[Dict[str, Any]] | |
| query: str | |
| retrieval_scores: List[float] | |
| class RAGEngine: | |
| def __init__(self, groq_api_key: Optional[str] = None): | |
| self.groq_api_key = groq_api_key or os.environ.get("GROQ_API_KEY") | |
| if not self.groq_api_key: | |
| raise ValueError("GROQ_API_KEY is required.") | |
| # Load embeddings (allow auto-detection of CUDA/GPU on ZeroGPU) | |
| self.embeddings = HuggingFaceEmbeddings( | |
| model_name=EMBEDDING_MODEL, | |
| encode_kwargs={'normalize_embeddings': True} | |
| ) | |
| self.llm = ChatGroq( | |
| api_key=self.groq_api_key, | |
| model=LLM_MODEL, | |
| temperature=LLM_TEMPERATURE, | |
| max_tokens=LLM_MAX_TOKENS, | |
| ) | |
| self.vector_store: Optional[FAISS] = None | |
| self.index_path = VECTOR_STORE_DIR / INDEX_NAME | |
| def build_vector_store(self, documents: List[Document]) -> FAISS: | |
| logger.info(f"Building vector store from {len(documents)} chunks...") | |
| self.vector_store = FAISS.from_documents(documents, self.embeddings) | |
| self.vector_store.save_local(str(self.index_path)) | |
| return self.vector_store | |
| def load_vector_store(self) -> Optional[FAISS]: | |
| if self.index_path.exists(): | |
| try: | |
| self.vector_store = FAISS.load_local( | |
| str(self.index_path), | |
| self.embeddings, | |
| allow_dangerous_deserialization=True | |
| ) | |
| return self.vector_store | |
| except Exception as e: | |
| logger.error(f"Failed to load vector store: {e}") | |
| return None | |
| def get_or_create_vector_store(self, documents: Optional[List[Document]] = None) -> FAISS: | |
| vs = self.load_vector_store() | |
| if vs is None: | |
| if documents is None: | |
| raise ValueError("No vector store exists and no documents provided") | |
| vs = self.build_vector_store(documents) | |
| return vs | |
| def retrieve(self, query: str, top_k: int = TOP_K, source_filter: Optional[str] = None) -> Tuple[List[Document], List[float]]: | |
| if self.vector_store is None: | |
| raise RuntimeError("Vector store not initialized") | |
| results = self.vector_store.similarity_search_with_score(query, k=top_k * 2 if source_filter else top_k) | |
| if source_filter: | |
| results = [(doc, score) for doc, score in results if doc.metadata.get("source") == source_filter][:top_k] | |
| docs = [doc for doc, _ in results] | |
| scores = [score for _, score in results] | |
| return docs, scores | |
| def _format_context(self, documents: List[Document]) -> str: | |
| context_parts = [] | |
| for i, doc in enumerate(documents, 1): | |
| source = doc.metadata.get("source", "Unknown") | |
| page = doc.metadata.get("page", "?") | |
| title = doc.metadata.get("title", "") | |
| header = f"[Chunk {i}] Source: {source} (Page {page})" | |
| if title: | |
| header += f"\nPaper: {title}" | |
| context_parts.append(f"{header}\n{doc.page_content}") | |
| return "\n\n---\n\n".join(context_parts) | |
| def _extract_sources(self, documents: List[Document], scores: List[float]) -> List[Dict[str, Any]]: | |
| sources = [] | |
| for doc, score in zip(documents, scores): | |
| sources.append({ | |
| "source": doc.metadata.get("source", "Unknown"), | |
| "title": doc.metadata.get("title", ""), | |
| "page": doc.metadata.get("page", "?"), | |
| "similarity_score": round(float(score), 4), | |
| "preview": doc.page_content[:200] + "...", | |
| }) | |
| return sources | |
| def query(self, question: str, top_k: int = TOP_K, source_filter: Optional[str] = None) -> RAGResponse: | |
| docs, scores = self.retrieve(question, top_k, source_filter) | |
| if not docs: | |
| return RAGResponse("I couldn't find relevant information.", [], question, []) | |
| context = self._format_context(docs) | |
| chain = RAG_PROMPT | self.llm | StrOutputParser() | |
| answer = chain.invoke({"context": context, "question": question}) | |
| return RAGResponse(answer, self._extract_sources(docs, scores), question, scores) | |
| SUGGESTED_QUESTIONS = [ | |
| "How does the bowtie-shaped beam shaping in Watts et al. improve flow cytometry sensitivity, and what computational methods could further optimize this beam design?", | |
| "Compare the diagnostic criteria for MDS using flow cytometry (Ogata score, IPSS-R) with the SARS-CoV-2 antibody detection method in Qu et al.", | |
| "What are the main limitations of conventional flow cytometry for MDS diagnosis, and how does microflow cytometry address them?", | |
| "Explain the transit-time analysis method used in the SARS-CoV-2 immunoassay and how machine learning could improve aggregate classification.", | |
| "How could the photonic-microfluidic integration from Watts et al. be adapted for MDS biomarker detection?", | |
| "What biomarkers are most relevant for MDS diagnosis, and which ones are most amenable to microflow cytometry detection?", | |
| "Describe the SU-8 fabrication process used for the photonic-microfluidic device. What are the design trade-offs?", | |
| "How does the prozone effect limit the SARS-CoV-2 immunoassay, and what computational solutions could extend the dynamic range?", | |
| ] |