From 7eb183aa47673c11f8e766105524146c88420531 Mon Sep 17 00:00:00 2001 From: bonnal-enzo Date: Sun, 23 Jul 2023 16:42:47 +0200 Subject: [PATCH] init --- .github/workflows/deploy.yml | 28 +++++ .github/workflows/test.yml | 33 ++++++ .gitignore | 4 + LICENSE | 201 ++++++++++++++++++++++++++++++++ README.md | 38 ++++++ kissio/__init__.py | 1 + kissio/pipe.py | 220 +++++++++++++++++++++++++++++++++++ setup.py | 12 ++ test/__init__.py | 0 test/test.py | 151 ++++++++++++++++++++++++ 10 files changed, 688 insertions(+) create mode 100644 .github/workflows/deploy.yml create mode 100644 .github/workflows/test.yml create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 kissio/__init__.py create mode 100644 kissio/pipe.py create mode 100644 setup.py create mode 100644 test/__init__.py create mode 100644 test/test.py diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 0000000..bb2a391 --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,28 @@ +name: PyPI + +on: + push: + branches: + - main + paths: + - 'setup.py' +jobs: + deploy: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v1 + - name: Set up Python + uses: actions/setup-python@v1 + with: + python-version: '3.x' + - name: Install dependencies + run: | + python3 -m pip install --upgrade pip + pip install setuptools wheel twine + - name: Build and publish + env: + TWINE_USERNAME: enzobnl + TWINE_PASSWORD: ${{ secrets.pypipassword }} + run: | + python setup.py sdist bdist_wheel + twine upload dist/* diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..87dafc2 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,33 @@ +name: test + +on: [push] + +jobs: + unittest: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v1 + - name: Set up Python 3.6 + uses: actions/setup-python@v1 + with: + python-version: 3.9 + + - name: unittest + run: | + python -m unittest + + lint: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v1 + - name: Set up Python 3.6 + uses: actions/setup-python@v1 + with: + python-version: 3.9 + + - name: unittest + run: | + python -m black --check kissio/* test/* diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0d14867 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.idea +__pycache__ +.venv +_* \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..8c29ce7 --- /dev/null +++ b/README.md @@ -0,0 +1,38 @@ +# `kissIO` + +[![Actions Status](https://github.com/bonnal-enzo/kissio/workflows/test/badge.svg)](https://github.com/bonnal-enzo/kissio/actions) [![Actions Status](https://github.com/bonnal-enzo/kissio/workflows/PyPI/badge.svg)](https://github.com/bonnal-enzo/kissio/actions) + +## Install + +`python -m pip install kissio` + +## Usage + +```python +import json +from kissio import Pipe, CatchedPipeError + +if ( + errors := Pipe(range(-10, 10)) + .map(str) + .map(lambda elem: elem[:1]) # get the first character of the int + .map(int) # cast to int + .catch() # a CatchedPipeError element will be yielded by the upstream iterator in case an exception would be raised + .log() # add verbosity to the iteration process + .filter(lambda elem: isinstance(elem, CatchedPipeError)) # only keep the errors + .map(str) # get the str of the error + .list(limit=3) # exhaust the entire interator but only store the first 3 errors +): + raise RuntimeError(errors) + +``` + +## Setup + +```bash +python -m venv .venv +source ./.venv/bin/activate +python -m pip install -r requirements.txt +python -m unittest +python -m black kissio/* test/* +``` diff --git a/kissio/__init__.py b/kissio/__init__.py new file mode 100644 index 0000000..a022c44 --- /dev/null +++ b/kissio/__init__.py @@ -0,0 +1 @@ +from kissio.pipe import CatchedPipeError, Pipe diff --git a/kissio/pipe.py b/kissio/pipe.py new file mode 100644 index 0000000..a8b3955 --- /dev/null +++ b/kissio/pipe.py @@ -0,0 +1,220 @@ +import itertools +import logging +import time +import timeit +from concurrent.futures import ThreadPoolExecutor +from datetime import datetime +from functools import reduce +from queue import Empty, Queue +from typing import Callable, Iterable, Iterator, List, TypeVar + +T = TypeVar("T") +R = TypeVar("R") + + +class Pipe(Iterator[T]): + def __init__(self, iterator: Iterator[T]) -> None: + self.iterator: Iterator[T] = iter( + iterator + ) # call iter in case it is an iterable that is passed + + def __next__(self) -> T: + return next(self.iterator) + + def __iter__(self) -> T: + return self + + def chain(self, *others: Iterable["Pipe[T]"]) -> "Pipe[T]": + return Pipe(itertools.chain(self, *others)) + + def merge(self, *others: Iterable["Pipe[T]"]) -> "Pipe[T]": + return _ConcurrentlyMergingPipe([self, *others]) + + def map(self, func: Callable[[T], R], num_threads: int = 0) -> "Pipe[R]": + if num_threads <= 1: + return Pipe(map(func, self)) + else: + + def iterable(): + executor = ThreadPoolExecutor(max_workers=num_threads) + yield from executor.map(func, self) + executor.shutdown() + + return Pipe(iter(iterable())) + + def explode(self) -> "Pipe": + return _ExplodingPipe(self) + + def filter(self, predicate: Callable[[T], bool]) -> "Pipe[R]": + return Pipe(filter(predicate, self)) + + def batch( + self, max_size: int = 100, max_window_seconds: float = float("inf") + ) -> "Pipe[List[T]]": + return _BatchingPipe(self, max_size, max_window_seconds) + + def slow(self, freq: int) -> "Pipe[T]": + return Pipe(_SlowingIterator(self, freq)) + + def head(self, n) -> "Pipe[T]": + return Pipe(itertools.islice(self, n)) + + def catch(self) -> "Pipe[T]": + return _CatchingPipe(self) + + def log(self) -> "Pipe[T]": + return _LoggingPipe(self) + + def reduce(self, f: Callable[[R, T], R], initial: R) -> R: + return reduce(f, self, initial) + + def list(self, limit: int = float("inf")) -> List[T]: + return [elem for i, elem in enumerate(self) if i < limit] + + def timeit(self) -> float: + def iterate(): + for _ in self: + pass + + return timeit.timeit(iterate, number=1) + + +class _ExplodingPipe(Pipe[T]): + def __init__(self, iterator: Iterator[Iterable[T]]) -> None: + super().__init__(iterator) + self.current_iterator_elem = iter(super().__next__()) + + def __next__(self) -> T: + try: + return next(self.current_iterator_elem) + except StopIteration: + self.current_iterator_elem = iter(super().__next__()) + return next(self) + + +class CatchedPipeError: + def __init__(self, e: Exception) -> None: + self.error_type = type(e) + self.message = str(e) + + def __str__(self) -> str: + return f"{self.error_type}: {self.message}" + + +class _CatchingPipe(Pipe[T]): + def __next__(self) -> T: + try: + return super().__next__() + except Exception as e: + if isinstance(e, StopIteration): + raise + else: + return CatchedPipeError(e) + + +class _LoggingPipe(Pipe[T]): + def __init__(self, iterator: Iterator[T]) -> None: + super().__init__(iterator) + logging.getLogger().setLevel(logging.INFO) + self.yields_count = 0 + self.errors_count = 0 + self.last_log_at_yields_count = 0 + self.start_time = time.time() + + def _log(self) -> None: + logging.info( + "%s yields in %s, leading to the catch of %s errors.", + self.yields_count, + str( + datetime.fromtimestamp(time.time()) + - datetime.fromtimestamp(self.start_time) + ), + self.errors_count, + ) + + def __next__(self) -> T: + try: + elem = super().__next__() + except StopIteration: + self._log() + raise + + self.yields_count += 1 + if isinstance(elem, CatchedPipeError): + self.errors_count += 1 + + if self.yields_count + self.errors_count >= 2 * self.last_log_at_yields_count: + self._log() + self.last_log_at_yields_count = self.yields_count + self.errors_count + + return elem + + +class _SlowingIterator(Pipe[T]): + def __init__(self, iterator: Iterator[T], freq: int) -> None: + super().__init__(iterator) + self.freq = freq + self.start = None + self.yields_count = 0 + + def __next__(self) -> T: + if not self.start: + self.start = time.time() + while True: + while self.yields_count > (time.time() - self.start) * self.freq: + time.sleep(1 / self.freq) + self.yields_count += 1 + return super().__next__() + + +class _BatchingPipe(Pipe[List[T]]): + def __init__( + self, iterator: Iterator[T], max_size: int, max_window_seconds: float + ) -> None: + super().__init__(iterator) + self.max_size = max_size + self.max_window_seconds = max_window_seconds + + def __next__(self) -> List[T]: + start_time = time.time() + batch = [next(self.iterator)] + try: + while ( + len(batch) < self.max_size + and (time.time() - start_time) < self.max_window_seconds + ): + batch.append(next(self.iterator)) + return batch + except StopIteration: + if batch: + return batch + else: + raise + + +class _ConcurrentlyMergingPipe(Pipe[T]): + def __init__(self, iterators: List[Iterator[T]]) -> None: + super().__init__( + iter(_ConcurrentlyMergingPipe._concurrently_merging_iterable(iterators)) + ) + + @staticmethod + def _pull_in_queue(iterator: Iterator[T], queue: Queue) -> None: + for elem in iterator: + queue.put(elem) + + @staticmethod + def _concurrently_merging_iterable(iterators: List[Iterator[T]]) -> Iterator[T]: + queue = Queue() + with ThreadPoolExecutor(max_workers=len(iterators)) as executor: + futures = [ + executor.submit( + _ConcurrentlyMergingPipe._pull_in_queue, iterator, queue + ) + for iterator in iterators + ] + while not queue.empty() or not all((future.done() for future in futures)): + try: + yield queue.get(block=False) + except Empty: + time.sleep(0.05) diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..a4884d1 --- /dev/null +++ b/setup.py @@ -0,0 +1,12 @@ +from setuptools import setup + +setup( + name='kissio', + version='0.0.5', + packages=['kissio'], + url='http://github.com/bonnal-enzo/kissio', + license='Apache 2.', + author='bonnal-enzo', + author_email='bonnal.enzo.dev@gmail.com', + description='Library providing a simple Iterator-based interface to create ETL pipelines.' +) diff --git a/test/__init__.py b/test/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/test/test.py b/test/test.py new file mode 100644 index 0000000..2370d07 --- /dev/null +++ b/test/test.py @@ -0,0 +1,151 @@ +import time +import timeit +import unittest + +from kissio import Pipe +from kissio.pipe import CatchedPipeError + +TEN_MS = 0.01 + + +def ten_millis_identity(x): + time.sleep(TEN_MS) + return x + + +class TestPipe(unittest.TestCase): + def test_init(self): + # from iterable + self.assertListEqual(list(Pipe(range(8))), list(range(8))) + # from iterator + self.assertListEqual(list(Pipe(iter(range(8)))), list(range(8))) + + def test_chain(self): + self.assertListEqual( + list( + Pipe(range(2)) + .chain(Pipe(range(2, 4)), Pipe(range(4, 6))) + .chain(Pipe(range(6, 8))) + ), + list(range(8)), + ) + + def test_merge(self): + self.assertSetEqual( + set( + Pipe(iter(range(2))) + .merge(Pipe(range(2, 4)), Pipe(range(4, 6))) + .merge(Pipe(range(6, 8))) + ), + set(range(8)), + ) + # execution_time + + def test_map(self): + func = lambda x: x**2 + # non threaded + self.assertListEqual(list(Pipe(range(8)).map(func)), list(map(func, range(8)))) + # threaded + self.assertListEqual( + list(Pipe(range(8)).map(func, num_threads=2)), list(map(func, range(8))) + ) + # non-threaded vs threaded execution time + pipe = Pipe(range(8)).map(ten_millis_identity) + self.assertAlmostEqual(pipe.timeit(), TEN_MS * 8, delta=0.3 * (TEN_MS * 8)) + num_threads = 2 + pipe = Pipe(range(8)).map(ten_millis_identity, num_threads=num_threads) + self.assertAlmostEqual( + pipe.timeit(), + TEN_MS * 8 / num_threads, + delta=0.3 * (TEN_MS * 8) / num_threads, + ) + + def test_explode(self): + self.assertListEqual( + list(Pipe(["Hello World", "Happy to be here :)"]).map(str.split).explode()), + ["Hello", "World", "Happy", "to", "be", "here", ":)"], + ) + self.assertEqual( + sum( + Pipe([["1 2 3", "4 5 6"], ["7", "8 9 10"]]) + .explode() + .map(str.split) + .explode() + .map(int) + ), + 55, + ) + + def test_filter(self): + self.assertListEqual(list(Pipe(range(8)).filter(lambda x: x % 2)), [1, 3, 5, 7]) + + self.assertListEqual(list(Pipe(range(8)).filter(lambda _: False)), []) + + def test_batch(self): + self.assertListEqual( + list(Pipe(range(8)).batch(max_size=3)), [[0, 1, 2], [3, 4, 5], [6, 7]] + ) + self.assertListEqual( + list(Pipe(range(6)).batch(max_size=3)), [[0, 1, 2], [3, 4, 5]] + ) + self.assertListEqual( + list(Pipe(range(8)).batch(max_size=1)), list(map(lambda x: [x], range(8))) + ) + self.assertListEqual(list(Pipe(range(8)).batch(max_size=8)), [list(range(8))]) + + def test_slow(self): + freq = 64 + pipe = Pipe(range(8)).map(ten_millis_identity).slow(freq) + self.assertAlmostEqual( + pipe.timeit(), + 1 / freq * 8, + delta=0.3 * (1 / freq * 8), + ) + + def test_head(self): + self.assertListEqual(list(Pipe(range(8)).head(3)), [0, 1, 2]) + # stops after the second element + self.assertAlmostEqual( + Pipe(range(8)).map(ten_millis_identity).head(2).timeit(), + TEN_MS * 2, + delta=0.3 * TEN_MS * 2, + ) + + def test_list(self): + self.assertListEqual(Pipe(range(8)).list(limit=6), list(range(6))) + self.assertListEqual(Pipe(range(8)).list(), list(range(8))) + self.assertAlmostEqual( + timeit.timeit( + lambda: Pipe(range(8)).map(ten_millis_identity).list(0), + number=1, + ), + TEN_MS * 8, + delta=0.3 * TEN_MS * 8, + ) + + def test_reduce(self): + self.assertEqual(Pipe(range(8)).reduce(lambda count, elem: count + 1, 0), 8) + + def test_timeit(self): + get_pipe = lambda: Pipe(range(8)).slow(64) + start_time = time.time() + list(get_pipe()) + execution_time = time.time() - start_time + self.assertAlmostEqual( + execution_time, get_pipe().timeit(), delta=0.3 * execution_time + ) + + def test_catch(self): + self.assertListEqual( + list(Pipe(["1", "r", "2"]).map(int).catch().map(type)), + [int, CatchedPipeError, int], + ) + + def test_log(self): + list( + Pipe(range(9)) + .map(lambda elem: ("_" if elem % 2 else "") + str(elem)) + .map(int) + .catch() + .log() + )