|
|
|
@ -1,8 +1,10 @@
|
|
|
|
|
import csv
|
|
|
|
|
from io import TextIOWrapper
|
|
|
|
|
from typing import Any, Dict, List, Optional
|
|
|
|
|
|
|
|
|
|
from langchain.docstore.document import Document
|
|
|
|
|
from langchain.document_loaders.base import BaseLoader
|
|
|
|
|
from langchain.document_loaders.helpers import detect_file_encodings
|
|
|
|
|
from langchain.document_loaders.unstructured import (
|
|
|
|
|
UnstructuredFileLoader,
|
|
|
|
|
validate_unstructured_version,
|
|
|
|
@ -36,6 +38,7 @@ class CSVLoader(BaseLoader):
|
|
|
|
|
source_column: Optional[str] = None,
|
|
|
|
|
csv_args: Optional[Dict] = None,
|
|
|
|
|
encoding: Optional[str] = None,
|
|
|
|
|
autodetect_encoding: bool = False,
|
|
|
|
|
):
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
@ -46,33 +49,58 @@ class CSVLoader(BaseLoader):
|
|
|
|
|
csv_args: A dictionary of arguments to pass to the csv.DictReader.
|
|
|
|
|
Optional. Defaults to None.
|
|
|
|
|
encoding: The encoding of the CSV file. Optional. Defaults to None.
|
|
|
|
|
autodetect_encoding: Whether to try to autodetect the file encoding.
|
|
|
|
|
"""
|
|
|
|
|
self.file_path = file_path
|
|
|
|
|
self.source_column = source_column
|
|
|
|
|
self.encoding = encoding
|
|
|
|
|
self.csv_args = csv_args or {}
|
|
|
|
|
self.autodetect_encoding = autodetect_encoding
|
|
|
|
|
|
|
|
|
|
def load(self) -> List[Document]:
|
|
|
|
|
"""Load data into document objects."""
|
|
|
|
|
|
|
|
|
|
docs = []
|
|
|
|
|
with open(self.file_path, newline="", encoding=self.encoding) as csvfile:
|
|
|
|
|
csv_reader = csv.DictReader(csvfile, **self.csv_args) # type: ignore
|
|
|
|
|
for i, row in enumerate(csv_reader):
|
|
|
|
|
content = "\n".join(f"{k.strip()}: {v.strip()}" for k, v in row.items())
|
|
|
|
|
try:
|
|
|
|
|
source = (
|
|
|
|
|
row[self.source_column]
|
|
|
|
|
if self.source_column is not None
|
|
|
|
|
else self.file_path
|
|
|
|
|
)
|
|
|
|
|
except KeyError:
|
|
|
|
|
raise ValueError(
|
|
|
|
|
f"Source column '{self.source_column}' not found in CSV file."
|
|
|
|
|
)
|
|
|
|
|
metadata = {"source": source, "row": i}
|
|
|
|
|
doc = Document(page_content=content, metadata=metadata)
|
|
|
|
|
docs.append(doc)
|
|
|
|
|
try:
|
|
|
|
|
with open(self.file_path, newline="", encoding=self.encoding) as csvfile:
|
|
|
|
|
docs = self.__read_file(csvfile)
|
|
|
|
|
except UnicodeDecodeError as e:
|
|
|
|
|
if self.autodetect_encoding:
|
|
|
|
|
detected_encodings = detect_file_encodings(self.file_path)
|
|
|
|
|
for encoding in detected_encodings:
|
|
|
|
|
try:
|
|
|
|
|
with open(
|
|
|
|
|
self.file_path, newline="", encoding=encoding.encoding
|
|
|
|
|
) as csvfile:
|
|
|
|
|
docs = self.__read_file(csvfile)
|
|
|
|
|
break
|
|
|
|
|
except UnicodeDecodeError:
|
|
|
|
|
continue
|
|
|
|
|
else:
|
|
|
|
|
raise RuntimeError(f"Error loading {self.file_path}") from e
|
|
|
|
|
except Exception as e:
|
|
|
|
|
raise RuntimeError(f"Error loading {self.file_path}") from e
|
|
|
|
|
|
|
|
|
|
return docs
|
|
|
|
|
|
|
|
|
|
def __read_file(self, csvfile: TextIOWrapper) -> List[Document]:
|
|
|
|
|
docs = []
|
|
|
|
|
csv_reader = csv.DictReader(csvfile, **self.csv_args) # type: ignore
|
|
|
|
|
for i, row in enumerate(csv_reader):
|
|
|
|
|
content = "\n".join(f"{k.strip()}: {v.strip()}" for k, v in row.items())
|
|
|
|
|
try:
|
|
|
|
|
source = (
|
|
|
|
|
row[self.source_column]
|
|
|
|
|
if self.source_column is not None
|
|
|
|
|
else self.file_path
|
|
|
|
|
)
|
|
|
|
|
except KeyError:
|
|
|
|
|
raise ValueError(
|
|
|
|
|
f"Source column '{self.source_column}' not found in CSV file."
|
|
|
|
|
)
|
|
|
|
|
metadata = {"source": source, "row": i}
|
|
|
|
|
doc = Document(page_content=content, metadata=metadata)
|
|
|
|
|
docs.append(doc)
|
|
|
|
|
|
|
|
|
|
return docs
|
|
|
|
|
|
|
|
|
|