setup.py 15.1 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 17
    CI_BUILD = os.environ.get("CI_BUILD", "False")
    is_CI_build = True if CI_BUILD == "True" else False
18
    cmake_source_dir = "opencv"
O
Olli-Pekka Heinisuo 已提交
19
    minimum_supported_numpy = "1.13.1"
O
Olli-Pekka Heinisuo 已提交
20 21
    build_contrib = get_build_env_var_by_name("contrib")
    build_headless = get_build_env_var_by_name("headless")
22

23
    if sys.version_info[:2] >= (3, 6):
O
Olli-Pekka Heinisuo 已提交
24
        minimum_supported_numpy = "1.13.3"
25 26
    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()
O
Olli-Pekka Heinisuo 已提交
33 34 35 36 37 38
    python_lib_path = cmaker.CMaker.get_python_library(python_version).replace(
        "\\", "/"
    )
    python_include_dir = cmaker.CMaker.get_python_include_dir(python_version).replace(
        "\\", "/"
    )
39

40
    if os.path.exists(".git"):
O
Olli-Pekka Heinisuo 已提交
41
        import pip._internal.vcs.git as git
O
Olli-Pekka Heinisuo 已提交
42

O
Olli-Pekka Heinisuo 已提交
43
        g = git.Git()  # NOTE: pip API's are internal, this has to be refactored
44

45
        g.run_command(["submodule", "sync"])
46 47 48
        g.run_command(
            ["submodule", "update", "--init", "--recursive", cmake_source_dir]
        )
49

50
        if build_contrib:
51 52 53
            g.run_command(
                ["submodule", "update", "--init", "--recursive", "opencv_contrib"]
            )
O
Olli-Pekka Heinisuo 已提交
54

O
Olli-Pekka Heinisuo 已提交
55 56 57
    package_version, build_contrib, build_headless = get_opencv_version(
        build_contrib, build_headless
    )
O
Olli-Pekka Heinisuo 已提交
58

59
    # https://stackoverflow.com/questions/1405913/python-32bit-or-64bit-mode
60
    x64 = sys.maxsize > 2 ** 32
61

O
Olli-Pekka Heinisuo 已提交
62 63
    package_name = "opencv-python"

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

O
Olli-Pekka Heinisuo 已提交
67
    if build_contrib and build_headless:
O
Olli-Pekka Heinisuo 已提交
68 69
        package_name = "opencv-contrib-python-headless"

70
    if build_headless and not build_contrib:
O
Olli-Pekka Heinisuo 已提交
71 72
        package_name = "opencv-python-headless"

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

75
    packages = ["cv2", "cv2.data"]
76

77
    package_data = {
O
Olli-Pekka Heinisuo 已提交
78
        "cv2": ["*%s" % sysconfig.get_config_vars().get("SO"), "version.py"]
79 80 81
        + (["*.dll"] if os.name == "nt" else [])
        + ["LICENSE.txt", "LICENSE-3RD-PARTY.txt"],
        "cv2.data": ["*.xml"],
82
    }
83 84 85

    # Files from CMake output to copy to package.
    # Path regexes with forward slashes relative to CMake install dir.
86
    rearrange_cmake_output_data = {
87 88 89 90 91 92
        "cv2": (
            [r"bin/opencv_videoio_ffmpeg\d{3}%s\.dll" % ("_64" if x64 else "")]
            if os.name == "nt"
            else []
        )
        +
93 94 95
        # 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 已提交
96 97 98 99
        [
            "python/cv2[^/]*%(ext)s"
            % {"ext": re.escape(sysconfig.get_config_var("EXT_SUFFIX"))}
        ],
100 101 102
        "cv2.data": [  # OPENCV_OTHER_INSTALL_PATH
            ("etc" if os.name == "nt" else "share/opencv4") + r"/haarcascades/.*\.xml"
        ],
103 104
    }

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

O
Olli-Pekka Heinisuo 已提交
109 110 111 112 113 114
    ci_cmake_generator = (
        ["-G", "Visual Studio 14" + (" Win64" if x64 else "")]
        if os.name == "nt"
        else ["-G", "Unix Makefiles"]
    )

115
    cmake_args = (
O
Olli-Pekka Heinisuo 已提交
116
        (ci_cmake_generator if is_CI_build else [])
117 118
        + [
            # skbuild inserts PYTHON_* vars. That doesn't satisfy opencv build scripts in case of Py3
O
Olli-Pekka Heinisuo 已提交
119
            "-DPYTHON3_EXECUTABLE=%s" % sys.executable,
120 121
            "-DPYTHON3_INCLUDE_DIR=%s" % python_include_dir,
            "-DPYTHON3_LIBRARY=%s" % python_lib_path,
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
            "-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 []
        )
    )
