You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

637 lines
20 KiB

4 years ago
  1. # coding: utf8
  2. from __future__ import unicode_literals, print_function
  3. import os
  4. import ujson
  5. import pkg_resources
  6. import importlib
  7. import regex as re
  8. from pathlib import Path
  9. import sys
  10. import textwrap
  11. import random
  12. from collections import OrderedDict
  13. from thinc.neural._classes.model import Model
  14. import functools
  15. import cytoolz
  16. import itertools
  17. import numpy.random
  18. from .symbols import ORTH
  19. from .compat import cupy, CudaStream, path2str, basestring_, input_, unicode_
  20. from .compat import import_file
  21. from .errors import Errors
  22. # Import these directly from Thinc, so that we're sure we always have the
  23. # same version.
  24. from thinc.neural._classes.model import msgpack
  25. from thinc.neural._classes.model import msgpack_numpy
  26. LANGUAGES = {}
  27. _data_path = Path(__file__).parent / 'data'
  28. _PRINT_ENV = False
  29. def set_env_log(value):
  30. global _PRINT_ENV
  31. _PRINT_ENV = value
  32. def get_lang_class(lang):
  33. """Import and load a Language class.
  34. lang (unicode): Two-letter language code, e.g. 'en'.
  35. RETURNS (Language): Language class.
  36. """
  37. global LANGUAGES
  38. if lang not in LANGUAGES:
  39. try:
  40. module = importlib.import_module('.lang.%s' % lang, 'spacy')
  41. except ImportError:
  42. raise ImportError(Errors.E048.format(lang=lang))
  43. LANGUAGES[lang] = getattr(module, module.__all__[0])
  44. return LANGUAGES[lang]
  45. def set_lang_class(name, cls):
  46. """Set a custom Language class name that can be loaded via get_lang_class.
  47. name (unicode): Name of Language class.
  48. cls (Language): Language class.
  49. """
  50. global LANGUAGES
  51. LANGUAGES[name] = cls
  52. def get_data_path(require_exists=True):
  53. """Get path to spaCy data directory.
  54. require_exists (bool): Only return path if it exists, otherwise None.
  55. RETURNS (Path or None): Data path or None.
  56. """
  57. if not require_exists:
  58. return _data_path
  59. else:
  60. return _data_path if _data_path.exists() else None
  61. def set_data_path(path):
  62. """Set path to spaCy data directory.
  63. path (unicode or Path): Path to new data directory.
  64. """
  65. global _data_path
  66. _data_path = ensure_path(path)
  67. def ensure_path(path):
  68. """Ensure string is converted to a Path.
  69. path: Anything. If string, it's converted to Path.
  70. RETURNS: Path or original argument.
  71. """
  72. if isinstance(path, basestring_):
  73. return Path(path)
  74. else:
  75. return path
  76. def load_model(name, **overrides):
  77. """Load a model from a shortcut link, package or data path.
  78. name (unicode): Package name, shortcut link or model path.
  79. **overrides: Specific overrides, like pipeline components to disable.
  80. RETURNS (Language): `Language` class with the loaded model.
  81. """
  82. data_path = get_data_path()
  83. if not data_path or not data_path.exists():
  84. raise IOError(Errors.E049.format(path=path2str(data_path)))
  85. if isinstance(name, basestring_): # in data dir / shortcut
  86. if name in set([d.name for d in data_path.iterdir()]):
  87. return load_model_from_link(name, **overrides)
  88. if is_package(name): # installed as package
  89. return load_model_from_package(name, **overrides)
  90. if Path(name).exists(): # path to model data directory
  91. return load_model_from_path(Path(name), **overrides)
  92. elif hasattr(name, 'exists'): # Path or Path-like to model data
  93. return load_model_from_path(name, **overrides)
  94. raise IOError(Errors.E050.format(name=name))
  95. def load_model_from_link(name, **overrides):
  96. """Load a model from a shortcut link, or directory in spaCy data path."""
  97. path = get_data_path() / name / '__init__.py'
  98. try:
  99. cls = import_file(name, path)
  100. except AttributeError:
  101. raise IOError(Errors.E051.format(name=name))
  102. return cls.load(**overrides)
  103. def load_model_from_package(name, **overrides):
  104. """Load a model from an installed package."""
  105. cls = importlib.import_module(name)
  106. return cls.load(**overrides)
  107. def load_model_from_path(model_path, meta=False, **overrides):
  108. """Load a model from a data directory path. Creates Language class with
  109. pipeline from meta.json and then calls from_disk() with path."""
  110. if not meta:
  111. meta = get_model_meta(model_path)
  112. cls = get_lang_class(meta['lang'])
  113. nlp = cls(meta=meta, **overrides)
  114. pipeline = meta.get('pipeline', [])
  115. disable = overrides.get('disable', [])
  116. if pipeline is True:
  117. pipeline = nlp.Defaults.pipe_names
  118. elif pipeline in (False, None):
  119. pipeline = []
  120. for name in pipeline:
  121. if name not in disable:
  122. config = meta.get('pipeline_args', {}).get(name, {})
  123. component = nlp.create_pipe(name, config=config)
  124. nlp.add_pipe(component, name=name)
  125. return nlp.from_disk(model_path)
  126. def load_model_from_init_py(init_file, **overrides):
  127. """Helper function to use in the `load()` method of a model package's
  128. __init__.py.
  129. init_file (unicode): Path to model's __init__.py, i.e. `__file__`.
  130. **overrides: Specific overrides, like pipeline components to disable.
  131. RETURNS (Language): `Language` class with loaded model.
  132. """
  133. model_path = Path(init_file).parent
  134. meta = get_model_meta(model_path)
  135. data_dir = '%s_%s-%s' % (meta['lang'], meta['name'], meta['version'])
  136. data_path = model_path / data_dir
  137. if not model_path.exists():
  138. raise IOError(Errors.E052.format(path=path2str(data_path)))
  139. return load_model_from_path(data_path, meta, **overrides)
  140. def get_model_meta(path):
  141. """Get model meta.json from a directory path and validate its contents.
  142. path (unicode or Path): Path to model directory.
  143. RETURNS (dict): The model's meta data.
  144. """
  145. model_path = ensure_path(path)
  146. if not model_path.exists():
  147. raise IOError(Errors.E052.format(path=path2str(model_path)))
  148. meta_path = model_path / 'meta.json'
  149. if not meta_path.is_file():
  150. raise IOError(Errors.E053.format(path=meta_path))
  151. meta = read_json(meta_path)
  152. for setting in ['lang', 'name', 'version']:
  153. if setting not in meta or not meta[setting]:
  154. raise ValueError(Errors.E054.format(setting=setting))
  155. return meta
  156. def is_package(name):
  157. """Check if string maps to a package installed via pip.
  158. name (unicode): Name of package.
  159. RETURNS (bool): True if installed package, False if not.
  160. """
  161. name = name.lower() # compare package name against lowercase name
  162. packages = pkg_resources.working_set.by_key.keys()
  163. for package in packages:
  164. if package.lower().replace('-', '_') == name:
  165. return True
  166. return False
  167. def get_package_path(name):
  168. """Get the path to an installed package.
  169. name (unicode): Package name.
  170. RETURNS (Path): Path to installed package.
  171. """
  172. name = name.lower() # use lowercase version to be safe
  173. # Here we're importing the module just to find it. This is worryingly
  174. # indirect, but it's otherwise very difficult to find the package.
  175. pkg = importlib.import_module(name)
  176. return Path(pkg.__file__).parent
  177. def is_in_jupyter():
  178. """Check if user is running spaCy from a Jupyter notebook by detecting the
  179. IPython kernel. Mainly used for the displaCy visualizer.
  180. RETURNS (bool): True if in Jupyter, False if not.
  181. """
  182. try:
  183. cfg = get_ipython().config
  184. if cfg['IPKernelApp']['parent_appname'] == 'ipython-notebook':
  185. return True
  186. except NameError:
  187. return False
  188. return False
  189. def get_cuda_stream(require=False):
  190. return CudaStream() if CudaStream is not None else None
  191. def get_async(stream, numpy_array):
  192. if cupy is None:
  193. return numpy_array
  194. else:
  195. array = cupy.ndarray(numpy_array.shape, order='C',
  196. dtype=numpy_array.dtype)
  197. array.set(numpy_array, stream=stream)
  198. return array
  199. def env_opt(name, default=None):
  200. if type(default) is float:
  201. type_convert = float
  202. else:
  203. type_convert = int
  204. if 'SPACY_' + name.upper() in os.environ:
  205. value = type_convert(os.environ['SPACY_' + name.upper()])
  206. if _PRINT_ENV:
  207. print(name, "=", repr(value), "via", "$SPACY_" + name.upper())
  208. return value
  209. elif name in os.environ:
  210. value = type_convert(os.environ[name])
  211. if _PRINT_ENV:
  212. print(name, "=", repr(value), "via", '$' + name)
  213. return value
  214. else:
  215. if _PRINT_ENV:
  216. print(name, '=', repr(default), "by default")
  217. return default
  218. def read_regex(path):
  219. path = ensure_path(path)
  220. with path.open() as file_:
  221. entries = file_.read().split('\n')
  222. expression = '|'.join(['^' + re.escape(piece)
  223. for piece in entries if piece.strip()])
  224. return re.compile(expression)
  225. def compile_prefix_regex(entries):
  226. if '(' in entries:
  227. # Handle deprecated data
  228. expression = '|'.join(['^' + re.escape(piece)
  229. for piece in entries if piece.strip()])
  230. return re.compile(expression)
  231. else:
  232. expression = '|'.join(['^' + piece
  233. for piece in entries if piece.strip()])
  234. return re.compile(expression)
  235. def compile_suffix_regex(entries):
  236. expression = '|'.join([piece + '$' for piece in entries if piece.strip()])
  237. return re.compile(expression)
  238. def compile_infix_regex(entries):
  239. expression = '|'.join([piece for piece in entries if piece.strip()])
  240. return re.compile(expression)
  241. def add_lookups(default_func, *lookups):
  242. """Extend an attribute function with special cases. If a word is in the
  243. lookups, the value is returned. Otherwise the previous function is used.
  244. default_func (callable): The default function to execute.
  245. *lookups (dict): Lookup dictionary mapping string to attribute value.
  246. RETURNS (callable): Lexical attribute getter.
  247. """
  248. # This is implemented as functools.partial instead of a closure, to allow
  249. # pickle to work.
  250. return functools.partial(_get_attr_unless_lookup, default_func, lookups)
  251. def _get_attr_unless_lookup(default_func, lookups, string):
  252. for lookup in lookups:
  253. if string in lookup:
  254. return lookup[string]
  255. return default_func(string)
  256. def update_exc(base_exceptions, *addition_dicts):
  257. """Update and validate tokenizer exceptions. Will overwrite exceptions.
  258. base_exceptions (dict): Base exceptions.
  259. *addition_dicts (dict): Exceptions to add to the base dict, in order.
  260. RETURNS (dict): Combined tokenizer exceptions.
  261. """
  262. exc = dict(base_exceptions)
  263. for additions in addition_dicts:
  264. for orth, token_attrs in additions.items():
  265. if not all(isinstance(attr[ORTH], unicode_)
  266. for attr in token_attrs):
  267. raise ValueError(Errors.E055.format(key=orth, orths=token_attrs))
  268. described_orth = ''.join(attr[ORTH] for attr in token_attrs)
  269. if orth != described_orth:
  270. raise ValueError(Errors.E056.format(key=orth, orths=described_orth))
  271. exc.update(additions)
  272. exc = expand_exc(exc, "'", "")
  273. return exc
  274. def expand_exc(excs, search, replace):
  275. """Find string in tokenizer exceptions, duplicate entry and replace string.
  276. For example, to add additional versions with typographic apostrophes.
  277. excs (dict): Tokenizer exceptions.
  278. search (unicode): String to find and replace.
  279. replace (unicode): Replacement.
  280. RETURNS (dict): Combined tokenizer exceptions.
  281. """
  282. def _fix_token(token, search, replace):
  283. fixed = dict(token)
  284. fixed[ORTH] = fixed[ORTH].replace(search, replace)
  285. return fixed
  286. new_excs = dict(excs)
  287. for token_string, tokens in excs.items():
  288. if search in token_string:
  289. new_key = token_string.replace(search, replace)
  290. new_value = [_fix_token(t, search, replace) for t in tokens]
  291. new_excs[new_key] = new_value
  292. return new_excs
  293. def normalize_slice(length, start, stop, step=None):
  294. if not (step is None or step == 1):
  295. raise ValueError(Errors.E057)
  296. if start is None:
  297. start = 0
  298. elif start < 0:
  299. start += length
  300. start = min(length, max(0, start))
  301. if stop is None:
  302. stop = length
  303. elif stop < 0:
  304. stop += length
  305. stop = min(length, max(start, stop))
  306. return start, stop
  307. def minibatch(items, size=8):
  308. """Iterate over batches of items. `size` may be an iterator,
  309. so that batch-size can vary on each step.
  310. """
  311. if isinstance(size, int):
  312. size_ = itertools.repeat(size)
  313. else:
  314. size_ = size
  315. items = iter(items)
  316. while True:
  317. batch_size = next(size_)
  318. batch = list(cytoolz.take(int(batch_size), items))
  319. if len(batch) == 0:
  320. break
  321. yield list(batch)
  322. def compounding(start, stop, compound):
  323. """Yield an infinite series of compounding values. Each time the
  324. generator is called, a value is produced by multiplying the previous
  325. value by the compound rate.
  326. EXAMPLE:
  327. >>> sizes = compounding(1., 10., 1.5)
  328. >>> assert next(sizes) == 1.
  329. >>> assert next(sizes) == 1 * 1.5
  330. >>> assert next(sizes) == 1.5 * 1.5
  331. """
  332. def clip(value):
  333. return max(value, stop) if (start > stop) else min(value, stop)
  334. curr = float(start)
  335. while True:
  336. yield clip(curr)
  337. curr *= compound
  338. def decaying(start, stop, decay):
  339. """Yield an infinite series of linearly decaying values."""
  340. def clip(value):
  341. return max(value, stop) if (start > stop) else min(value, stop)
  342. nr_upd = 1.
  343. while True:
  344. yield clip(start * 1./(1. + decay * nr_upd))
  345. nr_upd += 1
  346. def itershuffle(iterable, bufsize=1000):
  347. """Shuffle an iterator. This works by holding `bufsize` items back
  348. and yielding them sometime later. Obviously, this is not unbiased
  349. but should be good enough for batching. Larger bufsize means less bias.
  350. From https://gist.github.com/andres-erbsen/1307752
  351. iterable (iterable): Iterator to shuffle.
  352. bufsize (int): Items to hold back.
  353. YIELDS (iterable): The shuffled iterator.
  354. """
  355. iterable = iter(iterable)
  356. buf = []
  357. try:
  358. while True:
  359. for i in range(random.randint(1, bufsize-len(buf))):
  360. buf.append(iterable.next())
  361. random.shuffle(buf)
  362. for i in range(random.randint(1, bufsize)):
  363. if buf:
  364. yield buf.pop()
  365. else:
  366. break
  367. except StopIteration:
  368. random.shuffle(buf)
  369. while buf:
  370. yield buf.pop()
  371. raise StopIteration
  372. def read_json(location):
  373. """Open and load JSON from file.
  374. location (Path): Path to JSON file.
  375. RETURNS (dict): Loaded JSON content.
  376. """
  377. location = ensure_path(location)
  378. with location.open('r', encoding='utf8') as f:
  379. return ujson.load(f)
  380. def get_raw_input(description, default=False):
  381. """Get user input from the command line via raw_input / input.
  382. description (unicode): Text to display before prompt.
  383. default (unicode or False/None): Default value to display with prompt.
  384. RETURNS (unicode): User input.
  385. """
  386. additional = ' (default: %s)' % default if default else ''
  387. prompt = ' %s%s: ' % (description, additional)
  388. user_input = input_(prompt)
  389. return user_input
  390. def to_bytes(getters, exclude):
  391. serialized = OrderedDict()
  392. for key, getter in getters.items():
  393. if key not in exclude:
  394. serialized[key] = getter()
  395. return msgpack.dumps(serialized, use_bin_type=True, encoding='utf8')
  396. def from_bytes(bytes_data, setters, exclude):
  397. msg = msgpack.loads(bytes_data, raw=False)
  398. for key, setter in setters.items():
  399. if key not in exclude and key in msg:
  400. setter(msg[key])
  401. return msg
  402. def to_disk(path, writers, exclude):
  403. path = ensure_path(path)
  404. if not path.exists():
  405. path.mkdir()
  406. for key, writer in writers.items():
  407. if key not in exclude:
  408. writer(path / key)
  409. return path
  410. def from_disk(path, readers, exclude):
  411. path = ensure_path(path)
  412. for key, reader in readers.items():
  413. if key not in exclude:
  414. reader(path / key)
  415. return path
  416. def print_table(data, title=None):
  417. """Print data in table format.
  418. data (dict or list of tuples): Label/value pairs.
  419. title (unicode or None): Title, will be printed above.
  420. """
  421. if isinstance(data, dict):
  422. data = list(data.items())
  423. tpl_row = ' {:<15}' * len(data[0])
  424. table = '\n'.join([tpl_row.format(l, unicode_(v)) for l, v in data])
  425. if title:
  426. print('\n \033[93m{}\033[0m'.format(title))
  427. print('\n{}\n'.format(table))
  428. def print_markdown(data, title=None):
  429. """Print data in GitHub-flavoured Markdown format for issues etc.
  430. data (dict or list of tuples): Label/value pairs.
  431. title (unicode or None): Title, will be rendered as headline 2.
  432. """
  433. def excl_value(value):
  434. # contains path, i.e. personal info
  435. return isinstance(value, basestring_) and Path(value).exists()
  436. if isinstance(data, dict):
  437. data = list(data.items())
  438. markdown = ["* **{}:** {}".format(l, unicode_(v))
  439. for l, v in data if not excl_value(v)]
  440. if title:
  441. print("\n## {}".format(title))
  442. print('\n{}\n'.format('\n'.join(markdown)))
  443. def prints(*texts, **kwargs):
  444. """Print formatted message (manual ANSI escape sequences to avoid
  445. dependency)
  446. *texts (unicode): Texts to print. Each argument is rendered as paragraph.
  447. **kwargs: 'title' becomes coloured headline. exits=True performs sys exit.
  448. """
  449. exits = kwargs.get('exits', None)
  450. title = kwargs.get('title', None)
  451. title = '\033[93m{}\033[0m\n'.format(_wrap(title)) if title else ''
  452. message = '\n\n'.join([_wrap(text) for text in texts])
  453. print('\n{}{}\n'.format(title, message))
  454. if exits is not None:
  455. sys.exit(exits)
  456. def _wrap(text, wrap_max=80, indent=4):
  457. """Wrap text at given width using textwrap module.
  458. text (unicode): Text to wrap. If it's a Path, it's converted to string.
  459. wrap_max (int): Maximum line length (indent is deducted).
  460. indent (int): Number of spaces for indentation.
  461. RETURNS (unicode): Wrapped text.
  462. """
  463. indent = indent * ' '
  464. wrap_width = wrap_max - len(indent)
  465. if isinstance(text, Path):
  466. text = path2str(text)
  467. return textwrap.fill(text, width=wrap_width, initial_indent=indent,
  468. subsequent_indent=indent, break_long_words=False,
  469. break_on_hyphens=False)
  470. def minify_html(html):
  471. """Perform a template-specific, rudimentary HTML minification for displaCy.
  472. Disclaimer: NOT a general-purpose solution, only removes indentation and
  473. newlines.
  474. html (unicode): Markup to minify.
  475. RETURNS (unicode): "Minified" HTML.
  476. """
  477. return html.strip().replace(' ', '').replace('\n', '')
  478. def escape_html(text):
  479. """Replace <, >, &, " with their HTML encoded representation. Intended to
  480. prevent HTML errors in rendered displaCy markup.
  481. text (unicode): The original text.
  482. RETURNS (unicode): Equivalent text to be safely used within HTML.
  483. """
  484. text = text.replace('&', '&amp;')
  485. text = text.replace('<', '&lt;')
  486. text = text.replace('>', '&gt;')
  487. text = text.replace('"', '&quot;')
  488. return text
  489. def use_gpu(gpu_id):
  490. try:
  491. import cupy.cuda.device
  492. except ImportError:
  493. return None
  494. from thinc.neural.ops import CupyOps
  495. device = cupy.cuda.device.Device(gpu_id)
  496. device.use()
  497. Model.ops = CupyOps()
  498. Model.Ops = CupyOps
  499. return device
  500. def fix_random_seed(seed=0):
  501. random.seed(seed)
  502. numpy.random.seed(seed)
  503. class SimpleFrozenDict(dict):
  504. """Simplified implementation of a frozen dict, mainly used as default
  505. function or method argument (for arguments that should default to empty
  506. dictionary). Will raise an error if user or spaCy attempts to add to dict.
  507. """
  508. def __setitem__(self, key, value):
  509. raise NotImplementedError(Errors.E095)
  510. def pop(self, key, default=None):
  511. raise NotImplementedError(Errors.E095)
  512. def update(self, other):
  513. raise NotImplementedError(Errors.E095)