Showing preview only (7,107K chars total). Download the full file or copy to clipboard to get everything.
Repository: vngrs-ai/vnlp
Branch: main
Commit: 73265d820c0b
Files: 94
Total size: 18.3 MB
Directory structure:
gitextract_fqx72n4r/
├── .flake8
├── .github/
│ └── workflows/
│ └── test.yml
├── .gitignore
├── .pre-commit-config.yaml
├── .readthedocs.yaml
├── Examples.ipynb
├── LICENSE
├── MANIFEST.in
├── README.md
├── docs/
│ ├── Makefile
│ ├── make.bat
│ ├── requirements.txt
│ └── source/
│ ├── conf.py
│ ├── index.md
│ ├── main_classes/
│ │ ├── dependency_parser.md
│ │ ├── named_entity_recognizer.md
│ │ ├── normalizer.md
│ │ ├── part_of_speech_tagger.md
│ │ ├── sentence_splitter.md
│ │ ├── sentiment_analyzer.md
│ │ ├── stemmer_morph_analyzer.md
│ │ ├── stopword_remover.md
│ │ └── word_embeddings.md
│ └── quickstart.md
├── pyproject.toml
├── setup.cfg
├── setup.py
├── tests/
│ └── test_general.py
└── vnlp/
├── __init__.py
├── bin/
│ ├── __init__.py
│ └── vnlp.py
├── dependency_parser/
│ ├── ReadMe.md
│ ├── __init__.py
│ ├── _spu_context_utils.py
│ ├── _treestack_utils.py
│ ├── dependency_parser.py
│ ├── resources/
│ │ └── DP_label_tokenizer.json
│ ├── spu_context_dp.py
│ ├── treestack_dp.py
│ └── utils.py
├── named_entity_recognizer/
│ ├── ReadMe.md
│ ├── __init__.py
│ ├── _charner_utils.py
│ ├── _spu_context_utils.py
│ ├── charner.py
│ ├── named_entity_recognizer.py
│ ├── resources/
│ │ ├── CharNER_char_tokenizer.json
│ │ └── NER_label_tokenizer.json
│ ├── spu_context_ner.py
│ └── utils.py
├── normalizer/
│ ├── ReadMe.md
│ ├── __init__.py
│ ├── _deasciifier.py
│ └── normalizer.py
├── part_of_speech_tagger/
│ ├── ReadMe.md
│ ├── __init__.py
│ ├── _spu_context_utils.py
│ ├── _treestack_utils.py
│ ├── part_of_speech_tagger.py
│ ├── resources/
│ │ └── PoS_label_tokenizer.json
│ ├── spu_context_pos.py
│ └── treestack_pos.py
├── resources/
│ ├── SPU_word_tokenizer_16k.model
│ ├── TB_word_tokenizer.json
│ ├── non_breaking_prefixes_tr.txt
│ ├── turkish_known_words_lexicon.txt
│ └── turkish_stop_words.txt
├── sentence_splitter/
│ ├── ReadMe.md
│ ├── __init__.py
│ └── sentence_splitter.py
├── sentiment_analyzer/
│ ├── ReadMe.md
│ ├── __init__.py
│ ├── _spu_context_bigru_utils.py
│ ├── sentiment_analyzer.py
│ └── spu_context_bigru_sentiment.py
├── stemmer_morph_analyzer/
│ ├── ReadMe.md
│ ├── __init__.py
│ ├── _melik_utils.py
│ ├── _yildiz_analyzer.py
│ ├── resources/
│ │ ├── ExactLookup.txt
│ │ ├── StemListWithFlags_v2.txt
│ │ ├── Stemmer_char_tokenizer.json
│ │ ├── Stemmer_morph_tag_tokenizer.json
│ │ └── Suffixes&Tags.txt
│ └── stemmer_morph_analyzer.py
├── stopword_remover/
│ ├── ReadMe.md
│ ├── __init__.py
│ └── stopword_remover.py
├── tokenizer/
│ ├── ReadMe.md
│ ├── __init__.py
│ └── tokenizer.py
├── turkish_word_embeddings/
│ ├── ReadMe.md
│ └── example.ipynb
└── utils.py
================================================
FILE CONTENTS
================================================
================================================
FILE: .flake8
================================================
[flake8]
ignore = E203, E266, E501, W503, F403, F401
max-line-length = 79
max-complexity = 18
select = B,C,E,F,W,T4,B9
================================================
FILE: .github/workflows/test.yml
================================================
name: Python check
on: [push]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.8", "3.9", "3.10", "3.11"]
steps:
- uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
sudo apt update
sudo apt -y install swig3.0
python -m pip install --upgrade pip setuptools wheel pytest
pip install .
- name: Test with pytest
run: |
pytest
================================================
FILE: .gitignore
================================================
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# Externally managed resources
vnlp/resources/spell_correction_model.bin
vnlp/resources/spell_correction_model.bin.spell
# Model weights that will be downloaded from AWS
.weights
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# Vscode
.vscode
# pyenv
.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# MacOS
.DS_Store
================================================
FILE: .pre-commit-config.yaml
================================================
repos:
- repo: https://github.com/psf/black
rev: 23.1.0
hooks:
- id: black-jupyter
- repo: https://github.com/PyCQA/flake8
rev: 5.0.4
hooks:
- id: flake8
================================================
FILE: .readthedocs.yaml
================================================
# .readthedocs.yaml
# Read the Docs configuration file
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
# Required
version: 2
# Set the version of Python and other tools you might need
build:
os: ubuntu-22.04
tools:
python: "3.9"
# Build documentation in the docs/ directory with Sphinx
sphinx:
builder: html
configuration: docs/source/conf.py
# First installation is the packages required by readthedocs build
# Second installation is to install vngrs-nlp while building the documentation, otherwise the docstrings are not parsed.
python:
install:
- requirements: docs/requirements.txt
- method: pip
path: .
================================================
FILE: Examples.ipynb
================================================
{
"cells": [
{
"cell_type": "markdown",
"id": "6c310b03",
"metadata": {},
"source": [
"#### Morphological Analyzer"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "cdae2a11",
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"from vnlp import StemmerAnalyzer\n",
"\n",
"stemmer_analyzer = StemmerAnalyzer()"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "7d97f600",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['üniversite+Noun+A3sg+Pnon+Nom',\n",
" 'sınav+Noun+A3pl+P3sg+Dat',\n",
" 'can+Noun+A3sg+Pnon+Ins',\n",
" 'baş+Noun+A3sg+Pnon+Ins',\n",
" 'çalış+Verb+Pos+Prog1+A3pl+Past',\n",
" '.+Punc']"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"stemmer_analyzer.predict(\"Üniversite sınavlarına canla başla çalışıyorlardı.\")"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "3934834e",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['şimdi+Adverb', 'baş+Noun+A3sg+Pnon+Abl', 'başla+Verb+Pos+Imp+A2sg', '.+Punc']"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"stemmer_analyzer.predict(\"Şimdi baştan başla.\")"
]
},
{
"cell_type": "markdown",
"id": "602313e4",
"metadata": {},
"source": [
"#### Named Entity Recognizer"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "886e1623",
"metadata": {},
"outputs": [],
"source": [
"from vnlp import NamedEntityRecognizer\n",
"\n",
"ner = NamedEntityRecognizer()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "612d529a",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[('Benim', 'O'),\n",
" ('adım', 'O'),\n",
" ('Melikşah', 'PER'),\n",
" (',', 'O'),\n",
" ('32', 'O'),\n",
" ('yaşındayım', 'O'),\n",
" (',', 'O'),\n",
" (\"İstanbul'da\", 'LOC'),\n",
" ('ikamet', 'O'),\n",
" ('ediyorum', 'O'),\n",
" ('ve', 'O'),\n",
" ('VNGRS', 'ORG'),\n",
" ('AI', 'ORG'),\n",
" (\"Takımı'nda\", 'ORG'),\n",
" ('çalışıyorum', 'O'),\n",
" ('.', 'O')]"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"ner.predict(\n",
" \"Benim adım Melikşah, 32 yaşındayım, İstanbul'da ikamet ediyorum ve VNGRS AI Takımı'nda çalışıyorum.\"\n",
")"
]
},
{
"cell_type": "markdown",
"id": "e11c01c0",
"metadata": {},
"source": [
"#### Dependency Parser"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "a1c42cff",
"metadata": {},
"outputs": [],
"source": [
"from vnlp import DependencyParser\n",
"\n",
"dep_parser = DependencyParser()"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "9eba1ed4",
"metadata": {
"scrolled": false
},
"outputs": [
{
"data": {
"text/plain": [
"[(1, 'Onun', 6, 'obl'),\n",
" (2, 'için', 1, 'case'),\n",
" (3, 'yol', 4, 'nmod'),\n",
" (4, 'arkadaşlarımızı', 6, 'obj'),\n",
" (5, 'titizlikle', 6, 'obl'),\n",
" (6, 'seçer', 10, 'parataxis'),\n",
" (7, ',', 6, 'punct'),\n",
" (8, 'kendilerini', 10, 'obj'),\n",
" (9, 'iyice', 10, 'advmod'),\n",
" (10, 'sınarız', 0, 'root'),\n",
" (11, '.', 10, 'punct')]"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dep_parser.predict(\n",
" \"Onun için yol arkadaşlarımızı titizlikle seçer, kendilerini iyice sınarız.\"\n",
")"
]
},
{
"cell_type": "markdown",
"id": "c1075a96",
"metadata": {},
"source": [
"#### Part of Speech Tagger"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "ffdd890e",
"metadata": {},
"outputs": [],
"source": [
"from vnlp import PoSTagger\n",
"\n",
"pos_tagger = PoSTagger()"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "d674e72b",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[(\"Oğuz'un\", 'PROPN'),\n",
" ('kırmızı', 'ADJ'),\n",
" ('bir', 'DET'),\n",
" (\"Astra'sı\", 'PROPN'),\n",
" ('vardı', 'VERB'),\n",
" ('.', 'PUNCT')]"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pos_tagger.predict(\"Oğuz'un kırmızı bir Astra'sı vardı.\")"
]
},
{
"cell_type": "markdown",
"id": "04480f14",
"metadata": {},
"source": [
"#### Visualize Dependency & Part of Speech Tags with Spacy"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "e29e2a02",
"metadata": {},
"outputs": [],
"source": [
"from spacy import displacy"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "72792075",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<span class=\"tex2jax_ignore\"><svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xml:lang=\"en\" id=\"0e475726d3c948d4a2e09d60c6672ece-0\" class=\"displacy\" width=\"650\" height=\"287.0\" direction=\"ltr\" style=\"max-width: none; height: 287.0px; color: #000000; background: #ffffff; font-family: Arial; direction: ltr\">\n",
"<text class=\"displacy-token\" fill=\"currentColor\" text-anchor=\"middle\" y=\"197.0\">\n",
" <tspan class=\"displacy-word\" fill=\"currentColor\" x=\"50\">Oğuz'un</tspan>\n",
" <tspan class=\"displacy-tag\" dy=\"2em\" fill=\"currentColor\" x=\"50\">PROPN</tspan>\n",
"</text>\n",
"\n",
"<text class=\"displacy-token\" fill=\"currentColor\" text-anchor=\"middle\" y=\"197.0\">\n",
" <tspan class=\"displacy-word\" fill=\"currentColor\" x=\"150\">kırmızı</tspan>\n",
" <tspan class=\"displacy-tag\" dy=\"2em\" fill=\"currentColor\" x=\"150\">ADJ</tspan>\n",
"</text>\n",
"\n",
"<text class=\"displacy-token\" fill=\"currentColor\" text-anchor=\"middle\" y=\"197.0\">\n",
" <tspan class=\"displacy-word\" fill=\"currentColor\" x=\"250\">bir</tspan>\n",
" <tspan class=\"displacy-tag\" dy=\"2em\" fill=\"currentColor\" x=\"250\">DET</tspan>\n",
"</text>\n",
"\n",
"<text class=\"displacy-token\" fill=\"currentColor\" text-anchor=\"middle\" y=\"197.0\">\n",
" <tspan class=\"displacy-word\" fill=\"currentColor\" x=\"350\">Astra'sı</tspan>\n",
" <tspan class=\"displacy-tag\" dy=\"2em\" fill=\"currentColor\" x=\"350\">PROPN</tspan>\n",
"</text>\n",
"\n",
"<text class=\"displacy-token\" fill=\"currentColor\" text-anchor=\"middle\" y=\"197.0\">\n",
" <tspan class=\"displacy-word\" fill=\"currentColor\" x=\"450\">vardı</tspan>\n",
" <tspan class=\"displacy-tag\" dy=\"2em\" fill=\"currentColor\" x=\"450\">VERB</tspan>\n",
"</text>\n",
"\n",
"<text class=\"displacy-token\" fill=\"currentColor\" text-anchor=\"middle\" y=\"197.0\">\n",
" <tspan class=\"displacy-word\" fill=\"currentColor\" x=\"550\">.</tspan>\n",
" <tspan class=\"displacy-tag\" dy=\"2em\" fill=\"currentColor\" x=\"550\">PUNCT</tspan>\n",
"</text>\n",
"\n",
"<g class=\"displacy-arrow\">\n",
" <path class=\"displacy-arc\" id=\"arrow-0e475726d3c948d4a2e09d60c6672ece-0-0\" stroke-width=\"2px\" d=\"M62,152.0 C62,2.0 350.0,2.0 350.0,152.0\" fill=\"none\" stroke=\"currentColor\"/>\n",
" <text dy=\"1.25em\" style=\"font-size: 0.8em; letter-spacing: 1px\">\n",
" <textPath xlink:href=\"#arrow-0e475726d3c948d4a2e09d60c6672ece-0-0\" class=\"displacy-label\" startOffset=\"50%\" side=\"left\" fill=\"currentColor\" text-anchor=\"middle\">nmod</textPath>\n",
" </text>\n",
" <path class=\"displacy-arrowhead\" d=\"M350.0,154.0 L358.0,142.0 342.0,142.0\" fill=\"currentColor\"/>\n",
"</g>\n",
"\n",
"<g class=\"displacy-arrow\">\n",
" <path class=\"displacy-arc\" id=\"arrow-0e475726d3c948d4a2e09d60c6672ece-0-1\" stroke-width=\"2px\" d=\"M162,152.0 C162,52.0 347.0,52.0 347.0,152.0\" fill=\"none\" stroke=\"currentColor\"/>\n",
" <text dy=\"1.25em\" style=\"font-size: 0.8em; letter-spacing: 1px\">\n",
" <textPath xlink:href=\"#arrow-0e475726d3c948d4a2e09d60c6672ece-0-1\" class=\"displacy-label\" startOffset=\"50%\" side=\"left\" fill=\"currentColor\" text-anchor=\"middle\">amod</textPath>\n",
" </text>\n",
" <path class=\"displacy-arrowhead\" d=\"M347.0,154.0 L355.0,142.0 339.0,142.0\" fill=\"currentColor\"/>\n",
"</g>\n",
"\n",
"<g class=\"displacy-arrow\">\n",
" <path class=\"displacy-arc\" id=\"arrow-0e475726d3c948d4a2e09d60c6672ece-0-2\" stroke-width=\"2px\" d=\"M262,152.0 C262,102.0 344.0,102.0 344.0,152.0\" fill=\"none\" stroke=\"currentColor\"/>\n",
" <text dy=\"1.25em\" style=\"font-size: 0.8em; letter-spacing: 1px\">\n",
" <textPath xlink:href=\"#arrow-0e475726d3c948d4a2e09d60c6672ece-0-2\" class=\"displacy-label\" startOffset=\"50%\" side=\"left\" fill=\"currentColor\" text-anchor=\"middle\">det</textPath>\n",
" </text>\n",
" <path class=\"displacy-arrowhead\" d=\"M344.0,154.0 L352.0,142.0 336.0,142.0\" fill=\"currentColor\"/>\n",
"</g>\n",
"\n",
"<g class=\"displacy-arrow\">\n",
" <path class=\"displacy-arc\" id=\"arrow-0e475726d3c948d4a2e09d60c6672ece-0-3\" stroke-width=\"2px\" d=\"M362,152.0 C362,102.0 444.0,102.0 444.0,152.0\" fill=\"none\" stroke=\"currentColor\"/>\n",
" <text dy=\"1.25em\" style=\"font-size: 0.8em; letter-spacing: 1px\">\n",
" <textPath xlink:href=\"#arrow-0e475726d3c948d4a2e09d60c6672ece-0-3\" class=\"displacy-label\" startOffset=\"50%\" side=\"left\" fill=\"currentColor\" text-anchor=\"middle\">nsubj</textPath>\n",
" </text>\n",
" <path class=\"displacy-arrowhead\" d=\"M444.0,154.0 L452.0,142.0 436.0,142.0\" fill=\"currentColor\"/>\n",
"</g>\n",
"\n",
"<g class=\"displacy-arrow\">\n",
" <path class=\"displacy-arc\" id=\"arrow-0e475726d3c948d4a2e09d60c6672ece-0-4\" stroke-width=\"2px\" d=\"M462,152.0 C462,102.0 544.0,102.0 544.0,152.0\" fill=\"none\" stroke=\"currentColor\"/>\n",
" <text dy=\"1.25em\" style=\"font-size: 0.8em; letter-spacing: 1px\">\n",
" <textPath xlink:href=\"#arrow-0e475726d3c948d4a2e09d60c6672ece-0-4\" class=\"displacy-label\" startOffset=\"50%\" side=\"left\" fill=\"currentColor\" text-anchor=\"middle\">punct</textPath>\n",
" </text>\n",
" <path class=\"displacy-arrowhead\" d=\"M462,154.0 L454,142.0 470,142.0\" fill=\"currentColor\"/>\n",
"</g>\n",
"</svg></span>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"text = \"Oğuz'un kırmızı bir Astra'sı vardı.\"\n",
"pos_result = pos_tagger.predict(text)\n",
"dp_result = dep_parser.predict(\n",
" text, displacy_format=True, pos_result=pos_result\n",
")\n",
"# Options: https://spacy.io/api/top-level#displacy_options\n",
"opts = {\n",
" \"distance\": 100,\n",
" \"word_spacing\": 45,\n",
" \"arrow_stroke\": 2, # arrow body width\n",
" \"arrow_width\": 10, # arrow head width\n",
" \"arrow_spacing\": 12, # space between arrows\n",
" \"compact\": False, # square arrows\n",
"}\n",
"displacy.render(dp_result, style=\"dep\", options=opts, manual=True)"
]
},
{
"cell_type": "markdown",
"id": "1c3421ae",
"metadata": {},
"source": [
"#### Sentiment Analysis"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "a19c4f55",
"metadata": {},
"outputs": [],
"source": [
"from vnlp import SentimentAnalyzer\n",
"\n",
"sentiment_analyzer = SentimentAnalyzer()"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "de3ef6a6",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.9879776"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sentiment_analyzer.predict_proba(\n",
" \"Zeynep'in okul taksitini Bürokratistan'daki Parabank'tan yatırdım.\"\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "4782f1dd",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.08877806"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sentiment_analyzer.predict_proba(\n",
" \"Sipariş geldiğinde biz karnımızı çoktan atıştırmalıklarla doyurmuştuk.\"\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 15,
"id": "7e011191",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sentiment_analyzer.predict(\n",
" \"Servis daha iyi olabilirdi ama lezzet ve hız geçer not aldı.\"\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 16,
"id": "7454e45b",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.8481084"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sentiment_analyzer.predict_proba(\"Mutlu değilim diyemem.\")"
]
},
{
"cell_type": "code",
"execution_count": 17,
"id": "0814f489",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.9930549"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sentiment_analyzer.predict_proba(\n",
" \"Geçmesin günümüz sevgilim yasla, o güzel başını göğsüme yasla.\"\n",
")"
]
},
{
"cell_type": "markdown",
"id": "01b9fdf4",
"metadata": {},
"source": [
"#### Normalizer\n",
"- Spelling/Typo correction\n",
"- Converts numbers to word form\n",
"- Deascification\n",
"- Lowercasing\n",
"- Punctuation removal\n",
"- Accent mark removal"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "bd17944b",
"metadata": {},
"outputs": [],
"source": [
"from vnlp import Normalizer\n",
"\n",
"normalizer = Normalizer()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "1f8f9e82",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'kasıtlı yazım hatası ekliyorum'"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"normalizer.correct_typos(\"kassıtlı yaezım hatasssı ekliyorumm\")"
]
},
{
"cell_type": "code",
"execution_count": 20,
"id": "4fb41e55",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['sabah',\n",
" 'iki',\n",
" 'yumurta',\n",
" 'yedim',\n",
" 've',\n",
" 'tartıldığımda',\n",
" 'bir',\n",
" 'virgül',\n",
" 'on',\n",
" 'beş',\n",
" 'kilogram',\n",
" 'aldığımı',\n",
" 'gördüm']"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"normalizer.convert_numbers_to_words(\n",
" \"sabah 2 yumurta yedim ve tartıldığımda 1,15 kilogram aldığımı gördüm\".split()\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 21,
"id": "88148c71",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['böyle', 'şey', 'görmedim', 'duymadım']"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"normalizer.deasciify(\"boyle sey gormedim duymadim\".split())"
]
},
{
"cell_type": "code",
"execution_count": 22,
"id": "2c912cba",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['yatırdım']"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"normalizer.deasciify(\"yatirdim\".split())"
]
},
{
"cell_type": "code",
"execution_count": 23,
"id": "50b0567e",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'test karakterleri: iığüöşç'"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"normalizer.lower_case(\"Test karakterleri: İIĞÜÖŞÇ\")"
]
},
{
"cell_type": "code",
"execution_count": 24,
"id": "8c029b73",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'noktalamalı test cümlesidir'"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"normalizer.remove_punctuations(\"noktalamalı test cümlesidir...\")"
]
},
{
"cell_type": "code",
"execution_count": 25,
"id": "9446830b",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'merhaba guzel yılkı atı'"
]
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"normalizer.remove_accent_marks(\"merhâbâ gûzel yîlkî atî\")"
]
},
{
"cell_type": "markdown",
"id": "f4f83fd7",
"metadata": {},
"source": [
"#### Sentence Splitter"
]
},
{
"cell_type": "code",
"execution_count": 26,
"id": "b1c46de2",
"metadata": {},
"outputs": [],
"source": [
"from vnlp import SentenceSplitter\n",
"\n",
"sentence_splitter = SentenceSplitter()"
]
},
{
"cell_type": "code",
"execution_count": 27,
"id": "37a80618",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['Dr. Can Çıkaran, tedavisi devam eden hastanın durumu ile ilgili dedi ki, \"Can çıkar, huy çıkmaz.\"',\n",
" 'Hasta yakınları ne hissedeceğini şaşırdı.']"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sentence_splitter.split_sentences(\n",
" 'Dr. Can Çıkaran, tedavisi devam eden hastanın durumu ile ilgili dedi ki, \"Can çıkar, huy çıkmaz.\" Hasta yakınları ne hissedeceğini şaşırdı.",
")"
]
},
{
"cell_type": "code",
"execution_count": 28,
"id": "74bad0f6",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['4. Murat, diğer yazım şekli ile IV. Murat, alkollü içecekleri halka yasaklamıştı.']"
]
},
"execution_count": 28,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sentence_splitter.split_sentences(\n",
" \"4. Murat, diğer yazım şekli ile IV. Murat, alkollü içecekleri halka yasaklamıştı.\"\n",
")"
]
},
{
"cell_type": "markdown",
"id": "811c70b6",
"metadata": {},
"source": [
"#### Stopword Remover\n",
"- Static: uses pre-defined lexicon of stopwords\n",
"- Dynamic: detects stop-words regardless of language and context\n",
" - optional: can detect and drop rare-words"
]
},
{
"cell_type": "code",
"execution_count": 29,
"id": "5a902786",
"metadata": {},
"outputs": [],
"source": [
"from vnlp import StopwordRemover\n",
"\n",
"stopword_remover = StopwordRemover()"
]
},
{
"cell_type": "code",
"execution_count": 30,
"id": "c73bcf7e",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['bugün', 'kahvaltıda', 'kahve', 'çay', 'içsem', 'süt', 'içeyim']"
]
},
"execution_count": 30,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sentence = (\n",
" \"acaba bugün kahvaltıda kahve yerine çay mı içsem ya da neyse süt içeyim\"\n",
")\n",
"stopword_remover.drop_stop_words(sentence.split())"
]
},
{
"cell_type": "code",
"execution_count": 31,
"id": "21aa3dd2",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['ama', 'aşı', 'gelip', 'eve']\n"
]
}
],
"source": [
"sentence = \"ben bugün gidip aşı olacağım sonra da eve gelip telefon açacağım aşı nasıl etkiledi eve gelip anlatırım aşı olmak bu dönemde çok ama ama ama ama çok önemli\"\n",
"dynamically_detected_stop_words = (\n",
" stopword_remover.dynamically_detect_stop_words(sentence.split())\n",
")\n",
"print(dynamically_detected_stop_words)"
]
},
{
"cell_type": "code",
"execution_count": 32,
"id": "213c2717",
"metadata": {},
"outputs": [],
"source": [
"stopword_remover.add_to_stop_words(dynamically_detected_stop_words)"
]
},
{
"cell_type": "code",
"execution_count": 33,
"id": "ed3f23b1",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['önemli', 'demiş', 'miydim']"
]
},
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"stopword_remover.drop_stop_words(\"aşı olmak önemli demiş miydim\".split())"
]
},
{
"cell_type": "markdown",
"id": "7990850b",
"metadata": {},
"source": [
"#### Turkish Embeddings"
]
},
{
"cell_type": "code",
"execution_count": 34,
"id": "4a134e68",
"metadata": {},
"outputs": [],
"source": [
"from gensim.models import Word2Vec, FastText"
]
},
{
"cell_type": "code",
"execution_count": 35,
"id": "e32dcb80",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[('saruman', 0.7153398394584656),\n",
" ('geralt', 0.6540620923042297),\n",
" ('aragorn', 0.6260802149772644),\n",
" ('thorin', 0.613937258720398),\n",
" ('orklar', 0.5860564112663269),\n",
" ('gollum', 0.5781465768814087),\n",
" ('tyrion', 0.5738440155982971),\n",
" ('sauron', 0.5715942978858948),\n",
" ('frodo', 0.5662911534309387),\n",
" ('lancelot', 0.5607389211654663),\n",
" ('elfler', 0.5591437816619873),\n",
" ('bilbo', 0.5585811138153076),\n",
" ('mordor', 0.5550921559333801),\n",
" ('baggins', 0.5519346594810486),\n",
" ('belgarath', 0.5489327311515808),\n",
" ('titanlar', 0.5449507832527161),\n",
" ('bran', 0.5402933359146118),\n",
" ('asgard', 0.5372824668884277),\n",
" ('thor', 0.5362329483032227),\n",
" ('uther', 0.5343433618545532)]"
]
},
"execution_count": 35,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Word2Vec\n",
"model = Word2Vec.load(\"vnlp/turkish_word_embeddings/Word2Vec_large.model\")\n",
"model.wv.most_similar(\"gandalf\", topn=20)"
]
},
{
"cell_type": "code",
"execution_count": 36,
"id": "d09c0bac",
"metadata": {
"scrolled": true
},
"outputs": [
{
"data": {
"text/plain": [
"[('kayalardan', 0.8831543326377869),\n",
" ('tepelerden', 0.8753724694252014),\n",
" ('kayalıklardan', 0.8729402422904968),\n",
" ('ormanlardan', 0.8672202229499817),\n",
" ('dağlardan', 0.8540675044059753),\n",
" ('otlardan', 0.8288434147834778),\n",
" ('kısımlardan', 0.8267730474472046),\n",
" ('ağaçlardan', 0.8248404860496521),\n",
" ('amaçlardan', 0.8242634534835815),\n",
" ('bloklardan', 0.820052444934845),\n",
" ('adalardan', 0.8200141191482544),\n",
" ('sahalardan', 0.8146253824234009),\n",
" ('dallardan', 0.8107085824012756),\n",
" ('kuyulardan', 0.80833500623703),\n",
" ('oralardan', 0.8079319000244141),\n",
" ('tünellerden', 0.8079005479812622),\n",
" ('sulardan', 0.8050841689109802),\n",
" ('köşelerden', 0.8049306869506836),\n",
" ('tarlalardan', 0.8024468421936035),\n",
" ('pisliklerden', 0.800993025302887)]"
]
},
"execution_count": 36,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# FastText\n",
"model = Word2Vec.load(\"vnlp/turkish_word_embeddings/FastText_large.model\")\n",
"model.wv.most_similar(\"yamaçlardan\", topn=20)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.16"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
================================================
FILE: LICENSE
================================================
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
================================================
FILE: MANIFEST.in
================================================
include README.md
include LICENSE
recursive-include vnlp *.md
recursive-include vnlp *.py
recursive-include vnlp *.json
recursive-include vnlp *.txt
recursive-include vnlp *.aff
recursive-include vnlp *.dic
recursive-include vnlp *.model
================================================
FILE: README.md
================================================
<img src="https://github.com/vngrs-ai/vnlp/blob/main/img/logo.png?raw=true" width="256">
## VNLP: Turkish NLP Tools
State-of-the-art, lightweight NLP tools for Turkish language.
Developed by VNGRS.
https://vngrs.com/
[](https://badge.fury.io/py/vngrs-nlp)
[](https://pypi.org/project/vngrs-nlp/)
[](https://vnlp.readthedocs.io/)
[](https://github.com/vngrs-ai/vnlp/blob/main/LICENSE)
[](https://github.com/vngrs-ai/vnlp/actions/workflows/test.yml)
### Functionality:
- Sentence Splitter
- Normalizer
- Spelling/Typo correction
- Convert numbers to word form
- Deasciification
- Stopword Remover:
- Static
- Dynamic
- Stemmer: Morphological Analyzer & Disambiguator
- Named Entity Recognizer (NER)
- Dependency Parser
- Part of Speech (PoS) Tagger
- Sentiment Analyzer
- Turkish Word Embeddings
- FastText
- Word2Vec
- SentencePiece Unigram Tokenizer
- News Summarization
- News Paraphrasing
- Summarization and Paraphrasing models are available in the demo. Contact us at vnlp@vngrs.com for API.
### Demo:
- Try the [Demo](https://demo.vnlp.io).
### Installation
```
pip install vngrs-nlp
```
### Documentation:
- See the [Documentation](https://vnlp.readthedocs.io) for the details about usage, classes, functions, datasets and evaluation metrics.
### Metrics:
<img src="https://github.com/vngrs-ai/vnlp/blob/main/img/metrics.png?raw=true" width="600">
<img src="https://github.com/vngrs-ai/vnlp/blob/main/img/sum_metrics.png?raw=true" width="124">
### Usage Example:
**Dependency Parser**
```
from vnlp import DependencyParser
dep_parser = DependencyParser()
dep_parser.predict("Oğuz'un kırmızı bir Astra'sı vardı.")
[("Oğuz'un", 'PROPN'),
('kırmızı', 'ADJ'),
('bir', 'DET'),
("Astra'sı", 'PROPN'),
('vardı', 'VERB'),
('.', 'PUNCT')]
# Spacy's submodule Displacy can be used to visualize DependencyParser result.
import spacy
from vnlp import DependencyParser
dependency_parser = DependencyParser()
result = dependency_parser.predict("Oğuz'un kırmızı bir Astra'sı vardı.", displacy_format = True)
spacy.displacy.render(result, style="dep", manual = True)
```
<img src="https://raw.githubusercontent.com/vngrs-ai/vnlp/main/img/dp_vis_sample.png" width="512">
## Citation
```bibtex
@article{turker2024vnlp,
title={VNLP: Turkish NLP Package},
author={Turker, Meliksah and Ari, Erdi and Han, Aydin},
journal={arXiv preprint arXiv:2403.01309},
year={2024}
}
```
================================================
FILE: docs/Makefile
================================================
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = source
BUILDDIR = build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
================================================
FILE: docs/make.bat
================================================
@ECHO OFF
pushd %~dp0
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=source
set BUILDDIR=build
if "%1" == "" goto help
%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
goto end
:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
:end
popd
================================================
FILE: docs/requirements.txt
================================================
sphinx_theme
sphinx<7
================================================
FILE: docs/source/conf.py
================================================
# Configuration file for the Sphinx documentation builder.
import os
import sys
import sphinx_theme
sys.path.insert(0, os.path.abspath("../.."))
# mock deps with system level requirements.
autodoc_mock_imports = ["tensorflow"]
# -- Project information
project = "VNLP"
author = "Meliksah Turker"
release = "0.1"
version = "0.1.0"
# -- General configuration
extensions = [
"sphinx.ext.duration",
"sphinx.ext.doctest",
"sphinx.ext.autodoc",
"sphinx.ext.autosummary",
"sphinx.ext.intersphinx",
"sphinx.ext.napoleon",
"sphinx.ext.viewcode",
"sphinx.ext.todo",
"sphinx.ext.autosectionlabel",
]
# Make sure the target is unique
autosectionlabel_prefix_document = True
intersphinx_mapping = {
"python": ("https://docs.python.org/3/", None),
"sphinx": ("https://www.sphinx-doc.org/en/master/", None),
}
intersphinx_disabled_domains = ["std"]
# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", "TODO/*"]
source_suffix = [".rst", ".md"]
# -- Options for HTML output
# Stanford Theme
html_theme = "stanford_theme"
html_theme_path = [sphinx_theme.get_html_theme_path("stanford-theme")]
# sphinx readthedocs theme
# html_theme = 'sphinx_rtd_theme'
html_logo = "_static/vnlp_white.png"
# Below html_theme_options config depends on the theme.
# For Stanford theme:
# https://sphinx-rtd-theme.readthedocs.io/en/stable/configuring.html
html_theme_options = {"logo_only": True, "display_version": True}
# -- Options for EPUB output
epub_show_urls = "footnote"
================================================
FILE: docs/source/index.md
================================================
Welcome to VNLP's documentation!
===================================
**VNLP** is a Python library for developers working on Turkish NLP.
It implements the *state of the art* research papers in an efficient manner with an *intuitive* API to allow inference.
- Try the `Demo <https://demo.vnlp.io/>`_.
- See the `Official Website <https://vnlp.io/>`_.
- See the `Github <https://github.com/vngrs-ai/vnlp>`_ page.
- See the `Pypi <https://pypi.org/project/vngrs-nlp/>`_ page.
Contents
--------
.. toctree::
:maxdepth: 2
:caption: Get Started
quickstart
.. toctree::
:maxdepth: 2
:caption: Main Classes
main_classes/dependency_parser
main_classes/named_entity_recognizer
main_classes/normalizer
main_classes/part_of_speech_tagger
main_classes/sentence_splitter
main_classes/sentiment_analyzer
main_classes/stemmer_morph_analyzer
main_classes/stopword_remover
main_classes/word_embeddings
================================================
FILE: docs/source/main_classes/dependency_parser.md
================================================
Dependency Parser
----------
.. automodule:: vnlp.dependency_parser.dependency_parser
:members:
SentencePiece Unigram Context Dependency Parser
===================================
.. automodule:: vnlp.dependency_parser.spu_context_dp
:members:
Tree-stack Dependency Parser
===================================
.. automodule:: vnlp.dependency_parser.treestack_dp
:members:
================================================
FILE: docs/source/main_classes/named_entity_recognizer.md
================================================
Named Entity Recognizer
----------
.. automodule:: vnlp.named_entity_recognizer.named_entity_recognizer
:members:
SentencePiece Unigram Context Named Entity Recognizer
===================================
.. automodule:: vnlp.named_entity_recognizer.spu_context_ner
:members:
CharNER
===================================
.. automodule:: vnlp.named_entity_recognizer.charner
:members:
================================================
FILE: docs/source/main_classes/normalizer.md
================================================
Normalizer
----------
.. automodule:: vnlp.normalizer.normalizer
:members:
================================================
FILE: docs/source/main_classes/part_of_speech_tagger.md
================================================
Part of Speech Tagger
----------
.. automodule:: vnlp.part_of_speech_tagger.part_of_speech_tagger
:members:
SentencePiece Unigram Context Part of Speech Tagger
===================================
.. automodule:: vnlp.part_of_speech_tagger.spu_context_pos
:members:
Tree-stack Part of Speech Tagger
===================================
.. automodule:: vnlp.part_of_speech_tagger.treestack_pos
:members:
================================================
FILE: docs/source/main_classes/sentence_splitter.md
================================================
Sentence Splitter
----------
.. automodule:: vnlp.sentence_splitter.sentence_splitter
:members:
================================================
FILE: docs/source/main_classes/sentiment_analyzer.md
================================================
Sentiment Analyzer
----------
.. automodule:: vnlp.sentiment_analyzer.sentiment_analyzer
:members:
SentencePiece Unigram Context BiGRU Sentiment Analyzer
===================================
.. automodule:: vnlp.sentiment_analyzer.spu_context_bigru_sentiment
:members:
================================================
FILE: docs/source/main_classes/stemmer_morph_analyzer.md
================================================
Stemmer: Morphological Analyzer & Disambiguator
----------
.. automodule:: vnlp.stemmer_morph_analyzer.stemmer_morph_analyzer
:members:
================================================
FILE: docs/source/main_classes/stopword_remover.md
================================================
Stopword Remover
----------
.. automodule:: vnlp.stopword_remover.stopword_remover
:members:
================================================
FILE: docs/source/main_classes/word_embeddings.md
================================================
**Word Embeddings**
----------
- `Word2Vec <https://arxiv.org/pdf/1301.3781.pdf>`_ , `FastText <https://arxiv.org/pdf/1607.04606.pdf>`_ and `SentencePiece Unigram Tokenizer <https://arxiv.org/pdf/1808.06226.pdf>`_ and its associated Word2Vec Turkish word embeddings are trained on a corpora of 32 GBs.
- In terms Tokenization, there are two groups of word embeddings: NLTK.tokenize.TreebankWordTokenizer and SentencePiece Unigram Tokenizer.
SentencePiece Unigram Tokenizer and Word Embeddings
===================================
- Sentence Piece Unigram Tokenizer and its associated Word2Vec embeddings come in 2 sizes for each config and can be downloaded from the links below:
- **Medium Tokenizer and its Word2Vec Embeddings**:
- `Medium Tokenizer <https://vnlp-word-embeddings.s3.eu-west-1.amazonaws.com/SentencePiece_32k_Tokenizer.zip>`_ : vocabulary size: 32_000
- `Large Word2Vec embeddings <https://vnlp-word-embeddings.s3.eu-west-1.amazonaws.com/SentencePiece_32k_Word2Vec_large.zip>`_ : vector size: 256
- `Medium Word2Vec embeddings <https://vnlp-word-embeddings.s3.eu-west-1.amazonaws.com/SentencePiece_32k_Word2Vec_medium.zip>`_ : vector size: 128
- **Small Tokenizer and its Word2Vec Embeddings**:
- `Small Tokenizer <https://vnlp-word-embeddings.s3.eu-west-1.amazonaws.com/SentencePiece_16k_Tokenizer.zip>`_ : vocabulary size: 16_000
- `Large Word2Vec embeddings <https://vnlp-word-embeddings.s3.eu-west-1.amazonaws.com/SentencePiece_16k_Word2Vec_large.zip>`_ : vector size: 256
- `Medium Word2Vec embeddings <https://vnlp-word-embeddings.s3.eu-west-1.amazonaws.com/SentencePiece_16k_Word2Vec_medium.zip>`_ : vector size: 128
- Word2Vec and FastText embeddings are trained with `gensim <https://github.com/RaRe-Technologies/gensim>`_ algorithm.
- Sentence Piece Unigram tokenizer is trained with `SentencePiece <https://github.com/google/sentencepiece>`_ algorithm.
TreebankWordTokenizer tokenized Word Embeddings
===================================
- TreebankWordTokenizer tokenized Word2Vec and FastText embeddings come in 3 sizes and can be downloaded from the links below:
- **Large**:
- `Word2Vec <https://vnlp-word-embeddings.s3.eu-west-1.amazonaws.com/Word2Vec_large.zip>`_ : vocabulary size: 128_000, vector size: 256
- `FastText <https://vnlp-word-embeddings.s3.eu-west-1.amazonaws.com/FastText_large.zip>`_ : vocabulary size: 128_000, vector size: 256
- **Medium**:
- `Word2Vec <https://vnlp-word-embeddings.s3.eu-west-1.amazonaws.com/Word2Vec_medium.zip>`_ : vocabulary size: 64_000, vector size: 128
- `FastText <https://vnlp-word-embeddings.s3.eu-west-1.amazonaws.com/FastText_medium.zip>`_ : vocabulary size: 64_000, vector size: 128
- **Small**:
- `Word2Vec: <https://vnlp-word-embeddings.s3.eu-west-1.amazonaws.com/Word2Vec_small.zip>`_ : vocabulary size: 32_000, vector size: 64
- `FastText <https://vnlp-word-embeddings.s3.eu-west-1.amazonaws.com/FastText_small.zip>`_ : vocabulary size: 32_000, vector size: 64
- Usage:
>>> # Word2Vec
>>> from gensim.models import Word2Vec
>>>
>>> model = Word2Vec.load('Word2Vec_large.model')
>>> model.wv.most_similar('gandalf', topn = 10)
[('saruman', 0.7291593551635742),
('thorin', 0.6473978161811829),
('aragorn', 0.6401687264442444),
('isengard', 0.6123237013816833),
('orklar', 0.59786057472229),
('gollum', 0.5905635952949524),
('baggins', 0.5837421417236328),
('frodo', 0.5819021463394165),
('belgarath', 0.5811135172843933),
('sauron', 0.5763844847679138)]
>>> # FastText
>>> from gensim.models import FastText
>>>
>>> model = FastText.load('FastText_large.model')
>>> model.wv.most_similar('yamaçlardan', topn = 10)
[('kayalardan', 0.8601457476615906),
('kayalıklardan', 0.8567330837249756),
('tepelerden', 0.8423191905021667),
('ormanlardan', 0.8362939357757568),
('dağlardan', 0.8140010833740234),
('amaçlardan', 0.810560405254364),
('bloklardan', 0.803180992603302),
('otlardan', 0.8026642203330994),
('kısımlardan', 0.7993910312652588),
('ağaçlardan', 0.7961613535881042)]
>>> # SentencePiece Unigram Tokenizer
>>> import sentencepiece as spm
>>> sp = spm.SentencePieceProcessor('SentencePiece_16k_Tokenizer.model')
>>> tokenizer.encode_as_pieces('bilemezlerken')
['▁bile', 'mez', 'lerken']
>>> tokenizer.encode_as_ids('bilemezlerken')
[180, 1200, 8167]
- For more details about corpora, preprocessing and training, see `ReadMe <https://github.com/vngrs-ai/VNLP/blob/main/vnlp/turkish_word_embeddings/ReadMe.md>`_.
================================================
FILE: docs/source/quickstart.md
================================================
Quickstart
===================================
Installation
------------
Installation is possible via pip.
.. code-block:: console
$ pip install vngrs-nlp
Usage
----------------
VNLP provides 2 very intuitive and simple API options.
Python API
----------------
You can simply import, initialize and predict!
For example:
>>> from vnlp import NamedEntityRecognizer
>>> ner = NamedEntityRecognizer()
>>> ner.predict("Ben Melikşah, 29 yaşındayım, İstanbul'da ikamet ediyorum ve VNGRS AI Takımı'nda çalışıyorum.")
[('Ben', 'O'),
('Melikşah', 'PER'),
(',', 'O'),
('29', 'O'),
('yaşındayım', 'O'),
(',', 'O'),
('İstanbul', 'LOC'),
("'", 'O'),
('da', 'O'),
('ikamet', 'O'),
('ediyorum', 'O'),
('ve', 'O'),
('VNGRS', 'ORG'),
('AI', 'ORG'),
('Takımı', 'ORG'),
("'", 'O'),
('nda', 'O'),
('çalışıyorum', 'O'),
('.'), 'O']
- See Main Classes in :ref:`index:Contents` for the rest of the functionality.
Command Line API
----------------
Command Line API is even simpler than Python API!
The format is
.. code-block:: console
$ vnlp --task TASK_NAME --text INPUT_TEXT
Example:
.. code-block:: console
$ vnlp --task sentiment_analysis --text "Sipariş geldiğinde biz karnımızı çoktan atıştırmalıklarla doyurmuştuk."
0
To list available tasks/functionality:
.. code-block:: console
$ vnlp --list_tasks
# List of available tasks:
stemming_morph_analysis
named_entity_recognition
dependency_parsing
part_of_speech_tagging
sentiment_analysis
split_sentences
correct_typos
convert_numbers_to_words
deasciify
lower_case
remove_punctuations
remove_accent_marks
drop_stop_words
================================================
FILE: pyproject.toml
================================================
[build-system]
build-backend = "setuptools.build_meta"
requires = ["setuptools", "wheel"]
[tool.black]
line-length = 79
include = '\.pyi?$'
exclude = '''
/(
\.git
| \.hg
| \.mypy_cache
| \.tox
| \.venv
| docs
| img
| _build
| buck-out
| build
| dist
)/
'''
================================================
FILE: setup.cfg
================================================
[metadata]
description-file=README.md
license_files=LICENSE
================================================
FILE: setup.py
================================================
from setuptools import setup, find_packages
with open("README.md", "r", encoding="utf-8") as readme_file:
README = readme_file.read()
setup(
name="vngrs-nlp",
version="0.2.4",
description="Turkish NLP Tools developed by VNGRS.",
long_description=README,
long_description_content_type="text/markdown",
author="Meliksah Turker",
author_email="turkermeliksah@hotmail.com",
license="GNU Affero General Public License v3.0",
classifiers=[
"Development Status :: 3 - Alpha",
# Indicate who your project is intended for
"Intended Audience :: Developers",
"Intended Audience :: Education",
"Intended Audience :: Science/Research",
"Intended Audience :: Information Technology",
"Topic :: Scientific/Engineering",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
"Topic :: Scientific/Engineering :: Information Analysis",
"Topic :: Text Processing",
"Topic :: Text Processing :: Linguistic",
"Topic :: Software Development",
"Topic :: Software Development :: Libraries",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11"
],
project_urls={
"Homepage": "https://github.com/vngrs-ai/vnlp",
"Documentation": "https://vnlp.readthedocs.io/en/latest/",
"Website": "https://vnlp.io",
},
packages=find_packages(exclude=["turkish_embeddings"]),
include_package_data=True,
install_requires=[
'tensorflow<2.6.0; python_version < "3.8"',
'tensorflow>=2.6,<2.16; python_version >= "3.8"',
"regex",
"requests",
"sentencepiece",
],
extras_require={"extras": ["gensim", "spacy"], "develop": ["pre-commit", "pytest"]},
entry_points={"console_scripts": ["vnlp=vnlp.bin.vnlp:main"]},
)
================================================
FILE: tests/test_general.py
================================================
import unittest
from vnlp import (
DependencyParser,
PoSTagger,
NamedEntityRecognizer,
StemmerAnalyzer,
SentimentAnalyzer,
Normalizer,
StopwordRemover,
)
class StemmerTest(unittest.TestCase):
def setUp(self):
self.analyzer = StemmerAnalyzer()
def test_predict_1(self):
res = self.analyzer.predict(
"Üniversite sınavlarına canla başla çalışıyorlardı."
)
expected = [
"üniversite+Noun+A3sg+Pnon+Nom",
"sınav+Noun+A3pl+P3sg+Dat",
"can+Noun+A3sg+Pnon+Ins",
"baş+Noun+A3sg+Pnon+Ins",
"çalış+Verb+Pos+Prog1+A3pl+Past",
".+Punc",
]
self.assertEqual(res, expected)
def test_predict_2(self):
res = self.analyzer.predict("Şimdi baştan başla.")
expected = [
"şimdi+Adverb",
"baş+Noun+A3sg+Pnon+Abl",
"başla+Verb+Pos+Imp+A2sg",
".+Punc",
]
self.assertEqual(res, expected)
class NerTest(unittest.TestCase):
def setUp(self):
self.ner = NamedEntityRecognizer()
def test_predict_1(self):
res = self.ner.predict(
"Benim adım Melikşah, 29 yaşındayım, İstanbul'da ikamet ediyorum ve VNGRS AI Takımı'nda çalışıyorum."
)
expected = [
("Benim", "O"),
("adım", "O"),
("Melikşah", "PER"),
(",", "O"),
("29", "O"),
("yaşındayım", "O"),
(",", "O"),
("İstanbul'da", "LOC"),
("ikamet", "O"),
("ediyorum", "O"),
("ve", "O"),
("VNGRS", "ORG"),
("AI", "ORG"),
("Takımı'nda", "ORG"),
("çalışıyorum", "O"),
(".", "O"),
]
self.assertEqual(res, expected)
class PoSTest(unittest.TestCase):
def setUp(self):
self.pos_tagger = PoSTagger()
def test_predict_1(self):
res = self.pos_tagger.predict("Oğuz'un kırmızı bir Astra'sı vardı.")
expected = [
("Oğuz'un", "PROPN"),
("kırmızı", "ADJ"),
("bir", "DET"),
("Astra'sı", "PROPN"),
("vardı", "VERB"),
(".", "PUNCT"),
]
self.assertEqual(res, expected)
class DependencyParserTest(unittest.TestCase):
def setUp(self):
self.dep_parser = DependencyParser()
def test_predict_1(self):
res = self.dep_parser.predict(
"Onun için yol arkadaşlarımızı titizlikle seçer, kendilerini iyice sınarız."
)
expected = [
(1, "Onun", 6, "obl"),
(2, "için", 1, "case"),
(3, "yol", 4, "nmod"),
(4, "arkadaşlarımızı", 6, "obj"),
(5, "titizlikle", 6, "obl"),
(6, "seçer", 10, "parataxis"),
(7, ",", 6, "punct"),
(8, "kendilerini", 10, "obj"),
(9, "iyice", 10, "advmod"),
(10, "sınarız", 0, "root"),
(11, ".", 10, "punct"),
]
self.assertEqual(res, expected)
class SentimentAnalyzerTester(unittest.TestCase):
def setUp(self):
self.sentiment_analyzer = SentimentAnalyzer()
def test_predicts(self):
_places = 1 # 1 decimal places is enough for this test
_msg = "Sentiment analyzer results could change if the model is updated. Please check the results manually and replace the values if necessary."
self.assertAlmostEqual(
self.sentiment_analyzer.predict_proba(
"Zeynep'in okul taksitini Bürokratistan'daki Parabank'tan yatırdım."
),
0.98,
places=_places,
msg=_msg,
)
self.assertAlmostEqual(
self.sentiment_analyzer.predict_proba(
"Sipariş geldiğinde biz karnımızı çoktan atıştırmalıklarla doyurmuştuk."
),
0.08,
places=_places,
msg=_msg,
)
self.assertAlmostEqual(
self.sentiment_analyzer.predict_proba(
"Servis daha iyi olabilirdi ama lezzet ve hız geçer not aldı."
),
1.00,
places=_places,
msg=_msg,
)
self.assertAlmostEqual(
self.sentiment_analyzer.predict_proba("Mutlu değilim diyemem."),
0.85,
places=_places,
msg=_msg,
)
self.assertAlmostEqual(
self.sentiment_analyzer.predict_proba(
"Geçmesin günümüz sevgilim yasla, o güzel başını göğsüme yasla."
),
0.99,
places=_places,
msg=_msg,
)
class NormalizerTester(unittest.TestCase):
def setUp(self):
self.normalizer = Normalizer()
"""
# Commented for now until spelling is re-implemented.
def test_correct_typos(self):
self.assertEqual(
self.normalizer.correct_typos("kassıtlı yazım hatası ekliyorumm"),
"kasıtlı yazım hatası ekliyorum",
)
"""
def test_convert_number_to_words(self):
self.assertEqual(
self.normalizer.convert_numbers_to_words(
"sabah 2 yumurta yedim ve tartıldığımda 1,15 kilogram aldığımı gördüm".split()
),
[
"sabah",
"iki",
"yumurta",
"yedim",
"ve",
"tartıldığımda",
"bir",
"virgül",
"on",
"beş",
"kilogram",
"aldığımı",
"gördüm",
],
)
def test_deasciify(self):
self.assertEqual(
self.normalizer.deasciify("boyle sey gormedim duymadim".split()),
["böyle", "şey", "görmedim", "duymadım"],
)
self.assertEqual(
self.normalizer.deasciify("yatirdim".split()), ["yatırdım"]
)
def test_misc(self):
self.assertEqual(
self.normalizer.lower_case("Test karakterleri: İIĞÜÖŞÇ"),
"test karakterleri: iığüöşç",
)
self.assertEqual(
self.normalizer.remove_punctuations(
"noktalamalı test cümlesidir..."
),
"noktalamalı test cümlesidir",
)
self.assertEqual(
self.normalizer.remove_accent_marks("merhâbâ gûzel yîlkî atî"),
"merhaba guzel yılkı atı",
)
class StopwordRemoverTest(unittest.TestCase):
def setUp(self):
self.stopword_remover = StopwordRemover()
def test_remove_stopwords(self):
self.assertEqual(
self.stopword_remover.drop_stop_words(
"acaba bugün kahvaltıda kahve yerine çay mı içsem ya da neyse süt içeyim".split()
),
["bugün", "kahvaltıda", "kahve", "çay", "içsem", "süt", "içeyim"],
)
def test_dynamic_stopwords(self):
dsw = self.stopword_remover.dynamically_detect_stop_words(
"ben bugün gidip aşı olacağım sonra da eve gelip telefon açacağım aşı nasıl etkiledi eve gelip anlatırım aşı olmak bu dönemde çok ama ama ama ama çok önemli".split()
)
expected = ['ama', 'aşı', 'çok', 'eve', 'gelip']
# Converted to set since order is not stable
self.assertEqual(set(dsw), set(expected))
self.stopword_remover.add_to_stop_words(dsw)
self.assertEqual(
self.stopword_remover.drop_stop_words(
"aşı olmak önemli demiş miydim".split()
),
["önemli", "demiş", "miydim"],
)
if __name__ == "__main__":
unittest.main()
================================================
FILE: vnlp/__init__.py
================================================
import os
import tensorflow as tf
from .dependency_parser import DependencyParser
from .named_entity_recognizer import NamedEntityRecognizer
from .normalizer import Normalizer
from .part_of_speech_tagger import PoSTagger
from .sentence_splitter import SentenceSplitter
from .sentiment_analyzer import SentimentAnalyzer
from .stemmer_morph_analyzer import StemmerAnalyzer
from .stopword_remover import StopwordRemover
# Suppress tensorflow warnings
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
# Prevent tensorflow from allocating whole GPU memory.
gpus = tf.config.experimental.list_physical_devices("GPU")
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
__all__ = [
"DependencyParser",
"NamedEntityRecognizer",
"Normalizer",
"PoSTagger",
"SentenceSplitter",
"SentimentAnalyzer",
"StemmerAnalyzer",
"StopwordRemover",
]
================================================
FILE: vnlp/bin/__init__.py
================================================
================================================
FILE: vnlp/bin/vnlp.py
================================================
import argparse
import os
from vnlp import (
StemmerAnalyzer,
NamedEntityRecognizer,
DependencyParser,
PoSTagger,
SentimentAnalyzer,
SentenceSplitter,
Normalizer,
StopwordRemover,
)
# To suppress tensorflow warnings such as below:
"""
This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN)
to use the following CPU instructions in performance-critical operations:
AVX2 FMA To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:176]
None of the MLIR Optimization Passes are enabled (registered 2)
"""
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
def main():
list_tasks = "\
# List of available tasks:\n\
stemming_morph_analysis\n\
named_entity_recognition\n\
dependency_parsing\n\
part_of_speech_tagging\n\
sentiment_analysis\n\
split_sentences\n\
correct_typos\n\
convert_numbers_to_words\n\
deasciify\n\
lower_case\n\
remove_punctuations\n\
remove_accent_marks\n\
drop_stop_words\n\
"
example_usage = '\
$ vnlp --task stemming_morph_analysis --text "Üniversite sınavlarına canla başla çalışıyorlardı."\n\
$ vnlp --task correct_typos --text "kassıtlı yaezım hatasssı ekliyorumm"\
'
parser = argparse.ArgumentParser()
parser.add_argument(
"--task",
type=str,
action="store",
help="Task to be performed on text, e.g: sentiment_analysis",
)
parser.add_argument(
"--text", type=str, action="store", help="Input text to be processed"
)
parser.add_argument(
"--list_tasks",
action="store_true",
help="Lists available tasks/functions",
)
parser.add_argument(
"--example_usage", action="store_true", help="Shows usage examples"
)
args = parser.parse_args()
task = args.task
input_text = args.text
if args.list_tasks:
print(list_tasks)
return
if args.example_usage:
print(example_usage)
return
elif task == "stemming_morph_analysis":
stemmer_analyzer = StemmerAnalyzer()
result = stemmer_analyzer.predict(input_text)
elif task == "named_entity_recognition":
ner = NamedEntityRecognizer()
result = ner.predict(input_text)
elif task == "dependency_parsing":
dependency_parser = DependencyParser()
result = dependency_parser.predict(input_text)
elif task == "part_of_speech_tagging":
pos_tagger = PoSTagger()
result = pos_tagger.predict(input_text)
elif task == "sentiment_analysis":
sentiment_analyzer = SentimentAnalyzer()
result = str(sentiment_analyzer.predict(input_text))
elif task == "split_sentences":
sentence_splitter = SentenceSplitter()
result = sentence_splitter.split_sentences(input_text)
elif task == "correct_typos":
normalizer = Normalizer()
result_as_list = normalizer.correct_typos(input_text.split())
result = " ".join(result_as_list)
elif task == "convert_numbers_to_words":
normalizer = Normalizer()
result_as_list = normalizer.convert_numbers_to_words(
input_text.split()
)
result = " ".join(result_as_list)
elif task == "deasciify":
result_as_list = Normalizer.deasciify(input_text.split())
result = " ".join(result_as_list)
elif task == "lower_case":
result = Normalizer.lower_case(input_text)
elif task == "remove_punctuations":
result = Normalizer.remove_punctuations(input_text)
elif task == "remove_accent_marks":
result = Normalizer.remove_accent_marks(input_text)
elif task == "drop_stop_words":
stopword_remover = StopwordRemover()
result_as_list = stopword_remover.drop_stop_words(input_text.split())
result = " ".join(result_as_list)
return result
if __name__ == "__main__":
main()
================================================
FILE: vnlp/dependency_parser/ReadMe.md
================================================
### Dependency Parser
- Dependency Parser implementations of VNLP.
- Details of each model are provided below.
- Input data is processed by NLTK.tokenize.TreebankWordTokenizer.
- Training data can be accessed at: https://lindat.mff.cuni.cz/repository/xmlui/handle/11234/1-4611 .
- In order to evaluate, initialize the class with "evaluate = True" argument. This will load the model weights that are not trained on test sets.
#### SPUContext Dependency Parser
- This is a context aware Dependency Parser that uses SentencePiece Unigram tokenizer and pre-trained Word2Vec embeddings.
- It achieves 0.7117 LAS (Labeled Attachment Score) and 0.8370 UAS (Unlabeled Attachment Score) on all of test sets of Universal Dependencies 2.9.
- UD 2.9 consists of below datasets with evaluation metrics on each one's test set:
- UD_Turkish-Atis: LAS: 0.8852 UAS: 0.9154
- UD_Turkish-BOUN: LAS: 0.6764 UAS: 0.7815
- UD_Turkish-FrameNet: 0.8112 UAS: 0.9230
- UD_Turkish-GB: 0.7297 UAS: 0.8858
- UD_Turkish-IMST: 0.6332 UAS: 0.7653
- UD_Turkish-Kenet: 0.688 UAS: 0.8351
- UD_Turkish-Penn: 0.7072 UAS: 0.8524
- UD_Turkish-PUD: 0.6131 UAS: 0.7477
- UD_Turkish-Tourism: 0.9096 UAS: 0.9731
- UD_Turkish_German-SAGT: This is skipped since it contains lots of non-Turkish tokens.
- After development phase, final model in the repository is trained with all of train, dev and test data for 50 epochs.
- Starting with 0.001 learning rate, lr decay of 0.95 is used after the 5th epoch.
#### TreeStack Dependency Parser
- This dependency parser is inspired by "Tree-stack LSTM in Transition Based Dependency Parsing",
which can be found here: https://aclanthology.org/K18-2012/ .
- "Inspire" is emphasized because this implementation uses the approach of using Morphological Tags, Pre-trained word embeddings and POS tags as input for the model, rather than implementing the exact network proposed in the paper.
- The model uses pre-trained Word2Vec_medium embeddings which is also a part of this project.
- The model also uses pre-trained Morphological Tag embeddings, extracted from StemmerAnalyzer's neural network model.
- It achieves 0.6914 LAS (Labeled Attachment Score) and 0.8048 UAS (Unlabeled Attachment Score) on all of test sets of Universal Dependencies 2.9.
- UD 2.9 consists of below datasets with evaluation metrics on each one's test set:
- UD_Turkish-Atis: LAS: 0.8378 - UAS: 0.874
- UD_Turkish-BOUN: LAS: 0.6365 - UAS: 0.7290
- UD_Turkish-FrameNet: LAS: 0.8098 - UAS: 0.9148
- UD_Turkish-GB: LAS: 0.7526 - UAS: 0.8897
- UD_Turkish-IMST: LAS: 0.6032 - UAS: 0.7171
- UD_Turkish-Kenet: LAS: 0.6565 - UAS: 0.7959
- UD_Turkish-Penn: LAS: 0.6735 - UAS: 0.8036
- UD_Turkish-PUD: LAS: 0.5792 - UAS: 0.7024
- UD_Turkish-Tourism: LAS: 0.9134 - UAS: 0.9693
- UD_Turkish_German-SAGT: This is skipped since it contains lots of non-Turkish tokens.
- After development phase, final model in the repository is trained with all of train, dev and test data for 20 epochs.
- Starting with 0.001 learning rate, lr decay of 0.95 is used after the 5th epoch.
================================================
FILE: vnlp/dependency_parser/__init__.py
================================================
from .dependency_parser import DependencyParser
__all__ = ["DependencyParser"]
================================================
FILE: vnlp/dependency_parser/_spu_context_utils.py
================================================
import tensorflow as tf
import numpy as np
from ..utils import create_rnn_stacks, process_word_context
TOKEN_PIECE_MAX_LEN = 8 # 0.9995 quantile is 8 for 16k_vocab, 7 for 32k_vocab
SENTENCE_MAX_LEN = 40 # 0.998 quantile is 42
def create_spucontext_dp_model(
TOKEN_PIECE_MAX_LEN,
SENTENCE_MAX_LEN,
VOCAB_SIZE,
ARC_LABEL_VECTOR_LEN,
WORD_EMBEDDING_DIM,
WORD_EMBEDDING_MATRIX,
NUM_RNN_UNITS,
NUM_RNN_STACKS,
FC_UNITS_MULTIPLIER,
DROPOUT,
):
# Current Word
# WORD_RNN is common model for processing all word tokens
word_rnn = tf.keras.models.Sequential(name="WORD_RNN")
word_rnn.add(tf.keras.layers.InputLayer(input_shape=(TOKEN_PIECE_MAX_LEN)))
word_rnn.add(
tf.keras.layers.Embedding(
input_dim=VOCAB_SIZE,
output_dim=WORD_EMBEDDING_DIM,
embeddings_initializer=tf.keras.initializers.Constant(
WORD_EMBEDDING_MATRIX
),
trainable=False,
name="WORD_EMBEDDING",
)
)
word_rnn.add(create_rnn_stacks(NUM_RNN_STACKS, NUM_RNN_UNITS, DROPOUT))
# Left Context Words
left_context_rnn = tf.keras.models.Sequential(name="LEFT_CONTEXT_RNN")
left_context_rnn.add(
tf.keras.layers.InputLayer(
input_shape=(SENTENCE_MAX_LEN, TOKEN_PIECE_MAX_LEN)
)
)
left_context_rnn.add(tf.keras.layers.TimeDistributed(word_rnn))
left_context_rnn.add(
create_rnn_stacks(NUM_RNN_STACKS, NUM_RNN_UNITS, DROPOUT)
)
# Right Context Words
right_context_rnn = tf.keras.models.Sequential(name="RIGHT_CONTEXT_RNN")
right_context_rnn.add(
tf.keras.layers.InputLayer(
input_shape=(SENTENCE_MAX_LEN, TOKEN_PIECE_MAX_LEN)
)
)
right_context_rnn.add(tf.keras.layers.TimeDistributed(word_rnn))
right_context_rnn.add(
create_rnn_stacks(
NUM_RNN_STACKS, NUM_RNN_UNITS, DROPOUT, GO_BACKWARDS=True
)
)
# Previously Processed (Left) Arc-Labels
lc_arc_label_rnn = tf.keras.models.Sequential(name="PREV_ARC_LABEL_RNN")
lc_arc_label_rnn.add(
tf.keras.layers.InputLayer(
input_shape=(SENTENCE_MAX_LEN, ARC_LABEL_VECTOR_LEN)
)
)
lc_arc_label_rnn.add(
create_rnn_stacks(NUM_RNN_STACKS, NUM_RNN_UNITS, DROPOUT)
)
# FC Layers
current_left_right_concat = tf.keras.layers.Concatenate()(
[
word_rnn.output,
left_context_rnn.output,
right_context_rnn.output,
lc_arc_label_rnn.output,
]
)
fc_layer_one = tf.keras.layers.Dense(
NUM_RNN_UNITS * FC_UNITS_MULTIPLIER[0], activation="relu"
)(current_left_right_concat)
fc_layer_one = tf.keras.layers.Dropout(DROPOUT)(fc_layer_one)
fc_layer_two = tf.keras.layers.Dense(
NUM_RNN_UNITS * FC_UNITS_MULTIPLIER[1], activation="relu"
)(fc_layer_one)
fc_layer_two = tf.keras.layers.Dropout(DROPOUT)(fc_layer_two)
arc_label_output = tf.keras.layers.Dense(
ARC_LABEL_VECTOR_LEN, activation="sigmoid"
)(fc_layer_two)
dp_model = tf.keras.models.Model(
inputs=[
word_rnn.input,
left_context_rnn.input,
right_context_rnn.input,
lc_arc_label_rnn.input,
],
outputs=[arc_label_output],
)
return dp_model
def vectorize_arc_label(w, arcs, labels, sentence_max_len, tokenizer_label):
arc = arcs[w]
label = labels[w]
arc_vector = tf.keras.utils.to_categorical(
arc, num_classes=sentence_max_len + 1
)
label_vector = tf.keras.utils.to_categorical(
label, num_classes=len(tokenizer_label.word_index) + 1
)
arc_label_vector = np.array(arc_vector.tolist() + label_vector.tolist())
return arc_label_vector
def process_single_word_input(
w,
tokenized_sentence,
spu_tokenizer_word,
tokenizer_label,
arc_label_vector_len,
arcs,
labels,
):
(
current_word_processed,
left_context_words_processed,
right_context_words_processed,
) = process_word_context(
w,
tokenized_sentence,
spu_tokenizer_word,
SENTENCE_MAX_LEN,
TOKEN_PIECE_MAX_LEN,
)
left_context_arc_label_vectors = []
# Pad Left Context Arc Label Vectors
for _ in range(SENTENCE_MAX_LEN - w):
left_context_arc_label_vectors.append(np.zeros(arc_label_vector_len))
for w_ in range(w):
left_context_arc_label_vectors.append(
vectorize_arc_label(
w_, arcs, labels, SENTENCE_MAX_LEN, tokenizer_label
)
)
left_context_arc_label_vectors = np.array(left_context_arc_label_vectors)
# Expand dims for sequence processing with batch_size = 1
current_word_processed = np.expand_dims(current_word_processed, axis=0)
left_context_words_processed = np.expand_dims(
left_context_words_processed, axis=0
)
right_context_words_processed = np.expand_dims(
right_context_words_processed, axis=0
)
left_context_arc_label_vectors = np.expand_dims(
left_context_arc_label_vectors, axis=0
)
return (
current_word_processed,
left_context_words_processed,
right_context_words_processed,
left_context_arc_label_vectors,
)
================================================
FILE: vnlp/dependency_parser/_treestack_utils.py
================================================
import numpy as np
import tensorflow as tf
from ..normalizer import Normalizer
sentence_max_len = 40
tag_max_len = 15
num_unq_labels = 48 # len(tokenizer_label.word_index)
num_unq_pos_tags = 17 # len(tokenizer_pos.word_index)
def create_dependency_parser_model(
word_embedding_vocab_size,
word_embedding_vector_size,
word_embedding_matrix,
pos_vocab_size,
pos_embedding_vector_size,
sentence_max_len,
tag_max_len,
arc_label_vector_len,
num_rnn_stacks,
tag_num_rnn_units,
lc_num_rnn_units,
lc_arc_label_num_rnn_units,
rc_num_rnn_units,
dropout,
tag_embedding_matrix,
fc_units_multipliers,
):
word_embedding_layer = tf.keras.layers.Embedding(
input_dim=word_embedding_vocab_size,
output_dim=word_embedding_vector_size,
embeddings_initializer=tf.keras.initializers.Constant(
word_embedding_matrix
),
trainable=False,
)
pos_embedding_layer = tf.keras.layers.Embedding(
input_dim=pos_vocab_size + 1, output_dim=pos_embedding_vector_size
)
# ===============================================
# CURRENT WORD
# Word
word_input = tf.keras.layers.Input(shape=(1))
word_embedded_ = word_embedding_layer(
word_input
) # shape: (None, 1, embed_size)
word_embedded = tf.keras.backend.squeeze(
word_embedded_, axis=1
) # shape: (None, embed_size)
# Tag
# Transferred from learned weights of StemmerAnalyzer - Morphological Disambiguator
# tag_embedding_matrix = sa.model.layers[5].weights[0].numpy().copy() # shape: (127, 32)
tag_vocab_size = tag_embedding_matrix.shape[0]
tag_embed_size = tag_embedding_matrix.shape[1]
tag_input = tf.keras.layers.Input(shape=(tag_max_len))
tag_embedding_layer = tf.keras.layers.Embedding(
input_dim=tag_vocab_size,
output_dim=tag_embed_size,
weights=[tag_embedding_matrix],
trainable=False,
)
tag_embedded = tag_embedding_layer(tag_input)
tag_rnn = tf.keras.models.Sequential()
for n in range(num_rnn_stacks - 1):
tag_rnn.add(
tf.keras.layers.GRU(tag_num_rnn_units, return_sequences=True)
)
tag_rnn.add(tf.keras.layers.Dropout(dropout))
tag_rnn.add(tf.keras.layers.GRU(tag_num_rnn_units))
tag_rnn.add(tf.keras.layers.Dropout(dropout))
tag_rnn_output = tag_rnn(tag_embedded)
# Pos
pos_input = tf.keras.layers.Input(shape=(1))
pos_embedded_ = pos_embedding_layer(pos_input)
pos_embedded = tf.keras.backend.squeeze(pos_embedded_, axis=1)
word_tag_pos_concatanated = tf.keras.layers.Concatenate()(
[word_embedded, tag_rnn_output, pos_embedded]
)
# ===============================================
# LEFT CONTEXT
# Left Context Word
left_context_word_input = tf.keras.layers.Input(shape=(sentence_max_len))
left_context_word_embedded = word_embedding_layer(left_context_word_input)
# Left Context Tags
left_context_tag_input = tf.keras.layers.Input(
shape=(sentence_max_len, tag_max_len)
)
left_context_tag_embedded = tag_embedding_layer(left_context_tag_input)
left_context_td_tag_rnn_output = tf.keras.layers.TimeDistributed(
tag_rnn, input_shape=(sentence_max_len, tag_max_len, tag_embed_size)
)(left_context_tag_embedded)
# Left Context POS Tags
left_context_pos_input = tf.keras.layers.Input(shape=(sentence_max_len))
left_context_pos_embedded = pos_embedding_layer(left_context_pos_input)
left_context_word_td_tags_pos_concatenated = tf.keras.layers.Concatenate()(
[
left_context_word_embedded,
left_context_td_tag_rnn_output,
left_context_pos_embedded,
]
)
# Left Context Word-Tag-POS Final RNN (Left to Right)
lc_rnn = tf.keras.models.Sequential()
for n in range(num_rnn_stacks - 1):
lc_rnn.add(
tf.keras.layers.GRU(lc_num_rnn_units, return_sequences=True)
)
lc_rnn.add(tf.keras.layers.Dropout(dropout))
lc_rnn.add(tf.keras.layers.GRU(lc_num_rnn_units))
lc_rnn.add(tf.keras.layers.Dropout(dropout))
lc_output = lc_rnn(left_context_word_td_tags_pos_concatenated)
# Left-Context Arc-Label (previously processed tokens' arc-label results)
lc_arc_label_input = tf.keras.layers.Input(
shape=(sentence_max_len, arc_label_vector_len)
)
lc_arc_label_rnn = tf.keras.models.Sequential()
for n in range(num_rnn_stacks - 1):
lc_arc_label_rnn.add(
tf.keras.layers.GRU(
lc_arc_label_num_rnn_units, return_sequences=True
)
)
lc_arc_label_rnn.add(tf.keras.layers.Dropout(dropout))
lc_arc_label_rnn.add(tf.keras.layers.GRU(lc_arc_label_num_rnn_units))
lc_arc_label_rnn.add(tf.keras.layers.Dropout(dropout))
lc_arc_label_rnn_output = lc_arc_label_rnn(lc_arc_label_input)
# ===============================================
# RIGHT CONTEXT
# Right Context Word
right_context_word_input = tf.keras.layers.Input(shape=(sentence_max_len))
right_context_word_embedded = word_embedding_layer(
right_context_word_input
)
# Right Context Tags
right_context_tag_input = tf.keras.layers.Input(
shape=(sentence_max_len, tag_max_len)
)
right_context_tag_embedded = tag_embedding_layer(right_context_tag_input)
# Right Context POS Tags
right_context_pos_input = tf.keras.layers.Input(shape=(sentence_max_len))
right_context_pos_embedded = pos_embedding_layer(right_context_pos_input)
right_context_td_tag_rnn_output = tf.keras.layers.TimeDistributed(
tag_rnn, input_shape=(sentence_max_len, tag_max_len, tag_embed_size)
)(right_context_tag_embedded)
right_context_word_td_tags_pos_concatenated = (
tf.keras.layers.Concatenate()(
[
right_context_word_embedded,
right_context_td_tag_rnn_output,
right_context_pos_embedded,
]
)
)
# Right Context Word-Tag-POS Final RNN (Right to Left)
rc_rnn = tf.keras.models.Sequential()
for n in range(num_rnn_stacks - 1):
rc_rnn.add(
tf.keras.layers.GRU(
rc_num_rnn_units, return_sequences=True, go_backwards=True
)
) # Right to Left!
rc_rnn.add(tf.keras.layers.Dropout(dropout))
rc_rnn.add(tf.keras.layers.GRU(rc_num_rnn_units, go_backwards=True))
rc_rnn.add(tf.keras.layers.Dropout(dropout))
rc_output = rc_rnn(right_context_word_td_tags_pos_concatenated)
current_left_right_concat = tf.keras.layers.Concatenate()(
[
word_tag_pos_concatanated,
lc_output,
lc_arc_label_rnn_output,
rc_output,
]
)
# ===============================================
# FC LAYERS
fc_layer_one = tf.keras.layers.Dense(
tag_num_rnn_units * fc_units_multipliers[0], activation="relu"
)(current_left_right_concat)
fc_layer_one = tf.keras.layers.Dropout(dropout)(fc_layer_one)
fc_layer_two = tf.keras.layers.Dense(
tag_num_rnn_units * fc_units_multipliers[1], activation="relu"
)(fc_layer_one)
fc_layer_two = tf.keras.layers.Dropout(dropout)(fc_layer_two)
arc_label_output = tf.keras.layers.Dense(
arc_label_vector_len, activation="sigmoid"
)(fc_layer_two)
model = tf.keras.models.Model(
inputs=[
word_input,
tag_input,
pos_input,
left_context_word_input,
left_context_tag_input,
left_context_pos_input,
lc_arc_label_input,
right_context_word_input,
right_context_tag_input,
right_context_pos_input,
],
outputs=[arc_label_output],
)
return model
def preprocess_word(word):
word = word.replace("’", "'")
word = Normalizer.lower_case(word)
word = convert_numbers_to_zero(word)
return word
def process_single_word_input(
t,
whole_words_in_sentence,
sentence_analysis_result,
sentence_max_len,
tag_max_len,
arc_label_vector_len,
tokenizer_word,
tokenizer_tag,
tokenizer_label,
tokenizer_pos,
arcs,
labels,
pos_tags,
word_form,
):
num_tokens_in_sentence = len(sentence_analysis_result)
analysis_result = sentence_analysis_result[t]
word_and_tags = analysis_result.split("+")
stems = [
analysis_result.split("+")[0]
for analysis_result in sentence_analysis_result
]
# In case a word does not exist in tokenizer_word dict,
# its stem is used instead of an OOV token.
# vice versa for stem case: in case a stem is not recognized
# whole word is used
if word_form == "stem":
words = []
for stem, whole_word in zip(stems, whole_words_in_sentence):
# use whole_word only if stem is not in vocab, but whole_word IS in vocab
# otherwise use stem anyway
if (not (stem in tokenizer_word.word_index)) and (
whole_word in tokenizer_word.word_index
):
words.append(whole_word)
else:
words.append(stem)
elif word_form == "whole":
words = []
for whole_word, stem in zip(whole_words_in_sentence, stems):
# use stem only if whole_word is not in vocab, but stem IS in vocab
# otherwise use whole_word anyway (can benefit FastText or similar morphological embedding in future)
if (not (whole_word in tokenizer_word.word_index)) and (
stem in tokenizer_word.word_index
):
words.append(stem)
else:
words.append(whole_word)
words = [preprocess_word(word) for word in words]
word = words[t]
word = tokenizer_word.texts_to_sequences(
[[word]]
) # this wont have padding
tags = word_and_tags[1:]
tags = tokenizer_tag.texts_to_sequences([tags])
tags = tf.keras.preprocessing.sequence.pad_sequences(
tags, maxlen=tag_max_len, padding="pre"
)[0]
pos_tags = tokenizer_pos.texts_to_sequences([pos_tags])[0]
pos = pos_tags[t]
# ===============================================
# Left Context
if t == 0: # there's no left context yet
left_context_words = np.zeros(sentence_max_len)
left_context_tags = np.zeros((sentence_max_len, tag_max_len))
left_context_pos_tags = np.zeros(sentence_max_len)
left_context_arc_label_vectors = np.zeros(
(sentence_max_len, arc_label_vector_len)
)
else:
left_context_words = words[:t]
left_context_words = tokenizer_word.texts_to_sequences(
[left_context_words]
)
left_context_words = tf.keras.preprocessing.sequence.pad_sequences(
left_context_words,
maxlen=sentence_max_len,
truncating="pre",
padding="pre",
)[0]
left_context_tags = [
analysis_result.split("+")[1:]
for analysis_result in sentence_analysis_result[:t]
]
left_context_tags = tokenizer_tag.texts_to_sequences(left_context_tags)
left_context_tags = tf.keras.preprocessing.sequence.pad_sequences(
left_context_tags, maxlen=tag_max_len, padding="pre"
)
left_context_pos_tags = pos_tags[:t]
left_context_pos_tags = tf.keras.preprocessing.sequence.pad_sequences(
[left_context_pos_tags], maxlen=sentence_max_len, padding="pre"
)
left_context_arcs = arcs[:t]
left_context_labels = labels[:t]
left_context_arc_label_vectors = []
for left_context_arc_, left_context_label_ in zip(
left_context_arcs, left_context_labels
):
left_context_one_hot_arc = tf.keras.utils.to_categorical(
left_context_arc_, num_classes=sentence_max_len + 1
)
left_context_one_hot_label = tf.keras.utils.to_categorical(
left_context_label_,
num_classes=len(tokenizer_label.word_index) + 1,
)
left_context_arc_label_vector = (
left_context_one_hot_arc.tolist()
+ left_context_one_hot_label.tolist()
)
left_context_arc_label_vectors.append(
left_context_arc_label_vector
)
# 2D PRE-padding for left context tags and left_context_arc_vectors
# final shapes will be:
# left_context_tags: (sentence_max_len, tag_max_len)
# left_context_arc_vectors: (sentence_max_len, sentence_max_len)
left_context_tags_ = []
left_context_tags = left_context_tags.tolist()
left_context_arc_label_vectors_ = []
for _ in range(max(0, sentence_max_len - len(left_context_tags))):
left_context_tags_.append(np.zeros(tag_max_len))
left_context_arc_label_vectors_.append(
np.zeros(arc_label_vector_len)
)
left_context_tags = np.array(left_context_tags_ + left_context_tags)
left_context_arc_label_vectors = np.array(
left_context_arc_label_vectors_ + left_context_arc_label_vectors
)
# ===============================================
# Right Context
if t == (
num_tokens_in_sentence - 1
): # there's no right context for last token
right_context_words = np.zeros(sentence_max_len)
right_context_tags = np.zeros((sentence_max_len, tag_max_len))
right_context_pos_tags = np.zeros(sentence_max_len)
else:
right_context_words = words[t + 1 :]
right_context_words = tokenizer_word.texts_to_sequences(
[right_context_words]
)
right_context_words = tf.keras.preprocessing.sequence.pad_sequences(
right_context_words,
maxlen=sentence_max_len,
truncating="post",
padding="post",
)[0]
right_context_tags = [
analysis_result.split("+")[1:]
for analysis_result in sentence_analysis_result[t + 1 :]
]
right_context_tags = tokenizer_tag.texts_to_sequences(
right_context_tags
)
right_context_tags = tf.keras.preprocessing.sequence.pad_sequences(
right_context_tags, maxlen=tag_max_len, padding="pre"
) # last dimension padding is pre
right_context_pos_tags = pos_tags[t + 1 :]
right_context_pos_tags = tf.keras.preprocessing.sequence.pad_sequences(
[right_context_pos_tags], maxlen=sentence_max_len, padding="post"
)[0]
# 2D POST-padding for right context tags
# final shape will be: (sentence_max_len, tag_max_len)
right_context_tags = right_context_tags.tolist()
for _ in range(max(0, sentence_max_len - len(right_context_tags))):
right_context_tags.append(np.zeros(tag_max_len))
right_context_tags = np.array(right_context_tags)
word = np.array(word[0]).reshape(1, 1).astype(int)
tags = tags.reshape(1, tag_max_len).astype(int)
pos = np.array([pos]).reshape(1, 1).astype(int)
left_context_words = left_context_words.reshape(
1, sentence_max_len
).astype(int)
left_context_tags = left_context_tags.reshape(
1, sentence_max_len, tag_max_len
).astype(int)
left_context_pos_tags = left_context_pos_tags.reshape(
1, sentence_max_len
).astype(int)
left_context_arc_label_vectors = left_context_arc_label_vectors.reshape(
1, sentence_max_len, arc_label_vector_len
).astype(int)
right_context_words = right_context_words.reshape(
1, sentence_max_len
).astype(int)
right_context_tags = right_context_tags.reshape(
1, sentence_max_len, tag_max_len
).astype(int)
right_context_pos_tags = right_context_pos_tags.reshape(
1, sentence_max_len
).astype(int)
return (
word,
tags,
pos,
left_context_words,
left_context_tags,
left_context_pos_tags,
left_context_arc_label_vectors,
right_context_words,
right_context_tags,
right_context_pos_tags,
)
def convert_numbers_to_zero(text_: str):
text_ = str(text_) # in case input is not string
text = ""
for char in text_:
if char.isnumeric():
text += "0"
else:
text += char
return text
================================================
FILE: vnlp/dependency_parser/dependency_parser.py
================================================
from typing import List, Tuple
from .spu_context_dp import SPUContextDP
from .treestack_dp import TreeStackDP
class DependencyParser:
"""
Main API class for Dependency Parser implementations.
Available models: ['SPUContextDP', 'TreeStackDP']
In order to evaluate, initialize the class with "evaluate = True" argument.
This will load the model weights that are not trained on test sets.
"""
def __init__(self, model="SPUContextDP", evaluate=False):
self.models = ["SPUContextDP", "TreeStackDP"]
self.evaluate = evaluate
if model == "SPUContextDP":
self.instance = SPUContextDP(evaluate)
elif model == "TreeStackDP":
self.instance = TreeStackDP(evaluate)
else:
raise ValueError(
f"{model} is not a valid model. Try one of {self.models}"
)
def predict(
self,
sentence: str,
displacy_format: bool = False,
pos_result: List[Tuple[str, str]] = None,
) -> List[Tuple[int, str, int, str]]:
"""
High level user API for Dependency Parsing.
Args:
sentence:
Input sentence.
displacy_format:
When set True, returns the result in spacy.displacy format to allow visualization.
pos_result:
Part of Speech tags. To be used when displacy_format = True.
Returns:
List of (token_index, token, arc, label).
Raises:
ValueError: Sentence is too long. Try again by splitting it into smaller pieces.
Example::
from vnlp import DependencyParser
dependency_parser = DependencyParser()
dependency_parser.predict("Onun için yol arkadaşlarımızı titizlikle seçer, kendilerini iyice sınarız.")
[(1, 'Onun', 6, 'obl'),
(2, 'için', 1, 'case'),
(3, 'yol', 4, 'nmod'),
(4, 'arkadaşlarımızı', 6, 'obj'),
(5, 'titizlikle', 6, 'obl'),
(6, 'seçer', 10, 'parataxis'),
(7, ',', 6, 'punct'),
(8, 'kendilerini', 10, 'obj'),
(9, 'iyice', 10, 'advmod'),
(10, 'sınarız', 0, 'root'),
(11, '.', 10, 'punct')]
# Visualization with Spacy:
import spacy
from vnlp import DependencyParser
dependency_parser = DependencyParser()
result = dependency_parser.predict(Oğuz'un kırmızı bir Astra'sı vardı.", displacy_format = True)
spacy.displacy.render(result, style="dep", manual = True)
"""
return self.instance.predict(sentence, displacy_format, pos_result)
# this is called when an attribute is not found:
def __getattr__(self, name):
return self.instance.__getattribute__(name)
================================================
FILE: vnlp/dependency_parser/resources/DP_label_tokenizer.json
================================================
{"class_name": "Tokenizer", "config": {"num_words": null, "filters": null, "lower": false, "split": " ", "char_level": false, "oov_token": null, "document_count": 733342, "word_counts": "{\"nsubj\": 56757, \"root\": 82214, \"punct\": 115639, \"det\": 27517, \"obl\": 56269, \"amod\": 48678, \"compound\": 29045, \"parataxis\": 7547, \"nmod\": 71150, \"advmod\": 35581, \"obj\": 41426, \"advcl\": 14181, \"case\": 18369, \"aux\": 3631, \"nummod\": 12721, \"cc\": 14193, \"conj\": 23253, \"acl\": 16190, \"flat\": 11531, \"mark\": 2403, \"xcomp\": 2815, \"ccomp\": 7532, \"discourse\": 2988, \"fixed\": 582, \"goeswith\": 343, \"appos\": 1004, \"csubj\": 1793, \"advmod:emph\": 2862, \"nmod:poss\": 15796, \"compound:lvc\": 1957, \"cop\": 2654, \"compound:redup\": 716, \"vocative\": 338, \"cc:preconj\": 152, \"iobj\": 888, \"orphan\": 68, \"aux:q\": 700, \"clf\": 177, \"dislocated\": 80, \"list\": 717, \"dep\": 184, \"obl:tmod\": 503, \"nsubj:cop\": 25, \"nmod:part\": 62, \"nmod:comp\": 18, \"csubj:cop\": 63, \"obl:agent\": 23, \"reparandum\": 7}", "word_docs": "{\"nsubj\": 56757, \"root\": 82214, \"punct\": 115639, \"det\": 27517, \"obl\": 56269, \"amod\": 48678, \"compound\": 29045, \"parataxis\": 7547, \"nmod\": 71150, \"advmod\": 35581, \"obj\": 41426, \"advcl\": 14181, \"case\": 18369, \"aux\": 3631, \"nummod\": 12721, \"cc\": 14193, \"conj\": 23253, \"acl\": 16190, \"flat\": 11531, \"mark\": 2403, \"xcomp\": 2815, \"ccomp\": 7532, \"discourse\": 2988, \"fixed\": 582, \"goeswith\": 343, \"appos\": 1004, \"csubj\": 1793, \"advmod:emph\": 2862, \"nmod:poss\": 15796, \"compound:lvc\": 1957, \"cop\": 2654, \"compound:redup\": 716, \"vocative\": 338, \"cc:preconj\": 152, \"iobj\": 888, \"orphan\": 68, \"aux:q\": 700, \"clf\": 177, \"dislocated\": 80, \"list\": 717, \"dep\": 184, \"obl:tmod\": 503, \"nsubj:cop\": 25, \"nmod:part\": 62, \"nmod:comp\": 18, \"csubj:cop\": 63, \"obl:agent\": 23, \"reparandum\": 7}", "index_docs": "{\"4\": 56757, \"2\": 82214, \"1\": 115639, \"10\": 27517, \"5\": 56269, \"6\": 48678, \"9\": 29045, \"19\": 7547, \"3\": 71150, \"8\": 35581, \"7\": 41426, \"16\": 14181, \"12\": 18369, \"21\": 3631, \"17\": 12721, \"15\": 14193, \"11\": 23253, \"13\": 16190, \"18\": 11531, \"26\": 2403, \"24\": 2815, \"20\": 7532, \"22\": 2988, \"34\": 582, \"36\": 343, \"29\": 1004, \"28\": 1793, \"23\": 2862, \"14\": 15796, \"27\": 1957, \"25\": 2654, \"32\": 716, \"37\": 338, \"40\": 152, \"30\": 888, \"42\": 68, \"33\": 700, \"39\": 177, \"41\": 80, \"31\": 717, \"38\": 184, \"35\": 503, \"45\": 25, \"44\": 62, \"47\": 18, \"43\": 63, \"46\": 23, \"48\": 7}", "index_word": "{\"1\": \"punct\", \"2\": \"root\", \"3\": \"nmod\", \"4\": \"nsubj\", \"5\": \"obl\", \"6\": \"amod\", \"7\": \"obj\", \"8\": \"advmod\", \"9\": \"compound\", \"10\": \"det\", \"11\": \"conj\", \"12\": \"case\", \"13\": \"acl\", \"14\": \"nmod:poss\", \"15\": \"cc\", \"16\": \"advcl\", \"17\": \"nummod\", \"18\": \"flat\", \"19\": \"parataxis\", \"20\": \"ccomp\", \"21\": \"aux\", \"22\": \"discourse\", \"23\": \"advmod:emph\", \"24\": \"xcomp\", \"25\": \"cop\", \"26\": \"mark\", \"27\": \"compound:lvc\", \"28\": \"csubj\", \"29\": \"appos\", \"30\": \"iobj\", \"31\": \"list\", \"32\": \"compound:redup\", \"33\": \"aux:q\", \"34\": \"fixed\", \"35\": \"obl:tmod\", \"36\": \"goeswith\", \"37\": \"vocative\", \"38\": \"dep\", \"39\": \"clf\", \"40\": \"cc:preconj\", \"41\": \"dislocated\", \"42\": \"orphan\", \"43\": \"csubj:cop\", \"44\": \"nmod:part\", \"45\": \"nsubj:cop\", \"46\": \"obl:agent\", \"47\": \"nmod:comp\", \"48\": \"reparandum\"}", "word_index": "{\"punct\": 1, \"root\": 2, \"nmod\": 3, \"nsubj\": 4, \"obl\": 5, \"amod\": 6, \"obj\": 7, \"advmod\": 8, \"compound\": 9, \"det\": 10, \"conj\": 11, \"case\": 12, \"acl\": 13, \"nmod:poss\": 14, \"cc\": 15, \"advcl\": 16, \"nummod\": 17, \"flat\": 18, \"parataxis\": 19, \"ccomp\": 20, \"aux\": 21, \"discourse\": 22, \"advmod:emph\": 23, \"xcomp\": 24, \"cop\": 25, \"mark\": 26, \"compound:lvc\": 27, \"csubj\": 28, \"appos\": 29, \"iobj\": 30, \"list\": 31, \"compound:redup\": 32, \"aux:q\": 33, \"fixed\": 34, \"obl:tmod\": 35, \"goeswith\": 36, \"vocative\": 37, \"dep\": 38, \"clf\": 39, \"cc:preconj\": 40, \"dislocated\": 41, \"orphan\": 42, \"csubj:cop\": 43, \"nmod:part\": 44, \"nsubj:cop\": 45, \"obl:agent\": 46, \"nmod:comp\": 47, \"reparandum\": 48}"}}
================================================
FILE: vnlp/dependency_parser/spu_context_dp.py
================================================
from typing import List, Tuple
import pickle
import numpy as np
import tensorflow as tf
import sentencepiece as spm
from ..tokenizer import TreebankWordTokenize
from ..utils import check_and_download, load_keras_tokenizer
from .utils import dp_pos_to_displacy_format, decode_arc_label_vector
from ._spu_context_utils import (
create_spucontext_dp_model,
process_single_word_input,
)
# Resolving parent dependencies
from inspect import getsourcefile
import os
import sys
current_path = os.path.abspath(getsourcefile(lambda: 0))
current_dir = os.path.dirname(current_path)
parent_dir = current_dir[: current_dir.rfind(os.path.sep)]
sys.path.insert(0, parent_dir)
RESOURCES_PATH = os.path.join(os.path.dirname(__file__), "resources/")
PROD_WEIGHTS_LOC = RESOURCES_PATH + "DP_SPUContext_prod.weights"
EVAL_WEIGHTS_LOC = RESOURCES_PATH + "DP_SPUContext_eval.weights"
WORD_EMBEDDING_MATRIX_LOC = os.path.abspath(
os.path.join(
os.path.dirname(__file__),
"..",
"resources/SPUTokenized_word_embedding_16k.matrix",
)
)
PROD_WEIGHTS_LINK = "https://vnlp-model-weights.s3.eu-west-1.amazonaws.com/DP_SPUContext_prod.weights"
EVAL_WEIGHTS_LINK = "https://vnlp-model-weights.s3.eu-west-1.amazonaws.com/DP_SPUContext_eval.weights"
WORD_EMBEDDING_MATRIX_LINK = "https://vnlp-model-weights.s3.eu-west-1.amazonaws.com/SPUTokenized_word_embedding_16k.matrix"
SPU_TOKENIZER_WORD_LOC = os.path.abspath(
os.path.join(
os.path.dirname(__file__),
"..",
"resources/SPU_word_tokenizer_16k.model",
)
)
TOKENIZER_LABEL_LOC = RESOURCES_PATH + "DP_label_tokenizer.json"
# Data Preprocessing Config
TOKEN_PIECE_MAX_LEN = 8 # 0.9995 quantile is 8 for 16k_vocab, 7 for 32k_vocab
SENTENCE_MAX_LEN = 40 # 0.998 quantile is 42
# Loading Tokenizers
spu_tokenizer_word = spm.SentencePieceProcessor(SPU_TOKENIZER_WORD_LOC)
tokenizer_label = load_keras_tokenizer(TOKENIZER_LABEL_LOC)
sp_key_to_index = {
spu_tokenizer_word.id_to_piece(id): id
for id in range(spu_tokenizer_word.get_piece_size())
}
sp_index_to_key = {
id: spu_tokenizer_word.id_to_piece(id)
for id in range(spu_tokenizer_word.get_piece_size())
}
LABEL_VOCAB_SIZE = len(tokenizer_label.word_index)
WORD_EMBEDDING_VOCAB_SIZE = len(sp_key_to_index)
WORD_EMBEDDING_VECTOR_SIZE = 128
WORD_EMBEDDING_MATRIX = np.zeros(
(WORD_EMBEDDING_VOCAB_SIZE, WORD_EMBEDDING_VECTOR_SIZE)
)
ARC_LABEL_VECTOR_LEN = (
SENTENCE_MAX_LEN + 1 + len(tokenizer_label.word_index) + 1
)
NUM_RNN_STACKS = 2
RNN_UNITS_MULTIPLIER = 2
NUM_RNN_UNITS = WORD_EMBEDDING_VECTOR_SIZE * RNN_UNITS_MULTIPLIER
FC_UNITS_MULTIPLIER = (2, 1)
DROPOUT = 0.2
class SPUContextDP:
"""
SentencePiece Unigram Context Dependency Parser class.
- This is a context aware Deep GRU based Dependency Parser that uses `SentencePiece Unigram <https://arxiv.org/abs/1804.10959>`_ tokenizer and pre-trained Word2Vec embeddings.
- It achieves 0.7117 LAS (Labeled Attachment Score) and 0.8370 UAS (Unlabeled Attachment Score) on all of test sets of Universal Dependencies 2.9.
- For more details about the training procedure, dataset and evaluation metrics, see `ReadMe <https://github.com/vngrs-ai/VNLP/blob/main/vnlp/dependency_parser/ReadMe.md>`_.
"""
def __init__(self, evaluate):
self.model = create_spucontext_dp_model(
TOKEN_PIECE_MAX_LEN,
SENTENCE_MAX_LEN,
WORD_EMBEDDING_VOCAB_SIZE,
ARC_LABEL_VECTOR_LEN,
WORD_EMBEDDING_VECTOR_SIZE,
WORD_EMBEDDING_MATRIX,
NUM_RNN_UNITS,
NUM_RNN_STACKS,
FC_UNITS_MULTIPLIER,
DROPOUT,
)
# Check and download word embedding matrix and model weights
check_and_download(
WORD_EMBEDDING_MATRIX_LOC, WORD_EMBEDDING_MATRIX_LINK
)
if evaluate:
MODEL_WEIGHTS_LOC = EVAL_WEIGHTS_LOC
MODEL_WEIGHTS_LINK = EVAL_WEIGHTS_LINK
else:
MODEL_WEIGHTS_LOC = PROD_WEIGHTS_LOC
MODEL_WEIGHTS_LINK = PROD_WEIGHTS_LINK
check_and_download(MODEL_WEIGHTS_LOC, MODEL_WEIGHTS_LINK)
# Load Word embedding matrix
word_embedding_matrix = np.load(WORD_EMBEDDING_MATRIX_LOC)
# Load Model weights
with open(MODEL_WEIGHTS_LOC, "rb") as fp:
model_weights = pickle.load(fp)
# Insert word embedding weights to correct position (0 for SPUContext Dependency Parsing model)
model_weights.insert(0, word_embedding_matrix)
# Set model weights
self.model.set_weights(model_weights)
self.spu_tokenizer_word = spu_tokenizer_word
self.tokenizer_label = tokenizer_label
def predict(
self,
sentence: str,
displacy_format: bool = False,
pos_result: List[Tuple[str, str]] = None,
) -> List[Tuple[int, str, int, str]]:
"""
Args:
sentence:
Input sentence.
displacy_format:
When set True, returns the result in spacy.displacy format to allow visualization.
pos_result:
Part of Speech tags. To be used when displacy_format = True.
Returns:
List of (token_index, token, arc, label).
Raises:
ValueError: Sentence is too long. Try again by splitting it into smaller pieces.
"""
tokenized_sentence = TreebankWordTokenize(sentence)
num_tokens_in_sentence = len(tokenized_sentence)
if num_tokens_in_sentence > SENTENCE_MAX_LEN:
raise ValueError(
"Sentence is too long. Try again by splitting it into smaller pieces."
)
arcs = []
labels = []
for t in range(num_tokens_in_sentence):
# t is the index of token/word
X = process_single_word_input(
t,
tokenized_sentence,
self.spu_tokenizer_word,
self.tokenizer_label,
ARC_LABEL_VECTOR_LEN,
arcs,
labels,
)
# Predicting
logits = self.model(X).numpy()[0]
arc, label = decode_arc_label_vector(
logits, SENTENCE_MAX_LEN, LABEL_VOCAB_SIZE
)
arcs.append(arc)
labels.append(label)
# 0 arc index is reserved for root, therefore arc = 1 means word is dependent on the first word
dp_result = []
for idx, word in enumerate(tokenized_sentence):
dp_result.append(
(
idx + 1,
word,
arcs[idx],
self.tokenizer_label.sequences_to_texts([[labels[idx]]])[
0
],
)
)
if not displacy_format:
return dp_result
else:
dp_result_displacy_format = dp_pos_to_displacy_format(
dp_result, pos_result
)
return dp_result_displacy_format
================================================
FILE: vnlp/dependency_parser/treestack_dp.py
================================================
from typing import List, Tuple
import pickle
import tensorflow as tf
import numpy as np
from ..stemmer_morph_analyzer import StemmerAnalyzer
from ..part_of_speech_tagger import PoSTagger
from ..tokenizer import TreebankWordTokenize
from ..utils import check_and_download, load_keras_tokenizer
from .utils import dp_pos_to_displacy_format, decode_arc_label_vector
from ._treestack_utils import (
create_dependency_parser_model,
process_single_word_input,
)
# Resolving parent dependencies
from inspect import getsourcefile
import os
import sys
current_path = os.path.abspath(getsourcefile(lambda: 0))
current_dir = os.path.dirname(current_path)
parent_dir = current_dir[: current_dir.rfind(os.path.sep)]
sys.path.insert(0, parent_dir)
RESOURCES_PATH = os.path.join(os.path.dirname(__file__), "resources/")
PROD_WEIGHTS_LOC = RESOURCES_PATH + "DP_TreeStack_prod.weights"
EVAL_WEIGHTS_LOC = RESOURCES_PATH + "DP_TreeStack_eval.weights"
WORD_EMBEDDING_MATRIX_LOC = os.path.abspath(
os.path.join(
os.path.dirname(__file__),
"..",
"resources/TBWTokenized_word_embedding.matrix",
)
)
PROD_WEIGHTS_LINK = "https://vnlp-model-weights.s3.eu-west-1.amazonaws.com/DP_TreeStack_prod.weights"
EVAL_WEIGHTS_LINK = "https://vnlp-model-weights.s3.eu-west-1.amazonaws.com/DP_TreeStack_eval.weights"
WORD_EMBEDDING_MATRIX_LINK = "https://vnlp-model-weights.s3.eu-west-1.amazonaws.com/TBWTokenized_word_embedding.matrix"
TOKENIZER_WORD_LOC = os.path.abspath(
os.path.join(
os.path.dirname(__file__), "..", "resources/TB_word_tokenizer.json"
)
)
TOKENIZER_POS_LOC = os.path.abspath(
os.path.join(
os.path.dirname(__file__),
"..",
"part_of_speech_tagger/resources/PoS_label_tokenizer.json",
)
) # using the tokenizer of part_of_speech_tagger
TOKENIZER_TAG_LOC = os.path.abspath(
os.path.join(
os.path.dirname(__file__),
"..",
"stemmer_morph_analyzer/resources/Stemmer_morph_tag_tokenizer.json",
)
) # using the tokenizer of stemmer_morph_analyzer
TOKENIZER_LABEL_LOC = RESOURCES_PATH + "DP_label_tokenizer.json"
# Data Preprocessing Config
SENTENCE_MAX_LEN = 40
TAG_MAX_LEN = 15
WORD_OOV_TOKEN = "<OOV>"
# Loading Tokenizers
# Have to load tokenizers here because model config depends on them
tokenizer_word = load_keras_tokenizer(TOKENIZER_WORD_LOC)
tokenizer_pos = load_keras_tokenizer(TOKENIZER_POS_LOC)
tokenizer_tag = load_keras_tokenizer(TOKENIZER_TAG_LOC)
tokenizer_label = load_keras_tokenizer(TOKENIZER_LABEL_LOC)
LABEL_VOCAB_SIZE = len(tokenizer_label.word_index)
POS_VOCAB_SIZE = len(tokenizer_pos.word_index)
# Model Config
WORD_EMBEDDING_VECTOR_SIZE = 128 # Word2Vec_medium.model
WORD_EMBEDDING_VOCAB_SIZE = 63_992 # Word2Vec_medium.model
# WORD_EMBEDDING_MATRIX and TAG_EMBEDDING MATRIX are initialized as Zeros, will be overwritten when model is loaded.
WORD_EMBEDDING_MATRIX = np.zeros(
(WORD_EMBEDDING_VOCAB_SIZE, WORD_EMBEDDING_VECTOR_SIZE)
)
TAG_EMBEDDING_MATRIX = np.zeros((127, 32))
POS_EMBEDDING_VECTOR_SIZE = 8
NUM_RNN_STACKS = 2
RNN_UNITS_MULTIPLIER = 3
TAG_NUM_RNN_UNITS = WORD_EMBEDDING_VECTOR_SIZE
LC_NUM_RNN_UNITS = TAG_NUM_RNN_UNITS * RNN_UNITS_MULTIPLIER
LC_ARC_LABEL_NUM_RNN_UNITS = TAG_NUM_RNN_UNITS * RNN_UNITS_MULTIPLIER
RC_NUM_RNN_UNITS = TAG_NUM_RNN_UNITS * RNN_UNITS_MULTIPLIER
ARC_LABEL_VECTOR_LEN = SENTENCE_MAX_LEN + 1 + LABEL_VOCAB_SIZE + 1
FC_UNITS_MULTIPLIERS = (8, 4)
WORD_FORM = "whole"
DROPOUT = 0.2
class TreeStackDP:
"""
Tree-stack Dependency Parser class.
- This dependency parser is *inspired* by `Tree-stack LSTM in Transition Based Dependency Parsing <https://aclanthology.org/K18-2012/>`_.
- "Inspire" is emphasized because this implementation uses the approach of using Morphological Tags, Pre-trained word embeddings and POS tags as input for the model, rather than implementing the exact network proposed in the paper.
- It achieves 0.6914 LAS (Labeled Attachment Score) and 0.8048 UAS (Unlabeled Attachment Score) on all of test sets of Universal Dependencies 2.9.
- Input data is processed by NLTK.tokenize.TreebankWordTokenizer.
- For more details about the training procedure, dataset and evaluation metrics, see `ReadMe <https://github.com/vngrs-ai/VNLP/blob/main/vnlp/dependency_parser/ReadMe.md>`_.
"""
def __init__(self, evaluate):
self.model = create_dependency_parser_model(
WORD_EMBEDDING_VOCAB_SIZE,
WORD_EMBEDDING_VECTOR_SIZE,
WORD_EMBEDDING_MATRIX,
POS_VOCAB_SIZE,
POS_EMBEDDING_VECTOR_SIZE,
SENTENCE_MAX_LEN,
TAG_MAX_LEN,
ARC_LABEL_VECTOR_LEN,
NUM_RNN_STACKS,
TAG_NUM_RNN_UNITS,
LC_NUM_RNN_UNITS,
LC_ARC_LABEL_NUM_RNN_UNITS,
RC_NUM_RNN_UNITS,
DROPOUT,
TAG_EMBEDDING_MATRIX,
FC_UNITS_MULTIPLIERS,
)
# Check and download word embedding matrix and model weights
check_and_download(
WORD_EMBEDDING_MATRIX_LOC, WORD_EMBEDDING_MATRIX_LINK
)
if evaluate:
MODEL_WEIGHTS_LOC = EVAL_WEIGHTS_LOC
MODEL_WEIGHTS_LINK = EVAL_WEIGHTS_LINK
else:
MODEL_WEIGHTS_LOC = PROD_WEIGHTS_LOC
MODEL_WEIGHTS_LINK = PROD_WEIGHTS_LINK
check_and_download(MODEL_WEIGHTS_LOC, MODEL_WEIGHTS_LINK)
# Load Word embedding matrix
word_embedding_matrix = np.load(WORD_EMBEDDING_MATRIX_LOC)
# Load Model weights
with open(MODEL_WEIGHTS_LOC, "rb") as fp:
model_weights = pickle.load(fp)
# Insert word embedding weights to correct position (1 for TreeStack Dependency Parsing model)
model_weights.insert(1, word_embedding_matrix)
# Set model weights
self.model.set_weights(model_weights)
self.tokenizer_word = tokenizer_word
self.tokenizer_tag = tokenizer_tag
self.tokenizer_pos = tokenizer_pos
self.tokenizer_label = tokenizer_label
# I don't want StemmerAnalyzer and PosTagger to occupy any memory in GPU!
with tf.device("/cpu:0"):
stemmer_analyzer = StemmerAnalyzer()
self.stemmer_analyzer = stemmer_analyzer
# stemmer_analyzer is passed to PoSTagger to prevent chain stemmer_analyzer initializations
pos_tagger = PoSTagger(
"TreeStackPoS", evaluate, self.stemmer_analyzer
)
self.pos_tagger = pos_tagger
def predict(
self, sentence: str, displacy_format: bool = False, *args
) -> List[Tuple[int, str, int, str]]:
"""
Args:
sentence:
Input sentence.
displacy_format:
When set True, returns the result in spacy.displacy format to allow visualization.
Returns:
List of (token_index, token, arc, label).
Raises:
ValueError: Sentence is too long. Try again by splitting it into smaller pieces.
"""
sentence_word_punct_tokenized = TreebankWordTokenize(sentence)
sentence_analysis_result = self.stemmer_analyzer.predict(sentence)
sentence_analysis_result = [
sentence_analysis.replace("^", "+")
for sentence_analysis in sentence_analysis_result
]
num_tokens_in_sentence = len(sentence_word_punct_tokenized)
if num_tokens_in_sentence > SENTENCE_MAX_LEN:
raise ValueError(
"Sentence is too long. Try again by splitting it into smaller pieces."
)
# This is for debugging purposes in case a consistency occurs during tokenization.
if not len(sentence_analysis_result) == num_tokens_in_sentence:
raise Exception(
sentence,
"Length of sentence and sentence_analysis_result don't match",
)
# *args exist for API compatability. pos_result is overwritten here.
pos_result = self.pos_tagger.predict(sentence)
pos_tags = [pos for (word, pos) in pos_result]
arcs = []
labels = []
for t in range(num_tokens_in_sentence):
# t is the index of token/word
X = process_single_word_input(
t,
sentence,
sentence_analysis_result,
SENTENCE_MAX_LEN,
TAG_MAX_LEN,
ARC_LABEL_VECTOR_LEN,
self.tokenizer_word,
self.tokenizer_tag,
self.tokenizer_label,
self.tokenizer_pos,
arcs,
labels,
pos_tags,
WORD_FORM,
)
# Predicting
logits = self.model(X).numpy()[0]
arc, label = decode_arc_label_vector(
logits, SENTENCE_MAX_LEN, LABEL_VOCAB_SIZE
)
arcs.append(arc)
labels.append(label)
# 0 arc index is reserved for root, therefore arc = 1 means word is dependent on the first word
dp_result = []
for idx, word in enumerate(sentence_word_punct_tokenized):
dp_result.append(
(
idx + 1,
word,
arcs[idx],
self.tokenizer_label.sequences_to_texts([[labels[idx]]])[
0
],
)
)
if not displacy_format:
return dp_result
else:
dp_result_displacy_format = dp_pos_to_displacy_format(
dp_result, pos_result
)
return dp_result_displacy_format
================================================
FILE: vnlp/dependency_parser/utils.py
================================================
import numpy as np
def dp_pos_to_displacy_format(dp_result, pos_result=None):
"""
Converts Dependency Parser result to Displacy format.
Displacy requires that PoS tags are also provided, however this implementation allows skipping it.
"""
# In case PoS result is not provided, use empty strings.
if pos_result is None:
pos_result = [(triplet[0], "") for triplet in dp_result]
dp_result_displacy_format = {"words": [], "arcs": []}
for dp_res, pos_res in zip(dp_result, pos_result):
word = dp_res[1]
pos_tag = pos_res[1]
arc_source = dp_res[0] - 1
arc_dest = dp_res[2] - 1
dp_label = dp_res[3]
dp_result_displacy_format["words"].append(
{"text": word, "tag": pos_tag}
)
if arc_dest < 0:
continue
else:
if arc_source <= arc_dest:
dp_result_displacy_format["arcs"].append(
{
"start": arc_source,
"end": arc_dest,
"label": dp_label,
"dir": "right",
}
)
else:
dp_result_displacy_format["arcs"].append(
{
"start": arc_dest,
"end": arc_source,
"label": dp_label,
"dir": "left",
}
)
return dp_result_displacy_format
def decode_arc_label_vector(logits, SENTENCE_MAX_LEN, LABEL_VOCAB_SIZE):
"""
Converts the output vector of Dependency Parser model to arc and label values
"""
arc = np.argmax(
logits[: SENTENCE_MAX_LEN + 1]
) # +1 is due to reserving of arc 0 for root. Don't confuse it with padding 0!
label = np.argmax(
logits[
SENTENCE_MAX_LEN + 1 : SENTENCE_MAX_LEN + 1 + LABEL_VOCAB_SIZE + 1
]
)
return arc, label
================================================
FILE: vnlp/named_entity_recognizer/ReadMe.md
================================================
### Named Entity Recognizer (NER)
- Named Entity Recognition implementations of VNLP.
- Details of each model are provided below.
- In order to evaluate, initialize the class with "evaluate = True" argument. This will load the model weights that are not trained on test sets.
#### SPUContext Named Entity Recognizer
- This is a context aware Named Entity Recognizer that uses SentencePiece Unigram tokenizer and pre-trained Word2Vec embeddings.
- It achieves 0.9928 Accuracy and 0.9833 F1 macro score.
- Test set consists of below datasets with evaluation metrics on each one's test set:
- wikiann-tdd.ai-xtreme-tr-test: Accuracy: 0.9880 - F1_macro_score: 0.9814
- gungor.ner.test.14.only_consistent-test: Accuracy: 0.9970 - F1_macro_score: 0.9859
- teghub-TurkishNER-BERT-test: Accuracy: 0.9974 - F1_macro_score: 0.9891
- F1 scores for each entity (treating entity of interest as positive, and all other entities as negative):
- ORG: F1 score: 0.9766
- PER: F1 score: 0.9852
- LOC: F1 score: 0.9742
- After development phase, final model in the repository is trained with all of train, dev and test data for 50 epochs.
- Starting with 0.001 learning rate, lr decay of 0.95 is used after the 3rd epoch.
- Input data is processed by NLTK.tokenize.TreebankWordTokenizer.
#### CharNER
- This is an implementation of "CharNER: Character-Level Named Entity Recognition", which can be found here: https://aclanthology.org/C16-1087/
- There are slight modifications to original paper:
- I did not train for all languages, but only Turkish.
- I did not use Viterbi Decoder, mine is simple Mode operation among the outputs of each token.
- It achieves 0.9589 Accuracy and 0.9200 F1_macro_score.
- Tokens are processed by NLTK.tokenize.WordPunctTokenizer so that each punctuation becomes a new token.
#### Dataset
- I gathered, parsed and denoised a very extensive dataset.
- Train, dev and test sets are created by processing and merging multiple datasets in the literature.
- Gungor Joint Ner and Md Tagger dataset
https://github.com/onurgu/joint-ner-and-md-tagger/tree/master/dataset
- Turkish News NER dataset
https://data.tdd.ai/#/0a027105-498c-46f7-9867-2ceeac5e64b7
- XTREME Turkish NER dataset
https://github.com/google-research/xtreme
https://data.tdd.ai/#/204e1373-7a9e-4f76-aa75-7708593cf2dd
- TegHUB Turkish NER data 3 labels dataset
https://github.com/teghub/TurkishNER-BERT/tree/master/TurkishNERdata3Labels
- NER Turkish tweets dataset
https://github.com/dkucuk/NER-Turkish-Tweets/blob/master/2014_JRC_Twitter_TR_NER-dataset.zip
- Wikiann Turkish NER dataset
https://github.com/savasy/Turkish-Bert-Based-NERModel
- B/I prefixes are removed, other entities are converted to 'O' and all entities are standardized to: ['O', 'PER', 'LOC', 'ORG']
- Punctuation labels are strictly 'O'.
- TWNERTC_TC_Coarse Grained NER_DomainDependent_NoiseReduction.DUMP_train in train data is further noise reduced version of original form, consisting of 20 % of original dataset. Despite denoising, including this dataset hurts model performance because it contains lots of errors. Therefore it is not used in neither development, nor production phases of training.
================================================
FILE: vnlp/named_entity_recognizer/__init__.py
================================================
from .named_entity_recognizer import NamedEntityRecognizer
__all__ = ["NamedEntityRecognizer"]
================================================
FILE: vnlp/named_entity_recognizer/_charner_utils.py
================================================
import tensorflow as tf
def create_charner_model(
char_vocab_size,
embed_size,
seq_len_max,
num_rnn_stacks,
rnn_dim,
mlp_dim,
num_classes,
dropout,
):
model = tf.keras.models.Sequential()
model.add(
tf.keras.layers.Embedding(
input_dim=char_vocab_size,
output_dim=embed_size,
input_length=seq_len_max,
)
)
for _ in range(num_rnn_stacks):
model.add(
tf.keras.layers.Bidirectional(
tf.keras.layers.GRU(rnn_dim, return_sequences=True)
)
)
model.add(tf.keras.layers.Dropout(dropout))
model.add(tf.keras.layers.Dense(mlp_dim, activation="relu"))
model.add(tf.keras.layers.Dropout(dropout))
model.add(tf.keras.layers.Dense(num_classes, activation="softmax"))
return model
================================================
FILE: vnlp/named_entity_recognizer/_spu_context_utils.py
================================================
import tensorflow as tf
import numpy as np
from ..utils import create_rnn_stacks, process_word_context
TOKEN_PIECE_MAX_LEN = 8
SENTENCE_MAX_LEN = 40
def create_spucontext_ner_model(
TOKEN_PIECE_MAX_LEN,
SENTENCE_MAX_LEN,
VOCAB_SIZE,
ENTITY_VOCAB_SIZE,
WORD_EMBEDDING_DIM,
WORD_EMBEDDING_MATRIX,
NUM_RNN_UNITS,
NUM_RNN_STACKS,
FC_UNITS_MULTIPLIER,
DROPOUT,
):
# Current Word
# WORD_RNN is common model for processing all word tokens
word_rnn = tf.keras.models.Sequential(name="WORD_RNN")
word_rnn.add(tf.keras.layers.InputLayer(input_shape=(TOKEN_PIECE_MAX_LEN)))
word_rnn.add(
tf.keras.layers.Embedding(
input_dim=VOCAB_SIZE,
output_dim=WORD_EMBEDDING_DIM,
embeddings_initializer=tf.keras.initializers.Constant(
WORD_EMBEDDING_MATRIX
),
trainable=False,
name="WORD_EMBEDDING",
)
)
word_rnn.add(create_rnn_stacks(NUM_RNN_STACKS, NUM_RNN_UNITS, DROPOUT))
# Left Context Words
left_context_rnn = tf.keras.models.Sequential(name="LEFT_CONTEXT_RNN")
left_context_rnn.add(
tf.keras.layers.InputLayer(
input_shape=(SENTENCE_MAX_LEN, TOKEN_PIECE_MAX_LEN)
)
)
left_context_rnn.add(tf.keras.layers.TimeDistributed(word_rnn))
left_context_rnn.add(
create_rnn_stacks(NUM_RNN_STACKS, NUM_RNN_UNITS, DROPOUT)
)
# Right Context Words
right_context_rnn = tf.keras.models.Sequential(name="RIGHT_CONTEXT_RNN")
right_context_rnn.add(
tf.keras.layers.InputLayer(
input_shape=(SENTENCE_MAX_LEN, TOKEN_PIECE_MAX_LEN)
)
)
right_context_rnn.add(tf.keras.layers.TimeDistributed(word_rnn))
right_context_rnn.add(
create_rnn_stacks(
NUM_RNN_STACKS, NUM_RNN_UNITS, DROPOUT, GO_BACKWARDS=True
)
)
# Previously Processed (Left) Entities
lc_entity_rnn = tf.keras.models.Sequential(name="PREV_ENTITY_RNN")
lc_entity_rnn.add(
tf.keras.layers.InputLayer(
input_shape=(SENTENCE_MAX_LEN, ENTITY_VOCAB_SIZE + 1)
)
)
lc_entity_rnn.add(
create_rnn_stacks(NUM_RNN_STACKS, NUM_RNN_UNITS, DROPOUT)
)
# FC Layers
current_left_right_concat = tf.keras.layers.Concatenate()(
[
word_rnn.output,
left_context_rnn.output,
right_context_rnn.output,
lc_entity_rnn.output,
]
)
fc_layer_one = tf.keras.layers.Dense(
NUM_RNN_UNITS * FC_UNITS_MULTIPLIER[0], activation="relu"
)(current_left_right_concat)
fc_layer_one = tf.keras.layers.Dropout(DROPOUT)(fc_layer_one)
fc_layer_two = tf.keras.layers.Dense(
NUM_RNN_UNITS * FC_UNITS_MULTIPLIER[1], activation="relu"
)(fc_layer_one)
fc_layer_two = tf.keras.layers.Dropout(DROPOUT)(fc_layer_two)
entity_output = tf.keras.layers.Dense(
ENTITY_VOCAB_SIZE + 1, activation="softmax"
)(fc_layer_two)
ner_model = tf.keras.models.Model(
inputs=[
word_rnn.input,
left_context_rnn.input,
right_context_rnn.input,
lc_entity_rnn.input,
],
outputs=[entity_output],
)
return ner_model
def process_single_word_input(
w,
tokenized_sentence,
spu_tokenizer_word,
tokenizer_label,
int_preds_so_far,
):
entity_vocab_size = len(tokenizer_label.word_index)
(
current_word_processed,
left_context_words_processed,
right_context_words_processed,
) = process_word_context(
w,
tokenized_sentence,
spu_tokenizer_word,
SENTENCE_MAX_LEN,
TOKEN_PIECE_MAX_LEN,
)
left_context_preds = []
# Pad Left Context Arc Label Vectors
for _ in range(SENTENCE_MAX_LEN - w):
left_context_preds.append(np.zeros(entity_vocab_size + 1))
for w_ in range(w):
left_context_preds.append(
tf.keras.utils.to_categorical(
int_preds_so_far[w_], num_classes=entity_vocab_size + 1
)
)
left_context_preds = np.array(left_context_preds)[
-SENTENCE_MAX_LEN:
] # pre truncate
# Expand dims for sequence processing with batch_size = 1
current_word_processed = np.expand_dims(current_word_processed, axis=0)
left_context_words_processed = np.expand_dims(
left_context_words_processed, axis=0
)
right_context_words_processed = np.expand_dims(
right_context_words_processed, axis=0
)
left_context_preds = np.expand_dims(left_context_preds, axis=0)
return (
current_word_processed,
left_context_words_processed,
right_context_words_processed,
left_context_preds,
)
================================================
FILE: vnlp/named_entity_recognizer/charner.py
================================================
from typing import List, Tuple
import pickle
import numpy as np
import tensorflow as tf
from ..tokenizer import WordPunctTokenize
from ..utils import check_and_download, load_keras_tokenizer
from .utils import ner_to_displacy_format
from ._charner_utils import create_charner_model
# Resolving parent dependencies
from inspect import getsourcefile
import os
import sys
current_path = os.path.abspath(getsourcefile(lambda: 0))
current_dir = os.path.dirname(current_path)
parent_dir = current_dir[: current_dir.rfind(os.path.sep)]
sys.path.insert(0, parent_dir)
RESOURCES_PATH = os.path.join(os.path.dirname(__file__), "resources/")
PROD_WEIGHTS_LOC = RESOURCES_PATH + "NER_CharNER_prod.weights"
EVAL_WEIGHTS_LOC = RESOURCES_PATH + "NER_CharNER_eval.weights"
PROD_WEIGHTS_LINK = "https://vnlp-model-weights.s3.eu-west-1.amazonaws.com/NER_CharNER_prod.weights"
EVAL_WEIGHTS_LINK = "https://vnlp-model-weights.s3.eu-west-1.amazonaws.com/NER_CharNER_eval.weights"
TOKENIZER_CHAR_LOC = RESOURCES_PATH + "CharNER_char_tokenizer.json"
TOKENIZER_LABEL_LOC = RESOURCES_PATH + "NER_label_tokenizer.json"
CHAR_VOCAB_SIZE = 150
SEQ_LEN_MAX = 256
OOV_TOKEN = "<OOV>"
PADDING_STRAT = "post"
EMBED_SIZE = 32
RNN_DIM = 128
NUM_RNN_STACKS = 5
MLP_DIM = 32
NUM_CLASSES = 5 # Equals to len(tokenizer_label.index_word) + 1. +1 is reserved to 0, which corresponds to padded values.
DROPOUT = 0.3
class CharNER:
"""
CharNER Named Entity Recognizer.
- This is an implementation of `CharNER: Character-Level Named Entity Recognition <https://aclanthology.org/C16-1087/>`_.
- There are slight modifications to the original paper:
- This version is trained for Turkish language only.
- This version uses simple Mode operation among the character predictions of each token, instead of Viterbi Decoder
- It achieves 0.9589 Accuracy and 0.9200 F1_macro_score.
- Input data is processed by NLTK.tokenize.WordPunctTokenizer so that each punctuation becomes a new token.
- Entity labels are: ['O', 'PER', 'LOC', 'ORG']
- For more details about the training procedure, dataset and evaluation metrics, see `ReadMe <https://github.com/vngrs-ai/VNLP/blob/main/vnlp/named_entity_recognizer/ReadMe.md>`_.
"""
def __init__(self, evaluate):
self.model = create_charner_model(
CHAR_VOCAB_SIZE,
EMBED_SIZE,
SEQ_LEN_MAX,
NUM_RNN_STACKS,
RNN_DIM,
MLP_DIM,
NUM_CLASSES,
DROPOUT,
)
# Check and download model weights
if evaluate:
MODEL_WEIGHTS_LOC = EVAL_WEIGHTS_LOC
MODEL_WEIGHTS_LINK = EVAL_WEIGHTS_LINK
else:
MODEL_WEIGHTS_LOC = PROD_WEIGHTS_LOC
MODEL_WEIGHTS_LINK = PROD_WEIGHTS_LINK
check_and_download(MODEL_WEIGHTS_LOC, MODEL_WEIGHTS_LINK)
# Load Model weights
with open(MODEL_WEIGHTS_LOC, "rb") as fp:
model_weights = pickle.load(fp)
# Set model weights
self.model.set_weights(model_weights)
tokenizer_char = load_keras_tokenizer(TOKENIZER_CHAR_LOC)
tokenizer_label = load_keras_tokenizer(TOKENIZER_LABEL_LOC)
self.tokenizer_char = tokenizer_char
self.tokenizer_label = tokenizer_label
def _predict_char_level(
self, word_punct_tokenized: List[str]
) -> List[int]:
"""
Returns char level predictions in integers, which will be passed to decoder.
Args:
word_punct_tokenized:
List of tokens, tokenized by WordPunctTokenizer.
Returns:
List of integers, indicating entity classes for each character.
"""
white_space_joined_word_punct_tokens = " ".join(word_punct_tokenized)
white_space_joined_word_punct_tokens = [
char for char in white_space_joined_word_punct_tokens
]
sequences = self.tokenizer_char.texts_to_sequences(
[white_space_joined_word_punct_tokens]
)
padded = tf.keras.preprocessing.sequence.pad_sequences(
sequences, maxlen=SEQ_LEN_MAX, padding=PADDING_STRAT
)
raw_pred = self.model([padded]).numpy()
arg_max_pred = np.argmax(raw_pred, axis=2).reshape(-1)
return arg_max_pred
def _charner_decoder(
self, word_punct_tokenized: List[str], arg_max_pred: List[int]
) -> List[str]:
"""
Args:
word_punct_tokenized:
List of tokens, tokenized by WordPunctTokenizer.
arg_max_pred:
List of integers, indicating entity classes for each character.
Returns:
decoded_entities: List of entities, one entity per token.
"""
lens = [0] + [len(token) + 1 for token in word_punct_tokenized]
cumsum_of_lens = np.cumsum(lens)
decoded_entities = []
for idx in range(len(cumsum_of_lens) - 1):
lower_bound = cumsum_of_lens[idx]
upper_bound = (
cumsum_of_lens[idx + 1] - 1
) # minus one prevents including the whitespace after the token
island = arg_max_pred[lower_bound:upper_bound]
# Extracting mode value
vals, counts = np.unique(island, return_counts=True)
mode_value = vals[np.argmax(counts)]
detokenized_pred = self.tokenizer_label.sequences_to_texts(
[[mode_value]]
)[0]
decoded_entities.append(detokenized_pred)
return decoded_entities
def predict(
self, text: str, displacy_format: bool = False
) -> List[Tuple[str, str]]:
"""
Args:
text:
Input text.
displacy_format:
When set True, returns the result in spacy.displacy format to allow visualization.
Returns:
NER result as pairs of (token, entity).
"""
word_punct_tokenized = WordPunctTokenize(text)
# if len chars (including whitespaces) > sequence length, split it recursively
len_text = len(list(" ".join(word_punct_tokenized)))
if len_text > SEQ_LEN_MAX:
num_tokens = len(word_punct_tokenized)
first_half_result = self.predict(
" ".join(word_punct_tokenized[: num_tokens // 2])
)
first_half_tokens = [pair[0] for pair in first_half_result]
first_half_entities = [pair[1] for pair in first_half_result]
second_half_result = self.predict(
" ".join(word_punct_tokenized[(num_tokens // 2) :])
)
second_half_tokens = [pair[0] for pair in second_half_result]
second_half_entities = [pair[1] for pair in second_half_result]
word_punct_tokenized = first_half_tokens + second_half_tokens
decoded_entities = first_half_entities + second_half_entities
else:
charlevel_pred = self._predict_char_level(word_punct_tokenized)
decoded_entities = self._charner_decoder(
word_punct_tokenized, charlevel_pred
)
ner_result = [
(t, e) for t, e in zip(word_punct_tokenized, decoded_entities)
]
if not displacy_format:
return ner_result
else:
return ner_to_displacy_format(text, ner_result)
================================================
FILE: vnlp/named_entity_recognizer/named_entity_recognizer.py
================================================
from typing import List, Tuple
from .charner import CharNER
from .spu_context_ner import SPUContextNER
class NamedEntityRecognizer:
"""
Main API class for Named Entity Recognizer implementations.
Available models: ['SPUContextNER', 'CharNER']
In order to evaluate, initialize the class with "evaluate = True" argument.
This will load the model weights that are not trained on test sets.
"""
def __init__(self, model="SPUContextNER", evaluate=False):
self.models = ["SPUContextNER", "CharNER"]
self.evaluate = evaluate
if model == "SPUContextNER":
self.instance = SPUContextNER(evaluate)
elif model == "CharNER":
self.instance = CharNER(evaluate)
else:
raise ValueError(
f"{model} is not a valid model. Try one of {self.models}"
)
def predict(
self, sentence: str, displacy_format: bool = False
) -> List[Tuple[str, str]]:
"""
High level user API for Named Entity Recognition.
Args:
sentence:
Input sentence/text.
displacy_format:
When set True, returns the result in spacy.displacy format to allow visualization.
Returns:
NER result as pairs of (token, entity).
Example::
from vnlp import NamedEntityRecognizer
ner = NamedEntityRecognizer()
ner.predict("Benim adım Melikşah, 29 yaşındayım, İstanbul'da ikamet ediyorum ve VNGRS AI Takımı'nda çalışıyorum.")
[('Benim', 'O'),
('adım', 'O'),
('Melikşah', 'PER'),
(',', 'O'),
('29', 'O'),
('yaşındayım', 'O'),
(',', 'O'),
("İstanbul'da", 'LOC'),
('ikamet', 'O'),
('ediyorum', 'O'),
('ve', 'O'),
('VNGRS', 'ORG'),
('AI', 'ORG'),
("Takımı'nda", 'ORG'),
('çalışıyorum', 'O'),
('.', 'O')]
# Visualization with Spacy:
import spacy
from vnlp import NamedEntityRecognizer
ner = NamedEntityRecognizer()
result = ner.predict("İstanbul'dan Foça'ya giderken Zeynep ile Bursa'ya uğradık.", displacy_format = True)
spacy.displacy.render(result, style="ent", manual = True)
"""
return self.instance.predict(sentence, displacy_format)
================================================
FILE: vnlp/named_entity_recognizer/resources/CharNER_char_tokenizer.json
================================================
{"class_name": "Tokenizer", "config": {"num_words": 150, "filters": null, "lower": false, "split": " ", "char_level": false, "oov_token": "<OOV>", "document_count": 17544729, "word_counts": "{\"M\": 82762, \"\\u00fc\": 210123, \"z\": 152366, \"i\": 1062708, \"k\": 513310, \" \": 2970016, \"\\u015e\": 11131, \"e\": 1169698, \"n\": 968021, \"l\": 827493, \"\\u011f\": 110283, \"'\": 320684, \"h\": 130640, \"a\": 1475125, \"\\u0131\": 548053, \"r\": 896712, \"P\": 33142, \"O\": 18856, \"Z\": 5568, \"\\u0130\": 68879, \"T\": 51626, \"F\": 31610, \"v\": 138483, \"A\": 87773, \"\\u00e7\": 109775, \"R\": 64640, \"d\": 511711, \"y\": 385050, \"o\": 389176, \"\\u015f\": 173380, \"b\": 218543, \"c\": 127371, \"s\": 423072, \"t\": 472483, \"u\": 398038, \"2\": 33992, \",\": 125724, \"m\": 387179, \"g\": 152410, \"p\": 111957, \"H\": 33986, \"\\u00f6\": 88779, \"C\": 33921, \"D\": 82410, \"G\": 32131, \"f\": 64208, \"K\": 58525, \"S\": 62516, \"B\": 84583, \"\\\"\": 29545, \"j\": 9615, \"E\": 103256, \"0\": 45618, \"1\": 53001, \"9\": 29521, \"7\": 12941, \"V\": 12286, \"N\": 97040, \"w\": 10927, \"W\": 9285, \"L\": 66726, \"Y\": 63602, \"/\": 4648, \"\\u00d6\": 44790, \"I\": 13634, \"U\": 9692, \"J\": 13703, \"8\": 15924, \".\": 107873, \"-\": 42456, \";\": 2907, \"x\": 4261, \"Q\": 744, \"6\": 13411, \":\": 19657, \"\\u00dc\": 6770, \"&\": 396, \"\\u00c7\": 10445, \"5\": 16012, \"3\": 16986, \"(\": 38025, \")\": 37068, \"4\": 14337, \"\\u011e\": 416, \"q\": 1224, \"@\": 22, \"`\": 10674, \"%\": 429, \"X\": 1070, \"$\": 101, \"=\": 4129, \"\\u00c4\": 4, \"\\u00b0\": 45, \"+\": 443, \"\\u00c3\": 20, \"\\u0153\": 15, \"\\u00a2\": 17, \"#\": 11, \"!\": 492, \"?\": 309, \"\\u00c2\": 92, \"[\": 1007, \"]\": 2645, \"\\ud83d\\ude33\": 1, \"\\ud83d\\ude02\": 1, \"\\u00ee\": 3117, \"\\u00e9\": 2662, \"\\u0107\": 713, \"*\": 8186, \"\\u010d\": 153, \"\\u00e1\": 1413, \"\\u011b\": 19, \"\\u0161\": 310, \"|\": 411, \"\\u00ed\": 939, \"\\u00f5\": 28, \"\\u00e2\": 2579, \"\\u00f2\": 18, \"\\u00f3\": 846, \"\\u0106\": 5, \"\\u03bb\": 52, \"\\u00c9\": 229, \"\\u2192\": 198, \"\\u00e3\": 318, \"\\u012b\": 38, \"\\u00f8\": 101, \"\\u00d7\": 68, \"\\u20ac\": 38, \"\\u00eb\": 175, \"\\u0141\": 9, \"\\u00f1\": 188, \"\\u2021\": 170, \"\\u00c5\": 28, \"\\u00fb\": 393, \"\\u00da\": 19, \"\\u00f4\": 104, \"\\uae40\": 3, \"\\uc601\": 2, \"\\uc0bc\": 2, \"\\u91d1\": 3, \"\\u6cf3\": 2, \"\\u4e09\": 3, \"\\u00e8\": 309, \"\\u00fd\": 39, \"\\u00ce\": 6, \"\\u016b\": 66, \"\\u0160\": 96, \"\\u0633\": 52, \"\\u0627\": 212, \"\\u0645\": 120, \"\\u064e\": 17, \"\\u0631\": 93, \"\\u0621\": 10, \"\\u2020\": 251, \"\\u0643\": 19, \"\\u0628\": 70, \"\\u0644\": 143, \"\\u062a\": 31, \"\\u064a\": 106, \"\\u0148\": 11, \"\\u0219\": 95, \"\\u0103\": 74, \"\\u00e4\": 360, \"_\": 121, \"\\u0101\": 79, \"\\u2022\": 133, \"\\u00ea\": 68, \"^\": 54, \"\\u00e0\": 164, \"\\u00fa\": 186, \"\\u00f0\": 27, \"\\u00b2\": 146, \"\\u010c\": 78, \"\\u021b\": 40, \"\\u064f\": 28, \"\\u062d\": 48, \"\\u0641\": 31, \"\\u0638\": 15, \"\\u0629\": 79, \"\\u0642\": 32, \"\\u00df\": 60, \"\\u00c1\": 88, \"\\u00d0\": 4, \"\\u1ee9\": 5, \"\\u1ecd\": 4, \"\\u00cd\": 30, \"\\u0395\": 9, \"\\u03c5\": 35, \"\\u03b4\": 26, \"\\u03bf\": 125, \"\\u03ba\": 38, \"\\u03af\": 44, \"\\u03b1\": 110, \"\\u0391\": 28, \"\\u03b3\": 32, \"\\u03b5\": 37, \"\\u03bd\": 120, \"\\u041a\": 28, \"\\u0430\": 200, \"\\u0431\": 27, \"\\u0440\": 118, \"\\u0434\": 38, \"\\u0438\": 147, \"\\u043d\": 121, \"\\u0446\": 10, \"\\u044b\": 26, \"\\u0142\": 83, \"\\u0151\": 56, \"\\u0636\": 7, \"\\u0623\": 9, \"\\u30a2\": 5, \"\\u30c9\": 5, \"\\u30eb\": 11, \"\\u30d5\": 5, \"\\uff65\": 6, \"\\u30a4\": 4, \"\\u30d2\": 4, \"\\u30de\": 4, \"\\u30f3\": 6, \"\\u0648\": 67, \"\\u0649\": 8, \"\\u043e\": 156, \"\\u041c\": 15, \"\\u0301\": 35, \"\\u043b\": 85, \"\\u0439\": 29, \"\\u041b\": 6, \"\\u044f\": 19, \"\\u0445\": 12, \"\\u0432\": 58, \"\\u0441\": 69, \"\\u043a\": 86, \"\\u0163\": 27, \"\\u0144\": 60, \"\\u76ae\": 2, \"\\u5c71\": 3, \"\\u53bf\": 76, \"\\u0121\": 3, \"\\u063a\": 7, \"\\u0646\": 72, \"\\u017d\": 34, \"\\u017e\": 86, \"\\u0117\": 23, \"\\u0259\": 40, \"\\u00b9\": 5, \"\\u00d3\": 23, \"\\u03b9\": 52, \"\\u03cc\": 29, \"\\u03c2\": 87, \"\\u039a\": 33, \"\\u03c1\": 49, \"\\u03ae\": 20, \"\\u03c4\": 63, \"\\u03b7\": 29, \"\\u8f6e\": 2, \"\\u53f0\": 3, \"\\u0435\": 162, \"\\u0456\": 5, \"\\u0447\": 12, \"\\u0443\": 36, \"\\u00e5\": 65, \"\\u739b\": 2, \"\\u7eb3\": 2, \"\\u65af\": 3, \"\\u01ce\": 19, \"\\u00a7\": 27, \"\\u12f5\": 2, \"\\u122c\": 2, \"\\u12f3\": 2, \"\\u12cb\": 3, \"\\u0113\": 19, \"\\u1e5b\": 2, \"\\u014d\": 103, \"\\u0531\": 2, \"\\u0580\": 10, \"\\u0561\": 18, \"\\u0563\": 4, \"\\u056e\": 2, \"\\u0578\": 11, \"\\u057f\": 3, \"\\u0576\": 10, \"\\u056b\": 6, \"\\u0119\": 7, \"\\u9ad8\": 2, \"\\u660c\": 3, \"\\u56de\": 4, \"\\u9dbb\": 2, \"\\u0412\": 13, \"\\u045e\": 2, \"\\u0421\": 34, \"\\u0442\": 102, \"\\u0411\": 17, \"\\u0420\": 17, \"\\u00ef\": 20, \"\\u6c11\": 3, \"\\u4e30\": 2, \"\\u062e\": 19, \"\\u03ad\": 18, \"\\u03be\": 11, \"\\u0393\": 10, \"\\u0386\": 6, \"\\u1ec5\": 10, \">\": 32, \"\\u00e6\": 27, \"\\u5df4\": 5, \"\\u695a\": 2, \"\\u01d4\": 10, \"\\u038a\": 2, \"\\u03c9\": 26, \"\\u03ac\": 26, \"\\u6fdf\": 3, \"\\u5be7\": 2, \"\\u5e02\": 53, \"\\u6d4e\": 2, \"\\u5b81\": 3, \"\\u00ec\": 67, \"\\u0394\": 9, \"\\u039c\": 13, \"\\u00d8\": 11, \"\\u0392\": 15, \"\\u03c3\": 41, \"\\u6728\": 6, \"\\u5792\": 2, \"\\u54c8\": 5, \"\\u8428\": 5, \"\\u514b\": 12, \"\\u81ea\": 31, \"\\u6cbb\": 31, \"\\u00f9\": 26, \"\\u0639\": 35, \"\\u062f\": 66, \"\\u03bc\": 30, \"\\u01b0\": 5, \"\\u01a1\": 4, \"\\u043c\": 28, \"\\u05d0\": 7, \"\\u05d9\": 42, \"\\u05dc\": 30, \"\\u05ea\": 6, \"\\u00de\": 3, \"\\u758f\": 5, \"\\u52d2\": 5, \"\\u0410\": 23, \"\\u043f\": 19, \"\\u00ff\": 9, \"\\u8fd1\": 2, \"\\u85e4\": 2, \"\\u52c7\": 2, \"\\u68d7\": 3, \"\\u614e\": 2, \"\\u015a\": 7, \"\\u03c7\": 4, \"\\u03a3\": 8, \"\\u03c0\": 15, \"\\uac1c\": 5, \"\\uc131\": 6, \"\\uacf5\": 2, \"\\uc5c5\": 2, \"\\uc9c0\": 2, \"\\uad6c\": 2, \"\\u041f\": 21, \"\\u0634\": 25, \"\\ub178\": 3, \"\\ubb34\": 3, \"\\ud604\": 3, \"\\u76e7\": 3, \"\\u6b66\": 4, \"\\u9249\": 3, \"\\u1e57\": 4, \"\\u04a7\": 2, \"\\u062c\": 17, \"\\u0647\": 27, \"\\u0433\": 38, \"\\u767d\": 3, \"\\u78b1\": 2, \"\\u6ee9\": 2, \"\\u533a\": 29, \"\\u10d8\": 9, \"\\u10db\": 3, \"\\u10d4\": 7, \"\\u10e0\": 9, \"\\u10e3\": 7, \"\\u10da\": 4, \"\\ud574\": 2, \"\\uc8fc\": 3, \"\\uc2dc\": 18, \"\\u0110\": 21, \"\\u0625\": 8, \"\\u041d\": 11, \"\\u014c\": 6, \"\\u0632\": 16, \"\\u0399\": 9, \"\\u2609\": 4, \"\\u02bf\": 9, \"\\u1e25\": 4, \"\\u6771\": 6, \"\\u6d77\": 14, \"\\u65c5\": 4, \"\\u5ba2\": 4, \"\\u9244\": 5, \"\\u9053\": 7, \"\\u05de\": 14, \"\\u05dd\": 13, \"\\u049a\": 3, \"\\u0437\": 26, \"\\u049b\": 5, \"\\u0493\": 4, \"\\u05e8\": 14, \"\\u05e4\": 4, \"\\u05d7\": 4, \"\\u0712\": 3, \"\\u0713\": 2, \"\\u0715\": 5, \"\\u0710\": 5, \"\\u0448\": 14, \"\\u6258\": 3, \"\\u91cc\": 4, \"\\u01d0\": 5, \"\\u05d6\": 4, \"\\u05da\": 2, \"\\u05e9\": 8, \"\\u0414\": 13, \"\\u0436\": 4, \"\\u013d\": 5, \"\\u05e7\": 4, \"\\u05d1\": 10, \"\\u05d5\": 8, \"\\u0409\": 2, \"\\u0458\": 8, \"\\u7279\": 5, \"\\u522b\": 4, \"\\u884c\": 4, \"\\u653f\": 4, \"\\u6f4d\": 2, \"\\u574a\": 2, \"\\u064d\": 2, \"\\u0650\": 6, \"\\u05b8\": 2, \"\\u05e6\": 2, \"\\u05f2\": 2, \"\\u05b7\": 2, \"\\u05d8\": 2, \"\\u0637\": 11, \"\\u0422\": 7, \"\\u0159\": 20, \"\\u0105\": 13, \"\\u0396\": 3, \"\\u03a0\": 9, \"\\u03c6\": 10, \"\\u06cc\": 15, \"\\u0169\": 5, \"\\u0129\": 4, \"\\u03a4\": 5, \"\\u044c\": 14, \"\\u6c96\": 2, \"\\u7530\": 8, \"\\u7dcf\": 3, \"\\u53f8\": 2, \"\\u04c0\": 9, \"\\u897f\": 8, \"\\u85cf\": 7, \"\\u0375\": 8, \"\\u4e4c\": 6, \"\\u6070\": 2, \"\\u05e1\": 2, \"~\": 12, \"\\u9060\": 4, \"\\u96f7\": 2, \"\\uff5e\": 4, \"\\u304f\": 3, \"\\u306b\": 3, \"\\u3042\": 2, \"\\u308b\": 2, \"\\u660e\": 2, \"\\u304b\": 3, \"\\u308a\": 3, \"\\u0418\": 6, \"\\u65b0\": 11, \"\\u7586\": 9, \"\\u7ef4\": 8, \"\\u543e\": 9, \"\\u5c14\": 14, \"\\u06a9\": 5, \"\\u12f0\": 2, \"\\u1261\": 2, \"\\u1265\": 9, \"\\u1215\": 2, \"\\u05e2\": 4, \"\\u05d4\": 7, \"\\u5750\": 2, \"\\u7985\": 2, \"\\u5c09\": 3, \"\\u7281\": 2, \"\\u5cb3\": 2, \"\\u666e\": 3, \"\\u6e56\": 2, \"\\u9999\": 2, \"\\u6e2f\": 2, \"\\u039d\": 4, \"\\u661f\": 3, \"\\uff08\": 3, \"\\u6b63\": 3, \"\\u9762\": 3, \"\\uff09\": 3, \"\\u015d\": 2, \"<\": 3, \"\\u535a\": 5, \"\\u4e50\": 5, \"\\u0413\": 10, \"\\u12d3\": 2, \"\\u1233\": 2, \"\\u00b1\": 6, \"\\u0192\": 2, \"\\u0423\": 4, \"\\u018e\": 4, \"\\u82e5\": 2, \"\\u7f8c\": 2, \"\\u6d1b\": 2, \"\\u6d66\": 2, \"\\u03b6\": 5, \"\\u30e8\": 2, \"\\u30fc\": 4, \"\\u30bc\": 2, \"\\u30b2\": 3, \"\\u30c3\": 4, \"\\u30d9\": 3, \"\\u30b9\": 2, \"\\u017a\": 6, \"\\u5340\": 4, \"\\u0398\": 5, \"\\ud568\": 2, \"\\ud765\": 2, \"\\u9234\": 2, \"\\u8cb4\": 2, \"\\u7537\": 2, \"\\u4e0a\": 2, \"\\u0540\": 5, \"\\u0575\": 6, \"\\u056f\": 4, \"\\u054d\": 4, \"\\u0533\": 3, \"\\u0565\": 3, \"\\u0582\": 6, \"\\u053d\": 2, \"\\u0570\": 2, \"\\u0564\": 2, \"\\u0635\": 16, \"\\u1e5f\": 3, \"\\u1e6f\": 3, \"\\u011d\": 6, \"\\u6ff1\": 2, \"\\u5dde\": 8, \"\\u6ee8\": 2, \"\\u044e\": 4, \"\\u1ec7\": 3, \"\\u82cf\": 3, \"\\u017b\": 5, \"\\u10d9\": 1, \"\\u10d0\": 12, \"\\u10ee\": 2, \"\\u963f\": 6, \"\\u6cf0\": 3, \"\\u0100\": 6, \"\\u0535\": 2, \"\\u0587\": 1, \"\\u9676\": 1, \"\\u016f\": 2, \"\\u03b2\": 5, \"\\u03c8\": 1, \"\\u05c1\": 1, \"\\u05db\": 1, \"\\u12a2\": 2, \"\\u1275\": 2, \"\\u12ee\": 2, \"\\u1335\": 2, \"\\u12eb\": 3, \"\\u6dc4\": 1, \"\\u840a\": 1, \"\\u856a\": 1, \"\\u83b1\": 1, \"\\u829c\": 1, \"\\u0428\": 3, \"\\u044a\": 7, \"\\u044d\": 5, \"\\u5c3c\": 1, \"\\u078e\": 1, \"\\u07aa\": 2, \"\\u0796\": 2, \"\\u07ad\": 1, \"\\u0787\": 2, \"\\u07b0\": 3, \"\\u0783\": 2, \"\\u07a7\": 2, \"\\u0794\": 1, \"\\u07a8\": 1, \"\\u0780\": 1, \"\\u07ab\": 1, \"\\u0789\": 1, \"\\u900a\": 1, \"\\u0111\": 5, \"\\u53f6\": 1, \"\\u57ce\": 7, \"\\u30c8\": 4, \"\\u30e9\": 1, \"\\u0630\": 1, \"\\u2030\": 8, \"\\u548c\": 5, \"\\u95fd\": 1, \"\\u6c5f\": 2, \"\\u1eed\": 3, \"\\u1ed1\": 3, \"\\u5a01\": 1, \"\\uac15\": 1, \"\\uacc4\": 1, \"\\u2299\": 2, \"\\u1455\": 3, \"\\u14d7\": 3, \"\\u1550\": 6, \"\\u152a\": 3, \"\\u140a\": 3, \"\\u1483\": 3, \"\\u0416\": 3, \"\\ub0a8\": 1, \"\\ud3ec\": 1, \"\\ud2b9\": 1, \"\\ubcc4\": 1, \"\\u015b\": 6, \"\\u04d9\": 1, \"\\u04b9\": 1, \"\\u1e35\": 2, \"\\u2190\": 3, \"\\u121d\": 1, \"\\u133d\": 1, \"\\u5510\": 2, \"\\u671d\": 2, \"\\u594e\": 1, \"\\u5c6f\": 1, \"\\u054a\": 1, \"\\u5410\": 1, \"\\u9c81\": 1, \"\\u756a\": 1, \"\\u4e8e\": 2, \"\\u1eaf\": 1, \"\\u859b\": 1, \"\\u0173\": 1, \"\\u03cd\": 5, \"\\u0218\": 1, \"\\u02d0\": 1, \"\\u02bb\": 4, \"\\uc0ac\": 1, \"\\ub9ac\": 1, \"\\uc6d0\": 2, \"\\u0389\": 1, \"\\u1e2a\": 2, \"\\u0444\": 3, \"\\u0457\": 3, \"\\u00ba\": 5, \"\\u5fb3\": 1, \"\\u5ddd\": 2, \"\\u5bb6\": 2, \"\\u5eb7\": 2, \"\\u961c\": 1, \"\\u2113\": 1, \"\\u1e45\": 1, \"\\u0b9a\": 1, \"\\u0bbf\": 1, \"\\u0b99\": 2, \"\\u0bcd\": 4, \"\\u0b95\": 2, \"\\u0baa\": 2, \"\\u0bc2\": 1, \"\\u0bb0\": 1, \"\\u5764\": 2, \"\\u5854\": 6, \"\\u4ec0\": 4, \"\\u5e93\": 3, \"\\u5e72\": 2, \"\\u5409\": 6, \"\\u5de9\": 1, \"\\u7559\": 1, \"\\u01d2\": 1, \"\\u03b8\": 3, \"\\u03a5\": 2, \"\\u03ce\": 2, \"\\u201e\": 4, \"\\uff1b\": 1, \"\\u30ab\": 1, \"\\u30a6\": 1, \"\\u30dc\": 2, \"\\u30d3\": 1, \"\\u30d0\": 1, \"\\u30d7\": 1, \"\\u201f\": 1, \"\\u6cb3\": 3, \"\\u79be\": 1, \"\\u5357\": 1, \"\\u6c99\": 2, \"\\u6e7e\": 1, \"\\u5c11\": 3, \"\\u4f50\": 1, \"\\u016c\": 1, \"\\u040e\": 3, \"\\u4e14\": 1, \"\\u672b\": 1, \"\\u02bc\": 2, \"\\u74e6\": 1, \"\\u63d0\": 2, \"\\u838a\": 1, \"\\u67a3\": 1, \"\\u5e84\": 1, \"\\u5580\": 1, \"\\u1ea5\": 7, \"\\u1ea1\": 2, \"\\u041e\": 4, \"\\u82f1\": 2, \"\\u09ac\": 1, \"\\u09be\": 2, \"\\u0982\": 1, \"\\u09b2\": 1, \"\\u09a6\": 1, \"\\u09c7\": 1, \"\\u09b6\": 1, \"\\u5c06\": 1, \"\\u0425\": 2, \"\\u0686\": 2, \"\\u06b5\": 1, \"\\u0449\": 2, \"\\u56fd\": 2, \"\\u5b89\": 2, \"\\u5168\": 1, \"\\u90e8\": 1, \"\\u5fb7\": 1, \"\\u9644\": 3, \"\\u6cfd\": 2, \"{\": 4, \"}\": 4, \"\\u010e\": 1, \"\\uac00\": 1, \"\\uc704\": 1, \"\\ub20c\": 1, \"\\ub9bc\": 2, \"\\u042e\": 1, \"\\u200f\": 1, \"\\u062b\": 1, \"\\u838e\": 1, \"\\u8f66\": 2, \"\\u5bdf\": 1, \"\\u5e03\": 3, \"\\u67e5\": 1, \"\\u9521\": 1, \"\\u4f2f\": 1, \"\\ubba4\": 1, \"\\uc9c1\": 3, \"\\ubc45\": 1, \"\\ud06c\": 1, \"\\u1ebf\": 3, \"\\u0928\": 1, \"\\u0947\": 1, \"\\u092a\": 1, \"\\u093e\": 1, \"\\u0932\": 1, \"\\u6e05\": 2, \"\\u30c6\": 1, \"\\u30a3\": 1, \"\\u67ef\": 1, \"\\u576a\": 1, \"\\u1e6d\": 1, \"\\u2033\": 1, \"\\u4f0a\": 2, \"\\u6e29\": 2, \"\\u6cc9\": 1, \"\\u7cbe\": 1, \"\\u014f\": 4, \"\\ud3c9\": 2, \"\\uc591\": 1, \"\\ud560\": 2, \"\\u5e73\": 1, \"\\u58cc\": 1, \"\\u76f4\": 2, \"\\u8f44\": 2, \"\\u571f\": 1, \"\\u65b9\": 1, \"\\u6b73\": 1, \"\\u0722\": 3, \"\\u0718\": 3, \"\\u0717\": 1, \"\\u072a\": 3, \"\\u9ea6\": 1, \"\\u76d6\": 1, \"\\ud61c\": 1, \"\\uc0b0\": 2, \"\\u0424\": 1, \"\\u00ae\": 1, \"\\u30af\": 1, \"\\u30fb\": 2, \"\\u30ea\": 1, \"\\u30e3\": 1, \"\\u30be\": 1, \"\\u04e3\": 1, \"\\u04b7\": 1, \"\\u1405\": 2, \"\\u1585\": 6, \"\\u14f1\": 2, \"\\u1451\": 2, \"\\u00a3\": 2, \"\\u6d25\": 2, \"\\u5927\": 3, \"\\u5b66\": 1, \"\\u10e1\": 10, \"\\u2666\": 1, \"\\u05d2\": 1, \"\\u05e0\": 1, \"\\u05df\": 1, \"\\u03a1\": 5, \"\\u039b\": 3, \"\\u0397\": 2, \"\\u039f\": 1, \"\\u88d5\": 1, \"\\u045c\": 2, \"\\u5185\": 4, \"\\u8499\": 6, \"\\u53e4\": 6, \"\\u5167\": 1, \"\\u7dad\": 1, \"\\u723e\": 1, \"\\u03a7\": 1, \"\\u9752\": 2, \"\\u5cf6\": 1, \"\\u5c9b\": 1, \"\\u3002\": 1, \"\\u8d5b\": 1, \"\\u72ec\": 1, \"\\u5b50\": 1, \"\\u06af\": 1, \"\\u0622\": 5, \"\\u0f61\": 1, \"\\u0f58\": 1, \"\\u0fa6\": 1, \"\\u0f74\": 1, \"\\u0f0d\": 1, \"\\u10e5\": 2, \"\\u10d7\": 3, \"\\u10d5\": 4, \"\\u10dd\": 3, \"\\u10d3\": 1, \"\\u10d6\": 2, \"\\u017c\": 2, \"\\u2207\": 1, \"\\u0417\": 1, \"\\uc870\": 1, \"\\uc120\": 2, \"\\u7109\": 2, \"\\u8006\": 2, \"\\u65cf\": 3, \"\\u83cf\": 2, \"\\u6fa4\": 1, \"\\u00c6\": 1, \"\\u30e2\": 1, \"\\u30b4\": 1, \"\\u30c1\": 1, \"\\u7e54\": 1, \"\\u4fe1\": 1, \"\\u9577\": 1, \"\\u3059\": 1, \"\\u304d\": 2, \"\\u713c\": 1, \"\\u8fbf\": 1, \"\\u7740\": 1, \"\\u5834\": 1, \"\\u6240\": 1, \"\\u0651\": 2, \"\\u0384\": 1, \"\\u9759\": 1, \"\\u053f\": 1, \"\\u0584\": 3, \"\\u1ed7\": 2, \"\\u1e60\": 2, \"\\u6a39\": 1, \"\\u03a6\": 1, \"\\u71df\": 1, \"\\u4e1c\": 1, \"\\u8425\": 1, \"\\u1ea3\": 1, \"\\u00b6\": 1, \"\\uccad\": 1, \"\\uc9c4\": 1, \"\\u0406\": 1, \"\\u0454\": 1, \"\\uc1a1\": 1, \"\\u0388\": 2, \"\\uc2e0\": 1, \"\\uc758\": 1, \"\\u662d\": 1, \"\\u5e7f\": 1, \"\\u58ee\": 1, \"\\u5730\": 2, \"\\u1ef3\": 1, \"\\u10e8\": 1, \"\\u054f\": 1, \"\\u057e\": 2, \"\\u0577\": 1, \"\\u7d71\": 1, \"\\u738b\": 1, \"\\u4e5d\": 2, \"\\u540c\": 1, \"\\u5fc3\": 1, \"\\u0415\": 2, \"\\u04a3\": 2, \"\\u0572\": 1, \"\\u4e49\": 1, \"\\u02be\": 1, \"\\u067e\": 1, \"\\u0688\": 1, \"\\u547c\": 1, \"\\u56fe\": 1, \"\\u58c1\": 1, \"\\u0120\": 1, \"\\ub77c\": 1, \"\\u7f85\": 1, \"\\u5148\": 1, \"\\u12e8\": 1, \"\\u134c\": 1, \"\\u12f4\": 1, \"\\u122b\": 2, \"\\u120b\": 1, \"\\u12ca\": 2, \"\\u12f2\": 1, \"\\u121e\": 1, \"\\u12ad\": 2, \"\\u1232\": 1, \"\\u122a\": 1, \"\\u1350\": 1, \"\\u120a\": 1, \"\\u012a\": 1, \"\\u071f\": 3, \"\\u10dc\": 1, \"\\u10d1\": 1, \"\\u10ed\": 1, \"\\ud6a8\": 1, \"\\ub9b0\": 1, \"\\u6839\": 1, \"\\u4f1f\": 1, \"\\u798f\": 1, \"\\u016d\": 1, \"\\u1780\": 1, \"\\u1798\": 1, \"\\u17d2\": 1, \"\\u1796\": 1, \"\\u17bb\": 1, \"\\u1787\": 1, \"\\u17b6\": 1, \"\\ub300\": 1, \"\\uc911\": 1, \"\\u4e2d\": 1, \"\\u804a\": 1, \"\\u1ea7\": 1, \"\\u674e\": 1, \"\\u73ae\": 1, \"\\u950b\": 1, \"\\u4f3d\": 1, \"\\u5e08\": 1, \"\\u203a\": 1, \"\\u071d\": 2, \"\\u0720\": 1, \"\\u5408\": 1, \"\\u5947\": 1, \"\\u7159\": 1, \"\\u81fa\": 1, \"\\u70df\": 1, \"\\u5bcc\": 1, \"\\u8574\": 1, \"\\u053b\": 1, \"\\u652f\": 1, \"\\u5e81\": 1, \"\\u65e5\": 3, \"\\u7167\": 1, \"\\u672c\": 3, \"\\u8ca8\": 2, \"\\u7269\": 2, \"\\u2295\": 1, \"\\u25ac\": 1, \"\\u0b87\": 1, \"\\u0bb2\": 1, \"\\u0bc8\": 1, \"\\u018f\": 1, \"\\u81e8\": 1, \"\\u6c82\": 2, \"\\u4e34\": 1, \"\\u05b4\": 1, \"\\u05d3\": 1, \"\\u00aa\": 1, \"\\u307b\": 1, \"\\u3093\": 1, \"\\u3044\": 1, \"\\u5317\": 2, \"\\u6e90\": 1, \"\\u900f\": 1, \"\\u958b\": 1, \"\\u62dc\": 1, \"\\u59da\": 1, \"\\u8d1d\": 1, \"\\u5a1c\": 1, \"\\u4eac\": 1, \"\\u90fd\": 1, \"\\u5343\": 1, \"\\u4ee3\": 1, \"\\u5bbf\": 1, \"\\u90e1\": 1, \"\\u4e43\": 1}", "word_docs": "{\"M\": 82762, \"\\u00fc\": 210123, \"z\": 152366, \"i\": 1062708, \"k\": 513310, \" \": 2970016, \"\\u015e\": 11131, \"e\": 1169698, \"n\": 968021, \"l\": 827493, \"\\u011f\": 110283, \"'\": 320684, \"h\": 130640, \"a\": 1475125, \"\\u0131\": 548053, \"r\": 896712, \"P\": 33142, \"O\": 18856, \"Z\": 5568, \"\\u0130\": 68879, \"T\": 51626, \"F\": 31610, \"v\": 138483, \"A\": 87773, \"\\u00e7\": 109775, \"R\": 64640, \"d\": 511711, \"y\": 385050, \"o\": 389176, \"\\u015f\": 173380, \"b\": 218543, \"c\": 127371, \"s\": 423072, \"t\": 472483, \"u\": 398038, \"2\": 33992, \",\": 125724, \"m\": 387179, \"g\": 152410, \"p\": 111957, \"H\": 33986, \"\\u00f6\": 88779, \"C\": 33921, \"D\": 82410, \"G\": 32131, \"f\": 64208, \"K\": 58525, \"S\": 62516, \"B\": 84583, \"\\\"\": 29545, \"j\": 9615, \"E\": 103256, \"0\": 45618, \"1\": 53001, \"9\": 29521, \"7\": 12941, \"V\": 12286, \"N\": 97040, \"w\": 10927, \"W\": 9285, \"L\": 66726, \"Y\": 63602, \"/\": 4648, \"\\u00d6\": 44790, \"I\": 13634, \"U\": 9692, \"J\": 13703, \"8\": 15924, \".\": 107873, \"-\": 42456, \";\": 2907, \"x\": 4261, \"Q\": 744, \"6\": 13411, \":\": 19657, \"\\u00dc\": 6770, \"&\": 396, \"\\u00c7\": 10445, \"5\": 16012, \"3\": 16986, \"(\": 38025, \")\": 37068, \"4\": 14337, \"\\u011e\": 416, \"q\": 1224, \"@\": 22, \"`\": 10674, \"%\": 429, \"X\": 1070, \"$\": 101, \"=\": 4129, \"\\u00c4\": 4, \"\\u00b0\": 45, \"+\": 443, \"\\u00c3\": 20, \"\\u0153\": 15, \"\\u00a2\": 17, \"#\": 11, \"!\": 492, \"?\": 309, \"\\u00c2\": 92, \"[\": 1007, \"]\": 2645, \"\\ud83d\\ude33\": 1, \"\\ud83d\\ude02\": 1, \"\\u00ee\": 3117, \"\\u00e9\": 2662, \"\\u0107\": 713, \"*\": 8186, \"\\u010d\": 153, \"\\u00e1\": 1413, \"\\u011b\": 19, \"\\u0161\": 310, \"|\": 411, \"\\u00ed\": 939, \"\\u00f5\": 28, \"\\u00e2\": 2579, \"\\u00f2\": 18, \"\\u00f3\": 846, \"\\u0106\": 5, \"\\u03bb\": 52, \"\\u00c9\": 229, \"\\u2192\": 198, \"\\u00e3\": 318, \"\\u012b\": 38, \"\\u00f8\": 101, \"\\u00d7\": 68, \"\\u20ac\": 38, \"\\u00eb\": 175, \"\\u0141\": 9, \"\\u00f1\": 188, \"\\u2021\": 170, \"\\u00c5\": 28, \"\\u00fb\": 393, \"\\u00da\": 19, \"\\u00f4\": 104, \"\\uae40\": 3, \"\\uc601\": 2, \"\\uc0bc\": 2, \"\\u91d1\": 3, \"\\u6cf3\": 2, \"\\u4e09\": 3, \"\\u00e8\": 309, \"\\u00fd\": 39, \"\\u00ce\": 6, \"\\u016b\": 66, \"\\u0160\": 96, \"\\u0633\": 52, \"\\u0627\": 212, \"\\u0645\": 120, \"\\u064e\": 17, \"\\u0631\": 93, \"\\u0621\": 10, \"\\u2020\": 251, \"\\u0643\": 19, \"\\u0628\": 70, \"\\u0644\": 143, \"\\u062a\": 31, \"\\u064a\": 106, \"\\u0148\": 11, \"\\u0219\": 95, \"\\u0103\": 74, \"\\u00e4\": 360, \"_\": 121, \"\\u0101\": 79, \"\\u2022\": 133, \"\\u00ea\": 68, \"^\": 54, \"\\u00e0\": 164, \"\\u00fa\": 186, \"\\u00f0\": 27, \"\\u00b2\": 146, \"\\u010c\": 78, \"\\u021b\": 40, \"\\u064f\": 28, \"\\u062d\": 48, \"\\u0641\": 31, \"\\u0638\": 15, \"\\u0629\": 79, \"\\u0642\": 32, \"\\u00df\": 60, \"\\u00c1\": 88, \"\\u00d0\": 4, \"\\u1ee9\": 5, \"\\u1ecd\": 4, \"\\u00cd\": 30, \"\\u0395\": 9, \"\\u03c5\": 35, \"\\u03b4\": 26, \"\\u03bf\": 125, \"\\u03ba\": 38, \"\\u03af\": 44, \"\\u03b1\": 110, \"\\u0391\": 28, \"\\u03b3\": 32, \"\\u03b5\": 37, \"\\u03bd\": 120, \"\\u041a\": 28, \"\\u0430\": 200, \"\\u0431\": 27, \"\\u0440\": 118, \"\\u0434\": 38, \"\\u0438\": 147, \"\\u043d\": 121, \"\\u0446\": 10, \"\\u044b\": 26, \"\\u0142\": 83, \"\\u0151\": 56, \"\\u0636\": 7, \"\\u0623\": 9, \"\\u30a2\": 5, \"\\u30c9\": 5, \"\\u30eb\": 11, \"\\u30d5\": 5, \"\\uff65\": 6, \"\\u30a4\": 4, \"\\u30d2\": 4, \"\\u30de\": 4, \"\\u30f3\": 6, \"\\u0648\": 67, \"\\u0649\": 8, \"\\u043e\": 156, \"\\u041c\": 15, \"\\u0301\": 35, \"\\u043b\": 85, \"\\u0439\": 29, \"\\u041b\": 6, \"\\u044f\": 19, \"\\u0445\": 12, \"\\u0432\": 58, \"\\u0441\": 69, \"\\u043a\": 86, \"\\u0163\": 27, \"\\u0144\": 60, \"\\u76ae\": 2, \"\\u5c71\": 3, \"\\u53bf\": 76, \"\\u0121\": 3, \"\\u063a\": 7, \"\\u0646\": 72, \"\\u017d\": 34, \"\\u017e\": 86, \"\\u0117\": 23, \"\\u0259\": 40, \"\\u00b9\": 5, \"\\u00d3\": 23, \"\\u03b9\": 52, \"\\u03cc\": 29, \"\\u03c2\": 87, \"\\u039a\": 33, \"\\u03c1\": 49, \"\\u03ae\": 20, \"\\u03c4\": 63, \"\\u03b7\": 29, \"\\u8f6e\": 2, \"\\u53f0\": 3, \"\\u0435\": 162, \"\\u0456\": 5, \"\\u0447\": 12, \"\\u0443\": 36, \"\\u00e5\": 65, \"\\u739b\": 2, \"\\u7eb3\": 2, \"\\u65af\": 3, \"\\u01ce\": 19, \"\\u00a7\": 27, \"\\u12f5\": 2, \"\\u122c\": 2, \"\\u12f3\": 2, \"\\u12cb\": 3, \"\\u0113\": 19, \"\\u1e5b\": 2, \"\\u014d\": 103, \"\\u0531\": 2, \"\\u0580\": 10, \"\\u0561\": 18, \"\\u0563\": 4, \"\\u056e\": 2, \"\\u0578\": 11, \"\\u057f\": 3, \"\\u0576\": 10, \"\\u056b\": 6, \"\\u0119\": 7, \"\\u9ad8\": 2, \"\\u660c\": 3, \"\\u56de\": 4, \"\\u9dbb\": 2, \"\\u0412\": 13, \"\\u045e\": 2, \"\\u0421\": 34, \"\\u0442\": 102, \"\\u0411\": 17, \"\\u0420\": 17, \"\\u00ef\": 20, \"\\u6c11\": 3, \"\\u4e30\": 2, \"\\u062e\": 19, \"\\u03ad\": 18, \"\\u03be\": 11, \"\\u0393\": 10, \"\\u0386\": 6, \"\\u1ec5\": 10, \">\": 32, \"\\u00e6\": 27, \"\\u5df4\": 5, \"\\u695a\": 2, \"\\u01d4\": 10, \"\\u038a\": 2, \"\\u03c9\": 26, \"\\u03ac\": 26, \"\\u6fdf\": 3, \"\\u5be7\": 2, \"\\u5e02\": 53, \"\\u6d4e\": 2, \"\\u5b81\": 3, \"\\u00ec\": 67, \"\\u0394\": 9, \"\\u039c\": 13, \"\\u00d8\": 11, \"\\u0392\": 15, \"\\u03c3\": 41, \"\\u6728\": 6, \"\\u5792\": 2, \"\\u54c8\": 5, \"\\u8428\": 5, \"\\u514b\": 12, \"\\u81ea\": 31, \"\\u6cbb\": 31, \"\\u00f9\": 26, \"\\u0639\": 35, \"\\u062f\": 66, \"\\u03bc\": 30, \"\\u01b0\": 5, \"\\u01a1\": 4, \"\\u043c\": 28, \"\\u05d0\": 7, \"\\u05d9\": 42, \"\\u05dc\": 30, \"\\u05ea\": 6, \"\\u00de\": 3, \"\\u758f\": 5, \"\\u52d2\": 5, \"\\u0410\": 23, \"\\u043f\": 19, \"\\u00ff\": 9, \"\\u8fd1\": 2, \"\\u85e4\": 2, \"\\u52c7\": 2, \"\\u68d7\": 3, \"\\u614e\": 2, \"\\u015a\": 7, \"\\u03c7\": 4, \"\\u03a3\": 8, \"\\u03c0\": 15, \"\\uac1c\": 5, \"\\uc131\": 6, \"\\uacf5\": 2, \"\\uc5c5\": 2, \"\\uc9c0\": 2, \"\\uad6c\": 2, \"\\u041f\": 21, \"\\u0634\": 25, \"\\ub178\": 3, \"\\ubb34\": 3, \"\\ud604\": 3, \"\\u76e7\": 3, \"\\u6b66\": 4, \"\\u9249\": 3, \"\\u1e57\": 4, \"\\u04a7\": 2, \"\\u062c\": 17, \"\\u0647\": 27, \"\\u0433\": 38, \"\\u767d\": 3, \"\\u78b1\": 2, \"\\u6ee9\": 2, \"\\u533a\": 29, \"\\u10d8\": 9, \"\\u10db\": 3, \"\\u10d4\": 7, \"\\u10e0\": 9, \"\\u10e3\": 7, \"\\u10da\": 4, \"\\ud574\": 2, \"\\uc8fc\": 3, \"\\uc2dc\": 18, \"\\u0110\": 21, \"\\u0625\": 8, \"\\u041d\": 11, \"\\u014c\": 6, \"\\u0632\": 16, \"\\u0399\": 9, \"\\u2609\": 4, \"\\u02bf\": 9, \"\\u1e25\": 4, \"\\u6771\": 6, \"\\u6d77\": 14, \"\\u65c5\": 4, \"\\u5ba2\": 4, \"\\u9244\": 5, \"\\u9053\": 7, \"\\u05de\": 14, \"\\u05dd\": 13, \"\\u049a\": 3, \"\\u0437\": 26, \"\\u049b\": 5, \"\\u0493\": 4, \"\\u05e8\": 14, \"\\u05e4\": 4, \"\\u05d7\": 4, \"\\u0712\": 3, \"\\u0713\": 2, \"\\u0715\": 5, \"\\u0710\": 5, \"\\u0448\": 14, \"\\u6258\": 3, \"\\u91cc\": 4, \"\\u01d0\": 5, \"\\u05d6\": 4, \"\\u05da\": 2, \"\\u05e9\": 8, \"\\u0414\": 13, \"\\u0436\": 4, \"\\u013d\": 5, \"\\u05e7\": 4, \"\\u05d1\": 10, \"\\u05d5\": 8, \"\\u0409\": 2, \"\\u0458\": 8, \"\\u7279\": 5, \"\\u522b\": 4, \"\\u884c\": 4, \"\\u653f\": 4, \"\\u6f4d\": 2, \"\\u574a\": 2, \"\\u064d\": 2, \"\\u0650\": 6, \"\\u05b8\": 2, \"\\u05e6\": 2, \"\\u05f2\": 2, \"\\u05b7\": 2, \"\\u05d8\": 2, \"\\u0637\": 11, \"\\u0422\": 7, \"\\u0159\": 20, \"\\u0105\": 13, \"\\u0396\": 3, \"\\u03a0\": 9, \"\\u03c6\": 10, \"\\u06cc\": 15, \"\\u0169\": 5, \"\\u0129\": 4, \"\\u03a4\": 5, \"\\u044c\": 14, \"\\u6c96\": 2, \"\\u7530\": 8, \"\\u7dcf\": 3, \"\\u53f8\": 2, \"\\u04c0\": 9, \"\\u897f\": 8, \"\\u85cf\": 7, \"\\u0375\": 8, \"\\u4e4c\": 6, \"\\u6070\": 2, \"\\u05e1\": 2, \"~\": 12, \"\\u9060\": 4, \"\\u96f7\": 2, \"\\uff5e\": 4, \"\\u304f\": 3, \"\\u306b\": 3, \"\\u3042\": 2, \"\\u308b\": 2, \"\\u660e\": 2, \"\\u304b\": 3, \"\\u308a\": 3, \"\\u0418\": 6, \"\\u65b0\": 11, \"\\u7586\": 9, \"\\u7ef4\": 8, \"\\u543e\": 9, \"\\u5c14\": 14, \"\\u06a9\": 5, \"\\u12f0\": 2, \"\\u1261\": 2, \"\\u1265\": 9, \"\\u1215\": 2, \"\\u05e2\": 4, \"\\u05d4\": 7, \"\\u5750\": 2, \"\\u7985\": 2, \"\\u5c09\": 3, \"\\u7281\": 2, \"\\u5cb3\": 2, \"\\u666e\": 3, \"\\u6e56\": 2, \"\\u9999\": 2, \"\\u6e2f\": 2, \"\\u039d\": 4, \"\\u661f\": 3, \"\\uff08\": 3, \"\\u6b63\": 3, \"\\u9762\": 3, \"\\uff09\": 3, \"\\u015d\": 2, \"<\": 3, \"\\u535a\": 5, \"\\u4e50\": 5, \"\\u0413\": 10, \"\\u12d3\": 2, \"\\u1233\": 2, \"\\u00b1\": 6, \"\\u0192\": 2, \"\\u0423\": 4, \"\\u018e\": 4, \"\\u82e5\": 2, \"\\u7f8c\": 2, \"\\u6d1b\": 2, \"\\u6d66\": 2, \"\\u03b6\": 5, \"\\u30e8\": 2, \"\\u30fc\": 4, \"\\u30bc\": 2, \"\\u30b2\": 3, \"\\u30c3\": 4, \"\\u30d9\": 3, \"\\u30b9\": 2, \"\\u017a\": 6, \"\\u5340\": 4, \"\\u0398\": 5, \"\\ud568\": 2, \"\\ud765\": 2, \"\\u9234\": 2, \"\\u8cb4\": 2, \"\\u7537\": 2, \"\\u4e0a\": 2, \"\\u0540\": 5, \"\\u0575\": 6, \"\\u056f\": 4, \"\\u054d\": 4, \"\\u0533\": 3, \"\\u0565\": 3, \"\\u0582\": 6, \"\\u053d\": 2, \"\\u0570\": 2, \"\\u0564\": 2, \"\\u0635\": 16, \"\\u1e5f\": 3, \"\\u1e6f\": 3, \"\\u011d\": 6, \"\\u6ff1\": 2, \"\\u5dde\": 8, \"\\u6ee8\": 2, \"\\u044e\": 4, \"\\u1ec7\": 3, \"\\u82cf\": 3, \"\\u017b\": 5, \"\\u10d9\": 1, \"\\u10d0\": 12, \"\\u10ee\": 2, \"\\u963f\": 6, \"\\u6cf0\": 3, \"\\u0100\": 6, \"\\u0535\": 2, \"\\u0587\": 1, \"\\u9676\": 1, \"\\u016f\": 2, \"\\u03b2\": 5, \"\\u03c8\": 1, \"\\u05c1\": 1, \"\\u05db\": 1, \"\\u12a2\": 2, \"\\u1275\": 2, \"\\u12ee\": 2, \"\\u1335\": 2, \"\\u12eb\": 3, \"\\u6dc4\": 1, \"\\u840a\": 1, \"\\u856a\": 1, \"\\u83b1\": 1, \"\\u829c\": 1, \"\\u0428\": 3, \"\\u044a\": 7, \"\\u044d\": 5, \"\\u5c3c\": 1, \"\\u078e\": 1, \"\\u07aa\": 2, \"\\u0796\": 2, \"\\u07ad\": 1, \"\\u0787\": 2, \"\\u07b0\": 3, \"\\u0783\": 2, \"\\u07a7\": 2, \"\\u0794\": 1, \"\\u07a8\": 1, \"\\u0780\": 1, \"\\u07ab\": 1, \"\\u0789\": 1, \"\\u900a\": 1, \"\\u0111\": 5, \"\\u53f6\": 1, \"\\u57ce\": 7, \"\\u30c8\": 4, \"\\u30e9\": 1, \"\\u0630\": 1, \"\\u2030\": 8, \"\\u548c\": 5, \"\\u95fd\": 1, \"\\u6c5f\": 2, \"\\u1eed\": 3, \"\\u1ed1\": 3, \"\\u5a01\": 1, \"\\uac15\": 1, \"\\uacc4\": 1, \"\\u2299\": 2, \"\\u1455\": 3, \"\\u14d7\": 3, \"\\u1550\": 6, \"\\u152a\": 3, \"\\u140a\": 3, \"\\u1483\": 3, \"\\u0416\": 3, \"\\ub0a8\": 1, \"\\ud3ec\": 1, \"\\ud2b9\": 1, \"\\ubcc4\": 1, \"\\u015b\": 6, \"\\u04d9\": 1, \"\\u04b9\": 1, \"\\u1e35\": 2, \"\\u2190\": 3, \"\\u121d\": 1, \"\\u133d\": 1, \"\\u5510\": 2, \"\\u671d\": 2, \"\\u594e\": 1, \"\\u5c6f\": 1, \"\\u054a\": 1, \"\\u5410\": 1, \"\\u9c81\": 1, \"\\u756a\": 1, \"\\u4e8e\": 2, \"\\u1eaf\": 1, \"\\u859b\": 1, \"\\u0173\": 1, \"\\u03cd\": 5, \"\\u0218\": 1, \"\\u02d0\": 1, \"\\u02bb\": 4, \"\\uc0ac\": 1, \"\\ub9ac\": 1, \"\\uc6d0\": 2, \"\\u0389\": 1, \"\\u1e2a\": 2, \"\\u0444\": 3, \"\\u0457\": 3, \"\\u00ba\": 5, \"\\u5fb3\": 1, \"\\u5ddd\": 2, \"\\u5bb6\": 2, \"\\u5eb7\": 2, \"\\u961c\": 1, \"\\u2113\": 1, \"\\u1e45\": 1, \"\\u0b9a\": 1, \"\\u0bbf\": 1, \"\\u0b99\": 2, \"\\u0bcd\": 4, \"\\u0b95\": 2, \"\\u0baa\": 2, \"\\u0bc2\": 1, \"\\u0bb0\": 1, \"\\u5764\": 2, \"\\u5854\": 6, \"\\u4ec0\": 4, \"\\u5e93\": 3, \"\\u5e72\": 2, \"\\u5409\": 6, \"\\u5de9\": 1, \"\\u7559\": 1, \"\\u01d2\": 1, \"\\u03b8\": 3, \"\\u03a5\": 2, \"\\u03ce\": 2, \"\\u201e\": 4, \"\\uff1b\": 1, \"\\u30ab\": 1, \"\\u30a6\": 1, \"\\u30dc\": 2, \"\\u30d3\": 1, \"\\u30d0\": 1, \"\\u30d7\": 1, \"\\u201f\": 1, \"\\u6cb3\": 3, \"\\u79be\": 1, \"\\u5357\": 1, \"\\u6c99\": 2, \"\\u6e7e\": 1, \"\\u5c11\": 3, \"\\u4f50\": 1, \"\\u016c\": 1, \"\\u040e\": 3, \"\\u4e14\": 1, \"\\u672b\": 1, \"\\u02bc\": 2, \"\\u74e6\": 1, \"\\u63d0\": 2, \"\\u838a\": 1, \"\\u67a3\": 1, \"\\u5e84\": 1, \"\\u5580\": 1, \"\\u1ea5\": 7, \"\\u1ea1\": 2, \"\\u041e\": 4, \"\\u82f1\": 2, \"\\u09ac\": 1, \"\\u09be\": 2, \"\\u0982\": 1, \"\\u09b2\": 1, \"\\u09a6\": 1, \"\\u09c7\": 1, \"\\u09b6\": 1, \"\\u5c06\": 1, \"\\u0425\": 2, \"\\u0686\": 2, \"\\u06b5\": 1, \"\\u0449\": 2, \"\\u56fd\": 2, \"\\u5b89\": 2, \"\\u5168\": 1, \"\\u90e8\": 1, \"\\u5fb7\": 1, \"\\u9644\": 3, \"\\u6cfd\": 2, \"{\": 4, \"}\": 4, \"\\u010e\": 1, \"\\uac00\": 1, \"\\uc704\": 1, \"\\ub20c\": 1, \"\\ub9bc\": 2, \"\\u042e\": 1, \"\\u200f\": 1, \"\\u062b\": 1, \"\\u838e\": 1, \"\\u8f66\": 2, \"\\u5bdf\": 1, \"\\u5e03\": 3, \"\\u67e5\": 1, \"\\u9521\": 1, \"\\u4f2f\": 1, \"\\ubba4\": 1, \"\\uc9c1\": 3, \"\\ubc45\": 1, \"\\ud06c\": 1, \"\\u1ebf\": 3, \"\\u0928\": 1, \"\\u0947\": 1, \"\\u092a\": 1, \"\\u093e\": 1, \"\\u0932\": 1, \"\\u6e05\": 2, \"\\u30c6\": 1, \"\\u30a3\": 1, \"\\u67ef\": 1, \"\\u576a\": 1, \"\\u1e6d\": 1, \"\\u2033\": 1, \"\\u4f0a\": 2, \"\\u6e29\": 2, \"\\u6cc9\": 1, \"\\u7cbe\": 1, \"\\u014f\": 4, \"\\ud3c9\": 2, \"\\uc591\": 1, \"\\ud560\": 2, \"\\u5e73\": 1, \"\\u58cc\": 1, \"\\u76f4\": 2, \"\\u8f44\": 2, \"\\u571f\": 1, \"\\u65b9\": 1, \"\\u6b73\": 1, \"\\u0722\": 3, \"\\u0718\": 3, \"\\u0717\": 1, \"\\u072a\": 3, \"\\u9ea6\": 1, \"\\u76d6\": 1, \"\\ud61c\": 1, \"\\uc0b0\": 2, \"\\u0424\": 1, \"\\u00ae\": 1, \"\\u30af\": 1, \"\\u30fb\": 2, \"\\u30ea\": 1, \"\\u30e3\": 1, \"\\u30be\": 1, \"\\u04e3\": 1, \"\\u04b7
gitextract_fqx72n4r/
├── .flake8
├── .github/
│ └── workflows/
│ └── test.yml
├── .gitignore
├── .pre-commit-config.yaml
├── .readthedocs.yaml
├── Examples.ipynb
├── LICENSE
├── MANIFEST.in
├── README.md
├── docs/
│ ├── Makefile
│ ├── make.bat
│ ├── requirements.txt
│ └── source/
│ ├── conf.py
│ ├── index.md
│ ├── main_classes/
│ │ ├── dependency_parser.md
│ │ ├── named_entity_recognizer.md
│ │ ├── normalizer.md
│ │ ├── part_of_speech_tagger.md
│ │ ├── sentence_splitter.md
│ │ ├── sentiment_analyzer.md
│ │ ├── stemmer_morph_analyzer.md
│ │ ├── stopword_remover.md
│ │ └── word_embeddings.md
│ └── quickstart.md
├── pyproject.toml
├── setup.cfg
├── setup.py
├── tests/
│ └── test_general.py
└── vnlp/
├── __init__.py
├── bin/
│ ├── __init__.py
│ └── vnlp.py
├── dependency_parser/
│ ├── ReadMe.md
│ ├── __init__.py
│ ├── _spu_context_utils.py
│ ├── _treestack_utils.py
│ ├── dependency_parser.py
│ ├── resources/
│ │ └── DP_label_tokenizer.json
│ ├── spu_context_dp.py
│ ├── treestack_dp.py
│ └── utils.py
├── named_entity_recognizer/
│ ├── ReadMe.md
│ ├── __init__.py
│ ├── _charner_utils.py
│ ├── _spu_context_utils.py
│ ├── charner.py
│ ├── named_entity_recognizer.py
│ ├── resources/
│ │ ├── CharNER_char_tokenizer.json
│ │ └── NER_label_tokenizer.json
│ ├── spu_context_ner.py
│ └── utils.py
├── normalizer/
│ ├── ReadMe.md
│ ├── __init__.py
│ ├── _deasciifier.py
│ └── normalizer.py
├── part_of_speech_tagger/
│ ├── ReadMe.md
│ ├── __init__.py
│ ├── _spu_context_utils.py
│ ├── _treestack_utils.py
│ ├── part_of_speech_tagger.py
│ ├── resources/
│ │ └── PoS_label_tokenizer.json
│ ├── spu_context_pos.py
│ └── treestack_pos.py
├── resources/
│ ├── SPU_word_tokenizer_16k.model
│ ├── TB_word_tokenizer.json
│ ├── non_breaking_prefixes_tr.txt
│ ├── turkish_known_words_lexicon.txt
│ └── turkish_stop_words.txt
├── sentence_splitter/
│ ├── ReadMe.md
│ ├── __init__.py
│ └── sentence_splitter.py
├── sentiment_analyzer/
│ ├── ReadMe.md
│ ├── __init__.py
│ ├── _spu_context_bigru_utils.py
│ ├── sentiment_analyzer.py
│ └── spu_context_bigru_sentiment.py
├── stemmer_morph_analyzer/
│ ├── ReadMe.md
│ ├── __init__.py
│ ├── _melik_utils.py
│ ├── _yildiz_analyzer.py
│ ├── resources/
│ │ ├── ExactLookup.txt
│ │ ├── StemListWithFlags_v2.txt
│ │ ├── Stemmer_char_tokenizer.json
│ │ ├── Stemmer_morph_tag_tokenizer.json
│ │ └── Suffixes&Tags.txt
│ └── stemmer_morph_analyzer.py
├── stopword_remover/
│ ├── ReadMe.md
│ ├── __init__.py
│ └── stopword_remover.py
├── tokenizer/
│ ├── ReadMe.md
│ ├── __init__.py
│ └── tokenizer.py
├── turkish_word_embeddings/
│ ├── ReadMe.md
│ └── example.ipynb
└── utils.py
SYMBOL INDEX (154 symbols across 31 files)
FILE: tests/test_general.py
class StemmerTest (line 14) | class StemmerTest(unittest.TestCase):
method setUp (line 15) | def setUp(self):
method test_predict_1 (line 18) | def test_predict_1(self):
method test_predict_2 (line 32) | def test_predict_2(self):
class NerTest (line 43) | class NerTest(unittest.TestCase):
method setUp (line 44) | def setUp(self):
method test_predict_1 (line 47) | def test_predict_1(self):
class PoSTest (line 72) | class PoSTest(unittest.TestCase):
method setUp (line 73) | def setUp(self):
method test_predict_1 (line 76) | def test_predict_1(self):
class DependencyParserTest (line 89) | class DependencyParserTest(unittest.TestCase):
method setUp (line 90) | def setUp(self):
method test_predict_1 (line 93) | def test_predict_1(self):
class SentimentAnalyzerTester (line 113) | class SentimentAnalyzerTester(unittest.TestCase):
method setUp (line 114) | def setUp(self):
method test_predicts (line 117) | def test_predicts(self):
class NormalizerTester (line 160) | class NormalizerTester(unittest.TestCase):
method setUp (line 161) | def setUp(self):
method test_convert_number_to_words (line 173) | def test_convert_number_to_words(self):
method test_deasciify (line 195) | def test_deasciify(self):
method test_misc (line 204) | def test_misc(self):
class StopwordRemoverTest (line 221) | class StopwordRemoverTest(unittest.TestCase):
method setUp (line 222) | def setUp(self):
method test_remove_stopwords (line 225) | def test_remove_stopwords(self):
method test_dynamic_stopwords (line 233) | def test_dynamic_stopwords(self):
FILE: vnlp/bin/vnlp.py
function main (line 26) | def main():
FILE: vnlp/dependency_parser/_spu_context_utils.py
function create_spucontext_dp_model (line 10) | def create_spucontext_dp_model(
function vectorize_arc_label (line 110) | def vectorize_arc_label(w, arcs, labels, sentence_max_len, tokenizer_lab...
function process_single_word_input (line 124) | def process_single_word_input(
FILE: vnlp/dependency_parser/_treestack_utils.py
function create_dependency_parser_model (line 13) | def create_dependency_parser_model(
function preprocess_word (line 231) | def preprocess_word(word):
function process_single_word_input (line 238) | def process_single_word_input(
function convert_numbers_to_zero (line 465) | def convert_numbers_to_zero(text_: str):
FILE: vnlp/dependency_parser/dependency_parser.py
class DependencyParser (line 7) | class DependencyParser:
method __init__ (line 17) | def __init__(self, model="SPUContextDP", evaluate=False):
method predict (line 32) | def predict(
method __getattr__ (line 84) | def __getattr__(self, name):
FILE: vnlp/dependency_parser/spu_context_dp.py
class SPUContextDP (line 86) | class SPUContextDP:
method __init__ (line 96) | def __init__(self, evaluate):
method predict (line 135) | def predict(
FILE: vnlp/dependency_parser/treestack_dp.py
class TreeStackDP (line 104) | class TreeStackDP:
method __init__ (line 116) | def __init__(self, evaluate):
method predict (line 173) | def predict(
FILE: vnlp/dependency_parser/utils.py
function dp_pos_to_displacy_format (line 4) | def dp_pos_to_displacy_format(dp_result, pos_result=None):
function decode_arc_label_vector (line 51) | def decode_arc_label_vector(logits, SENTENCE_MAX_LEN, LABEL_VOCAB_SIZE):
FILE: vnlp/named_entity_recognizer/_charner_utils.py
function create_charner_model (line 4) | def create_charner_model(
FILE: vnlp/named_entity_recognizer/_spu_context_utils.py
function create_spucontext_ner_model (line 10) | def create_spucontext_ner_model(
function process_single_word_input (line 110) | def process_single_word_input(
FILE: vnlp/named_entity_recognizer/charner.py
class CharNER (line 47) | class CharNER:
method __init__ (line 61) | def __init__(self, evaluate):
method _predict_char_level (line 95) | def _predict_char_level(
method _charner_decoder (line 123) | def _charner_decoder(
method predict (line 159) | def predict(
FILE: vnlp/named_entity_recognizer/named_entity_recognizer.py
class NamedEntityRecognizer (line 7) | class NamedEntityRecognizer:
method __init__ (line 17) | def __init__(self, model="SPUContextNER", evaluate=False):
method predict (line 32) | def predict(
FILE: vnlp/named_entity_recognizer/spu_context_ner.py
class SPUContextNER (line 82) | class SPUContextNER:
method __init__ (line 92) | def __init__(self, evaluate):
method predict (line 131) | def predict(
FILE: vnlp/named_entity_recognizer/utils.py
function ner_to_displacy_format (line 4) | def ner_to_displacy_format(text, ner_result):
FILE: vnlp/normalizer/_deasciifier.py
class Deasciifier (line 5) | class Deasciifier:
method __init__ (line 13547) | def __init__(self, ascii_string):
method print_turkish_string (line 13551) | def print_turkish_string(self):
method set_char_at (line 13554) | def set_char_at(self, mystr, pos, c):
method convert_to_turkish (line 13557) | def convert_to_turkish(self):
method turkish_toggle_accent (line 13577) | def turkish_toggle_accent(self, c):
method turkish_need_correction (line 13606) | def turkish_need_correction(self, char, point=0):
method turkish_match_pattern (line 13627) | def turkish_match_pattern(self, dlist, point=0):
method turkish_get_context (line 13649) | def turkish_get_context(self, size=turkish_context_size, point=0):
FILE: vnlp/normalizer/normalizer.py
class Normalizer (line 9) | class Normalizer:
method __init__ (line 25) | def __init__(self):
method lower_case (line 40) | def lower_case(text: str) -> str:
method remove_punctuations (line 75) | def remove_punctuations(text: str) -> str:
method remove_accent_marks (line 95) | def remove_accent_marks(text: str) -> str:
method deasciify (line 130) | def deasciify(tokens: List[str]) -> List[str]:
method correct_typos (line 156) | def correct_typos(self, text: str) -> str:
method convert_numbers_to_words (line 184) | def convert_numbers_to_words(
method _is_token_valid_turkish (line 258) | def _is_token_valid_turkish(self, token):
method _int_to_words (line 273) | def _int_to_words(self, main_num, put_commas=False):
method _num_to_words (line 370) | def _num_to_words(self, num, num_dec_digits):
FILE: vnlp/part_of_speech_tagger/_spu_context_utils.py
function create_spucontext_pos_model (line 10) | def create_spucontext_pos_model(
function process_single_word_input (line 108) | def process_single_word_input(
FILE: vnlp/part_of_speech_tagger/_treestack_utils.py
function create_pos_tagger_model (line 10) | def create_pos_tagger_model(
function preprocess_word (line 185) | def preprocess_word(word):
function process_single_word_input (line 192) | def process_single_word_input(
function convert_numbers_to_zero (line 390) | def convert_numbers_to_zero(text_: str):
FILE: vnlp/part_of_speech_tagger/part_of_speech_tagger.py
class PoSTagger (line 7) | class PoSTagger:
method __init__ (line 17) | def __init__(self, model="SPUContextPoS", evaluate=False, *args):
method predict (line 36) | def predict(self, sentence: str) -> List[Tuple[str, str]]:
method __getattr__ (line 65) | def __getattr__(self, name):
FILE: vnlp/part_of_speech_tagger/spu_context_pos.py
class SPUContextPoS (line 81) | class SPUContextPoS:
method __init__ (line 91) | def __init__(self, evaluate):
method predict (line 130) | def predict(self, sentence: str) -> List[Tuple[str, str]]:
FILE: vnlp/part_of_speech_tagger/treestack_pos.py
class TreeStackPoS (line 90) | class TreeStackPoS:
method __init__ (line 101) | def __init__(self, evaluate, stemmer_analyzer=None):
method predict (line 150) | def predict(self, sentence: str) -> List[Tuple[str, str]]:
FILE: vnlp/sentence_splitter/sentence_splitter.py
class SentenceSplitter (line 10) | class SentenceSplitter:
class _PrefixType (line 19) | class _PrefixType(Enum):
method __init__ (line 23) | def __init__(self): # ISO 639-1 language code
method _split (line 51) | def _split(self, text): # noqa: C901
method split_sentences (line 185) | def split_sentences(self, text: str) -> List[str]:
FILE: vnlp/sentiment_analyzer/_spu_context_bigru_utils.py
function create_spucbigru_sentiment_model (line 5) | def create_spucbigru_sentiment_model(
function process_text_input (line 47) | def process_text_input(text, tokenizer, TEXT_MAX_LEN):
FILE: vnlp/sentiment_analyzer/sentiment_analyzer.py
class SentimentAnalyzer (line 4) | class SentimentAnalyzer:
method __init__ (line 14) | def __init__(self, model="SPUCBiGRUSentimentAnalyzer", evaluate=False):
method predict (line 26) | def predict(self, text: str) -> int:
method predict_proba (line 52) | def predict_proba(self, text: str) -> float:
method __getattr__ (line 75) | def __getattr__(self, name):
FILE: vnlp/sentiment_analyzer/spu_context_bigru_sentiment.py
class SPUCBiGRUSentimentAnalyzer (line 73) | class SPUCBiGRUSentimentAnalyzer:
method __init__ (line 83) | def __init__(self, evaluate):
method predict (line 118) | def predict(self, text: str) -> List[Tuple[str, str]]:
method predict_proba (line 132) | def predict_proba(self, text: str) -> float:
FILE: vnlp/stemmer_morph_analyzer/_melik_utils.py
function create_stemmer_model (line 5) | def create_stemmer_model(
function process_input_text (line 186) | def process_input_text(
function tokenize_stems_tags (line 219) | def tokenize_stems_tags(
function tokenize_surface_form_context (line 305) | def tokenize_surface_form_context(
FILE: vnlp/stemmer_morph_analyzer/_yildiz_analyzer.py
class TurkishStemSuffixCandidateGenerator (line 10) | class TurkishStemSuffixCandidateGenerator(object):
method __init__ (line 57) | def __init__(
method read_exact_lookup_table (line 73) | def read_exact_lookup_table(self):
method read_suffix_dic (line 85) | def read_suffix_dic(self):
method read_stem_list (line 98) | def read_stem_list(self):
method _parse_flag (line 119) | def _parse_flag(flag):
method _transform_soft_consonants (line 130) | def _transform_soft_consonants(text):
method _root_transform (line 144) | def _root_transform(candidate_roots):
method suffix_transform (line 157) | def suffix_transform(cls, candidate_suffixes):
method suffix_transform_single (line 164) | def suffix_transform_single(cls, candidate_suffix):
method _add_candidate_stem_suffix (line 175) | def _add_candidate_stem_suffix(
method get_stem_suffix_candidates (line 279) | def get_stem_suffix_candidates(self, surface_word):
method get_tags (line 339) | def get_tags(self, suffix, stem_tags=None):
method get_analysis_candidates (line 369) | def get_analysis_candidates(self, surface_word):
function to_lower (line 483) | def to_lower(text):
function capitalize (line 494) | def capitalize(text):
function asciify (line 501) | def asciify(text):
function get_tags_from_analysis (line 517) | def get_tags_from_analysis(analysis):
function get_root_from_analysis (line 524) | def get_root_from_analysis(analysis):
function get_pos_from_analysis (line 531) | def get_pos_from_analysis(analysis):
function get_tags_str_from_analysis (line 538) | def get_tags_str_from_analysis(analysis):
function standardize_tags (line 545) | def standardize_tags(tags):
function convert_tag_list_to_str (line 553) | def convert_tag_list_to_str(tags):
FILE: vnlp/stemmer_morph_analyzer/stemmer_morph_analyzer.py
class StemmerAnalyzer (line 56) | class StemmerAnalyzer:
method __init__ (line 71) | def __init__(self, evaluate=False):
method predict (line 116) | def predict(self, sentence: str, batch_size: int = 64) -> List[str]:
FILE: vnlp/stopword_remover/stopword_remover.py
class StopwordRemover (line 14) | class StopwordRemover:
method __init__ (line 27) | def __init__(self):
method dynamically_detect_stop_words (line 33) | def dynamically_detect_stop_words(
method add_to_stop_words (line 104) | def add_to_stop_words(self, novel_stop_words: List[str]):
method drop_stop_words (line 120) | def drop_stop_words(self, list_of_tokens: List[str]) -> List[str]:
FILE: vnlp/tokenizer/tokenizer.py
function WordPunctTokenize (line 5) | def WordPunctTokenize(text: str) -> List[str]:
function TreebankWordTokenize (line 19) | def TreebankWordTokenize(text: str) -> List[str]:
FILE: vnlp/utils.py
function check_and_download (line 9) | def check_and_download(file_path, file_url):
function load_keras_tokenizer (line 27) | def load_keras_tokenizer(tokenizer_json_file_path):
function create_rnn_stacks (line 40) | def create_rnn_stacks(
function tokenize_single_word (line 65) | def tokenize_single_word(word, tokenizer_word, TOKEN_PIECE_MAX_LEN):
function process_word_context (line 76) | def process_word_context(
Condensed preview — 94 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (8,580K chars).
[
{
"path": ".flake8",
"chars": 119,
"preview": "[flake8]\nignore = E203, E266, E501, W503, F403, F401\nmax-line-length = 79\nmax-complexity = 18\nselect = B,C,E,F,W,T4,B9\n"
},
{
"path": ".github/workflows/test.yml",
"chars": 639,
"preview": "name: Python check\n\non: [push]\n\njobs:\n build:\n\n runs-on: ubuntu-latest\n strategy:\n matrix:\n python-ve"
},
{
"path": ".gitignore",
"chars": 2017,
"preview": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# Externally managed resources\nvnlp/resources"
},
{
"path": ".pre-commit-config.yaml",
"chars": 181,
"preview": "repos:\n- repo: https://github.com/psf/black\n rev: 23.1.0\n hooks:\n - id: black-jupyter\n- repo: https://githu"
},
{
"path": ".readthedocs.yaml",
"chars": 673,
"preview": "# .readthedocs.yaml\n# Read the Docs configuration file\n# See https://docs.readthedocs.io/en/stable/config-file/v2.html f"
},
{
"path": "Examples.ipynb",
"chars": 25711,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"id\": \"6c310b03\",\n \"metadata\": {},\n \"source\": [\n \"#### Morpholog"
},
{
"path": "LICENSE",
"chars": 34523,
"preview": " GNU AFFERO GENERAL PUBLIC LICENSE\n Version 3, 19 November 2007\n\n Copyright (C)"
},
{
"path": "MANIFEST.in",
"chars": 237,
"preview": "include README.md\ninclude LICENSE\nrecursive-include vnlp *.md\nrecursive-include vnlp *.py\nrecursive-include vnlp *.json\n"
},
{
"path": "README.md",
"chars": 2868,
"preview": "<img src=\"https://github.com/vngrs-ai/vnlp/blob/main/img/logo.png?raw=true\" width=\"256\">\n\n## VNLP: Turkish NLP Tools\nSta"
},
{
"path": "docs/Makefile",
"chars": 638,
"preview": "# Minimal makefile for Sphinx documentation\n#\n\n# You can set these variables from the command line, and also\n# from the "
},
{
"path": "docs/make.bat",
"chars": 764,
"preview": "@ECHO OFF\n\npushd %~dp0\n\nREM Command file for Sphinx documentation\n\nif \"%SPHINXBUILD%\" == \"\" (\n\tset SPHINXBUILD=sphinx-bu"
},
{
"path": "docs/requirements.txt",
"chars": 21,
"preview": "sphinx_theme\nsphinx<7"
},
{
"path": "docs/source/conf.py",
"chars": 1806,
"preview": "# Configuration file for the Sphinx documentation builder.\nimport os\nimport sys\nimport sphinx_theme\n\nsys.path.insert(0, "
},
{
"path": "docs/source/index.md",
"chars": 936,
"preview": "Welcome to VNLP's documentation!\n===================================\n\n**VNLP** is a Python library for developers workin"
},
{
"path": "docs/source/main_classes/dependency_parser.md",
"chars": 385,
"preview": "Dependency Parser\n----------\n\n.. automodule:: vnlp.dependency_parser.dependency_parser\n :members:\n\nSentencePiece Unig"
},
{
"path": "docs/source/main_classes/named_entity_recognizer.md",
"chars": 396,
"preview": "Named Entity Recognizer\n----------\n\n.. automodule:: vnlp.named_entity_recognizer.named_entity_recognizer\n :members:\n\n"
},
{
"path": "docs/source/main_classes/normalizer.md",
"chars": 80,
"preview": "Normalizer\n----------\n\n.. automodule:: vnlp.normalizer.normalizer\n :members:\n"
},
{
"path": "docs/source/main_classes/part_of_speech_tagger.md",
"chars": 415,
"preview": "Part of Speech Tagger\n----------\n\n.. automodule:: vnlp.part_of_speech_tagger.part_of_speech_tagger\n :members:\n\nSenten"
},
{
"path": "docs/source/main_classes/sentence_splitter.md",
"chars": 100,
"preview": "Sentence Splitter\n----------\n\n.. automodule:: vnlp.sentence_splitter.sentence_splitter\n :members:"
},
{
"path": "docs/source/main_classes/sentiment_analyzer.md",
"chars": 277,
"preview": "Sentiment Analyzer\n----------\n\n.. automodule:: vnlp.sentiment_analyzer.sentiment_analyzer\n :members:\n\nSentencePiece U"
},
{
"path": "docs/source/main_classes/stemmer_morph_analyzer.md",
"chars": 140,
"preview": "Stemmer: Morphological Analyzer & Disambiguator\n----------\n\n.. automodule:: vnlp.stemmer_morph_analyzer.stemmer_morph_an"
},
{
"path": "docs/source/main_classes/stopword_remover.md",
"chars": 97,
"preview": "Stopword Remover\n----------\n\n.. automodule:: vnlp.stopword_remover.stopword_remover\n :members:"
},
{
"path": "docs/source/main_classes/word_embeddings.md",
"chars": 4617,
"preview": "**Word Embeddings**\n----------\n- `Word2Vec <https://arxiv.org/pdf/1301.3781.pdf>`_ , `FastText <https://arxiv.org/pdf/16"
},
{
"path": "docs/source/quickstart.md",
"chars": 1653,
"preview": "Quickstart\n===================================\n\nInstallation\n------------\n\nInstallation is possible via pip.\n\n.. code-bl"
},
{
"path": "pyproject.toml",
"chars": 281,
"preview": "[build-system]\nbuild-backend = \"setuptools.build_meta\"\nrequires = [\"setuptools\", \"wheel\"]\n\n[tool.black]\nline-length = 79"
},
{
"path": "setup.cfg",
"chars": 59,
"preview": "[metadata]\ndescription-file=README.md\nlicense_files=LICENSE"
},
{
"path": "setup.py",
"chars": 2101,
"preview": "from setuptools import setup, find_packages\n\nwith open(\"README.md\", \"r\", encoding=\"utf-8\") as readme_file:\n README = "
},
{
"path": "tests/test_general.py",
"chars": 7682,
"preview": "import unittest\n\nfrom vnlp import (\n DependencyParser,\n PoSTagger,\n NamedEntityRecognizer,\n StemmerAnalyzer,"
},
{
"path": "vnlp/__init__.py",
"chars": 878,
"preview": "import os\nimport tensorflow as tf\n\nfrom .dependency_parser import DependencyParser\nfrom .named_entity_recognizer import "
},
{
"path": "vnlp/bin/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "vnlp/bin/vnlp.py",
"chars": 4085,
"preview": "import argparse\nimport os\n\nfrom vnlp import (\n StemmerAnalyzer,\n NamedEntityRecognizer,\n DependencyParser,\n "
},
{
"path": "vnlp/dependency_parser/ReadMe.md",
"chars": 3056,
"preview": "### Dependency Parser\n- Dependency Parser implementations of VNLP.\n- Details of each model are provided below.\n\n- Input "
},
{
"path": "vnlp/dependency_parser/__init__.py",
"chars": 80,
"preview": "from .dependency_parser import DependencyParser\n\n__all__ = [\"DependencyParser\"]\n"
},
{
"path": "vnlp/dependency_parser/_spu_context_utils.py",
"chars": 5345,
"preview": "import tensorflow as tf\nimport numpy as np\n\nfrom ..utils import create_rnn_stacks, process_word_context\n\nTOKEN_PIECE_MAX"
},
{
"path": "vnlp/dependency_parser/_treestack_utils.py",
"chars": 16580,
"preview": "import numpy as np\nimport tensorflow as tf\n\nfrom ..normalizer import Normalizer\n\nsentence_max_len = 40\ntag_max_len = 15\n"
},
{
"path": "vnlp/dependency_parser/dependency_parser.py",
"chars": 2852,
"preview": "from typing import List, Tuple\n\nfrom .spu_context_dp import SPUContextDP\nfrom .treestack_dp import TreeStackDP\n\n\nclass D"
},
{
"path": "vnlp/dependency_parser/resources/DP_label_tokenizer.json",
"chars": 4367,
"preview": "{\"class_name\": \"Tokenizer\", \"config\": {\"num_words\": null, \"filters\": null, \"lower\": false, \"split\": \" \", \"char_level\": f"
},
{
"path": "vnlp/dependency_parser/spu_context_dp.py",
"chars": 7080,
"preview": "from typing import List, Tuple\n\nimport pickle\n\nimport numpy as np\nimport tensorflow as tf\n\nimport sentencepiece as spm\n\n"
},
{
"path": "vnlp/dependency_parser/treestack_dp.py",
"chars": 9725,
"preview": "from typing import List, Tuple\n\nimport pickle\n\nimport tensorflow as tf\nimport numpy as np\n\nfrom ..stemmer_morph_analyzer"
},
{
"path": "vnlp/dependency_parser/utils.py",
"chars": 1988,
"preview": "import numpy as np\n\n\ndef dp_pos_to_displacy_format(dp_result, pos_result=None):\n \"\"\"\n Converts Dependency Parser r"
},
{
"path": "vnlp/named_entity_recognizer/ReadMe.md",
"chars": 3172,
"preview": "### Named Entity Recognizer (NER)\n- Named Entity Recognition implementations of VNLP.\n- Details of each model are provid"
},
{
"path": "vnlp/named_entity_recognizer/__init__.py",
"chars": 96,
"preview": "from .named_entity_recognizer import NamedEntityRecognizer\n\n__all__ = [\"NamedEntityRecognizer\"]\n"
},
{
"path": "vnlp/named_entity_recognizer/_charner_utils.py",
"chars": 851,
"preview": "import tensorflow as tf\n\n\ndef create_charner_model(\n char_vocab_size,\n embed_size,\n seq_len_max,\n num_rnn_st"
},
{
"path": "vnlp/named_entity_recognizer/_spu_context_utils.py",
"chars": 4783,
"preview": "import tensorflow as tf\nimport numpy as np\n\nfrom ..utils import create_rnn_stacks, process_word_context\n\nTOKEN_PIECE_MAX"
},
{
"path": "vnlp/named_entity_recognizer/charner.py",
"chars": 7394,
"preview": "from typing import List, Tuple\n\nimport pickle\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom ..tokenizer import WordP"
},
{
"path": "vnlp/named_entity_recognizer/named_entity_recognizer.py",
"chars": 2454,
"preview": "from typing import List, Tuple\n\nfrom .charner import CharNER\nfrom .spu_context_ner import SPUContextNER\n\n\nclass NamedEnt"
},
{
"path": "vnlp/named_entity_recognizer/resources/CharNER_char_tokenizer.json",
"chars": 84494,
"preview": "{\"class_name\": \"Tokenizer\", \"config\": {\"num_words\": 150, \"filters\": null, \"lower\": false, \"split\": \" \", \"char_level\": fa"
},
{
"path": "vnlp/named_entity_recognizer/resources/NER_label_tokenizer.json",
"chars": 565,
"preview": "{\"class_name\": \"Tokenizer\", \"config\": {\"num_words\": null, \"filters\": null, \"lower\": false, \"split\": \" \", \"char_level\": f"
},
{
"path": "vnlp/named_entity_recognizer/spu_context_ner.py",
"chars": 6036,
"preview": "from typing import List, Tuple\n\nimport pickle\n\nimport numpy as np\n\nimport sentencepiece as spm\n\nfrom ..tokenizer import "
},
{
"path": "vnlp/named_entity_recognizer/utils.py",
"chars": 2287,
"preview": "import re\n\n\ndef ner_to_displacy_format(text, ner_result):\n # Obtain Token Start and End indices\n token_loc = {}\n "
},
{
"path": "vnlp/normalizer/ReadMe.md",
"chars": 528,
"preview": "#### Normalizer\n\nContains following functionality:\n- Spelling uses [jamspell](https://github.com/bakwc/JamSpell/) algori"
},
{
"path": "vnlp/normalizer/__init__.py",
"chars": 61,
"preview": "from .normalizer import Normalizer\n\n__all__ = [\"Normalizer\"]\n"
},
{
"path": "vnlp/normalizer/_deasciifier.py",
"chars": 370904,
"preview": "# -*- coding: utf-8 -*-\nimport string\n\n\nclass Deasciifier:\n \"\"\"\n This class provides a function to deasciify a giv"
},
{
"path": "vnlp/normalizer/normalizer.py",
"chars": 11895,
"preview": "from typing import List\nfrom pathlib import Path\n\nfrom ._deasciifier import Deasciifier\nfrom ..stemmer_morph_analyzer im"
},
{
"path": "vnlp/part_of_speech_tagger/ReadMe.md",
"chars": 3331,
"preview": "### Part of Speech (PoS) Tagger\n- Part of Speech tagging implementations of VNLP.\n- Details of each model are provided b"
},
{
"path": "vnlp/part_of_speech_tagger/__init__.py",
"chars": 70,
"preview": "from .part_of_speech_tagger import PoSTagger\n\n__all__ = [\"PoSTagger\"]\n"
},
{
"path": "vnlp/part_of_speech_tagger/_spu_context_utils.py",
"chars": 4815,
"preview": "import tensorflow as tf\nimport numpy as np\n\nfrom ..utils import create_rnn_stacks, process_word_context\n\nTOKEN_PIECE_MAX"
},
{
"path": "vnlp/part_of_speech_tagger/_treestack_utils.py",
"chars": 13950,
"preview": "import numpy as np\nimport tensorflow as tf\n\nfrom ..normalizer import Normalizer\n\nsentence_max_len = 40\ntag_max_len = 15\n"
},
{
"path": "vnlp/part_of_speech_tagger/part_of_speech_tagger.py",
"chars": 1871,
"preview": "from typing import List, Tuple\n\nfrom .spu_context_pos import SPUContextPoS\nfrom .treestack_pos import TreeStackPoS\n\n\ncla"
},
{
"path": "vnlp/part_of_speech_tagger/resources/PoS_label_tokenizer.json",
"chars": 1548,
"preview": "{\"class_name\": \"Tokenizer\", \"config\": {\"num_words\": null, \"filters\": null, \"lower\": false, \"split\": \" \", \"char_level\": f"
},
{
"path": "vnlp/part_of_speech_tagger/spu_context_pos.py",
"chars": 5596,
"preview": "from typing import List, Tuple\n\nimport pickle\n\nimport numpy as np\n\nimport sentencepiece as spm\n\nfrom ..tokenizer import "
},
{
"path": "vnlp/part_of_speech_tagger/treestack_pos.py",
"chars": 7572,
"preview": "from typing import List, Tuple\n\nimport pickle\n\nimport tensorflow as tf\nimport numpy as np\n\nfrom ..stemmer_morph_analyzer"
},
{
"path": "vnlp/resources/TB_word_tokenizer.json",
"chars": 3645800,
"preview": "{\"class_name\": \"Tokenizer\", \"config\": {\"num_words\": null, \"filters\": \"!\\\"#$%&()*+,-./:;<=>?@[\\\\]^_`{|}~\\t\\n\", \"lower\": f"
},
{
"path": "vnlp/resources/non_breaking_prefixes_tr.txt",
"chars": 6056,
"preview": "# This is a non-breaking prefix list for the Turkish language.\r\n# The file is used for sentence tokenization (text -> se"
},
{
"path": "vnlp/resources/turkish_known_words_lexicon.txt",
"chars": 1201907,
"preview": "a\r\nab\r\naba\r\nabacı\r\nabacılık\r\nabadan\r\nabadi\r\nabadı\r\nabajur\r\nabajurcu\r\nabajurculuk\r\nabajurcunun\r\nabajurlu\r\nabajursuz\r\nabaj"
},
{
"path": "vnlp/resources/turkish_stop_words.txt",
"chars": 1515,
"preview": "a\nacaba\nama\nancak\narada\nartık\nasla\naslında\nayrıca\naz\nbana\nbazen\nbazı\nbazıları\nbelki\nben\nbenden\nbeni\nbenim\nberi\nbile\nbilh"
},
{
"path": "vnlp/sentence_splitter/ReadMe.md",
"chars": 227,
"preview": "#### Sentence Splitter\n\nThis is an adapted version of Koehn and Schroeder's Sentence Splitter found in https://pypi.org/"
},
{
"path": "vnlp/sentence_splitter/__init__.py",
"chars": 80,
"preview": "from .sentence_splitter import SentenceSplitter\n\n__all__ = [\"SentenceSplitter\"]\n"
},
{
"path": "vnlp/sentence_splitter/sentence_splitter.py",
"chars": 8164,
"preview": "from typing import List\r\nfrom pathlib import Path\r\nfrom enum import Enum\r\nimport regex\r\n\r\nPATH = \"../resources/\"\r\nPATH ="
},
{
"path": "vnlp/sentiment_analyzer/ReadMe.md",
"chars": 1571,
"preview": "### Sentiment Analyzer\n\n- This is a Deep Bidirectional GRU based Sentiment Analysis classifier implementation.\n- It uses"
},
{
"path": "vnlp/sentiment_analyzer/__init__.py",
"chars": 83,
"preview": "from .sentiment_analyzer import SentimentAnalyzer\n\n__all__ = [\"SentimentAnalyzer\"]\n"
},
{
"path": "vnlp/sentiment_analyzer/_spu_context_bigru_utils.py",
"chars": 1913,
"preview": "import tensorflow as tf\nimport numpy as np\n\n\ndef create_spucbigru_sentiment_model(\n TEXT_MAX_LEN,\n VOCAB_SIZE,\n "
},
{
"path": "vnlp/sentiment_analyzer/sentiment_analyzer.py",
"chars": 2151,
"preview": "from .spu_context_bigru_sentiment import SPUCBiGRUSentimentAnalyzer\n\n\nclass SentimentAnalyzer:\n \"\"\"\n Main API clas"
},
{
"path": "vnlp/sentiment_analyzer/spu_context_bigru_sentiment.py",
"chars": 5324,
"preview": "from typing import List, Tuple\n\nimport pickle\n\nimport numpy as np\n\nimport sentencepiece as spm\n\nfrom ..utils import chec"
},
{
"path": "vnlp/stemmer_morph_analyzer/ReadMe.md",
"chars": 1569,
"preview": "#### Stemmer: Morphological Analyzer & Disambiguator\n\n- This is an implementation of \"The Role of Context in Neural Morp"
},
{
"path": "vnlp/stemmer_morph_analyzer/__init__.py",
"chars": 83,
"preview": "from .stemmer_morph_analyzer import StemmerAnalyzer\n\n__all__ = [\"StemmerAnalyzer\"]\n"
},
{
"path": "vnlp/stemmer_morph_analyzer/_melik_utils.py",
"chars": 14944,
"preview": "import numpy as np\nimport tensorflow as tf\n\n\ndef create_stemmer_model(\n num_max_analysis,\n stem_max_len,\n char_"
},
{
"path": "vnlp/stemmer_morph_analyzer/_yildiz_analyzer.py",
"chars": 20334,
"preview": "# -*- coding: utf-8 -*-\nimport re\nimport math\nimport os\nfrom collections import namedtuple\n\nresources_path = os.path.joi"
},
{
"path": "vnlp/stemmer_morph_analyzer/resources/ExactLookup.txt",
"chars": 337789,
"preview": "ön\t/ön+Adj\nson\t/son+Adj\niç\t/iç+Adj\nvar\t/var+Adj /var+Verb+Pos+Imp+A2sg\nyok\t/yok+Adj\ndış\t/dış+Adj\nileri\t/ileri+Noun+A3sg+"
},
{
"path": "vnlp/stemmer_morph_analyzer/resources/StemListWithFlags_v2.txt",
"chars": 937746,
"preview": "Ertuğral\t4096\naytış\t1024\nErturun\t4096\nZulal\t4096\nkapodokya'y\t64\nfüzen\t64\nÇakara\t4096\nLawrence\t4096\nBenzet\t4096\nÖzgüvenç\t"
},
{
"path": "vnlp/stemmer_morph_analyzer/resources/Stemmer_char_tokenizer.json",
"chars": 8424,
"preview": "{\"class_name\": \"Tokenizer\", \"config\": {\"num_words\": null, \"filters\": null, \"lower\": false, \"split\": \" \", \"char_level\": t"
},
{
"path": "vnlp/stemmer_morph_analyzer/resources/Stemmer_morph_tag_tokenizer.json",
"chars": 10883,
"preview": "{\"class_name\": \"Tokenizer\", \"config\": {\"num_words\": null, \"filters\": null, \"lower\": false, \"split\": \" \", \"char_level\": f"
},
{
"path": "vnlp/stemmer_morph_analyzer/stemmer_morph_analyzer.py",
"chars": 8456,
"preview": "from typing import List\n\nimport pickle\n\nimport tensorflow as tf\nimport numpy as np\n\nfrom ..tokenizer import TreebankWord"
},
{
"path": "vnlp/stopword_remover/ReadMe.md",
"chars": 731,
"preview": "#### StopWord Remover\n\n- Static stopwords list are taken from https://github.com/ahmetax/trstop and some minor improveme"
},
{
"path": "vnlp/stopword_remover/__init__.py",
"chars": 77,
"preview": "from .stopword_remover import StopwordRemover\n\n__all__ = [\"StopwordRemover\"]\n"
},
{
"path": "vnlp/stopword_remover/stopword_remover.py",
"chars": 5251,
"preview": "from typing import List\n\nfrom pathlib import Path\n\nimport numpy as np\n\n# To suppress zero and nan division errors\nnp.set"
},
{
"path": "vnlp/tokenizer/ReadMe.md",
"chars": 290,
"preview": "Since Tokenization highly depends on custom needs depending on domain, task, etc, Tokenizers here exist as utility funct"
},
{
"path": "vnlp/tokenizer/__init__.py",
"chars": 120,
"preview": "from .tokenizer import WordPunctTokenize, TreebankWordTokenize\n\n__all__ = [\"WordPunctTokenize\", \"TreebankWordTokenize\"]\n"
},
{
"path": "vnlp/tokenizer/tokenizer.py",
"chars": 2441,
"preview": "import re\nfrom typing import List\n\n\ndef WordPunctTokenize(text: str) -> List[str]:\n \"\"\"\n This is a simplified vers"
},
{
"path": "vnlp/turkish_word_embeddings/ReadMe.md",
"chars": 4845,
"preview": "#### Word2Vec and FastText embeddings, SentencePiece Unigram Tokenizer\n\n- Models are trained on a corpus of 32 GBs, made"
},
{
"path": "vnlp/turkish_word_embeddings/example.ipynb",
"chars": 1981,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"execution_count\": 1,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [\n "
},
{
"path": "vnlp/utils.py",
"chars": 4193,
"preview": "import os\nimport logging\n\nimport requests\nimport tensorflow as tf\nimport numpy as np\n\n\ndef check_and_download(file_path,"
}
]
// ... and 2 more files (download for full content)
About this extraction
This page contains the full source code of the vngrs-ai/vnlp GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 94 files (18.3 MB), approximately 1.7M tokens, and a symbol index with 154 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.