-
Notifications
You must be signed in to change notification settings - Fork 29
1558 csv data reader #1640
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
alexfurmenkov
wants to merge
27
commits into
main
Choose a base branch
from
1558-csv-data-reader
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
1558 csv data reader #1640
Changes from all commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
9f5273b
#1558 WIP: csv readers
alexfurmenkov c791d7c
#1558 csv metadata reader and tables filtering
alexfurmenkov 1490237
#1558 example files
alexfurmenkov 83d2704
#1558 moved csv metadata reader
alexfurmenkov 4cbb541
Merge branch 'main' into 1558-csv-data-reader
alexfurmenkov 8098eb4
#1558 unit tests for dataset filtering
alexfurmenkov 514b147
#1558 unit tests for dataset readers
alexfurmenkov 155a236
#1558 regression and changes in metadata reader logic to preserve data
alexfurmenkov b3e8974
Merge branch 'main' into 1558-csv-data-reader
alexfurmenkov c351222
#1558 added envvar options for [-r, -er, -lr, -ss, -v, -s, -l, -dxp, …
alexfurmenkov 21b0d3e
#1558 added envvar option for -ct and -dv parameters.
alexfurmenkov 695e1da
Merge branch 'main' into 1558-csv-data-reader
RamilCDISC 0fc3bb1
Merge branch 'main' into 1558-csv-data-reader
RamilCDISC d38fe58
#1558 error handling while reading CSV
alexfurmenkov 43a083f
#1654 InvalidCSVFormat renamed to InvalidCSVFile
alexfurmenkov eb1cca9
#1558 added dotenv load from dataset path or path to datasets
alexfurmenkov cbca55e
Merge branch 'main' into 1558-csv-data-reader
alexfurmenkov 6dbad2e
#1558 returned -s and -v as required
alexfurmenkov 3ce61b5
#1558 PR fixes
alexfurmenkov b2ee46a
#1558 fixed csv tests
alexfurmenkov 51b7fef
Merge branch 'refs/heads/main' into 1558-csv-data-reader
alexfurmenkov 33c2bc4
#1558 -dp csv handling improved - errors on multiple tables.csv, fixe…
alexfurmenkov f3567fa
#1558 added cli arguments for tables.csv and variables.csv, .env paths.
alexfurmenkov 14afc1b
#1558 added kwargs to dataset metadata readers. fixed README.md
alexfurmenkov 2126df6
Merge branch 'refs/heads/main' into 1558-csv-data-reader
alexfurmenkov 4876aef
#1558 added positional arguments to test data
alexfurmenkov d863b8a
Merge branch 'refs/heads/main' into 1558-csv-data-reader
alexfurmenkov File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -8,3 +8,4 @@ class DataFormatTypes(BaseEnum): | |
| USDM = "USDM" | ||
| XLSX = "XLSX" | ||
| XPT = "XPT" | ||
| CSV = "CSV" | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -29,5 +29,7 @@ | |
| "max_report_rows", | ||
| "max_errors_per_rule", | ||
| "encoding", | ||
| "variables_csv_path", | ||
| "tables_csv_path", | ||
| ], | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,183 @@ | ||
| import logging | ||
| from datetime import datetime | ||
| from pathlib import Path | ||
|
|
||
| import pandas as pd | ||
|
|
||
| from cdisc_rules_engine.constants import DEFAULT_ENCODING | ||
|
|
||
|
|
||
| class DatasetCSVMetadataReader: | ||
| def __init__( | ||
| self, | ||
| file_path: str, | ||
| file_name: str, | ||
| encoding: str = DEFAULT_ENCODING, | ||
| variables_csv_path: str = None, | ||
| tables_csv_path: str = None, | ||
| **kwargs, | ||
| ): | ||
| self.file_path = file_path | ||
| self.file_name = file_name | ||
| self.encoding = encoding | ||
| self.variables_csv_path = ( | ||
| Path(variables_csv_path) | ||
| if variables_csv_path | ||
| else Path(self.file_path).parent / "variables.csv" | ||
| ) | ||
| self.tables_csv_path = ( | ||
| Path(tables_csv_path) | ||
| if tables_csv_path | ||
| else Path(self.file_path).parent / "tables.csv" | ||
| ) | ||
|
|
||
| def read(self) -> dict: | ||
| dataset_name = Path(self.file_name).stem.lower() | ||
|
|
||
| if not self.variables_csv_path.exists(): | ||
| logger = logging.getLogger("validator") | ||
| logger.info("No variables file found for %s", dataset_name) | ||
| variables_meta = {} | ||
| else: | ||
| variables_meta = self.__get_variable_metadata( | ||
| dataset_name, self.variables_csv_path | ||
| ) | ||
|
|
||
| metadata = { | ||
| "dataset_name": dataset_name.upper(), | ||
| "dataset_modification_date": datetime.fromtimestamp( | ||
| Path(self.file_path).stat().st_mtime | ||
| ).isoformat(), | ||
| "adam_info": { | ||
| "categorization_scheme": {}, | ||
| "w_indexes": {}, | ||
| "period": {}, | ||
| "selection_algorithm": {}, | ||
| }, | ||
| } | ||
| metadata.update(variables_meta) | ||
| metadata.update(self.__data_meta()) | ||
| metadata.update(self.__dataset_label()) | ||
| return metadata | ||
|
|
||
| def __get_variable_metadata( | ||
| self, dataset_name: str, variables_file_path: Path | ||
| ) -> dict: | ||
| logger = logging.getLogger("validator") | ||
| try: | ||
| meta_df = pd.read_csv(variables_file_path, encoding=self.encoding) | ||
| except (UnicodeDecodeError, UnicodeError) as e: | ||
| logger.error( | ||
| f"Could not decode CSV file {variables_file_path} with {self.encoding} encoding: {e}. " | ||
| f"Please specify the correct encoding using the -e flag." | ||
| ) | ||
| return {} | ||
| except Exception as e: | ||
| logger.error("Error reading CSV file %s. %s", self.file_path, e) | ||
| return {} | ||
|
|
||
| meta_df["dataset"] = meta_df["dataset"].apply( | ||
| lambda x: Path(str(x)).stem.lower() | ||
| ) | ||
|
|
||
| dataset_meta_df = meta_df[meta_df["dataset"] == dataset_name] | ||
|
|
||
| if dataset_meta_df.empty: | ||
| logger = logging.getLogger("validator") | ||
| logger.info("No dataset metadata found for %s", dataset_name) | ||
| return {} | ||
|
|
||
| variable_names = dataset_meta_df["variable"].tolist() | ||
| variable_labels = dataset_meta_df["label"].tolist() | ||
|
|
||
| variable_name_to_label_map = dict(zip(variable_names, variable_labels)) | ||
| variable_name_to_data_type_map = dict( | ||
| zip(variable_names, dataset_meta_df["type"]) | ||
| ) | ||
| variable_name_to_size_map = { | ||
| var: (int(length) if pd.notna(length) else None) | ||
| for var, length in zip(variable_names, dataset_meta_df["length"]) | ||
| } | ||
| return { | ||
| "variable_names": variable_names, | ||
| "variable_labels": variable_labels, | ||
| "variable_formats": [""] * len(variable_names), | ||
| "variable_name_to_label_map": variable_name_to_label_map, | ||
| "variable_name_to_data_type_map": variable_name_to_data_type_map, | ||
| "variable_name_to_size_map": variable_name_to_size_map, | ||
| "number_of_variables": len(variable_names), | ||
| } | ||
|
|
||
| def __dataset_label(self) -> dict: | ||
| logger = logging.getLogger("validator") | ||
|
|
||
| if not self.tables_csv_path.exists(): | ||
| return {} | ||
|
|
||
| try: | ||
| tables_df = pd.read_csv(self.tables_csv_path, encoding=self.encoding) | ||
| except (UnicodeDecodeError, UnicodeError) as e: | ||
| logger.error( | ||
| f"\n Error reading CSV from: {self.file_path}" | ||
| f"\n Failed to decode with {self.encoding} encoding: {e}" | ||
| f"\n Please specify the correct encoding using the -e flag." | ||
| ) | ||
| return {} | ||
| except Exception as e: | ||
| logger.error("Error reading CSV file %s. %s", self.file_path, e) | ||
| return {} | ||
|
|
||
| if "Filename" not in tables_df.columns or "Label" not in tables_df.columns: | ||
| return {} | ||
|
|
||
| tables_df["dataset"] = tables_df["Filename"].apply( | ||
| lambda x: Path(str(x)).stem.lower() | ||
| ) | ||
|
|
||
| current_dataset = Path(self.file_name).stem.lower() | ||
| match = tables_df[tables_df["dataset"] == current_dataset] | ||
|
|
||
| if match.empty: | ||
| return {} | ||
|
|
||
| return {"dataset_label": str(match.iloc[0]["Label"])} | ||
|
|
||
| def __data_meta(self): | ||
| logger = logging.getLogger("validator") | ||
| result = { | ||
| "dataset_length": 0, | ||
| "first_record": {}, | ||
| } | ||
| try: | ||
| first_row_df = pd.read_csv(self.file_path, encoding=self.encoding, nrows=1) | ||
| except (UnicodeDecodeError, UnicodeError) as e: | ||
| logger.error( | ||
| f"\n Error reading CSV from: {self.file_path}" | ||
| f"\n Failed to decode with {self.encoding} encoding: {e}" | ||
| f"\n Please specify the correct encoding using the -e flag." | ||
| ) | ||
| return result | ||
| except Exception as e: | ||
| logger.error("Error reading CSV file %s. %s", self.file_path, e) | ||
| return result | ||
|
|
||
| if not first_row_df.empty: | ||
| result["first_record"] = ( | ||
| first_row_df.iloc[0].fillna("").astype(str).to_dict() | ||
| ) | ||
|
|
||
| try: | ||
| with open(self.file_path, encoding=self.encoding) as f: | ||
| result["dataset_length"] = max( | ||
| sum(1 for _ in f) - 1, 0 | ||
| ) # subtract header | ||
| except (UnicodeDecodeError, UnicodeError) as e: | ||
| logger.error( | ||
| f"\n Error reading CSV from: {self.file_path}" | ||
| f"\n Failed to decode with {self.encoding} encoding: {e}" | ||
| f"\n Please specify the correct encoding using the -e flag." | ||
| ) | ||
| except Exception as e: | ||
| logger.error("Error reading CSV file %s. %s", self.file_path, e) | ||
|
|
||
| return result |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| import tempfile | ||
|
|
||
| from cdisc_rules_engine.exceptions.custom_exceptions import InvalidCSVFile | ||
| from cdisc_rules_engine.interfaces import DataReaderInterface | ||
| import pandas as pd | ||
|
|
||
|
|
||
| class CSVReader(DataReaderInterface): | ||
| def read(self, data): | ||
| """ | ||
| Function for reading data from a specific file type and returning a | ||
| pandas dataframe of the data. | ||
| """ | ||
| raise NotImplementedError | ||
|
|
||
| def from_file(self, file_path): | ||
| try: | ||
| with open(file_path, "r", encoding=self.encoding) as fp: | ||
| data = pd.read_csv(fp, sep=",", header=0, index_col=False) | ||
| return data | ||
| except (UnicodeDecodeError, UnicodeError) as e: | ||
| raise InvalidCSVFile( | ||
| f"\n Error reading CSV from: {file_path}" | ||
| f"\n Failed to decode with {self.encoding} encoding: {e}" | ||
| f"\n Please specify the correct encoding using the -e flag." | ||
| ) | ||
| except Exception as e: | ||
| raise InvalidCSVFile( | ||
| f"\n Error reading CSV from: {file_path}" | ||
| f"\n {type(e).__name__}: {e}" | ||
| ) | ||
|
|
||
| def to_parquet(self, file_path: str) -> tuple[int, str]: | ||
| temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".parquet") | ||
|
|
||
| dataset = pd.read_csv(file_path, chunksize=20000, encoding=self.encoding) | ||
|
|
||
| created = False | ||
| num_rows = 0 | ||
|
|
||
| for chunk in dataset: | ||
| num_rows += len(chunk) | ||
|
|
||
| if not created: | ||
| chunk.to_parquet(temp_file.name, engine="fastparquet") | ||
| created = True | ||
| else: | ||
| chunk.to_parquet(temp_file.name, engine="fastparquet", append=True) | ||
|
|
||
| if not created: | ||
| empty_df = pd.read_csv(file_path, nrows=0, encoding=self.encoding) | ||
| empty_df.to_parquet(temp_file.name, engine="fastparquet") | ||
|
|
||
| return num_rows, temp_file.name | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This function always returns a file path, but file is only written when csv is not empty. An empty csv can cause to return path to a file that is not yet created. It may cause some downstream errors.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
added empty parquet file creation in case when csv was empty.
or should we raise value error in this scenario? should I also fix it in xpt reader?