setup.py 12.3 KB
Newer Older
1
"""setup for the dlib project
Ehsan Azarnasab's avatar
Ehsan Azarnasab committed
2
3
 Copyright (C) 2015  Ehsan Azar (dashesy@linux.com)
 License: Boost Software License   See LICENSE.txt for the full license.
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

To build the dlib:
    python setup.py build
To build and install:
    python setup.py install
To package the wheel:
    python setup.py bdist_wheel
To repackage the previously built package as wheel (bypassing build):
    python setup.py bdist_wheel --repackage
To install a develop version (egg with symbolic link):
    python setup.py develop
To exclude/include certain features in the build:
    --no-gui-support: sets DLIB_NO_GUI_SUPPORT
    --enable-stack-trace: sets DLIB_ENABLE_STACK_TRACE
    --enable-asserts: sets DLIB_ENABLE_ASSERTS
    --no-blas: unsets DLIB_USE_BLAS
    --no-lapack: unsets DLIB_USE_LAPACK
    --no-libpng: unsets DLIB_LINK_WITH_LIBPNG
    --no-libjpeg: unsets DLIB_LINK_WITH_LIBJPEG
    --no-sqlite3: unsets DLIB_LINK_WITH_SQLITE3
Additional options:
    --debug: makes a debug build
    --cmake: path to specific cmake executable
"""

from __future__ import print_function
import shutil
import stat
import errno

from setuptools.command.bdist_egg import bdist_egg as _bdist_egg
from setuptools.command.develop import develop as _develop
from distutils.command.build_ext import build_ext as _build_ext
from distutils.command.build import build as _build
Ehsan Azarnasab's avatar
Ehsan Azarnasab committed
38
from distutils.errors import DistutilsSetupError
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
from distutils.spawn import find_executable
from distutils import log
import os
import sys
from setuptools import Extension, setup
import platform
from subprocess import Popen, PIPE, STDOUT
import signal
from threading import Thread
import time


# change directory to this module path
try:
    this_file = __file__
except NameError:
    this_file = sys.argv[0]
this_file = os.path.abspath(this_file)
if os.path.dirname(this_file):
    os.chdir(os.path.dirname(this_file))
script_dir = os.getcwd()

61

Ehsan Azarnasab's avatar
Ehsan Azarnasab committed
62
63
64
65
66
67
def _get_options():
    """read arguments and creates options
    """
    _cmake_path = find_executable("cmake")
    _cmake_extra = []
    _cmake_config = 'Release'
68

Ehsan Azarnasab's avatar
Ehsan Azarnasab committed
69
70
    _options = []
    opt_key = None
71

Ehsan Azarnasab's avatar
Ehsan Azarnasab committed
72
73
74
75
76
77
78
79
    # parse commandline options and consume those we care about
    for opt_idx, arg in enumerate(sys.argv):
        if opt_key == 'cmake':
            _cmake_path = opt

        if opt_key:
            sys.argv.remove(arg)
            continue
80

81
82
        if not arg.startswith('--'):
            continue
Ehsan Azarnasab's avatar
Ehsan Azarnasab committed
83

84
        opt = arg[2:].lower()
Ehsan Azarnasab's avatar
Ehsan Azarnasab committed
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
        if opt == 'cmake':
            _cmake_path = None
            opt_key = opt
            sys.argv.remove(arg)
            continue

        opt_key = None
        custom_arg = True
        if opt == 'debug':
            _cmake_config = 'Debug'
        elif opt == 'release':
            _cmake_config = 'Release'
        elif opt == 'no-gui-support':
            _cmake_extra.append('-DDLIB_NO_GUI_SUPPORT=yes')
        elif opt == 'enable-stack-trace':
            _cmake_extra.append('-DDLIB_ENABLE_STACK_TRACE=yes')
        elif opt == 'enable-asserts':
            _cmake_extra.append('-DDLIB_ENABLE_ASSERTS=yes')
        elif opt == 'no-blas':
            _cmake_extra.append('-DDLIB_USE_BLAS=no')
        elif opt == 'no-lapack':
            _cmake_extra.append('-DDLIB_USE_LAPACK=no')
        elif opt == 'no-libpng':
            _cmake_extra.append('-DDLIB_LINK_WITH_LIBPNG=no')
        elif opt == 'no-libjpeg':
            _cmake_extra.append('-DDLIB_LINK_WITH_LIBJPEG=no')
        elif opt == 'no-sqlite3':
            _cmake_extra.append('-DDLIB_LINK_WITH_SQLITE3=no')
        elif opt in ['debug', 'release',
                     'repackage']:
            _options.append(opt)
        else:
            custom_arg = False
        if custom_arg:
            sys.argv.remove(arg)
