Existing chroma Vector DB not getting deleted

I’m creating a project where a user uploads a PDF, which creates a chroma vector db, and the user receives the output. The issue arises when the user uploads a second PDF: the system should delete the existing vector db and create a new one. However, I keep running into a ‘PermissionError: [WinError 32] The process cannot access the file because it is being used by another process’ error. It appears that the file is still in use by another process, and I’m unable to delete the old vector db as needed. How can I resolve this issue to ensure the file is properly closed or released before deletion?

After researching, I found that Chroma doesn’t have a built-in function to close or delete the vector db. I’ve tried several solutions, including force deletion and using the psutil library to terminate processes, but none have worked so far.It would be really helpful if anyone could help me on this.

This is the code below :
"from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import FileResponse
from langchain.document_loaders import PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.vectorstores.chroma import Chroma
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_openai import ChatOpenAI
from langchain.chains.combine_documents import create_stuff_documents_chain
from langchain.chains import create_retrieval_chain
from langchain.prompts import PromptTemplate
import os
import shutil
import tempfile
import time
from dotenv import load_dotenv

load_dotenv()

app = FastAPI()

# Folders
OUTPUT_DIR = "output_dir"
PERSIST_DIR = "vector_db"

os.makedirs(OUTPUT_DIR, exist_ok=True)
os.makedirs(PERSIST_DIR, exist_ok=True)

OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")

# 
def process_pdf(pdf_path: str) -> str:
    # Check if a vector DB already exists, and delete it if found
    if os.path.exists(PERSIST_DIR):
        shutil.rmtree(PERSIST_DIR)
        os.makedirs(PERSIST_DIR)

    # Load the PDF document
    loader = PyPDFLoader(pdf_path)
    pages = loader.load()

    # Split the document into chunks
    splitter = RecursiveCharacterTextSplitter(
        chunk_size=200,  
        chunk_overlap=50  
    )
    chunks = splitter.split_documents(pages)

    # Initialize embeddings and vector store
    embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
    vectorstore = Chroma.from_documents(chunks, embeddings, persist_directory=PERSIST_DIR)

    # Initialize retriever and LLM
    retriever = vectorstore.as_retriever(search_kwargs={"k": 1})
    llm = ChatOpenAI(
        model="gpt-4o",
        temperature=0.9,
        max_tokens=500,
        openai_api_key=OPENAI_API_KEY
    )

    # Create prompt template and retrieval chain
    template = """
    Act as an experienced document reviewer. Your task is to give a clear concise summary of the                 document.
    context: {context}
    input: {input}
    answer:
    """
    prompt = PromptTemplate.from_template(template)
    combine_docs_chain = create_stuff_documents_chain(llm, prompt)
    retrieval_chain = create_retrieval_chain(retriever, combine_docs_chain)

    # Generate responses from the LLM
    response_1 = retrieval_chain.invoke({"input": "Give me summary of the document."})
    time.sleep(5)

    # Generate a unique filename by incrementing a number suffix
    base_filename = "Output"
    file_number = 1

    while os.path.exists(f"{OUTPUT_DIR}/{base_filename}_{file_number}.txt"):
        file_number += 1

    filename = f"{OUTPUT_DIR}/{base_filename}_{file_number}.txt"
    
    # Save responses to a text file 
    with open(filename, "w", encoding="utf-8") as file:
        file.write("Output:nn")

        file.write("Summary:n")
        file.write(response_1["answer"] + "nn")
    return filename  


# API
@app.post("/process-pdf/")
async def process_pdf_file(file: UploadFile = File(...)):
    try:
        # Use a temporary directory to store the uploaded PDF file
        with tempfile.TemporaryDirectory() as temp_dir:
            temp_pdf_path = os.path.join(temp_dir, file.filename)

            # Save the uploaded PDF temporarily
            with open(temp_pdf_path, "wb") as temp_file:
                shutil.copyfileobj(file.file, temp_file)

            # Process the PDF and generate the report
            result_file_path = process_pdf(temp_pdf_path)

        # Return the generated text file as a response
        return FileResponse(result_file_path, filename=os.path.basename(result_file_path))

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

New contributor

Aachal Gupta is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật