setup.py 14.9 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 42
        import pip._internal.vcs.git as git
        g = git.Git()  # NOTE: pip API's are internal, this has to be refactored
43

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

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

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

O
Olli-Pekka Heinisuo 已提交
53 54
    package_name = "opencv-python"

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

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

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

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

67
    packages = ['cv2', 'cv2.data']
68

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

    # Files from CMake output to copy to package.
    # Path regexes with forward slashes relative to CMake install dir.
80
    rearrange_cmake_output_data = {
81

O
Olli-Pekka Heinisuo 已提交
82
        'cv2': ([r'bin/opencv_videoio_ffmpeg\d{3}%s\.dll' % ('_64' if x64 else '')] if os.name == 'nt' else []) +
83 84 85
        # 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 已提交
86
        ['python/cv2[^/]*%(ext)s' % {'ext': re.escape(sysconfig.get_config_var('SO'))}],
87

88
        'cv2.data': [  # OPENCV_OTHER_INSTALL_PATH
89
            ('etc' if os.name == 'nt' else 'share/opencv4') +
90 91 92 93
            r'/haarcascades/.*\.xml'
        ]
    }

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

100
    cmake_args = ([
101 102
        "-G", "Visual Studio 14" + (" Win64" if x64 else '')
    ] if os.name == 'nt' else [
103
        "-G", "Unix Makefiles"  # don't make CMake try (and fail) Ninja first
104
    ]) + [
105
        # skbuild inserts PYTHON_* vars. That doesn't satisfy opencv build scripts in case of Py3
106 107 108 109
        "-DPYTHON_DEFAULT_EXECUTABLE=%s" % sys.executable,
        "-DPYTHON3_EXECUTABLE=%s" % sys.executable,
        "-DBUILD_opencv_python3=ON",
        "-DBUILD_opencv_python2=OFF",
O
Olli-Pekka Heinisuo 已提交
110

111
        # When off, adds __init__.py and a few more helper .py's. We use our own helper files with a different structure.
112
        "-DOPENCV_SKIP_PYTHON_LOADER=ON",
113 114
        # 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
115
        "-DOPENCV_PYTHON3_INSTALL_PATH=python",
116 117 118
        # Otherwise, opencv scripts would want to install `.pyd' right into site-packages,
        # and skbuild bails out on seeing that
        "-DINSTALL_CREATE_DISTRIB=ON",
O
Olli-Pekka Heinisuo 已提交
119

120 121 122 123 124
        # See opencv/CMakeLists.txt for options and defaults
        "-DBUILD_opencv_apps=OFF",
        "-DBUILD_SHARED_LIBS=OFF",
        "-DBUILD_TESTS=OFF",
        "-DBUILD_PERF_TESTS=OFF",
O
Olli-Pekka Heinisuo 已提交
125
        "-DBUILD_DOCS=OFF"
126
    ] + (["-DOPENCV_EXTRA_MODULES_PATH=" + os.path.abspath("opencv_contrib/modules")] if build_contrib else [])
127

128
    # OS-specific components
129 130
    if sys.platform.startswith('linux') or sys.platform == 'darwin' and not build_headless:
        cmake_args.append("-DWITH_QT=5")
131

O
Olli-Pekka Heinisuo 已提交
132
    if sys.platform == 'darwin' and not build_headless:
D
David Lechner 已提交
133
        rearrange_cmake_output_data['cv2.qt.plugins.platforms'] = [(r'lib/qt/plugins/platforms/libqcocoa\.dylib')]
O
Olli-Pekka Heinisuo 已提交
134

O
Olli-Pekka Heinisuo 已提交
135 136 137 138
    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")
139
        cmake_args.append("-DWITH_MSMF=OFF") # see: https://github.com/skvark/opencv-python/issues/263
O
Olli-Pekka Heinisuo 已提交
140

141
    if sys.platform.startswith('linux'):
142
        cmake_args.append("-DWITH_V4L=ON")
143
        cmake_args.append("-DENABLE_PRECOMPILED_HEADERS=OFF")
144

O
Olli-Pekka Heinisuo 已提交
145
    # Fixes for macOS builds
