From 4345e05547e29b832ddc47eff02b877d52eb9b21 Mon Sep 17 00:00:00 2001 From: PrivacyGo-PETPlatform Date: Mon, 20 Jan 2025 12:27:00 +0800 Subject: [PATCH] feat: version 0.1.0 --- .dockerignore | 17 + .gitignore | 114 +++++ .pre-commit-config.yaml | 25 ++ .style.yapf | 397 ++++++++++++++++++ CODE_OF_CONDUCT.md | 127 ++++++ CONTRIBUTING.md | 61 +++ LICENSE | 201 +++++++++ NOTICE | 1 + README.md | 98 +++++ requirements.txt | 3 + setup.py | 26 ++ src/__init__.py | 13 + src/crypto_data_engine/__init__.py | 23 + src/crypto_data_engine/constants.py | 35 ++ src/crypto_data_engine/context.py | 101 +++++ src/crypto_data_engine/data/__init__.py | 13 + src/crypto_data_engine/data/base.py | 46 ++ src/crypto_data_engine/data/csv_dataset.py | 200 +++++++++ src/crypto_data_engine/data/data_io.py | 29 ++ src/crypto_data_engine/data/data_type.py | 72 ++++ src/crypto_data_engine/data/scalar_dataset.py | 61 +++ src/crypto_data_engine/demo.py | 142 +++++++ src/crypto_data_engine/engine/__init__.py | 19 + src/crypto_data_engine/engine/base.py | 26 ++ src/crypto_data_engine/engine/compute.py | 46 ++ .../engine/local/__init__.py | 13 + .../engine/local/local_engine.py | 86 ++++ .../engine/local/predefined/__init__.py | 16 + .../engine/local/predefined/impl.py | 55 +++ .../engine/local/predefined/wrapper.py | 27 ++ .../engine/spark/__init__.py | 13 + .../spark/pyspark_job_scripts/__init__.py | 13 + .../predefined/__init__.py | 13 + .../predefined/csv_get_unique_rows.py | 72 ++++ .../predefined/csv_sort_by_key.py | 67 +++ .../engine/spark/pyspark_job_scripts/udf.py | 69 +++ .../engine/spark/spark_client.py | 120 ++++++ .../engine/spark/spark_engine.py | 77 ++++ .../engine/spark/spark_utils.py | 61 +++ src/crypto_data_engine/settings.py | 44 ++ src/crypto_data_engine/utils/__init__.py | 13 + src/crypto_data_engine/utils/petace_utils.py | 70 +++ test/data/a.csv | 100 +++++ test/data/a_sorted_0.csv | 100 +++++ test/data/a_sorted_1.csv | 100 +++++ test/data/a_sorted_2.csv | 100 +++++ test/data/names.csv | 20 + test/data/sorted.csv | 20 + test/data/unique.csv | 16 + test/generate_csv.py | 34 ++ 50 files changed, 3215 insertions(+) create mode 100644 .dockerignore create mode 100644 .gitignore create mode 100644 .pre-commit-config.yaml create mode 100644 .style.yapf create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE create mode 100644 NOTICE create mode 100644 README.md create mode 100644 requirements.txt create mode 100644 setup.py create mode 100644 src/__init__.py create mode 100644 src/crypto_data_engine/__init__.py create mode 100644 src/crypto_data_engine/constants.py create mode 100644 src/crypto_data_engine/context.py create mode 100644 src/crypto_data_engine/data/__init__.py create mode 100644 src/crypto_data_engine/data/base.py create mode 100644 src/crypto_data_engine/data/csv_dataset.py create mode 100644 src/crypto_data_engine/data/data_io.py create mode 100644 src/crypto_data_engine/data/data_type.py create mode 100644 src/crypto_data_engine/data/scalar_dataset.py create mode 100644 src/crypto_data_engine/demo.py create mode 100644 src/crypto_data_engine/engine/__init__.py create mode 100644 src/crypto_data_engine/engine/base.py create mode 100644 src/crypto_data_engine/engine/compute.py create mode 100644 src/crypto_data_engine/engine/local/__init__.py create mode 100644 src/crypto_data_engine/engine/local/local_engine.py create mode 100644 src/crypto_data_engine/engine/local/predefined/__init__.py create mode 100644 src/crypto_data_engine/engine/local/predefined/impl.py create mode 100644 src/crypto_data_engine/engine/local/predefined/wrapper.py create mode 100644 src/crypto_data_engine/engine/spark/__init__.py create mode 100644 src/crypto_data_engine/engine/spark/pyspark_job_scripts/__init__.py create mode 100644 src/crypto_data_engine/engine/spark/pyspark_job_scripts/predefined/__init__.py create mode 100644 src/crypto_data_engine/engine/spark/pyspark_job_scripts/predefined/csv_get_unique_rows.py create mode 100644 src/crypto_data_engine/engine/spark/pyspark_job_scripts/predefined/csv_sort_by_key.py create mode 100644 src/crypto_data_engine/engine/spark/pyspark_job_scripts/udf.py create mode 100644 src/crypto_data_engine/engine/spark/spark_client.py create mode 100644 src/crypto_data_engine/engine/spark/spark_engine.py create mode 100644 src/crypto_data_engine/engine/spark/spark_utils.py create mode 100644 src/crypto_data_engine/settings.py create mode 100644 src/crypto_data_engine/utils/__init__.py create mode 100644 src/crypto_data_engine/utils/petace_utils.py create mode 100644 test/data/a.csv create mode 100644 test/data/a_sorted_0.csv create mode 100644 test/data/a_sorted_1.csv create mode 100644 test/data/a_sorted_2.csv create mode 100644 test/data/names.csv create mode 100644 test/data/sorted.csv create mode 100644 test/data/unique.csv create mode 100644 test/generate_csv.py diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..b923fcf --- /dev/null +++ b/.dockerignore @@ -0,0 +1,17 @@ +.dockerignore +.flake8 +.git/ +.gitignore +.pre-commit-config.yaml +.pylintrc +.style.yapf +**/__pycache__/ +docker/ +docs/ +test/ +CODE_OF_CONDUCT.md +CONTRIBUTING.md +Disclaimers +LICENSE +NOTICE +README.md diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..44402a8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,114 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# .idea +.idea/ + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit operators.test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..7d37a3d --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,25 @@ +default_language_version: + # force all unspecified python hooks to run python3 + python: python3 +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.4.0 + hooks: + - id: check-added-large-files + - id: check-case-conflict + - id: check-merge-conflict + - id: check-symlinks + - id: check-yaml + - id: end-of-file-fixer + - id: forbid-submodules + - id: mixed-line-ending + - id: trailing-whitespace + - repo: https://github.com/google/yapf/ + rev: v0.40.2 + hooks: + - id: yapf + name: yapf + language: python + entry: yapf + args: ["--style=.style.yapf", "-i"] + types: [python] diff --git a/.style.yapf b/.style.yapf new file mode 100644 index 0000000..ecc2642 --- /dev/null +++ b/.style.yapf @@ -0,0 +1,397 @@ +[style] +# Align closing bracket with visual indentation. +align_closing_bracket_with_visual_indent=False + +# Allow dictionary keys to exist on multiple lines. For example: +# +# x = { +# ('this is the first element of a tuple', +# 'this is the second element of a tuple'): +# value, +# } +allow_multiline_dictionary_keys=False + +# Allow lambdas to be formatted on more than one line. +allow_multiline_lambdas=False + +# Allow splitting before a default / named assignment in an argument list. +allow_split_before_default_or_named_assigns=True + +# Allow splits before the dictionary value. +allow_split_before_dict_value=True + +# Let spacing indicate operator precedence. For example: +# +# a = 1 * 2 + 3 / 4 +# b = 1 / 2 - 3 * 4 +# c = (1 + 2) * (3 - 4) +# d = (1 - 2) / (3 + 4) +# e = 1 * 2 - 3 +# f = 1 + 2 + 3 + 4 +# +# will be formatted as follows to indicate precedence: +# +# a = 1*2 + 3/4 +# b = 1/2 - 3*4 +# c = (1+2) * (3-4) +# d = (1-2) / (3+4) +# e = 1*2 - 3 +# f = 1 + 2 + 3 + 4 +# +arithmetic_precedence_indication=False + +# Number of blank lines surrounding top-level function and class +# definitions. +blank_lines_around_top_level_definition=2 + +# Number of blank lines between top-level imports and variable +# definitions. +blank_lines_between_top_level_imports_and_variables=1 + +# Insert a blank line before a class-level docstring. +blank_line_before_class_docstring=False + +# Insert a blank line before a module docstring. +blank_line_before_module_docstring=False + +# Insert a blank line before a 'def' or 'class' immediately nested +# within another 'def' or 'class'. For example: +# +# class Foo: +# # <------ this blank line +# def method(): +# ... +blank_line_before_nested_class_or_def=True + +# Do not split consecutive brackets. Only relevant when +# dedent_closing_brackets is set. For example: +# +# call_func_that_takes_a_dict( +# { +# 'key1': 'value1', +# 'key2': 'value2', +# } +# ) +# +# would reformat to: +# +# call_func_that_takes_a_dict({ +# 'key1': 'value1', +# 'key2': 'value2', +# }) +coalesce_brackets=False + +# The column limit. +column_limit=120 + +# The style for continuation alignment. Possible values are: +# +# - SPACE: Use spaces for continuation alignment. This is default behavior. +# - FIXED: Use fixed number (CONTINUATION_INDENT_WIDTH) of columns +# (ie: CONTINUATION_INDENT_WIDTH/INDENT_WIDTH tabs or +# CONTINUATION_INDENT_WIDTH spaces) for continuation alignment. +# - VALIGN-RIGHT: Vertically align continuation lines to multiple of +# INDENT_WIDTH columns. Slightly right (one tab or a few spaces) if +# cannot vertically align continuation lines with indent characters. +continuation_align_style=SPACE + +# Indent width used for line continuations. +continuation_indent_width=4 + +# Put closing brackets on a separate line, dedented, if the bracketed +# expression can't fit in a single line. Applies to all kinds of brackets, +# including function definitions and calls. For example: +# +# config = { +# 'key1': 'value1', +# 'key2': 'value2', +# } # <--- this bracket is dedented and on a separate line +# +# time_series = self.remote_client.query_entity_counters( +# entity='dev3246.region1', +# key='dns.query_latency_tcp', +# transform=Transformation.AVERAGE(window=timedelta(seconds=60)), +# start_ts=now()-timedelta(days=3), +# end_ts=now(), +# ) # <--- this bracket is dedented and on a separate line +dedent_closing_brackets=False + +# Disable the heuristic which places each list element on a separate line +# if the list is comma-terminated. +disable_ending_comma_heuristic=False + +# Place each dictionary entry onto its own line. +each_dict_entry_on_separate_line=True + +# Require multiline dictionary even if it would normally fit on one line. +# For example: +# +# config = { +# 'key1': 'value1' +# } +force_multiline_dict=False + +# The regex for an i18n comment. The presence of this comment stops +# reformatting of that line, because the comments are required to be +# next to the string they translate. +i18n_comment=#\..* + +# The i18n function call names. The presence of this function stops +# reformattting on that line, because the string it has cannot be moved +# away from the i18n comment. +i18n_function_call=N_, _ + +# Indent blank lines. +indent_blank_lines=False + +# Put closing brackets on a separate line, indented, if the bracketed +# expression can't fit in a single line. Applies to all kinds of brackets, +# including function definitions and calls. For example: +# +# config = { +# 'key1': 'value1', +# 'key2': 'value2', +# } # <--- this bracket is indented and on a separate line +# +# time_series = self.remote_client.query_entity_counters( +# entity='dev3246.region1', +# key='dns.query_latency_tcp', +# transform=Transformation.AVERAGE(window=timedelta(seconds=60)), +# start_ts=now()-timedelta(days=3), +# end_ts=now(), +# ) # <--- this bracket is indented and on a separate line +indent_closing_brackets=False + +# Indent the dictionary value if it cannot fit on the same line as the +# dictionary key. For example: +# +# config = { +# 'key1': +# 'value1', +# 'key2': value1 + +# value2, +# } +indent_dictionary_value=True + +# The number of columns to use for indentation. +indent_width=4 + +# Join short lines into one line. E.g., single line 'if' statements. +join_multiple_lines=False + +# Do not include spaces around selected binary operators. For example: +# +# 1 + 2 * 3 - 4 / 5 +# +# will be formatted as follows when configured with "*,/": +# +# 1 + 2*3 - 4/5 +no_spaces_around_selected_binary_operators= + +# Use spaces around default or named assigns. +spaces_around_default_or_named_assign=False + +# Adds a space after the opening '{' and before the ending '}' dict delimiters. +# +# {1: 2} +# +# will be formatted as: +# +# { 1: 2 } +spaces_around_dict_delimiters=False + +# Adds a space after the opening '[' and before the ending ']' list delimiters. +# +# [1, 2] +# +# will be formatted as: +# +# [ 1, 2 ] +spaces_around_list_delimiters=False + +# Use spaces around the power operator. +spaces_around_power_operator=False + +# Use spaces around the subscript / slice operator. For example: +# +# my_list[1 : 10 : 2] +spaces_around_subscript_colon=False + +# Adds a space after the opening '(' and before the ending ')' tuple delimiters. +# +# (1, 2, 3) +# +# will be formatted as: +# +# ( 1, 2, 3 ) +spaces_around_tuple_delimiters=False + +# The number of spaces required before a trailing comment. +# This can be a single value (representing the number of spaces +# before each trailing comment) or list of values (representing +# alignment column values; trailing comments within a block will +# be aligned to the first column value that is greater than the maximum +# line length within the block). For example: +# +# With spaces_before_comment=5: +# +# 1 + 1 # Adding values +# +# will be formatted as: +# +# 1 + 1 # Adding values <-- 5 spaces between the end of the statement and comment +# +# With spaces_before_comment=15, 20: +# +# 1 + 1 # Adding values +# two + two # More adding +# +# longer_statement # This is a longer statement +# short # This is a shorter statement +# +# a_very_long_statement_that_extends_beyond_the_final_column # Comment +# short # This is a shorter statement +# +# will be formatted as: +# +# 1 + 1 # Adding values <-- end of line comments in block aligned to col 15 +# two + two # More adding +# +# longer_statement # This is a longer statement <-- end of line comments in block aligned to col 20 +# short # This is a shorter statement +# +# a_very_long_statement_that_extends_beyond_the_final_column # Comment <-- the end of line comments are aligned based on the line length +# short # This is a shorter statement +# +spaces_before_comment=2 + +# Insert a space between the ending comma and closing bracket of a list, +# etc. +space_between_ending_comma_and_closing_bracket=False + +# Use spaces inside brackets, braces, and parentheses. For example: +# +# method_call( 1 ) +# my_dict[ 3 ][ 1 ][ get_index( *args, **kwargs ) ] +# my_set = { 1, 2, 3 } +space_inside_brackets=False + +# Split before arguments +split_all_comma_separated_values=False + +# Split before arguments, but do not split all subexpressions recursively +# (unless needed). +split_all_top_level_comma_separated_values=False + +# Split before arguments if the argument list is terminated by a +# comma. +split_arguments_when_comma_terminated=False + +# Set to True to prefer splitting before '+', '-', '*', '/', '//', or '@' +# rather than after. +split_before_arithmetic_operator=False + +# Set to True to prefer splitting before '&', '|' or '^' rather than +# after. +split_before_bitwise_operator=False + +# Split before the closing bracket if a list or dict literal doesn't fit on +# a single line. +split_before_closing_bracket=True + +# Split before a dictionary or set generator (comp_for). For example, note +# the split before the 'for': +# +# foo = { +# variable: 'Hello world, have a nice day!' +# for variable in bar if variable != 42 +# } +split_before_dict_set_generator=False + +# Split before the '.' if we need to split a longer expression: +# +# foo = ('This is a really long string: {}, {}, {}, {}'.format(a, b, c, d)) +# +# would reformat to something like: +# +# foo = ('This is a really long string: {}, {}, {}, {}' +# .format(a, b, c, d)) +split_before_dot=False + +# Split after the opening paren which surrounds an expression if it doesn't +# fit on a single line. +split_before_expression_after_opening_paren=False + +# If an argument / parameter list is going to be split, then split before +# the first argument. +split_before_first_argument=False + +# Set to True to prefer splitting before 'and' or 'or' rather than +# after. +split_before_logical_operator=False + +# Split named assignments onto individual lines. +split_before_named_assigns=True + +# Set to True to split list comprehensions and generators that have +# non-trivial expressions and multiple clauses before each of these +# clauses. For example: +# +# result = [ +# a_long_var + 100 for a_long_var in xrange(1000) +# if a_long_var % 10] +# +# would reformat to something like: +# +# result = [ +# a_long_var + 100 +# for a_long_var in xrange(1000) +# if a_long_var % 10] +split_complex_comprehension=True + +# The penalty for splitting right after the opening bracket. +split_penalty_after_opening_bracket=300 + +# The penalty for splitting the line after a unary operator. +split_penalty_after_unary_operator=10000 + +# The penalty of splitting the line around the '+', '-', '*', '/', '//', +# ``%``, and '@' operators. +split_penalty_arithmetic_operator=300 + +# The penalty for splitting right before an if expression. +split_penalty_before_if_expr=0 + +# The penalty of splitting the line around the '&', '|', and '^' +# operators. +split_penalty_bitwise_operator=300 + +# The penalty for splitting a list comprehension or generator +# expression. +split_penalty_comprehension=2100 + +# The penalty for characters over the column limit. +split_penalty_excess_character=7000 + +# The penalty incurred by adding a line split to the unwrapped line. The +# more line splits added the higher the penalty. +split_penalty_for_added_line_split=30 + +# The penalty of splitting a list of "import as" names. For example: +# +# from a_very_long_or_indented_module_name_yada_yad import (long_argument_1, +# long_argument_2, +# long_argument_3) +# +# would reformat to something like: +# +# from a_very_long_or_indented_module_name_yada_yad import ( +# long_argument_1, long_argument_2, long_argument_3) +split_penalty_import_names=0 + +# The penalty of splitting the line around the 'and' and 'or' +# operators. +split_penalty_logical_operator=300 + +# Use the Tab character for indentation. +use_tabs=False diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..41dd9eb --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,127 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..b78bda1 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,61 @@ +# Contributing to PETNet + +Thank you for investing your time in contributing to PETNet! + +Read our [Code of Conduct](CODE_OF_CONDUCT.md) to keep our community approachable and respectable. + +This guide details how to use issues and pull requests to improve PETNet. + +## General Guidelines + +### Pull Requests + +Make sure to keep Pull Requests small and functional to make them easier to review, understand, and look up in commit history. This repository uses "Squash and Commit" to keep our history clean and make it easier to revert changes based on PR. + +Adding the appropriate documentation, unit tests and e2e tests as part of a feature is the responsibility of the feature owner, whether it is done in the same Pull Request or not. + +Pull Requests should follow the "subject: message" format, where the subject describes what part of the code is being modified. + +Refer to the template for more information on what goes into a PR description. + +### Design Docs + +A contributor proposes a design with a PR on the repository to allow for revisions and discussions. If a design needs to be discussed before formulating a document for it, make use of Google doc and GitHub issue to involve the community on the discussion. + +### GitHub Issues + +GitHub Issues are used to file bugs, work items, and feature requests with actionable items/issues (Please refer to the "Reporting Bugs/Feature Requests" section below for more information). + +### Reporting Bugs/Feature Requests + +We welcome you to use the GitHub issue tracker to report bugs or suggest features that have actionable items/issues (as opposed to introducing a feature request on GitHub Discussions). + +When filing an issue, please check existing open, or recently closed, issues to make sure somebody else hasn't already reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: + +- A reproducible test case or series of steps +- The version of the code being used +- Any modifications you've made relevant to the bug +- Anything unusual about your environment or deployment + +## Contributing via Pull Requests + +### Find interesting issue + +If you spot a problem with the problem, [search if an issue already exists](https://github.com/tiktok-privacy-innovation/PETNet/issues). If a related issue doesn't exist, you can open a new issue using [issue template](https://github.com/tiktok-privacy-innovation/PETNet/issues/new/choose). + +### Solve an issue + +Please check `DEVELOPMENT.md` in sub folder to get familar with running and testing codes. + +### Open a Pull request. + +When you're done making the changes, open a pull request and fill PR template so we can better review your PR. The template helps reviewers understand your changes and the purpose of your pull request. + +Don't forget to link PR to issue if you are solving one. + +If you run into any merge issues, checkout this [git tutorial](https://lab.github.com/githubtraining/managing-merge-conflicts) to help you resolve merge conflicts and other issues. + + +## Finding contributions to work on + +Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' and 'good first issue' issues are a great place to start. 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/NOTICE b/NOTICE new file mode 100644 index 0000000..66e0c57 --- /dev/null +++ b/NOTICE @@ -0,0 +1 @@ +Copyright 2024 TikTok Pte. Ltd. diff --git a/README.md b/README.md new file mode 100644 index 0000000..01ca1e9 --- /dev/null +++ b/README.md @@ -0,0 +1,98 @@ +# CryptoDataEngine: A robust engine designed specifically for large scale privacy computing + + +CryptoDataEngine is a robust engine designed specifically for handling large-scale computational problems in privacy computing scenarios. +It provides a powerful solution for distributed privacy computing, +enabling efficient and secure processing of large datasets while ensuring privacy preservation. + + +## Key Features + +- Distributed Privacy Computing: CryptoDataEngine leverages the power of distributed computing to handle large-scale privacy computations. This allows for efficient processing of massive datasets across multiple nodes, significantly improving computational speed and scalability. + +- Support for Single-Machine Multi-Process Parallelism: In addition to distributed parallelism, CryptoDataEngine also supports single-machine multiprocess parallelism. This provides flexibility for different computational needs and resource availability. + +- Integration with Spark: CryptoDataEngine is built to work seamlessly with Spark, a leading platform for distributed data processing. This integration enables CryptoDataEngine to take full advantage of Spark's capabilities in handling large datasets and performing complex computations. + +- Privacy Preservation: At the core of CryptoDataEngine is a strong commitment to privacy. The engine is designed to perform computations in a way that preserves the privacy of the data, making it an ideal solution for scenarios where data privacy is a critical requirement. + + +## Getting Started + +### Requirements + +| System | Toolchain | +|--------|-------------------------------| +| Linux | Python (==3.9), pip(>=23.3.1) | + + +### How to Build + +To build PETNet as a docker image, execute: + +```bash +python3 setup.py sdist bdist_wheel +``` + +### How to Run + +Here is an example to show how to use CryptoDataEngine to parallize privacy computation. + +```python +from crypto_data_engine.context import Context +from crypto_data_engine import PREDEFINED +from crypto_data_engine.data.data_type import DataType + + +class SinglePartyFunction: + def udf(self, index, inputs, outputs, *args, **kwargs): + for idx, input_ in enumerate(inputs): + rows = input_.read() + for row in rows: + row[2] = str(float(row[2]) * (index + 1)) + outputs[idx].save(rows) + return True + + +with Context(work_directory='') as ctx: + local = ctx.csv_dataset( + file_path='../../test/data/a.csv', + data_type=[DataType.Integer, DataType.String, DataType.Float] + ) + # sorted src data + local_sorted = ctx.csv_dataset( + file_path=f'../../test/data/a_sorted.csv', + data_type=[DataType.Integer, DataType.String, DataType.Float] + ) + # final output + # result = ctx.dataset(file_path='../../test/data/result.csv') + result = ctx.csv_dataset() + + ctx.compute(PREDEFINED.SORT_BY_KEY, None, [local], [local_sorted], 1) + + ctx.compute(PREDEFINED.REPARTITION, None, [local_sorted], [], 1) + ctx.compute(None, SinglePartyFunction().udf, [local_sorted], [result]) + ctx.execute() + + print(result.file_path) +``` + + +## Contribution + +Please check [Contributing](CONTRIBUTING.md) for more details. + + +## Code of Conduct + +Please check [Code of Conduct](CODE_OF_CONDUCT.md) for more details. + + +## License + +This project is licensed under the [Apache-2.0 License](LICENSE). + + +## Disclaimers + +This software is not an officially supported product of TikTok. It is provided as-is, without any guarantees or warranties, whether express or implied. diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..2453a39 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +setuptools>=73.0.1 +pyspark~=3.5.1 +dill~=0.3.6 diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..af5b2e5 --- /dev/null +++ b/setup.py @@ -0,0 +1,26 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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. +from setuptools import setup, find_packages + +with open('requirements.txt') as f: + requirements = f.read().splitlines() + +setup(name='crypto-data-engine', + version='0.1.0', + description='crypto-data-engine is a bigdata computing framework for private computing', + author="PrivacyGo-PETPlatform", + author_email="privacygo-petplatform@tiktok.com", + packages=find_packages('src'), + package_dir={'': 'src'}, + install_requires=requirements) diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000..4d6166b --- /dev/null +++ b/src/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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/src/crypto_data_engine/__init__.py b/src/crypto_data_engine/__init__.py new file mode 100644 index 0000000..2576ae1 --- /dev/null +++ b/src/crypto_data_engine/__init__.py @@ -0,0 +1,23 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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. + +from .context import Context +from .constants import PREDEFINED +from .data.base import DatasetBase +from .data.csv_dataset import CSVDataset +from .data.scalar_dataset import ScalarDataset +from .data.data_type import DataType +from .data.data_io import Partition + +__all__ = ["Context", "Partition", "DatasetBase", "CSVDataset", "ScalarDataset", "DataType", "PREDEFINED"] diff --git a/src/crypto_data_engine/constants.py b/src/crypto_data_engine/constants.py new file mode 100644 index 0000000..c9c58a9 --- /dev/null +++ b/src/crypto_data_engine/constants.py @@ -0,0 +1,35 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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. + + +class ByteSize: + B = 1 + KB = 1024 * B + MB = 1024 * KB + GB = 1024 * MB + TB = 1024 * GB + + +class ComputeNodeType: + PREDEFINED = "PREDEFINED" + USER_DEFINED = "USER_DEFINED" + + all = [PREDEFINED, USER_DEFINED] + + +class PREDEFINED: + REPARTITION = "REPARTITION" + SORT_BY_KEY = "SORT_BY_KEY" + SHUFFLE = "SHUFFLE" + GET_UNIQUE_ROWS_FROM_CSV = "GET_UNIQUE_ROWS_FROM_CSV" diff --git a/src/crypto_data_engine/context.py b/src/crypto_data_engine/context.py new file mode 100644 index 0000000..b02474c --- /dev/null +++ b/src/crypto_data_engine/context.py @@ -0,0 +1,101 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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. +from collections import OrderedDict +import logging +import logging.config +import time +from typing import Dict, List + +from crypto_data_engine.constants import ComputeNodeType +from crypto_data_engine.data.csv_dataset import CSVDataset +from crypto_data_engine.data.scalar_dataset import ScalarDataset +from crypto_data_engine.data.data_type import DataTypeBase +from crypto_data_engine.engine import LocalEngine, SparkEngine, EngineBase, ComputingNode +from crypto_data_engine.settings import LOGGING_CONFIG + +logging.config.dictConfig(LOGGING_CONFIG) + + +class Context: + + def __init__(self, **kwargs): + self._datasets = [] + self._dag: Dict[int, "ComputingNode"] = OrderedDict() + self._scheduler = None + self._task_manager = None + self._work_dir = kwargs["work_directory"] + + self._get_engine(**kwargs) + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + + def _get_engine(self, **kwargs): + engine_type = kwargs.get('engine_type', 'local') + if engine_type == 'local': + self._engines: List["EngineBase"] = [LocalEngine(self, **kwargs)] + elif engine_type == 'spark': + self._engines: List["EngineBase"] = [SparkEngine(self, **kwargs)] + else: + raise ValueError(f"unknown engine type {engine_type}") + + def clear(self): + self._dag.clear() + + def close(self): + for engine in self._engines: + engine.close() + + def csv_dataset(self, + file_path: str = None, + data_type: List["DataTypeBase"] = None, + placeholder: bool = False, + partitioner=None, + **kwargs): + dataset = CSVDataset(id_=len(self._datasets), + file_path=file_path, + data_type=data_type, + work_dir=self._work_dir, + placeholder=placeholder, + partitioner=partitioner, + **kwargs) + self._datasets.append(dataset) + return dataset + + def scalar_dataset(self, value, **kwargs): + dataset = ScalarDataset(id_=len(self._datasets), value=value, **kwargs) + self._datasets.append(dataset) + return dataset + + def compute(self, name, func, inputs, outputs, *args, **kwargs): + if name is None and func is None: + raise ValueError(f"name and func not initialized") + function_type = ComputeNodeType.PREDEFINED if name is not None else ComputeNodeType.USER_DEFINED + computing_node = ComputingNode(len(self._dag), function_type, name or func, inputs, outputs, args, kwargs, []) + self._dag[computing_node.id_] = computing_node + return computing_node + + def execute(self): + engine = self._engines[0] + for node in self._dag.values(): + start = time.time() + if node.type == ComputeNodeType.PREDEFINED: + ret = engine.run_predefined(node) + else: + ret = engine.run_udf(node) + time_cost = time.time() - start + logging.info(f"finished executing {node}, ret: {ret}, time cost: {time_cost}") diff --git a/src/crypto_data_engine/data/__init__.py b/src/crypto_data_engine/data/__init__.py new file mode 100644 index 0000000..4d6166b --- /dev/null +++ b/src/crypto_data_engine/data/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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/src/crypto_data_engine/data/base.py b/src/crypto_data_engine/data/base.py new file mode 100644 index 0000000..6ce6c20 --- /dev/null +++ b/src/crypto_data_engine/data/base.py @@ -0,0 +1,46 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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. + + +class DatasetBase: + _partition_num = 1 + + def size(self): + """get estimated data storage size""" + raise NotImplementedError + + def shape(self): + raise NotImplementedError + + def is_placeholder(self): + raise NotImplementedError + + def read_partition(self, index, **kwargs): + raise NotImplementedError + + def save_partition(self, index, data, **kwargs): + raise NotImplementedError + + def collect(self): + raise NotImplementedError + + @property + def partition_num(self): + return self._partition_num + + def repartition(self, partition_num: int): + self._partition_num = partition_num + + def set_partitioner(self, udf): + raise NotImplementedError diff --git a/src/crypto_data_engine/data/csv_dataset.py b/src/crypto_data_engine/data/csv_dataset.py new file mode 100644 index 0000000..bea438d --- /dev/null +++ b/src/crypto_data_engine/data/csv_dataset.py @@ -0,0 +1,200 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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. +import csv +from datetime import datetime +import dill +import os +from pathlib import Path +import random +import shutil +from typing import List + +from crypto_data_engine.data.base import DatasetBase +from crypto_data_engine.data.data_type import DataTypeBase + + +class CSVDataset(DatasetBase): + + def __init__(self, + id_: int, + file_path: str = None, + data_type: List["DataTypeBase"] = None, + header: bool = False, + partition_num: int = 1, + work_dir: str = "", + placeholder: bool = False, + partitioner=None): + self._id = id_ + self._has_header = header + self._data_type = data_type + self._shape = None + self._partition_num = partition_num + self._placeholder = placeholder + self._work_dir = work_dir + self._file_path = file_path or self._generate_random_filepath() + Path(self.file_path).parent.mkdir(parents=True, exist_ok=True) + self._dilled_partitioner = dill.dumps(partitioner) if partitioner is not None else None + self._partitioner = None + + def __str__(self): + return f"CSVDataset(filepath={self.file_path}, partition_num={self.partition_num})" + + def __repr__(self): + return self.__str__() + + @property + def file_path(self): + return self._file_path + + @file_path.setter + def file_path(self, path: str): + self._file_path = path + + @property + def partitioner(self): + if self._partitioner is None: + if self._dilled_partitioner is not None: + self._partitioner = dill.loads(self._dilled_partitioner) + return self._partitioner + + def set_partitioner(self, udf): + self._dilled_partitioner = dill.dumps(udf) + + def is_placeholder(self): + return self._placeholder + + def _generate_random_filepath(self): + now = datetime.now() + timestamp = now.strftime('%Y%m%d%H%M%S') + rand_number = random.randint(1000, 9999) + filename = "f_" + timestamp + "_" + str(rand_number) + '.tmp' + return str((Path(self._work_dir) / 'tmp' / filename).absolute()) + + def has_header(self): + return self._has_header + + def size(self): + if self.is_placeholder(): + return 0 + path = Path(self.file_path).absolute() + if path.exists() is False: + return 0 + else: + return os.path.getsize(str(path)) + + def shape(self): + """ + return the shape of the csv file (number of rows, number of columns) + :return: tuple (nrows, ncols) + """ + if self.is_placeholder(): + self._shape = (0, 0) + else: + path = Path(self.file_path).absolute() + if path.exists() is False: + self._shape = (0, 0) + else: + with path.open("r") as f: + reader = csv.reader(f) + nrows = sum(1 for _ in reader) + f.seek(0) + ncols = len(next(reader)) if nrows > 0 else 0 + nrows = nrows - 1 if self.has_header() else nrows + self._shape = (nrows, ncols) + return self._shape + + def load_row(self, row: List[str], data_type: List["DataTypeBase"] = None): + if data_type is None: + return row + else: + return [data_type[idx].from_str(ele) for idx, ele in enumerate(row)] + + def save_row(self, row: List, data_type: List["DataTypeBase"] = None): + if data_type is None: + return row + else: + return [data_type[idx].to_str(ele) for idx, ele in enumerate(row)] + + def _read_by_row_index(self, start=0, end=None, data_type: List["DataTypeBase"] = None, **_): + data_type = data_type or self._data_type + result = [] + if self.is_placeholder(): + return result + else: + if self.has_header(): + start += 1 + if end is not None: + end += 1 + with open(self.file_path, 'r') as f: + reader = csv.reader(f) + for i, row in enumerate(reader): + if i < start: + continue + if end is not None and i >= end: + break + result.append(self.load_row(row, data_type)) + return result + + def _process_batch(self, batch, index, data_type): + return [self.load_row(row, data_type) for row in batch if self.partitioner(row) % self._partition_num == index] + + def _read_by_partitioner(self, index, data_type: List["DataTypeBase"] = None, **_): + data_type = data_type or self._data_type + result = [] + if self.is_placeholder(): + pass + else: + batch_size = 10000 + with open(self.file_path, 'r') as f: + reader = csv.reader(f) + batch = [] + for row in reader: + batch.append(row) + if len(batch) >= batch_size: + result.extend(self._process_batch(batch, index, data_type)) + batch = [] + if batch: + result.extend(self._process_batch(batch, index, data_type)) + return result + + def read_partition(self, index, data_type: List["DataTypeBase"] = None, **kwargs): + if self.is_placeholder(): + return [] + else: + nrows, _ = self.shape() + if self.partitioner is None: + chunk_size = max((nrows + self._partition_num - 1) // self._partition_num, 1) + start = index * chunk_size + end = min(start + chunk_size, nrows) + return self._read_by_row_index(start, end, data_type=data_type, **kwargs) + else: + return self._read_by_partitioner(index, data_type=data_type, **kwargs) + + def save_partition(self, index, data: List[List[str]], data_type: List["DataTypeBase"] = None, **kwargs): + data_type = data_type or self._data_type + partition_filepath = f"{self.file_path}.partitions.{index}" + with open(partition_filepath, 'w', newline='') as f: + writer = csv.writer(f) + writer.writerows([self.save_row(ele, data_type) for ele in data]) + + def collect(self): + if self.is_placeholder(): + return + partition_paths = [f"{self.file_path}.partitions.{index}" for index in range(self._partition_num)] + with open(self.file_path, 'wb') as outfile: + for path in partition_paths: + path = Path(path) + if path.exists() and path.is_file(): + with open(path, 'rb') as infile: + shutil.copyfileobj(infile, outfile) diff --git a/src/crypto_data_engine/data/data_io.py b/src/crypto_data_engine/data/data_io.py new file mode 100644 index 0000000..bad45ad --- /dev/null +++ b/src/crypto_data_engine/data/data_io.py @@ -0,0 +1,29 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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. +from crypto_data_engine.data.base import DatasetBase + + +class Partition: + + def __init__(self, dataset: "DatasetBase", index: int, num_partitions: int = None): + self._dataset = dataset + self._index = index + if num_partitions is not None: + self._dataset.repartition(partition_num=num_partitions) + + def read(self, **kwargs): + return self._dataset.read_partition(self._index, **kwargs) + + def save(self, data, **kwargs): + return self._dataset.save_partition(self._index, data, **kwargs) diff --git a/src/crypto_data_engine/data/data_type.py b/src/crypto_data_engine/data/data_type.py new file mode 100644 index 0000000..a9987e0 --- /dev/null +++ b/src/crypto_data_engine/data/data_type.py @@ -0,0 +1,72 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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. + + +class DataTypeBase: + + def from_str(self, value: str): + raise NotImplementedError + + def to_str(self, value): + raise NotImplementedError + + +class String(DataTypeBase): + + def from_str(self, value: str) -> str: + return value + + def to_str(self, value: str) -> str: + return value + + +class Integer(DataTypeBase): + + def from_str(self, value: str) -> int: + return int(value) + + def to_str(self, value: int) -> str: + return str(value) + + +class Float(DataTypeBase): + + def from_str(self, value: str) -> float: + return float(value) + + def to_str(self, value: float) -> str: + return str(value) + + +class ZOBool(DataTypeBase): + """ + 0/1 boolean + """ + + def from_str(self, value: str) -> bool: + if value == '1': + return True + elif value == '0': + return False + raise ValueError + + def to_str(self, value: bool) -> str: + return '0' if value is False else '1' + + +class DataType: + Integer = Integer() + Float = Float() + String = String() + ZOBool = ZOBool() diff --git a/src/crypto_data_engine/data/scalar_dataset.py b/src/crypto_data_engine/data/scalar_dataset.py new file mode 100644 index 0000000..0033277 --- /dev/null +++ b/src/crypto_data_engine/data/scalar_dataset.py @@ -0,0 +1,61 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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. +from typing import List + +from crypto_data_engine.data.base import DatasetBase +from crypto_data_engine.data.data_type import DataTypeBase + + +class ScalarDataset(DatasetBase): + + def __init__(self, + id_: int, + value, + data_type: List["DataTypeBase"] = None, + partition_num: int = 1, + placeholder: bool = False): + self._id = id_ + self._data_type = data_type + self._partition_num = partition_num + self._placeholder = placeholder + self._value = value + + def __str__(self): + return f"ScalarDataset(value={self._value}, partition_num={self.partition_num})" + + def __repr__(self): + return self.__str__() + + @property + def value(self): + return self._value + + @value.setter + def value(self, v): + self._value = v + + def is_placeholder(self): + return self._placeholder + + def size(self): + return 1 + + def read_partition(self, index, **kwargs): + return self._value + + def save_partition(self, index, data: List[List[str]], data_type: List["DataTypeBase"] = None, **kwargs): + pass + + def collect(self): + pass diff --git a/src/crypto_data_engine/demo.py b/src/crypto_data_engine/demo.py new file mode 100644 index 0000000..28fbce7 --- /dev/null +++ b/src/crypto_data_engine/demo.py @@ -0,0 +1,142 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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. +import multiprocessing +from typing import List + +from crypto_data_engine.context import Context +from crypto_data_engine.constants import PREDEFINED +from crypto_data_engine.data.data_type import DataType +from crypto_data_engine.data.data_io import Partition + + +class SinglePartyFunction: + + def udf(self, vm, index, inputs, outputs, *_, **__): + if vm is None: + print("vm is None") + else: + print("vm is initialized") + for idx, input_ in enumerate(inputs): + rows = input_.read() + for row in rows: + row[2] = str(float(row[2]) * (index + 1)) + outputs[idx].save(rows) + return True + + +def single_party_demo(index=0): + with Context(work_directory='') as ctx: + local = ctx.csv_dataset(file_path='../../test/data/a.csv', + data_type=[DataType.Integer, DataType.String, DataType.Float]) + # sorted src data + local_sorted = ctx.csv_dataset(file_path=f'../../test/data/a_sorted_{index}.csv', + data_type=[DataType.Integer, DataType.String, DataType.Float]) + # final output + # result = ctx.dataset(file_path='../../test/data/result.csv') + result = ctx.csv_dataset() + + ctx.compute(PREDEFINED.SORT_BY_KEY, None, [local], [local_sorted], 1) + + ctx.compute(PREDEFINED.REPARTITION, None, [local_sorted], [], 1) + ctx.compute(None, SinglePartyFunction().udf, [local_sorted], [result], vm_mode='none') + ctx.execute() + print(index, result.file_path) + + +def scalar_dataset_demo(): + with Context(work_directory='') as ctx: + scalar = ctx.scalar_dataset(value=1.0) + partition = Partition(dataset=scalar, index=0) + print(partition.read()) + + +def user_defined_partitioner_demo(): + + def f(): + + def g(_: List[str]): + return 0 + + return g + + ctx = Context(work_directory='') + local = ctx.csv_dataset(file_path='../../test/data/a.csv', + data_type=[DataType.Integer, DataType.String, DataType.Float], + partitioner=None) + + local.set_partitioner(f()) + local.repartition(2) + partition = Partition(dataset=local, index=0) + print(partition.read()) + partition = Partition(dataset=local, index=1) + print(partition.read()) + + +def multiprocess(): + p1 = multiprocessing.Process(target=single_party_demo, args=(1,)) + p2 = multiprocessing.Process(target=single_party_demo, args=(2,)) + p1.start() + p2.start() + p1.join() + p2.join() + print("end") + + +def get_unique_rows_from_csv_demo(): + with Context(work_directory='') as ctx: + local = ctx.csv_dataset(file_path='../../test/data/unique.csv') + local_unique = ctx.scalar_dataset(value=1.0) + ctx.compute(PREDEFINED.GET_UNIQUE_ROWS_FROM_CSV, None, [local], [local_unique], 0) + ctx.execute() + print(local_unique.value) + partition = Partition(dataset=local_unique, index=0) + print(partition.read()) + # ctx.execute() + + +def new_context(): + ctx = Context(work_directory='.', engine_type='local', max_workers=8) + ctx.close() + + ctx = Context(work_directory='.', engine_type='spark', master_url='1234') + ctx.close() + + +def print_dag(): + with Context(work_directory='') as ctx: + local = ctx.csv_dataset(file_path='../../test/data/a.csv', + data_type=[DataType.Integer, DataType.String, DataType.Float]) + # sorted src data + local_sorted = ctx.csv_dataset(file_path=f'../../test/data/a_sorted.csv', + data_type=[DataType.Integer, DataType.String, DataType.Float]) + # final output + # result = ctx.dataset(file_path='../../test/data/result.csv') + result = ctx.csv_dataset() + + ctx.compute(PREDEFINED.SORT_BY_KEY, None, [local], [local_sorted], 1) + + ctx.compute(PREDEFINED.REPARTITION, None, [local_sorted], [], 1) + ctx.compute(None, SinglePartyFunction().udf, [local_sorted], [result], vm_mode='none') + + print(ctx._dag) + + +if __name__ == '__main__': + # print_dag() + # new_context() + # multiprocess() + single_party_demo() + # scalar_dataset_demo() + # user_defined_partitioner_demo() + # get_unique_rows_from_csv_demo() diff --git a/src/crypto_data_engine/engine/__init__.py b/src/crypto_data_engine/engine/__init__.py new file mode 100644 index 0000000..d82bc5a --- /dev/null +++ b/src/crypto_data_engine/engine/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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. +from crypto_data_engine.engine.compute import ComputingNode +from crypto_data_engine.engine.base import EngineBase +from crypto_data_engine.engine.local.local_engine import LocalEngine +from crypto_data_engine.engine.spark.spark_engine import SparkEngine + +__all__ = [ComputingNode, EngineBase, LocalEngine] diff --git a/src/crypto_data_engine/engine/base.py b/src/crypto_data_engine/engine/base.py new file mode 100644 index 0000000..1a86e5b --- /dev/null +++ b/src/crypto_data_engine/engine/base.py @@ -0,0 +1,26 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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. +from crypto_data_engine.engine.compute import ComputingNode + + +class EngineBase: + + def run_predefined(self, node: "ComputingNode", partition_num: int = None): + raise NotImplementedError + + def run_udf(self, node: "ComputingNode", partition_num: int = None): + raise NotImplementedError + + def close(self): + raise NotImplementedError diff --git a/src/crypto_data_engine/engine/compute.py b/src/crypto_data_engine/engine/compute.py new file mode 100644 index 0000000..ba4c77f --- /dev/null +++ b/src/crypto_data_engine/engine/compute.py @@ -0,0 +1,46 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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. +from dataclasses import dataclass +from typing import Any, Dict, List, Tuple + +from crypto_data_engine.constants import ComputeNodeType +from crypto_data_engine.data.base import DatasetBase + + +@dataclass +class ComputingNode: + id_: int + type: "ComputeNodeType" + content: Any + inputs: List["DatasetBase"] + outputs: List["DatasetBase"] + args: Tuple + kwargs: Dict + depends: List + + def partition_num(self) -> int: + partition_num = self.kwargs.get("partition_num") + if partition_num is None: + partition_nums = [ds._partition_num for ds in self.inputs] + if len(set(partition_nums)) != 1: + raise ValueError("datasets partition num not equal") + else: + partition_num = partition_nums[0] + return partition_num + + def __str__(self): + return f"type={self.type}, inputs={self.inputs}, outputs={self.outputs}, args={self.args}, kwargs={self.kwargs}" + + def __repr__(self): + return self.__str__() diff --git a/src/crypto_data_engine/engine/local/__init__.py b/src/crypto_data_engine/engine/local/__init__.py new file mode 100644 index 0000000..4d6166b --- /dev/null +++ b/src/crypto_data_engine/engine/local/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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/src/crypto_data_engine/engine/local/local_engine.py b/src/crypto_data_engine/engine/local/local_engine.py new file mode 100644 index 0000000..d7a68aa --- /dev/null +++ b/src/crypto_data_engine/engine/local/local_engine.py @@ -0,0 +1,86 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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. +from concurrent.futures import ProcessPoolExecutor, wait +import dill +import logging + +from crypto_data_engine.constants import PREDEFINED +from crypto_data_engine.data.data_io import Partition +from crypto_data_engine.engine import ComputingNode, EngineBase +from crypto_data_engine.engine.local.predefined import csv_sort_by_key, repartition, get_unique_rows_from_csv +from crypto_data_engine.utils.petace_utils import init_duet_vm + + +def udf(func_str, index, inputs, outputs, *args, **kwargs): + func = dill.loads(func_str) + vm, vm_mode = None, kwargs.get('vm_mode', 'duet') + if vm_mode == 'duet': + vm = init_duet_vm(index, kwargs) + return func(vm, inputs, outputs, *args, **kwargs) + + +class LocalEngine(EngineBase): + _predefined = { + PREDEFINED.SORT_BY_KEY: csv_sort_by_key, + PREDEFINED.REPARTITION: repartition, + PREDEFINED.GET_UNIQUE_ROWS_FROM_CSV: get_unique_rows_from_csv + } + + def __init__(self, context, max_workers=4, **_): + self._context = context + self._pool = ProcessPoolExecutor(max_workers=max_workers) + + def run_predefined(self, node: "ComputingNode", *args, **kwargs): + function_name = node.content + if function_name not in self._predefined: + raise ValueError(f"unknown predefined function {node.content}") + else: + f = self._predefined[function_name] + return f(node.inputs, node.outputs, *node.args, **node.kwargs) + + def run_udf(self, node: "ComputingNode", *args, **kwargs): + try: + partition_num = node.partition_num() + futures = [ + self._pool.submit(udf, dill.dumps(node.content), i, + [Partition(ds, i, partition_num) + for ds in node.inputs], [Partition(ds, i, partition_num) + for ds in node.outputs], *node.args, **node.kwargs) + for i in range(partition_num) + ] + + wait(futures) + success, results, errors = True, [], [] + for idx, future in enumerate(futures): + try: + result = future.result() + results.append((idx, result)) + except Exception as e: + errors.append((idx, e)) + if errors: + success = False + + if success is True: + for ds in node.outputs: + ds.collect() + + logging.info("worker tasks finished") + return success, results, errors + except Exception as e: + raise e + + def close(self): + if self._pool is not None: + self._pool.shutdown() + self._pool = None diff --git a/src/crypto_data_engine/engine/local/predefined/__init__.py b/src/crypto_data_engine/engine/local/predefined/__init__.py new file mode 100644 index 0000000..971cd03 --- /dev/null +++ b/src/crypto_data_engine/engine/local/predefined/__init__.py @@ -0,0 +1,16 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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. +from .wrapper import csv_sort_by_key, repartition, get_unique_rows_from_csv + +__all__ = [csv_sort_by_key, repartition, get_unique_rows_from_csv] diff --git a/src/crypto_data_engine/engine/local/predefined/impl.py b/src/crypto_data_engine/engine/local/predefined/impl.py new file mode 100644 index 0000000..d777ace --- /dev/null +++ b/src/crypto_data_engine/engine/local/predefined/impl.py @@ -0,0 +1,55 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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. +from crypto_data_engine.data.csv_dataset import CSVDataset +from crypto_data_engine.data.scalar_dataset import ScalarDataset + + +def csv_sort_by_key_impl(src: "CSVDataset", dst: "CSVDataset", column_index: int): + """ + in memory csv sort + """ + import csv + import operator + + with open(src.file_path, 'r') as f: + reader = csv.reader(f) + data = list(reader) + + data.sort(key=operator.itemgetter(column_index)) + + with open(dst.file_path, 'w', newline='') as f: + writer = csv.writer(f) + writer.writerows(data) + + +def repartition_impl(src: "CSVDataset", partition_num: int): + src.repartition(partition_num) + + +def get_unique_rows_from_csv_impl(src: "CSVDataset", dst: "ScalarDataset", skip_row: int): + import csv + import json + + if skip_row not in [0, 1]: + raise ValueError("skip_row must be 0 or 1") + unique_rows = set() + with open(src.file_path, 'r') as f: + reader = csv.reader(f) + for i in range(skip_row): + next(reader) + for row in reader: + unique_rows.add(tuple(row)) + + unique_rows_sorted = sorted(unique_rows) + dst.value = json.dumps(unique_rows_sorted) diff --git a/src/crypto_data_engine/engine/local/predefined/wrapper.py b/src/crypto_data_engine/engine/local/predefined/wrapper.py new file mode 100644 index 0000000..6ffaf27 --- /dev/null +++ b/src/crypto_data_engine/engine/local/predefined/wrapper.py @@ -0,0 +1,27 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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. +from crypto_data_engine.engine.local.predefined.impl import (csv_sort_by_key_impl, repartition_impl, + get_unique_rows_from_csv_impl) + + +def csv_sort_by_key(inputs, outputs, column_index, *args, **kwargs): + return csv_sort_by_key_impl(inputs[0], outputs[0], column_index) + + +def repartition(inputs, outputs, partition_num, *args, **kwargs): + return repartition_impl(inputs[0], partition_num) + + +def get_unique_rows_from_csv(inputs, outputs, skip_row, *args, **kwargs): + return get_unique_rows_from_csv_impl(inputs[0], outputs[0], skip_row) diff --git a/src/crypto_data_engine/engine/spark/__init__.py b/src/crypto_data_engine/engine/spark/__init__.py new file mode 100644 index 0000000..4d6166b --- /dev/null +++ b/src/crypto_data_engine/engine/spark/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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/src/crypto_data_engine/engine/spark/pyspark_job_scripts/__init__.py b/src/crypto_data_engine/engine/spark/pyspark_job_scripts/__init__.py new file mode 100644 index 0000000..4d6166b --- /dev/null +++ b/src/crypto_data_engine/engine/spark/pyspark_job_scripts/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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/src/crypto_data_engine/engine/spark/pyspark_job_scripts/predefined/__init__.py b/src/crypto_data_engine/engine/spark/pyspark_job_scripts/predefined/__init__.py new file mode 100644 index 0000000..4d6166b --- /dev/null +++ b/src/crypto_data_engine/engine/spark/pyspark_job_scripts/predefined/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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/src/crypto_data_engine/engine/spark/pyspark_job_scripts/predefined/csv_get_unique_rows.py b/src/crypto_data_engine/engine/spark/pyspark_job_scripts/predefined/csv_get_unique_rows.py new file mode 100644 index 0000000..033f44e --- /dev/null +++ b/src/crypto_data_engine/engine/spark/pyspark_job_scripts/predefined/csv_get_unique_rows.py @@ -0,0 +1,72 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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. +import base64 +import json + +import dill +import sys +from typing import List +import uuid + +from pyspark import SparkConf, SparkContext +from pyspark.sql import SparkSession +from pyspark.sql.functions import col + +from crypto_data_engine.data.csv_dataset import CSVDataset +from crypto_data_engine.engine.spark.spark_utils import merge_csv_files + +if __name__ == '__main__': + spark = None + try: + print("csv_sort_by_key application started") + # create spark context session + conf = SparkConf().setAppName("GetUniqueRowsFromCSV") + sc = SparkContext(conf=conf) + spark = SparkSession(sc) + + # get args + pickled_inputs = base64.b64decode(sys.argv[1]) + pickled_outputs = base64.b64decode(sys.argv[2]) + args = json.loads(sys.argv[3]) + skip_row = int(args[0]) + # 'true'/'false' + # header = sys.argv[4] + + inputs: List["CSVDataset"] = dill.loads(pickled_inputs) + outputs: List["CSVDataset"] = dill.loads(pickled_outputs) + + # read csv file + if not isinstance(inputs[0], CSVDataset): + raise ValueError("inputs should be CSVDataset object") + if not isinstance(outputs[0], CSVDataset): + raise ValueError("outputs should be CSVDataset object") + if skip_row not in [0, 1]: + raise ValueError("skip_row must be 0 or 1") + + print(inputs[0].file_path, outputs[0].file_path, skip_row) + + df = spark.read.format("csv").option("header", 'false' if skip_row == 0 else 'true').load(inputs[0].file_path) + df_with_count = df.groupBy(*df.columns).count() + unique_rows_df = df_with_count.filter(col("count") == 1).drop("count") + random_file_path = f"/tmp/{uuid.uuid4()}" + unique_rows_df.write.format('csv').option('header', 'false').mode("overwrite").save(random_file_path) + merge_csv_files(random_file_path, outputs[0].file_path) + print("csv_sort_by_key application finished") + except Exception as e: + print(e) + raise + finally: + if spark: + spark.stop() + print("csv_sort_by_key application exit") diff --git a/src/crypto_data_engine/engine/spark/pyspark_job_scripts/predefined/csv_sort_by_key.py b/src/crypto_data_engine/engine/spark/pyspark_job_scripts/predefined/csv_sort_by_key.py new file mode 100644 index 0000000..b20e786 --- /dev/null +++ b/src/crypto_data_engine/engine/spark/pyspark_job_scripts/predefined/csv_sort_by_key.py @@ -0,0 +1,67 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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. +import base64 +import dill +import json +import sys +from typing import List +import uuid + +from pyspark import SparkConf, SparkContext +from pyspark.sql import SparkSession + +from crypto_data_engine.data.csv_dataset import CSVDataset +from crypto_data_engine.engine.spark.spark_utils import merge_csv_files + +if __name__ == '__main__': + spark = None + try: + print("csv_sort_by_key application started") + # create spark context session + conf = SparkConf().setAppName("Sort CSV by Key") + sc = SparkContext(conf=conf) + spark = SparkSession(sc) + + # get args + pickled_inputs = base64.b64decode(sys.argv[1]) + pickled_outputs = base64.b64decode(sys.argv[2]) + args = json.loads(sys.argv[3]) + sort_column_index = int(args[0]) + # 'true'/'false' + # header = sys.argv[4] + + inputs: List["CSVDataset"] = dill.loads(pickled_inputs) + outputs: List["CSVDataset"] = dill.loads(pickled_outputs) + + # read csv file + if not isinstance(inputs[0], CSVDataset): + raise ValueError("inputs should be CSVDataset object") + if not isinstance(outputs[0], CSVDataset): + raise ValueError("outputs should be CSVDataset object") + + print(inputs[0].file_path, outputs[0].file_path, sort_column_index) + + df = spark.read.format("csv").option("header", 'false').load(inputs[0].file_path) + sorted_df = df.sort(df.columns[sort_column_index]) + random_file_path = f"/tmp/{uuid.uuid4()}" + sorted_df.write.format('csv').option('header', 'false').mode("overwrite").save(random_file_path) + merge_csv_files(random_file_path, outputs[0].file_path) + print("csv_sort_by_key application finished") + except Exception as e: + print(e) + raise + finally: + if spark: + spark.stop() + print("csv_sort_by_key application exit") diff --git a/src/crypto_data_engine/engine/spark/pyspark_job_scripts/udf.py b/src/crypto_data_engine/engine/spark/pyspark_job_scripts/udf.py new file mode 100644 index 0000000..d2c4e15 --- /dev/null +++ b/src/crypto_data_engine/engine/spark/pyspark_job_scripts/udf.py @@ -0,0 +1,69 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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. +import base64 +import dill +import json +import sys +from typing import List + +from pyspark import SparkConf, SparkContext +from pyspark.sql import SparkSession + +from crypto_data_engine.data.data_io import Partition +from crypto_data_engine.data.base import DatasetBase +from crypto_data_engine.data.csv_dataset import CSVDataset +from crypto_data_engine.data.scalar_dataset import ScalarDataset +from crypto_data_engine.utils.petace_utils import init_duet_vm + +pickled_udf = base64.b64decode(sys.argv[1]) +pickled_inputs = base64.b64decode(sys.argv[2]) +pickled_outputs = base64.b64decode(sys.argv[3]) +partition_num = int(sys.argv[4]) +args = json.loads(sys.argv[5]) +kwargs = json.loads(sys.argv[6]) + + +def map_func(index, iterator): + # parse parameters + udf = dill.loads(pickled_udf) + inputs: List["DatasetBase"] = dill.loads(pickled_inputs) + outputs: List["DatasetBase"] = dill.loads(pickled_outputs) + + vm, vm_mode = None, kwargs.get('vm_mode', 'duet') + if vm_mode == 'duet': + vm = init_duet_vm(index, kwargs) + udf(vm, [Partition(ds, index, partition_num) for ds in inputs], + [Partition(ds, index, partition_num) for ds in outputs], *args, **kwargs) + return iterator + + +if __name__ == '__main__': + spark = None + try: + print("udf application started") + conf = SparkConf().setAppName("Spark UDF Application") + sc = SparkContext(conf=conf) + spark = SparkSession(sc) + + rdd = sc.parallelize(range(partition_num), numSlices=partition_num) + result = rdd.mapPartitionsWithIndex(map_func) + result.collect() + print("udf application finished") + except Exception as e: + print(e) + raise + finally: + if spark: + spark.stop() + print("udf application exit") diff --git a/src/crypto_data_engine/engine/spark/spark_client.py b/src/crypto_data_engine/engine/spark/spark_client.py new file mode 100644 index 0000000..e3a4ec8 --- /dev/null +++ b/src/crypto_data_engine/engine/spark/spark_client.py @@ -0,0 +1,120 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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. +import subprocess +# import requests +# import re +# from typing import List + +import logging + + +class SparkClient: + + def submit_job(self, app_name, script_path, app_args): + raise NotImplementedError + + def status(self, app_id): + raise NotImplementedError + + def stop_job(self, app_id): + raise NotImplementedError + + +class SparkStandaloneClient(SparkClient): + + def __init__(self, master_url, spark_home): + self.master_url = master_url + self.spark_home = spark_home + + # todo: may need more flexible resources config + def get_resource_config(self): + return [ + "--executor-memory", + "4g", + "--executor-cores", + "1", + "--num-executors", + "1", + ] + + # def submit_job(self, app_name: str, script_path: str, app_args: List = None): + # submit_args = [ + # f"{self.spark_home}/bin/spark-submit", + # "--master", f"spark://{self.master_url}:7077", + # "--name", app_name, + # ] + # submit_args += self.get_resource_config() + # submit_args += [script_path] + # if app_args is not None: + # submit_args += app_args + # + # logging.info(submit_args) + # + # process = subprocess.Popen(submit_args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + # app_id = None + # while True: + # line = process.stdout.readline().decode('utf-8') + # logging.info(line) + # if not line: + # break + # match = re.search(r"app ID (\S+)", line) + # if match: + # app_id = match.group(1) + # break + # return app_id + # + # def status(self, app_id): + # response = requests.get(f"http://{self.master_url}:8080/app/?appId={app_id}") + # if response.status_code != 200: + # raise Exception(f"Failed to get Spark Master Web UI: {response.status_code}") + # + # pattern = r'
  • State: (\w+)
  • ' + # match = re.search(pattern, response.text) + # if match is None: + # raise Exception(f"failed to parse job status") + # + # status = match.group(1) + # return status + + # def stop_job(self, app_id): + # stop_args = [ + # f"{self.spark_home}/bin/spark-class", + # "org.apache.spark.deploy.Client", + # "kill", + # f"spark://{self.master_url}:7077", + # app_id + # ] + # process = subprocess.Popen(stop_args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + # stdout, stderr = process.communicate() + # logging.info(stdout) + # logging.info(stderr) + + def submit_and_wait(self, app_name, script_path, app_args): + submit_args = [ + f"{self.spark_home}/bin/spark-submit", + "--master", + f"spark://{self.master_url}:7077", + "--name", + app_name, + ] + submit_args += self.get_resource_config() + submit_args += [script_path] + if app_args is not None: + submit_args += app_args + + logging.info(submit_args) + + process = subprocess.Popen(submit_args, stdout=subprocess.PIPE) + output, _ = process.communicate() + logging.info(output.decode()) diff --git a/src/crypto_data_engine/engine/spark/spark_engine.py b/src/crypto_data_engine/engine/spark/spark_engine.py new file mode 100644 index 0000000..2bfc4d5 --- /dev/null +++ b/src/crypto_data_engine/engine/spark/spark_engine.py @@ -0,0 +1,77 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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. +import base64 +import dill +import json +import os + +from crypto_data_engine.engine import ComputingNode, EngineBase +from crypto_data_engine.constants import PREDEFINED +from crypto_data_engine.engine.local.predefined import repartition, get_unique_rows_from_csv +from crypto_data_engine.engine.spark.spark_client import SparkStandaloneClient + + +class SparkEngine(EngineBase): + _predefined = { + PREDEFINED.SORT_BY_KEY: "csv_sort_by_key.py", + PREDEFINED.REPARTITION: repartition, + PREDEFINED.GET_UNIQUE_ROWS_FROM_CSV: "csv_get_unique_rows.py" + } + _base_path = "." + + def __init__(self, context, master_url=None, spark_home=None, **_): + self._context = context + self.master_url = os.environ.get('MASTER_URL', master_url) + self.spark_home = os.environ.get('SPARK_HOME', spark_home) + self._client = SparkStandaloneClient(self.master_url, self.spark_home) + + def run_predefined(self, node: "ComputingNode", *args, **kwargs): + function_name = node.content + if function_name not in self._predefined: + raise ValueError(f"unknown predefined function {node.content}") + else: + if function_name == PREDEFINED.REPARTITION: + repartition(node.inputs, node.outputs, *node.args, **node.kwargs) + elif function_name == PREDEFINED.GET_UNIQUE_ROWS_FROM_CSV: + get_unique_rows_from_csv(node.inputs, node.outputs, *node.args, **node.kwargs) + else: + script_path = f"{self._base_path}/pyspark_job_scripts/predefined/{self._predefined[function_name]}" + spark_args = [ + base64.b64encode(dill.dumps(node.inputs)), + base64.b64encode(dill.dumps(node.outputs)), + json.dumps(list(node.args)), + json.dumps(node.kwargs) + ] + self._client.submit_and_wait(function_name, script_path, spark_args) + + def run_udf(self, node: "ComputingNode", *args, **kwargs): + try: + args = [ + base64.b64encode(dill.dumps(node.content)), + base64.b64encode(dill.dumps(node.inputs)), + base64.b64encode(dill.dumps(node.outputs)), + str(node.partition_num()), + json.dumps(list(node.args)), + json.dumps(node.kwargs) + ] + script_path = f"{self._base_path}/pyspark_job_scripts/udf.py" + self._client.submit_and_wait("udf", script_path, args) + # collect results + for ds in node.outputs: + ds.collect() + except Exception as e: + raise e + + def close(self): + pass diff --git a/src/crypto_data_engine/engine/spark/spark_utils.py b/src/crypto_data_engine/engine/spark/spark_utils.py new file mode 100644 index 0000000..89f6bf9 --- /dev/null +++ b/src/crypto_data_engine/engine/spark/spark_utils.py @@ -0,0 +1,61 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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. +import os +from pathlib import Path +import shutil + + +def get_spark_work_dir(): + dir_ = None + spark_workdir = os.environ.get("SPARK_WORKDIR") + if spark_workdir is not None: + dir_ = spark_workdir + else: + spark_home = os.environ.get("SPARK_HOME") + if spark_home is not None: + dir_ = f"{spark_home}/work" + else: + home = os.environ.get("HOME") + if home is not None: + dir_ = f"{home}/spark-3.5.1-bin-hadoop3/work" + if dir_ is None or not Path(dir_).exists() or not Path(dir_).is_dir(): + raise Exception("spark work directory not found") + return dir_ + + +def merge_csv_files(output_path, final_output_path): + # 获取所有分区文件的路径 + csv_files = [] + for root, _, files in os.walk(output_path): + for file in files: + if file.endswith(".csv"): + csv_files.append(os.path.join(root, file)) + + # 按文件名排序 + csv_files.sort() + + # 打开最终输出文件 + with open(final_output_path, 'wb') as outfile: + # 遍历每个 CSV 文件 + for i, file in enumerate(csv_files): + with open(file, 'rb') as infile: + # 将整个文件内容读取并写入到最终输出文件 + shutil.copyfileobj(infile, outfile) + # 如果不是最后一个文件,添加换行符 + if i < len(csv_files) - 1: + outfile.write(b'\n') + + +if __name__ == '__main__': + merge_csv_files('/tmp/sorted', '/tmp/a_sorted.csv') diff --git a/src/crypto_data_engine/settings.py b/src/crypto_data_engine/settings.py new file mode 100644 index 0000000..b7b9677 --- /dev/null +++ b/src/crypto_data_engine/settings.py @@ -0,0 +1,44 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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. +import platform + +# ============================ LOGGING =================================== +FILE_LOG_PATH = 'crypto-data-engine.log' + +LOGGING_CONFIG = { + 'version': 1, + 'disable_existing_loggers': False, + 'formatters': { + 'default': { + 'format': '%(asctime)s %(levelname)s %(message)s' + } + }, + 'handlers': { + 'console': { + 'level': 'INFO', + 'class': 'logging.StreamHandler', + 'formatter': 'default', + }, + 'file': { + 'level': 'INFO', + 'class': 'logging.FileHandler', + 'filename': FILE_LOG_PATH, + 'formatter': 'default' + } + }, + 'root': { + 'handlers': ['console', 'file'], + 'level': "INFO" + } +} diff --git a/src/crypto_data_engine/utils/__init__.py b/src/crypto_data_engine/utils/__init__.py new file mode 100644 index 0000000..4d6166b --- /dev/null +++ b/src/crypto_data_engine/utils/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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/src/crypto_data_engine/utils/petace_utils.py b/src/crypto_data_engine/utils/petace_utils.py new file mode 100644 index 0000000..95e4175 --- /dev/null +++ b/src/crypto_data_engine/utils/petace_utils.py @@ -0,0 +1,70 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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. +from enum import Enum +from typing import Dict + + +class NetworkType(Enum): + SOCKET = "socket" + AGENT = "agent" + + +class NetworkManger: + + def __init__(self, type: NetworkType, params: Dict): + """ + for socket: + { + "remote_addr": "127.0.0.1" + "remote_port_base": 8890 + "local_port_base": 8891 + } + """ + self.type = type + self.params = params + + def get_network(self, count, index): + from petace.network import NetParams, NetScheme, NetFactory + net_scheme, net_params = None, NetParams() + if self.type == NetworkType.SOCKET: + net_scheme = NetScheme.SOCKET + net_params.remote_addr = self.params["remote_addr"] + net_params.remote_port = self.params["remote_port_base"] + (count * 7 % 1000) + index + net_params.local_port = self.params["local_port_base"] + (count * 7 % 1000) + index + print("port: ", net_params.local_port) + elif self.type == NetworkType.AGENT: + net_scheme = NetScheme.AGENT + net_params.shared_topic = f"{self.params['shared_topic']}:{count}:{index}" + net_params.local_agent = self.params["local_agent"] + net_params.remote_party = self.params["remote_party"] + else: + raise ValueError(f"unknown network type {self.type}") + return NetFactory.get_instance().build(net_scheme, net_params) + + +def init_duet_vm(index, kwargs): + from petace.duet.pyduet import DuetVM + + party = kwargs['party'] + parties = kwargs['parties'] + count = int(kwargs['count']) + + scheme = kwargs.get('scheme', 'socket') + if scheme not in ['socket', 'agent']: + raise ValueError(f"unknown network scheme {scheme}") + network_type = NetworkType.SOCKET if scheme == 'socket' else NetworkType.AGENT + network_manager = NetworkManger(type=network_type, params=parties[party]) + network = network_manager.get_network(count, index) + vm = DuetVM(network, int(party)) + return vm diff --git a/test/data/a.csv b/test/data/a.csv new file mode 100644 index 0000000..404a3e7 --- /dev/null +++ b/test/data/a.csv @@ -0,0 +1,100 @@ +1,4eNDD,35.742209891057406 +2,upDfd,22.042113017574426 +3,YYFLT,19.997519702217083 +4,GWSQO,71.19080820939074 +5,gGkPo,11.395150697851964 +6,U8TcM,80.00120002696609 +7,xzicB,71.74360668535775 +8,uL2jm,59.88785227536888 +9,c2rmH,26.48060007390255 +10,B4Sg5,56.777581905729704 +11,VgGxz,42.4874478501282 +12,0T6eJ,31.15271384138295 +13,lrt0b,67.89711490554942 +14,vRe7c,85.93063881001424 +15,ofTwu,58.946715551785445 +16,Dw26x,63.02691181449165 +17,UFgjy,26.31654549673562 +18,wCG1l,53.94029690217228 +19,NTC06,92.48339174538208 +20,LtQ4d,17.981794858922783 +21,pcmyk,8.513074426503731 +22,ysDrz,16.653597569336654 +23,RhbNt,63.379514635267256 +24,KyLvp,79.89496651511219 +25,mW7pn,21.666353991926755 +26,afYZ0,61.482517416177316 +27,fh0uy,91.80372300673079 +28,dS32I,42.22430175897467 +29,E9O0w,32.18901854697334 +30,RqvvD,80.75680869262045 +31,eoLxk,84.61029985223165 +32,0Hofj,57.46263778833084 +33,QTwJd,65.08895377039133 +34,VsPPx,55.14932104205389 +35,eUm9O,54.71776673337292 +36,azUXp,91.69363505428603 +37,aWUqC,33.787848542537034 +38,8C0fM,78.98295089104795 +39,VPWtd,52.20100172481212 +40,2DS6R,60.287093554556606 +41,eAtv7,96.36691423213361 +42,3IXbd,56.45336820532499 +43,rTrta,28.711274728148737 +44,VtRZe,26.30691674511908 +45,eJOxm,42.371467290426246 +46,9hLT6,50.087159954737345 +47,SpITj,1.1678535148897828 +48,2NxIF,60.19570289373494 +49,Lk7iQ,96.75903826667319 +50,GXbT0,88.84405060822289 +51,n82NW,55.30439165955037 +52,xKV1z,19.557795292489466 +53,751yZ,54.71638429997404 +54,QnUwW,20.863893531256128 +55,T8fxe,7.568541251694006 +56,IASIn,38.213802141035394 +57,xZZxj,8.838853561357762 +58,1E3kL,20.48854833817485 +59,AakOR,80.26035738134372 +60,ZwLPU,56.97026618378822 +61,Vpack,0.9558008322402833 +62,OlLPY,39.38711354176184 +63,syavV,43.919987509697556 +64,hv1Pf,30.887055243361207 +65,CTQg5,13.692988467263788 +66,uIQaB,33.47803240319812 +67,gNtSP,94.30075479068208 +68,Ye0I5,28.702854483319605 +69,4UfzH,40.61101832093473 +70,KFfFb,66.25064142675794 +71,ceWJB,34.084832140658875 +72,OjdZu,85.29052976662346 +73,mh5fu,73.17939330431328 +74,7BYVs,79.74518827930201 +75,AucXQ,61.53761952180076 +76,KI6B2,87.83360990741339 +77,nCSVz,87.52734529452752 +78,1W8wd,7.4059522196293965 +79,9waIp,48.44142171879285 +80,0hxlM,32.388023969318084 +81,m7Kco,24.9826598154667 +82,mErQw,2.3383487623848342 +83,Hrnzs,4.966532134326229 +84,Rf4cF,8.76209582837635 +85,UqGKD,57.28890779084627 +86,iZ3d3,91.1643577892994 +87,SjbqH,66.71314019972554 +88,Vvkhn,27.110318250643274 +89,uzj5Z,29.55391877874152 +90,jA37r,1.74936138155658 +91,bH0mx,68.36336965646373 +92,HyhGN,14.150615905476016 +93,4CA7n,5.746668157714751 +94,ZEEjJ,1.7531265412177977 +95,fW1rt,27.563889605069804 +96,TNLrD,67.69584723618732 +97,w7r0E,54.457529558141715 +98,xNNXK,96.18446132847131 +99,lTKVb,77.61660489394008 +100,vVYCj,28.713825616987098 diff --git a/test/data/a_sorted_0.csv b/test/data/a_sorted_0.csv new file mode 100644 index 0000000..b2dda39 --- /dev/null +++ b/test/data/a_sorted_0.csv @@ -0,0 +1,100 @@ +32,0Hofj,57.46263778833084 +12,0T6eJ,31.15271384138295 +80,0hxlM,32.388023969318084 +58,1E3kL,20.48854833817485 +78,1W8wd,7.4059522196293965 +40,2DS6R,60.287093554556606 +48,2NxIF,60.19570289373494 +42,3IXbd,56.45336820532499 +93,4CA7n,5.746668157714751 +69,4UfzH,40.61101832093473 +1,4eNDD,35.742209891057406 +53,751yZ,54.71638429997404 +74,7BYVs,79.74518827930201 +38,8C0fM,78.98295089104795 +46,9hLT6,50.087159954737345 +79,9waIp,48.44142171879285 +59,AakOR,80.26035738134372 +75,AucXQ,61.53761952180076 +10,B4Sg5,56.777581905729704 +65,CTQg5,13.692988467263788 +16,Dw26x,63.02691181449165 +29,E9O0w,32.18901854697334 +4,GWSQO,71.19080820939074 +50,GXbT0,88.84405060822289 +83,Hrnzs,4.966532134326229 +92,HyhGN,14.150615905476016 +56,IASIn,38.213802141035394 +70,KFfFb,66.25064142675794 +76,KI6B2,87.83360990741339 +24,KyLvp,79.89496651511219 +49,Lk7iQ,96.75903826667319 +20,LtQ4d,17.981794858922783 +19,NTC06,92.48339174538208 +72,OjdZu,85.29052976662346 +62,OlLPY,39.38711354176184 +33,QTwJd,65.08895377039133 +54,QnUwW,20.863893531256128 +84,Rf4cF,8.76209582837635 +23,RhbNt,63.379514635267256 +30,RqvvD,80.75680869262045 +87,SjbqH,66.71314019972554 +47,SpITj,1.1678535148897828 +55,T8fxe,7.568541251694006 +96,TNLrD,67.69584723618732 +6,U8TcM,80.00120002696609 +17,UFgjy,26.31654549673562 +85,UqGKD,57.28890779084627 +39,VPWtd,52.20100172481212 +11,VgGxz,42.4874478501282 +61,Vpack,0.9558008322402833 +34,VsPPx,55.14932104205389 +44,VtRZe,26.30691674511908 +88,Vvkhn,27.110318250643274 +3,YYFLT,19.997519702217083 +68,Ye0I5,28.702854483319605 +94,ZEEjJ,1.7531265412177977 +60,ZwLPU,56.97026618378822 +37,aWUqC,33.787848542537034 +26,afYZ0,61.482517416177316 +36,azUXp,91.69363505428603 +91,bH0mx,68.36336965646373 +9,c2rmH,26.48060007390255 +71,ceWJB,34.084832140658875 +28,dS32I,42.22430175897467 +41,eAtv7,96.36691423213361 +45,eJOxm,42.371467290426246 +35,eUm9O,54.71776673337292 +31,eoLxk,84.61029985223165 +95,fW1rt,27.563889605069804 +27,fh0uy,91.80372300673079 +5,gGkPo,11.395150697851964 +67,gNtSP,94.30075479068208 +64,hv1Pf,30.887055243361207 +86,iZ3d3,91.1643577892994 +90,jA37r,1.74936138155658 +99,lTKVb,77.61660489394008 +13,lrt0b,67.89711490554942 +81,m7Kco,24.9826598154667 +82,mErQw,2.3383487623848342 +25,mW7pn,21.666353991926755 +73,mh5fu,73.17939330431328 +51,n82NW,55.30439165955037 +77,nCSVz,87.52734529452752 +15,ofTwu,58.946715551785445 +21,pcmyk,8.513074426503731 +43,rTrta,28.711274728148737 +63,syavV,43.919987509697556 +66,uIQaB,33.47803240319812 +8,uL2jm,59.88785227536888 +2,upDfd,22.042113017574426 +89,uzj5Z,29.55391877874152 +14,vRe7c,85.93063881001424 +100,vVYCj,28.713825616987098 +97,w7r0E,54.457529558141715 +18,wCG1l,53.94029690217228 +52,xKV1z,19.557795292489466 +98,xNNXK,96.18446132847131 +57,xZZxj,8.838853561357762 +7,xzicB,71.74360668535775 +22,ysDrz,16.653597569336654 diff --git a/test/data/a_sorted_1.csv b/test/data/a_sorted_1.csv new file mode 100644 index 0000000..b2dda39 --- /dev/null +++ b/test/data/a_sorted_1.csv @@ -0,0 +1,100 @@ +32,0Hofj,57.46263778833084 +12,0T6eJ,31.15271384138295 +80,0hxlM,32.388023969318084 +58,1E3kL,20.48854833817485 +78,1W8wd,7.4059522196293965 +40,2DS6R,60.287093554556606 +48,2NxIF,60.19570289373494 +42,3IXbd,56.45336820532499 +93,4CA7n,5.746668157714751 +69,4UfzH,40.61101832093473 +1,4eNDD,35.742209891057406 +53,751yZ,54.71638429997404 +74,7BYVs,79.74518827930201 +38,8C0fM,78.98295089104795 +46,9hLT6,50.087159954737345 +79,9waIp,48.44142171879285 +59,AakOR,80.26035738134372 +75,AucXQ,61.53761952180076 +10,B4Sg5,56.777581905729704 +65,CTQg5,13.692988467263788 +16,Dw26x,63.02691181449165 +29,E9O0w,32.18901854697334 +4,GWSQO,71.19080820939074 +50,GXbT0,88.84405060822289 +83,Hrnzs,4.966532134326229 +92,HyhGN,14.150615905476016 +56,IASIn,38.213802141035394 +70,KFfFb,66.25064142675794 +76,KI6B2,87.83360990741339 +24,KyLvp,79.89496651511219 +49,Lk7iQ,96.75903826667319 +20,LtQ4d,17.981794858922783 +19,NTC06,92.48339174538208 +72,OjdZu,85.29052976662346 +62,OlLPY,39.38711354176184 +33,QTwJd,65.08895377039133 +54,QnUwW,20.863893531256128 +84,Rf4cF,8.76209582837635 +23,RhbNt,63.379514635267256 +30,RqvvD,80.75680869262045 +87,SjbqH,66.71314019972554 +47,SpITj,1.1678535148897828 +55,T8fxe,7.568541251694006 +96,TNLrD,67.69584723618732 +6,U8TcM,80.00120002696609 +17,UFgjy,26.31654549673562 +85,UqGKD,57.28890779084627 +39,VPWtd,52.20100172481212 +11,VgGxz,42.4874478501282 +61,Vpack,0.9558008322402833 +34,VsPPx,55.14932104205389 +44,VtRZe,26.30691674511908 +88,Vvkhn,27.110318250643274 +3,YYFLT,19.997519702217083 +68,Ye0I5,28.702854483319605 +94,ZEEjJ,1.7531265412177977 +60,ZwLPU,56.97026618378822 +37,aWUqC,33.787848542537034 +26,afYZ0,61.482517416177316 +36,azUXp,91.69363505428603 +91,bH0mx,68.36336965646373 +9,c2rmH,26.48060007390255 +71,ceWJB,34.084832140658875 +28,dS32I,42.22430175897467 +41,eAtv7,96.36691423213361 +45,eJOxm,42.371467290426246 +35,eUm9O,54.71776673337292 +31,eoLxk,84.61029985223165 +95,fW1rt,27.563889605069804 +27,fh0uy,91.80372300673079 +5,gGkPo,11.395150697851964 +67,gNtSP,94.30075479068208 +64,hv1Pf,30.887055243361207 +86,iZ3d3,91.1643577892994 +90,jA37r,1.74936138155658 +99,lTKVb,77.61660489394008 +13,lrt0b,67.89711490554942 +81,m7Kco,24.9826598154667 +82,mErQw,2.3383487623848342 +25,mW7pn,21.666353991926755 +73,mh5fu,73.17939330431328 +51,n82NW,55.30439165955037 +77,nCSVz,87.52734529452752 +15,ofTwu,58.946715551785445 +21,pcmyk,8.513074426503731 +43,rTrta,28.711274728148737 +63,syavV,43.919987509697556 +66,uIQaB,33.47803240319812 +8,uL2jm,59.88785227536888 +2,upDfd,22.042113017574426 +89,uzj5Z,29.55391877874152 +14,vRe7c,85.93063881001424 +100,vVYCj,28.713825616987098 +97,w7r0E,54.457529558141715 +18,wCG1l,53.94029690217228 +52,xKV1z,19.557795292489466 +98,xNNXK,96.18446132847131 +57,xZZxj,8.838853561357762 +7,xzicB,71.74360668535775 +22,ysDrz,16.653597569336654 diff --git a/test/data/a_sorted_2.csv b/test/data/a_sorted_2.csv new file mode 100644 index 0000000..b2dda39 --- /dev/null +++ b/test/data/a_sorted_2.csv @@ -0,0 +1,100 @@ +32,0Hofj,57.46263778833084 +12,0T6eJ,31.15271384138295 +80,0hxlM,32.388023969318084 +58,1E3kL,20.48854833817485 +78,1W8wd,7.4059522196293965 +40,2DS6R,60.287093554556606 +48,2NxIF,60.19570289373494 +42,3IXbd,56.45336820532499 +93,4CA7n,5.746668157714751 +69,4UfzH,40.61101832093473 +1,4eNDD,35.742209891057406 +53,751yZ,54.71638429997404 +74,7BYVs,79.74518827930201 +38,8C0fM,78.98295089104795 +46,9hLT6,50.087159954737345 +79,9waIp,48.44142171879285 +59,AakOR,80.26035738134372 +75,AucXQ,61.53761952180076 +10,B4Sg5,56.777581905729704 +65,CTQg5,13.692988467263788 +16,Dw26x,63.02691181449165 +29,E9O0w,32.18901854697334 +4,GWSQO,71.19080820939074 +50,GXbT0,88.84405060822289 +83,Hrnzs,4.966532134326229 +92,HyhGN,14.150615905476016 +56,IASIn,38.213802141035394 +70,KFfFb,66.25064142675794 +76,KI6B2,87.83360990741339 +24,KyLvp,79.89496651511219 +49,Lk7iQ,96.75903826667319 +20,LtQ4d,17.981794858922783 +19,NTC06,92.48339174538208 +72,OjdZu,85.29052976662346 +62,OlLPY,39.38711354176184 +33,QTwJd,65.08895377039133 +54,QnUwW,20.863893531256128 +84,Rf4cF,8.76209582837635 +23,RhbNt,63.379514635267256 +30,RqvvD,80.75680869262045 +87,SjbqH,66.71314019972554 +47,SpITj,1.1678535148897828 +55,T8fxe,7.568541251694006 +96,TNLrD,67.69584723618732 +6,U8TcM,80.00120002696609 +17,UFgjy,26.31654549673562 +85,UqGKD,57.28890779084627 +39,VPWtd,52.20100172481212 +11,VgGxz,42.4874478501282 +61,Vpack,0.9558008322402833 +34,VsPPx,55.14932104205389 +44,VtRZe,26.30691674511908 +88,Vvkhn,27.110318250643274 +3,YYFLT,19.997519702217083 +68,Ye0I5,28.702854483319605 +94,ZEEjJ,1.7531265412177977 +60,ZwLPU,56.97026618378822 +37,aWUqC,33.787848542537034 +26,afYZ0,61.482517416177316 +36,azUXp,91.69363505428603 +91,bH0mx,68.36336965646373 +9,c2rmH,26.48060007390255 +71,ceWJB,34.084832140658875 +28,dS32I,42.22430175897467 +41,eAtv7,96.36691423213361 +45,eJOxm,42.371467290426246 +35,eUm9O,54.71776673337292 +31,eoLxk,84.61029985223165 +95,fW1rt,27.563889605069804 +27,fh0uy,91.80372300673079 +5,gGkPo,11.395150697851964 +67,gNtSP,94.30075479068208 +64,hv1Pf,30.887055243361207 +86,iZ3d3,91.1643577892994 +90,jA37r,1.74936138155658 +99,lTKVb,77.61660489394008 +13,lrt0b,67.89711490554942 +81,m7Kco,24.9826598154667 +82,mErQw,2.3383487623848342 +25,mW7pn,21.666353991926755 +73,mh5fu,73.17939330431328 +51,n82NW,55.30439165955037 +77,nCSVz,87.52734529452752 +15,ofTwu,58.946715551785445 +21,pcmyk,8.513074426503731 +43,rTrta,28.711274728148737 +63,syavV,43.919987509697556 +66,uIQaB,33.47803240319812 +8,uL2jm,59.88785227536888 +2,upDfd,22.042113017574426 +89,uzj5Z,29.55391877874152 +14,vRe7c,85.93063881001424 +100,vVYCj,28.713825616987098 +97,w7r0E,54.457529558141715 +18,wCG1l,53.94029690217228 +52,xKV1z,19.557795292489466 +98,xNNXK,96.18446132847131 +57,xZZxj,8.838853561357762 +7,xzicB,71.74360668535775 +22,ysDrz,16.653597569336654 diff --git a/test/data/names.csv b/test/data/names.csv new file mode 100644 index 0000000..62b41fa --- /dev/null +++ b/test/data/names.csv @@ -0,0 +1,20 @@ +John Doe,30,New York +Jane Doe,25,Chicago +Mike Smith,35,San Francisco +Sara Johnson,32,Los Angeles +John Doe,30,New York +Jane Doe,25,Chicago +Mike Smith,35,San Francisco +Sara Johnson,32,Los Angeles +John Doe,30,New York +Jane Doe,25,Chicago +Mike Smith,35,San Francisco +Sara Johnson,32,Los Angeles +John Doe,30,New York +Jane Doe,25,Chicago +Mike Smith,35,San Francisco +Sara Johnson,32,Los Angeles +John Doe,30,New York +Jane Doe,25,Chicago +Mike Smith,35,San Francisco +Sara Johnson,32,Los Angeles diff --git a/test/data/sorted.csv b/test/data/sorted.csv new file mode 100644 index 0000000..9d14fe4 --- /dev/null +++ b/test/data/sorted.csv @@ -0,0 +1,20 @@ +Jane Doe,25,Chicago +Jane Doe,25,Chicago +Jane Doe,25,Chicago +Jane Doe,25,Chicago +Jane Doe,25,Chicago +John Doe,30,New York +John Doe,30,New York +John Doe,30,New York +John Doe,30,New York +John Doe,30,New York +Sara Johnson,32,Los Angeles +Sara Johnson,32,Los Angeles +Sara Johnson,32,Los Angeles +Sara Johnson,32,Los Angeles +Sara Johnson,32,Los Angeles +Mike Smith,35,San Francisco +Mike Smith,35,San Francisco +Mike Smith,35,San Francisco +Mike Smith,35,San Francisco +Mike Smith,35,San Francisco diff --git a/test/data/unique.csv b/test/data/unique.csv new file mode 100644 index 0000000..b221ec6 --- /dev/null +++ b/test/data/unique.csv @@ -0,0 +1,16 @@ +1 +2 +3 +1 +3 +1 +2 +3 +4 +5 +1 +2 +9 +1 +8 +9 diff --git a/test/generate_csv.py b/test/generate_csv.py new file mode 100644 index 0000000..c2da670 --- /dev/null +++ b/test/generate_csv.py @@ -0,0 +1,34 @@ +# Copyright 2024 TikTok Pte. Ltd. +# +# 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. +import csv +import random +import string + + +def generate_csv(filename, num_rows): + with open(filename, 'w', newline='') as f: + writer = csv.writer(f) + # 写入标题行 + # writer.writerow(['id', 'name', 'value']) + # 写入数据行 + for i in range(1, num_rows + 1): + # 生成一个随机字符串作为 'name' + name = ''.join(random.choices(string.ascii_letters + string.digits, k=5)) + # 生成一个随机数作为 'value' + value = random.uniform(0, 100) + writer.writerow([i, name, value]) + + +if __name__ == '__main__': + generate_csv('data/a.csv', 100)