Update app.py
Browse files
app.py
CHANGED
|
@@ -3,7 +3,7 @@ import faiss
|
|
| 3 |
import numpy as np
|
| 4 |
import os
|
| 5 |
from langchain.memory import ConversationBufferMemory
|
| 6 |
-
from langchain.document_loaders import PyPDFLoader
|
| 7 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 8 |
from sentence_transformers import SentenceTransformer
|
| 9 |
from rank_bm25 import BM25Okapi
|
|
@@ -15,13 +15,23 @@ 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 and split PDF ---
|
| 19 |
def load_pdf(uploaded_file, chunk_size=500, chunk_overlap=100):
|
| 20 |
-
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
|
| 23 |
doc_splits = text_splitter.split_documents(pages)
|
| 24 |
-
|
|
|
|
|
|
|
| 25 |
|
| 26 |
# --- Initialize BM25 + FAISS index ---
|
| 27 |
def create_hybrid_index():
|
|
@@ -57,7 +67,7 @@ def hybrid_search(query, top_n=3):
|
|
| 57 |
final_indices = [top_bm25_indices[i] for i in sub_ranked[0]]
|
| 58 |
return [pdf_texts[i] for i in final_indices]
|
| 59 |
|
| 60 |
-
# --- Generate GPT response ---
|
| 61 |
def generate_response(query):
|
| 62 |
relevant_chunks = hybrid_search(query)
|
| 63 |
memory_context = memory.load_memory_variables({})
|
|
@@ -70,30 +80,32 @@ def generate_response(query):
|
|
| 70 |
)
|
| 71 |
|
| 72 |
llm = OpenAI(model_name="gpt-4", openai_api_key=openai_api_key)
|
| 73 |
-
response = llm(prompt)
|
| 74 |
memory.save_context({"user": query}, {"AI": response})
|
| 75 |
return response
|
| 76 |
|
| 77 |
-
# --- Upload PDF ---
|
| 78 |
def handle_pdf_upload(uploaded_file):
|
| 79 |
global pdf_texts
|
| 80 |
try:
|
| 81 |
pdf_texts = load_pdf(uploaded_file)
|
|
|
|
|
|
|
|
|
|
| 82 |
create_hybrid_index()
|
| 83 |
-
return "β
PDF processed
|
| 84 |
except Exception as e:
|
| 85 |
return f"β Failed to process PDF: {str(e)}"
|
| 86 |
|
| 87 |
-
# ---
|
| 88 |
def handle_query(query):
|
| 89 |
-
global pdf_texts
|
| 90 |
if not pdf_texts:
|
| 91 |
return "β No PDF uploaded. Please upload a PDF first."
|
| 92 |
return generate_response(query)
|
| 93 |
|
| 94 |
# --- Gradio UI ---
|
| 95 |
with gr.Blocks() as demo:
|
| 96 |
-
gr.Markdown("## π€ Chat with Your PDF (BM25 + FAISS + GPT-4)")
|
| 97 |
|
| 98 |
with gr.Row():
|
| 99 |
file_input = gr.File(label="Upload a PDF", file_types=[".pdf"])
|
|
@@ -110,6 +122,4 @@ with gr.Blocks() as demo:
|
|
| 110 |
submit_btn.click(fn=handle_query, inputs=query_input, outputs=response_output)
|
| 111 |
query_input.submit(fn=handle_query, inputs=query_input, outputs=response_output)
|
| 112 |
|
| 113 |
-
|
| 114 |
-
if __name__ == "__main__":
|
| 115 |
-
demo.launch()
|
|
|
|
| 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
|
| 8 |
from sentence_transformers import SentenceTransformer
|
| 9 |
from rank_bm25 import BM25Okapi
|
|
|
|
| 15 |
memory = ConversationBufferMemory()
|
| 16 |
openai_api_key = os.getenv("OPENAI_API_KEY")
|
| 17 |
|
| 18 |
+
# --- Load and split PDF (with OCR fallback) ---
|
| 19 |
def load_pdf(uploaded_file, chunk_size=500, chunk_overlap=100):
|
| 20 |
+
try:
|
| 21 |
+
print(f"π Trying to load with PyPDFLoader: {uploaded_file}")
|
| 22 |
+
loader = PyPDFLoader(str(uploaded_file))
|
| 23 |
+
pages = loader.load()
|
| 24 |
+
except Exception as e:
|
| 25 |
+
print(f"β οΈ PyPDFLoader failed: {e}")
|
| 26 |
+
print("π Falling back to OCR with UnstructuredPDFLoader.")
|
| 27 |
+
loader = UnstructuredPDFLoader(str(uploaded_file))
|
| 28 |
+
pages = loader.load()
|
| 29 |
+
|
| 30 |
text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
|
| 31 |
doc_splits = text_splitter.split_documents(pages)
|
| 32 |
+
texts = [doc.page_content.strip() for doc in doc_splits if doc.page_content.strip()]
|
| 33 |
+
print(f"β
Extracted {len(texts)} chunks.")
|
| 34 |
+
return texts
|
| 35 |
|
| 36 |
# --- Initialize BM25 + FAISS index ---
|
| 37 |
def create_hybrid_index():
|
|
|
|
| 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 response based on hybrid search ---
|
| 71 |
def generate_response(query):
|
| 72 |
relevant_chunks = hybrid_search(query)
|
| 73 |
memory_context = memory.load_memory_variables({})
|
|
|
|
| 80 |
)
|
| 81 |
|
| 82 |
llm = OpenAI(model_name="gpt-4", openai_api_key=openai_api_key)
|
| 83 |
+
response = llm.predict(prompt)
|
| 84 |
memory.save_context({"user": query}, {"AI": response})
|
| 85 |
return response
|
| 86 |
|
| 87 |
+
# --- Step 1: Upload PDF ---
|
| 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 "β Failed: No readable text found in the PDF."
|
| 94 |
+
|
| 95 |
create_hybrid_index()
|
| 96 |
+
return f"β
PDF processed. {len(pdf_texts)} text chunks ready. You can now ask a question."
|
| 97 |
except Exception as e:
|
| 98 |
return f"β Failed to process PDF: {str(e)}"
|
| 99 |
|
| 100 |
+
# --- Step 2: Handle question ---
|
| 101 |
def handle_query(query):
|
|
|
|
| 102 |
if not pdf_texts:
|
| 103 |
return "β No PDF uploaded. Please upload a PDF first."
|
| 104 |
return generate_response(query)
|
| 105 |
|
| 106 |
# --- Gradio UI ---
|
| 107 |
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 a PDF", file_types=[".pdf"])
|
|
|
|
| 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)
|
| 124 |
|
| 125 |
+
demo.launch()
|
|
|
|
|
|