Spaces:
Sleeping
Sleeping
Update app.py
Browse filesHandling deletion of indexes
57 unmodified lines5859606162635 unmodified lines697071727374757677787980818210 unmodified lines939495969798991001011021034 unmodified lines10810911011111211311411511611711811912010 unmodified lines13113213313413513613712 unmodified lines15015115215315415515615715815918 unmodified lines1781791801811821831841851861871881894 unmodified lines1941951961971981992002012022032042052062072082092102112122132142152162172 unmodified lines22022122222322422522622734 unmodified lines26226326426526626726826927027113 unmodified lines28528628728828929057 unmodified lines# Combine base name with unique ID, ensuring total length is under 45 charsreturn f"{base_name}-{unique_id}" # This will be like "docdb-12345678"if not st.session_state.initialized:# Clear everything only on first run or page refreshif os.path.exists("data"):5 unmodified linesst.session_state.retriever = Nonest.session_state.initialized = True# Delete any existing index for this session (in case of page refresh)try:pc = Pinecone(api_key=os.getenv("PINECONE_API_KEY"))index_name = get_session_index_name()if index_name in pc.list_indexes().names():pc.delete_index(index_name)except Exception as e:st.error(f"Error cleaning up old index: {str(e)}")def save_uploaded_file(uploaded_file):"""Save uploaded file to the data directory"""10 unmodified linesif os.path.exists(file_path):return file_pathelse:st.error(f"File not saved: {file_path}")return Noneexcept Exception as e:st.error(f"Error saving file: {str(e)}")return Nonedef process_documents(uploaded_files_dict):4 unmodified linestry:with st.spinner('Processing documents...'):docs = []# Process each filefor filename, file_info in uploaded_files_dict.items():file_path = file_info["path"]if not os.path.exists(file_path):st.error(f"File not found: {file_path}")continueif filename.endswith(".pdf"):10 unmodified linesdocs.extend(file_doc)if not docs:st.error("No documents were successfully processed")return False# Split documents12 unmodified linesindex_name = get_session_index_name()try:# Recreate the indexif index_name in pc.list_indexes().names():pc.delete_index(index_name)pc.create_index(name=index_name,dimension=512,18 unmodified linesreturn Trueexcept PineconeApiException as e:st.error("File upload failed! Avoid interrupting document processing by uploading or removing files. Kindly refresh the app to continue.")st.session_state.chat_enabled = Falsereturn Falseexcept Exception as e:st.error(f"An error occurred during processing: {str(e)}")st.session_state.chat_enabled = Falsereturn Falsefinally:4 unmodified linesdef format_reranked_docs(pc, retriever, question):"""Rerank documents using Pinecone's reranking model"""relevant_docs = [doc.page_content for doc in retriever.invoke(question) if len(doc.page_content)>5]reranked_docs = pc.inference.rerank(model="pinecone-rerank-v0",query=question,documents=relevant_docs,top_n=3,return_documents=True)final_docs = [d.document.text for d in reranked_docs.data]context = doc2str(final_docs)return contextdef run_chatbot(retriever, pc, llm):"""Run the chatbot with the given components"""# st.markdown("<h4>💬 Chat with your Documents</h4>", unsafe_allow_html=True)# Initialize chat promptprompt = ChatPromptTemplate.from_template("""You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know.2 unmodified lines{context}</context>Important: Don't start revealing context in your responses until its asked. First look at the question and then think if the context is needed to answer this or its a normal question, once you have judged then only answer the question.Answer the following question:{question}""")34 unmodified lines# Add assistant response to chat historyst.session_state.messages.append({"role": "assistant", "content": response})except Exception as e:error_msg = f"An error occurred while processing your question: {str(e)}"with st.chat_message("assistant"):st.error(error_msg)st.session_state.messages.append({"role": "assistant", "content": f"❌ {error_msg}"})def process_and_chat():"""Process documents and handle chat interface"""13 unmodified lines# Check for removed filesfiles_to_remove = set(st.session_state.uploaded_files.keys()) - current_uploaded_filenamesif files_to_remove:for file_name in files_to_remove:# Remove file from session stateif file_name in st.session_state.uploaded_files:57 unmodified lines585960616263646566676869707172735 unmodified lines798081828384858610 unmodified lines9798991001011021031041051061074 unmodified lines11211311411511611711811912012112212312412512612710 unmodified lines13813914014114214314412 unmodified lines15715815916016116218 unmodified lines1811821831841851861871881891901911921931944 unmodified lines1992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332 unmodified lines23623723823924024124224324424524634 unmodified lines28128228328428528628728828929029113 unmodified lines30530630730830931031131257 unmodified lines# Combine base name with unique ID, ensuring total length is under 45 charsreturn f"{base_name}-{unique_id}" # This will be like "docdb-12345678"def cleanup_pinecone_index():"""Clean up existing Pinecone index for the current session"""try:pc = Pinecone(api_key=os.getenv("PINECONE_API_KEY"))index_name = get_session_index_name()if index_name in pc.list_indexes().names():pc.delete_index(index_name)except Exception as e:print(f"Error cleaning up index: {str(e)}") # Log error internallyif not st.session_state.initialized:# Clear everything only on first run or page refreshif os.path.exists("data"):5 unmodified linesst.session_state.retriever = Nonest.session_state.initialized = True# Clean up any existing indexcleanup_pinecone_index()def save_uploaded_file(uploaded_file):"""Save uploaded file to the data directory"""10 unmodified linesif os.path.exists(file_path):return file_pathelse:print(f"File not saved: {file_path}") # Log error internallyreturn Noneexcept Exception as e:print(f"Error saving file: {str(e)}") # Log error internallyreturn Nonedef process_documents(uploaded_files_dict):4 unmodified linestry:with st.spinner('Processing documents...'):# Clean up existing index before processingcleanup_pinecone_index()docs = []# Process each filefor filename, file_info in uploaded_files_dict.items():file_path = file_info["path"]if not os.path.exists(file_path):print(f"File not found: {file_path}") # Log error internallycontinueif filename.endswith(".pdf"):10 unmodified linesdocs.extend(file_doc)if not docs:st.warning("Unable to process the documents. Please try again.")return False# Split documents12 unmodified linesindex_name = get_session_index_name()try:pc.create_index(name=index_name,dimension=512,18 unmodified linesreturn Trueexcept PineconeApiException as e:print(f"Pinecone API error: {str(e)}") # Log error internallyst.warning("Unable to process documents at the moment. Please try again.")st.session_state.chat_enabled = Falsereturn Falseexcept Exception as e:print(f"Processing error: {str(e)}") # Log error internallyst.warning("Unable to process documents at the moment. Please try again.")st.session_state.chat_enabled = Falsereturn Falsefinally:4 unmodified linesdef format_reranked_docs(pc, retriever, question):"""Rerank documents using Pinecone's reranking model"""# Get relevant docs and ensure they're not emptyrelevant_docs = [doc.page_content for doc in retriever.invoke(question) if doc.page_content.strip()]if not relevant_docs:return "I don't have enough context to answer this question."try:# Format documents for rerankingformatted_docs = [{"text": doc} for doc in relevant_docs]reranked_docs = pc.inference.rerank(model="pinecone-rerank-v0",query=question,documents=formatted_docs,top_n=3,return_documents=True)# Extract text from reranked documentsfinal_docs = [d.document["text"] for d in reranked_docs.data]context = "\n\n".join(final_docs)return contextexcept Exception as e:print(f"Error during reranking: {str(e)}") # Log error internally# Fallback to using retrieved docs without rerankingreturn "\n\n".join(relevant_docs[:3])def run_chatbot(retriever, pc, llm):"""Run the chatbot with the given components"""# Initialize chat promptprompt = ChatPromptTemplate.from_template("""You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know.2 unmodified lines{context}</context><important>Don't start revealing context in your responses until its asked. First look at the question and then think if the context is needed to answer this or its a normal question, once you have judged then only answer the question.When there is no context, just respond on your own knowledge as a normal assistant.</important>Answer the following question:{question}""")34 unmodified lines# Add assistant response to chat historyst.session_state.messages.append({"role": "assistant", "content": response})except Exception as e:print(f"Chat error: {str(e)}") # Log error internallywith st.chat_message("assistant"):error_msg = "I'm having trouble processing your question. Please try asking something else."st.markdown(error_msg)st.session_state.messages.append({"role": "assistant", "content": error_msg})def process_and_chat():"""Process documents and handle chat interface"""13 unmodified lines# Check for removed filesfiles_to_remove = set(st.session_state.uploaded_files.keys()) - current_uploaded_filenamesif files_to_remove:# Clean up index when files are removedcleanup_pinecone_index()for file_name in files_to_remove:# Remove file from session stateif file_name in st.session_state.uploaded_files:
app.py+59-37