├── groovy ├── version.txt ├── __init__.py └── transpiler.py ├── tests ├── __init__.py └── test_transpiler.py ├── pytest.ini ├── .github └── workflows │ ├── test.yml │ ├── format.yml │ └── publish.yml ├── pyproject.toml ├── .gitignore ├── README.md └── LICENSE /groovy/version.txt: -------------------------------------------------------------------------------- 1 | 0.1.2 -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | # Empty init file to make the tests directory a package 2 | -------------------------------------------------------------------------------- /pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | testpaths = tests 3 | python_files = test_*.py 4 | python_classes = Test* 5 | python_functions = test_* -------------------------------------------------------------------------------- /groovy/__init__.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | 3 | from groovy.transpiler import TranspilerError, transpile 4 | 5 | __version__ = Path(__file__).parent.joinpath("version.txt").read_text().strip() 6 | 7 | __all__ = ["__version__", "transpile", "TranspilerError"] 8 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Unit Tests 2 | 3 | on: 4 | pull_request: 5 | branches: [ main ] 6 | push: 7 | branches: [ main ] 8 | 9 | jobs: 10 | test: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v3 15 | 16 | - name: Set up Python 17 | uses: actions/setup-python@v4 18 | with: 19 | python-version: '3.10' 20 | 21 | - name: Install dependencies 22 | run: | 23 | python -m pip install --upgrade pip 24 | pip install -e . 25 | pip install pytest gradio 26 | 27 | - name: Run tests 28 | run: | 29 | pytest -------------------------------------------------------------------------------- /.github/workflows/format.yml: -------------------------------------------------------------------------------- 1 | name: Format 2 | 3 | on: 4 | pull_request: 5 | branches: [ main ] 6 | push: 7 | branches: [ main ] 8 | 9 | jobs: 10 | format: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v3 15 | 16 | - name: Set up Python 17 | uses: actions/setup-python@v4 18 | with: 19 | python-version: '3.10' 20 | 21 | - name: Install dependencies 22 | run: | 23 | python -m pip install --upgrade pip 24 | pip install ruff 25 | 26 | - name: Check formatting with ruff 27 | run: | 28 | ruff format --check . 29 | 30 | - name: Check code with ruff 31 | run: | 32 | ruff check . -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish to PyPI 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | paths: 8 | - 'groovy/version.txt' 9 | 10 | jobs: 11 | publish: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v4 15 | 16 | - name: Debug - Show version.txt content 17 | run: cat groovy/version.txt 18 | 19 | - name: Set up Python 20 | uses: actions/setup-python@v4 21 | with: 22 | python-version: '3.x' 23 | 24 | - name: Install dependencies 25 | run: | 26 | python -m pip install --upgrade pip 27 | pip install build twine 28 | 29 | - name: Build package 30 | run: python -m build 31 | 32 | - name: Publish to PyPI 33 | env: 34 | TWINE_USERNAME: __token__ 35 | TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }} 36 | run: | 37 | python -m twine upload dist/* -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["hatchling"] 3 | build-backend = "hatchling.build" 4 | 5 | [project] 6 | name = "groovy" 7 | description = "A small Python library created to help developers protect their applications from Server Side Request Forgery (SSRF) attacks." 8 | authors = [ 9 | { name = "Abubakar Abid", email = "abubakar@hf.co" } 10 | ] 11 | readme = "README.md" 12 | requires-python = ">3.9" 13 | dependencies = [ 14 | ] 15 | classifiers = [ 16 | "Programming Language :: Python :: 3", 17 | "License :: OSI Approved :: MIT License", 18 | "Operating System :: OS Independent", 19 | ] 20 | dynamic = ["version"] 21 | 22 | [project.urls] 23 | homepage = "https://github.com/gradio-app/groovy" 24 | repository = "https://github.com/gradio-app/groovy" 25 | 26 | [project.optional-dependencies] 27 | dev = [ 28 | "pytest", 29 | "ruff==0.9.3" 30 | ] 31 | 32 | [tool.hatch.build.targets.wheel] 33 | packages = ["groovy"] 34 | 35 | [tool.hatch.version] 36 | path = "groovy/version.txt" 37 | pattern = "^(?P[0-9]+\\.[0-9]+\\.[0-9]+)$" 38 | 39 | [tool.ruff] 40 | # Exclude a variety of commonly ignored directories. 41 | exclude = [ 42 | ".git", 43 | ".mypy_cache", 44 | ".ruff_cache", 45 | ".venv", 46 | "__pycache__", 47 | "build", 48 | "dist", 49 | ] 50 | 51 | # Same as Black. 52 | line-length = 88 53 | indent-width = 4 54 | 55 | # Assume Python 3.8 56 | target-version = "py38" 57 | 58 | [tool.ruff.lint] 59 | # Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`) 60 | select = ["E", "F", "I"] 61 | # Ignore line length violations 62 | ignore = ["E501"] 63 | 64 | # Allow autofix for all enabled rules (when `--fix`) is provided. 65 | fixable = ["ALL"] 66 | 67 | # Allow unused variables when underscore-prefixed. 68 | dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$" 69 | 70 | [tool.ruff.format] 71 | # Use single quotes for strings. 72 | quote-style = "double" 73 | 74 | # Indent with spaces, rather than tabs. 75 | indent-style = "space" 76 | 77 | # Like Black, respect magic trailing commas. 78 | skip-magic-trailing-comma = false 79 | 80 | # Like Black, automatically detect the appropriate line ending. 81 | line-ending = "auto" 82 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 110 | .pdm.toml 111 | .pdm-python 112 | .pdm-build/ 113 | 114 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 115 | __pypackages__/ 116 | 117 | # Celery stuff 118 | celerybeat-schedule 119 | celerybeat.pid 120 | 121 | # SageMath parsed files 122 | *.sage.py 123 | 124 | # Environments 125 | .env 126 | .venv 127 | env/ 128 | venv/ 129 | ENV/ 130 | env.bak/ 131 | venv.bak/ 132 | 133 | # Spyder project settings 134 | .spyderproject 135 | .spyproject 136 | 137 | # Rope project settings 138 | .ropeproject 139 | 140 | # mkdocs documentation 141 | /site 142 | 143 | # mypy 144 | .mypy_cache/ 145 | .dmypy.json 146 | dmypy.json 147 | 148 | # Pyre type checker 149 | .pyre/ 150 | 151 | # pytype static type analyzer 152 | .pytype/ 153 | 154 | # Cython debug symbols 155 | cython_debug/ 156 | 157 | # PyCharm 158 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 159 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 160 | # and can be added to the global gitignore or merged into this file. For a more nuclear 161 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 162 | #.idea/ 163 | 164 | .ruff_cache/ 165 | recording.gif -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | PyPI 3 | Python version 4 | Format 5 | Test 6 |

