Spaces:
Sleeping
Sleeping
Update app.py
Browse files1 unmodified line2345678910111213141516171811 unmodified lines303132333435365 unmodified lines424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101 unmodified linefrom PyPDF2 import PdfReaderfrom io import BytesIOimport osfrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom langchain_google_genai import GoogleGenerativeAIEmbeddingsfrom langchain_community.vectorstores import FAISSfrom langchain_google_genai import ChatGoogleGenerativeAIfrom langchain.chains.question_answering import load_qa_chainfrom langchain.prompts import PromptTemplate# --- Get API key from environment variable (set in Hugging Face Secrets or .env file) ---GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY", "")def get_pdf_text(pdf_docs):text = ""for pdf in pdf_docs:11 unmodified linesdef get_vector_store(text_chunks, api_key):embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001", google_api_key=api_key)vector_store = FAISS.from_texts(text_chunks, embedding=embeddings)vector_store.save_local("/tmp/faiss_index")def get_conversational_chain(api_key):prompt_template = """5 unmodified lines{question}Answer:"""model = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0, google_api_key=api_key)prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)return chaindef user_input(user_question, api_key):embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001", google_api_key=api_key)new_db = FAISS.load_local("/tmp/faiss_index", embeddings, allow_dangerous_deserialization=True)docs = new_db.similarity_search(user_question)chain = get_conversational_chain(api_key)response = chain({"input_documents": docs, "question": user_question}, return_only_outputs=True)st.write("Reply: ", response["output_text"])def main():st.set_page_config(page_title="Chat PDF")st.header("Retrieval-Augmented Generation - Gemini 2.0")st.markdown("---")# STEP 1: Use API key from env or ask userif "api_entered" not in st.session_state:st.session_state["api_entered"] = Falseif "pdf_processed" not in st.session_state:st.session_state["pdf_processed"] = Falseapi_key = GOOGLE_API_KEYif not st.session_state["api_entered"]:if not api_key:user_api_key = st.text_input("Enter your Gemini API key", type="password")if st.button("Continue") and user_api_key:st.session_state["user_api_key"] = user_api_keyst.session_state["api_entered"] = Truest.experimental_rerun()st.stop()else:st.session_state["user_api_key"] = api_keyst.session_state["api_entered"] = Truest.experimental_rerun()api_key = st.session_state.get("user_api_key", "")# STEP 2: Upload PDF(s)if not st.session_state["pdf_processed"]:st.subheader("Step 2: Upload your PDF file(s)")pdf_docs = st.file_uploader("Upload PDF files", accept_multiple_files=True, type=['pdf'])if st.button("Submit & Process PDFs"):if pdf_docs:with st.spinner("Processing..."):raw_text = get_pdf_text(pdf_docs)text_chunks = get_text_chunks(raw_text)get_vector_store(text_chunks, api_key)st.session_state["pdf_processed"] = Truest.success("PDFs processed! You can now ask questions.")st.experimental_rerun()else:st.error("Please upload at least one PDF file.")st.stop()# STEP 3: Ask questionsst.subheader("Step 3: Ask a question about your PDFs")user_question = st.text_input("Ask a question")if user_question:user_input(user_question, api_key)if __name__ == "__main__":main()1 unmodified line234567891011121314151617181920212223242511 unmodified lines373839404142435 unmodified lines4950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671 unmodified linefrom PyPDF2 import PdfReaderfrom io import BytesIOimport osimport tempfile# Fixed imports for LangChainfrom langchain_text_splitters import RecursiveCharacterTextSplitterfrom langchain_google_genai import GoogleGenerativeAIEmbeddingsfrom langchain_community.vectorstores import FAISSfrom langchain_google_genai import ChatGoogleGenerativeAIfrom langchain.chains.question_answering import load_qa_chainfrom langchain.prompts import PromptTemplate# --- Get API key from Hugging Face Secrets ---# In Hugging Face Spaces, set this in Settings -> Repository secretsGOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY", "")# Use temporary directory for Hugging Face SpacesTEMP_DIR = tempfile.gettempdir()FAISS_INDEX_PATH = os.path.join(TEMP_DIR, "faiss_index")def get_pdf_text(pdf_docs):text = ""for pdf in pdf_docs:11 unmodified linesdef get_vector_store(text_chunks, api_key):embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001", google_api_key=api_key)vector_store = FAISS.from_texts(text_chunks, embedding=embeddings)vector_store.save_local(FAISS_INDEX_PATH)def get_conversational_chain(api_key):prompt_template = """5 unmodified lines{question}Answer:"""model = ChatGoogleGenerativeAI(model="gemini-2.0-flash-exp", temperature=0, google_api_key=api_key)prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)return chaindef user_input(user_question, api_key):embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001", google_api_key=api_key)new_db = FAISS.load_local(FAISS_INDEX_PATH, embeddings, allow_dangerous_deserialization=True)docs = new_db.similarity_search(user_question)chain = get_conversational_chain(api_key)response = chain({"input_documents": docs, "question": user_question}, return_only_outputs=True)st.write("Reply: ", response["output_text"])def main():st.set_page_config(page_title="Chat PDF", page_icon="📄")st.header("📚 RAG Chat with PDF - Gemini 2.0")st.markdown("---")# Initialize session stateif "api_entered" not in st.session_state:st.session_state["api_entered"] = Falseif "pdf_processed" not in st.session_state:st.session_state["pdf_processed"] = False# Check for API keyapi_key = GOOGLE_API_KEY# STEP 1: API Key handlingif not st.session_state["api_entered"]:if not api_key:st.warning(" Google API Key not found in environment variables.")st.info("Please add GOOGLE_API_KEY to your Hugging Face Space secrets or enter it below.")user_api_key = st.text_input("Enter your Gemini API key", type="password", help="Get your API key from https://makersuite.google.com/app/apikey")if st.button("Continue", type="primary") and user_api_key:st.session_state["user_api_key"] = user_api_keyst.session_state["api_entered"] = Truest.rerun()st.stop()else:st.session_state["user_api_key"] = api_keyst.session_state["api_entered"] = Trueapi_key = st.session_state.get("user_api_key", "")# STEP 2: Upload PDF(s)if not st.session_state["pdf_processed"]:st.subheader("📤 Step 1: Upload your PDF file(s)")pdf_docs = st.file_uploader("Upload PDF files",accept_multiple_files=True,type=['pdf'],help="Select one or more PDF files to analyze")if st.button("Submit & Process PDFs", type="primary", disabled=not pdf_docs):if pdf_docs:with st.spinner("Processing PDFs... This may take a moment."):try:raw_text = get_pdf_text(pdf_docs)if not raw_text.strip():st.error(" No text could be extracted from the PDF(s). Please check your files.")st.stop()text_chunks = get_text_chunks(raw_text)get_vector_store(text_chunks, api_key)st.session_state["pdf_processed"] = Truest.success(" PDFs processed successfully! You can now ask questions.")st.rerun()except Exception as e:st.error(f" Error processing PDFs: {str(e)}")st.stop()else:st.error("Please upload at least one PDF file.")if not pdf_docs:st.info(" Please upload one or more PDF files to get started.")st.stop()# STEP 3: Ask questionsst.subheader(" Step 2: Ask questions about your PDFs")# Add a reset buttoncol1, col2 = st.columns([3, 1])with col2:if st.button(" Upload New PDFs"):st.session_state["pdf_processed"] = Falsest.rerun()# Question inputuser_question = st.text_input("Ask a question about your uploaded PDFs",placeholder="e.g., What are the main topics discussed in the document?",help="The AI will only answer based on the content of your uploaded PDFs")if user_question:with st.spinner("Searching for answer..."):try:user_input(user_question, api_key)except Exception as e:st.error(f" Error getting answer: {str(e)}")# Add footerst.markdown("---")st.markdown("""<div style='text-align: center'><small>Built with Streamlit, LangChain, and Google Gemini 2.0</small></div>""",unsafe_allow_html=True)if __name__ == "__main__":main()
app.py+83-26