Spaces:
Sleeping
Sleeping
Upload 7 files
Browse files- app.py +97 -69
- chunker.py +31 -0
- embedder.py +19 -0
- loader.py +17 -0
- requirements.txt +7 -0
- retriever.py +28 -0
- vector.py +26 -0
app.py
CHANGED
|
@@ -1,69 +1,97 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
-
from huggingface_hub import InferenceClient
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from huggingface_hub import InferenceClient
|
| 3 |
+
|
| 4 |
+
from loader import Loader
|
| 5 |
+
from chunker import Chunker
|
| 6 |
+
from embedder import Embedder
|
| 7 |
+
from vector import VectorStorage
|
| 8 |
+
from retriever import Retriever
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
client = InferenceClient("meta-llama/Llama-3.2-3B-Instruct")
|
| 12 |
+
|
| 13 |
+
def process_document(file):
|
| 14 |
+
"""Systemic Entry Point: Converts PDF to Searchable Index"""
|
| 15 |
+
if file is None:
|
| 16 |
+
return None, None, "❌ Please upload a PDF first."
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
text = Loader(file.name).load()
|
| 20 |
+
chunks = Chunker().chunker(text)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
embedder = Embedder()
|
| 24 |
+
vectors = embedder.embed(chunks)
|
| 25 |
+
|
| 26 |
+
store = VectorStorage(dimension=len(vectors[0]))
|
| 27 |
+
store.add(vectors, chunks)
|
| 28 |
+
|
| 29 |
+
return store, embedder, "✅ PDF Indexed. Ready to chat!"
|
| 30 |
+
|
| 31 |
+
def rag_chat(message, history, store, embedder):
|
| 32 |
+
"""The Retrieval-Generation Loop"""
|
| 33 |
+
if store is None:
|
| 34 |
+
yield "Please upload and process a PDF on the left first."
|
| 35 |
+
return
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
retriever = Retriever(store, embedder, k=3)
|
| 39 |
+
context_chunks = retriever.retrieve(message)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
if not context_chunks:
|
| 43 |
+
yield "I couldn't find any relevant information in the document to answer that."
|
| 44 |
+
return
|
| 45 |
+
|
| 46 |
+
context_text = "\n\n".join(context_chunks)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
system_prompt = (
|
| 50 |
+
"You are a research assistant which gives answer to the questions of the user from the provided context only. Use the provided context to answer. "
|
| 51 |
+
"If the answer isn't there, say you don't know. Do not hallucinate."
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
messages = [{"role": "system", "content": system_prompt}]
|
| 56 |
+
messages.extend(history)
|
| 57 |
+
messages.append({"role": "user", "content": f"Context:\n{context_text}\n\nQuestion: {message}"})
|
| 58 |
+
|
| 59 |
+
response = ""
|
| 60 |
+
for token in client.chat_completion(messages, max_tokens=512, stream=True):
|
| 61 |
+
token_text = token.choices[0].delta.content
|
| 62 |
+
if token_text:
|
| 63 |
+
response += token_text
|
| 64 |
+
yield response
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
with gr.Blocks(theme=gr.themes.Soft(primary_hue="slate")) as demo:
|
| 68 |
+
|
| 69 |
+
store_state = gr.State()
|
| 70 |
+
embedder_state = gr.State()
|
| 71 |
+
|
| 72 |
+
gr.Markdown("# 📑 DocuMind AI")
|
| 73 |
+
|
| 74 |
+
with gr.Row():
|
| 75 |
+
|
| 76 |
+
with gr.Column(scale=1):
|
| 77 |
+
file_input = gr.File(label="Source Document", file_types=[".pdf"])
|
| 78 |
+
btn = gr.Button("Build Knowledge Base", variant="primary")
|
| 79 |
+
status = gr.Markdown("Status: Waiting for upload...")
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
with gr.Column(scale=3):
|
| 83 |
+
gr.ChatInterface(
|
| 84 |
+
fn=rag_chat,
|
| 85 |
+
additional_inputs=[store_state, embedder_state],
|
| 86 |
+
type="messages",
|
| 87 |
+
fill_height=True
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
btn.click(
|
| 92 |
+
fn=process_document,
|
| 93 |
+
inputs=[file_input],
|
| 94 |
+
outputs=[store_state, embedder_state, status]
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
demo.launch()
|
chunker.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class Chunker:
|
| 2 |
+
def __init__(self, chunk_size=500, overlap=100):
|
| 3 |
+
self.chunk_size = chunk_size
|
| 4 |
+
self.overlap = overlap
|
| 5 |
+
|
| 6 |
+
def chunker(self, text):
|
| 7 |
+
if self.overlap >= self.chunk_size:
|
| 8 |
+
raise ValueError("Overlap must be smaller than chunk size.")
|
| 9 |
+
|
| 10 |
+
chunks = []
|
| 11 |
+
start = 0
|
| 12 |
+
text_size = len(text)
|
| 13 |
+
|
| 14 |
+
while start < text_size:
|
| 15 |
+
end = start + self.chunk_size
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
if end < text_size:
|
| 19 |
+
last_space = text.rfind(' ', start, end)
|
| 20 |
+
if last_space != -1:
|
| 21 |
+
end = last_space
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
chunk = text[start:end].strip()
|
| 25 |
+
if chunk:
|
| 26 |
+
chunks.append(chunk)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
start = end - self.overlap
|
| 30 |
+
|
| 31 |
+
return chunks
|
embedder.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sentence_transformers import SentenceTransformer
|
| 2 |
+
class Embedder:
|
| 3 |
+
"""
|
| 4 |
+
converts the text into numbers
|
| 5 |
+
and places them close meaningfully
|
| 6 |
+
"""
|
| 7 |
+
def __init__(self):
|
| 8 |
+
self.model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def embed(self,chunk):
|
| 12 |
+
vectors = self.model.encode(chunk)
|
| 13 |
+
return vectors
|
| 14 |
+
|
| 15 |
+
def embed_q(self,query):
|
| 16 |
+
q_vector = self.model.encode(query)
|
| 17 |
+
return q_vector
|
| 18 |
+
|
| 19 |
+
|
loader.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import PyPDF2
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class Loader:
|
| 5 |
+
"""
|
| 6 |
+
loads the text from the pdf files
|
| 7 |
+
"""
|
| 8 |
+
def __init__(self,file_path):
|
| 9 |
+
self.file = file_path
|
| 10 |
+
|
| 11 |
+
def load(self):
|
| 12 |
+
reader = PyPDF2.PdfReader(self.file)
|
| 13 |
+
text = ""
|
| 14 |
+
|
| 15 |
+
for page in reader.pages:
|
| 16 |
+
text = text + page.extract_text()
|
| 17 |
+
return text
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
huggingface_hub
|
| 3 |
+
sentence-transformers
|
| 4 |
+
faiss-cpu
|
| 5 |
+
numpy
|
| 6 |
+
PyPDF2>=3.0.0
|
| 7 |
+
|
retriever.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class Retriever:
|
| 2 |
+
def __init__(self, vector_store, embedder, k=5):
|
| 3 |
+
self.vector_store = vector_store
|
| 4 |
+
self.embedder = embedder
|
| 5 |
+
self.k = k
|
| 6 |
+
|
| 7 |
+
def retrieve(self, query):
|
| 8 |
+
|
| 9 |
+
vquery = self.embedder.embed_q(query)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
scores, indices = self.vector_store.search(vquery, self.k)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
if scores[0] < 0.5:
|
| 16 |
+
print(f"Evidence too low: {scores[0]}")
|
| 17 |
+
return []
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
results = [
|
| 21 |
+
self.vector_store.chunks[i]
|
| 22 |
+
for i in indices if i != -1
|
| 23 |
+
]
|
| 24 |
+
return results
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
|
vector.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import faiss
|
| 2 |
+
import numpy as np
|
| 3 |
+
|
| 4 |
+
class VectorStorage:
|
| 5 |
+
def __init__(self, dimension=384):
|
| 6 |
+
|
| 7 |
+
self.index = faiss.IndexFlatIP(dimension)
|
| 8 |
+
self.chunks = []
|
| 9 |
+
|
| 10 |
+
def add(self, vectors, chunks):
|
| 11 |
+
|
| 12 |
+
v_array = np.array(vectors).astype('float32')
|
| 13 |
+
|
| 14 |
+
faiss.normalize_L2(v_array)
|
| 15 |
+
|
| 16 |
+
self.index.add(v_array)
|
| 17 |
+
self.chunks.extend(chunks)
|
| 18 |
+
|
| 19 |
+
def search(self, query_vector, k=5):
|
| 20 |
+
|
| 21 |
+
q_array = np.array([query_vector]).astype('float32')
|
| 22 |
+
faiss.normalize_L2(q_array)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
scores, indices = self.index.search(q_array, k)
|
| 26 |
+
return scores[0], indices[0]
|