Microflow-Cytometry / frontend.py
MalikShehram's picture
Update frontend.py
69d66f8 verified
Raw History Blame Contribute Delete
9.54 kB
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 "<p style='color: #a0aec0; text-align: center;'>No sources cited.</p>"
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"""
<div class="source-box">
<div class="source-header">[{i}] {title}</div>
<div class="source-meta">πŸ“„ Page {page} &nbsp;β€’&nbsp; <span style="color: {score_color}; font-weight: 600;">Score: {score:.3f}</span></div>
<div class="source-preview">"{preview}"</div>
</div>
""")
return "".join(html_parts)
def format_papers_sidebar() -> str:
html_parts = []
for filename in PDF_FILES:
meta = DOCUMENT_METADATA.get(filename, {})
if not meta: continue
topics_html = "".join(f'<span class="topic-tag">{t}</span>' for t in meta.get("topics", [])[:4])
html_parts.append(f"""
<div class="paper-card">
<h4>{meta.get('title', filename)[:80]}...</h4>
<p class="meta">{meta.get('authors', 'Unknown')[:60]}...<br>{meta.get('journal', '')} β€’ {meta.get('year', '')}</p>
<div style="margin-top: 0.5rem;">{topics_html}</div>
</div>
""")
return "".join(html_parts)
def respond(message: str, history: List[Dict[str, str]], top_k: int, source_filter: str):
if not message.strip():
yield history, "", ""
return
history = history + [{"role": "user", "content": message}]
history.append({"role": "assistant", "content": "⏳ *Thinking...*"})
yield history, "", ""
filter_file = None
if source_filter and source_filter != "All Papers":
for filename, meta in DOCUMENT_METADATA.items():
if filename == source_filter or meta.get("title") == source_filter:
filter_file = filename
break
try:
engine = get_engine()
docs, scores = engine.retrieve(message, top_k=top_k, source_filter=filter_file)
if not docs:
history[-1]["content"] = "I couldn't find relevant information. Try rephrasing."
yield history, "", ""
return
context = engine._format_context(docs)
sources = engine._extract_sources(docs, scores)
sources_html = format_sources_html(sources)
from langchain_core.output_parsers import StrOutputParser
from rag_engine import RAG_PROMPT
chain = RAG_PROMPT | engine.llm | StrOutputParser()
answer = chain.invoke({"context": context, "question": message})
history[-1]["content"] = answer
yield history, "", sources_html
except Exception as e:
logger.error(f"Error: {e}")
history[-1]["content"] = f"⚠️ Error: {str(e)}"
yield history, "", ""
def create_ui() -> gr.Blocks:
with gr.Blocks(title="Microflow Cytometry RAG", css=CUSTOM_CSS, theme=gr.themes.Soft(primary_hue="indigo")) as demo:
gr.HTML("""
<div class="main-header">
<h1>πŸ”¬ Microflow Cytometry Research Assistant</h1>
<p>AI-powered Q&A over three research papers on photonic-microfluidic flow cytometry, MDS cancer diagnosis, and biosensing</p>
</div>
""")
with gr.Row():
with gr.Column(scale=3):
chatbot = gr.Chatbot(label="Research Assistant", height=520, type="messages", show_copy_button=True)
with gr.Row():
msg_input = gr.Textbox(label="Your question", placeholder="Ask anything...", lines=2, scale=5, show_label=False)
submit_btn = gr.Button("Send πŸš€", variant="primary", scale=1, min_width=100)
clear_btn = gr.Button("πŸ—‘οΈ Clear Chat", variant="secondary", size="sm")
with gr.Accordion("πŸ“š Cited Sources", open=False):
sources_html = gr.HTML("<p style='color: #a0aec0; text-align: center;'>Sources will appear here.</p>")
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)