mirror of
https://github.com/explosion/spaCy.git
synced 2024-12-26 01:46:28 +03:00
faaa832518
* Generalize handling of tokenizer special cases Handle tokenizer special cases more generally by using the Matcher internally to match special cases after the affix/token_match tokenization is complete. Instead of only matching special cases while processing balanced or nearly balanced prefixes and suffixes, this recognizes special cases in a wider range of contexts: * Allows arbitrary numbers of prefixes/affixes around special cases * Allows special cases separated by infixes Existing tests/settings that couldn't be preserved as before: * The emoticon '")' is no longer a supported special case * The emoticon ':)' in "example:)" is a false positive again When merged with #4258 (or the relevant cache bugfix), the affix and token_match properties should be modified to flush and reload all special cases to use the updated internal tokenization with the Matcher. * Remove accidentally added test case * Really remove accidentally added test * Reload special cases when necessary Reload special cases when affixes or token_match are modified. Skip reloading during initialization. * Update error code number * Fix offset and whitespace in Matcher special cases * Fix offset bugs when merging and splitting tokens * Set final whitespace on final token in inserted special case * Improve cache flushing in tokenizer * Separate cache and specials memory (temporarily) * Flush cache when adding special cases * Repeated `self._cache = PreshMap()` and `self._specials = PreshMap()` are necessary due to this bug: https://github.com/explosion/preshed/issues/21 * Remove reinitialized PreshMaps on cache flush * Update UD bin scripts * Update imports for `bin/` * Add all currently supported languages * Update subtok merger for new Matcher validation * Modify blinded check to look at tokens instead of lemmas (for corpora with tokens but not lemmas like Telugu) * Use special Matcher only for cases with affixes * Reinsert specials cache checks during normal tokenization for special cases as much as possible * Additionally include specials cache checks while splitting on infixes * Since the special Matcher needs consistent affix-only tokenization for the special cases themselves, introduce the argument `with_special_cases` in order to do tokenization with or without specials cache checks * After normal tokenization, postprocess with special cases Matcher for special cases containing affixes * Replace PhraseMatcher with Aho-Corasick Replace PhraseMatcher with the Aho-Corasick algorithm over numpy arrays of the hash values for the relevant attribute. The implementation is based on FlashText. The speed should be similar to the previous PhraseMatcher. It is now possible to easily remove match IDs and matches don't go missing with large keyword lists / vocabularies. Fixes #4308. * Restore support for pickling * Fix internal keyword add/remove for numpy arrays * Add test for #4248, clean up test * Improve efficiency of special cases handling * Use PhraseMatcher instead of Matcher * Improve efficiency of merging/splitting special cases in document * Process merge/splits in one pass without repeated token shifting * Merge in place if no splits * Update error message number * Remove UD script modifications Only used for timing/testing, should be a separate PR * Remove final traces of UD script modifications * Update UD bin scripts * Update imports for `bin/` * Add all currently supported languages * Update subtok merger for new Matcher validation * Modify blinded check to look at tokens instead of lemmas (for corpora with tokens but not lemmas like Telugu) * Add missing loop for match ID set in search loop * Remove cruft in matching loop for partial matches There was a bit of unnecessary code left over from FlashText in the matching loop to handle partial token matches, which we don't have with PhraseMatcher. * Replace dict trie with MapStruct trie * Fix how match ID hash is stored/added * Update fix for match ID vocab * Switch from map_get_unless_missing to map_get * Switch from numpy array to Token.get_struct_attr Access token attributes directly in Doc instead of making a copy of the relevant values in a numpy array. Add unsatisfactory warning for hash collision with reserved terminal hash key. (Ideally it would change the reserved terminal hash and redo the whole trie, but for now, I'm hoping there won't be collisions.) * Restructure imports to export find_matches * Implement full remove() Remove unnecessary trie paths and free unused maps. Parallel to Matcher, raise KeyError when attempting to remove a match ID that has not been added. * Switch to PhraseMatcher.find_matches * Switch to local cdef functions for span filtering * Switch special case reload threshold to variable Refer to variable instead of hard-coded threshold * Move more of special case retokenize to cdef nogil Move as much of the special case retokenization to nogil as possible. * Rewrap sort as stdsort for OS X * Rewrap stdsort with specific types * Switch to qsort * Fix merge * Improve cmp functions * Fix realloc * Fix realloc again * Initialize span struct while retokenizing * Temporarily skip retokenizing * Revert "Move more of special case retokenize to cdef nogil" This reverts commit0b7e52c797
. * Revert "Switch to qsort" This reverts commita98d71a942
. * Fix specials check while caching * Modify URL test with emoticons The multiple suffix tests result in the emoticon `:>`, which is now retokenized into one token as a special case after the suffixes are split off. * Refactor _apply_special_cases() * Use cdef ints for span info used in multiple spots * Modify _filter_special_spans() to prefer earlier Parallel to #4414, modify _filter_special_spans() so that the earlier span is preferred for overlapping spans of the same length. * Replace MatchStruct with Entity Replace MatchStruct with Entity since the existing Entity struct is nearly identical. * Replace Entity with more general SpanC * Replace MatchStruct with SpanC * Add error in debug-data if no dev docs are available (see #4575) * Update azure-pipelines.yml * Revert "Update azure-pipelines.yml" This reverts commited1060cf59
. * Use latest wasabi * Reorganise install_requires * add dframcy to universe.json (#4580) * Update universe.json [ci skip] * Fix multiprocessing for as_tuples=True (#4582) * Fix conllu script (#4579) * force extensions to avoid clash between example scripts * fix arg order and default file encoding * add example config for conllu script * newline * move extension definitions to main function * few more encodings fixes * Add load_from_docbin example [ci skip] TODO: upload the file somewhere * Update README.md * Add warnings about 3.8 (resolves #4593) [ci skip] * Fixed typo: Added space between "recognize" and "various" (#4600) * Fix DocBin.merge() example (#4599) * Replace function registries with catalogue (#4584) * Replace functions registries with catalogue * Update __init__.py * Fix test * Revert unrelated flag [ci skip] * Bugfix/dep matcher issue 4590 (#4601) * add contributor agreement for prilopes * add test for issue #4590 * fix on_match params for DependencyMacther (#4590) * Minor updates to language example sentences (#4608) * Add punctuation to Spanish example sentences * Combine multilanguage examples for lang xx * Add punctuation to nb examples * Always realloc to a larger size Avoid potential (unlikely) edge case and cymem error seen in #4604. * Add error in debug-data if no dev docs are available (see #4575) * Update debug-data for GoldCorpus / Example * Ignore None label in misaligned NER data
182 lines
5.1 KiB
Python
182 lines
5.1 KiB
Python
# coding: utf8
|
|
"""
|
|
Helpers for Python and platform compatibility. To distinguish them from
|
|
the builtin functions, replacement functions are suffixed with an underscore,
|
|
e.g. `unicode_`.
|
|
|
|
DOCS: https://spacy.io/api/top-level#compat
|
|
"""
|
|
from __future__ import unicode_literals
|
|
|
|
import os
|
|
import sys
|
|
import itertools
|
|
import ast
|
|
import types
|
|
|
|
from thinc.neural.util import copy_array
|
|
|
|
try:
|
|
import cPickle as pickle
|
|
except ImportError:
|
|
import pickle
|
|
|
|
try:
|
|
import copy_reg
|
|
except ImportError:
|
|
import copyreg as copy_reg
|
|
|
|
try:
|
|
from cupy.cuda.stream import Stream as CudaStream
|
|
except ImportError:
|
|
CudaStream = None
|
|
|
|
try:
|
|
import cupy
|
|
except ImportError:
|
|
cupy = None
|
|
|
|
try:
|
|
from thinc.neural.optimizers import Optimizer # noqa: F401
|
|
except ImportError:
|
|
from thinc.neural.optimizers import Adam as Optimizer # noqa: F401
|
|
|
|
pickle = pickle
|
|
copy_reg = copy_reg
|
|
CudaStream = CudaStream
|
|
cupy = cupy
|
|
copy_array = copy_array
|
|
izip = getattr(itertools, "izip", zip)
|
|
|
|
is_windows = sys.platform.startswith("win")
|
|
is_linux = sys.platform.startswith("linux")
|
|
is_osx = sys.platform == "darwin"
|
|
|
|
# See: https://github.com/benjaminp/six/blob/master/six.py
|
|
is_python2 = sys.version_info[0] == 2
|
|
is_python3 = sys.version_info[0] == 3
|
|
is_python_pre_3_5 = is_python2 or (is_python3 and sys.version_info[1] < 5)
|
|
|
|
if is_python2:
|
|
bytes_ = str
|
|
unicode_ = unicode # noqa: F821
|
|
basestring_ = basestring # noqa: F821
|
|
input_ = raw_input # noqa: F821
|
|
path2str = lambda path: str(path).decode("utf8")
|
|
class_types = (type, types.ClassType)
|
|
|
|
elif is_python3:
|
|
bytes_ = bytes
|
|
unicode_ = str
|
|
basestring_ = str
|
|
input_ = input
|
|
path2str = lambda path: str(path)
|
|
class_types = (type, types.ClassType) if is_python_pre_3_5 else type
|
|
|
|
|
|
def b_to_str(b_str):
|
|
"""Convert a bytes object to a string.
|
|
|
|
b_str (bytes): The object to convert.
|
|
RETURNS (unicode): The converted string.
|
|
"""
|
|
if is_python2:
|
|
return b_str
|
|
# Important: if no encoding is set, string becomes "b'...'"
|
|
return str(b_str, encoding="utf8")
|
|
|
|
|
|
def symlink_to(orig, dest):
|
|
"""Create a symlink. Used for model shortcut links.
|
|
|
|
orig (unicode / Path): The origin path.
|
|
dest (unicode / Path): The destination path of the symlink.
|
|
"""
|
|
if is_windows:
|
|
import subprocess
|
|
|
|
subprocess.check_call(
|
|
["mklink", "/d", path2str(orig), path2str(dest)], shell=True
|
|
)
|
|
else:
|
|
orig.symlink_to(dest)
|
|
|
|
|
|
def symlink_remove(link):
|
|
"""Remove a symlink. Used for model shortcut links.
|
|
|
|
link (unicode / Path): The path to the symlink.
|
|
"""
|
|
# https://stackoverflow.com/q/26554135/6400719
|
|
if os.path.isdir(path2str(link)) and is_windows:
|
|
# this should only be on Py2.7 and windows
|
|
os.rmdir(path2str(link))
|
|
else:
|
|
os.unlink(path2str(link))
|
|
|
|
|
|
def is_config(python2=None, python3=None, windows=None, linux=None, osx=None):
|
|
"""Check if a specific configuration of Python version and operating system
|
|
matches the user's setup. Mostly used to display targeted error messages.
|
|
|
|
python2 (bool): spaCy is executed with Python 2.x.
|
|
python3 (bool): spaCy is executed with Python 3.x.
|
|
windows (bool): spaCy is executed on Windows.
|
|
linux (bool): spaCy is executed on Linux.
|
|
osx (bool): spaCy is executed on OS X or macOS.
|
|
RETURNS (bool): Whether the configuration matches the user's platform.
|
|
|
|
DOCS: https://spacy.io/api/top-level#compat.is_config
|
|
"""
|
|
return (
|
|
python2 in (None, is_python2)
|
|
and python3 in (None, is_python3)
|
|
and windows in (None, is_windows)
|
|
and linux in (None, is_linux)
|
|
and osx in (None, is_osx)
|
|
)
|
|
|
|
|
|
def import_file(name, loc):
|
|
"""Import module from a file. Used to load models from a directory.
|
|
|
|
name (unicode): Name of module to load.
|
|
loc (unicode / Path): Path to the file.
|
|
RETURNS: The loaded module.
|
|
"""
|
|
loc = path2str(loc)
|
|
if is_python_pre_3_5:
|
|
import imp
|
|
|
|
return imp.load_source(name, loc)
|
|
else:
|
|
import importlib.util
|
|
|
|
spec = importlib.util.spec_from_file_location(name, str(loc))
|
|
module = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(module)
|
|
return module
|
|
|
|
|
|
def unescape_unicode(string):
|
|
"""Python2.7's re module chokes when compiling patterns that have ranges
|
|
between escaped unicode codepoints if the two codepoints are unrecognised
|
|
in the unicode database. For instance:
|
|
|
|
re.compile('[\\uAA77-\\uAA79]').findall("hello")
|
|
|
|
Ends up matching every character (on Python 2). This problem doesn't occur
|
|
if we're dealing with unicode literals.
|
|
"""
|
|
if string is None:
|
|
return string
|
|
# We only want to unescape the unicode, so we first must protect the other
|
|
# backslashes.
|
|
string = string.replace("\\", "\\\\")
|
|
# Now we remove that protection for the unicode.
|
|
string = string.replace("\\\\u", "\\u")
|
|
string = string.replace("\\\\U", "\\U")
|
|
# Now we unescape by evaling the string with the AST. This can't execute
|
|
# code -- it only does the representational level.
|
|
return ast.literal_eval("u'''" + string + "'''")
|