145

O
Olli-Pekka Heinisuo 已提交
146 147 148 149
    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")
O
Olli-Pekka Heinisuo 已提交
150 151 152 153 154 155 156 157 158 159
        cmake_args.append("-DWITH_GTK=OFF")
        if is_CI_build:
            cmake_args.append(
                "-DWITH_MSMF=OFF"
            )  # see: https://github.com/skvark/opencv-python/issues/263

    # OS-specific components during CI builds
    if is_CI_build:
        if sys.platform.startswith("linux") and not build_headless:
            cmake_args.append("-DWITH_QT=4")
O
Olli-Pekka Heinisuo 已提交
160

O
Olli-Pekka Heinisuo 已提交
161 162 163 164 165 166 167
        if sys.platform == "darwin" and not build_headless:
            cmake_args.append("-DWITH_QT=5")

        if sys.platform.startswith("linux"):
            cmake_args.append("-DWITH_V4L=ON")
            cmake_args.append("-DWITH_LAPACK=ON")
            cmake_args.append("-DENABLE_PRECOMPILED_HEADERS=OFF")
168

O
Olli-Pekka Heinisuo 已提交
169
    if sys.platform.startswith("linux") and not x64 and "bdist_wheel" in sys.argv:
170 171
        subprocess.check_call("patch -p0 < patches/patchOpenEXR", shell=True)

O
Olli-Pekka Heinisuo 已提交
172 173 174 175 176 177 178 179
    if (
        sys.platform == "darwin"
        and "bdist_wheel" in sys.argv
        and ("WITH_QT=5" in sys.argv or "WITH_QT=5" in cmake_args)
    ):
        rearrange_cmake_output_data["cv2.qt.plugins.platforms"] = [
            (r"lib/qt/plugins/platforms/libqcocoa\.dylib")
        ]
O
Olli-Pekka Heinisuo 已提交
180 181
        subprocess.check_call("patch -p1 < patches/patchQtPlugins", shell=True)

182
    # works via side effect
183 184 185
    RearrangeCMakeOutput(
        rearrange_cmake_output_data, files_outside_package_dir, package_data.keys()
    )
186 187 188 189

    skbuild.setup(
        name=package_name,
        version=package_version,
190 191 192
        url="https://github.com/skvark/opencv-python",
        license="MIT",
        description="Wrapper package for OpenCV python bindings.",
193
        long_description=long_description,
194
        long_description_content_type="text/markdown",
195 196 197 198
        packages=packages,
        package_data=package_data,
        maintainer="Olli-Pekka Heinisuo",
        ext_modules=EmptyListWithLength(),
O
Olli-Pekka Heinisuo 已提交
199
        install_requires=numpy_version,
200
        classifiers=[
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
            "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",
223 224 225
        ],
        cmake_args=cmake_args,
        cmake_source_dir=cmake_source_dir,
226
    )
227 228 229


class RearrangeCMakeOutput(object):
230 231 232 233
    """
        Patch SKBuild logic to only take files related to the Python package
        and construct a file hierarchy that SKBuild expects (see below)
    """
234

235 236 237 238 239
    _setuptools_wrap = None

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

O
Olli-Pekka Heinisuo 已提交
241
    wraps = argparse.Namespace(_classify_installed_files=None)
242 243 244 245 246 247 248 249
    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 已提交
250
        assert not cls.wraps._classify_installed_files, "Singleton object"
251 252 253
        import skbuild.setuptools_wrap

        cls._setuptools_wrap = skbuild.setuptools_wrap
254 255 256 257 258 259
        cls.wraps._classify_installed_files = (
            cls._setuptools_wrap._classify_installed_files
        )
        cls._setuptools_wrap._classify_installed_files = (
            self._classify_installed_files_override
        )
260 261 262 263

        cls.package_paths_re = package_paths_re
        cls.files_outside_package = files_outside_package
        cls.packages = packages
264

265 266
    def __del__(self):
        cls = self.__class__
267 268 269
        cls._setuptools_wrap._classify_installed_files = (
            cls.wraps._classify_installed_files
        )
O
Olli-Pekka Heinisuo 已提交
270
        cls.wraps._classify_installed_files = None
271 272
        cls._setuptools_wrap = None

273 274 275 276 277 278 279 280 281 282 283 284 285
    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,
    ):
