2021-05-17 11:16:20 +03:00
|
|
|
from typing import Any, Dict, Union
|
|
|
|
from pathlib import Path
|
|
|
|
import re
|
|
|
|
import srsly
|
|
|
|
import string
|
|
|
|
|
2018-03-29 13:19:51 +03:00
|
|
|
from .stop_words import STOP_WORDS
|
|
|
|
from .lex_attrs import LEX_ATTRS
|
2020-09-30 11:20:14 +03:00
|
|
|
from ...language import Language
|
|
|
|
from ...tokens import Doc
|
|
|
|
from ...util import DummyTokenizer, registry, load_config_from_str
|
2021-05-17 11:16:20 +03:00
|
|
|
from ... import util
|
2018-03-29 13:19:51 +03:00
|
|
|
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
DEFAULT_CONFIG = """
|
|
|
|
[nlp]
|
2018-03-29 13:19:51 +03:00
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
[nlp.tokenizer]
|
2020-07-24 15:50:26 +03:00
|
|
|
@tokenizers = "spacy.vi.VietnameseTokenizer"
|
2020-07-22 14:42:59 +03:00
|
|
|
use_pyvi = true
|
|
|
|
"""
|
💫 Tidy up and auto-format .py files (#2983)
<!--- Provide a general summary of your changes in the title. -->
## Description
- [x] Use [`black`](https://github.com/ambv/black) to auto-format all `.py` files.
- [x] Update flake8 config to exclude very large files (lemmatization tables etc.)
- [x] Update code to be compatible with flake8 rules
- [x] Fix various small bugs, inconsistencies and messy stuff in the language data
- [x] Update docs to explain new code style (`black`, `flake8`, when to use `# fmt: off` and `# fmt: on` and what `# noqa` means)
Once #2932 is merged, which auto-formats and tidies up the CLI, we'll be able to run `flake8 spacy` actually get meaningful results.
At the moment, the code style and linting isn't applied automatically, but I'm hoping that the new [GitHub Actions](https://github.com/features/actions) will let us auto-format pull requests and post comments with relevant linting information.
### Types of change
enhancement, code style
## Checklist
<!--- Before you submit the PR, go over this checklist and make sure you can
tick off all the boxes. [] -> [x] -->
- [x] I have submitted the spaCy Contributor Agreement.
- [x] I ran the tests, and all new and existing tests passed.
- [x] My changes don't require a change to the documentation, or if they do, I've added all required information.
2018-11-30 19:03:03 +03:00
|
|
|
|
2018-03-29 13:19:51 +03:00
|
|
|
|
2020-07-24 15:50:26 +03:00
|
|
|
@registry.tokenizers("spacy.vi.VietnameseTokenizer")
|
2020-09-29 22:39:28 +03:00
|
|
|
def create_vietnamese_tokenizer(use_pyvi: bool = True):
|
2020-07-22 14:42:59 +03:00
|
|
|
def vietnamese_tokenizer_factory(nlp):
|
|
|
|
return VietnameseTokenizer(nlp, use_pyvi=use_pyvi)
|
|
|
|
|
|
|
|
return vietnamese_tokenizer_factory
|
|
|
|
|
|
|
|
|
|
|
|
class VietnameseTokenizer(DummyTokenizer):
|
|
|
|
def __init__(self, nlp: Language, use_pyvi: bool = False):
|
|
|
|
self.vocab = nlp.vocab
|
|
|
|
self.use_pyvi = use_pyvi
|
|
|
|
if self.use_pyvi:
|
2018-03-29 13:19:51 +03:00
|
|
|
try:
|
|
|
|
from pyvi import ViTokenizer
|
2020-07-22 14:42:59 +03:00
|
|
|
|
|
|
|
self.ViTokenizer = ViTokenizer
|
2018-03-29 13:19:51 +03:00
|
|
|
except ImportError:
|
💫 Tidy up and auto-format .py files (#2983)
<!--- Provide a general summary of your changes in the title. -->
## Description
- [x] Use [`black`](https://github.com/ambv/black) to auto-format all `.py` files.
- [x] Update flake8 config to exclude very large files (lemmatization tables etc.)
- [x] Update code to be compatible with flake8 rules
- [x] Fix various small bugs, inconsistencies and messy stuff in the language data
- [x] Update docs to explain new code style (`black`, `flake8`, when to use `# fmt: off` and `# fmt: on` and what `# noqa` means)
Once #2932 is merged, which auto-formats and tidies up the CLI, we'll be able to run `flake8 spacy` actually get meaningful results.
At the moment, the code style and linting isn't applied automatically, but I'm hoping that the new [GitHub Actions](https://github.com/features/actions) will let us auto-format pull requests and post comments with relevant linting information.
### Types of change
enhancement, code style
## Checklist
<!--- Before you submit the PR, go over this checklist and make sure you can
tick off all the boxes. [] -> [x] -->
- [x] I have submitted the spaCy Contributor Agreement.
- [x] I ran the tests, and all new and existing tests passed.
- [x] My changes don't require a change to the documentation, or if they do, I've added all required information.
2018-11-30 19:03:03 +03:00
|
|
|
msg = (
|
2020-07-22 14:42:59 +03:00
|
|
|
"Pyvi not installed. Either set use_pyvi = False, "
|
💫 Tidy up and auto-format .py files (#2983)
<!--- Provide a general summary of your changes in the title. -->
## Description
- [x] Use [`black`](https://github.com/ambv/black) to auto-format all `.py` files.
- [x] Update flake8 config to exclude very large files (lemmatization tables etc.)
- [x] Update code to be compatible with flake8 rules
- [x] Fix various small bugs, inconsistencies and messy stuff in the language data
- [x] Update docs to explain new code style (`black`, `flake8`, when to use `# fmt: off` and `# fmt: on` and what `# noqa` means)
Once #2932 is merged, which auto-formats and tidies up the CLI, we'll be able to run `flake8 spacy` actually get meaningful results.
At the moment, the code style and linting isn't applied automatically, but I'm hoping that the new [GitHub Actions](https://github.com/features/actions) will let us auto-format pull requests and post comments with relevant linting information.
### Types of change
enhancement, code style
## Checklist
<!--- Before you submit the PR, go over this checklist and make sure you can
tick off all the boxes. [] -> [x] -->
- [x] I have submitted the spaCy Contributor Agreement.
- [x] I ran the tests, and all new and existing tests passed.
- [x] My changes don't require a change to the documentation, or if they do, I've added all required information.
2018-11-30 19:03:03 +03:00
|
|
|
"or install it https://pypi.python.org/pypi/pyvi"
|
|
|
|
)
|
2020-08-06 00:53:21 +03:00
|
|
|
raise ImportError(msg) from None
|
2020-07-22 14:42:59 +03:00
|
|
|
|
|
|
|
def __call__(self, text: str) -> Doc:
|
|
|
|
if self.use_pyvi:
|
2021-05-17 11:16:20 +03:00
|
|
|
words = self.pyvi_tokenize(text)
|
|
|
|
words, spaces = util.get_words_and_spaces(words, text)
|
2018-03-29 13:19:51 +03:00
|
|
|
return Doc(self.vocab, words=words, spaces=spaces)
|
|
|
|
else:
|
2021-05-17 11:16:20 +03:00
|
|
|
words, spaces = util.get_words_and_spaces(text.split(), text)
|
2018-03-29 13:19:51 +03:00
|
|
|
return Doc(self.vocab, words=words, spaces=spaces)
|
|
|
|
|
2021-05-17 11:16:20 +03:00
|
|
|
# The methods pyvi_sylabelize_with_ws and pyvi_tokenize are adapted from
|
|
|
|
# pyvi v0.1, MIT License, Copyright (c) 2016 Viet-Trung Tran.
|
|
|
|
# See licenses/3rd_party_licenses.txt
|
|
|
|
def pyvi_sylabelize_with_ws(self, text):
|
|
|
|
"""Modified from pyvi to preserve whitespace and skip unicode
|
|
|
|
normalization."""
|
|
|
|
specials = [r"==>", r"->", r"\.\.\.", r">>"]
|
|
|
|
digit = r"\d+([\.,_]\d+)+"
|
|
|
|
email = r"([a-zA-Z0-9_.+-]+@([a-zA-Z0-9-]+\.)+[a-zA-Z0-9-]+)"
|
|
|
|
web = r"\w+://[^\s]+"
|
|
|
|
word = r"\w+"
|
|
|
|
non_word = r"[^\w\s]"
|
|
|
|
abbreviations = [
|
|
|
|
r"[A-ZĐ]+\.",
|
|
|
|
r"Tp\.",
|
|
|
|
r"Mr\.",
|
|
|
|
r"Mrs\.",
|
|
|
|
r"Ms\.",
|
|
|
|
r"Dr\.",
|
|
|
|
r"ThS\.",
|
|
|
|
]
|
|
|
|
|
|
|
|
patterns = []
|
|
|
|
patterns.extend(abbreviations)
|
|
|
|
patterns.extend(specials)
|
|
|
|
patterns.extend([web, email])
|
|
|
|
patterns.extend([digit, non_word, word])
|
|
|
|
|
|
|
|
patterns = r"(\s+|" + "|".join(patterns) + ")"
|
|
|
|
tokens = re.findall(patterns, text, re.UNICODE)
|
|
|
|
|
|
|
|
return [token[0] for token in tokens]
|
|
|
|
|
|
|
|
def pyvi_tokenize(self, text):
|
|
|
|
"""Modified from pyvi to preserve text and whitespace."""
|
|
|
|
if len(text) == 0:
|
|
|
|
return []
|
|
|
|
elif text.isspace():
|
|
|
|
return [text]
|
|
|
|
segs = self.pyvi_sylabelize_with_ws(text)
|
|
|
|
words = []
|
|
|
|
preceding_ws = []
|
|
|
|
for i, token in enumerate(segs):
|
|
|
|
if not token.isspace():
|
|
|
|
words.append(token)
|
|
|
|
preceding_ws.append(
|
|
|
|
"" if (i == 0 or not segs[i - 1].isspace()) else segs[i - 1]
|
|
|
|
)
|
|
|
|
labels = self.ViTokenizer.ViTokenizer.model.predict(
|
|
|
|
[self.ViTokenizer.ViTokenizer.sent2features(words, False)]
|
|
|
|
)
|
|
|
|
token = words[0]
|
|
|
|
tokens = []
|
|
|
|
for i in range(1, len(labels[0])):
|
|
|
|
if (
|
|
|
|
labels[0][i] == "I_W"
|
|
|
|
and words[i] not in string.punctuation
|
|
|
|
and words[i - 1] not in string.punctuation
|
|
|
|
and not words[i][0].isdigit()
|
|
|
|
and not words[i - 1][0].isdigit()
|
|
|
|
and not (words[i][0].istitle() and not words[i - 1][0].istitle())
|
|
|
|
):
|
|
|
|
token = token + preceding_ws[i] + words[i]
|
|
|
|
else:
|
|
|
|
tokens.append(token)
|
|
|
|
token = words[i]
|
|
|
|
tokens.append(token)
|
|
|
|
return tokens
|
|
|
|
|
|
|
|
def _get_config(self) -> Dict[str, Any]:
|
|
|
|
return {"use_pyvi": self.use_pyvi}
|
|
|
|
|
|
|
|
def _set_config(self, config: Dict[str, Any] = {}) -> None:
|
|
|
|
self.use_pyvi = config.get("use_pyvi", False)
|
|
|
|
|
|
|
|
def to_bytes(self, **kwargs) -> bytes:
|
|
|
|
serializers = {"cfg": lambda: srsly.json_dumps(self._get_config())}
|
|
|
|
return util.to_bytes(serializers, [])
|
|
|
|
|
|
|
|
def from_bytes(self, data: bytes, **kwargs) -> "VietnameseTokenizer":
|
|
|
|
deserializers = {"cfg": lambda b: self._set_config(srsly.json_loads(b))}
|
|
|
|
util.from_bytes(data, deserializers, [])
|
|
|
|
return self
|
|
|
|
|
|
|
|
def to_disk(self, path: Union[str, Path], **kwargs) -> None:
|
|
|
|
path = util.ensure_path(path)
|
|
|
|
serializers = {"cfg": lambda p: srsly.write_json(p, self._get_config())}
|
|
|
|
return util.to_disk(path, serializers, [])
|
|
|
|
|
|
|
|
def from_disk(self, path: Union[str, Path], **kwargs) -> "VietnameseTokenizer":
|
|
|
|
path = util.ensure_path(path)
|
|
|
|
serializers = {"cfg": lambda p: self._set_config(srsly.read_json(p))}
|
|
|
|
util.from_disk(path, serializers, [])
|
|
|
|
return self
|
|
|
|
|
💫 Tidy up and auto-format .py files (#2983)
<!--- Provide a general summary of your changes in the title. -->
## Description
- [x] Use [`black`](https://github.com/ambv/black) to auto-format all `.py` files.
- [x] Update flake8 config to exclude very large files (lemmatization tables etc.)
- [x] Update code to be compatible with flake8 rules
- [x] Fix various small bugs, inconsistencies and messy stuff in the language data
- [x] Update docs to explain new code style (`black`, `flake8`, when to use `# fmt: off` and `# fmt: on` and what `# noqa` means)
Once #2932 is merged, which auto-formats and tidies up the CLI, we'll be able to run `flake8 spacy` actually get meaningful results.
At the moment, the code style and linting isn't applied automatically, but I'm hoping that the new [GitHub Actions](https://github.com/features/actions) will let us auto-format pull requests and post comments with relevant linting information.
### Types of change
enhancement, code style
## Checklist
<!--- Before you submit the PR, go over this checklist and make sure you can
tick off all the boxes. [] -> [x] -->
- [x] I have submitted the spaCy Contributor Agreement.
- [x] I ran the tests, and all new and existing tests passed.
- [x] My changes don't require a change to the documentation, or if they do, I've added all required information.
2018-11-30 19:03:03 +03:00
|
|
|
|
2020-07-24 15:50:26 +03:00
|
|
|
class VietnameseDefaults(Language.Defaults):
|
2020-09-30 11:20:14 +03:00
|
|
|
config = load_config_from_str(DEFAULT_CONFIG)
|
2020-07-24 15:50:26 +03:00
|
|
|
lex_attr_getters = LEX_ATTRS
|
|
|
|
stop_words = STOP_WORDS
|
|
|
|
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
class Vietnamese(Language):
|
|
|
|
lang = "vi"
|
2020-07-24 15:50:26 +03:00
|
|
|
Defaults = VietnameseDefaults
|
2020-07-22 14:42:59 +03:00
|
|
|
|
|
|
|
|
💫 Tidy up and auto-format .py files (#2983)
<!--- Provide a general summary of your changes in the title. -->
## Description
- [x] Use [`black`](https://github.com/ambv/black) to auto-format all `.py` files.
- [x] Update flake8 config to exclude very large files (lemmatization tables etc.)
- [x] Update code to be compatible with flake8 rules
- [x] Fix various small bugs, inconsistencies and messy stuff in the language data
- [x] Update docs to explain new code style (`black`, `flake8`, when to use `# fmt: off` and `# fmt: on` and what `# noqa` means)
Once #2932 is merged, which auto-formats and tidies up the CLI, we'll be able to run `flake8 spacy` actually get meaningful results.
At the moment, the code style and linting isn't applied automatically, but I'm hoping that the new [GitHub Actions](https://github.com/features/actions) will let us auto-format pull requests and post comments with relevant linting information.
### Types of change
enhancement, code style
## Checklist
<!--- Before you submit the PR, go over this checklist and make sure you can
tick off all the boxes. [] -> [x] -->
- [x] I have submitted the spaCy Contributor Agreement.
- [x] I ran the tests, and all new and existing tests passed.
- [x] My changes don't require a change to the documentation, or if they do, I've added all required information.
2018-11-30 19:03:03 +03:00
|
|
|
__all__ = ["Vietnamese"]
|