🔬 Microflow Cytometry Research Assistant
AI-powered Q&A over three research papers on photonic-microfluidic flow cytometry, MDS cancer diagnosis, and biosensing
import os import logging from typing import List, Dict, Any # ============================================================ # FIX: Gradio + Pydantic 2.11+ bug workaround # Must be imported BEFORE gradio to patch the buggy schema generator # ============================================================ import gradio_client.utils as _gcu _orig_get_type = _gcu.get_type def _safe_get_type(schema): if not isinstance(schema, dict): return "Any" return _orig_get_type(schema) _gcu.get_type = _safe_get_type _orig_jspt = _gcu._json_schema_to_python_type def _safe_jspt(schema, defs=None): if isinstance(schema, bool): return "Any" return _orig_jspt(schema, defs) _gcu._json_schema_to_python_type = _safe_jspt import gradio as gr import spaces from dotenv import load_dotenv from rag_engine import RAGEngine, SUGGESTED_QUESTIONS from document_processor import PDFProcessor, add_contextual_metadata from config import DOCUMENT_METADATA, PDF_FILES, LLM_MODEL load_dotenv() logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # ============================================================ # FIX: ZeroGPU requires at least one @spaces.GPU function at startup # ============================================================ @spaces.GPU(duration=60) def gpu_warmup(): """Dummy function to satisfy ZeroGPU startup detection.""" return True _engine: RAGEngine = None def get_engine() -> RAGEngine: global _engine if _engine is None: logger.info("Initializing RAG engine...") _engine = RAGEngine() vs = _engine.load_vector_store() if vs is None: logger.info("Building vector store from PDFs (this may take a minute)...") processor = PDFProcessor() docs = processor.process_all_documents() docs = add_contextual_metadata(docs) _engine.build_vector_store(docs) return _engine CUSTOM_CSS = """ .gradio-container { max-width: 1400px !important; margin: auto; font-family: 'Inter', sans-serif; } .main-header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 2rem; border-radius: 16px; color: white; margin-bottom: 1.5rem; box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3); } .main-header h1 { margin: 0 0 0.5rem 0; font-size: 2.2rem; font-weight: 700; } .main-header p { margin: 0; opacity: 0.95; font-size: 1.05rem; } .paper-card { background: linear-gradient(135deg, #f5f7fa 0%, #e8eef5 100%); padding: 1rem; border-radius: 12px; border-left: 4px solid #667eea; margin-bottom: 0.75rem; } .paper-card h4 { margin: 0 0 0.4rem 0; color: #2d3748; font-size: 0.95rem; } .paper-card .meta { color: #718096; font-size: 0.85rem; margin: 0; } .topic-tag { background: #667eea; color: white; padding: 0.15rem 0.5rem; border-radius: 12px; font-size: 0.7rem; font-weight: 500; margin-right: 4px; } .source-box { background: #f7fafc; border-radius: 8px; padding: 0.75rem; margin-bottom: 0.5rem; border-left: 3px solid #48bb78; } .source-box .source-header { font-weight: 600; color: #2d3748; font-size: 0.9rem; margin-bottom: 0.3rem; } .source-box .source-meta { color: #718096; font-size: 0.8rem; margin-bottom: 0.4rem; } .source-box .source-preview { color: #4a5568; font-size: 0.82rem; font-style: italic; } """ def format_sources_html(sources: List[Dict[str, Any]]) -> str: if not sources: return "
No sources cited.
" html_parts = [] for i, s in enumerate(sources, 1): title = s.get("title", s.get("source", "Unknown")) page = s.get("page", "?") score = s.get("similarity_score", 0) preview = s.get("preview", "") score_color = "#48bb78" if score < 0.5 else ("#ed8936" if score < 0.8 else "#f56565") html_parts.append(f"""AI-powered Q&A over three research papers on photonic-microfluidic flow cytometry, MDS cancer diagnosis, and biosensing
Sources will appear here.
") with gr.Column(scale=1): gr.Markdown("### ⚙️ Retrieval Settings") top_k_slider = gr.Slider(minimum=2, maximum=12, value=6, step=1, label="Chunks to retrieve") source_dropdown = gr.Dropdown(choices=["All Papers"] + [meta["title"] for meta in DOCUMENT_METADATA.values()], value="All Papers", label="Filter by Paper") gr.Markdown("---") gr.Markdown("### 📄 Indexed Papers") gr.HTML(format_papers_sidebar()) gr.Markdown("---") gr.Markdown(f"**LLM:** `{LLM_MODEL}` (Groq) \n**Embeddings:** `all-MiniLM-L6-v2` \n**Vector DB:** FAISS") gr.Markdown("### 💡 Suggested Questions") with gr.Row(): with gr.Column(): for i in range(0, len(SUGGESTED_QUESTIONS), 2): with gr.Row(): for q in SUGGESTED_QUESTIONS[i:i+2]: gr.Button(q[:100] + "...", size="sm").click(fn=lambda x=q: x, outputs=msg_input) def submit_handler(message, history, top_k, source_filter): yield from respond(message, history, int(top_k), source_filter) return gr.update(value="") submit_btn.click(fn=submit_handler, inputs=[msg_input, chatbot, top_k_slider, source_dropdown], outputs=[chatbot, msg_input, sources_html]) msg_input.submit(fn=submit_handler, inputs=[msg_input, chatbot, top_k_slider, source_dropdown], outputs=[chatbot, msg_input, sources_html]) clear_btn.click(fn=lambda: ([], "", ""), outputs=[chatbot, msg_input, sources_html]) return demo if __name__ == "__main__": demo = create_ui() # show_api=False fixes the Gradio rendering bug on Hugging Face demo.launch(server_name="0.0.0.0", server_port=7860, show_api=False)