ShubhangiAg commited on
Commit
a39cbc2
·
verified ·
1 Parent(s): f101127

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +14 -10
app.py CHANGED
@@ -9,13 +9,13 @@ 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
  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()
@@ -23,7 +23,7 @@ def load_pdf(pdf_path, chunk_size=500, chunk_overlap=100):
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:
@@ -37,7 +37,7 @@ def create_hybrid_index():
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."]
@@ -53,7 +53,7 @@ def hybrid_search(query, top_n=3):
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({})
@@ -66,7 +66,7 @@ def generate_response(query):
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
 
@@ -80,15 +80,19 @@ def pdf_chatbot(uploaded_file, query):
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()
 
9
  from rank_bm25 import BM25Okapi
10
  from langchain.llms import OpenAI
11
 
12
+ # --- Global state ---
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()
 
23
  doc_splits = text_splitter.split_documents(pages)
24
  return [doc.page_content for doc in doc_splits]
25
 
26
+ # --- Initialize hybrid BM25 + FAISS retrieval ---
27
  def create_hybrid_index():
28
  global bm25, index, embed_model, document_embeddings
29
  if not 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."]
 
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-based response ---
57
  def generate_response(query):
58
  retrieved_docs = hybrid_search(query)
59
  memory_context = memory.load_memory_variables({})
 
66
  memory.save_context({"user": query}, {"AI": response})
67
  return response
68
 
69
+ # --- Main handler for Gradio UI ---
70
  def pdf_chatbot(uploaded_file, query):
71
  global pdf_texts
72
 
 
80
 
81
  return generate_response(query)
82
 
83
+ # --- Gradio UI ---
84
  with gr.Blocks() as demo:
85
+ gr.Markdown("## 📄 Chat with Your PDF using GPT and Hybrid Retrieval")
86
+
87
  with gr.Row():
88
  file_input = gr.File(label="Upload a PDF", file_types=[".pdf"])
89
+ query_input = gr.Textbox(label="Ask something from the document", lines=2, placeholder="Type your question here...")
90
+ submit_btn = gr.Button("Submit")
91
+
92
+ output = gr.Textbox(label="Answer", lines=4)
93
 
94
  file_input.change(fn=pdf_chatbot, inputs=[file_input, query_input], outputs=output)
95
+ submit_btn.click(fn=pdf_chatbot, inputs=[file_input, query_input], outputs=output)
96
  query_input.submit(fn=pdf_chatbot, inputs=[file_input, query_input], outputs=output)
97
 
98
  demo.launch()