setup.py 14.7 KB
Newer Older
1 2 3 4 5 6 7 8
import io
import os
import os.path
import sys
import runpy
import subprocess
import re
import sysconfig
O
Olli-Pekka Heinisuo 已提交
9 10
import skbuild
from skbuild import cmaker
11

12

13 14
def main():
    os.chdir(os.path.dirname(os.path.abspath(__file__)))
15

O
Olli-Pekka Heinisuo 已提交
16
    # These are needed for source fetching
17
    cmake_source_dir = "opencv"
O
Olli-Pekka Heinisuo 已提交
18
    minimum_supported_numpy = "1.11.1"
O
Olli-Pekka Heinisuo 已提交
19 20 21
    build_contrib = get_build_env_var_by_name("contrib")
    # headless flag to skip GUI deps if needed
    build_headless = get_build_env_var_by_name("headless")
22

23 24 25 26
    if sys.version_info[:2] >= (3, 6):
        minimum_supported_numpy = "1.11.3"
    if sys.version_info[:2] >= (3, 7):
        minimum_supported_numpy = "1.14.5"
27 28
    if sys.version_info[:2] >= (3, 8):
        minimum_supported_numpy = "1.17.3"
29

O
Olli-Pekka Heinisuo 已提交
30
    numpy_version = "numpy>=%s" % minimum_supported_numpy
31 32

    python_version = cmaker.CMaker.get_python_version()
33 34
    python_lib_path = cmaker.CMaker.get_python_library(python_version).replace('\\', '/')
    python_include_dir = cmaker.CMaker.get_python_include_dir(python_version).replace('\\', '/')
35

36
    if os.path.exists(".git"):
O
Olli-Pekka Heinisuo 已提交
37 38
        import pip._internal.vcs.git as git
        g = git.Git()  # NOTE: pip API's are internal, this has to be refactored
39

40
        g.run_command(["submodule", "sync"])
41 42 43
        g.run_command(
            ["submodule", "update", "--init", "--recursive", cmake_source_dir]
        )
44

45
        if build_contrib:
46 47 48
            g.run_command(
                ["submodule", "update", "--init", "--recursive", "opencv_contrib"]
            )
O
Olli-Pekka Heinisuo 已提交
49

O
Olli-Pekka Heinisuo 已提交
50 51
    package_version, build_contrib, build_headless = get_opencv_version(build_contrib, build_headless)

52
    # https://stackoverflow.com/questions/1405913/python-32bit-or-64bit-mode
53
    x64 = sys.maxsize > 2 ** 32
54

O
Olli-Pekka Heinisuo 已提交
55 56
    package_name = "opencv-python"

57
    if build_contrib and not build_headless:
O
Olli-Pekka Heinisuo 已提交
58 59
        package_name = "opencv-contrib-python"

O
Olli-Pekka Heinisuo 已提交
60
    if build_contrib and build_headless:
O
Olli-Pekka Heinisuo 已提交
61 62
        package_name = "opencv-contrib-python-headless"

63
    if build_headless and not build_contrib:
O
Olli-Pekka Heinisuo 已提交
64 65
        package_name = "opencv-python-headless"

66
    long_description = io.open("README.md", encoding="utf-8").read()
O
Olli-Pekka Heinisuo 已提交
67

68
    packages = ["cv2", "cv2.data"]
69

70
    package_data = {
O
Olli-Pekka Heinisuo 已提交
71
        "cv2": ["*%s" % sysconfig.get_config_vars().get("SO"), "version.py"]
72 73 74
        + (["*.dll"] if os.name == "nt" else [])
        + ["LICENSE.txt", "LICENSE-3RD-PARTY.txt"],
        "cv2.data": ["*.xml"],
75
    }
76 77 78

    # Files from CMake output to copy to package.
    # Path regexes with forward slashes relative to CMake install dir.
79
    rearrange_cmake_output_data = {
80 81 82 83 84 85
        "cv2": (
            [r"bin/opencv_videoio_ffmpeg\d{3}%s\.dll" % ("_64" if x64 else "")]
            if os.name == "nt"
            else []
        )
        +
86 87 88
        # In Windows, in python/X.Y/<arch>/; in Linux, in just python/X.Y/.
        # Naming conventions vary so widely between versions and OSes
        # had to give up on checking them.
O
Olli-Pekka Heinisuo 已提交
89
        ["python/cv2[^/]*%(ext)s" % {"ext": re.escape(sysconfig.get_config_var("EXT_SUFFIX"))}],
90 91 92
        "cv2.data": [  # OPENCV_OTHER_INSTALL_PATH
            ("etc" if os.name == "nt" else "share/opencv4") + r"/haarcascades/.*\.xml"
        ],
93 94
    }

