Update app.py
Browse files
app.py
CHANGED
|
@@ -2,6 +2,7 @@ import gradio as gr
|
|
| 2 |
import faiss
|
| 3 |
import numpy as np
|
| 4 |
import os
|
|
|
|
| 5 |
from langchain.memory import ConversationBufferMemory
|
| 6 |
from langchain.document_loaders import PyPDFLoader, UnstructuredPDFLoader
|
| 7 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
|
@@ -9,6 +10,9 @@ 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
|
|
@@ -18,41 +22,43 @@ openai_api_key = os.getenv("OPENAI_API_KEY")
|
|
| 18 |
# --- Load and split PDF (with OCR fallback) ---
|
| 19 |
def load_pdf(uploaded_file, chunk_size=500, chunk_overlap=100):
|
| 20 |
try:
|
| 21 |
-
|
| 22 |
loader = PyPDFLoader(str(uploaded_file))
|
| 23 |
pages = loader.load()
|
| 24 |
except Exception as e:
|
| 25 |
-
|
| 26 |
-
|
| 27 |
loader = UnstructuredPDFLoader(str(uploaded_file))
|
| 28 |
pages = loader.load()
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
texts = [doc.page_content.strip() for doc in
|
| 33 |
-
|
| 34 |
return texts
|
| 35 |
|
| 36 |
-
# --- Initialize BM25 + FAISS
|
| 37 |
def create_hybrid_index():
|
| 38 |
global bm25, index, embed_model, document_embeddings
|
| 39 |
|
| 40 |
if not pdf_texts:
|
| 41 |
-
raise ValueError("β No
|
| 42 |
|
| 43 |
tokenized_corpus = [doc.split() for doc in pdf_texts]
|
| 44 |
bm25 = BM25Okapi(tokenized_corpus)
|
| 45 |
|
| 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
|
| 53 |
def hybrid_search(query, top_n=3):
|
| 54 |
if bm25 is None or index is None:
|
| 55 |
-
|
|
|
|
| 56 |
|
| 57 |
bm25_scores = bm25.get_scores(query.split())
|
| 58 |
top_bm25_indices = np.argsort(bm25_scores)[-top_n:]
|
|
@@ -67,40 +73,45 @@ def hybrid_search(query, top_n=3):
|
|
| 67 |
final_indices = [top_bm25_indices[i] for i in sub_ranked[0]]
|
| 68 |
return [pdf_texts[i] for i in final_indices]
|
| 69 |
|
| 70 |
-
# --- Generate GPT
|
| 71 |
def generate_response(query):
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
def handle_pdf_upload(uploaded_file):
|
| 89 |
global pdf_texts
|
| 90 |
try:
|
| 91 |
pdf_texts = load_pdf(uploaded_file)
|
| 92 |
if not pdf_texts:
|
| 93 |
-
return "β
|
| 94 |
|
| 95 |
create_hybrid_index()
|
| 96 |
-
return f"β
PDF processed. {len(pdf_texts)}
|
| 97 |
except Exception as e:
|
| 98 |
-
|
|
|
|
| 99 |
|
| 100 |
-
# ---
|
| 101 |
def handle_query(query):
|
| 102 |
if not pdf_texts:
|
| 103 |
-
return "β No PDF uploaded
|
| 104 |
return generate_response(query)
|
| 105 |
|
| 106 |
# --- Gradio UI ---
|
|
@@ -108,16 +119,15 @@ with gr.Blocks() as demo:
|
|
| 108 |
gr.Markdown("## π€ Chat with Your PDF (BM25 + FAISS + GPT-4 + OCR)")
|
| 109 |
|
| 110 |
with gr.Row():
|
| 111 |
-
file_input = gr.File(label="Upload
|
| 112 |
upload_output = gr.Textbox(label="Upload Status", interactive=False)
|
| 113 |
|
| 114 |
with gr.Row():
|
| 115 |
-
query_input = gr.Textbox(label="Ask a Question",
|
| 116 |
submit_btn = gr.Button("Submit")
|
| 117 |
|
| 118 |
response_output = gr.Textbox(label="Response", lines=6)
|
| 119 |
|
| 120 |
-
# Event Bindings
|
| 121 |
file_input.change(fn=handle_pdf_upload, inputs=file_input, outputs=upload_output)
|
| 122 |
submit_btn.click(fn=handle_query, inputs=query_input, outputs=response_output)
|
| 123 |
query_input.submit(fn=handle_query, inputs=query_input, outputs=response_output)
|
|
|
|
| 2 |
import faiss
|
| 3 |
import numpy as np
|
| 4 |
import os
|
| 5 |
+
import logging
|
| 6 |
from langchain.memory import ConversationBufferMemory
|
| 7 |
from langchain.document_loaders import PyPDFLoader, UnstructuredPDFLoader
|
| 8 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
|
|
|
| 10 |
from rank_bm25 import BM25Okapi
|
| 11 |
from langchain.llms import OpenAI
|
| 12 |
|
| 13 |
+
# Enable logging
|
| 14 |
+
logging.basicConfig(level=logging.INFO)
|
| 15 |
+
|
| 16 |
# --- Global Variables ---
|
| 17 |
pdf_texts = []
|
| 18 |
bm25, index, embed_model, document_embeddings = None, None, None, None
|
|
|
|
| 22 |
# --- Load and split PDF (with OCR fallback) ---
|
| 23 |
def load_pdf(uploaded_file, chunk_size=500, chunk_overlap=100):
|
| 24 |
try:
|
| 25 |
+
logging.info(f"π Trying PyPDFLoader on: {uploaded_file}")
|
| 26 |
loader = PyPDFLoader(str(uploaded_file))
|
| 27 |
pages = loader.load()
|
| 28 |
except Exception as e:
|
| 29 |
+
logging.warning(f"PyPDFLoader failed: {e}")
|
| 30 |
+
logging.info("π Trying UnstructuredPDFLoader (OCR)")
|
| 31 |
loader = UnstructuredPDFLoader(str(uploaded_file))
|
| 32 |
pages = loader.load()
|
| 33 |
|
| 34 |
+
splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
|
| 35 |
+
docs = splitter.split_documents(pages)
|
| 36 |
+
texts = [doc.page_content.strip() for doc in docs if doc.page_content.strip()]
|
| 37 |
+
logging.info(f"β
Extracted {len(texts)} chunks.")
|
| 38 |
return texts
|
| 39 |
|
| 40 |
+
# --- Initialize BM25 + FAISS ---
|
| 41 |
def create_hybrid_index():
|
| 42 |
global bm25, index, embed_model, document_embeddings
|
| 43 |
|
| 44 |
if not pdf_texts:
|
| 45 |
+
raise ValueError("β No text to index!")
|
| 46 |
|
| 47 |
tokenized_corpus = [doc.split() for doc in pdf_texts]
|
| 48 |
bm25 = BM25Okapi(tokenized_corpus)
|
| 49 |
|
| 50 |
embed_model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 51 |
+
document_embeddings = embed_model.encode(pdf_texts, show_progress_bar=True)
|
| 52 |
|
| 53 |
index = faiss.IndexFlatL2(document_embeddings.shape[1])
|
| 54 |
index.add(np.array(document_embeddings).astype("float32"))
|
| 55 |
+
logging.info("π Hybrid index created.")
|
| 56 |
|
| 57 |
+
# --- Hybrid Search ---
|
| 58 |
def hybrid_search(query, top_n=3):
|
| 59 |
if bm25 is None or index is None:
|
| 60 |
+
logging.error("β Index not initialized.")
|
| 61 |
+
return ["β PDF not processed yet."]
|
| 62 |
|
| 63 |
bm25_scores = bm25.get_scores(query.split())
|
| 64 |
top_bm25_indices = np.argsort(bm25_scores)[-top_n:]
|
|
|
|
| 73 |
final_indices = [top_bm25_indices[i] for i in sub_ranked[0]]
|
| 74 |
return [pdf_texts[i] for i in final_indices]
|
| 75 |
|
| 76 |
+
# --- Generate GPT Response ---
|
| 77 |
def generate_response(query):
|
| 78 |
+
try:
|
| 79 |
+
relevant_chunks = hybrid_search(query)
|
| 80 |
+
context = memory.load_memory_variables({}).get("history", "")
|
| 81 |
+
|
| 82 |
+
prompt = (
|
| 83 |
+
f"Conversation history:\n{context}\n\n"
|
| 84 |
+
f"Relevant text from document:\n{relevant_chunks}\n\n"
|
| 85 |
+
f"Answer the user's question: {query}"
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
llm = OpenAI(model_name="gpt-4", openai_api_key=openai_api_key)
|
| 89 |
+
logging.info("π§ Sending prompt to GPT...")
|
| 90 |
+
response = llm.predict(prompt)
|
| 91 |
+
memory.save_context({"user": query}, {"AI": response})
|
| 92 |
+
return response
|
| 93 |
+
except Exception as e:
|
| 94 |
+
logging.error(f"Error during GPT response generation: {e}")
|
| 95 |
+
return f"β GPT Error: {str(e)}"
|
| 96 |
+
|
| 97 |
+
# --- Handle File Upload ---
|
| 98 |
def handle_pdf_upload(uploaded_file):
|
| 99 |
global pdf_texts
|
| 100 |
try:
|
| 101 |
pdf_texts = load_pdf(uploaded_file)
|
| 102 |
if not pdf_texts:
|
| 103 |
+
return "β No readable text found."
|
| 104 |
|
| 105 |
create_hybrid_index()
|
| 106 |
+
return f"β
PDF processed. {len(pdf_texts)} chunks ready."
|
| 107 |
except Exception as e:
|
| 108 |
+
logging.error(f"β PDF Processing failed: {e}")
|
| 109 |
+
return f"β PDF processing failed: {str(e)}"
|
| 110 |
|
| 111 |
+
# --- Handle Query ---
|
| 112 |
def handle_query(query):
|
| 113 |
if not pdf_texts:
|
| 114 |
+
return "β No PDF uploaded yet."
|
| 115 |
return generate_response(query)
|
| 116 |
|
| 117 |
# --- Gradio UI ---
|
|
|
|
| 119 |
gr.Markdown("## π€ Chat with Your PDF (BM25 + FAISS + GPT-4 + OCR)")
|
| 120 |
|
| 121 |
with gr.Row():
|
| 122 |
+
file_input = gr.File(label="Upload PDF", file_types=[".pdf"])
|
| 123 |
upload_output = gr.Textbox(label="Upload Status", interactive=False)
|
| 124 |
|
| 125 |
with gr.Row():
|
| 126 |
+
query_input = gr.Textbox(label="Ask a Question", lines=2)
|
| 127 |
submit_btn = gr.Button("Submit")
|
| 128 |
|
| 129 |
response_output = gr.Textbox(label="Response", lines=6)
|
| 130 |
|
|
|
|
| 131 |
file_input.change(fn=handle_pdf_upload, inputs=file_input, outputs=upload_output)
|
| 132 |
submit_btn.click(fn=handle_query, inputs=query_input, outputs=response_output)
|
| 133 |
query_input.submit(fn=handle_query, inputs=query_input, outputs=response_output)
|