286
        """
287 288 289 290 291 292 293 294 295
            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.
        """

296
        cls = self.__class__
297

298 299
        # 'relpath'/'reldir' = relative to CMAKE_INSTALL_DIR/cmake_install_dir
        # 'path'/'dir' = relative to sourcetree root
300 301 302 303 304 305 306 307 308
        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
        ]
309 310 311 312
        relpaths_zip = list(zip(fslash_install_relpaths, install_relpaths))
        del install_relpaths, fslash_install_relpaths

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

314
        print("Copying files from CMake output")
315

316
        for package_name, relpaths_re in cls.package_paths_re.items():
317
            package_dest_reldir = package_name.replace(".", os.path.sep)
318 319
            for relpath_re in relpaths_re:
                found = False
320
                r = re.compile(relpath_re + "$")
321 322
                for fslash_relpath, relpath in relpaths_zip:
                    m = r.match(fslash_relpath)
323 324
                    if not m:
                        continue
325 326
                    found = True
                    new_install_relpath = os.path.join(
327 328
                        package_dest_reldir, os.path.basename(relpath)
                    )
329 330 331
                    cls._setuptools_wrap._copy_file(
                        os.path.join(cmake_install_dir, relpath),
                        os.path.join(cmake_install_dir, new_install_relpath),
332 333
                        hide_listing=False,
                    )
334 335 336
                    final_install_relpaths.append(new_install_relpath)
                    del m, fslash_relpath, new_install_relpath
                else:
337 338
                    if not found:
                        raise Exception("Not found: '%s'" % relpath_re)
339
                del r, found
O
Olli-Pekka Heinisuo 已提交
340

341 342 343
        del relpaths_zip

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

345
        for package_name, paths in cls.files_outside_package.items():
346
            package_dest_reldir = package_name.replace(".", os.path.sep)
347 348
            for path in paths:
                new_install_relpath = os.path.join(
349 350 351 352 353
                    package_dest_reldir,
                    # Don't yet have a need to copy
                    # to subdirectories of package dir
                    os.path.basename(path),
                )
354
                cls._setuptools_wrap._copy_file(
355 356 357
                    path,
                    os.path.join(cmake_install_dir, new_install_relpath),
                    hide_listing=False,
358 359 360
                )
                final_install_relpaths.append(new_install_relpath)

361 362 363
        final_install_paths = [
            os.path.join(cmake_install_dir, p) for p in final_install_relpaths
        ]
364

O
Olli-Pekka Heinisuo 已提交
365
        return (cls.wraps._classify_installed_files)(
366
            final_install_paths,
367 368 369 370 371 372
            package_data,
            package_prefixes,
            py_modules,
            new_py_modules,
            scripts,
            new_scripts,
373
            data_files,
374
            # To get around a check that prepends source dir to paths and breaks package detection code.
375 376
            cmake_source_dir="",
            cmake_install_dir=cmake_install_reldir,
377
        )
378

O
Olli-Pekka Heinisuo 已提交
379

O
Olli-Pekka Heinisuo 已提交
380 381 382 383 384
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")
385

O
Olli-Pekka Heinisuo 已提交
386 387 388 389 390 391
    # generate a fresh version.py always when Git repository exists
    if os.path.exists(".git"):
        old_args = sys.argv.copy()
        sys.argv = ["", str(contrib), str(headless)]
        runpy.run_path("find_version.py", run_name="__main__")
        sys.argv = old_args
392

O
Olli-Pekka Heinisuo 已提交
393 394
    with open(version_file) as fp:
        exec(fp.read(), version)
395

O
Olli-Pekka Heinisuo 已提交
396 397
    return version["opencv_version"], version["contrib"], version["headless"]

398

O
Olli-Pekka Heinisuo 已提交
399 400 401
def get_build_env_var_by_name(flag_name):
    flag_set = False

402
    try:
403
        flag_set = bool(int(os.getenv("ENABLE_" + flag_name.upper(), None)))
404 405 406
    except Exception:
        pass

O
Olli-Pekka Heinisuo 已提交
407
    if not flag_set:
408
        try:
O
Olli-Pekka Heinisuo 已提交
409
            flag_set = bool(int(open(flag_name + ".enabled").read(1)))
410 411
        except Exception:
            pass
O
Olli-Pekka Heinisuo 已提交
412 413

    return flag_set
414

O
Olli-Pekka Heinisuo 已提交
415

416 417
# 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 已提交
418 419 420 421
class EmptyListWithLength(list):
    def __len__(self):
        return 1

422

423
if __name__ == "__main__":
424
    main()