File size: 12,445 Bytes
2898f47
 
 
 
 
 
992675e
 
 
2898f47
080adfc
5c44ad5
080adfc
5c44ad5
080adfc
81f92b6
 
 
 
 
080adfc
5c44ad5
080adfc
5c44ad5
080adfc
2898f47
 
 
 
 
 
 
 
992675e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2898f47
81f92b6
 
8a319d5
81f92b6
 
8a319d5
 
 
 
 
 
 
 
 
 
 
 
 
 
81f92b6
 
 
 
8a319d5
2898f47
 
8a319d5
81f92b6
 
 
 
 
080adfc
81f92b6
 
 
 
 
080adfc
 
 
 
 
5c44ad5
080adfc
 
5c44ad5
080adfc
 
 
 
 
 
 
 
 
5c44ad5
 
 
 
080adfc
5c44ad5
 
 
080adfc
 
 
 
 
 
 
 
81f92b6
 
080adfc
81f92b6
 
080adfc
 
 
 
 
 
 
 
81f92b6
 
080adfc
 
 
 
81f92b6
080adfc
2898f47
 
 
 
 
 
 
 
 
 
 
 
 
992675e
2898f47
 
 
 
 
 
81f92b6
 
2898f47
 
 
8a319d5
080adfc
8a319d5
 
2898f47
 
8a319d5
81f92b6
 
080adfc
 
 
 
81f92b6
080adfc
81f92b6
080adfc
81f92b6
2898f47
 
 
81f92b6
 
 
080adfc
 
81f92b6
2898f47
992675e
 
2898f47
81f92b6
2898f47
 
 
992675e
2898f47
 
992675e
 
 
 
 
 
 
2898f47
992675e
 
 
2898f47
992675e
2898f47
 
 
 
 
 
992675e
2898f47
 
 
992675e
2898f47
 
 
 
 
 
992675e
 
2898f47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a319d5
 
2898f47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a319d5
 
 
 
 
 
 
 
 
2898f47
 
 
 
 
8a319d5
2898f47
 
992675e
2898f47
 
992675e
2898f47
 
 
 
 
 
 
 
 
 
81f92b6
2898f47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
992675e
 
2898f47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
import gradio as gr
import PyPDF2
import io
from huggingface_hub import InferenceClient
import os
import sys
import math
import re
from collections import Counter

try:
    from PIL import Image
except Exception:  # pragma: no cover - optional runtime fallback
    Image = None

try:
    import fitz  # PyMuPDF
except Exception:  # pragma: no cover - optional runtime fallback
    fitz = None

try:
    import pytesseract
except Exception:  # pragma: no cover - optional runtime fallback
    pytesseract = None

sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from shared.components import create_method_panel, create_premium_hero

client = InferenceClient(token=os.getenv("HF_TOKEN"))

# Global storage
chunks = []
sources = []
chunk_vectors = []

def tokenize(text):
    """Small lexical tokenizer used for transparent CPU-friendly retrieval."""
    return re.findall(r"[a-zA-Z0-9_]+", text.lower())

def vectorize(text):
    return Counter(tokenize(text))

def cosine_similarity(left, right):
    if not left or not right:
        return 0.0
    overlap = set(left).intersection(right)
    dot = sum(left[token] * right[token] for token in overlap)
    left_norm = math.sqrt(sum(value * value for value in left.values()))
    right_norm = math.sqrt(sum(value * value for value in right.values()))
    return dot / (left_norm * right_norm) if left_norm and right_norm else 0.0

def read_uploaded_pdf(pdf_file):
    """Normalize Gradio upload variants into bytes plus a display name."""
    if hasattr(pdf_file, "read"):
        if hasattr(pdf_file, "seek"):
            pdf_file.seek(0)
        payload = pdf_file.read()
        source_name = getattr(pdf_file, "name", "uploaded.pdf")
    elif isinstance(pdf_file, (str, os.PathLike)):
        source_name = os.path.basename(str(pdf_file))
        with open(pdf_file, "rb") as handle:
            payload = handle.read()
    elif hasattr(pdf_file, "path"):
        source_name = os.path.basename(str(pdf_file.path))
        with open(pdf_file.path, "rb") as handle:
            payload = handle.read()
    else:
        payload = bytes(pdf_file)
        source_name = "uploaded.pdf"

    return payload, os.path.basename(str(source_name))

def extract_with_pypdf(payload):
    """Extract embedded text with PyPDF2."""
    pdf_reader = PyPDF2.PdfReader(io.BytesIO(payload))
    text = ""
    for page in pdf_reader.pages:
        text += (page.extract_text() or "") + "\n"
    return text

