setup.py 16.4 KB
Newer Older
1
# No 3rd-party modules here, see "3rd-party" note below
2 3 4 5 6 7 8 9
import io
import os
import os.path
import sys
import runpy
import subprocess
import re
import sysconfig
10

11

12
def main():
O
Olli-Pekka Heinisuo 已提交
13

14
    os.chdir(os.path.dirname(os.path.abspath(__file__)))
15

16 17
    # These are neede for source fetching
    cmake_source_dir = "opencv"
O
Olli-Pekka Heinisuo 已提交
18 19 20
    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")
21

22 23 24
    # Only import 3rd-party modules after having installed all the build dependencies:
    # any of them, or their dependencies, can be updated during that process,
    # leading to version conflicts
25 26 27 28 29 30
    minimum_supported_numpy = "1.11.1"

    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"
31 32
    if sys.version_info[:2] >= (3, 8):
        minimum_supported_numpy = "1.17.3"
33 34

    numpy_version = get_or_install("numpy", minimum_supported_numpy)
35
    get_or_install("scikit-build")
36
    get_or_install("cmake")
37
    import skbuild
38

39
    if os.path.exists(".git"):
40

O
Olli-Pekka Heinisuo 已提交
41
        import pip._internal.vcs.git as git
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

55
    # https://stackoverflow.com/questions/1405913/python-32bit-or-64bit-mode
56
    x64 = sys.maxsize > 2 ** 32
57

O
Olli-Pekka Heinisuo 已提交
58 59
    package_name = "opencv-python"

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

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

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

69
    long_description = io.open("README.md", encoding="utf-8").read()
70
    package_version = get_opencv_version()
O
Olli-Pekka Heinisuo 已提交
71

72
    packages = ["cv2", "cv2.data"]
73

74
    package_data = {
75 76 77 78
        "cv2": ["*%s" % sysconfig.get_config_vars().get("SO")]
        + (["*.dll"] if os.name == "nt" else [])
        + ["LICENSE.txt", "LICENSE-3RD-PARTY.txt"],
        "cv2.data": ["*.xml"],
79
    }
80 81 82

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

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

103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
    cmake_args = (
        (
            ["-G", "Visual Studio 14" + (" Win64" if x64 else "")]
            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
            "-DPYTHON_DEFAULT_EXECUTABLE=%s" % sys.executable,
            "-DPYTHON3_INCLUDE_DIR=%s" % sysconfig.get_paths()["include"],
            "-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",
        ]
        + (
            [
                "-DPYTHON3_LIBRARY=%s"
                % os.path.join(
                    *[
                        sysconfig.get_config_var("BINDIR"),
                        "libs",
                        "python{}.lib".format(
                            "".join(str(v) for v in sys.version_info[:2])
                        ),
                    ]
                )
            ]
            if sys.platform.startswith("win")
            else [
                "-DPYTHON3_LIBRARY=%s"
                % os.path.join(
                    "/usr/lib/x86_64-linux-gnu/", sysconfig.get_config_var("LDLIBRARY")
                )
            ]
        )
        + (
            ["-DOPENCV_EXTRA_MODULES_PATH=" + os.path.abspath("opencv_contrib/modules")]
            if build_contrib
            else []
        )
    )
157

158
    # OS-specific components
159 160 161 162 163
    if (
        sys.platform.startswith("linux")
        or sys.platform == "darwin"
        and not build_headless
    ):
164
        cmake_args.append("-DWITH_QT=5")
165

166 167 168 169
    if sys.platform == "darwin" and not build_headless:
        rearrange_cmake_output_data["cv2.qt.plugins.platforms"] = [
            (r"lib/qt/plugins/platforms/libqcocoa\.dylib")
        ]
O
Olli-Pekka Heinisuo 已提交
170

O
Olli-Pekka Heinisuo 已提交
171 172 173 174
    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")
175 176 177
        cmake_args.append(
            "-DWITH_MSMF=OFF"
        )  # see: https://github.com/skvark/opencv-python/issues/263
O
Olli-Pekka Heinisuo 已提交
178

179
    if sys.platform.startswith("linux"):
180
        cmake_args.append("-DWITH_V4L=ON")
181
        cmake_args.append("-DENABLE_PRECOMPILED_HEADERS=OFF")
