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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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
"""Streamlit Web Application for Production Document Question Answering (DQA).

Ready for Deployment on Hugging Face Spaces.
Features:
- Auto-loads sample documents for instant one-click demonstration.
- Upload & Ingest PDF (layout-aware, OCR fallback), DOCX, TXT.
- Hybrid Retrieval: BAAI/bge-small-en-v1.5 + BM25Okapi + Reciprocal Rank Fusion (RRF).
- Cross-Encoder Reranking (ms-marco-MiniLM-L-6-v2).
- Multi-Model Generation:
    1. Hugging Face Serverless Inference API (Qwen-2.5, Llama-3.2, Mistral)
    2. High-Precision Offline Grounding Engine (0-cost, 100% cited)
    3. OpenAI / Groq / DeepSeek API
- Strict Grounding with Evidence Quotes & [Page X, Section Y] Citations.
- Second-Pass Verification Audit with Faithfulness scoring.
- Quick-question prompt chips for instant testing.
"""

import os
import sys
import tempfile
import time
from typing import List

import streamlit as st

# Local modules
from config import DQAConfig, default_config
from ingest import DocumentIngestionPipeline, DocumentChunk
from retrieve import HybridRetriever
from generate import Generator, OpenAILLMClient, HuggingFaceInferenceClient
from verify import AnswerVerifier


st.set_page_config(
    page_title="Document QA System - Production RAG",
    page_icon="πŸ“„",
    layout="wide",
    initial_sidebar_state="expanded"
)

# Custom CSS for modern styling
st.markdown("""
<style>
    .main-header {
        font-size: 2.2rem;
        font-weight: 700;
        color: #1E3A8A;
        margin-bottom: 0.2rem;
    }
    .sub-header {
        font-size: 1.05rem;
        color: #4B5563;
        margin-bottom: 1.2rem;
    }
    .citation-box {
        background-color: #F8FAFC;
        border-left: 4px solid #3B82F6;
        padding: 0.8rem 1rem;
        border-radius: 4px;
        margin-top: 0.6rem;
        font-size: 0.9rem;
    }
    .verified-pill {
        display: inline-block;
        padding: 3px 10px;
        border-radius: 12px;
        font-size: 0.82rem;
        font-weight: 600;
        background-color: #DEF7EC;
        color: #03543F;
    }
    .unverified-pill {
        display: inline-block;
        padding: 3px 10px;
        border-radius: 12px;
        font-size: 0.82rem;
        font-weight: 600;
        background-color: #FDE8E8;
        color: #9B1C1C;
    }
    .chip-btn {
        margin: 2px;
    }
</style>
""", unsafe_allow_html=True)


@st.cache_resource(show_spinner="Loading Neural Embedder & Cross-Encoder Models...")
def load_core_components(embedding_model_name: str):
    """Initializes and caches the heavy neural models."""
    retriever = HybridRetriever(
        embedding_model=embedding_model_name,
        cross_encoder_model=default_config.cross_encoder_model_name,
        rrf_k=default_config.rrf_k
    )
    verifier = AnswerVerifier(
        cross_encoder=retriever.reranker,
        threshold=default_config.verification_threshold,
        flag_unsupported=default_config.flag_unsupported_claims
    )
    pipeline = DocumentIngestionPipeline(
        chunk_size=default_config.chunk_size_tokens,
        chunk_overlap=default_config.chunk_overlap_tokens,
        ocr_fallback=default_config.ocr_fallback_enabled,
        ocr_min_chars=default_config.ocr_min_chars_per_page
    )
    return retriever, verifier, pipeline


# Initialize session state variables
if "embedding_model" not in st.session_state:
    st.session_state.embedding_model = default_config.embedding_model_name

