-
Notifications
You must be signed in to change notification settings - Fork 7
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
feat: add CsvDecoder to support streaming CSV parsing #321
Open
devin-ai-integration
wants to merge
3
commits into
main
Choose a base branch
from
devin/1738888021-add-csv-decoder
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.
+152
−1
Open
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 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 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 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,70 @@ | ||
# | ||
# Copyright (c) 2024 Airbyte, Inc., all rights reserved. | ||
# | ||
|
||
import io | ||
import logging | ||
from dataclasses import InitVar, dataclass | ||
from typing import Any, Generator, Mapping, MutableMapping | ||
|
||
import pandas as pd | ||
import requests | ||
|
||
from airbyte_cdk.sources.declarative.decoders.decoder import Decoder | ||
|
||
logger = logging.getLogger("airbyte") | ||
|
||
|
||
@dataclass | ||
class CsvDecoder(Decoder): | ||
parameters: InitVar[Mapping[str, Any]] | ||
|
||
def __post_init__(self, parameters: Mapping[str, Any]) -> None: | ||
self.delimiter = parameters.get("delimiter", ",") | ||
self.encoding = parameters.get("encoding", "utf-8") | ||
self.chunk_size = 100 | ||
|
||
def is_stream_response(self) -> bool: | ||
return True | ||
|
||
def decode( | ||
self, response: requests.Response | ||
) -> Generator[MutableMapping[str, Any], None, None]: | ||
try: | ||
if not response.text.strip(): | ||
yield {} | ||
return | ||
|
||
# First validate CSV structure | ||
lines = response.text.strip().split("\n") | ||
if not lines: | ||
yield {} | ||
return | ||
|
||
# Check if all rows have the same number of columns | ||
first_row_cols = len(lines[0].split(self.delimiter)) | ||
if any(len(line.split(self.delimiter)) != first_row_cols for line in lines[1:]): | ||
yield {} | ||
return | ||
|
||
csv_data = io.StringIO(response.text) | ||
try: | ||
chunks = pd.read_csv( | ||
csv_data, | ||
chunksize=self.chunk_size, | ||
iterator=True, | ||
dtype=object, | ||
delimiter=self.delimiter, | ||
encoding=self.encoding, | ||
) | ||
except (pd.errors.EmptyDataError, pd.errors.ParserError): | ||
yield {} | ||
return | ||
for chunk in chunks: | ||
for record in chunk.replace({pd.NA: None}).to_dict(orient="records"): | ||
yield record | ||
except Exception as exc: | ||
logger.warning( | ||
f"Response cannot be parsed as CSV: {response.status_code=}, {response.text=}, {exc=}" | ||
) | ||
yield {} |
This file contains 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 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
39 changes: 39 additions & 0 deletions
39
unit_tests/sources/declarative/decoders/test_csv_decoder.py
This file contains 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,39 @@ | ||
# | ||
# Copyright (c) 2024 Airbyte, Inc., all rights reserved. | ||
# | ||
|
||
import pytest | ||
import requests | ||
|
||
from airbyte_cdk.sources.declarative.decoders import CsvDecoder | ||
|
||
|
||
@pytest.mark.parametrize( | ||
"response_body, expected, delimiter", | ||
[ | ||
("name,age\nJohn,30", [{"name": "John", "age": "30"}], ","), | ||
("name;age\nJohn;30", [{"name": "John", "age": "30"}], ";"), | ||
("", [{}], ","), # Empty response | ||
("invalid,csv,data\nno,columns", [{}], ","), # Malformed CSV | ||
( | ||
"name,age\nJohn,30\nJane,25", | ||
[{"name": "John", "age": "30"}, {"name": "Jane", "age": "25"}], | ||
",", | ||
), # Multiple rows | ||
], | ||
) | ||
def test_csv_decoder(requests_mock, response_body, expected, delimiter): | ||
requests_mock.register_uri("GET", "https://airbyte.io/", text=response_body) | ||
response = requests.get("https://airbyte.io/") | ||
decoder = CsvDecoder(parameters={"delimiter": delimiter}) | ||
assert list(decoder.decode(response)) == expected | ||
|
||
|
||
def test_is_stream_response(): | ||
decoder = CsvDecoder(parameters={}) | ||
assert decoder.is_stream_response() is True | ||
|
||
|
||
def test_custom_encoding(): | ||
decoder = CsvDecoder(parameters={"encoding": "latin1"}) | ||
assert decoder.encoding == "latin1" |
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 looks good, but you also need to add
CsvDecoder
as an option to all the spots in the schema that acceptXmlDecoder
as an option.