182

183 184 185
    if sys.platform.startswith('linux') and not x64:
        subprocess.check_call("patch -p0 < patches/patchOpenEXR", shell=True)

O
Olli-Pekka Heinisuo 已提交
186
    # Fixes for macOS builds
187
    if sys.platform == "darwin":
O
Olli-Pekka Heinisuo 已提交
188
        cmake_args.append("-DCMAKE_OSX_DEPLOYMENT_TARGET:STRING=10.9")
D
David Lechner 已提交
189
        subprocess.check_call("patch -p1 < patches/patchQtPlugins", shell=True)
O
Olli-Pekka Heinisuo 已提交
190

191
    if "CMAKE_ARGS" in os.environ:
192
        import shlex
193 194

        cmake_args.extend(shlex.split(os.environ["CMAKE_ARGS"]))
195
        del shlex
O
Olli-Pekka Heinisuo 已提交
196

197 198 199
    # ABI config variables are introduced in PEP 425
    if sys.version_info[:2] < (3, 2):
        import warnings
200 201 202 203 204 205

        warnings.filterwarnings(
            "ignore",
            r"Config variable '[^']+' is unset, " r"Python ABI tag may be incorrect",
            category=RuntimeWarning,
        )
206 207 208
        del warnings

    # works via side effect
209 210 211
    RearrangeCMakeOutput(
        rearrange_cmake_output_data, files_outside_package_dir, package_data.keys()
    )
212 213 214 215

    skbuild.setup(
        name=package_name,
        version=package_version,
216 217 218
        url="https://github.com/skvark/opencv-python",
        license="MIT",
        description="Wrapper package for OpenCV python bindings.",
219
        long_description=long_description,
220
        long_description_content_type="text/markdown",
221 222 223 224 225 226 227
        packages=packages,
        package_data=package_data,
        maintainer="Olli-Pekka Heinisuo",
        include_package_data=True,
        ext_modules=EmptyListWithLength(),
        install_requires="numpy>=%s" % numpy_version,
        classifiers=[
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
            "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",
250 251 252
        ],
        cmake_args=cmake_args,
        cmake_source_dir=cmake_source_dir,
253
    )
254 255 256


class RearrangeCMakeOutput(object):
257 258 259 260
    """
        Patch SKBuild logic to only take files related to the Python package
        and construct a file hierarchy that SKBuild expects (see below)
    """
261

262 263 264 265 266
    _setuptools_wrap = None

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

O
Olli-Pekka Heinisuo 已提交
268
    wraps = argparse.Namespace(_classify_installed_files=None)
269 270 271 272 273 274 275 276
    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 已提交
277
        assert not cls.wraps._classify_installed_files, "Singleton object"
278 279 280
        import skbuild.setuptools_wrap

        cls._setuptools_wrap = skbuild.setuptools_wrap
281 282 283 284 285 286
        cls.wraps._classify_installed_files = (
            cls._setuptools_wrap._classify_installed_files
        )
        cls._setuptools_wrap._classify_installed_files = (
            self._classify_installed_files_override
        )
287 288 289 290

        cls.package_paths_re = package_paths_re
        cls.files_outside_package = files_outside_package
        cls.packages = packages
291

292 293
    def __del__(self):
        cls = self.__class__
294 295 296
        cls._setuptools_wrap._classify_installed_files = (
            cls.wraps._classify_installed_files
        )
O
Olli-Pekka Heinisuo 已提交
297
        cls.wraps._classify_installed_files = None
298 299
        cls._setuptools_wrap = None

300 301 302 303 304 305 306 307 308 309 310 311 312
    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,
    ):
313
        """
314 315 316 317 318 319 320 321 322
            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.
        """

323
        cls = self.__class__
324

325 326
        # 'relpath'/'reldir' = relative to CMAKE_INSTALL_DIR/cmake_install_dir
        # 'path'/'dir' = relative to sourcetree root
327 328 329 330 331 332 333 334 335
        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
        ]
336 337 338 339
        relpaths_zip = list(zip(fslash_install_relpaths, install_relpaths))
        del install_relpaths, fslash_install_relpaths

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

341
        print("Copying files from CMake output")
342

343
        for package_name, relpaths_re in cls.package_paths_re.items():