146
    if sys.platform == 'darwin':
O
Olli-Pekka Heinisuo 已提交
147
        cmake_args.append("-DCMAKE_OSX_DEPLOYMENT_TARGET:STRING=10.9")
D
David Lechner 已提交
148
        subprocess.check_call("patch -p1 < patches/patchQtPlugins", shell=True)
O
Olli-Pekka Heinisuo 已提交
149

150 151 152 153
    if 'CMAKE_ARGS' in os.environ:
        import shlex
        cmake_args.extend(shlex.split(os.environ['CMAKE_ARGS']))
        del shlex
O
Olli-Pekka Heinisuo 已提交
154

155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
    # ABI config variables are introduced in PEP 425
    if sys.version_info[:2] < (3, 2):
        import warnings
        warnings.filterwarnings('ignore', r"Config variable '[^']+' is unset, "
                                          r"Python ABI tag may be incorrect",
                                category=RuntimeWarning)
        del warnings

    # works via side effect
    RearrangeCMakeOutput(rearrange_cmake_output_data,
                         files_outside_package_dir,
                         package_data.keys())

    skbuild.setup(
        name=package_name,
        version=package_version,
        url='https://github.com/skvark/opencv-python',
        license='MIT',
        description='Wrapper package for OpenCV python bindings.',
        long_description=long_description,
175
        long_description_content_type="text/markdown",
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
        packages=packages,
        package_data=package_data,
        maintainer="Olli-Pekka Heinisuo",
        include_package_data=True,
        ext_modules=EmptyListWithLength(),
        install_requires="numpy>=%s" % numpy_version,
        classifiers=[
          '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',
198
          'Programming Language :: Python :: 3.7',
O
Olli-Pekka Heinisuo 已提交
199
          'Programming Language :: Python :: 3.8',
200 201 202 203 204 205 206 207 208 209 210 211
          'Programming Language :: C++',
          'Programming Language :: Python :: Implementation :: CPython',
          'Topic :: Scientific/Engineering',
          'Topic :: Scientific/Engineering :: Image Recognition',
          'Topic :: Software Development',
        ],
        cmake_args=cmake_args,
        cmake_source_dir=cmake_source_dir,
          )


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
    _setuptools_wrap = None

    # Have to wrap a function reference, or it's converted
    # into an instance method on attr assignment
    import argparse
O
Olli-Pekka Heinisuo 已提交
221
    wraps = argparse.Namespace(_classify_installed_files=None)
222 223 224 225 226 227 228 229
    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 已提交
230
        assert not cls.wraps._classify_installed_files, "Singleton object"
231 232 233
        import skbuild.setuptools_wrap

        cls._setuptools_wrap = skbuild.setuptools_wrap
O
Olli-Pekka Heinisuo 已提交
234 235
        cls.wraps._classify_installed_files = cls._setuptools_wrap._classify_installed_files
        cls._setuptools_wrap._classify_installed_files = self._classify_installed_files_override
236 237 238 239

        cls.package_paths_re = package_paths_re
        cls.files_outside_package = files_outside_package
        cls.packages = packages
240

241 242
    def __del__(self):
        cls = self.__class__
O
Olli-Pekka Heinisuo 已提交
243 244
        cls._setuptools_wrap._classify_installed_files = cls.wraps._classify_installed_files
        cls.wraps._classify_installed_files = None
245 246
        cls._setuptools_wrap = None

O
Olli-Pekka Heinisuo 已提交
247
    def _classify_installed_files_override(self, install_paths,
248 249 250 251 252 253
            package_data, package_prefixes,
            py_modules, new_py_modules,
            scripts, new_scripts,
            data_files,
            cmake_source_dir, cmake_install_reldir):
        """
254 255 256 257 258 259 260 261 262
            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.
        """

263
        cls = self.__class__
264

265 266
        # 'relpath'/'reldir' = relative to CMAKE_INSTALL_DIR/cmake_install_dir
        # 'path'/'dir' = relative to sourcetree root
