Ishva24's picture
Upload folder using huggingface_hub
3e3c91e verified
Raw History Blame Contribute Delete
13.4 kB
import os
import gradio as gr
import numpy as np
import torch
from transformers import AutoModel, AutoTokenizer
from rank_bm25 import BM25Okapi
import faiss
from pypdf import PdfReader
import cohere
import openai
# ==========================================
# 1. Embeddings & Ingestion Core
# ==========================================
class JinaEmbedder:
"""Wraps jinaai/jina-embeddings-v2-base-en (8192 token window)."""
def __init__(self, model_name="jinaai/jina-embeddings-v2-base-en", max_seq_len=2048):
print(f"Loading embedding model: {model_name}...")
self.tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
self.model = AutoModel.from_pretrained(model_name, trust_remote_code=True)
self.model.eval()
self.max_seq_len = max_seq_len
def _mean_pool(self, token_embeddings, attention_mask):
mask = attention_mask[:, :, np.newaxis].astype(float)
summed = (token_embeddings * mask).sum(axis=1)
counts = mask.sum(axis=1).clip(min=1e-9)
return summed / counts
def embed_documents(self, texts):
encoded = self.tokenizer(
texts,
padding=True,
truncation=True,
max_length=self.max_seq_len,
return_tensors="pt"
)
with torch.no_grad():
outputs = self.model(**encoded)
embeddings = self._mean_pool(
outputs.last_hidden_state.numpy(),
encoded["attention_mask"].numpy()
)
return embeddings.tolist()
def embed_query(self, text):
return self.embed_documents([text])[0]
def late_chunk_embed(self, text, chunk_spans):
encoded = self.tokenizer(
text,
return_offsets_mapping=True,
truncation=True,
max_length=self.max_seq_len,
return_tensors="pt"
)
offset_mapping = encoded.pop("offset_mapping")[0].numpy()
with torch.no_grad():
outputs = self.model(**encoded)
token_embeddings = outputs.last_hidden_state[0].numpy()
chunk_vectors = []
for start, end in chunk_spans:
token_mask = (offset_mapping[:, 0] < end) & (offset_mapping[:, 1] > start)
selected = token_embeddings[token_mask]
if len(selected) == 0:
vec = self.embed_documents([text[start:end]])[0]
else:
vec = selected.mean(axis=0).tolist()
chunk_vectors.append(vec)
return chunk_vectors
# ==========================================
# 2. Text Splitters
# ==========================================
def split_text_recursive(text, chunk_size=500, overlap=50):
chunks = []
start = 0
while start < len(text):
end = min(start + chunk_size, len(text))
chunks.append({
"text": text[start:end],
"start": start,
"end": end
})
start += chunk_size - overlap
return chunks
def split_text_late(text, chunk_size=400):
# Split text roughly by paragraphs or sentences
parts = text.split("\n\n")
chunks = []
cursor = 0
for part in parts:
part = part.strip()
if not part:
continue
start = text.find(part, cursor)
if start == -1:
start = cursor
end = start + len(part)
chunks.append({
"text": part,
"start": start,
"end": end
})
cursor = end
return chunks
# ==========================================
# 3. Hybrid Indexing (FAISS + BM25)
# ==========================================
class HybridIndex:
def __init__(self, embedder):
self.embedder = embedder
self.chunks = []
self.faiss_index = None
self.bm25 = None
def build(self, text, strategy, chunk_size=500):
if strategy == "Late Chunking":
self.chunks = split_text_late(text, chunk_size)
spans = [(c["start"], c["end"]) for c in self.chunks]
vectors = self.embedder.late_chunk_embed(text, spans)
else:
self.chunks = split_text_recursive(text, chunk_size)
texts = [c["text"] for c in self.chunks]
vectors = self.embedder.embed_documents(texts)
# Build FAISS
vectors_np = np.array(vectors, dtype=np.float32)
faiss.normalize_L2(vectors_np)
self.faiss_index = faiss.IndexFlatIP(vectors_np.shape[1])
self.faiss_index.add(vectors_np)
# Build BM25
tokenized_corpus = [c["text"].lower().split() for c in self.chunks]
self.bm25 = BM25Okapi(tokenized_corpus)
print(f"Built HybridIndex with {len(self.chunks)} chunks.")
def search_dense(self, query, k=10):
if self.faiss_index is None:
return []
query_vec = np.array([self.embedder.embed_query(query)], dtype=np.float32)
faiss.normalize_L2(query_vec)
distances, indices = self.faiss_index.search(query_vec, k)
results = []
for dist, idx in zip(distances[0], indices[0]):
if idx >= 0 and idx < len(self.chunks):
results.append((self.chunks[idx], float(dist)))
return results
def search_sparse(self, query, k=10):
if self.bm25 is None:
return []
tokens = query.lower().split()
scores = self.bm25.get_scores(tokens)
top_indices = np.argsort(scores)[::-1][:k]
results = []
for idx in top_indices:
if scores[idx] > 0:
results.append((self.chunks[idx], float(scores[idx])))
return results
# ==========================================
# 4. Reciprocal Rank Fusion & Re-ranking
# ==========================================
def rrf_fuse(dense_results, sparse_results, dense_weight=0.7, bm25_weight=0.3, k_constant=60):
scores = {}
chunk_map = {}
# Dense rank
for rank, (chunk, _) in enumerate(dense_results, start=1):
key = chunk["text"]
scores[key] = scores.get(key, 0.0) + (dense_weight / (k_constant + rank))
chunk_map[key] = chunk
# Sparse rank
for rank, (chunk, _) in enumerate(sparse_results, start=1):
key = chunk["text"]
scores[key] = scores.get(key, 0.0) + (bm25_weight / (k_constant + rank))
chunk_map[key] = chunk
sorted_keys = sorted(scores, key=lambda x: scores[x], reverse=True)
return [(chunk_map[key], scores[key]) for key in sorted_keys]
def flashrank_rerank(query, fused_results, top_n=5):
try:
from flashrank import Ranker, RerankRequest
ranker = Ranker()
passages = [{"id": i, "text": item[0]["text"]} for i, item in enumerate(fused_results)]
req = RerankRequest(query=query, passages=passages)
results = ranker.rerank(req)
reranked = []
for r in results[:top_n]:
idx = r["id"]
reranked.append((fused_results[idx][0], float(r["score"])))
return reranked
except Exception as e:
print(f"FlashRank fallback: {e}")
return fused_results[:top_n]
# ==========================================
# 5. Global State & App Logic
# ==========================================
embedder = JinaEmbedder()
current_index = HybridIndex(embedder)
def load_document(file_obj):
if file_obj is None:
return "No file uploaded."
filename = file_obj.name
text = ""
if filename.endswith(".pdf"):
reader = PdfReader(filename)
for page in reader.pages:
t = page.extract_text()
if t:
text += t + "\n"
else:
with open(filename, "r", encoding="utf-8") as f:
text = f.read()
return text
def index_document(file_obj, strategy, chunk_size):
text = load_document(file_obj)
if not text.strip():
return "Failed to extract text from file."
current_index.build(text, strategy, chunk_size)
return f"Successfully indexed document! Strategy: {strategy}, Total Chunks: {len(current_index.chunks)}"
def query_rag(query, dense_weight, bm25_weight, rerank, openai_key, gemini_key):
if not current_index.chunks:
return "Please upload and index a document first.", "", "", ""
# 1. Retrieve
dense_res = current_index.search_dense(query, k=10)
sparse_res = current_index.search_sparse(query, k=10)
# 2. Fuse (RRF)
fused_res = rrf_fuse(dense_res, sparse_res, dense_weight, bm25_weight)
# 3. Re-rank
if rerank:
final_res = flashrank_rerank(query, fused_res, top_n=4)
else:
final_res = fused_res[:4]
# Format visual outputs for retrieval pipeline
dense_out = "\n\n".join([f"**Score: {score:.4f}**\n{chunk['text']}" for chunk, score in dense_res[:3]])
sparse_out = "\n\n".join([f"**Score: {score:.4f}**\n{chunk['text']}" for chunk, score in sparse_res[:3]])
fused_out = "\n\n".join([f"**RRF Score: {score:.4f}**\n{chunk['text']}" for chunk, score in final_res])
# 4. Generate Answer if API Key is available
answer = "Please enter an OpenAI or Gemini API Key to synthesize a final summary/answer."
context = "\n".join([chunk["text"] for chunk, _ in final_res])
if openai_key.strip():
try:
client = openai.OpenAI(api_key=openai_key)
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a helpful assistant. Answer the question based on the provided context."},
{"role": "user", "content": f"Context:\n{context}\n\nQuestion: {query}"}
]
)
answer = response.choices[0].message.content
except Exception as e:
answer = f"Error during OpenAI completion: {str(e)}"
elif gemini_key.strip():
try:
import google.generativeai as genai
genai.configure(api_key=gemini_key)
model = genai.GenerativeModel('gemini-1.5-flash')
response = model.generate_content(
f"You are a helpful assistant. Answer the question based on the provided context.\n\nContext:\n{context}\n\nQuestion: {query}"
)
answer = response.text
except Exception as e:
answer = f"Error during Gemini completion: {str(e)}"
return answer, dense_out, sparse_out, fused_out
# ==========================================
# 6. UI Layout
# ==========================================
with gr.Blocks(theme=gr.themes.Soft(primary_hue="purple", secondary_hue="indigo")) as demo:
gr.Markdown("# 🗂️ DocuQuery: Hybrid RAG Pipeline")
gr.Markdown(
"Upload a PDF or TXT document, choose your chunking strategy, build the index, and ask questions. "
"Explore dense/sparse hybrid search, Reciprocal Rank Fusion (RRF), and cross-encoder re-ranking in action."
)
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### 1. Ingestion Configuration")
file_input = gr.File(label="Upload Document (.pdf, .txt)", file_types=[".pdf", ".txt"])
strategy = gr.Dropdown(choices=["Recursive Splitting", "Late Chunking"], value="Late Chunking", label="Chunking Strategy")
chunk_size = gr.Slider(minimum=200, maximum=1500, step=100, value=500, label="Chunk Size (characters)")
index_btn = gr.Button("Build Hybrid Index", variant="primary")
index_status = gr.Textbox(label="Index Status", interactive=False)
gr.Markdown("### 2. LLM Provider (Optional)")
openai_key = gr.Textbox(label="OpenAI API Key (sk-...)", type="password")
gemini_key = gr.Textbox(label="Gemini API Key", type="password")
with gr.Column(scale=1):
gr.Markdown("### 3. Ask Your Document")
query_input = gr.Textbox(label="Enter Question/Query", placeholder="What does the document say about...")
with gr.Accordion("Retrieval Settings", open=False):
dense_weight = gr.Slider(minimum=0.0, maximum=1.0, value=0.7, step=0.1, label="Dense Weight (FAISS)")
sparse_weight = gr.Slider(minimum=0.0, maximum=1.0, value=0.3, step=0.1, label="Sparse Weight (BM25)")
rerank = gr.Checkbox(label="Enable Cross-Encoder Re-ranking", value=True)
query_btn = gr.Button("Submit Query", variant="primary")
answer_output = gr.Markdown(label="Generated Answer")
with gr.Row():
with gr.Tab("Dense Search (FAISS)"):
dense_output = gr.Markdown(label="Top Dense Hits")
with gr.Tab("Sparse Search (BM25)"):
sparse_output = gr.Markdown(label="Top Sparse Hits")
with gr.Tab("RRF Fused & Re-ranked Context"):
fused_output = gr.Markdown(label="Fused Context")
# Hook up events
index_btn.click(
fn=index_document,
inputs=[file_input, strategy, chunk_size],
outputs=[index_status]
)
query_btn.click(
fn=query_rag,
inputs=[query_input, dense_weight, sparse_weight, rerank, openai_key, gemini_key],
outputs=[answer_output, dense_output, sparse_output, fused_output]
)
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0", server_port=7860)