How to use DirectoryLoader in langchain to load pdf and store them in weaviate, but also to split the documents up so they don't become too large
Assistant
User
do it with DirectoryLoader
Assistant
Langchain is a flexible framework for creating AI-powered applications, particularly involving language models. To use the DirectoryLoader in Langchain to load PDFs and store them in Weaviate, while also splitting the documents so they don't become too large, you would typically need to do the following steps:
Install the required packages if you haven't already done that:
bash
pip install langchain weaviate-client pdfplumber
Define a PDF parser that can handle the loading and splitting of documents.
Use the DirectoryLoader to read the documents from your directory.
Configure a Weaviate client to connect with your Weaviate instance.
Load the documents into Weaviate, ensuring that each part fits within your desired size limit.
An example code snippet for using DirectoryLoader, parsing PDFs, and storing them into Weaviate while splitting documents is shown below:
python
import weaviate
from weaviate.tools import TheBatcher
import os
import pdfplumber
# Load your PDF and split it up
def split_pdf(pdf_path, max_length=5000):
with pdfplumber.open(pdf_path) as pdf:
texts = []
text = ""
for page in pdf.pages:
page_text = page.extract_text()
if len(text + page_text) > max_length:
texts.append(text)
text = page_text
else:
text += page_text
texts.append(text) # Last part
return texts
# Replace 'your_weaviate_url' with your actual Weaviate instance URL
client = weaviate.Client("http://your_weaviate_url")
# Assuming you have 'Text' class in your Weaviate schema
batcher = TheBatcher(client, max_batch_size=50)
# Replace '/path/to/pdf/directory' with the actual path to your PDF files
for filename in os.listdir('/path/to/pdf/directory'):
if filename.endswith('.pdf'):
full_path = os.path.join('/path/to/pdf/directory', filename)
parts = split_pdf(full_path)
for i, part in enumerate(parts):
data_object = {
"title": f"{filename} Part {i+1}",
"content": part
}
# Make sure 'Text' is in your schema with 'title' and 'content' properties
batcher.add_data_object(data_object, "Text")
batcher.flush()
In the above code snippet, the split_pdf function is defined to split the PDF into segments not exceeding a length of max_length. This maximum length should be chosen based on the average size of the content that you want to store in Weaviate.
The Weaviate TheBatcher is used to efficiently store multiple entries into Weaviate. It will automatically handle the posting of data to Weaviate in batches of max_batch_size.
This is a basic example, and you will need to modify it, particularly the URL for the Weaviate instance and the schema class you are using to store the PDF content. Make sure that you have already set up the appropriate schema in your Weaviate instance before running this code. If you don't have a Text class, you will need to create one with at least title and content properties to store your PDF content.
Additionally, the pdfplumber library requires that you have the pdftotext utility installed in your system, which may come with the Poppler utils package.
This code demonstrates how to split and load PDFs locally, but Langchain DirectoryLoader and Weaviate specifics could vary, and you might need to make further configurations or adapt the code to fit your specific use case. Always refer to the documentation of the packages you're using for the most accurate and up-to-date information.
The DirectoryLoader is not an actual component from LangChain or Weaviate. It seems that there's a confusion with the concept. What you might be looking for is a custom way to load directories containing PDFs, process them, and store them into Weaviate. Since there is no out-of-the-box DirectoryLoader, you can create a script that functions similarly.
Here's an updated version that would manually handle loading PDF files from a directory, splitting them by size, and then storing them into Weaviate:
python
import weaviate
from pdfplumber import open as open_pdf
import os
# Initialize the Weaviate client
client = weaviate.Client("http://your_weaviate_url")
# Assume schema already exists with a class "Text" with properties "title" and "content"
def split_pdf(pdf_path, max_length=5000):
# Split the PDF file into segments
with open_pdf(pdf_path) as pdf:
texts = []
text = ""
for page in pdf.pages:
page_text = page.extract_text()
if len(text + page_text) > max_length:
texts.append(text)
text = page_text
else:
text += page_text
texts.append(text) # Append any remaining text from the last page
return texts
def store_parts_in_weaviate(file_path, parts):
# Store each part as a separate entry in Weaviate
for i, part in enumerate(parts):
data_object = {
"title": f"{os.path.basename(file_path)} Part {i+1}",
"content": part
}
client.data_object.create(data_object, "Text")
# Directory containing the PDF files
pdf_directory = '/path/to/pdf/directory'
# Loop through each file in the directory
for file_name in os.listdir(pdf_directory):
if file_name.lower().endswith('.pdf'):
full_path = os.path.join(pdf_directory, file_name)
print(f"Processing {full_path}")
pdf_parts = split_pdf(full_path)
store_parts_in_weaviate(full_path, pdf_parts)
This script does manually what you thought DirectoryLoader does (loads PDF files from a directory), splits them using the split_pdf function, and stores each part into Weaviate using the store_parts_in_weaviate function.
Make sure to replace http://your_weaviate_url with the actual URL of your Weaviate instance and update the path /path/to/pdf/directory with the correct path to your directory containing PDF files. Additionally, ensure your Weaviate schema is configured to have a "Text" data class with at least "title" and "content" properties.
Keep in mind the importance of optimizing the max_length parameter according to the capacity of your Weaviate instance and the average size of your documents. The sizes of the parts should be balanced to maintain fast search and retrieval in Weaviate, yet not be too small as to cause fragmentation in the content.