File size: 7,374 Bytes
d37571a
4eb325f
 
 
d37571a
7f20221
 
4eb325f
7f20221
4eb325f
7f20221
7f13670
7f20221
4d290ee
7f20221
 
 
 
 
 
 
 
 
 
 
4eb325f
7f20221
d37571a
4eb325f
7f20221
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4eb325f
d37571a
7f20221
 
d37571a
7f20221
 
 
 
 
 
 
d37571a
4eb325f
7f20221
 
 
 
 
 
 
 
4eb325f
7f20221
 
 
4eb325f
 
7f20221
4eb325f
7f20221
 
 
 
 
d7086c2
c50dda1
d7086c2
 
7f20221
 
 
 
 
 
 
d7086c2
 
 
4eb325f
7f20221
 
 
 
 
 
 
4eb325f
7f20221
4eb325f
7f20221
 
 
 
 
 
 
 
4eb325f
 
7f20221
 
 
 
 
 
 
 
 
4eb325f
7f20221
 
 
 
4eb325f
 
 
7f20221
4eb325f
7f20221
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40781f0
d7086c2
40781f0
7f20221
40781f0
 
7f20221
40781f0
 
d7086c2
4eb325f
40781f0
 
c50dda1
7f20221
 
 
 
40781f0
 
 
7f20221
 
 
 
 
 
 
 
40781f0
 
e0d703d
4eb325f
 
 
 
d7086c2
40781f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f20221
40781f0
 
 
 
 
 
 
 
 
 
 
d7086c2
40781f0
d7086c2
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
import os
import gradio as gr
import PyPDF2
import torch
from transformers import AutoTokenizer, AutoModel
from qdrant_client import QdrantClient
from qdrant_client.models import VectorParams, Distance, PointStruct
import cohere
from uuid import uuid4

# -------------------- CONFIG --------------------

# Qdrant Cloud config
QDRANT_URL = "https://9ecb3b08-e6fa-482c-a03f-e8cb3313a6c0.sa-east-1-0.aws.cloud.qdrant.io"   # e.g. "https://xxxxxx-xxxxx-xxxxx-xxxx-xxxxxxxxx.us-east.aws.cloud.qdrant.io:6333"
QDRANT_API_KEY = "<your-qdrant-api-key>"
COLLECTION_NAME = "Document"

# Cohere config
COHERE_API_KEY = "<your-cohere-api-key>"

# -------------------- INITIALIZE CLIENTS --------------------

qdrant = QdrantClient(
    url=QDRANT_URL,
    api_key=QDRANT_API_KEY,
)

cohere_client = cohere.Client(COHERE_API_KEY)

# -------------------- LOAD EMBEDDING MODEL --------------------

# Using MiniLM (384-dim)
tokenizer = AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
model = AutoModel.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")

# -------------------- VECTOR COLLECTION SETUP --------------------

def setup_collection():
    """Create collection in Qdrant if it doesn't exist."""
    collections = qdrant.get_collections().collections
    existing_names = [c.name for c in collections]

    if COLLECTION_NAME not in existing_names:
        qdrant.create_collection(
            collection_name=COLLECTION_NAME,
            vectors_config=VectorParams(
                size=384,             # MiniLM-L6-v2 output size
                distance=Distance.COSINE
            )
        )

setup_collection()

# -------------------- UTILITY FUNCTIONS --------------------

def load_pdf(file):
    """Extract raw text from a PDF file."""
    # Gradio's File component passes a tempfile path or file object
    reader = PyPDF2.PdfReader(file)
    text = ""
    for page in reader.pages:
        page_text = page.extract_text()
        if page_text:
            text += page_text
    return text


def get_embeddings(text):
    """Compute mean-pooled embeddings using MiniLM."""
    inputs = tokenizer(
        text,
        return_tensors="pt",
        padding=True,
        truncation=True,
        max_length=512
    )
    with torch.no_grad():
        outputs = model(**inputs)
        # Mean pooling over sequence length
        embeddings = outputs.last_hidden_state.mean(dim=1).squeeze().cpu().numpy()
    return embeddings


def upload_document_chunks(chunks):
    """
    Insert document chunks into Qdrant as points.
    Each chunk becomes one point with a vector and payload.
    """
    points = []

    for chunk in chunks:
        try:
            embedding = get_embeddings(chunk)

            points.append(
                PointStruct(
                    id=str(uuid4()),          # unique ID per chunk
                    vector=embedding.tolist(),
                    payload={"content": chunk}
                )
            )
        except Exception as e:
            print(f"⚠️ Skipped chunk due to error: {e}")

    if points:
        qdrant.upsert(
            collection_name=COLLECTION_NAME,
            points=points
        )


def query_answer(query):
    """Search Qdrant for the most relevant chunks to the query."""
    query_embedding = get_embeddings(query)

    hits = qdrant.search(
        collection_name=COLLECTION_NAME,
        query_vector=query_embedding.tolist(),
        limit=3
    )
    return hits


def generate_response(context, query):
    """Use Cohere to generate a natural language answer based on context."""
    prompt = f"""You are a helpful assistant answering questions based only on the given context.

Context:
{context}

Question: {query}
Answer:"""

    response = cohere_client.generate(
        model="command",
        prompt=prompt,
        max_tokens=200,
        temperature=0.3
    )
    return response.generations[0].text.strip()


def qa_pipeline(pdf_file, query):
    """
    Full QA pipeline:
    1. Read PDF
    2. Chunk text
    3. Store chunks in Qdrant
    4. Search relevant chunks for query
    5. Generate answer via Cohere
    """
    if pdf_file is None:
        return "⚠️ Please upload a PDF first.", ""

    if not query or query.strip() == "":
        return "⚠️ Please enter a question.", ""

    # 1. Extract text
    document_text = load_pdf(pdf_file)

    if not document_text.strip():
        return "⚠️ No extractable text found in the PDF.", ""

    # 2. Simple character-based chunking
    chunk_size = 500
    document_chunks = [
        document_text[i:i + chunk_size]
        for i in range(0, len(document_text), chunk_size)
    ]

    # 3. Upload chunks to Qdrant
    upload_document_chunks(document_chunks)

    # 4. Search relevant chunks
    hits = query_answer(query)

    if not hits:
        return "⚠️ No relevant document segments found.", "I couldn't find an answer based on the document."

    context = " ".join([hit.payload.get("content", "") for hit in hits])

    # 5. Generate answer
    answer = generate_response(context, query)

    return context, answer


# -------------------- GRADIO UI --------------------

with gr.Blocks(theme="compact") as demo:
    gr.Markdown("""
        <div style="text-align: center; font-size: 28px; font-weight: bold; margin-bottom: 20px; color: #2D3748;">
            πŸ“„ Interactive PDF QA Bot (Qdrant + Cohere) πŸ”
        </div>
        <p style="text-align: center; font-size: 16px; color: #4A5568;">
            Upload a PDF document, ask a question, and get answers grounded in the document content.
        </p>
        <hr style="border: 1px solid #CBD5E0; margin: 20px 0;">
    """)

    with gr.Row():
        with gr.Column(scale=1):
            pdf_input = gr.File(label="πŸ“ Upload PDF", file_types=[".pdf"])
            query_input = gr.Textbox(
                label="❓ Ask a Question",
                placeholder="Enter your question here..."
            )
            submit_button = gr.Button("πŸ” Submit")

        with gr.Column(scale=2):
            doc_segments_output = gr.Textbox(
                label="πŸ“œ Retrieved Document Segments",
                lines=10
            )
            answer_output = gr.Textbox(
                label="πŸ’¬ Answer",
                lines=3
            )

    submit_button.click(
        fn=qa_pipeline,
        inputs=[pdf_input, query_input],
        outputs=[doc_segments_output, answer_output]
    )

    gr.Markdown("""
        <style>
            body {
                background-color: #EDF2F7;
            }
            input[type="file"] {
                background-color: #3182CE;
                color: white;
                padding: 8px;
                border-radius: 5px;
            }
            button {
                background-color: #3182CE;
                color: white;
                padding: 10px;
                font-size: 16px;
                border-radius: 5px;
                cursor: pointer;
                border: none;
            }
            button:hover {
                background-color: #2B6CB0;
            }
            textarea {
                border: 2px solid #CBD5E0;
                border-radius: 8px;
                padding: 10px;
                background-color: #FAFAFA;
            }
        </style>
    """)

demo.launch(share=True)