344
            package_dest_reldir = package_name.replace(".", os.path.sep)
345 346
            for relpath_re in relpaths_re:
                found = False
347
                r = re.compile(relpath_re + "$")
348 349
                for fslash_relpath, relpath in relpaths_zip:
                    m = r.match(fslash_relpath)
350 351
                    if not m:
                        continue
352 353
                    found = True
                    new_install_relpath = os.path.join(
354 355
                        package_dest_reldir, os.path.basename(relpath)
                    )
356 357 358
                    cls._setuptools_wrap._copy_file(
                        os.path.join(cmake_install_dir, relpath),
                        os.path.join(cmake_install_dir, new_install_relpath),
359 360
                        hide_listing=False,
                    )
361 362 363
                    final_install_relpaths.append(new_install_relpath)
                    del m, fslash_relpath, new_install_relpath
                else:
364 365
                    if not found:
                        raise Exception("Not found: '%s'" % relpath_re)
366
                del r, found
O
Olli-Pekka Heinisuo 已提交
367

368 369 370
        del relpaths_zip

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

372
        for package_name, paths in cls.files_outside_package.items():
373
            package_dest_reldir = package_name.replace(".", os.path.sep)
374 375
            for path in paths:
                new_install_relpath = os.path.join(
376 377 378 379 380
                    package_dest_reldir,
                    # Don't yet have a need to copy
                    # to subdirectories of package dir
                    os.path.basename(path),
                )
381
                cls._setuptools_wrap._copy_file(
382 383 384
                    path,
                    os.path.join(cmake_install_dir, new_install_relpath),
                    hide_listing=False,
385 386 387
                )
                final_install_relpaths.append(new_install_relpath)

388 389 390
        final_install_paths = [
            os.path.join(cmake_install_dir, p) for p in final_install_relpaths
        ]
391

O
Olli-Pekka Heinisuo 已提交
392
        return (cls.wraps._classify_installed_files)(
393
            final_install_paths,
394 395 396 397 398 399
            package_data,
            package_prefixes,
            py_modules,
            new_py_modules,
            scripts,
            new_scripts,
400
            data_files,
401
            # To get around a check that prepends source dir to paths and breaks package detection code.
402 403
            cmake_source_dir="",
            cmake_install_dir=cmake_install_reldir,
404
        )
405 406 407 408


def install_packages(*requirements):
    # No more convenient way until PEP 518 is implemented; setuptools only handles eggs
409
    subprocess.check_call([sys.executable, "-m", "pip", "install"] + list(requirements))
410 411 412 413 414 415


def get_opencv_version():
    # cv_version.py should be generated by running find_version.py
    runpy.run_path("find_version.py")
    from cv_version import opencv_version
416

417 418 419
    return opencv_version


O
Olli-Pekka Heinisuo 已提交
420 421 422
def get_build_env_var_by_name(flag_name):
    flag_set = False

423
    try:
424
        flag_set = bool(int(os.getenv("ENABLE_" + flag_name.upper(), None)))
425 426 427
    except Exception:
        pass

O
Olli-Pekka Heinisuo 已提交
428
    if not flag_set:
429
        try:
O
Olli-Pekka Heinisuo 已提交
430
            flag_set = bool(int(open(flag_name + ".enabled").read(1)))
431 432
        except Exception:
            pass
O
Olli-Pekka Heinisuo 已提交
433 434

    return flag_set
435 436


437
def get_or_install(name, version=None):
438
    """ If a package is already installed, build against it. If not, install """
439 440
    # Do not import 3rd-party modules into the current process
    import json
441

442
    js_packages = json.loads(
443 444 445 446
        subprocess.check_output(
            [sys.executable, "-m", "pip", "list", "--format", "json"]
        ).decode("ascii")
    )  # valid names & versions are ASCII as per PEP 440
447
    try:
448
        [package] = (package for package in js_packages if package["name"] == name)
449
    except ValueError:
450
        install_packages("%s==%s" % (name, version) if version else name)
451 452
        return version
    else:
453
        return package["version"]
454 455 456 457


# 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 已提交
458 459 460 461
class EmptyListWithLength(list):
    def __len__(self):
        return 1

462

463
if __name__ == "__main__":
464
    main()