-
Notifications
You must be signed in to change notification settings - Fork 5
feat(RND-13624): Migrate WithS3File to AWS Data Wrangler
#88
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
Draft
Christos-Hadjinikolis
wants to merge
3
commits into
master
Choose a base branch
from
rnd-13624
base: master
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.
Draft
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,4 +4,4 @@ omit = | |
| *__init__* | ||
|
|
||
| [report] | ||
| fail_under = 85 | ||
| fail_under = 90 | ||
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
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
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 |
|---|---|---|
|
|
@@ -7,10 +7,12 @@ | |
| from threading import Lock | ||
| from typing import Any, MutableMapping | ||
|
|
||
| import pandas as pd # type: ignore | ||
| from fastparquet import ParquetFile, write # type: ignore | ||
| from pyarrow.parquet import read_table, write_table # type: ignore # pylint: disable=no-name-in-module | ||
| import pandas as pd | ||
| from fastparquet import ParquetFile, write | ||
| from magic_logger import logger | ||
| from pyarrow.parquet import read_table, write_table | ||
|
|
||
| # Application Imports | ||
| from dynamicio.config.pydantic import DataframeSchema, LocalBatchDataEnvironment, LocalDataEnvironment | ||
| from dynamicio.mixins import utils | ||
| from dynamicio.mixins.utils import get_file_type_value | ||
|
|
@@ -32,8 +34,10 @@ def _read_from_local(self) -> pd.DataFrame: | |
| - `file_path` | ||
| - `file_type` | ||
|
|
||
| To actually read the file, a method is dynamically invoked by name, using | ||
| "_read_{file_type}_file". | ||
| To actually read the file, a method is dynamically invoked by name, using "_read_{file_type}_file". | ||
|
|
||
| Additional options: | ||
| - single_record: bool: used for json files. If True, treats the file as a single JSON object instead of a list of records. | ||
|
|
||
| Returns: | ||
| DataFrame | ||
|
|
@@ -106,23 +110,49 @@ def _read_csv_file(file_path: str, schema: DataframeSchema, **options: Any) -> p | |
| return pd.read_csv(file_path, **options) | ||
|
|
||
| @staticmethod | ||
| @utils.allow_options(pd.read_json) | ||
| @utils.allow_options([*utils.args_of(pd.read_json), *["single_record"]]) | ||
| def _read_json_file(file_path: str, schema: DataframeSchema, **options: Any) -> pd.DataFrame: | ||
| """Read a json file as a DataFrame using `pd.read_hdf`. | ||
|
|
||
| All `options` are passed directly to `pd.read_hdf`. | ||
|
|
||
| Args: | ||
| file_path: | ||
| options: | ||
| file_path: The path to the json file to be read. | ||
| options: The pandas `read_json` options. | ||
|
|
||
| Returns: | ||
| DataFrame | ||
| DataFrame: The dataframe read from the json file. | ||
| """ | ||
| df = pd.read_json(file_path, **options) | ||
| columns = [column for column in df.columns.to_list() if column in schema.column_names] | ||
| df = df[columns] | ||
| return df | ||
| user_orient = options.pop("orient", None) | ||
| user_lines = options.pop("lines", None) | ||
|
|
||
| if user_orient is not None and user_orient != "records": | ||
| raise ValueError("[local-json] Unsupported orient='{user_orient}'. Only 'records' orientation is supported.") | ||
|
|
||
| if user_lines is not None and user_lines is not False: | ||
| logger.warning("[local-json-read] Overriding lines=%s with lines=False for consistency with aws-wrangler expectations.", user_lines) | ||
|
|
||
| if options.get("convert_dates") is True: | ||
| logger.warning("[local-json-read] Ignoring 'convert_dates=True'. Handle datetime parsing post-read.") | ||
| options.pop("convert_dates", None) | ||
|
|
||
| is_single_record = options.pop("single_record", False) | ||
| df = pd.read_json(file_path, orient="records", convert_dates=False, lines=False, **options) | ||
|
|
||
| # π§Ό Check if this is a single-record json file | ||
| if is_single_record: | ||
| # Re-wrap as single dict row β i.e., rehydrate the record | ||
| df = pd.DataFrame([{df.columns[0]: dict(zip(df.index, df.iloc[:, 0]))}]) | ||
| elif ( | ||
| df.shape[1] == 1 | ||
| and df.columns.dtype == "object" | ||
| and df.index.dtype == "object" | ||
| and all(isinstance(i, str) for i in df.index) | ||
| and all(isinstance(v, (str, int, float, bool, type(None))) for v in df.iloc[:, 0]) | ||
| ): | ||
| logger.warning("[local-json-read] File appears to be a single-record JSON object. Pass 'single_record=True' in options to handle this case.") | ||
|
Comment on lines
+142
to
+153
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Necessary for alignment with |
||
|
|
||
| return df[[col for col in df.columns if col in schema.column_names]] | ||
|
|
||
| @staticmethod | ||
| def _read_parquet_file(file_path: str, schema: DataframeSchema, **options: Any) -> pd.DataFrame: | ||
|
|
@@ -192,7 +222,10 @@ def _write_csv_file(df: pd.DataFrame, file_path: str, **options: Any): | |
| @staticmethod | ||
| @utils.allow_options(pd.DataFrame.to_json) | ||
| def _write_json_file(df: pd.DataFrame, file_path: str, **options: Any): | ||
| """Write a dataframe as a json file using `df.to_json`. | ||
| """Writes a JSON file using 'records' orientation with lines=True. | ||
|
|
||
| If the user provides an unsupported `orient`, raise an error. | ||
| This mirrors wr.s3.to_json and guarantees tabular consistency. | ||
|
|
||
| All `options` are passed directly to `df.to_json`. | ||
|
|
||
|
|
@@ -201,6 +234,16 @@ def _write_json_file(df: pd.DataFrame, file_path: str, **options: Any): | |
| file_path: The location where the file needs to be written. | ||
| options: Options relative to writing a json file. | ||
| """ | ||
| user_orient = options.pop("orient", None) | ||
| user_lines = options.pop("lines", None) | ||
|
|
||
| if user_orient is not None and user_orient != "records": | ||
| raise ValueError( | ||
| f"[local-json] Unsupported orient='{user_orient}'. Only 'records' orientation is supported for tabular output (imposed for aws-wrangler consistency reasons)." | ||
| ) | ||
| if user_lines is not None and user_lines is not True: | ||
| logger.warning("[local-json-write] Overriding lines=%s with lines=True for consistency.", user_lines) | ||
|
|
||
| df.to_json(file_path, **options) | ||
|
|
||
| @staticmethod | ||
|
|
@@ -283,6 +326,6 @@ def _read_from_local_batch(self) -> pd.DataFrame: | |
| dfs_to_concatenate = [] | ||
| for file in files: | ||
| file_to_load = os.path.join(file_path, file) | ||
| dfs_to_concatenate.append(getattr(self, f"_read_{file_type}_file")(file_to_load, self.schema, **self.options)) # type: ignore | ||
| dfs_to_concatenate.append(getattr(self, f"_read_{file_type}_file")(file_to_load, self.schema, **self.options)) | ||
|
|
||
| return pd.concat(dfs_to_concatenate).reset_index(drop=True) | ||
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.
Fixes a
pylintfalse positive on abstract methods not implemented...