95 96
    # Files in sourcetree outside package dir that should be copied to package.
    # Raw paths relative to sourcetree root.
97
    files_outside_package_dir = {"cv2": ["LICENSE.txt", "LICENSE-3RD-PARTY.txt"]}
98

99 100
    cmake_args = (
        (
O
Olli-Pekka Heinisuo 已提交
101
            ["-G", "Visual Studio 15" + (" Win64" if x64 else "")]
102 103 104 105 106
            if os.name == "nt"
            else ["-G", "Unix Makefiles"]  # don't make CMake try (and fail) Ninja first
        )
        + [
            # skbuild inserts PYTHON_* vars. That doesn't satisfy opencv build scripts in case of Py3
O
Olli-Pekka Heinisuo 已提交
107
            "-DPYTHON3_EXECUTABLE=%s" % sys.executable,
108 109
            "-DPYTHON3_INCLUDE_DIR=%s" % python_include_dir,
            "-DPYTHON3_LIBRARY=%s" % python_lib_path,
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
            "-DBUILD_opencv_python3=ON",
            "-DBUILD_opencv_python2=OFF",
            # When off, adds __init__.py and a few more helper .py's. We use our own helper files with a different structure.
            "-DOPENCV_SKIP_PYTHON_LOADER=ON",
            # Relative dir to install the built module to in the build tree.
            # The default is generated from sysconfig, we'd rather have a constant for simplicity
            "-DOPENCV_PYTHON3_INSTALL_PATH=python",
            # Otherwise, opencv scripts would want to install `.pyd' right into site-packages,
            # and skbuild bails out on seeing that
            "-DINSTALL_CREATE_DISTRIB=ON",
            # See opencv/CMakeLists.txt for options and defaults
            "-DBUILD_opencv_apps=OFF",
            "-DBUILD_SHARED_LIBS=OFF",
            "-DBUILD_TESTS=OFF",
            "-DBUILD_PERF_TESTS=OFF",
            "-DBUILD_DOCS=OFF",
        ]
        + (
            ["-DOPENCV_EXTRA_MODULES_PATH=" + os.path.abspath("opencv_contrib/modules")]
            if build_contrib
            else []
        )
    )
133

134
    # OS-specific components
O
Olli-Pekka Heinisuo 已提交
135 136
    if sys.platform.startswith('linux') and not build_headless:
        cmake_args.append("-DWITH_QT=4")
137

O
Olli-Pekka Heinisuo 已提交
138 139
    if sys.platform == 'darwin' and not build_headless:
        cmake_args.append("-DWITH_QT=5")
140 141 142
        rearrange_cmake_output_data["cv2.qt.plugins.platforms"] = [
            (r"lib/qt/plugins/platforms/libqcocoa\.dylib")
        ]
O
Olli-Pekka Heinisuo 已提交
143

O
Olli-Pekka Heinisuo 已提交
144 145 146 147
    if build_headless:
        # it seems that cocoa cannot be disabled so on macOS the package is not truly headless
        cmake_args.append("-DWITH_WIN32UI=OFF")
        cmake_args.append("-DWITH_QT=OFF")
148 149 150
        cmake_args.append(
            "-DWITH_MSMF=OFF"
        )  # see: https://github.com/skvark/opencv-python/issues/263
O
Olli-Pekka Heinisuo 已提交
151

152
    if sys.platform.startswith("linux"):
153
        cmake_args.append("-DWITH_V4L=ON")
154
        cmake_args.append("-DWITH_LAPACK=ON")
155
        cmake_args.append("-DENABLE_PRECOMPILED_HEADERS=OFF")
156

157
    if sys.platform.startswith("linux") and not x64:
158 159
        subprocess.check_call("patch -p0 < patches/patchOpenEXR", shell=True)

O
Olli-Pekka Heinisuo 已提交
160
    if sys.platform == "darwin":
O
Olli-Pekka Heinisuo 已提交
161 162
        subprocess.check_call("patch -p1 < patches/patchQtPlugins", shell=True)

163
    # works via side effect
164 165 166
    RearrangeCMakeOutput(
        rearrange_cmake_output_data, files_outside_package_dir, package_data.keys()
    )
