Package: cythonautoinstall
Generates and installs simple Cython modules with specified settings. If you are overwhelmed by the compiler directives and the creation of the setup.py file, this is right for you.Tested against Windows 10 / Python 3.11 / Anacondapip install cythonautoinstallThis function takes Cython code along with various setup parameters and generates a
Cython module, compiles it, and installs it as a Python package. It handles the
generation of the Cython code, the creation of a setup script, compilation, and
installation. Made for people who write simple scripts and are overwhelmed
by the compiler directives and the creation of the setup.py fileParameters:cython_code(str):TheCythoncodetobecompiledintoamodule.foldername(str):Thenameofthefolderwherethepackagewillbeinstalled.setup_name(str):Thenameofthemoduletobegenerated.setup_sources(tupleorlist):Atupleorlistofsourcefilepaths.setup_include_dirs(tupleorlist):Atupleorlistofincludedirectorypaths.setup_py_limited_api(bool,optional):WhethertousePythonlimitedAPI.DefaultisFalse.setup_define_macros(tupleorlist,optional):Definemacrosforthecompilation.Defaultis().setup_undef_macros(tupleorlist,optional):Undefinemacrosforthecompilation.Defaultis().setup_library_dirs(tupleorlist,optional):Librarydirectories.Defaultis().setup_libraries(tupleorlist,optional):Librariestolinkagainst.Defaultis().setup_runtime_library_dirs(tupleorlist,optional):Runtimelibrarydirectories.Defaultis().setup_extra_objects(tupleorlist,optional):Extraobjectstolinkwith.Defaultis().setup_extra_compile_args(tupleorlist,optional):Extracompilationarguments.Defaultis().setup_extra_link_args(tupleorlist,optional):Extralinkarguments.Defaultis().setup_export_symbols(tupleorlist,optional):Exportedsymbols.Defaultis().setup_swig_opts(tupleorlist,optional):SWIGoptions.Defaultis().setup_depends(tupleorlist,optional):Dependencyfiles.Defaultis().setup_language(str,optional):Languageforcompilation.DefaultisNone.setup_optional(tupleorlist,optional):Optionalcomponents.DefaultisNone.extra_directives(str,optional):AdditionalCythoncompilerdirectives.Defaultis"".distutils_extra_compile_args(str,optional):Additionaldistutilscompilationarguments.Defaultis"".distutils_extra_link_args(str,optional):Additionaldistutilslinkarguments.Defaultis"".distutils_language(str,optional):Languagefordistutilscompilation.Defaultis"".distutils_define_macros(str,optional):Definemacrosfordistutilscompilation.Defaultis"NPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION".cython_binding(bool,optional):WhethertogenerateCythonbindings.DefaultisTrue.cython_boundscheck(bool,optional):Enableboundschecking.DefaultisTrue.cython_wraparound(bool,optional):Enablewraparoundchecking.DefaultisTrue.cython_initializedcheck(bool,optional):Enableinitializedvariablechecking.DefaultisFalse.cython_nonecheck(bool,optional):EnableNonechecking.DefaultisFalse.cython_overflowcheck(bool,optional):Enableoverflowchecking.DefaultisFalse.cython_overflowcheck_fold(bool,optional):Enablefoldingofoverflowchecks.DefaultisTrue.cython_embedsignature(bool,optional):Embedfunctionsignatures.DefaultisFalse.cython_embedsignature_format(str,optional):Formatforembeddedsignatures.Defaultis"c".cython_cdivision(bool,optional):EnableCdivision.DefaultisFalse.cython_cdivision_warnings(bool,optional):EnableCdivisionwarnings.DefaultisFalse.cython_cpow(bool,optional):EnableCpowfunction.DefaultisFalse.cython_c_api_binop_methods(bool,optional):EnableCAPIbinaryoperatormethods.DefaultisFalse.cython_profile(bool,optional):Enableprofiling.DefaultisFalse.cython_linetrace(bool,optional):Enablelinetracing.DefaultisFalse.cython_infer_types(bool,optional):Enabletypeinference.DefaultisFalse.cython_language_level(int,optional):Cythonlanguagelevel.Defaultis3.cython_c_string_type(str,optional):Cstringtype.Defaultis"bytes".cython_c_string_encoding(str,optional):Cstringencoding.Defaultis"default".cython_type_version_tag(bool,optional):Enabletypeversiontag.DefaultisTrue.cython_unraisable_tracebacks(bool,optional):Enableunraisabletracebacks.DefaultisFalse.cython_iterable_coroutine(bool,optional):Enableiterablecoroutinesupport.DefaultisTrue.cython_annotation_typing(bool,optional):Enableannotationtyping.DefaultisTrue.cython_emit_code_comments(bool,optional):Enablecodecommentsinthegeneratedcode.DefaultisFalse.cython_cpp_locals(bool,optional):EnableC++localvariablesupport.DefaultisFalse.Returns:str:Thepathtothegeneratedpackage's __init__.py file.Note:Readhttps://cython.readthedocs.io/en/latest/src/userguide/source_files_and_compilation.html#compiler-directivesExample:importnumpyasnpcython_code='''from cython.parallel cimport prangecimport cythonimport numpy as npcimport numpy as npimport cythonfrom collections import defaultdictcpdef searchforcolor(unsigned char[:] pic, unsigned char[:] colors, int width, int totallengthpic, int totallengthcolor):cdef my_dict = defaultdict(list)cdef int i, jcdef unsigned char r,g,bfor i in prange(0, totallengthcolor, 3,nogil=True):r = colors[i]g = colors[i + 1]b = colors[i + 2]for j in range(0, totallengthpic, 3):if (r == pic[j]) and (g == pic[j+1]) and (b == pic[j+2]):with gil:my_dict[(r,g,b)].append(j )for key in my_dict.keys():my_dict[key] = np.dstack(np.divmod(np.array(my_dict[key]) // 3, width))[0]return my_dict'''fx=generate_auto_install(cython_code,foldername="locatepixelcolcompiledpy",setup_py_limited_api=False,setup_name="locatepixelcolorcompiled",setup_sources=("locatepixelcolorcompiled.pyx",),setup_include_dirs=(np.get_include(),),setup_define_macros=(),setup_undef_macros=(),setup_library_dirs=(),setup_libraries=(),setup_runtime_library_dirs=(),setup_extra_objects=(),setup_extra_compile_args=(),setup_extra_link_args=(),setup_export_symbols=(),setup_swig_opts=(),setup_depends=(),setup_language=None,setup_optional=None,extra_directives="",distutils_extra_compile_args="/openmp",distutils_extra_link_args="/openmp",distutils_language="c",distutils_define_macros="NPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION",cython_binding=False,cython_boundscheck=False,cython_wraparound=False,cython_initializedcheck=False,cython_nonecheck=False,cython_overflowcheck=True,cython_overflowcheck_fold=False,cython_embedsignature=False,cython_embedsignature_format="c",cython_cdivision=True,cython_cdivision_warnings=False,cython_cpow=True,cython_c_api_binop_methods=True,cython_profile=False,cython_linetrace=False,cython_infer_types=False,cython_language_level=3,cython_c_string_type="bytes",cython_c_string_encoding="default",cython_type_version_tag=True,cython_unraisable_tracebacks=False,cython_iterable_coroutine=True,cython_annotation_typing=True,cython_emit_code_comments=False,cython_cpp_locals=True,)print(fx)# create a Python filer'''import numpy as npimport cv2import locatepixelcolcompiledpydef search_colors(pic,colors):if not isinstance(colors, np.ndarray):colors = np.array(colors, dtype=np.uint8)pipi = pic.ravel()cololo = colors.ravel()totallengthcolor = cololo.shape[0] - 1totallenghtpic = pipi.shape[0]-1width = pic.shape[1]resus0 = locatepixelcolcompiledpy.locatepixelcolorcompiled.searchforcolor(pipi, cololo,width,totallenghtpic,totallengthcolor)return resus0# 4525 x 6623 x 3 picture https://www.pexels.com/pt-br/foto/foto-da-raposa-sentada-no-chao-2295744/picx = r"C:\Users\hansc\Downloads\pexels-alex-andrews-2295744.jpg"pic = cv2.imread(picx)colors0 = np.array([[255, 255, 255]],dtype=np.uint8)resus0 = search_colors(pic=pic, colors=colors0)colors1=np.array([(66,  71,  69),(62,  67,  65),(144, 155, 153),(52,  57,  55),(127, 138, 136),(53,  58,  56),(51,  56,  54),(32,  27,  18),(24,  17,   8),],dtype=np.uint8)resus1 =  search_colors(pic=pic, colors=colors1)'''Thisishowageneratedfilelookslike(itcanbeeditedafterthegeneration):importosimportsubprocessimportsysdef_dummyimport():importCythontry:from.importlocatepixelcolorcompiledexceptExceptionase:cstring='''# distutils: language=c# distutils: extra_compile_args=/openmp# distutils: extra_link_args=/openmp# distutils: define_macros=NPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION# cython: binding=False# cython: boundscheck=False# cython: wraparound=False# cython: initializedcheck=False# cython: nonecheck=False# cython: overflowcheck=True# cython: overflowcheck.fold=False# cython: embedsignature=False# cython: embedsignature.format=c# cython: cdivision=True# cython: cdivision_warnings=False# cython: cpow=True# cython: c_api_binop_methods=True# cython: profile=False# cython: linetrace=False# cython: infer_types=False# cython: language_level=3# cython: c_string_type=bytes# cython: c_string_encoding=default# cython: type_version_tag=True# cython: unraisable_tracebacks=False# cython: iterable_coroutine=True# cython: annotation_typing=True# cython: emit_code_comments=False# cython: cpp_locals=Truefrom cython.parallel cimport prangecimport cythonimport numpy as npcimport numpy as npimport cythonfrom collections import defaultdictcpdef searchforcolor(unsigned char[:] pic, unsigned char[:] colors, int width, int totallengthpic, int totallengthcolor):cdef my_dict = defaultdict(list)cdef int i, jcdef unsigned char r,g,bfor i in prange(0, totallengthcolor, 3,nogil=True):r = colors[i]g = colors[i + 1]b = colors[i + 2]for j in range(0, totallengthpic, 3):if (r == pic[j]) and (g == pic[j+1]) and (b == pic[j+2]):with gil:my_dict[(r,g,b)].append(j )for key in my_dict.keys():my_dict[key] = np.dstack(np.divmod(np.array(my_dict[key]) // 3, width))[0]return my_dict'''pyxfile=f"locatepixelcolorcompiled.pyx"pyxfilesetup=f"locatepixelcolorcompiled_setup.py"dirname=os.path.abspath(os.path.dirname(__file__))pyxfile_complete_path=os.path.join(dirname,pyxfile)pyxfile_setup_complete_path=os.path.join(dirname,pyxfilesetup)ifos.path.exists(pyxfile_complete_path):os.remove(pyxfile_complete_path)ifos.path.exists(pyxfile_setup_complete_path):os.remove(pyxfile_setup_complete_path)withopen(pyxfile_complete_path,mode="w",encoding="utf-8")asf:f.write(cstring)compilefile='''from setuptools import Extension, setupfrom Cython.Build import cythonizeext_modules = Extension(**{'py_limited_api': False, 'name': 'locatepixelcolorcompiled', 'sources': ['locatepixelcolorcompiled.pyx'], 'include_dirs': ['C:\\Users\\hansc\\.conda\\envs\\dfdir\\Lib\\site-packages\\numpy\\core\\include'], 'define_macros': [], 'undef_macros': [], 'library_dirs': [], 'libraries': [], 'runtime_library_dirs': [], 'extra_objects': [], 'extra_compile_args': [], 'extra_link_args': [], 'export_symbols': [], 'swig_opts': [], 'depends': [], 'language': None, 'optional': None})setup(name='locatepixelcolorcompiled',ext_modules=cythonize(ext_modules),)'''withopen(pyxfile_setup_complete_path,mode="w",encoding="utf-8")asf:f.write('\n'.join([x.lstrip().replace(os.sep,"/")forxincompilefile.splitlines()]))subprocess.run([sys.executable,pyxfile_setup_complete_path,"build_ext","--inplace"],cwd=dirname,shell=True,env=os.environ.copy(),)from.importlocatepixelcolorcompiled