Itzadityapandey commited on
Commit
8563a16
·
verified ·
1 Parent(s): 75df3d3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -7
app.py CHANGED
@@ -4,9 +4,8 @@ from PyPDF2 import PdfReader
4
  from langchain_text_splitters import RecursiveCharacterTextSplitter
5
  from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI
6
  from langchain_community.vectorstores import FAISS
7
- from langchain_core.prompts import ChatPromptTemplate
8
- from langchain_classic.chains.combine_documents import create_stuff_documents_chain
9
- from langchain_classic.chains import create_retrieval_chain
10
  from dotenv import load_dotenv
11
 
12
  # Load environment variables
@@ -20,11 +19,11 @@ def get_pdf_text(pdf_files):
20
  text = ""
21
  for pdf in pdf_files:
22
  try:
23
- pdf_reader = PdfReader(pdf.name) # pdf is a tempfile.NamedTemporaryFile in Gradio
24
  for page in pdf_reader.pages:
25
- extracted_text = page.extract_text()
26
- if extracted_text:
27
- text += extracted_text + "\n"
28
  except Exception as e:
29
  return f"Error reading PDF: {str(e)}"
30
  return text
@@ -51,6 +50,82 @@ def load_vector_store():
51
  except Exception as e:
52
  return None
53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  def get_qa_chain():
55
  # Modern stuff QA chain
56
  llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0.3, google_api_key=GOOGLE_API_KEY)
 
4
  from langchain_text_splitters import RecursiveCharacterTextSplitter
5
  from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI
6
  from langchain_community.vectorstores import FAISS
7
+ from langchain_classic.chains.question_answering import load_qa_chain # Fixed import
8
+ from langchain_core.prompts import PromptTemplate
 
9
  from dotenv import load_dotenv
10
 
11
  # Load environment variables
 
19
  text = ""
20
  for pdf in pdf_files:
21
  try:
22
+ pdf_reader = PdfReader(pdf.name) # Gradio gives tempfile
23
  for page in pdf_reader.pages:
24
+ extracted = page.extract_text()
25
+ if extracted:
26
+ text += extracted + "\n"
27
  except Exception as e:
28
  return f"Error reading PDF: {str(e)}"
29
  return text
 
50
  except Exception as e:
51
  return None
52
 
53
+ def get_conversational_chain():
54
+ prompt_template = """
55
+ Answer the question as detailed as possible from the provided context.
56
+ If the answer is not in the provided context, respond with "answer is not available in the context".
57
+ Do not provide incorrect information.
58
+
59
+ Context:
60
+ {context}
61
+
62
+ Question:
63
+ {question}
64
+
65
+ Answer:
66
+ """
67
+ model = ChatGoogleGenerativeAI(model="gemini-1.5-flash", temperature=0.3, google_api_key=GOOGLE_API_KEY) # Updated to a current fast model
68
+ prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
69
+ return load_qa_chain(model, chain_type="stuff", prompt=prompt)
70
+
71
+ def query_pdf(user_question):
72
+ vector_store = load_vector_store()
73
+ if vector_store is None:
74
+ return "Please process a PDF first by uploading and submitting it."
75
+
76
+ try:
77
+ docs = vector_store.similarity_search(user_question, k=4)
78
+ chain = get_conversational_chain()
79
+ response = chain({"input_documents": docs, "question": user_question}, return_only_outputs=True)
80
+ return response["output_text"]
81
+ except Exception as e:
82
+ return f"Error querying the PDF: {str(e)}"
83
+
84
+ def process_pdfs(pdf_files):
85
+ if not pdf_files:
86
+ return "Please upload at least one PDF."
87
+
88
+ raw_text = get_pdf_text(pdf_files)
89
+ if "Error" in raw_text:
90
+ return raw_text
91
+ if not raw_text.strip():
92
+ return "No extractable text found in the uploaded PDFs."
93
+
94
+ text_chunks = get_text_chunks(raw_text)
95
+ result = create_vector_store(text_chunks)
96
+ return result
97
+
98
+ # Gradio UI
99
+ with gr.Blocks(title="Chat with PDF") as demo:
100
+ gr.Markdown("## Chat with PDF 💁")
101
+ pdf_input = gr.File(file_types=[".pdf"], label="Upload PDF(s)", file_count="multiple")
102
+ process_button = gr.Button("Submit & Process")
103
+ status_output = gr.Textbox(label="Status", placeholder="Status updates will appear here...")
104
+ question_input = gr.Textbox(label="Ask a Question from the PDF")
105
+ answer_output = gr.Textbox(label="Reply", placeholder="Answers will appear here...")
106
+ ask_button = gr.Button("Get Answer")
107
+
108
+ process_button.click(process_pdfs, inputs=[pdf_input], outputs=[status_output])
109
+ ask_button.click(query_pdf, inputs=[question_input], outputs=[answer_output])
110
+
111
+ if __name__ == "__main__":
112
+ demo.launch() try:
113
+ embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001", google_api_key=GOOGLE_API_KEY)
114
+ vector_store = FAISS.from_texts(text_chunks, embedding=embeddings)
115
+ vector_store.save_local(INDEX_PATH)
116
+ return "PDFs processed successfully! Vector store saved. Now you can ask questions."
117
+ except Exception as e:
118
+ return f"Error creating vector store: {str(e)}"
119
+
120
+ def load_vector_store():
121
+ try:
122
+ embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001", google_api_key=GOOGLE_API_KEY)
123
+ if os.path.exists(INDEX_PATH):
124
+ return FAISS.load_local(INDEX_PATH, embeddings, allow_dangerous_deserialization=True)
125
+ return None
126
+ except Exception as e:
127
+ return None
128
+
129
  def get_qa_chain():
130
  # Modern stuff QA chain
131
  llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0.3, google_api_key=GOOGLE_API_KEY)