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.

748 lines
30 KiB

4 years ago
  1. # coding: utf8
  2. from __future__ import absolute_import, unicode_literals
  3. import random
  4. import ujson
  5. import itertools
  6. import weakref
  7. import functools
  8. from collections import OrderedDict
  9. from contextlib import contextmanager
  10. from copy import copy
  11. from thinc.neural import Model
  12. from thinc.neural.optimizers import Adam
  13. from .tokenizer import Tokenizer
  14. from .vocab import Vocab
  15. from .lemmatizer import Lemmatizer
  16. from .pipeline import DependencyParser, Tensorizer, Tagger, EntityRecognizer
  17. from .pipeline import SimilarityHook, TextCategorizer, SentenceSegmenter
  18. from .pipeline import merge_noun_chunks, merge_entities
  19. from .compat import json_dumps, izip, basestring_
  20. from .gold import GoldParse
  21. from .scorer import Scorer
  22. from ._ml import link_vectors_to_models, create_default_optimizer
  23. from .attrs import IS_STOP
  24. from .lang.punctuation import TOKENIZER_PREFIXES, TOKENIZER_SUFFIXES
  25. from .lang.punctuation import TOKENIZER_INFIXES
  26. from .lang.tokenizer_exceptions import TOKEN_MATCH
  27. from .lang.tag_map import TAG_MAP
  28. from .lang.lex_attrs import LEX_ATTRS, is_stop
  29. from .errors import Errors
  30. from . import util
  31. from . import about
  32. class BaseDefaults(object):
  33. @classmethod
  34. def create_lemmatizer(cls, nlp=None):
  35. return Lemmatizer(cls.lemma_index, cls.lemma_exc, cls.lemma_rules,
  36. cls.lemma_lookup)
  37. @classmethod
  38. def create_vocab(cls, nlp=None):
  39. lemmatizer = cls.create_lemmatizer(nlp)
  40. lex_attr_getters = dict(cls.lex_attr_getters)
  41. # This is messy, but it's the minimal working fix to Issue #639.
  42. lex_attr_getters[IS_STOP] = functools.partial(is_stop,
  43. stops=cls.stop_words)
  44. vocab = Vocab(lex_attr_getters=lex_attr_getters, tag_map=cls.tag_map,
  45. lemmatizer=lemmatizer)
  46. for tag_str, exc in cls.morph_rules.items():
  47. for orth_str, attrs in exc.items():
  48. vocab.morphology.add_special_case(tag_str, orth_str, attrs)
  49. return vocab
  50. @classmethod
  51. def create_tokenizer(cls, nlp=None):
  52. rules = cls.tokenizer_exceptions
  53. token_match = cls.token_match
  54. prefix_search = (util.compile_prefix_regex(cls.prefixes).search
  55. if cls.prefixes else None)
  56. suffix_search = (util.compile_suffix_regex(cls.suffixes).search
  57. if cls.suffixes else None)
  58. infix_finditer = (util.compile_infix_regex(cls.infixes).finditer
  59. if cls.infixes else None)
  60. vocab = nlp.vocab if nlp is not None else cls.create_vocab(nlp)
  61. return Tokenizer(vocab, rules=rules,
  62. prefix_search=prefix_search,
  63. suffix_search=suffix_search,
  64. infix_finditer=infix_finditer,
  65. token_match=token_match)
  66. pipe_names = ['tagger', 'parser', 'ner']
  67. token_match = TOKEN_MATCH
  68. prefixes = tuple(TOKENIZER_PREFIXES)
  69. suffixes = tuple(TOKENIZER_SUFFIXES)
  70. infixes = tuple(TOKENIZER_INFIXES)
  71. tag_map = dict(TAG_MAP)
  72. tokenizer_exceptions = {}
  73. stop_words = set()
  74. lemma_rules = {}
  75. lemma_exc = {}
  76. lemma_index = {}
  77. lemma_lookup = {}
  78. morph_rules = {}
  79. lex_attr_getters = LEX_ATTRS
  80. syntax_iterators = {}
  81. class Language(object):
  82. """A text-processing pipeline. Usually you'll load this once per process,
  83. and pass the instance around your application.
  84. Defaults (class): Settings, data and factory methods for creating the `nlp`
  85. object and processing pipeline.
  86. lang (unicode): Two-letter language ID, i.e. ISO code.
  87. """
  88. Defaults = BaseDefaults
  89. lang = None
  90. factories = {
  91. 'tokenizer': lambda nlp: nlp.Defaults.create_tokenizer(nlp),
  92. 'tensorizer': lambda nlp, **cfg: Tensorizer(nlp.vocab, **cfg),
  93. 'tagger': lambda nlp, **cfg: Tagger(nlp.vocab, **cfg),
  94. 'parser': lambda nlp, **cfg: DependencyParser(nlp.vocab, **cfg),
  95. 'ner': lambda nlp, **cfg: EntityRecognizer(nlp.vocab, **cfg),
  96. 'similarity': lambda nlp, **cfg: SimilarityHook(nlp.vocab, **cfg),
  97. 'textcat': lambda nlp, **cfg: TextCategorizer(nlp.vocab, **cfg),
  98. 'sbd': lambda nlp, **cfg: SentenceSegmenter(nlp.vocab, **cfg),
  99. 'sentencizer': lambda nlp, **cfg: SentenceSegmenter(nlp.vocab, **cfg),
  100. 'merge_noun_chunks': lambda nlp, **cfg: merge_noun_chunks,
  101. 'merge_entities': lambda nlp, **cfg: merge_entities
  102. }
  103. def __init__(self, vocab=True, make_doc=True, max_length=10**6, meta={}, **kwargs):
  104. """Initialise a Language object.
  105. vocab (Vocab): A `Vocab` object. If `True`, a vocab is created via
  106. `Language.Defaults.create_vocab`.
  107. make_doc (callable): A function that takes text and returns a `Doc`
  108. object. Usually a `Tokenizer`.
  109. meta (dict): Custom meta data for the Language class. Is written to by
  110. models to add model meta data.
  111. max_length (int) :
  112. Maximum number of characters in a single text. The current v2 models
  113. may run out memory on extremely long texts, due to large internal
  114. allocations. You should segment these texts into meaningful units,
  115. e.g. paragraphs, subsections etc, before passing them to spaCy.
  116. Default maximum length is 1,000,000 characters (1mb). As a rule of
  117. thumb, if all pipeline components are enabled, spaCy's default
  118. models currently requires roughly 1GB of temporary memory per
  119. 100,000 characters in one text.
  120. RETURNS (Language): The newly constructed object.
  121. """
  122. self._meta = dict(meta)
  123. self._path = None
  124. if vocab is True:
  125. factory = self.Defaults.create_vocab
  126. vocab = factory(self, **meta.get('vocab', {}))
  127. if vocab.vectors.name is None:
  128. vocab.vectors.name = meta.get('vectors', {}).get('name')
  129. self.vocab = vocab
  130. if make_doc is True:
  131. factory = self.Defaults.create_tokenizer
  132. make_doc = factory(self, **meta.get('tokenizer', {}))
  133. self.tokenizer = make_doc
  134. self.pipeline = []
  135. self.max_length = max_length
  136. self._optimizer = None
  137. @property
  138. def path(self):
  139. return self._path
  140. @property
  141. def meta(self):
  142. self._meta.setdefault('lang', self.vocab.lang)
  143. self._meta.setdefault('name', 'model')
  144. self._meta.setdefault('version', '0.0.0')
  145. self._meta.setdefault('spacy_version', '>={}'.format(about.__version__))
  146. self._meta.setdefault('description', '')
  147. self._meta.setdefault('author', '')
  148. self._meta.setdefault('email', '')
  149. self._meta.setdefault('url', '')
  150. self._meta.setdefault('license', '')
  151. self._meta['vectors'] = {'width': self.vocab.vectors_length,
  152. 'vectors': len(self.vocab.vectors),
  153. 'keys': self.vocab.vectors.n_keys,
  154. 'name': self.vocab.vectors.name}
  155. self._meta['pipeline'] = self.pipe_names
  156. return self._meta
  157. @meta.setter
  158. def meta(self, value):
  159. self._meta = value
  160. # Conveniences to access pipeline components
  161. @property
  162. def tensorizer(self):
  163. return self.get_pipe('tensorizer')
  164. @property
  165. def tagger(self):
  166. return self.get_pipe('tagger')
  167. @property
  168. def parser(self):
  169. return self.get_pipe('parser')
  170. @property
  171. def entity(self):
  172. return self.get_pipe('ner')
  173. @property
  174. def matcher(self):
  175. return self.get_pipe('matcher')
  176. @property
  177. def pipe_names(self):
  178. """Get names of available pipeline components.
  179. RETURNS (list): List of component name strings, in order.
  180. """
  181. return [pipe_name for pipe_name, _ in self.pipeline]
  182. def get_pipe(self, name):
  183. """Get a pipeline component for a given component name.
  184. name (unicode): Name of pipeline component to get.
  185. RETURNS (callable): The pipeline component.
  186. """
  187. for pipe_name, component in self.pipeline:
  188. if pipe_name == name:
  189. return component
  190. raise KeyError(Errors.E001.format(name=name, opts=self.pipe_names))
  191. def create_pipe(self, name, config=dict()):
  192. """Create a pipeline component from a factory.
  193. name (unicode): Factory name to look up in `Language.factories`.
  194. config (dict): Configuration parameters to initialise component.
  195. RETURNS (callable): Pipeline component.
  196. """
  197. if name not in self.factories:
  198. raise KeyError(Errors.E002.format(name=name))
  199. factory = self.factories[name]
  200. return factory(self, **config)
  201. def add_pipe(self, component, name=None, before=None, after=None,
  202. first=None, last=None):
  203. """Add a component to the processing pipeline. Valid components are
  204. callables that take a `Doc` object, modify it and return it. Only one
  205. of before/after/first/last can be set. Default behaviour is "last".
  206. component (callable): The pipeline component.
  207. name (unicode): Name of pipeline component. Overwrites existing
  208. component.name attribute if available. If no name is set and
  209. the component exposes no name attribute, component.__name__ is
  210. used. An error is raised if a name already exists in the pipeline.
  211. before (unicode): Component name to insert component directly before.
  212. after (unicode): Component name to insert component directly after.
  213. first (bool): Insert component first / not first in the pipeline.
  214. last (bool): Insert component last / not last in the pipeline.
  215. EXAMPLE:
  216. >>> nlp.add_pipe(component, before='ner')
  217. >>> nlp.add_pipe(component, name='custom_name', last=True)
  218. """
  219. if not hasattr(component, '__call__'):
  220. msg = Errors.E003.format(component=repr(component), name=name)
  221. if isinstance(component, basestring_) and component in self.factories:
  222. msg += Errors.E004.format(component=component)
  223. raise ValueError(msg)
  224. if name is None:
  225. if hasattr(component, 'name'):
  226. name = component.name
  227. elif hasattr(component, '__name__'):
  228. name = component.__name__
  229. elif (hasattr(component, '__class__') and
  230. hasattr(component.__class__, '__name__')):
  231. name = component.__class__.__name__
  232. else:
  233. name = repr(component)
  234. if name in self.pipe_names:
  235. raise ValueError(Errors.E007.format(name=name, opts=self.pipe_names))
  236. if sum([bool(before), bool(after), bool(first), bool(last)]) >= 2:
  237. raise ValueError(Errors.E006)
  238. pipe = (name, component)
  239. if last or not any([first, before, after]):
  240. self.pipeline.append(pipe)
  241. elif first:
  242. self.pipeline.insert(0, pipe)
  243. elif before and before in self.pipe_names:
  244. self.pipeline.insert(self.pipe_names.index(before), pipe)
  245. elif after and after in self.pipe_names:
  246. self.pipeline.insert(self.pipe_names.index(after) + 1, pipe)
  247. else:
  248. raise ValueError(Errors.E001.format(name=before or after,
  249. opts=self.pipe_names))
  250. def has_pipe(self, name):
  251. """Check if a component name is present in the pipeline. Equivalent to
  252. `name in nlp.pipe_names`.
  253. name (unicode): Name of the component.
  254. RETURNS (bool): Whether a component of the name exists in the pipeline.
  255. """
  256. return name in self.pipe_names
  257. def replace_pipe(self, name, component):
  258. """Replace a component in the pipeline.
  259. name (unicode): Name of the component to replace.
  260. component (callable): Pipeline component.
  261. """
  262. if name not in self.pipe_names:
  263. raise ValueError(Errors.E001.format(name=name, opts=self.pipe_names))
  264. self.pipeline[self.pipe_names.index(name)] = (name, component)
  265. def rename_pipe(self, old_name, new_name):
  266. """Rename a pipeline component.
  267. old_name (unicode): Name of the component to rename.
  268. new_name (unicode): New name of the component.
  269. """
  270. if old_name not in self.pipe_names:
  271. raise ValueError(Errors.E001.format(name=old_name, opts=self.pipe_names))
  272. if new_name in self.pipe_names:
  273. raise ValueError(Errors.E007.format(name=new_name, opts=self.pipe_names))
  274. i = self.pipe_names.index(old_name)
  275. self.pipeline[i] = (new_name, self.pipeline[i][1])
  276. def remove_pipe(self, name):
  277. """Remove a component from the pipeline.
  278. name (unicode): Name of the component to remove.
  279. RETURNS (tuple): A `(name, component)` tuple of the removed component.
  280. """
  281. if name not in self.pipe_names:
  282. raise ValueError(Errors.E001.format(name=name, opts=self.pipe_names))
  283. return self.pipeline.pop(self.pipe_names.index(name))
  284. def __call__(self, text, disable=[]):
  285. """Apply the pipeline to some text. The text can span multiple sentences,
  286. and can contain arbtrary whitespace. Alignment into the original string
  287. is preserved.
  288. text (unicode): The text to be processed.
  289. disable (list): Names of the pipeline components to disable.
  290. RETURNS (Doc): A container for accessing the annotations.
  291. EXAMPLE:
  292. >>> tokens = nlp('An example sentence. Another example sentence.')
  293. >>> tokens[0].text, tokens[0].head.tag_
  294. ('An', 'NN')
  295. """
  296. if len(text) > self.max_length:
  297. raise ValueError(Errors.E088.format(length=len(text),
  298. max_length=self.max_length))
  299. doc = self.make_doc(text)
  300. for name, proc in self.pipeline:
  301. if name in disable:
  302. continue
  303. if not hasattr(proc, '__call__'):
  304. raise ValueError(Errors.E003.format(component=type(proc), name=name))
  305. doc = proc(doc)
  306. if doc is None:
  307. raise ValueError(Errors.E005.format(name=name))
  308. return doc
  309. def disable_pipes(self, *names):
  310. """Disable one or more pipeline components. If used as a context
  311. manager, the pipeline will be restored to the initial state at the end
  312. of the block. Otherwise, a DisabledPipes object is returned, that has
  313. a `.restore()` method you can use to undo your changes.
  314. EXAMPLE:
  315. >>> nlp.add_pipe('parser')
  316. >>> nlp.add_pipe('tagger')
  317. >>> with nlp.disable_pipes('parser', 'tagger'):
  318. >>> assert not nlp.has_pipe('parser')
  319. >>> assert nlp.has_pipe('parser')
  320. >>> disabled = nlp.disable_pipes('parser')
  321. >>> assert len(disabled) == 1
  322. >>> assert not nlp.has_pipe('parser')
  323. >>> disabled.restore()
  324. >>> assert nlp.has_pipe('parser')
  325. """
  326. return DisabledPipes(self, *names)
  327. def make_doc(self, text):
  328. return self.tokenizer(text)
  329. def update(self, docs, golds, drop=0., sgd=None, losses=None):
  330. """Update the models in the pipeline.
  331. docs (iterable): A batch of `Doc` objects.
  332. golds (iterable): A batch of `GoldParse` objects.
  333. drop (float): The droput rate.
  334. sgd (callable): An optimizer.
  335. RETURNS (dict): Results from the update.
  336. EXAMPLE:
  337. >>> with nlp.begin_training(gold) as (trainer, optimizer):
  338. >>> for epoch in trainer.epochs(gold):
  339. >>> for docs, golds in epoch:
  340. >>> state = nlp.update(docs, golds, sgd=optimizer)
  341. """
  342. if len(docs) != len(golds):
  343. raise IndexError(Errors.E009.format(n_docs=len(docs), n_golds=len(golds)))
  344. if len(docs) == 0:
  345. return
  346. if sgd is None:
  347. if self._optimizer is None:
  348. self._optimizer = create_default_optimizer(Model.ops)
  349. sgd = self._optimizer
  350. # Allow dict of args to GoldParse, instead of GoldParse objects.
  351. gold_objs = []
  352. doc_objs = []
  353. for doc, gold in zip(docs, golds):
  354. if isinstance(doc, basestring_):
  355. doc = self.make_doc(doc)
  356. if not isinstance(gold, GoldParse):
  357. gold = GoldParse(doc, **gold)
  358. doc_objs.append(doc)
  359. gold_objs.append(gold)
  360. golds = gold_objs
  361. docs = doc_objs
  362. grads = {}
  363. def get_grads(W, dW, key=None):
  364. grads[key] = (W, dW)
  365. pipes = list(self.pipeline)
  366. random.shuffle(pipes)
  367. for name, proc in pipes:
  368. if not hasattr(proc, 'update'):
  369. continue
  370. grads = {}
  371. proc.update(docs, golds, drop=drop, sgd=get_grads, losses=losses)
  372. for key, (W, dW) in grads.items():
  373. sgd(W, dW, key=key)
  374. def preprocess_gold(self, docs_golds):
  375. """Can be called before training to pre-process gold data. By default,
  376. it handles nonprojectivity and adds missing tags to the tag map.
  377. docs_golds (iterable): Tuples of `Doc` and `GoldParse` objects.
  378. YIELDS (tuple): Tuples of preprocessed `Doc` and `GoldParse` objects.
  379. """
  380. for name, proc in self.pipeline:
  381. if hasattr(proc, 'preprocess_gold'):
  382. docs_golds = proc.preprocess_gold(docs_golds)
  383. for doc, gold in docs_golds:
  384. yield doc, gold
  385. def begin_training(self, get_gold_tuples=None, sgd=None, **cfg):
  386. """Allocate models, pre-process training data and acquire a trainer and
  387. optimizer. Used as a contextmanager.
  388. get_gold_tuples (function): Function returning gold data
  389. **cfg: Config parameters.
  390. RETURNS: An optimizer
  391. """
  392. if get_gold_tuples is None:
  393. get_gold_tuples = lambda: []
  394. # Populate vocab
  395. else:
  396. for _, annots_brackets in get_gold_tuples():
  397. for annots, _ in annots_brackets:
  398. for word in annots[1]:
  399. _ = self.vocab[word]
  400. contexts = []
  401. if cfg.get('device', -1) >= 0:
  402. device = util.use_gpu(cfg['device'])
  403. if self.vocab.vectors.data.shape[1] >= 1:
  404. self.vocab.vectors.data = Model.ops.asarray(
  405. self.vocab.vectors.data)
  406. else:
  407. device = None
  408. link_vectors_to_models(self.vocab)
  409. if self.vocab.vectors.data.shape[1]:
  410. cfg['pretrained_vectors'] = self.vocab.vectors.name
  411. if sgd is None:
  412. sgd = create_default_optimizer(Model.ops)
  413. self._optimizer = sgd
  414. for name, proc in self.pipeline:
  415. if hasattr(proc, 'begin_training'):
  416. proc.begin_training(get_gold_tuples(),
  417. pipeline=self.pipeline,
  418. sgd=self._optimizer,
  419. **cfg)
  420. return self._optimizer
  421. def evaluate(self, docs_golds, verbose=False):
  422. scorer = Scorer()
  423. docs, golds = zip(*docs_golds)
  424. docs = list(docs)
  425. golds = list(golds)
  426. for name, pipe in self.pipeline:
  427. if not hasattr(pipe, 'pipe'):
  428. docs = (pipe(doc) for doc in docs)
  429. else:
  430. docs = pipe.pipe(docs, batch_size=256)
  431. for doc, gold in zip(docs, golds):
  432. if verbose:
  433. print(doc)
  434. scorer.score(doc, gold, verbose=verbose)
  435. return scorer
  436. @contextmanager
  437. def use_params(self, params, **cfg):
  438. """Replace weights of models in the pipeline with those provided in the
  439. params dictionary. Can be used as a contextmanager, in which case,
  440. models go back to their original weights after the block.
  441. params (dict): A dictionary of parameters keyed by model ID.
  442. **cfg: Config parameters.
  443. EXAMPLE:
  444. >>> with nlp.use_params(optimizer.averages):
  445. >>> nlp.to_disk('/tmp/checkpoint')
  446. """
  447. contexts = [pipe.use_params(params) for name, pipe
  448. in self.pipeline if hasattr(pipe, 'use_params')]
  449. # TODO: Having trouble with contextlib
  450. # Workaround: these aren't actually context managers atm.
  451. for context in contexts:
  452. try:
  453. next(context)
  454. except StopIteration:
  455. pass
  456. yield
  457. for context in contexts:
  458. try:
  459. next(context)
  460. except StopIteration:
  461. pass
  462. def pipe(self, texts, as_tuples=False, n_threads=2, batch_size=1000,
  463. disable=[], cleanup=False):
  464. """Process texts as a stream, and yield `Doc` objects in order.
  465. texts (iterator): A sequence of texts to process.
  466. as_tuples (bool):
  467. If set to True, inputs should be a sequence of
  468. (text, context) tuples. Output will then be a sequence of
  469. (doc, context) tuples. Defaults to False.
  470. n_threads (int): Currently inactive.
  471. batch_size (int): The number of texts to buffer.
  472. disable (list): Names of the pipeline components to disable.
  473. cleanup (bool): If True, unneeded strings are freed,
  474. to control memory use. Experimental.
  475. YIELDS (Doc): Documents in the order of the original text.
  476. EXAMPLE:
  477. >>> texts = [u'One document.', u'...', u'Lots of documents']
  478. >>> for doc in nlp.pipe(texts, batch_size=50, n_threads=4):
  479. >>> assert doc.is_parsed
  480. """
  481. if as_tuples:
  482. text_context1, text_context2 = itertools.tee(texts)
  483. texts = (tc[0] for tc in text_context1)
  484. contexts = (tc[1] for tc in text_context2)
  485. docs = self.pipe(texts, n_threads=n_threads, batch_size=batch_size,
  486. disable=disable)
  487. for doc, context in izip(docs, contexts):
  488. yield (doc, context)
  489. return
  490. docs = (self.make_doc(text) for text in texts)
  491. for name, proc in self.pipeline:
  492. if name in disable:
  493. continue
  494. if hasattr(proc, 'pipe'):
  495. docs = proc.pipe(docs, n_threads=n_threads,
  496. batch_size=batch_size)
  497. else:
  498. # Apply the function, but yield the doc
  499. docs = _pipe(proc, docs)
  500. # Track weakrefs of "recent" documents, so that we can see when they
  501. # expire from memory. When they do, we know we don't need old strings.
  502. # This way, we avoid maintaining an unbounded growth in string entries
  503. # in the string store.
  504. recent_refs = weakref.WeakSet()
  505. old_refs = weakref.WeakSet()
  506. # Keep track of the original string data, so that if we flush old strings,
  507. # we can recover the original ones. However, we only want to do this if we're
  508. # really adding strings, to save up-front costs.
  509. original_strings_data = None
  510. nr_seen = 0
  511. for doc in docs:
  512. yield doc
  513. if cleanup:
  514. recent_refs.add(doc)
  515. if nr_seen < 10000:
  516. old_refs.add(doc)
  517. nr_seen += 1
  518. elif len(old_refs) == 0:
  519. old_refs, recent_refs = recent_refs, old_refs
  520. if original_strings_data is None:
  521. original_strings_data = list(self.vocab.strings)
  522. else:
  523. keys, strings = self.vocab.strings._cleanup_stale_strings(original_strings_data)
  524. self.vocab._reset_cache(keys, strings)
  525. self.tokenizer._reset_cache(keys)
  526. nr_seen = 0
  527. def to_disk(self, path, disable=tuple()):
  528. """Save the current state to a directory. If a model is loaded, this
  529. will include the model.
  530. path (unicode or Path): A path to a directory, which will be created if
  531. it doesn't exist. Paths may be strings or `Path`-like objects.
  532. disable (list): Names of pipeline components to disable and prevent
  533. from being saved.
  534. EXAMPLE:
  535. >>> nlp.to_disk('/path/to/models')
  536. """
  537. path = util.ensure_path(path)
  538. serializers = OrderedDict((
  539. ('tokenizer', lambda p: self.tokenizer.to_disk(p, vocab=False)),
  540. ('meta.json', lambda p: p.open('w').write(json_dumps(self.meta)))
  541. ))
  542. for name, proc in self.pipeline:
  543. if not hasattr(proc, 'name'):
  544. continue
  545. if name in disable:
  546. continue
  547. if not hasattr(proc, 'to_disk'):
  548. continue
  549. serializers[name] = lambda p, proc=proc: proc.to_disk(p, vocab=False)
  550. serializers['vocab'] = lambda p: self.vocab.to_disk(p)
  551. util.to_disk(path, serializers, {p: False for p in disable})
  552. def from_disk(self, path, disable=tuple()):
  553. """Loads state from a directory. Modifies the object in place and
  554. returns it. If the saved `Language` object contains a model, the
  555. model will be loaded.
  556. path (unicode or Path): A path to a directory. Paths may be either
  557. strings or `Path`-like objects.
  558. disable (list): Names of the pipeline components to disable.
  559. RETURNS (Language): The modified `Language` object.
  560. EXAMPLE:
  561. >>> from spacy.language import Language
  562. >>> nlp = Language().from_disk('/path/to/models')
  563. """
  564. path = util.ensure_path(path)
  565. deserializers = OrderedDict((
  566. ('meta.json', lambda p: self.meta.update(util.read_json(p))),
  567. ('vocab', lambda p: (
  568. self.vocab.from_disk(p) and _fix_pretrained_vectors_name(self))),
  569. ('tokenizer', lambda p: self.tokenizer.from_disk(p, vocab=False)),
  570. ))
  571. for name, proc in self.pipeline:
  572. if name in disable:
  573. continue
  574. if not hasattr(proc, 'to_disk'):
  575. continue
  576. deserializers[name] = lambda p, proc=proc: proc.from_disk(p, vocab=False)
  577. exclude = {p: False for p in disable}
  578. if not (path / 'vocab').exists():
  579. exclude['vocab'] = True
  580. util.from_disk(path, deserializers, exclude)
  581. self._path = path
  582. return self
  583. def to_bytes(self, disable=[], **exclude):
  584. """Serialize the current state to a binary string.
  585. disable (list): Nameds of pipeline components to disable and prevent
  586. from being serialized.
  587. RETURNS (bytes): The serialized form of the `Language` object.
  588. """
  589. serializers = OrderedDict((
  590. ('vocab', lambda: self.vocab.to_bytes()),
  591. ('tokenizer', lambda: self.tokenizer.to_bytes(vocab=False)),
  592. ('meta', lambda: json_dumps(self.meta))
  593. ))
  594. for i, (name, proc) in enumerate(self.pipeline):
  595. if name in disable:
  596. continue
  597. if not hasattr(proc, 'to_bytes'):
  598. continue
  599. serializers[i] = lambda proc=proc: proc.to_bytes(vocab=False)
  600. return util.to_bytes(serializers, exclude)
  601. def from_bytes(self, bytes_data, disable=[]):
  602. """Load state from a binary string.
  603. bytes_data (bytes): The data to load from.
  604. disable (list): Names of the pipeline components to disable.
  605. RETURNS (Language): The `Language` object.
  606. """
  607. deserializers = OrderedDict((
  608. ('meta', lambda b: self.meta.update(ujson.loads(b))),
  609. ('vocab', lambda b: (
  610. self.vocab.from_bytes(b) and _fix_pretrained_vectors_name(self))),
  611. ('tokenizer', lambda b: self.tokenizer.from_bytes(b, vocab=False)),
  612. ))
  613. for i, (name, proc) in enumerate(self.pipeline):
  614. if name in disable:
  615. continue
  616. if not hasattr(proc, 'from_bytes'):
  617. continue
  618. deserializers[i] = lambda b, proc=proc: proc.from_bytes(b, vocab=False)
  619. msg = util.from_bytes(bytes_data, deserializers, {})
  620. return self
  621. def _fix_pretrained_vectors_name(nlp):
  622. # TODO: Replace this once we handle vectors consistently as static
  623. # data
  624. if 'vectors' in nlp.meta and nlp.meta['vectors'].get('name'):
  625. nlp.vocab.vectors.name = nlp.meta['vectors']['name']
  626. elif not nlp.vocab.vectors.size:
  627. nlp.vocab.vectors.name = None
  628. elif 'name' in nlp.meta and 'lang' in nlp.meta:
  629. vectors_name = '%s_%s.vectors' % (nlp.meta['lang'], nlp.meta['name'])
  630. nlp.vocab.vectors.name = vectors_name
  631. else:
  632. raise ValueError(Errors.E092)
  633. if nlp.vocab.vectors.size != 0:
  634. link_vectors_to_models(nlp.vocab)
  635. for name, proc in nlp.pipeline:
  636. if not hasattr(proc, 'cfg'):
  637. continue
  638. proc.cfg.setdefault('deprecation_fixes', {})
  639. proc.cfg['deprecation_fixes']['vectors_name'] = nlp.vocab.vectors.name
  640. class DisabledPipes(list):
  641. """Manager for temporary pipeline disabling."""
  642. def __init__(self, nlp, *names):
  643. self.nlp = nlp
  644. self.names = names
  645. # Important! Not deep copy -- we just want the container (but we also
  646. # want to support people providing arbitrarily typed nlp.pipeline
  647. # objects.)
  648. self.original_pipeline = copy(nlp.pipeline)
  649. list.__init__(self)
  650. self.extend(nlp.remove_pipe(name) for name in names)
  651. def __enter__(self):
  652. return self
  653. def __exit__(self, *args):
  654. self.restore()
  655. def restore(self):
  656. '''Restore the pipeline to its state when DisabledPipes was created.'''
  657. current, self.nlp.pipeline = self.nlp.pipeline, self.original_pipeline
  658. unexpected = [name for name, pipe in current
  659. if not self.nlp.has_pipe(name)]
  660. if unexpected:
  661. # Don't change the pipeline if we're raising an error.
  662. self.nlp.pipeline = current
  663. raise ValueError(Errors.E008.format(names=unexpected))
  664. self[:] = []
  665. def _pipe(func, docs):
  666. for doc in docs:
  667. doc = func(doc)
  668. yield doc