Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Rizwan-Hasan committed Dec 21, 2020
0 parents commit 8e5c9d0
Show file tree
Hide file tree
Showing 10 changed files with 433 additions and 0 deletions.
132 changes: 132 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
# VSCode
.vscode/

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-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 test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# 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

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# 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

# Pyre type checker
.pyre/
1 change: 1 addition & 0 deletions CHANGES.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
v1.2.0b1, 21-12-2020 -- Initial release.
21 changes: 21 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 TechLearners Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
4 changes: 4 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
include LICENSE.txt
include CHANGES.txt
include requirements.txt
include README.rst
57 changes: 57 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
==========
cythonizer
==========

*Cythonize one step faster*

.. image:: https://img.shields.io/badge/build-beta-brightgreen
:target: https://github.com/TechLearnersInc/cythonizer

.. image:: https://img.shields.io/badge/license-MIT-green
:target: LICENSE.txt

.. image:: https://img.shields.io/static/v1?label=Created%20with%20%E2%9D%A4%EF%B8%8F%20by&message=TechLearners&color=red
:target: https://github.com/TechLearnersInc

Introduction
------------

:code:`cythonizer.py` is a script that will attempt to
automatically convert one or more :code:`.py` and :code:`.pyx` files into
the corresponding compiled :code:`.pyd | .so` binary modules
files. Example::

$ python cythonizer.py myext.pyx

:code:`pip install cythonizer` will automatically create an
executable script in your :code:`Scripts/` folder, so you
should be able to simply::

$ cythonizer myext.py

or even::

$ cythonizer *.pyx

You can type::

$ cythonizer -h

to obtain the following CLI::

usage: cythonizer.py [-h] [--annotation] [--numpy-includes]
[--debugmode] filenames [filenames ...]

positional arguments:
filenames .py and .pyx files only

optional arguments:
-h, --help show this help message and exit
--annotation (default: False)
--numpy-includes (default: False)
--debugmode (default: False)


- :code:`--annotation` will create the HTML Cython annotation file.
- :code:`--numpy-includes` will add the numpy headers to the build command.
- Compiler flags :code:`-O2 -march=native` are automatically passed to the compiler.
Empty file added cythonizer/__init__.py
Empty file.
126 changes: 126 additions & 0 deletions cythonizer/cythonizer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import argparse
import logging
import os
import pathlib
import sys

# Always prefer setuptools over distutils
from setuptools import Extension, setup
import Cython.Compiler.Options
from Cython.Build import cythonize
from Cython.Distutils import build_ext

logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s")


class cythonizer:
def __init__(self) -> None:
self.__extension: list = []
self.__args = self.__Arguments()
self.__Checking()
self.__Compiling()
# self.__Cleanup()

# Argumebts Parser ↓
def __Arguments(self):
parser = argparse.ArgumentParser(
description="A script that will attempt to automatically convert one or more .py and .pyx files into the corresponding compiled .pyd or .so binary modules files."
)

# Taking Files ↓
parser.add_argument(
"filenames", type=pathlib.Path, nargs="+", help=".py and .pyx files only"
)

# Cython Annotation ↓
parser.add_argument(
"--annotation",
default=False,
action="store_true",
help="(default: False)",
)

# Numpy Includes ↓
parser.add_argument(
"--numpy-includes",
default=False,
action="store_true",
help="(default: False)",
)

# Cython Debugmode ↓
parser.add_argument(
"--debugmode",
default=False,
action="store_true",
help="(default: False)",
)

return parser.parse_args().__dict__

# Received File Checking ↓
def __Checking(self):
for file in self.__args.get("filenames"):
if not os.path.exists(file):
logging.error(f'"{file}" doesn\'t exist.')
sys.exit(-1)
if not os.path.isfile(file):
logging.error(f'"{file}" is not a file')
sys.exit(-1)
if os.path.splitext(file)[-1] not in (".py", ".pyx"):
logging.error(f'"{file}" is not a valid file')
sys.exit(-1)

# Includes Directory ↓
def __Includes_Dir(self):
# Extra include folders. Mainly for numpy.
if self.__args.get("numpy_includes"):
try:
import numpy as np

except ModuleNotFoundError:
logging.error("Numpy is required, but not found. Please install it")
sys.exit(-1)
return [np.get_include()]
else:
return []

# Cython Compilation ↓
def __Compiling(self):
Cython.Compiler.Options.annotate = self.__args.get("annotation")

ext_modules: list = []
for _ in self.__args.get("filenames"):
file: str = str(_)
# The name must be plain, no path
module_name = os.path.basename(file)
module_name = os.path.splitext(module_name)[0]
ext_modules.append(
Extension(
module_name, [file], extra_compile_args=["-O2", "-march=native"]
)
)

sys.argv = [sys.argv[0], "build_ext", "--inplace"]

setup(
cmdclass={"build_ext": build_ext},
include_dirs=self.__Includes_Dir(),
ext_modules=cythonize(module_list=ext_modules, language_level="3"),
)

def __Cleanup(self):
# Delete intermediate C files.
for _ in self.__args.get("filenames"):
filename = str(_)
filename = f"{filename}.c"
if os.path.exists(filename):
os.remove(filename)


def main():
cythonizer()


if __name__ == "__main__":
main()
2 changes: 2 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Cython>=0.29.21
numpy>=1.19.4
2 changes: 2 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[bdist_wheel]
universal=1
Loading

0 comments on commit 8e5c9d0

Please sign in to comment.