Harrison/add source column (#1784)

Co-authored-by: Brian Graham <46691715+briangrahamww@users.noreply.github.com>
Co-authored-by: briangrahamww <brian.graham@ww.com>
This commit is contained in:
Harrison Chase 2023-03-19 10:32:13 -07:00 committed by GitHub
parent 262d4cb9a8
commit 7de2ada3ea
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 96 additions and 43 deletions

File diff suppressed because one or more lines are too long

View File

@ -11,6 +11,13 @@ class CSVLoader(BaseLoader):
Each document represents one row of the CSV file. Every row is converted into a Each document represents one row of the CSV file. Every row is converted into a
key/value pair and outputted to a new line in the document's page_content. key/value pair and outputted to a new line in the document's page_content.
The source for each document loaded from csv is set to the value of the
`file_path` argument for all doucments by default.
You can override this by setting the `source_column` argument to the
name of a column in the CSV file.
The source of each document will then be set to the value of the column
with the name specified in `source_column`.
Output Example: Output Example:
.. code-block:: txt .. code-block:: txt
@ -19,8 +26,14 @@ class CSVLoader(BaseLoader):
column3: value3 column3: value3
""" """
def __init__(self, file_path: str, csv_args: Optional[Dict] = None): def __init__(
self,
file_path: str,
source_column: Optional[str] = None,
csv_args: Optional[Dict] = None,
):
self.file_path = file_path self.file_path = file_path
self.source_column = source_column
if csv_args is None: if csv_args is None:
self.csv_args = { self.csv_args = {
"delimiter": ",", "delimiter": ",",
@ -35,13 +48,13 @@ class CSVLoader(BaseLoader):
with open(self.file_path, newline="") as csvfile: with open(self.file_path, newline="") as csvfile:
csv = DictReader(csvfile, **self.csv_args) # type: ignore csv = DictReader(csvfile, **self.csv_args) # type: ignore
for i, row in enumerate(csv): for i, row in enumerate(csv):
docs.append( content = "\n".join(f"{k.strip()}: {v.strip()}" for k, v in row.items())
Document( if self.source_column is not None:
page_content="\n".join( source = row[self.source_column]
f"{k.strip()}: {v.strip()}" for k, v in row.items() else:
), source = self.file_path
metadata={"source": self.file_path, "row": i}, metadata = {"source": source, "row": i}
) doc = Document(page_content=content, metadata=metadata)
) docs.append(doc)
return docs return docs