setup.py 9.87 KB
Newer Older
liuzhe-lz's avatar
liuzhe-lz committed
1
2
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
3

4
5
6
7
8
9
10
11
"""
Script for installation and distribution.

You can use environment variable `NNI_RELEASE` to set release version.

If release version is not set, default to a development build whose version string will be `999.dev0`.


12
13
14
15
16
17
18
19
## Prepare Environment ##

Install development dependencies:

  $ pip install -U -r dependencies/setup.txt
  $ pip install -r dependencies/develop.txt


20
21
22
23
24
25
26
27
28
29
## Development ##

Build and install for development:

  $ python setup.py develop

Uninstall:

  $ pip uninstall nni

liuzhe-lz's avatar
liuzhe-lz committed
30
Remove generated files: (use "--all" to remove built wheel)
31
32
33

  $ python setup.py clean [--all]

34
Compile TypeScript modules without re-install:
35
36
37
38
39
40
41
42
43
44
45

  $ python setup.py build_ts


## Release ##

Build wheel package:

  $ NNI_RELEASE=2.0 python setup.py build_ts
  $ NNI_RELEASE=2.0 python setup.py bdist_wheel -p manylinux1_x86_64

46
47
48
49
for jupyterlab 2.x package:
  $ JUPYTER_LAB_VERSION=2.3.1 NNI_RELEASE=2.0 python setup.py build_ts
  $ JUPYTER_LAB_VERSION=2.3.1 NNI_RELEASE=2.0 python setup.py bdist_wheel -p manylinux1_x86_64

50
51
52
53
54
55
56
57
58
59
60
Where "2.0" is version string and "manylinux1_x86_64" is platform.
The platform may also be "macosx_10_9_x86_64" or "win_amd64".

`build_ts` must be manually invoked before `bdist_wheel`,
or setuptools cannot locate JS files which should be packed into wheel.
"""

from distutils.cmd import Command
from distutils.command.build import build
from distutils.command.clean import clean
import glob
61
import os
62
import shutil
liuzhe-lz's avatar
liuzhe-lz committed
63
import sys
64
65
66
67
68

import setuptools
from setuptools.command.develop import develop

import setup_ts
qianyj's avatar
qianyj committed
69
from nni.common import get_dcu_version
70

71
72
release = os.environ.get('NNI_RELEASE')

qianyj's avatar
qianyj committed
73
74
75
76
77
if (release):
    release_nni = release + get_dcu_version.nni_whl_name()
else:
    release_nni = release

78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
def _get_jupyter_lab_version():
    try:
        import jupyterlab
        return jupyterlab.__version__
    except ImportError:
        return '3.x'

jupyter_lab_major_version = _get_jupyter_lab_version().split('.')[0]

def check_jupyter_lab_version():
    environ_version = os.environ.get('JUPYTER_LAB_VERSION')

    jupyter_lab_version = _get_jupyter_lab_version()

    if environ_version:
        if jupyter_lab_version.split('.')[0] != environ_version.split('.')[0]:
            sys.exit(f'ERROR: To build a jupyter lab extension, run "JUPYTER_LAB_VERSION={jupyter_lab_version}", current: {environ_version} ')
    elif jupyter_lab_version.split('.')[0] != '3':
        sys.exit(f'ERROR: To build a jupyter lab extension, run "JUPYTER_LAB_VERSION={jupyter_lab_version}" first for nondefault version(3.x)')