if "retriever" not in st.session_state:
    retriever, verifier, pipeline = load_core_components(st.session_state.embedding_model)
    st.session_state.retriever = retriever
    st.session_state.verifier = verifier
    st.session_state.pipeline = pipeline
    st.session_state.generator = Generator(verifier=verifier)
    st.session_state.messages = []
    st.session_state.indexed_files = []
    st.session_state.total_chunks = 0
    st.session_state.all_chunks = []

    # Auto-load pre-built sample documents on first launch for Hugging Face Spaces visitors
    sample_paths = [
        "data/sample_financial_report.pdf",
        "data/sample_cloud_architecture.docx",
        "data/sample_security_policy.txt"
    ]
    parsed_list = []
    for p in sample_paths:
        if os.path.exists(p):
            parsed = pipeline.ingest_file(p)
            parsed_list.append(parsed)
            st.session_state.indexed_files.append(parsed.file_name)

    if parsed_list:
        retriever.index_documents(parsed_list)
        st.session_state.total_chunks = len(retriever.chunks)
        st.session_state.all_chunks = retriever.chunks

retriever = st.session_state.retriever
verifier = st.session_state.verifier
pipeline = st.session_state.pipeline
generator = st.session_state.generator


# ---------------- SIDEBAR: Controls & Configuration ----------------
with st.sidebar:
    st.header("βš™οΈ Settings & Ingestion")

    # Embedding Model selection
    st.subheader("1. Embedding Model")
    selected_embedder = st.selectbox(
        "Dense Embedding Model",
        options=["BAAI/bge-small-en-v1.5", "sentence-transformers/all-MiniLM-L6-v2"],
        index=0 if st.session_state.embedding_model == "BAAI/bge-small-en-v1.5" else 1,
        help="bge-small-en-v1.5 is the top MTEB benchmark retriever. all-MiniLM-L6-v2 is ultra fast."
    )
    if selected_embedder != st.session_state.embedding_model:
        st.session_state.embedding_model = selected_embedder
        with st.spinner("Switching embedding model..."):
            retriever, verifier, pipeline = load_core_components(selected_embedder)
            st.session_state.retriever = retriever
            st.session_state.verifier = verifier
            st.session_state.pipeline = pipeline
            generator.verifier = verifier
            if st.session_state.all_chunks:
                retriever.index_documents(st.session_state.all_chunks)
            st.rerun()

    # Document Upload Section
    st.divider()
    st.subheader("2. Upload & Ingest Documents")
    uploaded_files = st.file_uploader(
        "Upload PDF (with OCR), DOCX, or TXT",
        type=["pdf", "docx", "txt", "md"],
        accept_multiple_files=True
    )

    col1, col2 = st.columns(2)
    with col1:
        load_sample = st.button("πŸ“‚ Reload Samples", use_container_width=True)
    with col2:
        reindex = st.button("πŸ”„ Clear Index", use_container_width=True)

    if reindex:
        retriever.index_documents([])
        st.session_state.indexed_files = []
        st.session_state.total_chunks = 0
        st.session_state.all_chunks = []
        st.session_state.messages = []
        generator.memory.clear()
        st.success("Vector index & conversation memory cleared!")
        st.rerun()

    if load_sample:
        sample_paths = [
            "data/sample_financial_report.pdf",
            "data/sample_cloud_architecture.docx",
            "data/sample_security_policy.txt"
        ]
        parsed_list = []
        st.session_state.indexed_files = []
        for p in sample_paths:
            if os.path.exists(p):
                parsed = pipeline.ingest_file(p)
                parsed_list.append(parsed)
                st.session_state.indexed_files.append(parsed.file_name)

        if parsed_list:
            retriever.index_documents(parsed_list)
            st.session_state.total_chunks = len(retriever.chunks)
            st.session_state.all_chunks = retriever.chunks
            st.success(f"Indexed {len(parsed_list)} sample documents ({st.session_state.total_chunks} chunks)!")
            st.rerun()

    # Process user uploaded files
    if uploaded_files:
        if st.button("πŸš€ Process Uploaded Files", type="primary", use_container_width=True):
            new_parsed = []
            with st.spinner("Extracting layout, formatting tables & generating embeddings..."):
                for uploaded_file in uploaded_files:
                    ext = os.path.splitext(uploaded_file.name)[1]
                    with tempfile.NamedTemporaryFile(delete=False, suffix=ext) as tmp_file:
                        tmp_file.write(uploaded_file.read())
                        tmp_path = tmp_file.name

                    try:
                        parsed = pipeline.ingest_file(tmp_path)
                        parsed.file_name = uploaded_file.name
                        for c in parsed.chunks:
                            c.file_name = uploaded_file.name
                        new_parsed.append(parsed)
                        if uploaded_file.name not in st.session_state.indexed_files:
                            st.session_state.indexed_files.append(uploaded_file.name)
                    finally:
                        if os.path.exists(tmp_path):
                            os.remove(tmp_path)

                if new_parsed:
                    existing_chunks = list(retriever.chunks)
                    combined = existing_chunks + [c for p in new_parsed for c in p.chunks]
                    retriever.index_documents(combined)
                    st.session_state.total_chunks = len(retriever.chunks)
                    st.session_state.all_chunks = retriever.chunks
                    st.success(f"Successfully indexed {len(new_parsed)} document(s)!")
                    st.rerun()

    # Index Status Summary
    st.divider()
    st.markdown("**Index Status:**")
    st.write(f"β€’ **Documents Indexed:** `{len(st.session_state.indexed_files)}`")
    st.write(f"β€’ **Total Chunks:** `{st.session_state.total_chunks}`")
    if st.session_state.indexed_files:
        with st.expander("πŸ“ View Loaded Documents"):
            for fname in st.session_state.indexed_files:
                st.caption(f"βœ“ {fname}")

    # Chunk Inspector
    if st.session_state.all_chunks:
        with st.expander("πŸ” Inspect Chunks & Metadata"):
            chunk_num = st.selectbox(
                "Select Chunk",
                range(len(st.session_state.all_chunks)),
                format_func=lambda i: f"Chunk {i+1}: {st.session_state.all_chunks[i].file_name} (p. {st.session_state.all_chunks[i].page_number})"
            )
            selected = st.session_state.all_chunks[chunk_num]
            st.markdown(f"**Doc:** `{selected.file_name}` | **Page {selected.page_number}**")
            st.markdown(f"**Section:** `{selected.section_title}` | Table: `{selected.metadata.get('is_table', False)}`")
            st.text_area("Chunk Content", selected.text, height=120)

    # Retrieval Settings
    st.divider()
    st.subheader("3. Retrieval & Reranker")
    retrieval_mode = st.selectbox(
        "Search Pipeline",
        options=["hybrid_rerank", "hybrid_no_rerank", "dense_only", "bm25_only"],
        format_func=lambda m: {
            "hybrid_rerank": "🌟 Hybrid (Dense+BM25) + Cross-Encoder Rerank",
            "hybrid_no_rerank": "⚑ Hybrid Search (No Reranker)",
            "dense_only": "🎯 Dense Vector Only (FAISS)",
            "bm25_only": "πŸ”€ BM25 Lexical Only"
        }[m]
    )

    rerank_top_k = st.slider("Top-K Context Chunks", min_value=1, max_value=10, value=5)
    enable_verification = st.checkbox("Enable Second-Pass Verification", value=True)
    enable_decomposition = st.checkbox("Decompose Complex Queries", value=True)

    # LLM Generator Backend
    st.divider()
    st.subheader("4. LLM Generation Engine")
    engine_choice = st.radio(
        "Generation Backend",
        options=["Offline Grounding Engine", "Hugging Face Inference API", "OpenAI / Groq API"],
        index=0,
        help="Offline engine runs locally with 0 cost and 100% cited answers. HF and OpenAI support conversational LLMs."
    )

    if engine_choice == "Hugging Face Inference API":
        hf_token_input = st.text_input(
            "Hugging Face Token (Optional)",
            type="password",
            value=os.getenv("HF_TOKEN", ""),
            help="Your HF Token for higher rate limits on the Serverless Inference API."
        )
        hf_model_choice = st.selectbox(
            "Hugging Face Model",
            options=[
                "Qwen/Qwen2.5-7B-Instruct",
                "meta-llama/Llama-3.2-3B-Instruct",
                "mistralai/Mistral-7B-Instruct-v0.3"
            ]
        )
        generator.llm_client = HuggingFaceInferenceClient(
            model=hf_model_choice,
            token=hf_token_input or None
        )
    elif engine_choice == "OpenAI / Groq API":
        api_key_input = st.text_input(
            "API Key",
            type="password",
            value=os.getenv("OPENAI_API_KEY", "")
        )
        base_url_input = st.text_input(
            "Base URL (Optional, for Groq/Ollama)",
            value=os.getenv("OPENAI_BASE_URL", "")
        )
        if api_key_input:
            generator.llm_client = OpenAILLMClient(
                api_key=api_key_input,
                base_url=base_url_input or None
            )
        else:
            generator.llm_client = None
    else:
        # High-precision offline grounding engine
        generator.llm_client = None


