Spaces:
Sleeping
Sleeping
nitish17855 commited on
Commit ·
030e7a9
1
Parent(s): 16ac7fc
Deploy native Gradio Blocks with demo.launch() and @spaces.GPU for ZeroGPU
Browse filesFiles changed (2)
- api/main.py+25-22
- app.py+172-34
54 unmodified lines555657585960616263646566676869707172737475766 unmodified lines838485868788899091928 unmodified lines1011021031041051061071081091101111121131141151161171181191203 unmodified lines1241251261271281291301318 unmodified lines14014114214314414554 unmodified linesVECTORS_CACHE_FILE = DATA_DIR / "aapl_bge_vectors.npy"@asynccontextmanagerasync def lifespan(app: FastAPI):"""ASGI Lifespan Manager:Executes once on server startup to warm up and load all heavy ML assets(BGE embeddings, Qdrant in-memory, BM25, CrossEncoder, CRAG Orchestrator)into global application memory (app.state), avoiding per-request initialization."""print("=" * 80, flush=True)print("[*] FASTAPI STARTUP: Initializing Enterprise CRAG Intelligence Engine...", flush=True)print("=" * 80, flush=True)app.state.start_time = time.time()t_boot_0 = time.perf_counter()# 1. Corpus Text & Document Chunksif not CACHE_FILE.exists():raise FileNotFoundError(f"Required corpus file missing: {CACHE_FILE}")6 unmodified linesd.metadata["source"] = "aapl-20250927.htm"d.metadata["ticker"] = "AAPL"d.metadata["fiscal_year"] = "2025"app.state.total_chunks = len(docs)print(f"[+] Loaded and indexed {len(docs)} chunks from SEC 10-K filing.", flush=True)# 2. Dense Embeddings & Vector Storageembedder = BGEEmbedding()if VECTORS_CACHE_FILE.exists():print(f"[*] Loading precomputed embeddings from cache: {VECTORS_CACHE_FILE}", flush=True)8 unmodified linesqdrant = QdrantStore(collection_name="aapl_production", vector_size=embedder.dimension, location=":memory:")qdrant.upsert_documents(documents=docs, vectors=vectors)# 3. Sparse BM25 Lexical Storebm25 = BM25Store()bm25.index_documents(documents=docs)# 4. Query Processing Modelsclassifier = QueryClassifier(model_name="gemini-3.5-flash-lite")decomposer = Query_decomposer(model_name="gemini-3.5-flash-lite")expander = QueryExpander(model_name="gemini-3.5-flash-lite")# 5. Reranker & CRAG Orchestrationreranker = get_reranker("local")crag_orchestrator = CRAGOrchestrator(reranker=reranker)# 6. Generator & Citation Verifierprompt_builder = PromptBuilder(system_prompt=CRAG_SYSTEM_PROMPT,user_template=CRAG_USER_PROMPT_TEMPLATE,3 unmodified linessource_attributor = SourceAttributor()tokenizer = tiktoken.get_encoding("cl100k_base")# Store loaded resources in app.state for request handlersapp.state.pipeline_context = {"embedder": embedder,"qdrant": qdrant,"bm25": bm25,8 unmodified lines"source_attributor": source_attributor,"tokenizer": tokenizer,}t_boot_sec = time.perf_counter() - t_boot_0print(f"[+] All models, stores, and CRAG chains initialized in {t_boot_sec:.2f}s.", flush=True)54 unmodified lines5556575859606162636465666 unmodified lines73747576777879808 unmodified lines89909192939495969798991001011021031043 unmodified lines1081091101111121131148 unmodified lines12312412512612712812913013113213313413513613713813914014114214314414514614714854 unmodified linesVECTORS_CACHE_FILE = DATA_DIR / "aapl_bge_vectors.npy"def init_pipeline_context():"""Initializes and warms up all heavy ML assets:BGE embeddings (CPU), Qdrant in-memory, BM25, CrossEncoder (CPU), CRAG Orchestrator, LLM provider.Returns (pipeline_context, total_chunks)."""if not CACHE_FILE.exists():raise FileNotFoundError(f"Required corpus file missing: {CACHE_FILE}")6 unmodified linesd.metadata["source"] = "aapl-20250927.htm"d.metadata["ticker"] = "AAPL"d.metadata["fiscal_year"] = "2025"print(f"[+] Loaded and indexed {len(docs)} chunks from SEC 10-K filing.", flush=True)embedder = BGEEmbedding()if VECTORS_CACHE_FILE.exists():print(f"[*] Loading precomputed embeddings from cache: {VECTORS_CACHE_FILE}", flush=True)8 unmodified linesqdrant = QdrantStore(collection_name="aapl_production", vector_size=embedder.dimension, location=":memory:")qdrant.upsert_documents(documents=docs, vectors=vectors)bm25 = BM25Store()bm25.index_documents(documents=docs)classifier = QueryClassifier(model_name="gemini-3.5-flash-lite")decomposer = Query_decomposer(model_name="gemini-3.5-flash-lite")expander = QueryExpander(model_name="gemini-3.5-flash-lite")reranker = get_reranker("local")crag_orchestrator = CRAGOrchestrator(reranker=reranker)prompt_builder = PromptBuilder(system_prompt=CRAG_SYSTEM_PROMPT,user_template=CRAG_USER_PROMPT_TEMPLATE,3 unmodified linessource_attributor = SourceAttributor()tokenizer = tiktoken.get_encoding("cl100k_base")pipeline_context = {"embedder": embedder,"qdrant": qdrant,"bm25": bm25,8 unmodified lines"source_attributor": source_attributor,"tokenizer": tokenizer,}return pipeline_context, len(docs)@asynccontextmanagerasync def lifespan(app: FastAPI):"""ASGI Lifespan Manager:Executes once on server startup to warm up and load all heavy ML assetsinto global application memory (app.state), avoiding per-request initialization."""print("=" * 80, flush=True)print("[*] FASTAPI STARTUP: Initializing Enterprise CRAG Intelligence Engine...", flush=True)print("=" * 80, flush=True)app.state.start_time = time.time()t_boot_0 = time.perf_counter()ctx, total_chunks = init_pipeline_context()app.state.pipeline_context = ctxapp.state.total_chunks = total_chunkst_boot_sec = time.perf_counter() - t_boot_0print(f"[+] All models, stores, and CRAG chains initialized in {t_boot_sec:.2f}s.", flush=True)
123456726 unmodified lines34353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879"""Hugging Face Spaces Entrypoint (Gradio SDK compatible)Runs the Enterprise AURA CRAG FastAPI application with custom Glass-Box Frontendand mounts Gradio on port 7860 with 16 GB RAM support."""try:26 unmodified linesnltk.download(pkg, quiet=True)import gradio as grimport uvicornfrom api.main import app@spaces.GPUdef predict(query: str):if not query or not query.strip():return "Please enter a valid financial question (e.g. What was Apple's total revenue in FY 2025?)."try:from api.service import run_glassbox_crag_pipelinefrom api.schemas import QueryRequestreq = QueryRequest(query=query.strip(), enable_crag=True, top_k=5)context = getattr(app.state, "pipeline_context", None)if not context:return "⏳ Pipeline models are still warming up in memory. Please retry in 5 seconds."res = run_glassbox_crag_pipeline(req, context)return f"⚡ [CRAG Decision: {res.crag_action}] (Confidence: {res.confidence_score:.2f})\n\n{res.synthesized_answer}"except Exception as e:return f"Pipeline Execution Error: {str(e)}"with gr.Blocks(title="AURA CRAG — Enterprise Financial Intelligence", fill_width=True) as demo:gr.Markdown("# ⚡ AURA CRAG — Enterprise Financial Intelligence & Glass-Box Studio")with gr.Row():query_input = gr.Textbox(label="ZeroGPU Quick Query",placeholder="e.g. What was Apple's total revenue in FY 2025?",scale=4)submit_btn = gr.Button("Analyze via GPU", variant="primary", scale=1)status_output = gr.Textbox(label="Synthesized Intelligence & CRAG Routing Action", interactive=False, lines=4)submit_btn.click(fn=predict, inputs=query_input, outputs=status_output)gr.Markdown("---")gr.Markdown("### 🏛️ Interactive Glass-Box Studio (Live SEC 10-K Pipeline)")gr.HTML('<iframe src="/studio" style="width:100%; height:880px; border:none; border-radius:12px; box-shadow: 0 4px 25px rgba(0,0,0,0.4);"></iframe>')# Mount Gradio at root '/' so Hugging Face ZeroGPU probe detects it directly!app = gr.mount_gradio_app(app, demo, path="/")if __name__ == "__main__":uvicorn.run(app, host="0.0.0.0", port=7860)12345626 unmodified lines33343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217"""AURA CRAG — Enterprise Financial Intelligence & Glass-Box StudioProduction ZeroGPU Deployment on Hugging Face Spaces (Gradio 5 SDK)"""try:26 unmodified linesnltk.download(pkg, quiet=True)import gradio as grfrom api.main import init_pipeline_contextfrom api.service import run_glassbox_crag_pipelinefrom api.schemas import QueryRequest# Lazy-loaded singleton pipeline context_CONTEXT = Nonedef get_context():global _CONTEXTif _CONTEXT is None:_CONTEXT, _ = init_pipeline_context()return _CONTEXT@spaces.GPUdef query_financial_rag(query: str, enable_crag: bool, top_k: int):"""Core Inference Endpoint decorated with @spaces.GPU.ZeroGPU dynamically provisions an NVIDIA GPU slice to execute this function."""if not query or not query.strip():return ("⚠️ Please enter a financial question to analyze.","No query entered.","No query entered.","No query entered.",)try:ctx = get_context()req = QueryRequest(query=query.strip(), enable_crag=enable_crag, top_k=int(top_k))response = run_glassbox_crag_pipeline(req, ctx)# 1. Executive Answer & Header Metricsaction = response.crag_actionaction_emoji = "✅" if action == "CORRECT" else ("🌐" if action == "INCORRECT" else "⚖️")answer_md = f"### 💬 Synthesized Financial Intelligence\n\n"answer_md += f"{response.synthesized_answer}\n\n"answer_md += f"---\n"answer_md += f"**CRAG Routing Decision:** `{action_emoji} {action}` | **Confidence:** `{response.confidence_score:.2f}`\n\n"answer_md += f"**Total Latency:** `{response.latency_breakdown.total_ms:.1f} ms` | **Estimated Cost:** `${response.estimated_cost_usd:.5f}`"# 2. Stage 1 & 2: Decomposition & Hybrid Retrievals1 = response.stage_1_query_processings2 = response.stage_2_hybrid_retrievalstage1_2_md = f"### 🧭 Stage 1: Query Intent & Decomposition\n"stage1_2_md += f"- **Classified Intent:** `{s1.classified_type}` (Confidence: `{s1.confidence:.2f}`)\n"stage1_2_md += f"- **Decomposed Sub-queries ({len(s1.decomposed_subqueries)}):**\n"for sq in s1.decomposed_subqueries:stage1_2_md += f" - `{sq}`\n"if s1.expanded_queries:stage1_2_md += f"- **Lexical Expansions:** `{', '.join(s1.expanded_queries)}`\n"stage1_2_md += f"\n### 🔍 Stage 2: Dual Hybrid Retrieval\n"stage1_2_md += f"#### Dense Semantic Candidates (Qdrant in-memory — top {len(s2.dense_candidates)}):\n"for c in s2.dense_candidates[:3]:stage1_2_md += f"- **[{c.chunk_id}]** (Score: `{c.score:.4f}`): {c.content[:160]}...\n"stage1_2_md += f"\n#### Sparse Lexical Candidates (BM25Okapi — top {len(s2.sparse_candidates)}):\n"for c in s2.sparse_candidates[:3]:stage1_2_md += f"- **[{c.chunk_id}]** (Score: `{c.score:.4f}`): {c.content[:160]}...\n"# 3. Stage 3 & 4: Reranking & Corrective Evaluations3 = response.stage_3_fusion_and_reranks4 = response.stage_4_crag_enginestage3_4_md = f"### ⚡ Stage 3: Fusion & Cross-Encoder Reranking\n"stage3_4_md += f"**Top Reranked Chunks (ms-marco-MiniLM-L6-v2):**\n"for r in s3.reranked_chunks[:3]:stage3_4_md += f"- **[{r.chunk_id}]** (CrossEncoder Score: `{r.score:.4f}`): {r.content[:160]}...\n"stage3_4_md += f"\n### 🛡️ Stage 4: 3-Branch Corrective RAG Evaluation\n"stage3_4_md += f"- **Evaluator State:** `{s4.action}` | **Evaluator Score:** `{s4.confidence_score:.2f}`\n"if s4.web_search_fallback:stage3_4_md += f"\n**🌐 Live Tavily Web Search Fallback Triggered:**\n"for w in s4.web_search_fallback:stage3_4_md += f"- [{w.title}]({w.url})\n *{w.snippet[:140]}...*\n"else:stage3_4_md += f"\n- **Internal Corpus Sufficiency:** SEC 10-K disclosures provided sufficient evidence; web search bypassed.\n"# 4. Stage 5: Attribution & Grounding Audits5 = response.stage_5_attribution_auditstage5_md = f"### 🔬 Stage 5: Citation & Grounding Verification\n"stage5_md += f"- **Attribution Score:** `{s5.attribution_score * 100:.1f}%`\n"stage5_md += f"- **Verified Document Citations:** `{', '.join(s5.verified_citations) if s5.verified_citations else 'None'}`\n"stage5_md += f"- **Hallucinated / Unverified Citations:** `{', '.join(s5.hallucinated_citations) if s5.hallucinated_citations else '0 (Perfect Grounding)'}`\n\n"stage5_md += f"**Latency Breakdown:**\n"stage5_md += f"- Retrieval: `{response.latency_breakdown.retrieval_ms:.1f} ms`\n"stage5_md += f"- Reranking: `{response.latency_breakdown.rerank_ms:.1f} ms`\n"stage5_md += f"- Evaluation: `{response.latency_breakdown.crag_eval_ms:.1f} ms`\n"stage5_md += f"- Generation: `{response.latency_breakdown.generation_ms:.1f} ms`\n"return answer_md, stage1_2_md, stage3_4_md, stage5_mdexcept Exception as e:import tracebacktraceback.print_exc()err_msg = f"❌ Pipeline Execution Error: {str(e)}"return err_msg, err_msg, err_msg, err_msg# ==============================================================================# GRADIO APPLICATION INTERFACE# ==============================================================================CUSTOM_CSS = """.gradio-container {max-width: 1200px !important;margin: auto !important;font-family: 'Inter', -apple-system, sans-serif !important;}.header-box {background: linear-gradient(135deg, #111827 0%, #1f2937 100%);padding: 24px;border-radius: 12px;color: white;margin-bottom: 20px;border: 1px solid rgba(255,255,255,0.1);}"""with gr.Blocks(title="AURA CRAG — Enterprise Financial Intelligence") as demo:gr.HTML("""<div class="header-box"><h1 style="margin:0; font-size: 26px; font-weight: 700; color: #f9fafb;">⚡ AURA CRAG — Enterprise Financial Intelligence & Glass-Box Studio</h1><p style="margin: 8px 0 0 0; color: #9ca3af; font-size: 14px;">Production Corrective RAG indexing <b>Apple Inc. (AAPL) Form 10-K (FY 2025)</b> with Qdrant, BM25, Cross-Encoder reranking, and Tavily fallback.</p></div>""")with gr.Row():with gr.Column(scale=4):query_input = gr.Textbox(label="Enter Financial Question",placeholder="e.g. What was Apple's total revenue and net income in FY 2025?",lines=2,)with gr.Column(scale=1):enable_crag_toggle = gr.Checkbox(label="Enable Corrective RAG (CRAG)", value=True)top_k_slider = gr.Slider(minimum=1, maximum=10, value=5, step=1, label="Top-K Chunks")submit_btn = gr.Button("Analyze via ZeroGPU ⚡", variant="primary", size="lg")# Preset Query Chipsgr.Examples(examples=[["What was Apple's total revenue and net income in FY 2025?", True, 5],["Compare Services segment revenue and gross margin with Products.", True, 5],["What are Apple's primary risk factors regarding China and supply chain?", True, 5],["What was Google Pixel 9 release date?", True, 5], # Out-of-corpus query to test Tavily web fallback],inputs=[query_input, enable_crag_toggle, top_k_slider],label="Preset Benchmark Queries",)gr.Markdown("---")# Output Tabs for Glass-Box Transparencywith gr.Tabs():with gr.TabItem("💬 Synthesized Answer & Routing Action"):out_answer = gr.Markdown()with gr.TabItem("🧭 Stages 1 & 2: Decomposition & Hybrid Retrieval"):out_stage1_2 = gr.Markdown()with gr.TabItem("⚡ Stages 3 & 4: RRF Fusion & Corrective Decision"):out_stage3_4 = gr.Markdown()with gr.TabItem("🔬 Stage 5: Citations & Latency Breakdown"):out_stage5 = gr.Markdown()submit_btn.click(fn=query_financial_rag,inputs=[query_input, enable_crag_toggle, top_k_slider],outputs=[out_answer, out_stage1_2, out_stage3_4, out_stage5],)if __name__ == "__main__":demo.launch(css=CUSTOM_CSS)
api/main.py+25-22
app.py+172-34