98
99
100
def _setup():
    setuptools.setup(
        name = 'nni',
qianyj's avatar
qianyj committed
101
        version = release_nni or '999.dev0',
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
        description = 'Neural Network Intelligence project',
        long_description = open('README.md', encoding='utf-8').read(),
        long_description_content_type = 'text/markdown',
        url = 'https://github.com/Microsoft/nni',
        author = 'Microsoft NNI Team',
        author_email = 'nni@microsoft.com',
        license = 'MIT',
        classifiers = [
            'License :: OSI Approved :: MIT License',
            'Operating System :: MacOS :: MacOS X',
            'Operating System :: Microsoft :: Windows :: Windows 10',
            'Operating System :: POSIX :: Linux',
            'Programming Language :: Python :: 3 :: Only',
            'Topic :: Scientific/Engineering :: Artificial Intelligence',
        ],

        packages = _find_python_packages(),
        package_data = {
120
            'nni': _find_requirements_txt() + _find_default_config(),  # setuptools issue #1806
liuzhe-lz's avatar
liuzhe-lz committed
121
            'nni_assets': _find_asset_files(),
122
123
124
            'nni_node': _find_node_files()  # note: this does not work before building
        },

125
126
        data_files = _get_data_files(),

127
        python_requires = '>=3.7',
128
        install_requires = _read_requirements_txt('dependencies/required.txt'),
129
        extras_require = {
liuzhe-lz's avatar
liuzhe-lz committed
130
            'Anneal': _read_requirements_txt('dependencies/required_extra.txt', 'Anneal'),
131
132
            'SMAC': _read_requirements_txt('dependencies/required_extra.txt', 'SMAC'),
            'BOHB': _read_requirements_txt('dependencies/required_extra.txt', 'BOHB'),
98may's avatar
98may committed
133
134
            'PPOTuner': _read_requirements_txt('dependencies/required_extra.txt', 'PPOTuner'),
            'DNGO': _read_requirements_txt('dependencies/required_extra.txt', 'DNGO'),
liuzhe-lz's avatar
liuzhe-lz committed
135
            'all': _read_requirements_txt('dependencies/required_extra.txt'),
136
        },
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
        setup_requires = ['requests'],

        entry_points = {
            'console_scripts' : [
                'nnictl = nni.tools.nnictl.nnictl:parse_args'
            ]
        },

        cmdclass = {
            'build': Build,
            'build_ts': BuildTs,
            'clean': Clean,
            'develop': Develop,
        }
    )
152

153
154
155
156
157
158
def _get_data_files():
    data_files = []
    if jupyter_lab_major_version == '2':
        extension_file = glob.glob("nni_node/jupyter-extension/extensions/nni-jupyter-extension*.tgz")
        data_files = [('share/jupyter/lab/extensions', extension_file)]
    return data_files
159
160
161
162

def _find_python_packages():
    packages = []
    for dirpath, dirnames, filenames in os.walk('nni'):
163
        if '/__pycache__' not in dirpath and '/.mypy_cache' not in dirpath and '/default_config' not in dirpath:
164
            packages.append(dirpath.replace('/', '.'))
liuzhe-lz's avatar
liuzhe-lz committed
165
    return sorted(packages) + ['nni_assets', 'nni_node']
166

liuzhe-lz's avatar
liuzhe-lz committed
167
168
169
170
171
172
173
def _find_requirements_txt():
    requirement_files = []
    for dirpath, dirnames, filenames in os.walk('nni'):
        if 'requirements.txt' in filenames:
            requirement_files.append(os.path.join(dirpath[len('nni/'):], 'requirements.txt'))
    return requirement_files

174
175
176
def _find_default_config():
    return ['runtime/default_config/' + name for name in os.listdir('nni/runtime/default_config')]

liuzhe-lz's avatar
liuzhe-lz committed
177
178
179
180
181
182
183
184
def _find_asset_files():
    files = []
    for dirpath, dirnames, filenames in os.walk('nni_assets'):
        for filename in filenames:
            if os.path.splitext(filename)[1] == '.py':
                files.append(os.path.join(dirpath[len('nni_assets/'):], filename))
    return sorted(files)

185
def _find_node_files():
186
    if not os.path.exists('nni_node'):
187
        if release and 'build_ts' not in sys.argv and 'clean' not in sys.argv:
liuzhe-lz's avatar
liuzhe-lz committed
188
            sys.exit('ERROR: To build a release version, run "python setup.py build_ts" first')
189
        return []
190
191
192
    files = []
    for dirpath, dirnames, filenames in os.walk('nni_node'):
        for filename in filenames:
liuzhe-lz's avatar
liuzhe-lz committed
193
            files.append(os.path.join(dirpath[len('nni_node/'):], filename))
194
195
    if '__init__.py' in files:
        files.remove('__init__.py')
196
    return sorted(files)
197

198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
def _read_requirements_txt(file_path, section=None):
    with open(file_path) as f:
        lines = [line.strip() for line in f.readlines() if line.strip()]  # remove whitespaces and empty lines
    if section is None:
        return [line for line in lines if not line.startswith('#')]
    selected_lines = []
    started = False
    for line in lines:
        if started:
            if line.startswith('#'):
                return selected_lines
            else:
                selected_lines.append(line)
        elif line.startswith('# ' + section):
            started = True
    return selected_lines