120

Ehsan Azarnasab's avatar
Ehsan Azarnasab committed
121
    return _options, _cmake_config, _cmake_path, _cmake_extra
122

Ehsan Azarnasab's avatar
Ehsan Azarnasab committed
123
options, cmake_config, cmake_path, cmake_extra = _get_options()
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218

try:
    from Queue import Queue, Empty
except ImportError:
    # noinspection PyUnresolvedReferences
    from queue import Queue, Empty  # python 3.x


_ON_POSIX = 'posix' in sys.builtin_module_names


def enqueue_output(out, queue):
    for line in iter(out.readline, b''):
        queue.put(line)
    out.close()


def _log_buf(buf):
    if not buf:
        return
    buf = buf.rstrip()
    lines = buf.splitlines()
    for line in lines:
        log.info(line)


def run_process(cmds, timeout=None):
    """run a process asynchronously
    :param cmds: list of commands to invoke on a shell e.g. ['make', 'install']
    :param timeout: timeout in seconds (optional)
    """

    # open process as its own session, and with no stdout buffering
    p = Popen(cmds,
              stdout=PIPE, stderr=STDOUT,
              bufsize=1,
              close_fds=_ON_POSIX, preexec_fn=os.setsid)

    q = Queue()
    t = Thread(target=enqueue_output, args=(p.stdout, q))
    t.daemon = True  # thread dies with the program
    t.start()

    _time = time.time()
    e = None
    try:
        while t.isAlive():
            try:
                buf = q.get(timeout=.1)
            except Empty:
                buf = ''
            _log_buf(buf)
            elapsed = time.time() - _time
            if timeout and elapsed > timeout:
                break
    except (KeyboardInterrupt, SystemExit) as e:
        # if user interrupted
        pass

    # noinspection PyBroadException
    try:
        os.kill(p.pid, signal.SIGINT)
    except (KeyboardInterrupt, SystemExit) as e:
        pass
    except:
        pass

    # noinspection PyBroadException
    try:
        if e:
            os.kill(p.pid, signal.SIGKILL)
        else:
            p.wait()
    except (KeyboardInterrupt, SystemExit) as e:
        # noinspection PyBroadException
        try:
            os.kill(p.pid, signal.SIGKILL)
        except:
            pass
    except:
        pass

    t.join(timeout=0.1)
    if e:
        raise e

    return p.returncode


def readme(fname):
    """Read text out of a file relative to setup.py.
    """
    return open(os.path.join(script_dir, fname)).read()


Ehsan Azarnasab's avatar
Ehsan Azarnasab committed
219
220
221
def read_version():
    """Read version information
    """
222
223
    major = readme('./docs/.current_release_number').strip()
    minor = readme('./docs/.current_minor_release_number').strip()
Ehsan Azarnasab's avatar
Ehsan Azarnasab committed
224
225
    return major + '.' + minor

Ehsan Azarnasab's avatar
Ehsan Azarnasab committed
226

227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
def rmtree(name):
    """remove a directory and its subdirectories.
    """
    def remove_read_only(func, path, exc):
        excvalue = exc[1]
        if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES:
            os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
            func(path)
        else:
            raise
    shutil.rmtree(name, ignore_errors=False, onerror=remove_read_only)


def copy_file(src, dst):
    """copy a single file and log
    """
Ehsan Azarnasab's avatar
Ehsan Azarnasab committed
243
    log.info("Copying file %s -> %s." % (src, dst))
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
    shutil.copy2(src, dst)


# noinspection PyPep8Naming
class build(_build):
    def run(self):
        repackage = 'repackage' in options
        if not repackage:
            self.build_dlib()

        dist_dir = os.path.join(script_dir, "dist")
        if os.path.exists(dist_dir):
            log.info('Removing distribution directory %s' % dist_dir)
            rmtree(dist_dir)

259
260
        # this is where the extension examples go
        dist_dir_examples = os.path.join(script_dir, "./dist/dlib/examples")
261
262
263
264
265
        try:
            os.makedirs(dist_dir_examples)
        except OSError:
            pass

266
267
268
        # this is where the extension goes
        log.info('Populating the distribution directory %s ...' % dist_dir)
        dist_dir = os.path.join(script_dir, "./dist/dlib")
269
270

        # create the module init files
