|
| 1 | +import logging |
| 2 | +from functools import partial |
| 3 | +from typing import Any, Dict, List, Literal, Optional, Union |
| 4 | + |
| 5 | +import narwhals.stable.v1 as nw |
| 6 | +from haystack import Document, component |
| 7 | + |
| 8 | +from dataframes_haystack.components.converters._utils import ( |
| 9 | + FileFormat, |
| 10 | + ReaderFunc, |
| 11 | + frame_to_documents, |
| 12 | + get_pandas_readers_map, |
| 13 | + get_polars_readers_map, |
| 14 | + read_with_select, |
| 15 | +) |
| 16 | + |
| 17 | +logger = logging.getLogger(__name__) |
| 18 | + |
| 19 | +Backends = Literal["pandas", "polars"] |
| 20 | + |
| 21 | + |
| 22 | +@component |
| 23 | +class DataFrameFileToDocument: |
| 24 | + """Reads files and converts their data in Documents. |
| 25 | +
|
| 26 | + Usage example: |
| 27 | + ```python |
| 28 | + from dataframes_haystack.components.converters import DataFrameFileToDocument |
| 29 | +
|
| 30 | + converter = DataFrameFileToDocument(content_column="text_str") |
| 31 | + results = converter.run(files=["file1.csv", "file2.csv"]) |
| 32 | + documents = results["documents"] |
| 33 | + print(documents[0].content) |
| 34 | + ``` |
| 35 | + """ |
| 36 | + |
| 37 | + def __init__( |
| 38 | + self, |
| 39 | + content_column: str, |
| 40 | + meta_columns: Union[List[str], None] = None, |
| 41 | + index_column: Union[str, None] = None, |
| 42 | + file_format: FileFormat = "csv", |
| 43 | + read_kwargs: Optional[Dict[str, Any]] = None, |
| 44 | + backend: Backends = "polars", |
| 45 | + ) -> None: |
| 46 | + """Create a DataFrameFileToDocument component. |
| 47 | +
|
| 48 | + Args: |
| 49 | + content_column: The name of the DataFrame column that contains the text content. |
| 50 | + meta_columns: Optional list of names of the DataFrame columns that contain metadata. |
| 51 | + index_column: The name of the DataFrame column that contains the index. |
| 52 | + file_format: The format of the files to read. |
| 53 | + read_kwargs: Optional keyword arguments to pass to the file reader function. |
| 54 | + backend: The backend to use for reading the files. |
| 55 | + """ |
| 56 | + self.content_column = content_column |
| 57 | + self.meta_columns = meta_columns or [] |
| 58 | + self.index_column = index_column |
| 59 | + self.file_format = file_format |
| 60 | + self.read_kwargs = read_kwargs or {} |
| 61 | + self.backend = backend |
| 62 | + if self.backend not in ["pandas", "polars"]: |
| 63 | + msg = f"Unsupported backend: {self.backend}" |
| 64 | + raise ValueError(msg) |
| 65 | + self._reader_function = self._get_reader_function() |
| 66 | + |
| 67 | + def _get_reader_function(self) -> ReaderFunc: |
| 68 | + file_format_mapping = get_pandas_readers_map() if self.backend == "pandas" else get_polars_readers_map() |
| 69 | + reader_function = file_format_mapping.get(self.file_format) |
| 70 | + if reader_function: |
| 71 | + return reader_function |
| 72 | + msg = f"Unsupported file format for {self.backend} backend: {self.file_format}" |
| 73 | + raise ValueError(msg) |
| 74 | + |
| 75 | + def _run_read(self, file_paths: List[str]) -> nw.DataFrame: |
| 76 | + selected_columns = [self.index_column, self.content_column, *self.meta_columns] |
| 77 | + selected_columns = [col for col in selected_columns if col is not None] |
| 78 | + read_func = partial(self._reader_function, **self.read_kwargs) |
| 79 | + df_list = [read_with_select(read_func, file_path=path, columns_subset=selected_columns) for path in file_paths] |
| 80 | + return nw.concat(df_list, how="vertical") |
| 81 | + |
| 82 | + @component.output_types(documents=List[Document]) |
| 83 | + def run( |
| 84 | + self, |
| 85 | + file_paths: List[str], |
| 86 | + meta: Union[Dict[str, Any], List[Dict[str, Any]], None] = None, |
| 87 | + ) -> Dict[str, List[Document]]: |
| 88 | + """Reads files and converts their data in Documents. |
| 89 | +
|
| 90 | + Args: |
| 91 | + file_paths: List of file paths to read. |
| 92 | + meta: |
| 93 | + Optional metadata to attach to the Documents. |
| 94 | + This value can be either a dictionary or a list of dictionaries. |
| 95 | + If it's a dictionary, its content is added to the metadata of all produced Documents. |
| 96 | + If it's a list, the length of the list must match the number of rows in the DataFrame, |
| 97 | + because the two lists will be zipped. |
| 98 | +
|
| 99 | + Returns: |
| 100 | + A dictionary with the following keys: |
| 101 | + - `documents`: Created Documents |
| 102 | + """ |
| 103 | + df = self._run_read(file_paths) |
| 104 | + documents = frame_to_documents( |
| 105 | + df, |
| 106 | + content_column=self.content_column, |
| 107 | + meta_columns=self.meta_columns, |
| 108 | + index_column=self.index_column, |
| 109 | + extra_metadata=meta, |
| 110 | + ) |
| 111 | + |
| 112 | + return {"documents": documents} |
0 commit comments