liuzhe-lz's avatar
liuzhe-lz committed
215
216
217
def _using_conda_or_virtual_environment():
    return sys.prefix != sys.base_prefix or os.path.isdir(os.path.join(sys.prefix, 'conda-meta'))

218
219
220
221
222
223
224
225
226
227
228
229
class BuildTs(Command):
    description = 'build TypeScript modules'

    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
230
        check_jupyter_lab_version()
231
232
233
234
        setup_ts.build(release)

class Build(build):
    def run(self):
liuzhe-lz's avatar
liuzhe-lz committed
235
236
        if not release:
            sys.exit('Please set environment variable "NNI_RELEASE=<release_version>"')
237
238
239

        check_jupyter_lab_version()

liuzhe-lz's avatar
liuzhe-lz committed
240
        if os.path.islink('nni_node/main.js'):
liuzhe-lz's avatar
liuzhe-lz committed
241
            sys.exit('A development build already exists. Please uninstall NNI and run "python3 setup.py clean".')
qianyj's avatar
qianyj committed
242
243
244
245
246
        dcu_version = get_dcu_version.dcu_version()
        version_path = "nni/version.py"
        with open(version_path, "w") as f:
            f.write(f"__version__ = '{release}'\n")
            f.write(f"__dcu_version__ = '{dcu_version}'")
247
248
249
        super().run()

class Develop(develop):
liuzhe-lz's avatar
liuzhe-lz committed
250
    user_options = develop.user_options + [
liuzhe-lz's avatar
liuzhe-lz committed
251
252
        ('no-user', None, 'Prevent automatically adding "--user"'),
        ('skip-ts', None, 'Prevent building TypeScript modules')
liuzhe-lz's avatar
liuzhe-lz committed
253
254
    ]

liuzhe-lz's avatar
liuzhe-lz committed
255
    boolean_options = develop.boolean_options + ['no-user', 'skip-ts']
liuzhe-lz's avatar
liuzhe-lz committed
256
257
258
259

    def initialize_options(self):
        super().initialize_options()
        self.no_user = None
liuzhe-lz's avatar
liuzhe-lz committed
260
        self.skip_ts = None
liuzhe-lz's avatar
liuzhe-lz committed
261

262
    def finalize_options(self):
liuzhe-lz's avatar
liuzhe-lz committed
263
264
265
266
        # if `--user` or `--no-user` is explicitly set, do nothing
        # otherwise activate `--user` if using system python
        if not self.user and not self.no_user:
            self.user = not _using_conda_or_virtual_environment()
267
268
269
        super().finalize_options()

    def run(self):
liuzhe-lz's avatar
liuzhe-lz committed
270
        open('nni/version.py', 'w').write("__version__ = '999.dev0'")
liuzhe-lz's avatar
liuzhe-lz committed
271
272
        if not self.skip_ts:
            setup_ts.build(release=None)
273
274
275
276
277
278
279
280
281
282
        super().run()

class Clean(clean):
    def finalize_options(self):
        self._all = self.all
        self.all = True  # always use `clean --all`
        super().finalize_options()

    def run(self):
        super().run()
liuzhe-lz's avatar
liuzhe-lz committed
283
        setup_ts.clean()
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
        _clean_temp_files()
        shutil.rmtree('nni.egg-info', ignore_errors=True)
        if self._all:
            shutil.rmtree('dist', ignore_errors=True)


def _clean_temp_files():
    for pattern in _temp_files:
        for path in glob.glob(pattern):
            if os.path.islink(path) or os.path.isfile(path):
                os.remove(path)
            else:
                shutil.rmtree(path)

_temp_files = [
    # unit test
    'test/model_path/',
    'test/temp.json',
302
    'test/ut/sdk/*.pth',
liuzhe-lz's avatar
liuzhe-lz committed
303
304
305
306
    'test/ut/tools/annotation/_generated/',

    # example
    'nni_assets/**/data/',
307
308
309
]


liuzhe-lz's avatar
liuzhe-lz committed
310
311
if __name__ == '__main__':
    _setup()