# ---------------- MAIN CHAT INTERFACE ----------------
st.markdown('<div class="main-header">πŸ“„ Production Document Question Answering</div>', unsafe_allow_html=True)
st.markdown(
    '<div class="sub-header">Layout-aware Ingestion β€’ Hybrid Retrieval (bge-small-en + BM25) β€’ '
    'Cross-Encoder Reranking β€’ Strict Evidence Grounding β€’ Claim-Level Verification</div>',
    unsafe_allow_html=True
)

# Demo Prompt Chips
st.markdown("**πŸ’‘ Try sample questions on the pre-loaded documents:**")
chip_cols = st.columns(4)
sample_prompts = [
    "What was the total revenue and net profit margin in Q3?",
    "What are the target p99 latency and platform availability SLOs?",
    "What hardware MFA and encryption standards are required?",
    "Does the system run on Oracle Cloud Infrastructure in Frankfurt?"
]

selected_prompt = None
with chip_cols[0]:
    if st.button("πŸ“Š Q3 Revenue & Margin", use_container_width=True):
        selected_prompt = sample_prompts[0]
with chip_cols[1]:
    if st.button("⚑ Latency & SLA Targets", use_container_width=True):
        selected_prompt = sample_prompts[1]
with chip_cols[2]:
    if st.button("πŸ”’ MFA & TLS Standards", use_container_width=True):
        selected_prompt = sample_prompts[2]