271
272
273
274
275
        with open(os.path.join(dist_dir, '__init__.py'), 'w') as f:
            # just so that we can `import dlib` and not `from dlib import dlib`
            f.write('from .dlib import *\n')
            # add version here
            f.write('__version__ = {ver}\n'.format(ver=read_version()))
276
277
278
279
        with open(os.path.join(dist_dir_examples, '__init__.py'), 'w'):
            pass

        # this is where the extension and Python examples are located
280
        out_dir = os.path.join(script_dir, "./python_examples")
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296

        ext_found = False
        # manually copy everything to distribution folder with package hierarchy in mind
        names = os.listdir(out_dir)
        for name in names:
            srcname = os.path.join(out_dir, name)
            dstname = os.path.join(dist_dir, name)
            dstextname = os.path.join(dist_dir_examples, name)
            if name.endswith('.py') or name.endswith('.txt'):
                copy_file(srcname, dstextname)
            elif name.endswith('.dll') or name.endswith('.so') or name.endswith('.pyd'):
                if name.startswith('dlib'):
                    ext_found = True
                copy_file(srcname, dstname)

        if not ext_found:
297
            raise DistutilsSetupError("Cannot find built dlib extension module.")
298
299
300
301
302
303
304

        return _build.run(self)

    @staticmethod
    def build_dlib():
        """use cmake to build and install the extension
        """
305
306
307
        if cmake_path is None:
            raise DistutilsSetupError("Cannot find cmake in the path. Please specify its path with --cmake parameter.")
        
308
309
310
        platform_arch = platform.architecture()[0]
        log.info("Detected Python architecture: %s" % platform_arch)

311
        build_dir = os.path.join(script_dir, "./tools/python/build")
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
        if os.path.exists(build_dir):
            log.info('Removing build directory %s' % build_dir)
            rmtree(build_dir)

        try:
            os.makedirs(build_dir)
        except OSError:
            pass

        # cd build
        os.chdir(build_dir)
        log.info('Configuring cmake ...')
        cmake_cmd = [
            cmake_path,
            "..",
        ] + cmake_extra
        if run_process(cmake_cmd):
            raise DistutilsSetupError("cmake configuration failed!")

        log.info('Build using cmake ...')

        cmake_cmd = [
            cmake_path,
            "--build", ".",
            "--config", cmake_config,
            "--target", "install",
        ]

        if run_process(cmake_cmd):
            raise DistutilsSetupError("cmake build failed!")

343
        # cd back where setup awaits
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
        os.chdir(script_dir)


# noinspection PyPep8Naming
class develop(_develop):

    def __init__(self, *args, **kwargs):
        _develop.__init__(self, *args, **kwargs)

    def run(self):
        self.run_command("build")
        return _develop.run(self)


# noinspection PyPep8Naming
class bdist_egg(_bdist_egg):
    def __init__(self, *args, **kwargs):
        _bdist_egg.__init__(self, *args, **kwargs)

    def run(self):
        self.run_command("build")
        return _bdist_egg.run(self)


# noinspection PyPep8Naming
class build_ext(_build_ext):
    def __init__(self, *args, **kwargs):
        _build_ext.__init__(self, *args, **kwargs)

    def run(self):
        # cmake will do the heavy lifting, just pick up the fruits of its labour
        pass

setup(
    name='dlib',
Ehsan Azarnasab's avatar
Ehsan Azarnasab committed
379
    version=read_version(),
380
381
    keywords=['dlib', 'Computer Vision', 'Machine Learning'],
    description='A toolkit for making real world machine learning and data analysis applications',
382
    long_description=readme('./README.txt'),
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
    author='Davis King',
    author_email='davis@dlib.net',
    url='https://github.com/davisking/dlib',
    license='Boost Software License',
    packages=['dlib', 'dlib.examples'],
    package_dir={'': 'dist'},
    include_package_data=True,
    cmdclass={
        'build': build,
        'build_ext': build_ext,
        'bdist_egg': bdist_egg,
        'develop': develop,
    },
    zip_safe=False,
    ext_modules=[Extension('dlib', [])],
    ext_package='dlib',
Ehsan Azarnasab's avatar
Ehsan Azarnasab committed
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Science/Research',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: Boost Software License (BSL)',
        'Operating System :: MacOS :: MacOS X',
        'Operating System :: POSIX',
        'Operating System :: POSIX :: Linux',
        'Operating System :: Microsoft',
        'Operating System :: Microsoft :: Windows',
        'Programming Language :: C++',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Topic :: Scientific/Engineering',
        'Topic :: Scientific/Engineering :: Image Recognition',
        'Topic :: Software Development',
    ],
418
)