167 168 169 170

    skbuild.setup(
        name=package_name,
        version=package_version,
171 172 173
        url="https://github.com/skvark/opencv-python",
        license="MIT",
        description="Wrapper package for OpenCV python bindings.",
174
        long_description=long_description,
175
        long_description_content_type="text/markdown",
176 177 178 179 180
        packages=packages,
        package_data=package_data,
        maintainer="Olli-Pekka Heinisuo",
        include_package_data=True,
        ext_modules=EmptyListWithLength(),
O
Olli-Pekka Heinisuo 已提交
181
        install_requires=numpy_version,
182
        classifiers=[
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
            "Development Status :: 5 - Production/Stable",
            "Environment :: Console",
            "Intended Audience :: Developers",
            "Intended Audience :: Education",
            "Intended Audience :: Information Technology",
            "Intended Audience :: Science/Research",
            "License :: OSI Approved :: MIT License",
            "Operating System :: MacOS",
            "Operating System :: Microsoft :: Windows",
            "Operating System :: POSIX",
            "Operating System :: Unix",
            "Programming Language :: Python",
            "Programming Language :: Python :: 3",
            "Programming Language :: Python :: 3.5",
            "Programming Language :: Python :: 3.6",
            "Programming Language :: Python :: 3.7",
            "Programming Language :: Python :: 3.8",
            "Programming Language :: C++",
            "Programming Language :: Python :: Implementation :: CPython",
            "Topic :: Scientific/Engineering",
            "Topic :: Scientific/Engineering :: Image Recognition",
            "Topic :: Software Development",
205 206 207
        ],
        cmake_args=cmake_args,
        cmake_source_dir=cmake_source_dir,
208
    )
209 210 211


class RearrangeCMakeOutput(object):
212 213 214 215
    """
        Patch SKBuild logic to only take files related to the Python package
        and construct a file hierarchy that SKBuild expects (see below)
    """
216

217 218 219 220 221
    _setuptools_wrap = None

    # Have to wrap a function reference, or it's converted
    # into an instance method on attr assignment
    import argparse
222

O
Olli-Pekka Heinisuo 已提交
223
    wraps = argparse.Namespace(_classify_installed_files=None)
224 225 226 227 228 229 230 231
    del argparse

    package_paths_re = None
    packages = None
    files_outside_package = None

    def __init__(self, package_paths_re, files_outside_package, packages):
        cls = self.__class__
O
Olli-Pekka Heinisuo 已提交
232
        assert not cls.wraps._classify_installed_files, "Singleton object"
233 234 235
        import skbuild.setuptools_wrap

        cls._setuptools_wrap = skbuild.setuptools_wrap
236 237 238 239 240 241
        cls.wraps._classify_installed_files = (
            cls._setuptools_wrap._classify_installed_files
        )
        cls._setuptools_wrap._classify_installed_files = (
            self._classify_installed_files_override
        )
242 243 244 245

        cls.package_paths_re = package_paths_re
        cls.files_outside_package = files_outside_package
        cls.packages = packages
246

247 248
    def __del__(self):
        cls = self.__class__
249 250 251
        cls._setuptools_wrap._classify_installed_files = (
            cls.wraps._classify_installed_files
        )
O
Olli-Pekka Heinisuo 已提交
252
        cls.wraps._classify_installed_files = None
253 254
        cls._setuptools_wrap = None

255 256 257 258 259 260 261 262 263 264 265 266 267
    def _classify_installed_files_override(
        self,
        install_paths,
        package_data,
        package_prefixes,
        py_modules,
        new_py_modules,
        scripts,
        new_scripts,
        data_files,
        cmake_source_dir,
        cmake_install_reldir,
    ):
268
        """
269 270 271 272 273 274 275 276 277
            From all CMake output, we're only interested in a few files
            and must place them into CMake install dir according
            to Python conventions for SKBuild to find them:
                package\
                    file
                    subpackage\
                        etc.
        """

278
        cls = self.__class__
279

280 281
        # 'relpath'/'reldir' = relative to CMAKE_INSTALL_DIR/cmake_install_dir
        # 'path'/'dir' = relative to sourcetree root
282 283 284 285 286 287 288 289 290
        cmake_install_dir = os.path.join(
            cls._setuptools_wrap.CMAKE_INSTALL_DIR(), cmake_install_reldir
        )
        install_relpaths = [
            os.path.relpath(p, cmake_install_dir) for p in install_paths
        ]
        fslash_install_relpaths = [
            p.replace(os.path.sep, "/") for p in install_relpaths
        ]
