-
Notifications
You must be signed in to change notification settings - Fork 5
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 Composite Decoder #179
Open
artem1205
wants to merge
16
commits into
main
Choose a base branch
from
artem1205/add-composite-decoder-with-parsers
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.
+445
−68
Open
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
5b7724d
Composite Decoder: add Composite Decoder
artem1205 990584e
Composite Decoder: add Models
artem1205 50782f7
Composite Decoder: ref to use BufferedIOBase
artem1205 17add9e
Composite Decoder: remove inner_parser from parser definition
artem1205 655ce35
Composite Decoder: ref models
artem1205 513aa43
Composite Decoder: clean
artem1205 eada5bf
Composite Decoder: ref todo
artem1205 1984ef1
Composite Decoder: remove args & kwargs
artem1205 8d3f82a
Composite Decoder: fmt mypy
artem1205 f2c9b0a
Composite Decoder: add to model factory
artem1205 961356c
Composite Decoder: add to model factory
artem1205 5fa937c
Composite Raw Decoder: add unittest for parsers
artem1205 1b85c26
Composite Raw Decoder: fix CompositeRawDecoder creation
artem1205 a181608
Composite Raw Decoder: ref: CompositeRawDecoder & jsonlinedecoder
artem1205 5276ed1
Composite Raw Decoder: fmt
artem1205 adf9d3d
Composite Raw Decoder: fix mypy
artem1205 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
104 changes: 104 additions & 0 deletions
104
airbyte_cdk/sources/declarative/decoders/composite_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,104 @@ | ||
import gzip | ||
import json | ||
import logging | ||
from abc import ABC, abstractmethod | ||
from dataclasses import dataclass | ||
from io import BufferedIOBase | ||
from typing import Any, Generator, MutableMapping, Optional | ||
|
||
import pandas as pd | ||
import requests | ||
from numpy import nan | ||
|
||
from airbyte_cdk.sources.declarative.decoders.decoder import Decoder | ||
|
||
logger = logging.getLogger("airbyte") | ||
|
||
|
||
@dataclass | ||
class Parser(ABC): | ||
@abstractmethod | ||
def parse( | ||
self, | ||
data: BufferedIOBase, | ||
) -> Generator[MutableMapping[str, Any], None, None]: | ||
""" | ||
Parse data and yield dictionaries. | ||
""" | ||
pass | ||
|
||
|
||
@dataclass | ||
class GzipParser(Parser): | ||
inner_parser: Parser | ||
|
||
def parse( | ||
self, | ||
data: BufferedIOBase, | ||
) -> Generator[MutableMapping[str, Any], None, None]: | ||
""" | ||
Decompress gzipped bytes and pass decompressed data to the inner parser. | ||
""" | ||
gzipobj = gzip.GzipFile(fileobj=data, mode="rb") | ||
yield from self.inner_parser.parse(gzipobj) | ||
|
||
|
||
@dataclass | ||
class JsonLineParser(Parser): | ||
encoding: Optional[str] = "utf-8" | ||
|
||
def parse( | ||
self, | ||
data: BufferedIOBase, | ||
) -> Generator[MutableMapping[str, Any], None, None]: | ||
for line in data: | ||
try: | ||
yield json.loads(line.decode(encoding=self.encoding)) | ||
except json.JSONDecodeError: | ||
logger.warning(f"Cannot decode/parse line {line!r} as JSON") | ||
# Handle invalid JSON lines gracefully (e.g., log and skip) | ||
pass | ||
|
||
|
||
@dataclass | ||
class CsvParser(Parser): | ||
# TODO: migrate implementation to re-use file-base classes | ||
encoding: Optional[str] = "utf-8" | ||
delimiter: Optional[str] = "," | ||
|
||
def parse( | ||
self, | ||
data: BufferedIOBase, | ||
) -> Generator[MutableMapping[str, Any], None, None]: | ||
""" | ||
Parse CSV data from decompressed bytes. | ||
""" | ||
reader = pd.read_csv( | ||
data, sep=self.delimiter, iterator=True, dtype=object, encoding=self.encoding | ||
) | ||
for chunk in reader: | ||
chunk = chunk.replace({nan: None}).to_dict(orient="records") | ||
for row in chunk: | ||
yield row | ||
|
||
|
||
@dataclass | ||
class CompositeRawDecoder(Decoder): | ||
""" | ||
Decoder strategy to transform a requests.Response into a Generator[MutableMapping[str, Any], None, None] | ||
passed response.raw to parser(s). | ||
Note: response.raw is not decoded/decompressed by default. | ||
parsers should be instantiated recursively. | ||
Example: | ||
composite_decoder = CompositeDecoder(parser=GzipParser(inner_parser=JsonLineParser(encoding="iso-8859-1"))) | ||
""" | ||
|
||
parser: Parser | ||
|
||
def is_stream_response(self) -> bool: | ||
return True | ||
|
||
def decode( | ||
self, response: requests.Response | ||
) -> Generator[MutableMapping[str, Any], None, None]: | ||
yield from self.parser.parse(data=response.raw) # type: ignore[arg-type] |
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
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.
💡 Codebase verification
The GzipParser implementation looks good, but could benefit from explicit error handling.
Looking at the implementation and tests, I notice that while it handles normal cases well (including different encodings), it might be worth adding explicit error handling for:
Would you consider adding a try-catch block around the GzipFile operations to gracefully handle these edge cases? This would make the parser more robust in production scenarios. wdyt?
🔗 Analysis chain
GzipParser schema definition.
Is it worth clarifying how GzipParser interacts with various compression levels or edge cases, e.g., 0-sized input? wdyt?
Let me search for more context about the GzipParser implementation and its handling of compression levels and edge cases.
This will help us understand:
Let me analyze the results to provide a more informed response.
Let me try a different search strategy to find the implementation and related files.
This should help us find:
Let me check the test file and implementation for more details about edge case handling.
This will help us understand:
🏁 Scripts executed
The following scripts were executed for the analysis:
Error: No shell scripts found
Script:
Length of output: 143
Script:
Length of output: 2579
Script:
Length of output: 4399