setup.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. #!/usr/bin/env python
  2. # Copyright (c) 2017-present, Facebook, Inc.
  3. # All rights reserved.
  4. #
  5. # This source code is licensed under the MIT license found in the
  6. # LICENSE file in the root directory of this source tree.
  7. #
  8. from __future__ import absolute_import
  9. from __future__ import division
  10. from __future__ import print_function
  11. from __future__ import unicode_literals
  12. from setuptools import setup, Extension
  13. from setuptools.command.build_ext import build_ext
  14. import sys
  15. import setuptools
  16. import os
  17. import subprocess
  18. import platform
  19. __version__ = '0.9'
  20. FASTTEXT_SRC = "src"
  21. # Based on https://github.com/pybind/python_example
  22. class get_pybind_include(object):
  23. """Helper class to determine the pybind11 include path
  24. The purpose of this class is to postpone importing pybind11
  25. until it is actually installed, so that the ``get_include()``
  26. method can be invoked. """
  27. def __init__(self, user=False):
  28. try:
  29. import pybind11
  30. except ImportError:
  31. if subprocess.call([sys.executable, '-m', 'pip', 'install', 'pybind11']):
  32. raise RuntimeError('pybind11 install failed.')
  33. self.user = user
  34. def __str__(self):
  35. import pybind11
  36. return pybind11.get_include(self.user)
  37. try:
  38. coverage_index = sys.argv.index('--coverage')
  39. except ValueError:
  40. coverage = False
  41. else:
  42. del sys.argv[coverage_index]
  43. coverage = True
  44. fasttext_src_files = map(str, os.listdir(FASTTEXT_SRC))
  45. fasttext_src_cc = list(filter(lambda x: x.endswith('.cc'), fasttext_src_files))
  46. fasttext_src_cc = list(
  47. map(lambda x: str(os.path.join(FASTTEXT_SRC, x)), fasttext_src_cc)
  48. )
  49. ext_modules = [
  50. Extension(
  51. str('fasttext_pybind'),
  52. [
  53. str('python/fasttext_module/fasttext/pybind/fasttext_pybind.cc'),
  54. ] + fasttext_src_cc,
  55. include_dirs=[
  56. # Path to pybind11 headers
  57. get_pybind_include(),
  58. get_pybind_include(user=True),
  59. # Path to fasttext source code
  60. FASTTEXT_SRC,
  61. ],
  62. language='c++',
  63. extra_compile_args=["-O0 -fno-inline -fprofile-arcs -pthread -march=native" if coverage else
  64. "-O3 -funroll-loops -pthread -march=native"],
  65. ),
  66. ]
  67. # As of Python 3.6, CCompiler has a `has_flag` method.
  68. # cf http://bugs.python.org/issue26689
  69. def has_flag(compiler, flags):
  70. """Return a boolean indicating whether a flag name is supported on
  71. the specified compiler.
  72. """
  73. import tempfile
  74. with tempfile.NamedTemporaryFile('w', suffix='.cpp') as f:
  75. f.write('int main (int argc, char **argv) { return 0; }')
  76. try:
  77. compiler.compile([f.name], extra_postargs=flags)
  78. except setuptools.distutils.errors.CompileError:
  79. return False
  80. return True
  81. def cpp_flag(compiler):
  82. """Return the -std=c++[0x/11/14] compiler flag.
  83. The c++14 is preferred over c++0x/11 (when it is available).
  84. """
  85. standards = ['-std=c++14', '-std=c++11', '-std=c++0x']
  86. for standard in standards:
  87. if has_flag(compiler, [standard]):
  88. return standard
  89. raise RuntimeError(
  90. 'Unsupported compiler -- at least C++0x support '
  91. 'is needed!'
  92. )
  93. class BuildExt(build_ext):
  94. """A custom build extension for adding compiler-specific options."""
  95. c_opts = {
  96. 'msvc': ['/EHsc'],
  97. 'unix': [],
  98. }
  99. def build_extensions(self):
  100. if sys.platform == 'darwin':
  101. mac_osx_version = float('.'.join(platform.mac_ver()[0].split('.')[:2]))
  102. os.environ['MACOSX_DEPLOYMENT_TARGET'] = str(mac_osx_version)
  103. all_flags = ['-stdlib=libc++', '-mmacosx-version-min=10.7']
  104. if has_flag(self.compiler, [all_flags[0]]):
  105. self.c_opts['unix'] += [all_flags[0]]
  106. elif has_flag(self.compiler, all_flags):
  107. self.c_opts['unix'] += all_flags
  108. else:
  109. raise RuntimeError(
  110. 'libc++ is needed! Failed to compile with {} and {}.'.
  111. format(" ".join(all_flags), all_flags[0])
  112. )
  113. ct = self.compiler.compiler_type
  114. opts = self.c_opts.get(ct, [])
  115. extra_link_args = []
  116. if coverage:
  117. coverage_option = '--coverage'
  118. opts.append(coverage_option)
  119. extra_link_args.append(coverage_option)
  120. if ct == 'unix':
  121. opts.append('-DVERSION_INFO="%s"' % self.distribution.get_version())
  122. opts.append(cpp_flag(self.compiler))
  123. if has_flag(self.compiler, ['-fvisibility=hidden']):
  124. opts.append('-fvisibility=hidden')
  125. elif ct == 'msvc':
  126. opts.append(
  127. '/DVERSION_INFO=\\"%s\\"' % self.distribution.get_version()
  128. )
  129. for ext in self.extensions:
  130. ext.extra_compile_args = opts
  131. ext.extra_link_args = extra_link_args
  132. build_ext.build_extensions(self)
  133. def _get_readme():
  134. """
  135. Use pandoc to generate rst from md.
  136. pandoc --from=markdown --to=rst --output=python/README.rst python/README.md
  137. """
  138. with open("python/README.rst") as fid:
  139. return fid.read()
  140. setup(
  141. name='fasttext',
  142. version=__version__,
  143. author='Onur Celebi',
  144. author_email='[email protected]',
  145. description='fasttext Python bindings',
  146. long_description=_get_readme(),
  147. ext_modules=ext_modules,
  148. url='https://github.com/facebookresearch/fastText',
  149. license='MIT',
  150. classifiers=[
  151. 'Development Status :: 3 - Alpha',
  152. 'Intended Audience :: Developers',
  153. 'Intended Audience :: Science/Research',
  154. 'License :: OSI Approved :: MIT License',
  155. 'Programming Language :: Python :: 2.7',
  156. 'Programming Language :: Python :: 3.4',
  157. 'Programming Language :: Python :: 3.5',
  158. 'Programming Language :: Python :: 3.6',
  159. 'Topic :: Software Development',
  160. 'Topic :: Scientific/Engineering',
  161. 'Operating System :: Microsoft :: Windows',
  162. 'Operating System :: POSIX',
  163. 'Operating System :: Unix',
  164. 'Operating System :: MacOS',
  165. ],
  166. install_requires=['pybind11>=2.2', "setuptools >= 0.7.0", "numpy"],
  167. cmdclass={'build_ext': BuildExt},
  168. packages=[
  169. str('fasttext'),
  170. str('fasttext.util'),
  171. str('fasttext.tests'),
  172. ],
  173. package_dir={str(''): str('python/fasttext_module')},
  174. zip_safe=False,
  175. )