291 292 293 294
        relpaths_zip = list(zip(fslash_install_relpaths, install_relpaths))
        del install_relpaths, fslash_install_relpaths

        final_install_relpaths = []
O
Olli-Pekka Heinisuo 已提交
295

296
        print("Copying files from CMake output")
297

298
        for package_name, relpaths_re in cls.package_paths_re.items():
299
            package_dest_reldir = package_name.replace(".", os.path.sep)
300 301
            for relpath_re in relpaths_re:
                found = False
302
                r = re.compile(relpath_re + "$")
303 304
                for fslash_relpath, relpath in relpaths_zip:
                    m = r.match(fslash_relpath)
305 306
                    if not m:
                        continue
307 308
                    found = True
                    new_install_relpath = os.path.join(
309 310
                        package_dest_reldir, os.path.basename(relpath)
                    )
311 312 313
                    cls._setuptools_wrap._copy_file(
                        os.path.join(cmake_install_dir, relpath),
                        os.path.join(cmake_install_dir, new_install_relpath),
314 315
                        hide_listing=False,
                    )
316 317 318
                    final_install_relpaths.append(new_install_relpath)
                    del m, fslash_relpath, new_install_relpath
                else:
319 320
                    if not found:
                        raise Exception("Not found: '%s'" % relpath_re)
321
                del r, found
O
Olli-Pekka Heinisuo 已提交
322

323 324 325
        del relpaths_zip

        print("Copying files from non-default sourcetree locations")
326

327
        for package_name, paths in cls.files_outside_package.items():
328
            package_dest_reldir = package_name.replace(".", os.path.sep)
329 330
            for path in paths:
                new_install_relpath = os.path.join(
331 332 333 334 335
                    package_dest_reldir,
                    # Don't yet have a need to copy
                    # to subdirectories of package dir
                    os.path.basename(path),
                )
336
                cls._setuptools_wrap._copy_file(
337 338 339
                    path,
                    os.path.join(cmake_install_dir, new_install_relpath),
                    hide_listing=False,
340 341 342
                )
                final_install_relpaths.append(new_install_relpath)

343 344 345
        final_install_paths = [
            os.path.join(cmake_install_dir, p) for p in final_install_relpaths
        ]
346

O
Olli-Pekka Heinisuo 已提交
347
        return (cls.wraps._classify_installed_files)(
348
            final_install_paths,
349 350 351 352 353 354
            package_data,
            package_prefixes,
            py_modules,
            new_py_modules,
            scripts,
            new_scripts,
355
            data_files,
356
            # To get around a check that prepends source dir to paths and breaks package detection code.
357 358
            cmake_source_dir="",
            cmake_install_dir=cmake_install_reldir,
359
        )
360

O
Olli-Pekka Heinisuo 已提交
361 362 363 364 365
def get_opencv_version(contrib, headless):
    # cv2/version.py should be generated by running find_version.py
    version = {}
    here = os.path.abspath(os.path.dirname(__file__))
    version_file = os.path.join(here, "cv2", "version.py")
366

O
Olli-Pekka Heinisuo 已提交
367 368 369 370 371
    if not os.path.exists(version_file):
      old_args = sys.argv.copy()
      sys.argv = ['', str(contrib), str(headless)]
      runpy.run_path("find_version.py ", run_name="__main__")
      sys.argv = old_args
372

O
Olli-Pekka Heinisuo 已提交
373 374
    with open(version_file) as fp:
        exec(fp.read(), version)
375

O
Olli-Pekka Heinisuo 已提交
376
    return version['opencv_version'], version['contrib'], version['headless']
377

O
Olli-Pekka Heinisuo 已提交
378 379 380
def get_build_env_var_by_name(flag_name):
    flag_set = False

381
    try:
382
        flag_set = bool(int(os.getenv("ENABLE_" + flag_name.upper(), None)))
383 384 385
    except Exception:
        pass

O
Olli-Pekka Heinisuo 已提交
386
    if not flag_set:
387
        try:
O
Olli-Pekka Heinisuo 已提交
388
            flag_set = bool(int(open(flag_name + ".enabled").read(1)))
389 390
        except Exception:
            pass
O
Olli-Pekka Heinisuo 已提交
391 392

    return flag_set
393 394 395

# This creates a list which is empty but returns a length of 1.
# Should make the wheel a binary distribution and platlib compliant.
O
Olli-Pekka Heinisuo 已提交
396 397 398 399
class EmptyListWithLength(list):
    def __len__(self):
        return 1

400

401
if __name__ == "__main__":
402
    main()