7 | 8 | 9 |

10 | 11 |

12 | 13 | Groovy is a Python-to-JavaScript transpiler, meaning that it converts Python functions to their JavaScript equivalents. It is used in the [Gradio](https://gradio.app) library, so that developers can write functions in Python and have them run as fast as client-side JavaScript ⚡. Instead of aiming for full coverage of Python features, groovy prioritizes **clear error reporting** for unsupported Python code, making it easier for developers to modify their functions accordingly. 14 | 15 | ### 🚀 Features 16 | - Converts simple Python functions into JavaScript equivalents. 17 | - Supports a subset of the Python standard library along with some Gradio-specific classes. 18 | - Provides **complete error reporting** when a function can't be transpiled (either due to no equivalent in JavaScript or ambiguity). 19 | 20 | ### 📦 Installation 21 | Install groovy via pip: 22 | ```bash 23 | pip install groovy 24 | ``` 25 | 26 | ### 🔧 Usage 27 | ```python 28 | from groovy import transpile 29 | 30 | def sum_range(n: int): 31 | total = 0 32 | for i in range(n): 33 | total = total + i 34 | return total 35 | 36 | js_code = transpile(sum_range) 37 | print(js_code) 38 | ``` 39 | produces: 40 | 41 | ``` 42 | function sum_range(n) { 43 | let total = 0; 44 | for (let i of Array.from({length: n}, (_, i) => i)) { 45 | total = (total + i); 46 | } 47 | return total; 48 | ``` 49 | 50 | Note that the JavaScript function is not necessarily minimized or optimized (yet) but it should return exactly the same value when called with the same arguments. While the internal implementation of the transpiled JavaScript function may differ slightly from the Python version (e.g. Python tuples may get converted to JS arrays), groovy tries to guarantee that the return values will be identical for the same inputs. 51 | 52 | If groovy encounters unsupported syntax, it will **complain clearly** (throw a `TranspilationError` with all of the issues along with line numbers and the code that caused the issue, making it easy for developers to fix their code. 53 | 54 | 55 | ```python 56 | def example_function(x, y): 57 | z = x + y 58 | if z > 10: 59 | print(z) 60 | else: 61 | print(0) 62 | 63 | transpile(example_function) 64 | ``` 65 | 66 | raises: 67 | 68 | ``` 69 | TranspilerError: 2 issues found: 70 | 71 | * Line 4: Unsupported function "print()" 72 | >> print(z) 73 | * Line 6: Unsupported function "print()" 74 | >> print(0) 75 | ``` 76 | 77 | ### 🤔 Ambiguity 78 | groovy takes a conservative approach when encountering ambiguous types. Instead of making assumptions about types, it will raise a `TranspilationError`. For example, a simple sum function without type hints will fail: 79 | 80 | ```python 81 | def sum(a, b): 82 | return a + b 83 | 84 | transpile(sum) # Raises TranspilationError: Cannot determine types for parameters 'a' and 'b' 85 | ``` 86 | 87 | This is because `+` could mean different things in JavaScript depending on the types (string concatenation vs numeric addition vs. custom behavior for a custom class). Adding type hints (which is **strongly recommended** for all usage) resolves the ambiguity: 88 | 89 | ```python 90 | def sum(a: int, b: int): 91 | return a + b 92 | 93 | transpile(sum) # Works! Produces: function sum(a, b) { return (a + b); } 94 | ``` 95 | 96 | ### 🔥 Supported Syntax 97 | 98 | groovy supports the following Python syntax and built-in functions. Other functions will not be transpiled. 99 | 100 | **General** 101 | 102 | | Python Syntax | JavaScript Equivalent | 103 | |--------------|----------------------| 104 | | `def function(x: int)` | `function function(x)` | 105 | | `x + y`, `x - y`, `x * y`, `x / y` | `(x + y)`, `(x - y)`, `(x * y)`, `(x / y)` | 106 | | `x > y`, `x < y`, `x >= y`, `x <= y` | `(x > y)`, `(x < y)`, `(x >= y)`, `(x <= y)` | 107 | | `x == y`, `x != y` | `(x === y)`, `(x !== y)` | 108 | | `x in list`, `x not in list` | `list.includes(x)`, `!list.includes(x)` | 109 | | `x = value` | `let x = value` | 110 | | `if condition: ... elif: ... else: ...` | `if (condition) { ... } else if { ... } else { ... }` | 111 | | `for x in range(n)` | `for (let x of Array.from({length: n}, (_, i) => i))` | 112 | | `for x in list` | `for (let x of list)` | 113 | | `while condition` | `while (condition)` | 114 | | `[x for x in list if condition]` | `list.filter(x => condition).map(x => x)` | 115 | | `len(list)` | `list.length` | 116 | | `len(dict)` | `Object.keys(dict).length` | 117 | | `[1, 2, 3]` | `[1, 2, 3]` | 118 | | `(1, 2, 3)` | `[1, 2, 3]` | 119 | | `{"key": "value"}` | `{"key": "value"}` | 120 | | `x and y`, `x or y` | `(x && y)`, `(x || y)` | 121 | | `None` | `null` | 122 | 123 | 124 | **Gradio-specific syntax** 125 | 126 | | Python Syntax | JavaScript Equivalent | 127 | |--------------|----------------------| 128 | | `gr.Component(param=value)` | `{"param": "value", "__type__": "update"}` | 129 | 130 | 131 | ### 📜 License 132 | groovy is open-source under the [MIT License](https://github.com/abidlabs/groovy/blob/main/LICENSE). 133 | 134 | --- 135 | Contributions to increase coverage of the Python library that groovy can transpile are welcome! We welcome AI-generated PRs if the rationale is clear to follow, PRs are not too large in scope, and tests are included. 136 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /tests/test_transpiler.py: -------------------------------------------------------------------------------- 1 | import gradio 2 | import pytest 3 | 4 | from groovy.transpiler import TranspilerError, transpile 5 | 6 | 7 | def test_basic_arithmetic_without_type_hints(): 8 | def simple_add(a, b): 9 | return a + b 10 | 11 | with pytest.raises(TranspilerError) as e: 12 | transpile(simple_add) 13 | 14 | assert "Line 2" in str(e.value) 15 | 16 | 17 | def test_basic_arithmetic_with_type_hints(): 18 | def simple_add(a: int, b: int): 19 | return a + b 20 | 21 | expected = """function simple_add(a, b) { 22 | return (a + b); 23 | }""" 24 | assert transpile(simple_add).strip() == expected.strip() 25 | 26 | 27 | def test_if_else(): 28 | def check_value(x: int): 29 | if x > 10: 30 | return "high" 31 | else: 32 | return "low" 33 | 34 | expected = """function check_value(x) { 35 | if ((x > 10)) { 36 | return 'high'; 37 | } 38 | else { 39 | return 'low'; 40 | } 41 | }""" 42 | assert transpile(check_value).strip() == expected.strip() 43 | 44 | 45 | def test_variable_assignment(): 46 | def assign_vars(x: int): 47 | y = x * 2 48 | z = y + 1 49 | return z 50 | 51 | expected = """function assign_vars(x) { 52 | let y = (x * 2); 53 | let z = (y + 1); 54 | return z; 55 | }""" 56 | assert transpile(assign_vars).strip() == expected.strip() 57 | 58 | 59 | def test_for_loop_range(): 60 | def sum_range(n: int): 61 | total = 0 62 | for i in range(n): 63 | total = total + i 64 | return total 65 | 66 | expected = """function sum_range(n) { 67 | let total = 0; 68 | for (let i of Array.from({length: n}, (_, i) => i)) { 69 | total = (total + i); 70 | } 71 | return total; 72 | }""" 73 | assert transpile(sum_range).strip() == expected.strip() 74 | 75 | 76 | def test_while_loop(): 77 | def countdown(n: int): 78 | while n > 0: 79 | n = n - 1 80 | return n 81 | 82 | expected = """function countdown(n) { 83 | while ((n > 0)) { 84 | let n = (n - 1); 85 | } 86 | return n; 87 | }""" 88 | assert transpile(countdown).strip() == expected.strip() 89 | 90 | 91 | def test_list_operations(): 92 | def make_list(x: int): 93 | arr = [1, 2, x] 94 | arr[0] = x 95 | return arr 96 | 97 | expected = """function make_list(x) { 98 | let arr = [1, 2, x]; 99 | arr[0] = x; 100 | return arr; 101 | }""" 102 | assert transpile(make_list).strip() == expected.strip() 103 | 104 | 105 | def test_comparison_operators(): 106 | def compare_values(a: int, b: int): 107 | if a == b: 108 | return "equal" 109 | elif a > b: 110 | return "greater" 111 | else: 112 | return "less" 113 | 114 | expected = """function compare_values(a, b) { 115 | if ((a === b)) { 116 | return 'equal'; 117 | } 118 | else if ((a > b)) { 119 | return 'greater'; 120 | } 121 | else { 122 | return 'less'; 123 | } 124 | }""" 125 | assert transpile(compare_values).strip() == expected.strip() 126 | 127 | 128 | def test_boolean_operations(): 129 | def logical_ops(a: bool, b: bool): 130 | return a and b or not a 131 | 132 | with pytest.raises(TranspilerError) as e: 133 | transpile(logical_ops) 134 | 135 | assert "Line 2" in str(e.value) 136 | 137 | 138 | def test_dict_operations(): 139 | def create_dict(key, value): 140 | d = {"fixed": 42, key: value} 141 | return d 142 | 143 | expected = """function create_dict(key, value) { 144 | let d = {'fixed': 42, key: value}; 145 | return d; 146 | }""" 147 | assert transpile(create_dict).strip() == expected.strip() 148 | 149 | 150 | def test_simple_lambda(): 151 | simple_lambda = lambda x: x # noqa: E731 152 | 153 | expected = """function (x) { 154 | return x; 155 | }""" 156 | assert transpile(simple_lambda).strip() == expected.strip() 157 | 158 | 159 | def test_multi_param_lambda_with_None(): 160 | multi_param = lambda x, y: None # noqa: E731 161 | 162 | expected = """function (x, y) { 163 | return null; 164 | }""" 165 | assert transpile(multi_param).strip() == expected.strip() 166 | 167 | 168 | def test_multiple_return_values(): 169 | def return_multiple(x: int, y: int): 170 | return x, y, x + y 171 | 172 | expected = """function return_multiple(x, y) { 173 | return [x, y, (x + y)]; 174 | }""" 175 | assert transpile(return_multiple).strip() == expected.strip() 176 | 177 | 178 | def test_single_gradio_component(): 179 | def create_textbox(): 180 | return gradio.Textbox(lines=8, visible=True, value="Lorem ipsum") 181 | 182 | expected = """function create_textbox() { 183 | return {"lines": 8, "visible": true, "value": "Lorem ipsum", "__type__": "update"}; 184 | }""" 185 | assert transpile(create_textbox).strip() == expected.strip() 186 | 187 | 188 | def test_multiple_gradio_components(): 189 | def create_interface(): 190 | text_input = gradio.Textbox(label="Input", lines=2) 191 | button = gradio.Button(value="Submit", interactive=True) 192 | output = gradio.Textbox(label="Output") 193 | return text_input, button, output 194 | 195 | expected = """function create_interface() { 196 | let text_input = {"label": "Input", "lines": 2, "__type__": "update"}; 197 | let button = {"value": "Submit", "interactive": true, "__type__": "update"}; 198 | let output = {"label": "Output", "__type__": "update"}; 199 | return [text_input, button, output]; 200 | }""" 201 | assert transpile(create_interface).strip() == expected.strip() 202 | 203 | 204 | def test_len_function(): 205 | def get_length(arr: list, dictionary: dict): 206 | return len(arr), len(dictionary) 207 | 208 | expected = """function get_length(arr, dictionary) { 209 | return [arr.length, Object.keys(dictionary).length]; 210 | }""" 211 | assert transpile(get_length).strip() == expected.strip() 212 | 213 | 214 | def test_list_comprehension_with_in(): 215 | def filter_rows_by_term(data: list, search_term: str) -> list: 216 | return [row for row in data if search_term in row[0]] 217 | 218 | expected = """function filter_rows_by_term(data, search_term) { 219 | return data.filter(row => row[0].includes(search_term)); 220 | }""" 221 | assert transpile(filter_rows_by_term).strip() == expected.strip() 222 | 223 | 224 | def test_validate_no_arguments(): 225 | def no_args_function(): 226 | return gradio.Textbox(placeholder="This is valid") 227 | 228 | result = transpile(no_args_function, validate=True) 229 | expected = """function no_args_function() { 230 | return {"placeholder": "This is valid", "__type__": "update"}; 231 | }""" 232 | assert result.strip() == expected.strip() 233 | 234 | 235 | def test_validate_with_arguments(): 236 | def function_with_args(text_input): 237 | return gradio.Textbox(placeholder=f"You entered: {text_input}") 238 | 239 | with pytest.raises(TranspilerError) as e: 240 | transpile(function_with_args, validate=True) 241 | 242 | assert "text_input" in str(e.value) 243 | 244 | 245 | def test_validate_non_gradio_return(): 246 | def invalid_return_function(): 247 | return "This is not a Gradio component" 248 | 249 | with pytest.raises(TranspilerError) as e: 250 | transpile(invalid_return_function, validate=True) 251 | 252 | assert "Function must only return Gradio component updates" in str(e.value) 253 | 254 | 255 | def test_validate_mixed_return_paths(): 256 | def mixed_return_function(): 257 | if 5: 258 | return gradio.Textbox(placeholder="Valid path") 259 | else: 260 | return "Invalid path" 261 | 262 | with pytest.raises(TranspilerError) as e: 263 | transpile(mixed_return_function, validate=True) 264 | 265 | assert "Function must only return Gradio component updates" in str(e.value) 266 | 267 | 268 | def test_validate_multiple_gradio_returns(): 269 | def multiple_components(): 270 | return gradio.Textbox(placeholder="Component 1"), gradio.Button( 271 | variant="primary" 272 | ) 273 | 274 | result = transpile(multiple_components, validate=True) 275 | expected = """function multiple_components() { 276 | return [{"placeholder": "Component 1", "__type__": "update"}, {"variant": "primary", "__type__": "update"}]; 277 | }""" 278 | assert result.strip() == expected.strip() 279 | 280 | 281 | def test_validate_no_value_param(): 282 | def valid_component(): 283 | return gradio.Textbox(placeholder="This is valid") 284 | 285 | # This should pass validation 286 | result = transpile(valid_component, validate=True) 287 | expected = """function valid_component() { 288 | return {"placeholder": "This is valid", "__type__": "update"}; 289 | }""" 290 | assert result.strip() == expected.strip() 291 | 292 | 293 | def test_validate_with_value_param(): 294 | def invalid_component(): 295 | return gradio.Textbox(value="This is invalid") 296 | 297 | with pytest.raises(TranspilerError) as e: 298 | transpile(invalid_component, validate=True) 299 | 300 | assert "Function must only return Gradio component updates" in str(e.value) 301 | 302 | 303 | def test_validate_with_positional_args(): 304 | def invalid_positional(): 305 | return gradio.Textbox("This is invalid") 306 | 307 | with pytest.raises(TranspilerError) as e: 308 | transpile(invalid_positional, validate=True) 309 | 310 | assert "Function must only return Gradio component updates" in str(e.value) 311 | 312 | 313 | def test_validate_mixed_valid_invalid_components(): 314 | def mixed_components(): 315 | return gradio.Textbox(placeholder="Valid"), gradio.Button(value="Invalid") 316 | 317 | with pytest.raises(TranspilerError) as e: 318 | transpile(mixed_components, validate=True) 319 | 320 | assert "Function must only return Gradio component updates" in str(e.value) 321 | 322 | 323 | def test_gradio_component_with_none_values(): 324 | def component_with_none(): 325 | return gradio.Textbox(visible=True, info=None) 326 | 327 | expected = """function component_with_none() { 328 | return {"visible": true, "info": null, "__type__": "update"}; 329 | }""" 330 | assert transpile(component_with_none).strip() == expected.strip() 331 | 332 | 333 | def test_gradio_update_function(): 334 | def update_component(): 335 | return gradio.update(visible=False, interactive=True) 336 | 337 | expected = """function update_component() { 338 | return {"visible": false, "interactive": true, "__type__": "update"}; 339 | }""" 340 | assert transpile(update_component).strip() == expected.strip() 341 | 342 | 343 | def test_update_with_none_values(): 344 | def update_with_none(): 345 | return gradio.update(info=None, label="Updated") 346 | 347 | expected = """function update_with_none() { 348 | return {"info": null, "label": "Updated", "__type__": "update"}; 349 | }""" 350 | assert transpile(update_with_none).strip() == expected.strip() 351 | 352 | 353 | def test_mixed_update_and_components(): 354 | def mixed_updates(): 355 | return gradio.update(visible=True), gradio.Textbox(placeholder="Test") 356 | 357 | expected = """function mixed_updates() { 358 | return [{"visible": true, "__type__": "update"}, {"placeholder": "Test", "__type__": "update"}]; 359 | }""" 360 | assert transpile(mixed_updates).strip() == expected.strip() 361 | 362 | 363 | def test_conditional_update(): 364 | def conditional_update(x: int): 365 | if x > 10: 366 | return gradio.update(visible=True) 367 | else: 368 | return gradio.update(visible=False) 369 | 370 | expected = """function conditional_update(x) { 371 | if ((x > 10)) { 372 | return {"visible": true, "__type__": "update"}; 373 | } 374 | else { 375 | return {"visible": false, "__type__": "update"}; 376 | } 377 | }""" 378 | assert transpile(conditional_update).strip() == expected.strip() 379 | -------------------------------------------------------------------------------- /groovy/transpiler.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import ast 4 | import builtins 5 | import inspect 6 | import json 7 | import textwrap 8 | from collections.abc import Callable 9 | 10 | 11 | class TranspilerError(Exception): 12 | """Exception raised when transpilation fails or encounters ambiguous syntax.""" 13 | 14 | def __init__( 15 | self, 16 | issues: list[tuple[int, str, str]] | None = None, 17 | message: str | None = None, 18 | ): 19 | self.issues = issues or [] 20 | if message: 21 | super().__init__(message) 22 | else: 23 | issue_count = len(self.issues) 24 | issues_text = ( 25 | f"{issue_count} issue{'s' if issue_count != 1 else ''} found:\n\n" 26 | ) 27 | for line_no, message, code in self.issues: 28 | issues_text += f"* Line {line_no}: {message}\n>> {code}\n" 29 | super().__init__(issues_text) 30 | 31 | 32 | class PythonToJSVisitor(ast.NodeVisitor): 33 | def __init__(self): 34 | self.js_lines = [] # Accumulate lines of JavaScript code. 35 | self.indent_level = 0 # Track current indent level for readability. 36 | self.declared_vars = set() # Track declared variables 37 | self.issues: list[tuple[int, str, str]] = [] # Track transpilation issues 38 | self.source_lines: list[str] = [] # Store source code lines 39 | self.var_types: dict[str, type | None] = {} # Track variable types 40 | 41 | # Map built-in functions to their transformation functions. 42 | self.builtin_transforms = { 43 | "range": self.transform_range, 44 | "len": self.transform_len, 45 | } 46 | 47 | def add_issue(self, node: ast.AST, message: str) -> None: 48 | """Add a transpilation issue with source code context.""" 49 | if hasattr(node, "lineno"): 50 | line_no = node.lineno 51 | line_text = self.source_lines[line_no - 1].strip() 52 | self.issues.append((line_no, message, line_text)) 53 | 54 | def visit(self, node): 55 | try: 56 | return super().visit(node) 57 | except TranspilerError as e: 58 | if e.issues: 59 | self.issues.extend(e.issues) 60 | return "" # Return empty string for failed conversions 61 | 62 | def generic_visit(self, node): 63 | self.add_issue(node, f"Unsupported syntax: {type(node).__name__}") 64 | return "" 65 | 66 | def indent(self) -> str: 67 | return " " * self.indent_level 68 | 69 | # === Function Definition === 70 | def visit_FunctionDef(self, node: ast.FunctionDef): # noqa: N802 71 | # Extract parameter names and types from type hints 72 | params = [] 73 | for arg in node.args.args: 74 | params.append(arg.arg) 75 | if arg.annotation and isinstance(arg.annotation, ast.Name): 76 | type_name = arg.annotation.id 77 | type_obj = globals().get(type_name, getattr(builtins, type_name, None)) 78 | if type_obj is not None: 79 | self.var_types[arg.arg] = type_obj 80 | 81 | header = f"function {node.name}({', '.join(params)}) " + "{" 82 | self.js_lines.append(header) 83 | self.indent_level += 1 84 | 85 | for stmt in node.body: 86 | self.visit(stmt) 87 | self.indent_level -= 1 88 | self.js_lines.append("}") 89 | 90 | # === Attribute === 91 | def visit_Attribute(self, node: ast.Attribute): 92 | # Simply return a dotted string: e.g., gr.Textbox 93 | value = self.visit(node.value) 94 | return f"{value}.{node.attr}" 95 | 96 | # === Return Statement === 97 | def visit_Return(self, node: ast.Return): # noqa: N802 98 | ret_val = "" if node.value is None else self.visit(node.value) 99 | self.js_lines.append(f"{self.indent()}return {ret_val};") 100 | 101 | # === Expression Statements === 102 | def visit_Expr(self, node: ast.Expr): # noqa: N802 103 | expr = self.visit(node.value) 104 | self.js_lines.append(f"{self.indent()}{expr};") 105 | 106 | # === Assignment === 107 | def visit_Assign(self, node: ast.Assign): # noqa: N802 108 | if len(node.targets) != 1: 109 | raise TranspilerError("Multiple assignment targets are not supported yet.") 110 | target_node = node.targets[0] 111 | target = self.visit(target_node) 112 | value = self.visit(node.value) 113 | 114 | if ( 115 | isinstance(target_node, ast.Name) 116 | and target_node.id not in self.declared_vars 117 | ): 118 | self.declared_vars.add(target_node.id) 119 | expr_type = self.get_expr_type(node.value) 120 | if expr_type is not None: 121 | self.var_types[target_node.id] = expr_type 122 | self.js_lines.append(f"{self.indent()}let {target} = {value};") 123 | else: 124 | self.js_lines.append(f"{self.indent()}{target} = {value};") 125 | 126 | # === Binary Operations === 127 | def check_type_safety(self, node: ast.AST, *exprs: ast.AST, context: str) -> None: 128 | """ 129 | Check if an operation is type-safe. 130 | Raises TranspilerError if types are ambiguous or incompatible. 131 | """ 132 | types = [self.get_expr_type(expr) for expr in exprs] 133 | 134 | # Check for unknown types 135 | if any(t is None for t in types): 136 | self.add_issue( 137 | node, 138 | f"Ambiguous operation: Cannot determine types for {context}. " 139 | "Operation behavior may differ in JavaScript based on types.", 140 | ) 141 | raise TranspilerError() 142 | 143 | # Check for type consistency if multiple expressions 144 | if len(types) > 1 and not all(t == types[0] for t in types): 145 | type_names = [t.__name__ for t in types] 146 | self.add_issue( 147 | node, 148 | f"Ambiguous operation: Mixed types ({', '.join(type_names)}) in {context}. " 149 | "Behavior may differ in JavaScript.", 150 | ) 151 | raise TranspilerError() 152 | 153 | def visit_BinOp(self, node: ast.BinOp): # noqa: N802 154 | left = self.visit(node.left) 155 | right = self.visit(node.right) 156 | op = self.visit(node.op) 157 | 158 | self.check_type_safety( 159 | node, node.left, node.right, context=f"'{left} {op} {right}'" 160 | ) 161 | return f"({left} {op} {right})" 162 | 163 | def visit_Add(self, node: ast.Add): # noqa: N802, ARG002 164 | return "+" 165 | 166 | def visit_Sub(self, node: ast.Sub): # noqa: N802, ARG002 167 | return "-" 168 | 169 | def visit_Mult(self, node: ast.Mult): # noqa: N802, ARG002 170 | return "*" 171 | 172 | def visit_Div(self, node: ast.Div): # noqa: N802, ARG002 173 | return "/" 174 | 175 | # === Comparison Operations === 176 | def visit_Compare(self, node: ast.Compare): # noqa: N802 177 | if len(node.ops) != 1 or len(node.comparators) != 1: 178 | raise TranspilerError("Only single comparisons are supported") 179 | op = node.ops[0] 180 | left = self.visit(node.left) 181 | right = self.visit(node.comparators[0]) 182 | # Handle membership tests separately since types may differ. 183 | if isinstance(op, ast.In): 184 | # Translate Python "a in b" to JS "b.includes(a)" 185 | return f"{right}.includes({left})" 186 | elif isinstance(op, ast.NotIn): 187 | # Translate Python "a not in b" to JS "!b.includes(a)" 188 | return f"!{right}.includes({left})" 189 | else: 190 | # For other comparisons, check type safety. 191 | self.check_type_safety( 192 | node, 193 | node.left, 194 | node.comparators[0], 195 | context=f"comparison {left} {self.visit(op)} {right}", 196 | ) 197 | op_str = self.visit(op) 198 | return f"({left} {op_str} {right})" 199 | 200 | def visit_Gt(self, node: ast.Gt): # noqa: N802, ARG002 201 | return ">" 202 | 203 | def visit_Lt(self, node: ast.Lt): # noqa: N802, ARG002 204 | return "<" 205 | 206 | def visit_GtE(self, node: ast.GtE): # noqa: N802, ARG002 207 | return ">=" 208 | 209 | def visit_LtE(self, node: ast.LtE): # noqa: N802, ARG002 210 | return "<=" 211 | 212 | def visit_Eq(self, node: ast.Eq): # noqa: N802, ARG002 213 | return "===" 214 | 215 | def visit_NotEq(self, node: ast.NotEq): # noqa: N802, ARG002 216 | return "!==" 217 | 218 | # (Optional: in case In or NotIn are visited directly.) 219 | def visit_In(self, node: ast.In): 220 | return "in" 221 | 222 | def visit_NotIn(self, node: ast.NotIn): 223 | return "not in" 224 | 225 | # === If Statement === 226 | def visit_If(self, node: ast.If): # noqa: N802 227 | test = self.visit(node.test) 228 | self.js_lines.append(f"{self.indent()}if ({test}) " + "{") 229 | self.indent_level += 1 230 | for stmt in node.body: 231 | self.visit(stmt) 232 | self.indent_level -= 1 233 | self.js_lines.append(f"{self.indent()}" + "}") 234 | 235 | # Handle elif and else clauses 236 | current = node 237 | while ( 238 | current.orelse 239 | and len(current.orelse) == 1 240 | and isinstance(current.orelse[0], ast.If) 241 | ): 242 | current = current.orelse[0] 243 | test = self.visit(current.test) 244 | self.js_lines.append(f"{self.indent()}else if ({test}) " + "{") 245 | self.indent_level += 1 246 | for stmt in current.body: 247 | self.visit(stmt) 248 | self.indent_level -= 1 249 | self.js_lines.append(f"{self.indent()}" + "}") 250 | 251 | # Handle final else clause if it exists 252 | if current.orelse: 253 | self.js_lines.append(f"{self.indent()}else " + "{") 254 | self.indent_level += 1 255 | for stmt in current.orelse: 256 | self.visit(stmt) 257 | self.indent_level -= 1 258 | self.js_lines.append(f"{self.indent()}" + "}") 259 | 260 | # === Built-in Function Transformations === 261 | def transform_range(self, node: ast.Call) -> str: 262 | """Transform Python's range() to an equivalent JavaScript array expression.""" 263 | args = [self.visit(arg) for arg in node.args] 264 | for arg in node.args: 265 | self.check_type_safety(arg, arg, context="range() argument") 266 | if len(args) == 1: # range(stop) 267 | return f"Array.from({{length: {args[0]}}}, (_, i) => i)" 268 | elif len(args) == 2: # range(start, stop) 269 | return f"Array.from({{length: {args[1]} - {args[0]}}}, (_, i) => i + {args[0]})" 270 | elif len(args) == 3: # range(start, stop, step) 271 | raise TranspilerError("range() with step argument is not supported yet") 272 | else: 273 | raise TranspilerError("Invalid number of arguments for range()") 274 | 275 | def transform_len(self, node: ast.Call) -> str: 276 | """Transform Python's len() to the equivalent JavaScript property access.""" 277 | if len(node.args) != 1: 278 | raise TranspilerError("len() takes exactly one argument") 279 | arg_code = self.visit(node.args[0]) 280 | t = self.get_expr_type(node.args[0]) 281 | # If the type is a dictionary, return Object.keys(...).length; 282 | if t is dict: 283 | return f"Object.keys({arg_code}).length" 284 | else: 285 | # For lists, tuples, and strings, use .length. 286 | return f"{arg_code}.length" 287 | 288 | # === Function Calls === 289 | def _handle_gradio_component_updates(self, node: ast.Call): 290 | """Handle Gradio component calls and return JSON representation.""" 291 | kwargs = {} 292 | for kw in node.keywords: 293 | if isinstance(kw.value, ast.Constant) and kw.value.value is None: 294 | # None values should remain None in the kwargs dictionary 295 | # so that they are converted to null, not "null" in json.dumps(). 296 | kwargs[kw.arg] = None 297 | continue 298 | value = self.visit(kw.value) 299 | try: 300 | kwargs[kw.arg] = ast.literal_eval(value) 301 | except Exception: 302 | kwargs[kw.arg] = value 303 | kwargs["__type__"] = "update" 304 | return json.dumps(kwargs) 305 | 306 | def visit_Call(self, node: ast.Call): # noqa: N802 307 | try: 308 | import gradio 309 | 310 | has_gradio = True 311 | except ImportError: 312 | has_gradio = False 313 | 314 | # Handle built-in functions via our transformation mapping. 315 | if isinstance(node.func, ast.Name): 316 | if node.func.id in self.builtin_transforms: 317 | return self.builtin_transforms[node.func.id](node) 318 | 319 | # Try to resolve if this is a Gradio component. 320 | if has_gradio: 321 | try: 322 | # Handle direct update() call 323 | if node.func.id == "update": 324 | return self._handle_gradio_component_updates(node) 325 | 326 | component_class = getattr(gradio, node.func.id, None) 327 | if component_class and issubclass( 328 | component_class, gradio.blocks.Block 329 | ): 330 | return self._handle_gradio_component_updates(node) 331 | except Exception: 332 | pass 333 | 334 | for arg in node.args: 335 | self.check_type_safety( 336 | arg, arg, context=f"argument in {node.func.id}() call" 337 | ) 338 | self.add_issue(node, f'Unsupported function "{node.func.id}()"') 339 | return "" 340 | 341 | # Handle attribute access like gr.Textbox. (Note the updated check.) 342 | if isinstance(node.func, ast.Attribute) and has_gradio: 343 | try: 344 | # Now allow for module aliases such as "gr" as well as "gradio" 345 | if isinstance(node.func.value, ast.Name) and node.func.value.id in { 346 | "gradio", 347 | "gr", 348 | }: 349 | # Handle gr.update() call 350 | if node.func.attr == "update": 351 | return self._handle_gradio_component_updates(node) 352 | 353 | component_class = getattr(gradio, node.func.attr, None) 354 | if component_class and issubclass( 355 | component_class, gradio.blocks.Block 356 | ): 357 | return self._handle_gradio_component_updates(node) 358 | except Exception: 359 | pass 360 | 361 | # For other method calls (like obj.method()) 362 | func = self.visit(node.func) 363 | args = [self.visit(arg) for arg in node.args] 364 | 365 | if isinstance(node.func, ast.Attribute): 366 | self.check_type_safety( 367 | node.func, node.func.value, context=f"object in method call {func}" 368 | ) 369 | for arg in node.args: 370 | self.check_type_safety( 371 | arg, arg, context=f"argument in method call {func}" 372 | ) 373 | 374 | return f"{func}({', '.join(args)})" 375 | 376 | # === Variable Name === 377 | def visit_Name(self, node: ast.Name): # noqa: N802 378 | return node.id 379 | 380 | # === Constants === 381 | def visit_Constant(self, node: ast.Constant): # noqa: N802 382 | if node.value is None: 383 | return "null" 384 | return repr(node.value) 385 | 386 | # === For Loop === 387 | def visit_For(self, node: ast.For): # noqa: N802 388 | target = self.visit(node.target) 389 | iter_expr = self.visit(node.iter) 390 | 391 | # If iterating over a range, record that the loop variable is an int. 392 | if ( 393 | isinstance(node.iter, ast.Call) 394 | and isinstance(node.iter.func, ast.Name) 395 | and node.iter.func.id == "range" 396 | ): 397 | if isinstance(node.target, ast.Name): 398 | self.var_types[node.target.id] = int 399 | 400 | self.js_lines.append(f"{self.indent()}for (let {target} of {iter_expr}) " + "{") 401 | self.indent_level += 1 402 | for stmt in node.body: 403 | self.visit(stmt) 404 | self.indent_level -= 1 405 | self.js_lines.append(f"{self.indent()}" + "}") 406 | 407 | # === While Loop === 408 | def visit_While(self, node: ast.While): # noqa: N802 409 | test = self.visit(node.test) 410 | self.js_lines.append(f"{self.indent()}while ({test}) " + "{") 411 | self.indent_level += 1 412 | for stmt in node.body: 413 | self.visit(stmt) 414 | self.indent_level -= 1 415 | self.js_lines.append(f"{self.indent()}" + "}") 416 | 417 | # === List === 418 | def visit_List(self, node: ast.List): # noqa: N802 419 | elements = [self.visit(elt) for elt in node.elts] 420 | return f"[{', '.join(elements)}]" 421 | 422 | # === Tuple === 423 | def visit_Tuple(self, node: ast.Tuple): # noqa: N802 424 | elements = [self.visit(elt) for elt in node.elts] 425 | return f"[{', '.join(elements)}]" 426 | 427 | # === List Comprehension === 428 | def visit_ListComp(self, node: ast.ListComp): 429 | """ 430 | Transform a Python list comprehension into a combination of filter and map calls. 431 | For example: 432 | [x * 2 for x in arr if x > 10] 433 | becomes: 434 | arr.filter(x => x > 10).map(x => x * 2) 435 | """ 436 | if len(node.generators) != 1: 437 | self.add_issue( 438 | node, "Only single generator list comprehensions are supported" 439 | ) 440 | raise TranspilerError() 441 | gen = node.generators[0] 442 | iter_js = self.visit(gen.iter) 443 | target_js = self.visit(gen.target) 444 | elt_js = self.visit(node.elt) 445 | if gen.ifs: 446 | # Join multiple ifs with logical AND. 447 | conditions = " && ".join(self.visit(if_node) for if_node in gen.ifs) 448 | result = f"{iter_js}.filter({target_js} => {conditions})" 449 | # Only add a map step if the element expression is different from the loop variable. 450 | if not (isinstance(node.elt, ast.Name) and node.elt.id == gen.target.id): 451 | result += f".map({target_js} => {elt_js})" 452 | else: 453 | result = f"{iter_js}.map({target_js} => {elt_js})" 454 | return result 455 | 456 | # === Subscript === 457 | def visit_Subscript(self, node: ast.Subscript): # noqa: N802 458 | value = self.visit(node.value) 459 | slice_value = self.visit(node.slice) 460 | return f"{value}[{slice_value}]" 461 | 462 | # === Augmented Assignment === 463 | def visit_AugAssign(self, node: ast.AugAssign): # noqa: N802 464 | target = self.visit(node.target) 465 | op = self.visit(node.op).strip() 466 | value = self.visit(node.value) 467 | self.js_lines.append(f"{self.indent()}{target} {op}= {value};") 468 | 469 | # === Boolean Operations === 470 | def visit_BoolOp(self, node: ast.BoolOp): # noqa: N802 471 | op = self.visit(node.op) 472 | values = [self.visit(value) for value in node.values] 473 | # Join the values with the operator. 474 | return f"({f' {op} '.join(values)})" 475 | 476 | def visit_And(self, node: ast.And): # noqa: N802, ARG002 477 | return "&&" 478 | 479 | def visit_Or(self, node: ast.Or): # noqa: N802, ARG002 480 | return "||" 481 | 482 | # === Dictionary === 483 | def visit_Dict(self, node: ast.Dict): # noqa: N802 484 | pairs = [] 485 | for key, value in zip(node.keys, node.values): 486 | if key is None: # Handle dict unpacking 487 | continue 488 | key_js = self.visit(key) 489 | value_js = self.visit(value) 490 | pairs.append(f"{key_js}: {value_js}") 491 | return f"{{{', '.join(pairs)}}}" 492 | 493 | def get_expr_type(self, node: ast.AST) -> type | None: 494 | """Determine the type of an expression if possible.""" 495 | if isinstance(node, ast.Constant): 496 | return type(node.value) 497 | elif isinstance(node, ast.Name): 498 | # First check if we have a stored type from type hints or assignments. 499 | if node.id in self.var_types: 500 | return self.var_types[node.id] 501 | return None 502 | elif isinstance(node, ast.BinOp): 503 | left_type = self.get_expr_type(node.left) 504 | right_type = self.get_expr_type(node.right) 505 | if left_type == right_type and left_type is not None: 506 | return left_type 507 | return None 508 | elif isinstance(node, ast.Call): 509 | # We can't determine the return type of function calls yet. 510 | return None 511 | elif isinstance(node, ast.List): 512 | return list 513 | elif isinstance(node, ast.Dict): 514 | return dict 515 | elif isinstance(node, ast.Tuple): 516 | return tuple 517 | return None 518 | 519 | 520 | def transpile(fn: Callable, validate: bool = False) -> str: 521 | """ 522 | Transpiles a Python function to JavaScript and returns the JavaScript code as a string. 523 | 524 | Parameters: 525 | fn: The Python function to transpile. 526 | validate: If True, the function will be validated to ensure it takes no arguments & only returns gradio component property updates. This is used when Groovy is used inside Gradio and `gradio` must be installed to use this. 527 | 528 | Returns: 529 | The JavaScript code as a string. 530 | 531 | Raises: 532 | TranspilerError: If the function cannot be transpiled or if the transpiled function is not valid. 533 | """ 534 | if validate: 535 | sig = inspect.signature(fn) 536 | if sig.parameters: 537 | param_names = list(sig.parameters.keys()) 538 | raise TranspilerError( 539 | message=f"Function must take no arguments for client-side use, but got: {param_names}" 540 | ) 541 | 542 | try: 543 | source = inspect.getsource(fn) 544 | source = textwrap.dedent(source) 545 | except Exception as e: 546 | raise TranspilerError( 547 | message="Could not retrieve source code from the function." 548 | ) from e 549 | 550 | try: 551 | tree = ast.parse(source) 552 | except SyntaxError as e: 553 | raise TranspilerError(message="Could not parse function source.") from e 554 | 555 | if validate: 556 | try: 557 | import gradio # noqa: F401 558 | except ImportError: 559 | raise TranspilerError(message="Gradio must be installed for validation.") 560 | 561 | func_node = None 562 | for node in ast.walk(tree): 563 | if isinstance(node, ast.FunctionDef) and node.name == fn.__name__: 564 | func_node = node 565 | break 566 | 567 | if func_node: 568 | return_nodes = [] 569 | for node in ast.walk(func_node): 570 | if isinstance(node, ast.Return) and node.value is not None: 571 | return_nodes.append(node) 572 | 573 | if not return_nodes: 574 | raise TranspilerError( 575 | message="Function must return Gradio component updates, but no return statement found." 576 | ) 577 | 578 | for return_node in return_nodes: 579 | if not _is_valid_gradio_return(return_node.value): 580 | line_no = return_node.lineno 581 | line_text = source.splitlines()[line_no - 1].strip() 582 | raise TranspilerError( 583 | message=f"Function must only return Gradio component updates. Invalid return at line {line_no}: {line_text}" 584 | ) 585 | 586 | func_node = None 587 | for node in ast.walk(tree): 588 | if isinstance(node, (ast.FunctionDef, ast.Lambda)): 589 | func_node = node 590 | break 591 | 592 | if func_node is None: 593 | raise TranspilerError( 594 | message="No function or lambda definition found in the provided source." 595 | ) 596 | 597 | visitor = PythonToJSVisitor() 598 | visitor.source_lines = source.splitlines() 599 | 600 | if isinstance(func_node, ast.Lambda): 601 | args = [arg.arg for arg in func_node.args.args] 602 | visitor.js_lines.append(f"function ({', '.join(args)}) " + "{") 603 | visitor.indent_level += 1 604 | visitor.js_lines.append( 605 | f"{visitor.indent()}return {visitor.visit(func_node.body)};" 606 | ) 607 | visitor.indent_level -= 1 608 | visitor.js_lines.append("}") 609 | else: 610 | visitor.visit(func_node) 611 | 612 | if visitor.issues: 613 | raise TranspilerError(issues=visitor.issues) 614 | 615 | return "\n".join(visitor.js_lines) 616 | 617 | 618 | def _is_valid_gradio_return(node: ast.AST) -> bool: 619 | """ 620 | Check if a return value is a valid Gradio component or collection of components. 621 | 622 | Args: 623 | node: The AST node representing the return value 624 | 625 | Returns: 626 | bool: True if the return value is valid, False otherwise 627 | """ 628 | # Check for direct Gradio component call 629 | if isinstance(node, ast.Call): 630 | if isinstance(node.func, ast.Attribute) and isinstance( 631 | node.func.value, ast.Name 632 | ): 633 | if node.func.value.id in {"gr", "gradio"}: 634 | try: 635 | import gradio 636 | 637 | if node.func.attr == "update": 638 | return True 639 | 640 | component_class = getattr(gradio, node.func.attr, None) 641 | if component_class and issubclass( 642 | component_class, gradio.blocks.Block 643 | ): 644 | if node.args: 645 | return False 646 | for kw in node.keywords: 647 | if kw.arg == "value": 648 | return False 649 | return True 650 | except (ImportError, AttributeError): 651 | pass 652 | return False 653 | elif isinstance(node.func, ast.Name): 654 | try: 655 | import gradio 656 | 657 | if node.func.id == "update": 658 | return True 659 | 660 | component_class = getattr(gradio, node.func.id, None) 661 | if component_class and issubclass(component_class, gradio.blocks.Block): 662 | if node.args: 663 | return False 664 | for kw in node.keywords: 665 | if kw.arg == "value": 666 | return False 667 | return True 668 | except (ImportError, AttributeError): 669 | pass 670 | return False 671 | 672 | elif isinstance(node, (ast.Tuple, ast.List)): 673 | if not node.elts: 674 | return False 675 | return all(_is_valid_gradio_return(elt) for elt in node.elts) 676 | 677 | return False 678 | 679 | 680 | # === Example Usage === 681 | 682 | if __name__ == "__main__": 683 | import gradio as gr 684 | 685 | def filter_rows_by_term(): 686 | return gr.update(selected=2, visible=True, info=None) 687 | 688 | js_code = transpile(filter_rows_by_term, validate=True) 689 | print(js_code) 690 | --------------------------------------------------------------------------------