with chip_cols[3]:
    if st.button("🚫 Oracle Cloud (Negative Test)", use_container_width=True):
        selected_prompt = sample_prompts[3]

# Display Conversation History
for turn in st.session_state.messages:
    with st.chat_message(turn["role"]):
        st.markdown(turn["content"])

        # Display Citations if available
        if turn.get("citations"):
            with st.expander(f"πŸ“š View {len(turn['citations'])} Source Citations & Evidence Quotes"):
                for idx, c in enumerate(turn["citations"], 1):
                    score_info = f"(Score: `{c.get('score', 0.0):.3f}`)" if 'score' in c else ""
                    st.markdown(
                        f"**Citation {idx}:** `{c['file_name']}` | **Page {c['page']}**, Section *\"{c['section']}\"* {score_info}"
                    )
                    st.markdown(f"> *\"{c['text']}\"*")
                    st.divider()

        # Display Verification details if available
        if turn.get("verification"):
            ver = turn["verification"]
            faithfulness = ver.get("faithfulness_score", 1.0)
            status_class = "verified-pill" if faithfulness >= 0.8 else "unverified-pill"
            status_label = f"Faithfulness: {int(faithfulness * 100)}%"
            
            with st.expander(f"πŸ›‘οΈ Second-Pass Verification Audit ({status_label})"):
                st.markdown(f"Status: <span class='{status_class}'>{status_label}</span>", unsafe_allow_html=True)
                st.markdown(f"β€’ **Supported Claims:** {len(ver.get('supported_claims', []))}")
                for sc in ver.get("supported_claims", []):
                    st.caption(f"βœ“ {sc}")
                if ver.get("unsupported_claims"):
                    st.markdown(f"β€’ **⚠️ Flagged / Unsupported Claims:** {len(ver.get('unsupported_claims', []))}")
                    for uc in ver.get("unsupported_claims", []):
                        st.caption(f"⚠️ {uc}")


