Update app.py
Browse files
app.py
CHANGED
|
@@ -1,37 +1,94 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
from
|
| 5 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
#
|
| 8 |
-
memory = initialize_memory()
|
| 9 |
pdf_texts = []
|
| 10 |
bm25, index, embed_model, document_embeddings = None, None, None, None
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
# Function for user interaction
|
| 22 |
-
def chat_interface(user_input):
|
| 23 |
-
if not pdf_texts:
|
| 24 |
-
return "Please upload a PDF first!"
|
| 25 |
|
| 26 |
-
|
| 27 |
return response
|
| 28 |
|
| 29 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
file_input = gr.File(label="Upload a PDF", type="file", interactive=True)
|
| 31 |
chat_box = gr.Textbox(label="Ask a question based on the uploaded PDF")
|
| 32 |
|
| 33 |
iface = gr.Interface(
|
| 34 |
-
fn=
|
| 35 |
inputs=[file_input, chat_box],
|
| 36 |
outputs="text",
|
| 37 |
live=True
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import faiss
|
| 3 |
+
import numpy as np
|
| 4 |
+
from langchain.memory import ConversationBufferMemory
|
| 5 |
+
from langchain.document_loaders import PyPDFLoader
|
| 6 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 7 |
+
from sentence_transformers import SentenceTransformer
|
| 8 |
+
from rank_bm25 import BM25Okapi
|
| 9 |
+
from langchain.llms import OpenAI
|
| 10 |
|
| 11 |
+
# Global variables for retrieval
|
|
|
|
| 12 |
pdf_texts = []
|
| 13 |
bm25, index, embed_model, document_embeddings = None, None, None, None
|
| 14 |
|
| 15 |
+
# Initialize conversational memory
|
| 16 |
+
memory = ConversationBufferMemory()
|
| 17 |
+
|
| 18 |
+
# Function to load PDF and split text
|
| 19 |
+
def load_pdf(pdf_path, chunk_size=500, chunk_overlap=100):
|
| 20 |
+
"""Loads and splits an uploaded PDF document into chunks."""
|
| 21 |
+
loader = PyPDFLoader(pdf_path)
|
| 22 |
+
pages = loader.load()
|
| 23 |
+
|
| 24 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
|
| 25 |
+
doc_splits = text_splitter.split_documents(pages)
|
| 26 |
+
|
| 27 |
+
return [doc.page_content for doc in doc_splits]
|
| 28 |
+
|
| 29 |
+
# Function to initialize hybrid retrieval (BM25 + FAISS)
|
| 30 |
+
def create_hybrid_index(pdf_texts):
|
| 31 |
+
"""Initializes BM25 and FAISS for hybrid retrieval."""
|
| 32 |
+
global bm25, index, embed_model, document_embeddings
|
| 33 |
+
|
| 34 |
+
# BM25 setup
|
| 35 |
+
tokenized_corpus = [doc.split(" ") for doc in pdf_texts]
|
| 36 |
+
bm25 = BM25Okapi(tokenized_corpus)
|
| 37 |
+
|
| 38 |
+
# FAISS setup
|
| 39 |
+
embed_model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 40 |
+
document_embeddings = embed_model.encode(pdf_texts)
|
| 41 |
+
|
| 42 |
+
index = faiss.IndexFlatL2(document_embeddings.shape[1])
|
| 43 |
+
index.add(np.array(document_embeddings).astype("float32"))
|
| 44 |
+
|
| 45 |
+
# Hybrid search function (BM25 + FAISS)
|
| 46 |
+
def hybrid_search(query, top_n=3):
|
| 47 |
+
"""Performs hybrid search using BM25 for filtering and FAISS for semantic ranking."""
|
| 48 |
+
if not bm25 or not index:
|
| 49 |
+
return ["Error: PDF not uploaded! Please upload a PDF first."]
|
| 50 |
+
|
| 51 |
+
# BM25 search
|
| 52 |
+
bm25_scores = bm25.get_scores(query.split(" "))
|
| 53 |
+
top_docs_indices = np.argsort(bm25_scores)[-top_n:]
|
| 54 |
+
|
| 55 |
+
# FAISS search on filtered results
|
| 56 |
+
query_embedding = embed_model.encode([query])
|
| 57 |
+
sub_index = faiss.IndexFlatL2(document_embeddings.shape[1])
|
| 58 |
+
sub_index.add(np.array([document_embeddings[i] for i in top_docs_indices]).astype("float32"))
|
| 59 |
+
_, sub_ranked_indices = sub_index.search(np.array(query_embedding).astype("float32"), top_n)
|
| 60 |
+
|
| 61 |
+
# Map FAISS results back to original document indices
|
| 62 |
+
final_ranked_indices = [top_docs_indices[i] for i in sub_ranked_indices[0]]
|
| 63 |
+
return [pdf_texts[i] for i in final_ranked_indices]
|
| 64 |
+
|
| 65 |
+
# Function to generate response using OpenAI GPT-4
|
| 66 |
+
def generate_response(query):
|
| 67 |
+
"""Generates responses based on retrieved documents and conversation history."""
|
| 68 |
+
retrieved_docs = hybrid_search(query)
|
| 69 |
+
memory_context = memory.load_memory_variables({})
|
| 70 |
|
| 71 |
+
prompt = f"Conversation history: {memory_context}\nRelevant text: {retrieved_docs}\nGenerate a response:"
|
| 72 |
+
llm = OpenAI(model_name="gpt-4")
|
| 73 |
+
response = llm(prompt)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
+
memory.save_context({"user": query}, {"AI": response})
|
| 76 |
return response
|
| 77 |
|
| 78 |
+
# Function to process uploaded PDF
|
| 79 |
+
def process_pdf(uploaded_file):
|
| 80 |
+
"""Handles PDF upload and initializes retrieval system."""
|
| 81 |
+
global pdf_texts
|
| 82 |
+
pdf_texts = load_pdf(uploaded_file.name)
|
| 83 |
+
create_hybrid_index(pdf_texts)
|
| 84 |
+
return "✅ PDF processed successfully! You can now ask questions."
|
| 85 |
+
|
| 86 |
+
# Gradio UI with PDF Upload + Conversational Chat
|
| 87 |
file_input = gr.File(label="Upload a PDF", type="file", interactive=True)
|
| 88 |
chat_box = gr.Textbox(label="Ask a question based on the uploaded PDF")
|
| 89 |
|
| 90 |
iface = gr.Interface(
|
| 91 |
+
fn=generate_response,
|
| 92 |
inputs=[file_input, chat_box],
|
| 93 |
outputs="text",
|
| 94 |
live=True
|