Update app.py
Browse files
app.py
CHANGED
|
@@ -9,96 +9,86 @@ from sentence_transformers import SentenceTransformer
|
|
| 9 |
from rank_bm25 import BM25Okapi
|
| 10 |
from langchain.llms import OpenAI
|
| 11 |
|
| 12 |
-
# Global variables
|
| 13 |
pdf_texts = []
|
| 14 |
bm25, index, embed_model, document_embeddings = None, None, None, None
|
| 15 |
-
|
| 16 |
-
# Initialize conversational memory
|
| 17 |
memory = ConversationBufferMemory()
|
| 18 |
-
|
| 19 |
-
# Load API key from Hugging Face Spaces Secrets
|
| 20 |
openai_api_key = os.getenv("OPENAI_API_KEY")
|
| 21 |
|
| 22 |
-
#
|
| 23 |
def load_pdf(pdf_path, chunk_size=500, chunk_overlap=100):
|
| 24 |
-
"""Loads and splits an uploaded PDF document into chunks."""
|
| 25 |
loader = PyPDFLoader(pdf_path)
|
| 26 |
pages = loader.load()
|
| 27 |
-
|
| 28 |
text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
|
| 29 |
doc_splits = text_splitter.split_documents(pages)
|
| 30 |
-
|
| 31 |
return [doc.page_content for doc in doc_splits]
|
| 32 |
|
| 33 |
-
#
|
| 34 |
def create_hybrid_index():
|
| 35 |
-
"""Initializes BM25 and FAISS for hybrid retrieval."""
|
| 36 |
global bm25, index, embed_model, document_embeddings
|
| 37 |
-
|
| 38 |
if not pdf_texts:
|
| 39 |
return "β Error: No PDF data found!"
|
| 40 |
|
| 41 |
-
# BM25 setup
|
| 42 |
tokenized_corpus = [doc.split(" ") for doc in pdf_texts]
|
| 43 |
bm25 = BM25Okapi(tokenized_corpus)
|
| 44 |
|
| 45 |
-
# FAISS setup
|
| 46 |
embed_model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 47 |
document_embeddings = embed_model.encode(pdf_texts)
|
| 48 |
-
|
| 49 |
index = faiss.IndexFlatL2(document_embeddings.shape[1])
|
| 50 |
index.add(np.array(document_embeddings).astype("float32"))
|
| 51 |
|
| 52 |
-
# Hybrid search
|
| 53 |
def hybrid_search(query, top_n=3):
|
| 54 |
-
|
| 55 |
-
if not bm25 or not index:
|
| 56 |
return ["β Error: PDF not uploaded! Please upload a PDF first."]
|
| 57 |
|
| 58 |
-
# BM25 search
|
| 59 |
bm25_scores = bm25.get_scores(query.split(" "))
|
| 60 |
top_docs_indices = np.argsort(bm25_scores)[-top_n:]
|
| 61 |
|
| 62 |
-
# FAISS search on filtered results
|
| 63 |
query_embedding = embed_model.encode([query])
|
| 64 |
sub_index = faiss.IndexFlatL2(document_embeddings.shape[1])
|
| 65 |
sub_index.add(np.array([document_embeddings[i] for i in top_docs_indices]).astype("float32"))
|
| 66 |
_, sub_ranked_indices = sub_index.search(np.array(query_embedding).astype("float32"), top_n)
|
| 67 |
|
| 68 |
-
# Map FAISS results back to original document indices
|
| 69 |
final_ranked_indices = [top_docs_indices[i] for i in sub_ranked_indices[0]]
|
| 70 |
return [pdf_texts[i] for i in final_ranked_indices]
|
| 71 |
|
| 72 |
-
#
|
| 73 |
def generate_response(query):
|
| 74 |
-
"""Generates responses based on retrieved documents and conversation history."""
|
| 75 |
retrieved_docs = hybrid_search(query)
|
| 76 |
memory_context = memory.load_memory_variables({})
|
|
|
|
| 77 |
|
| 78 |
-
prompt = f"Conversation history: {
|
| 79 |
llm = OpenAI(model_name="gpt-4", openai_api_key=openai_api_key)
|
| 80 |
|
| 81 |
-
response = llm(prompt)
|
| 82 |
memory.save_context({"user": query}, {"AI": response})
|
| 83 |
return response
|
| 84 |
|
| 85 |
-
#
|
| 86 |
-
def
|
| 87 |
-
"""Handles PDF upload and initializes retrieval system."""
|
| 88 |
global pdf_texts
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
)
|
| 103 |
-
|
| 104 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
from rank_bm25 import BM25Okapi
|
| 10 |
from langchain.llms import OpenAI
|
| 11 |
|
| 12 |
+
# Global variables
|
| 13 |
pdf_texts = []
|
| 14 |
bm25, index, embed_model, document_embeddings = None, None, None, None
|
|
|
|
|
|
|
| 15 |
memory = ConversationBufferMemory()
|
|
|
|
|
|
|
| 16 |
openai_api_key = os.getenv("OPENAI_API_KEY")
|
| 17 |
|
| 18 |
+
# Load PDF and split into chunks
|
| 19 |
def load_pdf(pdf_path, chunk_size=500, chunk_overlap=100):
|
|
|
|
| 20 |
loader = PyPDFLoader(pdf_path)
|
| 21 |
pages = loader.load()
|
|
|
|
| 22 |
text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
|
| 23 |
doc_splits = text_splitter.split_documents(pages)
|
|
|
|
| 24 |
return [doc.page_content for doc in doc_splits]
|
| 25 |
|
| 26 |
+
# Initialize hybrid index
|
| 27 |
def create_hybrid_index():
|
|
|
|
| 28 |
global bm25, index, embed_model, document_embeddings
|
|
|
|
| 29 |
if not pdf_texts:
|
| 30 |
return "β Error: No PDF data found!"
|
| 31 |
|
|
|
|
| 32 |
tokenized_corpus = [doc.split(" ") for doc in pdf_texts]
|
| 33 |
bm25 = BM25Okapi(tokenized_corpus)
|
| 34 |
|
|
|
|
| 35 |
embed_model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 36 |
document_embeddings = embed_model.encode(pdf_texts)
|
|
|
|
| 37 |
index = faiss.IndexFlatL2(document_embeddings.shape[1])
|
| 38 |
index.add(np.array(document_embeddings).astype("float32"))
|
| 39 |
|
| 40 |
+
# Hybrid search
|
| 41 |
def hybrid_search(query, top_n=3):
|
| 42 |
+
if bm25 is None or index is None:
|
|
|
|
| 43 |
return ["β Error: PDF not uploaded! Please upload a PDF first."]
|
| 44 |
|
|
|
|
| 45 |
bm25_scores = bm25.get_scores(query.split(" "))
|
| 46 |
top_docs_indices = np.argsort(bm25_scores)[-top_n:]
|
| 47 |
|
|
|
|
| 48 |
query_embedding = embed_model.encode([query])
|
| 49 |
sub_index = faiss.IndexFlatL2(document_embeddings.shape[1])
|
| 50 |
sub_index.add(np.array([document_embeddings[i] for i in top_docs_indices]).astype("float32"))
|
| 51 |
_, sub_ranked_indices = sub_index.search(np.array(query_embedding).astype("float32"), top_n)
|
| 52 |
|
|
|
|
| 53 |
final_ranked_indices = [top_docs_indices[i] for i in sub_ranked_indices[0]]
|
| 54 |
return [pdf_texts[i] for i in final_ranked_indices]
|
| 55 |
|
| 56 |
+
# Generate GPT response
|
| 57 |
def generate_response(query):
|
|
|
|
| 58 |
retrieved_docs = hybrid_search(query)
|
| 59 |
memory_context = memory.load_memory_variables({})
|
| 60 |
+
context = memory_context.get("history", "")
|
| 61 |
|
| 62 |
+
prompt = f"Conversation history: {context}\nRelevant text: {retrieved_docs}\nGenerate a response:"
|
| 63 |
llm = OpenAI(model_name="gpt-4", openai_api_key=openai_api_key)
|
| 64 |
|
| 65 |
+
response = llm.predict(prompt)
|
| 66 |
memory.save_context({"user": query}, {"AI": response})
|
| 67 |
return response
|
| 68 |
|
| 69 |
+
# Combined Gradio function
|
| 70 |
+
def pdf_chatbot(uploaded_file, query):
|
|
|
|
| 71 |
global pdf_texts
|
| 72 |
+
|
| 73 |
+
if uploaded_file is not None:
|
| 74 |
+
pdf_texts = load_pdf(uploaded_file.name)
|
| 75 |
+
create_hybrid_index()
|
| 76 |
+
return "β
PDF processed successfully. Now ask your question."
|
| 77 |
+
|
| 78 |
+
if not pdf_texts:
|
| 79 |
+
return "β Please upload a PDF first."
|
| 80 |
+
|
| 81 |
+
return generate_response(query)
|
| 82 |
+
|
| 83 |
+
# Gradio UI
|
| 84 |
+
with gr.Blocks() as demo:
|
| 85 |
+
gr.Markdown("## π Chat with your PDF (Hybrid Retrieval + GPT)")
|
| 86 |
+
with gr.Row():
|
| 87 |
+
file_input = gr.File(label="Upload a PDF", file_types=[".pdf"])
|
| 88 |
+
query_input = gr.Textbox(label="Ask something from the document")
|
| 89 |
+
output = gr.Textbox(label="Answer")
|
| 90 |
+
|
| 91 |
+
file_input.change(fn=pdf_chatbot, inputs=[file_input, query_input], outputs=output)
|
| 92 |
+
query_input.submit(fn=pdf_chatbot, inputs=[file_input, query_input], outputs=output)
|
| 93 |
+
|
| 94 |
+
demo.launch()
|