def extract_with_pymupdf(payload):
    """Second-pass extraction for PDFs PyPDF2 parses poorly."""
    if fitz is None:
        return "", 0

    text = ""
    with fitz.open(stream=payload, filetype="pdf") as document:
        for page in document:
            text += page.get_text("text") + "\n"
        page_count = document.page_count
    return text, page_count

def extract_with_ocr(payload, max_pages=12):
    """Render PDF pages and OCR them when no embedded text exists."""
    if fitz is None or Image is None:
        return "", 0, "OCR dependencies are not available in this runtime."

    if pytesseract is None:
        return "", 0, "OCR engine is not available in this runtime."

    ocr_text = []
    pages_processed = 0
    with fitz.open(stream=payload, filetype="pdf") as document:
        page_limit = min(document.page_count, max_pages)
        for page_index in range(page_limit):
            page = document.load_page(page_index)
            pixmap = page.get_pixmap(matrix=fitz.Matrix(2, 2), alpha=False)
            image = Image.frombytes(
                "RGB",
                (pixmap.width, pixmap.height),
                pixmap.samples,
            )
            page_text = pytesseract.image_to_string(image, config="--psm 6").strip()
            if page_text:
                ocr_text.append(page_text)
            pages_processed += 1

        if document.page_count > max_pages:
            ocr_text.append(
                f"\n[OCR note: processed first {max_pages} of {document.page_count} pages to keep the Space responsive.]"
            )

    return "\n".join(ocr_text), pages_processed, ""

def extract_text_from_pdf(pdf_file):
    """Extract text from a PDF upload, using OCR when no text layer exists."""
    payload, source_name = read_uploaded_pdf(pdf_file)
    text = extract_with_pypdf(payload).strip()
    method = "PyPDF2 text layer"
    page_count = 0
    warning = ""

    if len(text.split()) < 5:
        text, page_count = extract_with_pymupdf(payload)
        text = text.strip()
        method = "PyMuPDF text layer"

    if len(text.split()) < 5:
        max_pages = int(os.getenv("OCR_MAX_PAGES", "12"))
        text, pages_processed, warning = extract_with_ocr(payload, max_pages=max_pages)
        text = text.strip()
        method = f"OCR over rendered PDF pages ({pages_processed} page{'s' if pages_processed != 1 else ''})"

    return text, source_name, method, warning, page_count

def chunk_text(text, chunk_size=500, overlap=50):
    """Split text into overlapping chunks."""
    words = text.split()
    chunks = []
    for i in range(0, len(words), chunk_size - overlap):
        chunk = ' '.join(words[i:i + chunk_size])
        if len(chunk.strip()) > 0:
            chunks.append(chunk)
    return chunks

def process_pdfs(pdf_files, progress=gr.Progress()):
    """Process uploaded PDFs and create vector store."""
    global chunks, sources, chunk_vectors

    if not pdf_files:
        return "❌ No PDFs uploaded"

    chunks = []
    sources = []
    chunk_vectors = []
    extraction_notes = []

    progress(0, desc="Extracting text from PDFs...")
    for i, pdf_file in enumerate(pdf_files):
        try:
            text, source_name, method, warning, page_count = extract_text_from_pdf(pdf_file)
        except Exception as exc:
            return f"❌ Could not read PDF: {exc}"
        pdf_chunks = chunk_text(text)
        chunks.extend(pdf_chunks)
        sources.extend([source_name] * len(pdf_chunks))
        word_count = len(text.split())
        if word_count:
            note = f"- {source_name}: {word_count:,} words extracted via {method}"
            if warning:
                note += f" ({warning})"
            extraction_notes.append(note)
        else:
            detail = warning or "no text layer or OCR-readable text was found"
            extraction_notes.append(
                f"- {source_name}: {detail}."
            )
        progress((i + 1) / len(pdf_files), desc=f"Processed {i+1}/{len(pdf_files)} PDFs")

    if not chunks:
        return (
            "❌ No text extracted from PDFs\n\n"
            + "\n".join(extraction_notes)
            + "\n\nThis Space now tries text extraction and OCR automatically. If this still fails, the PDF may contain "
            "low-resolution images, protected content, or pages whose text is too blurred for OCR."
        )

    progress(0.7, desc="Building lexical retrieval index...")
    chunk_vectors = [vectorize(chunk) for chunk in chunks]

    return f"βœ… Processed {len(pdf_files)} PDFs into {len(chunks)} chunks\n\n" + "\n".join(extraction_notes)

def retrieve_chunks(query, top_k=3):
    """Retrieve most relevant chunks for query."""
    if not chunk_vectors or len(chunks) == 0:
        return [], []

    query_vector = vectorize(query)
    scored = [
        (idx, cosine_similarity(query_vector, chunk_vector))
        for idx, chunk_vector in enumerate(chunk_vectors)
    ]
    scored.sort(key=lambda item: item[1], reverse=True)
    top = scored[:top_k]

    retrieved_chunks = [chunks[i] for i, _ in top]
    retrieved_sources = [sources[i] for i, _ in top]
    retrieved_scores = [score for _, score in top]

    return retrieved_chunks, retrieved_sources, retrieved_scores

