You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@beam.apache.org by ro...@apache.org on 2025/01/16 22:27:23 UTC
(beam-starter-python-provider) 01/01: Initial commit.
This is an automated email from the ASF dual-hosted git repository.
robertwb pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/beam-starter-python-provider.git
commit 8a769d2606b69f740494b3b49a37abd07af5a977
Author: Robert Bradshaw <ro...@gmail.com>
AuthorDate: Thu Jan 16 13:18:25 2025 -0800
Initial commit.
---
.gitignore | 2 +
LICENSE | 236 +++++++++++++++++++++++++++++++++++++++
README.md | 74 ++++++++++++
examples/error_handling.yaml | 43 +++++++
examples/multi_input_output.yaml | 60 ++++++++++
examples/provider_listing.yaml | 13 +++
examples/run_all.sh | 18 +++
examples/simple.yaml | 66 +++++++++++
examples/with_config.yaml | 73 ++++++++++++
my_provider.py | 142 +++++++++++++++++++++++
my_provider_test.py | 106 ++++++++++++++++++
pyproject.toml | 38 +++++++
12 files changed, 871 insertions(+)
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..1259436
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+dist/**
+__pycache__/**
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..723c574
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,236 @@
+This software is distributed under the terms of both the MIT license and the
+Apache License (Version 2.0).
+
+
+MIT license
+
+Copyright 2025 Google LLC
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+
+Apache 2 license
+
+ 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.
\ No newline at end of file
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..9f43423
--- /dev/null
+++ b/README.md
@@ -0,0 +1,74 @@
+# Apache Beam starter for Python Providers
+
+This provides an example of how to write a catalog of transforms via a provider
+in Python that can be used from Beam YAML.
+
+If you want to clone this repository to start your own project,
+you can choose the license you prefer and feel free to delete anything
+related to the license you are dropping.
+
+## Before you begin
+
+Make sure you have a [Python 3](https://www.python.org/) development environment ready.
+If you don't, you can download and install it from the
+[Python downloads page](https://www.python.org/downloads/).
+
+This project uses poetry to manage its dependencies, however it can be used
+with in any virtual environment where its dependencies (as listed in
+pyproject.toml) are installed.
+
+## Overview
+
+Beam YAML transforms can be ordinary Python transforms that are simply
+enumerated in a YAML file that indicates where to find them and how
+to instantiate them. This allows one to author arbitrarily complex
+transforms in Python and offer them for easy use from within a Beam
+YAML pipeline. The main steps that are involved are:
+
+1. Author PTransforms which accept (and produce) [schema'd PCollections](
+ https://beam.apache.org/documentation/programming-guide/#schemas).
+ In practice, this means that the elements are named tuples or `beam.Row`s.
+
+2. Publish these transforms as a standard Python package. For local development
+ this can be a simple tarball, for production use these can be published
+ to pypi or otherwise hosted anywhere else that is accessible to its users.
+
+3. Write a simple yaml file enumerating these transforms, providing both their
+ qualified names and the package(s) in which they live. This file can then
+ be referenced from a Beam YAML pipeline which can then use these transforms.
+
+## This repository
+
+This repository is a complete working example of the above steps.
+
+### PTransform definitions.
+
+Several transforms are defined in [my_provider.py](./my_provider.py).
+Ordinary unit tests can be found in
+[my_provider_test_.py](./my_provider_test.py)
+that can be run with pytest.
+A real-world example would probably have a more structured format than
+putting all transforms in a single top-level python module, but this
+is a python package structuring question and would not change anything
+essential here.
+
+### Publishing the package.
+
+Run `poetry build` to build the package.
+This will create the file `dist/beam_starter_python_provider-0.1.0.tar.gz`
+which is referenced elsewhere.
+
+### Write the provider listing file.
+
+The next step is to write a file that tells Beam YAML how and where to find the
+transforms that were defined above.
+An example of how to do this is given in
+[examples/provider_listing.yaml](examples/provider_listing.yaml).
+These listings can also be specified inline with the pipeline definition
+as done in [examples/simple.yaml](examples/simple.yaml).
+
+### Use the transforms.
+
+The (examples)[examples/] directory contains several examples of how to actually
+use the transforms. The script at (examples/run_all.sh)[examples/run_all.sh]
+then shows how they can be run.
diff --git a/examples/error_handling.yaml b/examples/error_handling.yaml
new file mode 100644
index 0000000..f8be526
--- /dev/null
+++ b/examples/error_handling.yaml
@@ -0,0 +1,43 @@
+
+pipeline:
+ type: chain
+ transforms:
+
+ # Create some input.
+ - type: Create
+ config:
+ elements:
+ - roman: I
+ - roman: IV
+ - roman: abc
+
+ # Map them to decimals with error handling.
+ - type: FromRoman
+ config:
+ error_handling:
+ output: my_errors
+
+ # Ensure that we got the same elements back.
+ - type: AssertEqual
+ config:
+ elements:
+ - value: 1
+ - value: 4
+
+ extra_transforms:
+ - type: StripErrorMetadata
+ input: FromRoman.my_errors
+
+ - type: LogForTesting
+ input: FromRoman.my_errors
+ config:
+ prefix: "Expected error:"
+
+ - type: AssertEqual
+ input: StripErrorMetadata
+ config:
+ elements:
+ - roman: 'abc'
+
+providers:
+ - include: "./provider_listing.yaml"
diff --git a/examples/multi_input_output.yaml b/examples/multi_input_output.yaml
new file mode 100644
index 0000000..57f8f28
--- /dev/null
+++ b/examples/multi_input_output.yaml
@@ -0,0 +1,60 @@
+
+pipeline:
+ type: composite
+ transforms:
+
+ # Create some input.
+ - type: Create
+ name: Weather
+ config:
+ elements:
+ - {date: '2024-12-01', city: 'Seattle', temperature: 51}
+ - {date: '2024-12-02', city: 'Seattle', temperature: 51}
+ - {date: '2024-12-03', city: 'Seattle', temperature: 45}
+ - {date: '2024-12-03', city: 'Kirkland', temperature: 52}
+ - {date: '2024-12-01', city: 'New York City', temperature: 41}
+ - {date: '2024-12-02', city: 'New York City', temperature: 43}
+
+ - type: Create
+ name: CityToState
+ config:
+ elements:
+ - {city: 'Seattle', state: 'WA'}
+ - {city: 'Kirkland', state: 'WA'}
+ - {city: 'New York City', state: 'NY'}
+
+ - type: MultiInputMultiOutput
+ input:
+ # Specify multiple inputs as a mapping that will get passed as a dict
+ # to the transform's expand function.
+ city_measurements: Weather
+ city_to_state: CityToState
+
+ # Multiple outputs are returned from the expand function as a dictionary
+ # mapping string keys to PCollections. Those string keys are referenced
+ # here.
+ - type: LogForTesting
+ input: MultiInputMultiOutput.avg_per_city
+
+ - type: LogForTesting
+ input: MultiInputMultiOutput.max_per_state
+
+ # Ensure that the pipeline ran correctly.
+ - type: AssertEqual
+ input: MultiInputMultiOutput.avg_per_city
+ config:
+ elements:
+ - {city: 'Seattle', temperature: 49}
+ - {city: 'Kirkland', temperature: 52}
+ - {city: 'New York City', temperature: 42}
+
+ # Ensure that the pipeline ran correctly.
+ - type: AssertEqual
+ input: MultiInputMultiOutput.max_per_state
+ config:
+ elements:
+ - {state: 'WA', temperature: 52}
+ - {state: 'NY', temperature: 43}
+
+providers:
+ - include: "./provider_listing.yaml"
diff --git a/examples/provider_listing.yaml b/examples/provider_listing.yaml
new file mode 100644
index 0000000..71cad6a
--- /dev/null
+++ b/examples/provider_listing.yaml
@@ -0,0 +1,13 @@
+- type: python
+ config:
+ packages:
+ # Enumerate any require packages here.
+ - "../dist/beam_starter_python_provider-0.1.0.tar.gz"
+ transforms:
+ # This is a mapping of transform types (used above) to the fully qualified
+ # name of PTransform classes (or PTransform-returning callables) that
+ # will be imported and invoked to construct the pipeline.
+ ToRoman: "my_provider.ToRomanNumerals"
+ FromRoman: "my_provider.FromRomanNumerals"
+ Stringify: "my_provider.StringifyRow"
+ MultiInputMultiOutput: "my_provider.MultiInputMultiOutput"
diff --git a/examples/run_all.sh b/examples/run_all.sh
new file mode 100755
index 0000000..caa7ad0
--- /dev/null
+++ b/examples/run_all.sh
@@ -0,0 +1,18 @@
+#!/bin/bash
+
+set -e
+
+# Create the package that we reference as a dependency.
+(cd .. && poetry build)
+
+# Run the pipelines one by one.
+
+python -m apache_beam.yaml.main --yaml_pipeline_file=./simple.yaml
+
+python -m apache_beam.yaml.main --yaml_pipeline_file=./error_handling.yaml
+
+python -m apache_beam.yaml.main --yaml_pipeline_file=./with_config.yaml
+
+python -m apache_beam.yaml.main --yaml_pipeline_file=./multi_input_output.yaml
+
+echo "All pipelines ran successfully."
diff --git a/examples/simple.yaml b/examples/simple.yaml
new file mode 100644
index 0000000..f36c101
--- /dev/null
+++ b/examples/simple.yaml
@@ -0,0 +1,66 @@
+#
+# Run locally as
+#
+# python -m apache_beam.yaml.main --yaml_pipeline_file=./simple.yaml
+#
+# Note that the first run may take a minute to create a virtual environment
+# into which to install this dependency, but this environment will be cached.
+#
+# This example can also be run on Dataflow via
+#
+# gcloud dataflow yaml run my_job \
+# --yaml-pipeline-file=./simple.yaml \
+# --region=us-central1
+#
+# (after placing my_provider-0.1.0.tar.gz in a globally accessible
+# location such as gcs and updating the path below).
+#
+
+pipeline:
+ type: chain
+ transforms:
+
+ # Create some input.
+ - type: Create
+ config:
+ elements:
+ - value: 1
+ - value: 99
+ - value: 2024
+
+ # Use the transform as defined below.
+ - type: ToRoman
+
+ # Log converted elements.
+ - type: LogForTesting
+
+ # Map them back.
+ - type: FromRoman
+
+ # Ensure that we got the same elements back.
+ - type: AssertEqual
+ config:
+ elements:
+ - value: 1
+ - value: 99
+ - value: 2024
+
+providers:
+ # Here we enumerate providers for the externally defined transforms
+ # used above.
+ # The set of providers can either be imported (see the other examples)
+ # and/or listed inline as here.
+ - type: python
+ config:
+ # Here we list packages that need to be installed to find the transforms.
+ # These can be local or remote files, urls, or pypi package identifiers
+ # (such as "scipy>=1.1").
+ packages:
+ - "../dist/beam_starter_python_provider-0.1.0.tar.gz"
+
+ # This is a mapping of transform types (used above) to the fully qualified
+ # name of PTransform classes (or PTransform-returning callables) that
+ # will be imported and invoked to construct the pipeline.
+ transforms:
+ ToRoman: "my_provider.ToRomanNumerals"
+ FromRoman: "my_provider.FromRomanNumerals"
diff --git a/examples/with_config.yaml b/examples/with_config.yaml
new file mode 100644
index 0000000..d19ae28
--- /dev/null
+++ b/examples/with_config.yaml
@@ -0,0 +1,73 @@
+pipeline:
+ transforms:
+
+ - type: Create
+ config:
+ elements:
+ - {label: '11a', conductor: 11, rank: 0}
+ - {label: '37a', conductor: 37, rank: 1}
+ - {label: '389a', conductor: 389, rank: 2}
+ - {label: '5077a', conductor: 5077, rank: 3}
+
+ # This pipeline is actually a forrest of several "chains" each of which
+ # illustrate a different configuration of the transform.
+ - type: chain
+ input: Create
+ transforms:
+ - type: Stringify
+ config:
+ item_sep: ', '
+ kv_sep: ' = '
+ prefix: '('
+ suffix: ')'
+
+ - type: LogForTesting
+
+ - type: AssertEqual
+ config:
+ elements:
+ - stringified: '(label = 11a, conductor = 11, rank = 0)'
+ - stringified: '(label = 37a, conductor = 37, rank = 1)'
+ - stringified: '(label = 389a, conductor = 389, rank = 2)'
+ - stringified: '(label = 5077a, conductor = 5077, rank = 3)'
+
+
+ # Test running with some defaults.
+ - type: chain
+ input: Create
+ transforms:
+ - type: Stringify
+ config:
+ prefix: '{'
+ suffix: '}'
+
+ - type: LogForTesting
+
+ - type: AssertEqual
+ config:
+ elements:
+ - stringified: '{label: 11a, conductor: 11, rank: 0}'
+ - stringified: '{label: 37a, conductor: 37, rank: 1}'
+ - stringified: '{label: 389a, conductor: 389, rank: 2}'
+ - stringified: '{label: 5077a, conductor: 5077, rank: 3}'
+
+
+ # And without any config at all (as all parameters are defaults)
+ - type: chain
+ input: Create
+ transforms:
+ - type: Stringify
+
+ - type: LogForTesting
+
+ - type: AssertEqual
+ config:
+ elements:
+ - stringified: 'label: 11a, conductor: 11, rank: 0'
+ - stringified: 'label: 37a, conductor: 37, rank: 1'
+ - stringified: 'label: 389a, conductor: 389, rank: 2'
+ - stringified: 'label: 5077a, conductor: 5077, rank: 3'
+
+
+providers:
+ - include: "./provider_listing.yaml"
diff --git a/my_provider.py b/my_provider.py
new file mode 100644
index 0000000..05f4f89
--- /dev/null
+++ b/my_provider.py
@@ -0,0 +1,142 @@
+import contextlib
+from typing import Optional
+
+import apache_beam as beam
+import apache_beam.transforms.error_handling
+try:
+ from apache_beam.yaml.yaml_errors import map_errors_to_standard_format
+except ImportError:
+ from apache_beam.yaml.yaml_mapping import _map_errors_to_standard_format as map_errors_to_standard_format
+
+import roman
+
+
+class ToRomanNumerals(beam.PTransform):
+ """A simple transform with external dependencies.
+
+ Note that it takes and returns schema'd PCollections.
+ """
+
+ def expand(self, pcoll):
+ return pcoll | beam.Map(
+ lambda row: beam.Row(roman=roman.toRoman(row.value)))
+
+
+class FromRomanNumerals(beam.PTransform):
+ """The inverse of ToRomanNumerals."""
+
+ def __init__(self, error_handling=None):
+ self._error_handling = error_handling
+
+ def expand(self, pcoll):
+ # Here we conditionally set up a context.
+ if self._error_handling is None:
+ error_handling_context = contextlib.nullcontext()
+ else:
+ error_handling_context = beam.transforms.error_handling.CollectingErrorHandler(
+ )
+
+ # Run our code, possibly catching errors.
+ with error_handling_context as error_handler:
+ result = pcoll | beam.Map(
+ lambda row: beam.Row(value=roman.fromRoman(row.roman))
+ ).with_error_handler(error_handler)
+
+ if self._error_handling is None:
+ # If error handling was not requested, return the bare result.
+ # Due to the null error handling context above, any errors
+ # will be raised and halt the pipeline itself.
+ # Alternatively, we could have unconditionally caught the
+ # errors and explicitly failed the pipeline if the errors
+ # PCollection was non-empty.
+ return result
+ else:
+ # Otherwise return a dict of the result and possibly some errors.
+ return {
+ 'result': result,
+ self._error_handling['output']: error_handler.output()
+ # These need to be mapped to the schema expected by yaml,
+ # which also ensures the errors are serializable.
+ | map_errors_to_standard_format(pcoll.element_type)
+ }
+
+
+class StringifyRow(beam.PTransform):
+ # The docstring here will become the documentation of the YAML transform,
+ # and its args (including their types and descriptions below) are pulled
+ # out to construct the configuration schema.
+ # When used in a YAML pipeline, the config parameter is passed here as
+ # kwargs.
+ # We allow None and assign defaults below to indicate that the arguments
+ # are actually optional.
+ def __init__(
+ self,
+ item_sep: Optional[str] = None,
+ kv_sep: Optional[str] = None,
+ prefix: Optional[str] = None,
+ suffix: Optional[str] = None):
+ """
+ Returns a customizable string representation of the each row.
+
+ Args:
+ item_sep: A string used to separate items in the row, defaults to ', '.
+ kv_sep: A string used to join keys and values, defaults to ', '.
+ prefix: A string to use as the prefix, defaults to the empty string.
+ suffix: A string to use as the suffix, defaults to the empty string.
+ """
+ self.item_sep = item_sep or ', '
+ self.kv_sep = kv_sep or ': '
+ self.prefix = prefix or ''
+ self.suffix = suffix or ''
+
+ def expand(self, pcoll):
+ return pcoll | beam.Map(
+ lambda row: beam.Row(
+ stringified=self.prefix + self.item_sep.join(
+ f'{k}{self.kv_sep}{v}'
+ for (k, v) in row._asdict().items()) + self.suffix))
+
+
+class MultiInputMultiOutput(beam.PTransform):
+ """An example transform with multiple inputs and multiple outputs.
+
+ This does aggregations and a join via side inputs, taking two inputs
+ and returning two outputs.
+
+ Taking a single input and returning two outputs, or taking a multiple
+ inputs and returning a single output, are handled according to whether
+ the input (respectively output) of expand is a dict or a single
+ PCollection.
+ """
+
+ def expand(self, pcolls):
+ # Input pcolls will be a dict
+ temp_per_city = pcolls['city_measurements']
+ city_to_state_pcoll = pcolls['city_to_state']
+ avg_per_city = (
+ temp_per_city
+ | 'PerCity' >> beam.GroupBy('city').aggregate_field(
+ 'temperature',
+ beam.transforms.combiners.MeanCombineFn(),
+ 'temperature')
+ # This remapping is just so we can compare directly against rows in our
+ # tests. Generally any named tuple (such as the one produced by the
+ # transform above) that can give us a schema will do.
+ | beam.Map(
+ lambda result: beam.Row(
+ city=result.city, temperature=result.temperature)))
+ max_per_state = (
+ temp_per_city
+ | beam.Map(
+ lambda row, city_to_state: beam.Row(
+ state=city_to_state[row.city], temperature=row.temperature),
+ # Side input.
+ city_to_state=beam.pvalue.AsDict(city_to_state_pcoll))
+ | 'PerState' >> beam.GroupBy('state').aggregate_field(
+ 'temperature', max, 'temperature')
+ # Likewise.
+ | beam.Map(
+ lambda result: beam.Row(
+ state=result.state, temperature=result.temperature)))
+ # As will output pcolls.
+ return dict(avg_per_city=avg_per_city, max_per_state=max_per_state)
diff --git a/my_provider_test.py b/my_provider_test.py
new file mode 100644
index 0000000..88f7034
--- /dev/null
+++ b/my_provider_test.py
@@ -0,0 +1,106 @@
+import unittest
+
+import apache_beam as beam
+from apache_beam.testing.util import assert_that
+from apache_beam.testing.util import equal_to
+
+import my_provider
+
+
+class TestTransforms(unittest.TestCase):
+
+ def test_to_roman(self):
+ with beam.Pipeline() as p:
+ pcoll = p | beam.Create([
+ beam.Row(value=1),
+ beam.Row(value=99),
+ beam.Row(value=2024),
+ ])
+ result = pcoll | my_provider.ToRomanNumerals()
+ assert_that(
+ result,
+ equal_to([
+ beam.Row(roman='I'),
+ beam.Row(roman='XCIX'),
+ beam.Row(roman='MMXXIV'),
+ ]))
+
+ def test_from_roman(self):
+ with beam.Pipeline() as p:
+ pcoll = p | beam.Create([
+ beam.Row(roman='I'),
+ beam.Row(roman='XCIX'),
+ beam.Row(roman='MMXXIV'),
+ ])
+ result = pcoll | my_provider.FromRomanNumerals()
+ assert_that(
+ result,
+ equal_to([
+ beam.Row(value=1),
+ beam.Row(value=99),
+ beam.Row(value=2024),
+ ]))
+
+ def test_from_roman_with_errors(self):
+ with self.assertRaisesRegex(Exception, 'Invalid Roman numeral'):
+ with beam.Pipeline() as p:
+ pcoll = p | beam.Create([
+ beam.Row(roman='I'),
+ beam.Row(roman='XCIX'),
+ beam.Row(roman='abc'),
+ ])
+ _ = pcoll | my_provider.FromRomanNumerals()
+
+ def test_from_roman_with_error_handling(self):
+ with beam.Pipeline() as p:
+ pcoll = p | beam.Create([
+ beam.Row(roman='I'),
+ beam.Row(roman='XCIX'),
+ beam.Row(roman='abc'),
+ ])
+ results = pcoll | my_provider.FromRomanNumerals(
+ error_handling={'output': 'errors'})
+ assert_that(
+ results['result'],
+ equal_to([
+ beam.Row(value=1),
+ beam.Row(value=99),
+ ]))
+ assert_that(
+ results['errors'] | beam.Map(lambda x: x.element.roman),
+ equal_to(['abc']))
+
+ def test_multi_input_multi_output(self):
+ with beam.Pipeline() as p:
+ city_measurements = p | 'city_measurements' >> beam.Create([
+ beam.Row(city='Seattle', temperature=51, date='2024-12-01'),
+ beam.Row(city='Seattle', temperature=51, date='2024-12-02'),
+ beam.Row(city='Seattle', temperature=45, date='2024-12-03'),
+ beam.Row(city='Kirkland', temperature=52, date='2024-12-03'),
+ beam.Row(city='New York City', temperature=41, date='2024-12-01'),
+ beam.Row(city='New York City', temperature=43, date='2024-12-02'),
+ ])
+ city_to_state = p | 'city_to_state' >> beam.Create([
+ beam.Row(city='Seattle', state='WA'),
+ beam.Row(city='Kirkland', state='WA'),
+ beam.Row(city='New York City', state='NY'),
+ ])
+ result = {
+ 'city_measurements': city_measurements,
+ 'city_to_state': city_to_state
+ } | my_provider.MultiInputMultiOutput()
+
+ assert_that(
+ result['avg_per_city'],
+ equal_to([
+ beam.Row(city='Seattle', temperature=49),
+ beam.Row(city='Kirkland', temperature=52),
+ beam.Row(city='New York City', temperature=42),
+ ]))
+
+ assert_that(
+ result['max_per_state'],
+ equal_to([
+ beam.Row(state='WA', temperature=52),
+ beam.Row(state='NY', temperature=43),
+ ]))
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 0000000..d8e1f64
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,38 @@
+[tool.poetry]
+name = "beam-starter-python-provider"
+version = "0.1.0"
+description = "Example Beam YAML Python providers"
+authors = ["Your Name <yo...@example.com>"]
+license = "Apache License 2.0 OR MIT license"
+readme = "README.md"
+packages = [
+ { include = "my_provider.py" },
+]
+
+
+[tool.poetry.dependencies]
+python = "^3.9"
+apache-beam = {extras = ["yaml"], version = "^2.61.0"}
+roman = "^5.0"
+
+[tool.poetry.group.dev.dependencies]
+pytest = "^8.3.4"
+yapf = "^0.43.0"
+
+[build-system]
+requires = ["poetry-core"]
+build-backend = "poetry.core.masonry.api"
+
+[tool.yapf]
+indent_width = 2
+continuation_indent_width = 4
+column_limit = 80
+allow_split_before_dict_value = false
+blank_line_before_module_docstring = true
+coalesce_brackets = true
+each_dict_entry_on_separate_line = true
+split_all_top_level_comma_separated_values = true
+split_arguments_when_comma_terminated = true
+split_before_expression_after_opening_paren = true
+split_before_first_argument = true
+split_before_logical_operator = false