Spaces:
Sleeping
Sleeping
| # import os | |
| # from dotenv import load_dotenv | |
| # load_dotenv() | |
| # from langchain.document_loaders import PyPDFLoader | |
| # from langchain.text_splitter import RecursiveCharacterTextSplitter | |
| # from langchain.embeddings import HuggingFaceEmbeddings | |
| # from langchain.vectorstores import FAISS | |
| # from langchain.chains.question_answering import load_qa_chain | |
| # from langchain_google_genai import ChatGoogleGenerativeAI | |
| # from tkinter import Tk | |
| # from tkinter.filedialog import askopenfilename | |
| # # Hide the main tkinter window | |
| # Tk().withdraw() | |
| # # Open file dialog to select PDF | |
| # pdf_path = askopenfilename( | |
| # title="Select a PDF File", | |
| # filetypes=[("PDF Files", "*.pdf")] | |
| # ) | |
| # # Print the selected PDF path | |
| # if pdf_path: | |
| # print("Selected PDF Path:") | |
| # print(pdf_path) | |
| # else: | |
| # print("No PDF file selected.") | |
| # # Step 1: Load pdf | |
| # loader = PyPDFLoader(pdf_path) | |
| # documents = loader.load() | |
| # print("PDF successfully loaded....") | |
| # # Step 2: Split into chunks | |
| # text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50) | |
| # docs = text_splitter.split_documents(documents) | |
| # print('Chunks Created', len(docs)) | |
| # # Step 3: Create Embeddings | |
| # embeddings = HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L6-v2') | |
| # print('Embedding model loaded') | |
| # vectorstore = FAISS.from_documents(docs, embeddings) | |
| # print('Vector Database Created') | |
| # # Step 4: Load Gemini Model | |
| # llm = ChatGoogleGenerativeAI( | |
| # model = 'gemini-2.5-flash', | |
| # temperature = 0.3, | |
| # google_api_key = os.getenv("GOOGLE_API_KEY") | |
| # ) | |
| # print("LLM loaded") | |
| # # STep 5: Ask Question | |
| # query = input('Ask Question :') | |
| # matched_docs = vectorstore.similarity_search(query) | |
| # chain = load_qa_chain(llm, chain_type='stuff') | |
| # response = chain.run(input_documents=matched_docs, question=query) | |
| # print('Response :') | |
| # print(response) | |
| import os | |
| from dotenv import load_dotenv | |
| load_dotenv() | |
| import gradio as gr | |
| from langchain_community.document_loaders import PyPDFLoader | |
| from langchain_text_splitters import RecursiveCharacterTextSplitter | |
| from langchain_huggingface import HuggingFaceEmbeddings | |
| from langchain_community.vectorstores import FAISS | |
| from langchain_google_genai import ChatGoogleGenerativeAI | |
| # ----------------------------- | |
| # Global Vector Store | |
| # ----------------------------- | |
| vectorstore = None | |
| # ----------------------------- | |
| # Load Gemini Model | |
| # ----------------------------- | |
| llm = ChatGoogleGenerativeAI( | |
| model="gemini-2.5-flash", | |
| temperature=0.3, | |
| google_api_key=os.getenv("GOOGLE_API_KEY") | |
| ) | |
| # ----------------------------- | |
| # Embedding Model | |
| # ----------------------------- | |
| embeddings = HuggingFaceEmbeddings( | |
| model_name="sentence-transformers/all-MiniLM-L6-v2" | |
| ) | |
| # ----------------------------- | |
| # Process PDF | |
| # ----------------------------- | |
| def process_pdf(pdf_file): | |
| global vectorstore | |
| if pdf_file is None: | |
| return "Please upload a PDF." | |
| try: | |
| # Load PDF | |
| loader = PyPDFLoader(pdf_file.name) | |
| documents = loader.load() | |
| # Split Text | |
| text_splitter = RecursiveCharacterTextSplitter( | |
| chunk_size=500, | |
| chunk_overlap=50 | |
| ) | |
| docs = text_splitter.split_documents(documents) | |
| # Create Vector Store | |
| vectorstore = FAISS.from_documents( | |
| docs, | |
| embeddings | |
| ) | |
| return f""" | |
| ✅ PDF processed successfully | |
| 📄 Pages Loaded: {len(documents)} | |
| 🧩 Chunks Created: {len(docs)} | |
| """ | |
| except Exception as e: | |
| return f"Error processing PDF:\n{str(e)}" | |
| # ----------------------------- | |
| # Ask Question | |
| # ----------------------------- | |
| def ask_question(query): | |
| global vectorstore | |
| if vectorstore is None: | |
| return "Please upload and process a PDF first." | |
| try: | |
| # Retrieve relevant docs | |
| docs = vectorstore.similarity_search(query, k=3) | |
| # Combine context | |
| context = "\n\n".join([doc.page_content for doc in docs]) | |
| # Prompt | |
| prompt = f""" | |
| Answer the question based only on the context below. | |
| Context: | |
| {context} | |
| Question: | |
| {query} | |
| """ | |
| # Gemini Response | |
| response = llm.invoke(prompt) | |
| return response.content | |
| except Exception as e: | |
| return f"Error:\n{str(e)}" | |
| # ----------------------------- | |
| # Gradio UI | |
| # ----------------------------- | |
| with gr.Blocks(theme=gr.themes.Soft()) as demo: | |
| gr.Markdown( | |
| """ | |
| # 📚 PDF Question Answering System | |
| Upload a PDF and ask questions from it using Gemini AI. | |
| """ | |
| ) | |
| with gr.Row(): | |
| pdf_input = gr.File( | |
| label="Upload PDF", | |
| file_types=[".pdf"] | |
| ) | |
| upload_btn = gr.Button( | |
| "Process PDF", | |
| variant="primary" | |
| ) | |
| upload_output = gr.Textbox( | |
| label="PDF Status", | |
| lines=4 | |
| ) | |
| upload_btn.click( | |
| fn=process_pdf, | |
| inputs=pdf_input, | |
| outputs=upload_output | |
| ) | |
| gr.Markdown("## ❓ Ask Questions") | |
| question_input = gr.Textbox( | |
| label="Enter your question", | |
| placeholder="What is this PDF about?" | |
| ) | |
| ask_btn = gr.Button( | |
| "Ask Question", | |
| variant="primary" | |
| ) | |
| answer_output = gr.Textbox( | |
| label="Answer", | |
| lines=10 | |
| ) | |
| ask_btn.click( | |
| fn=ask_question, | |
| inputs=question_input, | |
| outputs=answer_output | |
| ) | |
| # ----------------------------- | |
| # Launch | |
| # ----------------------------- | |
| if __name__ == "__main__": | |
| demo.queue() | |
| demo.launch() |