# User Input (via chat input or prompt chip)
chat_input_val = st.chat_input("Ask a question grounded strictly in your uploaded documents...")
active_prompt = selected_prompt or chat_input_val

if active_prompt:
    st.session_state.messages.append({"role": "user", "content": active_prompt})
    generator.memory.add_user_message(active_prompt)

    with st.chat_message("user"):
        st.markdown(active_prompt)

    with st.chat_message("assistant"):
        with st.spinner("Retrieving evidence, reranking passages & generating grounded response..."):
            conv_history = generator.memory.get_messages_for_prompt()[:-1]
            ret_result = retriever.retrieve(
                query=active_prompt,
                initial_top_k=20,
                rerank_top_k=rerank_top_k,
                mode=retrieval_mode,
                conversation_history=conv_history,
                decompose=enable_decomposition
            )

            retrieved_chunks = ret_result["chunks"]
            scores = ret_result["scores"]
            rewritten_query = ret_result.get("rewritten_query", active_prompt)
            sub_queries = ret_result.get("sub_queries", [active_prompt])

            if rewritten_query != active_prompt or len(sub_queries) > 1:
                st.caption(f"πŸ”„ **Query Reformulation:** `{rewritten_query}` | **Sub-queries:** {sub_queries}")

            # Generate and verify answer
            answer, verification = generator.generate_answer(
                query=rewritten_query,
                context_chunks=retrieved_chunks,
                verify=enable_verification
            )

            citations_data = []
            for c, s in zip(retrieved_chunks, scores):
                citations_data.append({
                    "file_name": c.file_name,
                    "page": c.page_number,
                    "section": c.section_title,
                    "text": c.text,
                    "score": s
                })

            # Stream output
            output_placeholder = st.empty()
            full_text = ""
            for word in answer.split(" "):
                full_text += word + " "
                output_placeholder.markdown(full_text + "β–Œ")
                time.sleep(0.012)
            output_placeholder.markdown(full_text.strip())

            # Citations expander
            if citations_data and "not found in the document" not in full_text.lower():
                with st.expander(f"πŸ“š View {len(citations_data)} Source Citations & Evidence Quotes"):
                    for idx, c in enumerate(citations_data, 1):
                        st.markdown(
                            f"**Citation {idx}:** `{c['file_name']}` | **Page {c['page']}**, Section *\"{c['section']}\"* (Score: `{c['score']:.3f}`)"
                        )
                        st.markdown(f"> *\"{c['text']}\"*")
                        st.divider()

            # Verification expander
            if verification and "not found in the document" not in full_text.lower():
                faithfulness = verification.faithfulness_score
                status_class = "verified-pill" if faithfulness >= 0.8 else "unverified-pill"
                status_label = f"Faithfulness: {int(faithfulness * 100)}%"

                with st.expander(f"πŸ›‘οΈ Second-Pass Verification Audit ({status_label})"):
                    st.markdown(f"Status: <span class='{status_class}'>{status_label}</span>", unsafe_allow_html=True)
                    st.markdown(f"β€’ **Supported Claims ({len(verification.supported_claims)}):**")
                    for sc in verification.supported_claims:
                        st.caption(f"βœ“ {sc}")
                    if verification.unsupported_claims:
                        st.markdown(f"β€’ **⚠️ Flagged / Unsupported Claims ({len(verification.unsupported_claims)}):**")
                        for uc in verification.unsupported_claims:
                            st.caption(f"⚠️ {uc}")

            generator.memory.add_assistant_message(
                message=full_text.strip(),
                citations=citations_data,
                verification=verification
            )
            st.session_state.messages.append({
                "role": "assistant",
                "content": full_text.strip(),
                "citations": citations_data,
                "verification": verification.to_dict() if verification else None
            })