ShubhangiAg commited on
Commit
c1b1e05
Β·
verified Β·
1 Parent(s): d314991

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -37
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
- 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():
38
  global bm25, index, embed_model, document_embeddings
39
 
40
  if not pdf_texts:
41
- raise ValueError("❌ No PDF text to index!")
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 search: BM25 + FAISS ---
53
  def hybrid_search(query, top_n=3):
54
  if bm25 is None or index is None:
55
- return ["❌ Please upload and process a PDF first."]
 
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 response based on hybrid search ---
71
  def generate_response(query):
72
- relevant_chunks = hybrid_search(query)
73
- memory_context = memory.load_memory_variables({})
74
- history = memory_context.get("history", "")
75
-
76
- prompt = (
77
- f"Conversation history:\n{history}\n\n"
78
- f"Relevant text from document:\n{relevant_chunks}\n\n"
79
- f"Answer the user's query: {query}"
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 ---
@@ -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 a PDF", file_types=[".pdf"])
112
  upload_output = gr.Textbox(label="Upload Status", interactive=False)
113
 
114
  with gr.Row():
115
- query_input = gr.Textbox(label="Ask a Question", placeholder="What is this document about?", lines=2)
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)