Spaces:
Running on Zero
Running on Zero
Download app.py from nitish12309/Correctra-Rag: direct link, hf CLI and curl.
- Browser
- Download file 9.19 kB
-
https://huggingface.co/spaces/nitish12309/Correctra-Rag/resolve/main/app.py
- Command line
-
hf download hf://spaces/nitish12309/Correctra-Rag/app.py
-
curl -L -o app.py https://huggingface.co/spaces/nitish12309/Correctra-Rag/resolve/main/app.py
9.19 kB
| """ | |
| AURA CRAG — Enterprise Financial Intelligence & Glass-Box Studio | |
| Production ZeroGPU Deployment on Hugging Face Spaces (Gradio 5 SDK) | |
| """ | |
| try: | |
| import spaces | |
| except ImportError: | |
| class spaces: | |
| def GPU(func=None, **kwargs): | |
| if func is None: | |
| def decorator(f): | |
| return f | |
| return decorator | |
| return func | |
| import os | |
| import sys | |
| from pathlib import Path | |
| # Ensure project root is in sys.path | |
| PROJECT_ROOT = Path(__file__).resolve().parent | |
| if str(PROJECT_ROOT) not in sys.path: | |
| sys.path.insert(0, str(PROJECT_ROOT)) | |
| # Pre-download NLTK sentence tokenizer models if missing | |
| import nltk | |
| for pkg in ["punkt", "punkt_tab"]: | |
| try: | |
| nltk.data.find(f"tokenizers/{pkg}") | |
| except LookupError: | |
| nltk.download(pkg, quiet=True) | |
| import gradio as gr | |
| from api.main import init_pipeline_context | |
| from api.service import run_glassbox_crag_pipeline | |
| from api.schemas import QueryRequest | |
| # Lazy-loaded singleton pipeline context | |
| _CONTEXT = None | |
| def get_context(): | |
| global _CONTEXT | |
| if _CONTEXT is None: | |
| _CONTEXT, _ = init_pipeline_context() | |
| return _CONTEXT | |
| def 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 Metrics | |
| action = response.crag_action | |
| action_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 Retrieval | |
| s1 = response.stage_1_query_processing | |
| s2 = response.stage_2_hybrid_retrieval | |
| stage1_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 Evaluation | |
| s3 = response.stage_3_fusion_and_rerank | |
| s4 = response.stage_4_crag_engine | |
| stage3_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 Audit | |
| s5 = response.stage_5_attribution_audit | |
| stage5_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_md | |
| except Exception as e: | |
| import traceback | |
| traceback.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", css=CUSTOM_CSS) 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 Chips | |
| gr.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 Transparency | |
| with 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() | |