File size: 9,192 Bytes
24f7855
030e7a9
 
24f7855
 
16ac7fc
 
 
 
 
 
 
 
 
 
 
43d66e1
24f7855
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
030e7a9
 
 
 
 
 
 
 
 
 
 
 
 
24f7855
f96fcc5
030e7a9
 
 
 
 
16ac7fc
030e7a9
 
 
 
 
 
 
16ac7fc
030e7a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16ac7fc
030e7a9
 
 
 
f96fcc5
18290ab
030e7a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38955e7
7e7820a
030e7a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e7820a
 
030e7a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24f7855
 
38955e7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
"""
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:
        @staticmethod
        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


@spaces.GPU
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()