def answer_question(question, progress=gr.Progress()):
    """Answer question using RAG pipeline."""
    if not question:
        return "Please enter a question", "", ""

    if not chunk_vectors:
        return "Please upload and process PDFs first", "", ""

    progress(0, desc="πŸ” Step 1: Retrieving relevant chunks...")
    retrieved_chunks, retrieved_sources, scores = retrieve_chunks(question, top_k=3)

    if not retrieved_chunks:
        return "No relevant information found", "", ""

    # Format retrieved chunks for display
    chunks_display = ""
    for i, (chunk, source, score) in enumerate(zip(retrieved_chunks, retrieved_sources, scores)):
        chunks_display += f"**Chunk {i+1}** (from {source}, lexical similarity: {score:.3f})\n"
        chunks_display += f"{chunk[:300]}...\n\n"

    progress(0.5, desc="πŸ€– Step 2: Generating answer...")

    # Create prompt for generation
    context = "\n\n".join(retrieved_chunks)
    prompt = f"""Based on the following context, answer the question. If the answer is not in the context, say so.

Context:
{context}

Question: {question}

Answer:"""

    try:
        if not os.getenv("HF_TOKEN"):
            raise RuntimeError("HF_TOKEN is not configured; using local extractive fallback.")
        response = ""
        for token in client.text_generation(
            prompt,
            model="meta-llama/Llama-3.2-3B-Instruct",
            max_new_tokens=300,
            stream=True
        ):
            response += token

        progress(1.0, desc="βœ… Done!")

        # Format citations
        citations = "\n\n**Sources:**\n"
        for i, source in enumerate(set(retrieved_sources)):
            citations += f"- {source}\n"

        return response.strip(), chunks_display, citations

    except Exception as e:
        fallback = (
            "No hosted generation token is configured, so this Space is returning the most relevant retrieved evidence instead.\n\n"
            f"**Question:** {question}\n\n"
            f"**Best evidence:** {retrieved_chunks[0][:900]}..."
        )
        citations = "\n\n**Sources:**\n"
        for source in sorted(set(retrieved_sources)):
            citations += f"- {source}\n"
        return fallback, chunks_display, citations

# Gradio Interface
with gr.Blocks(title="RAG from Scratch", theme=gr.themes.Soft()) as demo:
    create_premium_hero(
        "RAG from Scratch",
        "A transparent Retrieval-Augmented Generation lab: chunk PDFs, retrieve passages, and answer with cited context.",
        "πŸ“š",
        badge="Retrieval Systems",
        highlights=["Lexical retrieval", "Chunk inspection", "HF Inference"],
    )
    create_method_panel({
        "Pipeline": "PDF text extraction β†’ overlapping chunks β†’ lexical retrieval β†’ grounded generation.",
        "What it proves": "You can build and explain the moving parts behind production RAG systems.",
        "Community value": "A teaching Space for debugging retrieval quality before adding orchestration complexity.",
    })

    with gr.Row():
        with gr.Column(scale=1):
            gr.Markdown("### Step 1: Upload PDFs")
            pdf_input = gr.File(
                file_count="multiple",
                file_types=[".pdf"],
                type="filepath",
                label="Upload PDF files"
            )
            process_btn = gr.Button("Process PDFs", variant="primary")
            status = gr.Textbox(label="Status", interactive=False)

            gr.Markdown("### Step 2: Ask Questions")
            question_input = gr.Textbox(
                label="Your Question",
                placeholder="What is this document about?",
                lines=2
            )
            ask_btn = gr.Button("Get Answer", variant="primary")

        with gr.Column(scale=2):
            gr.Markdown("### Answer")
            answer_output = gr.Textbox(label="Generated Answer", lines=6)
            citations_output = gr.Markdown(label="Citations")

            with gr.Accordion("πŸ” Retrieved Chunks (View Pipeline)", open=False):
                chunks_output = gr.Markdown(label="Chunks Used")

    gr.Markdown("""
    ### πŸ’‘ How it works:
    - **Indexing**: Convert chunks into transparent lexical vectors
    - **Retrieval**: Find chunks with the strongest term overlap
    - **Generation**: LLM uses retrieved chunks to answer

    This is the foundation of most modern Q&A systems!
    """)

    process_btn.click(
        process_pdfs,
        inputs=[pdf_input],
        outputs=[status]
    )

    ask_btn.click(
        answer_question,
        inputs=[question_input],
        outputs=[answer_output, chunks_output, citations_output]
    )

if __name__ == "__main__":
    demo.launch()