A
Admin 已提交
267
        cmake_install_dir = os.path.join(cls._setuptools_wrap.CMAKE_INSTALL_DIR(),
268 269 270 271 272 273 274
                                         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]
        relpaths_zip = list(zip(fslash_install_relpaths, install_relpaths))
        del install_relpaths, fslash_install_relpaths

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

276
        print("Copying files from CMake output")
277

278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
        for package_name, relpaths_re in cls.package_paths_re.items():
            package_dest_reldir = package_name.replace('.', os.path.sep)
            for relpath_re in relpaths_re:
                found = False
                r = re.compile(relpath_re+'$')
                for fslash_relpath, relpath in relpaths_zip:
                    m = r.match(fslash_relpath)
                    if not m: continue
                    found = True
                    new_install_relpath = os.path.join(
                        package_dest_reldir,
                        os.path.basename(relpath))
                    cls._setuptools_wrap._copy_file(
                        os.path.join(cmake_install_dir, relpath),
                        os.path.join(cmake_install_dir, new_install_relpath),
                        hide_listing=False)
                    final_install_relpaths.append(new_install_relpath)
                    del m, fslash_relpath, new_install_relpath
                else:
                    if not found: raise Exception("Not found: '%s'" % relpath_re)
                del r, found
O
Olli-Pekka Heinisuo 已提交
299

300 301 302
        del relpaths_zip

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

304 305 306 307 308 309 310 311 312 313
        for package_name, paths in cls.files_outside_package.items():
            package_dest_reldir = package_name.replace('.', os.path.sep)
            for path in paths:
                new_install_relpath = os.path.join(
                        package_dest_reldir,
                        # Don't yet have a need to copy
                        # to subdirectories of package dir
                        os.path.basename(path))
                cls._setuptools_wrap._copy_file(
                    path, os.path.join(cmake_install_dir, new_install_relpath),
314
                    hide_listing=False
315 316 317 318 319
                )
                final_install_relpaths.append(new_install_relpath)

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

O
Olli-Pekka Heinisuo 已提交
320
        return (cls.wraps._classify_installed_files)(
321 322 323 324 325
            final_install_paths,
            package_data, package_prefixes,
            py_modules, new_py_modules,
            scripts, new_scripts,
            data_files,
326 327 328 329
            # To get around a check that prepends source dir to paths and breaks package detection code.
            cmake_source_dir='',
            cmake_install_dir=cmake_install_reldir
        )
330 331 332 333


def install_packages(*requirements):
    # No more convenient way until PEP 518 is implemented; setuptools only handles eggs
334
    subprocess.check_call([sys.executable, "-m", "pip", "install"] + list(requirements))
335 336 337 338 339 340 341 342 343


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
    return opencv_version


O
Olli-Pekka Heinisuo 已提交
344 345 346 347
def get_build_env_var_by_name(flag_name):

    flag_set = False

348
    try:
O
Olli-Pekka Heinisuo 已提交
349
        flag_set = bool(int(os.getenv('ENABLE_' + flag_name.upper() , None)))
350 351 352
    except Exception:
        pass

O
Olli-Pekka Heinisuo 已提交
353
    if not flag_set:
354
        try:
O
Olli-Pekka Heinisuo 已提交
355
            flag_set = bool(int(open(flag_name + ".enabled").read(1)))
356 357
        except Exception:
            pass
O
Olli-Pekka Heinisuo 已提交
358 359

    return flag_set
360 361


362
def get_or_install(name, version=None):
363
    """ If a package is already installed, build against it. If not, install """
364 365 366
    # Do not import 3rd-party modules into the current process
    import json
    js_packages = json.loads(
O
Olli-Pekka Heinisuo 已提交
367
        subprocess.check_output([sys.executable, "-m", "pip", "list", "--format", "json"]).decode('ascii'))  # valid names & versions are ASCII as per PEP 440
368
    try:
369
        [package] = (package for package in js_packages if package['name'] == name)
370
    except ValueError:
371
        install_packages("%s==%s" % (name, version) if version else name)
372 373 374 375 376 377 378
        return version
    else:
        return package['version']


# 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 已提交
379 380 381 382
class EmptyListWithLength(list):
    def __len__(self):
        return 1

383

384 385
if __name__ == '__main__':
    main()