├── .gitignore ├── .travis.yml ├── CONTRIBUTING.md ├── Dockerfile ├── LICENSE.md ├── README.md ├── available_models └── example.conf.json ├── data ├── README.md ├── morph │ ├── src.train │ ├── src.valid │ ├── tgt.train │ └── tgt.valid ├── src-test.txt ├── src-train.txt ├── src-val.txt ├── test_model2.src ├── test_model2.tgt ├── tgt-train.txt └── tgt-val.txt ├── docs ├── Makefile ├── generate.sh ├── requirements.txt └── source │ ├── CONTRIBUTING.md │ ├── FAQ.md │ ├── Library.ipynb │ ├── Library.md │ ├── Summarization.md │ ├── conf.py │ ├── examples.rst │ ├── extended.md │ ├── im2text.md │ ├── index.md │ ├── index.rst │ ├── main.md │ ├── modules.rst │ ├── onmt.io.rst │ ├── onmt.modules.rst │ ├── onmt.rst │ ├── onmt.translation.rst │ ├── options │ ├── preprocess.md │ ├── train.md │ └── translate.md │ ├── quickstart.md │ ├── ref.rst │ ├── refs.bib │ └── speech2text.md ├── github_deploy_key_opennmt_opennmt_py.enc ├── onmt ├── Loss.py ├── ModelConstructor.py ├── Models.py ├── Optim.py ├── Trainer.py ├── Utils.py ├── __init__.py ├── io │ ├── AudioDataset.py │ ├── DatasetBase.py │ ├── IO.py │ ├── ImageDataset.py │ ├── TextDataset.py │ └── __init__.py ├── modules │ ├── AudioEncoder.py │ ├── Conv2Conv.py │ ├── ConvMultiStepAttention.py │ ├── CopyGenerator.py │ ├── Embeddings.py │ ├── Gate.py │ ├── GlobalAttention.py │ ├── ImageEncoder.py │ ├── MultiHeadedAttn.py │ ├── NGram.py │ ├── SRU.py │ ├── StackedRNN.py │ ├── StructuredAttention.py │ ├── Transformer.py │ ├── UtilClass.py │ ├── WeightNorm.py │ └── __init__.py ├── opts.py └── translate │ ├── Beam.py │ ├── Penalties.py │ ├── Translation.py │ ├── TranslationServer.py │ ├── Translator.py │ └── __init__.py ├── preprocess.py ├── requirements.opt.txt ├── requirements.txt ├── server.py ├── setup.py ├── test ├── __init__.py ├── pull_request_chk.sh ├── rebuild_test_models.sh ├── test_attention.py ├── test_model.pt ├── test_model2.pt ├── test_models.py ├── test_preprocess.py └── test_simple.py ├── tools ├── README.md ├── apply_bpe.py ├── average_models.py ├── bpe_pipeline.sh ├── detokenize.perl ├── embeddings_to_torch.py ├── extract_embeddings.py ├── learn_bpe.py ├── multi-bleu-detok.perl ├── multi-bleu.perl ├── nonbreaking_prefixes │ ├── README.txt │ ├── nonbreaking_prefix.ca │ ├── nonbreaking_prefix.cs │ ├── nonbreaking_prefix.de │ ├── nonbreaking_prefix.el │ ├── nonbreaking_prefix.en │ ├── nonbreaking_prefix.es │ ├── nonbreaking_prefix.fi │ ├── nonbreaking_prefix.fr │ ├── nonbreaking_prefix.ga │ ├── nonbreaking_prefix.hu │ ├── nonbreaking_prefix.is │ ├── nonbreaking_prefix.it │ ├── nonbreaking_prefix.lt │ ├── nonbreaking_prefix.lv │ ├── nonbreaking_prefix.nl │ ├── nonbreaking_prefix.pl │ ├── nonbreaking_prefix.ro │ ├── nonbreaking_prefix.ru │ ├── nonbreaking_prefix.sk │ ├── nonbreaking_prefix.sl │ ├── nonbreaking_prefix.sv │ ├── nonbreaking_prefix.ta │ ├── nonbreaking_prefix.yue │ └── nonbreaking_prefix.zh ├── release_model.py ├── test_rouge.py └── tokenizer.perl ├── train.py └── translate.py /.gitignore: -------------------------------------------------------------------------------- 1 | # repo-specific stuff 2 | pred.txt 3 | multi-bleu.perl 4 | *.pt 5 | \#*# 6 | .idea 7 | *.sublime-* 8 | .DS_Store 9 | data/ 10 | 11 | # Byte-compiled / optimized / DLL files 12 | __pycache__/ 13 | *.py[cod] 14 | *$py.class 15 | 16 | # C extensions 17 | *.so 18 | 19 | # Distribution / packaging 20 | .Python 21 | build/ 22 | develop-eggs/ 23 | dist/ 24 | downloads/ 25 | eggs/ 26 | .eggs/ 27 | lib/ 28 | lib64/ 29 | parts/ 30 | sdist/ 31 | var/ 32 | wheels/ 33 | *.egg-info/ 34 | .installed.cfg 35 | *.egg 36 | 37 | # PyInstaller 38 | # Usually these files are written by a python script from a template 39 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 40 | *.manifest 41 | *.spec 42 | 43 | # Installer logs 44 | pip-log.txt 45 | pip-delete-this-directory.txt 46 | 47 | # Unit test / coverage reports 48 | htmlcov/ 49 | .tox/ 50 | .coverage 51 | .coverage.* 52 | .cache 53 | nosetests.xml 54 | coverage.xml 55 | *.cover 56 | .hypothesis/ 57 | 58 | # Translations 59 | *.mo 60 | *.pot 61 | 62 | # Django stuff: 63 | *.log 64 | local_settings.py 65 | 66 | # Flask stuff: 67 | instance/ 68 | .webassets-cache 69 | 70 | # Scrapy stuff: 71 | .scrapy 72 | 73 | # Sphinx documentation 74 | docs/_build/ 75 | 76 | # PyBuilder 77 | target/ 78 | 79 | # Jupyter Notebook 80 | .ipynb_checkpoints 81 | 82 | # pyenv 83 | .python-version 84 | 85 | # celery beat schedule file 86 | celerybeat-schedule 87 | 88 | # SageMath parsed files 89 | *.sage.py 90 | 91 | # Environments 92 | .env 93 | .venv 94 | env/ 95 | venv/ 96 | ENV/ 97 | 98 | # Spyder project settings 99 | .spyderproject 100 | .spyproject 101 | 102 | # Rope project settings 103 | .ropeproject 104 | 105 | # mkdocs documentation 106 | /site 107 | 108 | # mypy 109 | .mypy_cache/ 110 | 111 | # Tensorboard 112 | runs/ 113 | scripts/ 114 | notes/ 115 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "2.7" 4 | - "3.5" 5 | cache: pip 6 | before_install: 7 | - sudo apt-get update 8 | - wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh -O miniconda.sh; 9 | - bash miniconda.sh -b -p $HOME/miniconda 10 | - export PATH="$HOME/miniconda/bin:$PATH" 11 | - hash -r 12 | - conda config --set always_yes yes --set changeps1 no 13 | - conda update -q conda 14 | # Useful for debugging any issues with conda 15 | - conda info -a 16 | # freeze the supported pytorch version for consistency 17 | - conda create -q -n test-environment python=$TRAVIS_PYTHON_VERSION pytorch=0.3.0 -c soumith 18 | - source activate test-environment 19 | # use requirements.txt for dependencies 20 | - pip install -r requirements.txt 21 | # optional dependencies for im2text and speech2text 22 | - sudo apt-get install -y sox libsox-dev libsox-fmt-all 23 | - pip install -r requirements.opt.txt 24 | 25 | install: 26 | - python setup.py install 27 | 28 | # Please also add tests to `test/pull_request_chk.sh`. 29 | script: 30 | - wget -O /tmp/im2text.tgz http://lstm.seas.harvard.edu/latex/im2text_small.tgz; tar zxf /tmp/im2text.tgz -C /tmp/; head /tmp/im2text/src-train.txt > /tmp/im2text/src-train-head.txt; head /tmp/im2text/tgt-train.txt > /tmp/im2text/tgt-train-head.txt; head /tmp/im2text/src-val.txt > /tmp/im2text/src-val-head.txt; head /tmp/im2text/tgt-val.txt > /tmp/im2text/tgt-val-head.txt 31 | - wget -O /tmp/speech.tgz http://lstm.seas.harvard.edu/latex/speech.tgz; tar zxf /tmp/speech.tgz -C /tmp/; head /tmp/speech/src-train.txt > /tmp/speech/src-train-head.txt; head /tmp/speech/tgt-train.txt > /tmp/speech/tgt-train-head.txt; head /tmp/speech/src-val.txt > /tmp/speech/src-val-head.txt; head /tmp/speech/tgt-val.txt > /tmp/speech/tgt-val-head.txt 32 | - wget -O /tmp/test_model_speech.pt http://lstm.seas.harvard.edu/latex/test_model_speech.pt 33 | - wget -O /tmp/test_model_im2text.pt http://lstm.seas.harvard.edu/latex/test_model_im2text.pt 34 | - python -m unittest discover 35 | # test nmt preprocessing 36 | - python preprocess.py -train_src data/src-train.txt -train_tgt data/tgt-train.txt -valid_src data/src-val.txt -valid_tgt data/tgt-val.txt -save_data /tmp/data -src_vocab_size 1000 -tgt_vocab_size 1000 && rm -rf /tmp/data*.pt 37 | # test im2text preprocessing 38 | - python preprocess.py -data_type img -src_dir /tmp/im2text/images -train_src /tmp/im2text/src-train.txt -train_tgt /tmp/im2text/tgt-train.txt -valid_src /tmp/im2text/src-val.txt -valid_tgt /tmp/im2text/tgt-val.txt -save_data /tmp/im2text/data && rm -rf /tmp/im2text/data*.pt 39 | # test speech2text preprocessing 40 | - python preprocess.py -data_type audio -src_dir /tmp/speech/an4_dataset -train_src /tmp/speech/src-train.txt -train_tgt /tmp/speech/tgt-train.txt -valid_src /tmp/speech/src-val.txt -valid_tgt /tmp/speech/tgt-val.txt -save_data /tmp/speech/data && rm -rf /tmp/speech/data*.pt 41 | # test nmt translation 42 | - head data/src-test.txt > /tmp/src-test.txt; python translate.py -model test/test_model.pt -src /tmp/src-test.txt -verbose 43 | # test im2text translation 44 | - head /tmp/im2text/src-val.txt > /tmp/im2text/src-val-head.txt; head /tmp/im2text/tgt-val.txt > /tmp/im2text/tgt-val-head.txt; python translate.py -data_type img -src_dir /tmp/im2text/images -model /tmp/test_model_im2text.pt -src /tmp/im2text/src-val-head.txt -tgt /tmp/im2text/tgt-val-head.txt -verbose -out /tmp/im2text/trans 45 | # test speech2text translation 46 | - head /tmp/speech/src-val.txt > /tmp/speech/src-val-head.txt; head /tmp/speech/tgt-val.txt > /tmp/speech/tgt-val-head.txt; python translate.py -data_type audio -src_dir /tmp/speech/an4_dataset -model /tmp/test_model_speech.pt -src /tmp/speech/src-val-head.txt -tgt /tmp/speech/tgt-val-head.txt -verbose -out /tmp/speech/trans; diff /tmp/speech/tgt-val-head.txt /tmp/speech/trans 47 | # test nmt preprocessing and training 48 | - head data/src-val.txt > /tmp/src-val.txt; head data/tgt-val.txt > /tmp/tgt-val.txt; python preprocess.py -train_src /tmp/src-val.txt -train_tgt /tmp/tgt-val.txt -valid_src /tmp/src-val.txt -valid_tgt /tmp/tgt-val.txt -save_data /tmp/q -src_vocab_size 1000 -tgt_vocab_size 1000; python train.py -data /tmp/q -rnn_size 2 -batch_size 10 -word_vec_size 5 -report_every 5 -rnn_size 10 -epochs 1 && rm -rf /tmp/q*.pt 49 | # test nmt preprocessing w/ sharding and training w/copy 50 | - head data/src-val.txt > /tmp/src-val.txt; head data/tgt-val.txt > /tmp/tgt-val.txt; python preprocess.py -train_src /tmp/src-val.txt -train_tgt /tmp/tgt-val.txt -valid_src /tmp/src-val.txt -valid_tgt /tmp/tgt-val.txt -max_shard_size 1 -dynamic_dict -save_data /tmp/q -src_vocab_size 1000 -tgt_vocab_size 1000; python train.py -data /tmp/q -rnn_size 2 -batch_size 10 -word_vec_size 5 -report_every 5 -rnn_size 10 -copy_attn -epochs 1 && rm -rf /tmp/q*.pt 51 | 52 | # test im2text preprocessing and training 53 | - head /tmp/im2text/src-val.txt > /tmp/im2text/src-val-head.txt; head /tmp/im2text/tgt-val.txt > /tmp/im2text/tgt-val-head.txt; python preprocess.py -data_type img -src_dir /tmp/im2text/images -train_src /tmp/im2text/src-val-head.txt -train_tgt /tmp/im2text/tgt-val-head.txt -valid_src /tmp/im2text/src-val-head.txt -valid_tgt /tmp/im2text/tgt-val-head.txt -save_data /tmp/im2text/q; python train.py -model_type img -data /tmp/im2text/q -rnn_size 2 -batch_size 10 -word_vec_size 5 -report_every 5 -rnn_size 10 -epochs 1 && rm -rf /tmp/im2text/q*.pt 54 | # test speech2text preprocessing and training 55 | - head /tmp/speech/src-val.txt > /tmp/speech/src-val-head.txt; head /tmp/speech/tgt-val.txt > /tmp/speech/tgt-val-head.txt; python preprocess.py -data_type audio -src_dir /tmp/speech/an4_dataset -train_src /tmp/speech/src-val-head.txt -train_tgt /tmp/speech/tgt-val-head.txt -valid_src /tmp/speech/src-val-head.txt -valid_tgt /tmp/speech/tgt-val-head.txt -save_data /tmp/speech/q; python train.py -model_type audio -data /tmp/speech/q -rnn_size 2 -batch_size 10 -word_vec_size 5 -report_every 5 -rnn_size 10 -epochs 1 && rm -rf /tmp/speech/q*.pt 56 | # test nmt translation 57 | - python translate.py -model test/test_model2.pt -src data/morph/src.valid -verbose -batch_size 10 -beam_size 10 -tgt data/morph/tgt.valid -out /tmp/trans; diff data/morph/tgt.valid /tmp/trans 58 | # test tool 59 | - PYTHONPATH=$PYTHONPATH:. python tools/extract_embeddings.py -model test/test_model.pt 60 | 61 | env: 62 | global: 63 | # Doctr deploy key for OpenNMT/OpenNMT-py 64 | - secure: "gL0Soefo1cQgAqwiHUrlNyZd/+SI1eJAAjLD3BEDQWXW160eXyjQAAujGgJoCirjOM7cPHVwLzwmK3S7Y3PVM3JOZguOX5Yl4uxMh/mhiEM+RG77SZyv4OGoLFsEQ8RTvIdYdtP6AwyjlkRDXvZql88TqFNYjpXDu8NG+JwEfiIoGIDYxxZ5SlbrZN0IqmQSZ4/CsV6VQiuq99Jn5kqi4MnUZBTcmhqjaztCP1omvsMRdbrG2IVhDKQOCDIO0kaPJrMy2SGzP4GV7ar52bdBtpeP3Xbm6ZOuhDNfds7M/OMHp1wGdl7XwKtolw9MeXhnGBC4gcrqhhMfcQ6XtfVLMLnsB09Ezl3FXX5zWgTB5Pm0X6TgnGrMA25MAdVqKGJpfqZxOKTh4EMb04b6OXrVbxZ88mp+V0NopuxwlTPD8PMfYLWlTe9chh1BnT0iQlLqeA4Hv3+NdpiFb4aq3V3cWTTgMqOoWSGq4t318pqIZ3qbBXBq12DLFgO5n6+M6ZrdxbDUGQvgh8nAiZcIEdodKJ4ABHi1SNCeWOzCoedUdegcbjShHfkMVmNKrncB18aRWwQ3GQJ5qdkjgJmC++uZmkS6+GPM8UmmAy1ZIkRW0aWiitjG6teqtvUHOofNd/TCxX4bhnxAj+mtVIrARCE/ci8topJ6uG4wVJ1TrIkUlAY=" 65 | 66 | matrix: 67 | include: 68 | - env: LINT_CHECK 69 | python: "2.7" 70 | install: pip install flake8 pep8-naming 71 | script: flake8 72 | - python: "3.5" 73 | install: 74 | - python setup.py install 75 | - pip install doctr 76 | script: 77 | - pip install -r docs/requirements.txt 78 | - cd docs/; make html; cd .. 79 | - set -e 80 | - doctr deploy --built-docs docs/build/html/ . 81 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | OpenNMT-py is a community developed project and we love developer contributions. 2 | 3 | Before sending a PR, please do this checklist first: 4 | 5 | - Please run `tools/pull_request_chk.sh` and fix any errors. When adding new functionality, also add tests to this script. Included checks: 6 | 1. flake8 and pep8-naming check for coding style; 7 | 2. unittest; 8 | 3. continuous integration tests listed in `.travis.yml`. 9 | - When adding/modifying class constructor, please make the arguments as same naming style as its superclass in pytorch. 10 | - If your change is based on a paper, please include a clear comment and reference in the code. 11 | - If your function takes/returns tensor arguments, please include assertions to document the sizes. See `GlobalAttention.py` for examples. 12 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM pytorch/pytorch:latest 2 | RUN git clone https://github.com/OpenNMT/OpenNMT-py.git && cd OpenNMT-py && pip install -r requirements.txt && python setup.py install 3 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 OpenNMT 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Work in progress 2 | # Guided Neural Language Generation for Abstractive Summarization Using AMR 3 | 4 | This repository contains code for our EMNLP 2018 paper "[Guided Neural Language Generation for Abstractive Summarization Using AMR](https://arxiv.org/abs/1808.09160)" 5 | 6 | # Obtaining the Dataset 7 | 8 | We used the [Abstract Meaning Representation Annotation Release 2.0](https://catalog.ldc.upenn.edu/LDC2017T10) which contains manually annotated document and summary AMR. 9 | 10 | # Preprocessing the Data 11 | 12 | For preprocessing, clone the [AMR preprocessing](https://github.com/sheffieldnlp/AMR-Preprocessing) repository. 13 | 14 | ``` 15 | git clone https://github.com/sheffieldnlp/AMR-Preprocessing 16 | ``` 17 | 18 | Run the AMR linearizing where the input is the system summary AMR from Liu's summarizer ($F) and the AMR raw dataset ($AMR). Here we use the test dataset. Run the preprocessing on the training, and validation dataset if you want to train the model. 19 | 20 | ``` 21 | export F_TRAIN=//amr-release-2.0-amrs-training.txt 22 | export F_TEST=//amr-release-2.0-amrs-test.txt 23 | export F_DEV=//amr-release-2.0-amrs-dev.txt 24 | export OUTPUT=// 25 | python var_free_amrs.py -f $F_TRAIN -output_path $OUTPUT --custom_parentheses -no_semantics --delete_amr_var 26 | python var_free_amrs.py -f $F_TEST -output_path $OUTPUT --custom_parentheses -no_semantics --delete_amr_var 27 | python var_free_amrs.py -f $F_DEV -output_path $OUTPUT --custom_parentheses -no_semantics --delete_amr_var 28 | ``` 29 | 30 | For each set (train, test and dev) the script will produce a set of two files: the sentence (*.sent) and its respective linearized AMR (*.tf) files. 31 | 32 | # Training New Model 33 | ``` 34 | export SRC=//all_amr-release-2.0-amrs-training.txt.tf 35 | export TGT=//all_amr-release-2.0-amrs-training.txt.sent 36 | export SRC_VALID=//all_amr-release-2-0-amrs-dev-all.txt.tf 37 | export TGT_VALID=//all_amr-release-2-0-amrs-dev-all.txt.sent 38 | export SAVE=// 39 | 40 | python preprocess.py -train_src $SRC -train_tgt $TGT -valid_src $SRC_VALID -valid_tgt $TGT_VALID -save_data $SAVE -src_seq_length 1000 -tgt_seq_length 1000 -shuffle 1 41 | ``` 42 | 43 | ``` 44 | export F=//summ_ramp_10_passes_len_edges_exp_0 45 | export OUTPUT=/ 46 | export AMR=//amr-release-2.0-amrs-test-proxy.txt 47 | python var_free_amrs.py -is_dir -f $F -output_path $OUTPUT --custom_parentheses --no_semantics --delete_amr_var --with_side -side_file $AMR 48 | 49 | 50 | 51 | 52 | ``` 53 | 54 | 55 | 56 | python $WORK/train.py -data $PREPROCESS/van_noord/no_filter_amr_2/data -save_model $MODEL/$TYPE -rnn_size 500 -layers 2 -epochs 2000 -optim sgd -learning_rate 1 -learning_rate_decay 0.8 -encoder_type brnn -global_attention general -seed 1 -dropout 0.5 -batch_size 32 57 | # Generation with New Model 58 | python $WORK/translate.py -src $file -output $INPUT/gen/summ_rigotrio_fluent_side/$(basename $file).system -model $MODEL/rse/sprint_1/_acc_53.28_ppl_46.79_e126.pt -replace_unk -side_src $INPUT/processed/rigotrio/body_$(basename $file).s -side_tgt $INPUT/processed/rigotrio/body_$(basename $file).sent.s -beam_size 5 -max_length 100 -n_best 1 -batch_size 1 -verbose -psi 0.95 -theta 2.5 -k 15 59 | -------------------------------------------------------------------------------- /available_models/example.conf.json: -------------------------------------------------------------------------------- 1 | { 2 | "models_root": "./available_models", 3 | "models": [ 4 | { 5 | "id": 100, 6 | "model": "model_0.pt", 7 | "timeout": 600, 8 | "on_timeout": "to_cpu", 9 | "load": true, 10 | "opt": { 11 | "gpu": 0, 12 | "beam_size": 5 13 | }, 14 | "tokenizer": { 15 | "type": "sentencepiece", 16 | "model": "wmtenfr.model" 17 | } 18 | },{ 19 | "model": "model_0.light.pt", 20 | "timeout": -1, 21 | "on_timeout": "unload", 22 | "model_root": "../other_models", 23 | "opt": { 24 | "batch_size": 1, 25 | "beam_size": 10 26 | } 27 | } 28 | ] 29 | } 30 | -------------------------------------------------------------------------------- /data/README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | > python preprocess.py -train_src data/src-train.txt -train_tgt data/tgt-train.txt -valid_src data/src-val.txt -valid_tgt data/tgt-val.txt -save_data data/data -src_vocab_size 1000 -tgt_vocab_size 1000 6 | 7 | > python train.py -data data/data -save_model /n/rush_lab/data/tmp_ -gpuid 0 -rnn_size 100 -word_vec_size 50 -layers 1 -epochs 10 -optim adam -learning_rate 0.001 8 | -------------------------------------------------------------------------------- /data/morph/src.valid: -------------------------------------------------------------------------------- 1 | o p r u g a 2 | б е с т и ј а 3 | f a l s e t 4 | b e z i m e n o 5 | п р с и т и 6 | d e c e m b a r s k i 7 | м е ђ а 8 | š t a n d a r a c 9 | к р п о 10 | t a j n i k 11 | к е с и т и 12 | с р ч а н 13 | s c e n o g r a f 14 | б р а т и ћ 15 | з а у з е т и 16 | v e z a 17 | н е п а л а ц 18 | p r i l a g o d l j i v o s t 19 | g o l f e r i c a 20 | г р а ђ е в и н а ц 21 | с е к л у з и ј а 22 | р а с к р с н и ц а 23 | n e o p r a v d a n o 24 | k o m a d 25 | b e s t i j a l n o s t 26 | t u p o g l a v o 27 | с т р а н 28 | к р и в и ч а р 29 | п р о ј а х а т и 30 | о р г а н с к и 31 | r a z m i r i c a 32 | ц е с а р 33 | l j u t n j a 34 | н е в е ш т 35 | н о б е л о в а ц 36 | o s v a j a č 37 | х е д о н и с т 38 | р о ж н а т 39 | s r e b r e n 40 | p r i m e r a n 41 | и с к р и ч а в о 42 | s a g i n j a t i 43 | с и т а н 44 | v e š m a š i n a 45 | b l a m a ž a 46 | н е г и р а т и 47 | n a z d r a v i t i 48 | б о ж и 49 | r e š o 50 | к о ш у т е 51 | и м е н д а н 52 | e l e g a n t n o 53 | s k v r č i t i 54 | b e z v o l j a 55 | н а г и б 56 | k a p i t a l a n 57 | r e n o m e 58 | ф а с ц и н и р а т и 59 | с а к у п љ а т и 60 | п ш е н и ч н и 61 | u s m j e r a v a t i 62 | s k r i v a t i 63 | t i c a t i 64 | b i t n o 65 | j u r i š 66 | ч а с о п и с 67 | b e s k o n a č n o s t 68 | с а ф и р н и 69 | f a l s i f i k a t 70 | o n t o g e n e z a 71 | p r i m j e n a 72 | к р е к е т 73 | а е р о д р о м 74 | o s l o b a đ a t i 75 | с т у д и ј 76 | к р а т к о в и д 77 | л у п е ш т в о 78 | ž i v a c 79 | ј а ј а ш ц е 80 | r a z u v e r i t i 81 | z a v i s t 82 | k o n d u r a 83 | а м ф и т е а т а р 84 | а л г о н к и ј с к и 85 | у м и в а т и 86 | д а ж д е в њ а к 87 | д е ф е т и с т 88 | p r e s k a k a t i 89 | п е р у а н с к и 90 | s u p r o t s t a v l j a t i 91 | s p l j o š t e n 92 | с а ф и р 93 | п о ш т е ђ и в а т и 94 | к р а н и о л о г и ј с к и 95 | s v o j t a 96 | у п а д а т и 97 | r a ž a n j 98 | д о л и к о в а т и 99 | с а м о у в е р е н о с т 100 | х у м о р и с т и ч к и 101 | ч е ш к и 102 | s r a t i 103 | б л е б н у т и 104 | о д с е ц а т и 105 | n o v o r o đ e n 106 | b r e s k v a 107 | о б р е д 108 | k o n a č a n 109 | г р и с т и 110 | i k a v a c 111 | e p i l e p t i č a r k a 112 | d e z o r g a n i z a c i j a 113 | о т е ћ и 114 | z n a m e n j e 115 | м у љ а в 116 | i t a l i j a n s k i 117 | p r e t v o r b a 118 | g e r i j a t r i j a 119 | a l b a n i z a c i j a 120 | о ц ј е н а 121 | o d b i t i 122 | r e t o r i č n o 123 | м о љ а ц 124 | š k a f e t i n 125 | s p a n a ć 126 | у р а н 127 | n e p r i s t u p a č a n 128 | č e l n i k 129 | о п л о ђ и в а т и 130 | к и с т 131 | с а с е ћ и 132 | п о з д р а в 133 | ч а ђ а в о с т 134 | х а н 135 | п р и п о в е д а ч 136 | k i n o l o g i j a 137 | a s t r o n o m i j s k i 138 | n e i z l j e č i v o s t 139 | u s l o v a n 140 | s r p s k i 141 | e v o l u c i o n i z a m 142 | а н о т и р а т и 143 | d o s t a v i t i 144 | с а д а 145 | д о д а т а к 146 | p r o p i s i v a t i 147 | u s t v r đ i v a t i 148 | m i j e š a l i c a 149 | е г з и с т е н ц и ј а л а н 150 | и в и ц а 151 | a u t o k e f a l a n 152 | ж и в а х н о с т 153 | и з о р а в а т и 154 | х л а ч е 155 | к о н с о н а н т 156 | у з м а ћ и 157 | и м и г р и р а т и 158 | п л и т а к 159 | т е о з о ф и ј а 160 | к р а т к о в р а т 161 | s a t a n i z a m 162 | х а р а ч 163 | o t r c a n 164 | g i b a k 165 | k o s t r u š i t i 166 | o d g o v o r i t i 167 | b a l a v i t i 168 | f l a š i r a t i 169 | с л а ч и ц а 170 | t e n d e n c i j a 171 | g d a 172 | m n o ž i n a 173 | т е л е о л о г и ј а 174 | k r i z a n t e m a 175 | l j e t o 176 | к о н т р а д и к ц и ј а 177 | и н д и р е к т а н 178 | s l a m k a 179 | š t r a j h a t i 180 | п а п и р н и ч а р 181 | k u r t o a z n o 182 | o č e k i v a n j e 183 | n a m a ć i 184 | z a m a ć i 185 | b i f t e k 186 | с т о г а 187 | х о м о г е н 188 | з а м а к н у т и 189 | o k r i v i t i 190 | у ч и н и т и 191 | k i n u t i 192 | o b r t a t i 193 | t r a n s p l a n t a c i j a 194 | п р е в е л и к 195 | u k i d a t i 196 | к а м е н и 197 | -------------------------------------------------------------------------------- /data/morph/tgt.valid: -------------------------------------------------------------------------------- 1 | o p r u ɡ a 2 | b e s t i j a 3 | f a l s e t 4 | b e z i m e n o 5 | p r s i t i 6 | d e t s e m b a r s k i 7 | m e d z a 8 | ʃ t a n d a r a t s 9 | k r p o 10 | t a j n i k 11 | k e s i t i 12 | s r t ʃ a n 13 | s t s e n o ɡ r a f 14 | b r a t i t x 15 | z a u z e t i 16 | ʋ e z a 17 | n e p a l a t s 18 | p r i l a ɡ o d ʎ i ʋ o s t 19 | ɡ o l f e r i t s a 20 | ɡ r a d z e ʋ i n a t s 21 | s e k l u z i j a 22 | r a s k r s n i t s a 23 | n e o p r a ʋ d a n o 24 | k o m a d 25 | b e s t i j a l n o s t 26 | t u p o ɡ l a ʋ o 27 | s t r a n 28 | k r i ʋ i t ʃ a r 29 | p r o j a x a t i 30 | o r ɡ a n s k i 31 | r a z m i r i t s a 32 | t s e s a r 33 | ʎ u t ɲ a 34 | n e ʋ e ʃ t 35 | n o b e l o ʋ a t s 36 | o s ʋ a j a t ʃ 37 | x e d o n i s t 38 | r o ʒ n a t 39 | s r e b r e n 40 | p r i m e r a n 41 | i s k r i t ʃ a ʋ o 42 | s a ɡ i ɲ a t i 43 | s i t a n 44 | ʋ e ʃ m a ʃ i n a 45 | b l a m a ʒ a 46 | n e ɡ i r a t i 47 | n a z d r a ʋ i t i 48 | b o ʒ i 49 | r e ʃ o 50 | k o ʃ u t e 51 | i m e n d a n 52 | e l e ɡ a n t n o 53 | s k ʋ r t ʃ i t i 54 | b e z ʋ o ʎ a 55 | n a ɡ i b 56 | k a p i t a l a n 57 | r e n o m e 58 | f a s t s i n i r a t i 59 | s a k u p ʎ a t i 60 | p ʃ e n i t ʃ n i 61 | u s m j e r a ʋ a t i 62 | s k r i ʋ a t i 63 | t i t s a t i 64 | b i t n o 65 | j u r i ʃ 66 | t ʃ a s o p i s 67 | b e s k o n a t ʃ n o s t 68 | s a f i r n i 69 | f a l s i f i k a t 70 | o n t o ɡ e n e z a 71 | p r i m j e n a 72 | k r e k e t 73 | a e r o d r o m 74 | o s l o b a d z a t i 75 | s t u d i j 76 | k r a t k o ʋ i d 77 | l u p e ʃ t ʋ o 78 | ʒ i ʋ a t s 79 | j a j a ʃ t s e 80 | r a z u ʋ e r i t i 81 | z a ʋ i s t 82 | k o n d u r a 83 | a m f i t e a t a r 84 | a l ɡ o n k i j s k i 85 | u m i ʋ a t i 86 | d a ʒ d e ʋ ɲ a k 87 | d e f e t i s t 88 | p r e s k a k a t i 89 | p e r u a n s k i 90 | s u p r o t s t a ʋ ʎ a t i 91 | s p ʎ o ʃ t e n 92 | s a f i r 93 | p o ʃ t e d z i ʋ a t i 94 | k r a n i o l o ɡ i j s k i 95 | s ʋ o j t a 96 | u p a d a t i 97 | r a ʒ a ɲ 98 | d o l i k o ʋ a t i 99 | s a m o u ʋ e r e n o s t 100 | x u m o r i s t i t ʃ k i 101 | t ʃ e ʃ k i 102 | s r a t i 103 | b l e b n u t i 104 | o d s e t s a t i 105 | n o ʋ o r o d z e n 106 | b r e s k ʋ a 107 | o b r e d 108 | k o n a t ʃ a n 109 | ɡ r i s t i 110 | i k a ʋ a t s 111 | e p i l e p t i t ʃ a r k a 112 | d e z o r ɡ a n i z a t s i j a 113 | o t e t x i 114 | z n a m e ɲ e 115 | m u ʎ a ʋ 116 | i t a l i j a n s k i 117 | p r e t ʋ o r b a 118 | ɡ e r i j a t r i j a 119 | a l b a n i z a t s i j a 120 | o t s j e n a 121 | o d b i t i 122 | r e t o r i t ʃ n o 123 | m o ʎ a t s 124 | ʃ k a f e t i n 125 | s p a n a t x 126 | u r a n 127 | n e p r i s t u p a t ʃ a n 128 | t ʃ e l n i k 129 | o p l o d z i ʋ a t i 130 | k i s t 131 | s a s e t x i 132 | p o z d r a ʋ 133 | t ʃ a d z a ʋ o s t 134 | x a n 135 | p r i p o ʋ e d a t ʃ 136 | k i n o l o ɡ i j a 137 | a s t r o n o m i j s k i 138 | n e i z ʎ e t ʃ i ʋ o s t 139 | u s l o ʋ a n 140 | s r p s k i 141 | e ʋ o l u t s i o n i z a m 142 | a n o t i r a t i 143 | d o s t a ʋ i t i 144 | s a d a 145 | d o d a t a k 146 | p r o p i s i ʋ a t i 147 | u s t ʋ r d z i ʋ a t i 148 | m i j e ʃ a l i t s a 149 | e ɡ z i s t e n t s i j a l a n 150 | i ʋ i t s a 151 | a u t o k e f a l a n 152 | ʒ i ʋ a x n o s t 153 | i z o r a ʋ a t i 154 | x l a t ʃ e 155 | k o n s o n a n t 156 | u z m a t x i 157 | i m i ɡ r i r a t i 158 | p l i t a k 159 | t e o z o f i j a 160 | k r a t k o ʋ r a t 161 | s a t a n i z a m 162 | x a r a t ʃ 163 | o t r t s a n 164 | ɡ i b a k 165 | k o s t r u ʃ i t i 166 | o d ɡ o ʋ o r i t i 167 | b a l a ʋ i t i 168 | f l a ʃ i r a t i 169 | s l a t ʃ i t s a 170 | t e n d e n t s i j a 171 | ɡ d a 172 | m n o ʒ i n a 173 | t e l e o l o ɡ i j a 174 | k r i z a n t e m a 175 | ʎ e t o 176 | k o n t r a d i k t s i j a 177 | i n d i r e k t a n 178 | s l a m k a 179 | ʃ t r a j x a t i 180 | p a p i r n i t ʃ a r 181 | k u r t o a z n o 182 | o t ʃ e k i ʋ a ɲ e 183 | n a m a t x i 184 | z a m a t x i 185 | b i f t e k 186 | s t o ɡ a 187 | x o m o ɡ e n 188 | z a m a k n u t i 189 | o k r i ʋ i t i 190 | u t ʃ i n i t i 191 | k i n u t i 192 | o b r t a t i 193 | t r a n s p l a n t a t s i j a 194 | p r e ʋ e l i k 195 | u k i d a t i 196 | k a m e n i 197 | -------------------------------------------------------------------------------- /data/test_model2.src: -------------------------------------------------------------------------------- 1 | а з и ј а т с к и 2 | а к р о б а т с к и 3 | а л к о х о л и ч а р 4 | а р м а т у р а 5 | а у т о н о м а ш т в о 6 | б а р о к н и 7 | б е з б р о ј а н 8 | б о р о в и н а 9 | б о с а н а ц 10 | б р а у з е р 11 | в о ј н и ш т в о 12 | г д е г д е 13 | г р а б љ е 14 | г р д о с и ј а 15 | д а л е к о в и д н о 16 | д е з и н ф о р м а ц и ј а 17 | д е р и ш т е 18 | д р о б њ а к 19 | е м а н ц и п а ц и ј а 20 | ж а н д а р м е р и ј а 21 | з а в и д љ и в а ц 22 | з а к о ч и т и 23 | з а н е м а р и т и 24 | з в о н о 25 | з л о д ј е л о 26 | и г р о к а з 27 | ј е д и н и т и 28 | ј е д н о с т а в н о 29 | к о з л и н а ц 30 | к о н с т р у к т и в а н 31 | к р е к е т н у т и 32 | к у ш а ч и ц а 33 | л е г и т и м н о 34 | л и з а л и ц а 35 | л о м љ а в а 36 | м а м у р л у к 37 | м е д а љ а 38 | м о р а л н о 39 | н е г о с т о љ у б и в о с т 40 | н е д ј е љ н и 41 | н е к о ј и 42 | н е с т а н а к 43 | н е с т р у ч њ а к 44 | о д м о р и т и 45 | о п о р и ц а т и 46 | о п р и ч а т и 47 | о с а о 48 | п а њ 49 | п е р ф е к т 50 | п о н а в љ а т и 51 | п о п р и м и т и 52 | п р а с л о в е н с к и 53 | п р и г о д а н 54 | п р и п р е м а т и 55 | п с и х о п а т о л о г и ј а 56 | п с о в а ч к и 57 | п у н ч 58 | р а з а п и њ а т и 59 | с а б и т и 60 | с а г и б љ и в о с т 61 | с а к р и т и 62 | с а к р о с а н к т а н 63 | с а л а т н и 64 | с и р н и 65 | с к у п о ц ј е н 66 | с л а т к о р ј е ч и в о 67 | с н о ш љ и в о 68 | с о ч н о 69 | с т и д љ и в 70 | т а ј 71 | т а н а ц 72 | т е с т е н и н а 73 | т р а н з и т 74 | т р ч а т и 75 | ћ у м у р џ и ј а 76 | у ж и в а л а ц 77 | у к о р е н и т и 78 | у п о м о ћ 79 | у р о т н и к 80 | у с м ј е р а в а т и 81 | у с п у т 82 | у с т а ј а т и 83 | у ц е н и т и 84 | ф а н а т и ч н о с т 85 | ф о т к а 86 | х и љ а д у 87 | х и п и 88 | х у м а н и з а м 89 | ц р н е т и 90 | ш а м п и о н с к и 91 | ш и ф к а р т а 92 | ш л а ј е р 93 | ш л а ј ф а т и 94 | ш л у к 95 | ш п а ј з 96 | ш п а ј с к а р т а 97 | ш п а н с к и 98 | ш т о к а в а ц 99 | ш т р а ј х е р 100 | ш у п ч и ћ 101 | a g r e s o r s k i 102 | a k t e r 103 | a m b r o z i j a 104 | a p s t i n e n c i j a 105 | a s i m e t r i j a 106 | a v i o k o m p a n i j a 107 | d a ž d e v n j a k 108 | d e l o m 109 | d i j a l o g 110 | d o h v a t i t i 111 | d o k t o r a n d 112 | d o k t o r s k i 113 | d o v i t l j i v 114 | d o z v o l a 115 | d v o s m i s l e n 116 | e r i t r e j a 117 | e s t e t i k a 118 | e v r o p s k i 119 | f i z i o t e r a p i j s k i 120 | g a j 121 | g m a z 122 | h a j d e m o 123 | i n j e 124 | i n t o n a c i j a 125 | k e s t e n j a s t 126 | k o l e v k a 127 | k o z j i 128 | k r a l j e š a k 129 | k r a t k o 130 | k r č e v i n a 131 | k r e a t i v a n 132 | k r e š e n d o 133 | k u ć a n i c a 134 | k u ć n i 135 | l i č a n 136 | l j u l j a t i 137 | m e s n i 138 | m r l j a 139 | m u š k o s t 140 | n a b r u s i v a t i 141 | n a d o b u d a n 142 | n a k a l e m i t i 143 | n a r e č j e 144 | n a s l e đ i v a t i 145 | n e ć a k 146 | n e d e l j i v 147 | n e o s e t l j i v o 148 | n e s a v e s t a n 149 | n e s u v i s a o 150 | n e u r a s t e n i č a n 151 | n e u s t a v a n 152 | n i š a n d ž i j a 153 | o b r a ć a t i 154 | o k r e t a t i 155 | o n e s p o s o b l j i v a t i 156 | o s a k a ć i v a t i 157 | o s v e t l j i v 158 | p a l e o z o i k 159 | p e s n i k 160 | p l a t n e n 161 | p l e m e n i t 162 | p r a v o v a l j a n o s t 163 | p r a ž a n i n 164 | p r i p r a v l j a t i 165 | p r o l e t o s 166 | r a z g o v a r a t i 167 | r a z n o l i č a n 168 | r a z r e d 169 | r a z v r a t n o 170 | r i g i d i t e t 171 | r u b e š k i 172 | s e r i o z a n 173 | s i n o ć 174 | s i r u t k a 175 | s l e d i t i 176 | s m j e š t a j 177 | š n i r a t i 178 | s o k a k 179 | š p e k 180 | s r a m i t i 181 | š t i t o n o š a 182 | s t o t i n a 183 | t i n j a t i 184 | t o k s i k o l o g i j a 185 | t o l i k 186 | t r a n s a t l a n t s k i 187 | u n u t a r 188 | u z g r e d i c e 189 | v a k c i n a 190 | v a š m a š i n a 191 | v e ć e 192 | v l a d a v i n a 193 | v o k a c i j a 194 | z a b u š a n t s k i 195 | z a k l i n j a t i 196 | z a k o č i t i 197 | z n a t a n 198 | z o r a n 199 | -------------------------------------------------------------------------------- /data/test_model2.tgt: -------------------------------------------------------------------------------- 1 | a z i j a t s k i 2 | a k r o b a t s k i 3 | a l k o x o l i t ʃ a r 4 | a r m a t u r a 5 | a u t o n o m a ʃ t ʋ o 6 | b a r o k n i 7 | b e z b r o j a n 8 | b o r o ʋ i n a 9 | b o s a n a t s 10 | b r a u z e r 11 | ʋ o j n i ʃ t ʋ o 12 | ɡ d e ɡ d e 13 | ɡ r a b ʎ e 14 | ɡ r d o s i j a 15 | d a l e k o ʋ i d n o 16 | d e z i n f o r m a t s i j a 17 | d e r i ʃ t e 18 | d r o b ɲ a k 19 | e m a n t s i p a t s i j a 20 | ʒ a n d a r m e r i j a 21 | z a ʋ i d ʎ i ʋ a t s 22 | z a k o t ʃ i t i 23 | z a n e m a r i t i 24 | z ʋ o n o 25 | z l o d j e l o 26 | i ɡ r o k a z 27 | j e d i n i t i 28 | j e d n o s t a ʋ n o 29 | k o z l i n a t s 30 | k o n s t r u k t i ʋ a n 31 | k r e k e t n u t i 32 | k u ʃ a t ʃ i t s a 33 | l e ɡ i t i m n o 34 | l i z a l i t s a 35 | l o m ʎ a ʋ a 36 | m a m u r l u k 37 | m e d a ʎ a 38 | m o r a l n o 39 | n e ɡ o s t o ʎ u b i ʋ o s t 40 | n e d j e ʎ n i 41 | n e k o j i 42 | n e s t a n a k 43 | n e s t r u t ʃ ɲ a k 44 | o d m o r i t i 45 | o p o r i t s a t i 46 | o p r i t ʃ a t i 47 | o s a o 48 | p a ɲ 49 | p e r f e k t 50 | p o n a ʋ ʎ a t i 51 | p o p r i m i t i 52 | p r a s l o ʋ e n s k i 53 | p r i ɡ o d a n 54 | p r i p r e m a t i 55 | p s i x o p a t o l o ɡ i j a 56 | p s o ʋ a t ʃ k i 57 | p u n t ʃ 58 | r a z a p i ɲ a t i 59 | s a b i t i 60 | s a ɡ i b ʎ i ʋ o s t 61 | s a k r i t i 62 | s a k r o s a n k t a n 63 | s a l a t n i 64 | s i r n i 65 | s k u p o t s j e n 66 | s l a t k o r j e t ʃ i ʋ o 67 | s n o ʃ ʎ i ʋ o 68 | s o t ʃ n o 69 | s t i d ʎ i ʋ 70 | t a j 71 | t a n a t s 72 | t e s t e n i n a 73 | t r a n z i t 74 | t r t ʃ a t i 75 | t x u m u r d ʒ i j a 76 | u ʒ i ʋ a l a t s 77 | u k o r e n i t i 78 | u p o m o t x 79 | u r o t n i k 80 | u s m j e r a ʋ a t i 81 | u s p u t 82 | u s t a j a t i 83 | u t s e n i t i 84 | f a n a t i t ʃ n o s t 85 | f o t k a 86 | x i ʎ a d u 87 | x i p i 88 | x u m a n i z a m 89 | t s r n e t i 90 | ʃ a m p i o n s k i 91 | ʃ i f k a r t a 92 | ʃ l a j e r 93 | ʃ l a j f a t i 94 | ʃ l u k 95 | ʃ p a j z 96 | ʃ p a j s k a r t a 97 | ʃ p a n s k i 98 | ʃ t o k a ʋ a t s 99 | ʃ t r a j x e r 100 | ʃ u p t ʃ i t x 101 | a ɡ r e s o r s k i 102 | a k t e r 103 | a m b r o z i j a 104 | a p s t i n e n t s i j a 105 | a s i m e t r i j a 106 | a ʋ i o k o m p a n i j a 107 | d a ʒ d e ʋ ɲ a k 108 | d e l o m 109 | d i j a l o ɡ 110 | d o x ʋ a t i t i 111 | d o k t o r a n d 112 | d o k t o r s k i 113 | d o ʋ i t ʎ i ʋ 114 | d o z ʋ o l a 115 | d ʋ o s m i s l e n 116 | e r i t r e j a 117 | e s t e t i k a 118 | e ʋ r o p s k i 119 | f i z i o t e r a p i j s k i 120 | ɡ a j 121 | ɡ m a z 122 | x a j d e m o 123 | i ɲ e 124 | i n t o n a t s i j a 125 | k e s t e ɲ a s t 126 | k o l e ʋ k a 127 | k o z j i 128 | k r a ʎ e ʃ a k 129 | k r a t k o 130 | k r t ʃ e ʋ i n a 131 | k r e a t i ʋ a n 132 | k r e ʃ e n d o 133 | k u t x a n i t s a 134 | k u t x n i 135 | l i t ʃ a n 136 | ʎ u ʎ a t i 137 | m e s n i 138 | m r ʎ a 139 | m u ʃ k o s t 140 | n a b r u s i ʋ a t i 141 | n a d o b u d a n 142 | n a k a l e m i t i 143 | n a r e t ʃ j e 144 | n a s l e d z i ʋ a t i 145 | n e t x a k 146 | n e d e ʎ i ʋ 147 | n e o s e t ʎ i ʋ o 148 | n e s a ʋ e s t a n 149 | n e s u ʋ i s a o 150 | n e u r a s t e n i t ʃ a n 151 | n e u s t a ʋ a n 152 | n i ʃ a n d ʒ i j a 153 | o b r a t x a t i 154 | o k r e t a t i 155 | o n e s p o s o b ʎ i ʋ a t i 156 | o s a k a t x i ʋ a t i 157 | o s ʋ e t ʎ i ʋ 158 | p a l e o z o i k 159 | p e s n i k 160 | p l a t n e n 161 | p l e m e n i t 162 | p r a ʋ o ʋ a ʎ a n o s t 163 | p r a ʒ a n i n 164 | p r i p r a ʋ ʎ a t i 165 | p r o l e t o s 166 | r a z ɡ o ʋ a r a t i 167 | r a z n o l i t ʃ a n 168 | r a z r e d 169 | r a z ʋ r a t n o 170 | r i ɡ i d i t e t 171 | r u b e ʃ k i 172 | s e r i o z a n 173 | s i n o t x 174 | s i r u t k a 175 | s l e d i t i 176 | s m j e ʃ t a j 177 | ʃ n i r a t i 178 | s o k a k 179 | ʃ p e k 180 | s r a m i t i 181 | ʃ t i t o n o ʃ a 182 | s t o t i n a 183 | t i ɲ a t i 184 | t o k s i k o l o ɡ i j a 185 | t o l i k 186 | t r a n s a t l a n t s k i 187 | u n u t a r 188 | u z ɡ r e d i t s e 189 | ʋ a k t s i n a 190 | ʋ a ʃ m a ʃ i n a 191 | ʋ e t x e 192 | ʋ l a d a ʋ i n a 193 | ʋ o k a t s i j a 194 | z a b u ʃ a n t s k i 195 | z a k l i ɲ a t i 196 | z a k o t ʃ i t i 197 | z n a t a n 198 | z o r a n 199 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = python3 -msphinx 7 | SPHINXPROJ = OpenNMT-py 8 | SOURCEDIR = source 9 | BUILDDIR = build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | -------------------------------------------------------------------------------- /docs/generate.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh 2 | 3 | gen_script_options () 4 | { 5 | echo "" > $2 6 | echo "" >> $2 7 | python3 $1 -md >> $2 8 | } 9 | 10 | gen_script_options preprocess.py docs/source/options/preprocess.md 11 | gen_script_options train.py docs/source/options/train.md 12 | gen_script_options translate.py docs/source/options/translate.md 13 | -------------------------------------------------------------------------------- /docs/requirements.txt: -------------------------------------------------------------------------------- 1 | sphinx 2 | sphinxcontrib.bibtex 3 | sphinxcontrib.mermaid 4 | sphinx-rtd-theme 5 | recommonmark 6 | -------------------------------------------------------------------------------- /docs/source/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | OpenNMT-py is a community developed project and we love developer contributions. 4 | 5 | Before sending a PR, please do this checklist first: 6 | 7 | - Please run `tools/pull_request_chk.sh` and fix any errors. When adding new functionality, also add tests to this script. Included checks: 8 | 1. flake8 check for coding style; 9 | 2. unittest; 10 | 3. continuous integration tests listed in `.travis.yml`. 11 | - When adding/modifying class constructor, please make the arguments as same naming style as its superclass in pytorch. 12 | - If your change is based on a paper, please include a clear comment and reference in the code. 13 | - If your function takes/returns tensor arguments, please include assertions to document the sizes. See `GlobalAttention.py` for examples. 14 | -------------------------------------------------------------------------------- /docs/source/FAQ.md: -------------------------------------------------------------------------------- 1 | # FAQ 2 | 3 | ## How do I use Pretrained embeddings (e.g. GloVe)? 4 | 5 | Using vocabularies from OpenNMT-py preprocessing outputs, `embeddings_to_torch.py` to generate encoder and decoder embeddings initialized with GloVe’s values. 6 | 7 | the script is a slightly modified version of ylhsieh’s one2. 8 | 9 | Usage: 10 | 11 | ``` 12 | embeddings_to_torch.py [-h] -emb_file EMB_FILE -output_file OUTPUT_FILE -dict_file DICT_FILE [-verbose] 13 | 14 | emb_file: GloVe like embedding file i.e. CSV [word] [dim1] ... [dim_d] 15 | 16 | output_file: a filename to save the output as PyTorch serialized tensors2 17 | 18 | dict_file: dict output from OpenNMT-py preprocessing 19 | ``` 20 | 21 | Example 22 | 23 | 24 | 1) get GloVe files: 25 | 26 | ``` 27 | mkdir "glove_dir" 28 | wget http://nlp.stanford.edu/data/glove.6B.zip 29 | unzip glove.6B.zip -d "glove_dir" 30 | ``` 31 | 32 | 2) prepare data: 33 | 34 | ``` 35 | python preprocess.py \ 36 | -train_src data/train.src.txt \ 37 | -train_tgt data/train.tgt.txt \ 38 | -valid_src data/valid.src.txt \ 39 | -valid_tgt data/valid.tgt.txt \ 40 | -save_data data/data 41 | ``` 42 | 43 | 3) prepare embeddings: 44 | 45 | ``` 46 | ./tools/embeddings_to_torch.py -emb_file "glove_dir/glove.6B.100d.txt" \ 47 | -dict_file "data/data.vocab.pt" \ 48 | -output_file "data/embeddings" 49 | ``` 50 | 51 | 4) train using pre-trained embeddings: 52 | 53 | ``` 54 | python train.py -save_model data/model \ 55 | -batch_size 64 \ 56 | -layers 2 \ 57 | -rnn_size 200 \ 58 | -word_vec_size 100 \ 59 | -pre_word_vecs_enc "data/embeddings.enc.pt" \ 60 | -pre_word_vecs_dec "data/embeddings.dec.pt" \ 61 | -data data/data 62 | ``` 63 | 64 | 65 | ## How do I use the Transformer model? 66 | 67 | The transformer model is very sensitive to hyperparameters. To run it 68 | effectively you need to set a bunch of different options that mimic the Google 69 | setup. We have confirmed the following command can replicate their WMT results. 70 | 71 | ``` 72 | python train.py -data /tmp/de2/data -save_model /tmp/extra -gpuid 1 \ 73 | -layers 6 -rnn_size 512 -word_vec_size 512 \ 74 | -encoder_type transformer -decoder_type transformer -position_encoding \ 75 | -epochs 50 -max_generator_batches 32 -dropout 0.1 \ 76 | -batch_size 4096 -batch_type tokens -normalization tokens -accum_count 4 \ 77 | -optim adam -adam_beta2 0.998 -decay_method noam -warmup_steps 8000 -learning_rate 2 \ 78 | -max_grad_norm 0 -param_init 0 -param_init_glorot \ 79 | -label_smoothing 0.1 80 | ``` 81 | 82 | Here are what each of the parameters mean: 83 | 84 | * `param_init_glorot` `-param_init 0`: correct initialization of parameters 85 | * `position_encoding`: add sinusoidal position encoding to each embedding 86 | * `optim adam`, `decay_method noam`, `warmup_steps 8000`: use special learning rate. 87 | * `batch_type tokens`, `normalization tokens`, `accum_count 4`: batch and normalize based on number of tokens and not sentences. Compute gradients based on four batches. 88 | - `label_smoothing 0.1`: use label smoothing loss. 89 | 90 | 91 | ## Do you support multi-gpu? 92 | 93 | Currently our system does not support multi-gpu. It will be coming soon. 94 | 95 | 96 | -------------------------------------------------------------------------------- /docs/source/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # OpenNMT-py documentation build configuration file, created by 5 | # sphinx-quickstart on Sun Dec 17 12:07:14 2017. 6 | # 7 | # This file is execfile()d with the current directory set to its 8 | # containing dir. 9 | # 10 | # Note that not all possible configuration values are present in this 11 | # autogenerated file. 12 | # 13 | # All configuration values have a default; values that are commented out 14 | # serve to show the default. 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | # 20 | # import os 21 | # import sys 22 | # sys.path.insert(0, os.path.abspath('.')) 23 | 24 | 25 | # -- General configuration ------------------------------------------------ 26 | 27 | # If your documentation needs a minimal Sphinx version, state it here. 28 | # 29 | # needs_sphinx = '1.0' 30 | 31 | # Add any Sphinx extension module names here, as strings. They can be 32 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 33 | # ones. 34 | 35 | from recommonmark.parser import CommonMarkParser 36 | import sphinx_rtd_theme 37 | from recommonmark.transform import AutoStructify 38 | 39 | source_parsers = { 40 | '.md': CommonMarkParser, 41 | } 42 | 43 | source_suffix = ['.rst', '.md'] 44 | extensions = ['sphinx.ext.autodoc', 45 | 'sphinx.ext.mathjax', 46 | 'sphinx.ext.viewcode', 47 | 'sphinx.ext.coverage', 48 | 'sphinx.ext.githubpages', 49 | 'sphinx.ext.napoleon', 50 | 'sphinxcontrib.mermaid', 51 | 'sphinxcontrib.bibtex'] 52 | 53 | # Add any paths that contain templates here, relative to this directory. 54 | templates_path = ['.templates'] 55 | 56 | # The suffix(es) of source filenames. 57 | # You can specify multiple suffix as a list of string: 58 | # 59 | # source_suffix = ['.rst', '.md'] 60 | source_suffix = '.rst' 61 | 62 | # The master toctree document. 63 | master_doc = 'index' 64 | 65 | # General information about the project. 66 | project = 'OpenNMT-py' 67 | copyright = '2017, srush' 68 | author = 'srush' 69 | 70 | # The version info for the project you're documenting, acts as replacement for 71 | # |version| and |release|, also used in various other places throughout the 72 | # built documents. 73 | # 74 | # The short X.Y version. 75 | version = '' 76 | # The full version, including alpha/beta/rc tags. 77 | release = '' 78 | 79 | # The language for content autogenerated by Sphinx. Refer to documentation 80 | # for a list of supported languages. 81 | # 82 | # This is also used if you do content translation via gettext catalogs. 83 | # Usually you set "language" from the command line for these cases. 84 | language = None 85 | 86 | # List of patterns, relative to source directory, that match files and 87 | # directories to ignore when looking for source files. 88 | # This patterns also effect to html_static_path and html_extra_path 89 | exclude_patterns = [] 90 | 91 | # The name of the Pygments (syntax highlighting) style to use. 92 | pygments_style = 'sphinx' 93 | 94 | # If true, `todo` and `todoList` produce output, else they produce nothing. 95 | todo_include_todos = False 96 | 97 | 98 | # -- Options for HTML output ---------------------------------------------- 99 | 100 | # The theme to use for HTML and HTML Help pages. See the documentation for 101 | # a list of builtin themes. 102 | # 103 | 104 | 105 | # html_theme = 'sphinx_materialdesign_theme' 106 | # html_theme_path = [sphinx_materialdesign_theme.get_path()] 107 | html_theme = "sphinx_rtd_theme" 108 | html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] 109 | 110 | 111 | # Theme options are theme-specific and customize the look and feel of a theme 112 | # further. For a list of options available for each theme, see the 113 | # documentation. 114 | # 115 | # html_theme_options = {} 116 | 117 | # Add any paths that contain custom static files (such as style sheets) here, 118 | # relative to this directory. They are copied after the builtin static files, 119 | # so a file named "default.css" will overwrite the builtin "default.css". 120 | html_static_path = ['.static'] 121 | 122 | # Custom sidebar templates, must be a dictionary that maps document names 123 | # to template names. 124 | # 125 | # This is required for the alabaster theme 126 | # refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars 127 | html_sidebars = { 128 | '**': [ 129 | 'relations.html', # needs 'show_related': True theme option to display 130 | 'searchbox.html', 131 | ] 132 | } 133 | 134 | 135 | # -- Options for HTMLHelp output ------------------------------------------ 136 | 137 | # Output file base name for HTML help builder. 138 | htmlhelp_basename = 'OpenNMT-pydoc' 139 | 140 | 141 | # -- Options for LaTeX output --------------------------------------------- 142 | 143 | latex_elements = { 144 | # The paper size ('letterpaper' or 'a4paper'). 145 | # 146 | # 'papersize': 'letterpaper', 147 | 148 | # The font size ('10pt', '11pt' or '12pt'). 149 | # 150 | # 'pointsize': '10pt', 151 | 152 | # Additional stuff for the LaTeX preamble. 153 | # 154 | # 'preamble': '', 155 | 156 | # Latex figure (float) alignment 157 | # 158 | # 'figure_align': 'htbp', 159 | } 160 | 161 | # Grouping the document tree into LaTeX files. List of tuples 162 | # (source start file, target name, title, 163 | # author, documentclass [howto, manual, or own class]). 164 | latex_documents = [ 165 | (master_doc, 'OpenNMT-py.tex', 'OpenNMT-py Documentation', 166 | 'srush', 'manual'), 167 | ] 168 | 169 | 170 | # -- Options for manual page output --------------------------------------- 171 | 172 | # One entry per manual page. List of tuples 173 | # (source start file, name, description, authors, manual section). 174 | man_pages = [ 175 | (master_doc, 'opennmt-py', 'OpenNMT-py Documentation', 176 | [author], 1) 177 | ] 178 | 179 | 180 | # -- Options for Texinfo output ------------------------------------------- 181 | 182 | # Grouping the document tree into Texinfo files. List of tuples 183 | # (source start file, target name, title, author, 184 | # dir menu entry, description, category) 185 | texinfo_documents = [ 186 | (master_doc, 'OpenNMT-py', 'OpenNMT-py Documentation', 187 | author, 'OpenNMT-py', 'One line description of project.', 188 | 'Miscellaneous'), 189 | ] 190 | 191 | github_doc_root = 'https://github.com/opennmt/opennmt-py/tree/master/doc/' 192 | 193 | 194 | def setup(app): 195 | print("hello") 196 | app.add_config_value('recommonmark_config', { 197 | 'enable_eval_rst': True 198 | }, True) 199 | app.add_transform(AutoStructify) 200 | -------------------------------------------------------------------------------- /docs/source/examples.rst: -------------------------------------------------------------------------------- 1 | == Examples == 2 | 3 | 4 | .. include:: quickstart.md 5 | .. include:: extended.md 6 | -------------------------------------------------------------------------------- /docs/source/extended.md: -------------------------------------------------------------------------------- 1 | 2 | # Example: Translation 3 | 4 | The example below uses the Moses tokenizer (http://www.statmt.org/moses/) to prepare the data and the moses BLEU script for evaluation. This example if for training for the WMT'16 Multimodal Translation task (http://www.statmt.org/wmt16/multimodal-task.html). 5 | 6 | Step 0. Download the data. 7 | 8 | ```bash 9 | mkdir -p data/multi30k 10 | wget http://www.quest.dcs.shef.ac.uk/wmt16_files_mmt/training.tar.gz && tar -xf training.tar.gz -C data/multi30k && rm training.tar.gz 11 | wget http://www.quest.dcs.shef.ac.uk/wmt16_files_mmt/validation.tar.gz && tar -xf validation.tar.gz -C data/multi30k && rm validation.tar.gz 12 | wget http://www.quest.dcs.shef.ac.uk/wmt17_files_mmt/mmt_task1_test2016.tar.gz && tar -xf mmt_task1_test2016.tar.gz -C data/multi30k && rm mmt_task1_test2016.tar.gz 13 | ``` 14 | 15 | Step 1. Preprocess the data. 16 | 17 | ```bash 18 | for l in en de; do for f in data/multi30k/*.$l; do if [[ "$f" != *"test"* ]]; then sed -i "$ d" $f; fi; done; done 19 | for l in en de; do for f in data/multi30k/*.$l; do perl tools/tokenizer.perl -a -no-escape -l $l -q < $f > $f.atok; done; done 20 | python preprocess.py -train_src data/multi30k/train.en.atok -train_tgt data/multi30k/train.de.atok -valid_src data/multi30k/val.en.atok -valid_tgt data/multi30k/val.de.atok -save_data data/multi30k.atok.low -lower 21 | ``` 22 | 23 | Step 2. Train the model. 24 | 25 | ```bash 26 | python train.py -data data/multi30k.atok.low -save_model multi30k_model -gpuid 0 27 | ``` 28 | 29 | Step 3. Translate sentences. 30 | 31 | ```bash 32 | python translate.py -gpu 0 -model multi30k_model_*_e13.pt -src data/multi30k/test.en.atok -tgt data/multi30k/test.de.atok -replace_unk -verbose -output multi30k.test.pred.atok 33 | ``` 34 | 35 | And evaluate 36 | 37 | ```bash 38 | perl tools/multi-bleu.perl data/multi30k/test.de.atok < multi30k.test.pred.atok 39 | ``` 40 | -------------------------------------------------------------------------------- /docs/source/im2text.md: -------------------------------------------------------------------------------- 1 | # Example: Image to Text 2 | 3 | A deep learning-based approach to learning the image-to-text conversion, built on top of the OpenNMT system. It is completely data-driven, hence can be used for a variety of image-to-text problems, such as image captioning, optical character recognition and LaTeX decompilation. 4 | 5 | Take LaTeX decompilation as an example, given a formula image: 6 | 7 |

8 | 9 | The goal is to infer the LaTeX source that can be compiled to such an image: 10 | 11 | ``` 12 | d s _ { 1 1 } ^ { 2 } = d x ^ { + } d x ^ { - } + l _ { p } ^ { 9 } \frac { p _ { - } } { r ^ { 7 } } \delta ( x ^ { - } ) d x ^ { - } d x ^ { - } + d x _ { 1 } ^ { 2 } + \; \cdots \; + d x _ { 9 } ^ { 2 } 13 | ``` 14 | 15 | The paper [[What You Get Is What You See: A Visual Markup Decompiler]](https://arxiv.org/pdf/1609.04938.pdf) provides more technical details of this model. 16 | 17 | ### Dependencies 18 | 19 | * `torchvision`: `conda install torchvision` 20 | * `Pillow`: `pip install Pillow` 21 | 22 | ### Quick Start 23 | 24 | To get started, we provide a toy Math-to-LaTex example. We assume that the working directory is `OpenNMT-py` throughout this document. 25 | 26 | Im2Text consists of four commands: 27 | 28 | 0) Download the data. 29 | 30 | ``` 31 | wget -O data/im2text.tgz http://lstm.seas.harvard.edu/latex/im2text_small.tgz; tar zxf data/im2text.tgz -C data/ 32 | ``` 33 | 34 | 1) Preprocess the data. 35 | 36 | ``` 37 | python preprocess.py -data_type img -src_dir data/im2text/images/ -train_src data/im2text/src-train.txt -train_tgt data/im2text/tgt-train.txt -valid_src data/im2text/src-val.txt -valid_tgt data/im2text/tgt-val.txt -save_data data/im2text/demo 38 | ``` 39 | 40 | 2) Train the model. 41 | 42 | ``` 43 | python train.py -model_type img -data data/im2text/demo -save_model demo-model -gpuid 0 -batch_size 20 -max_grad_norm 20 -learning_rate 0.1 44 | ``` 45 | 46 | 3) Translate the images. 47 | 48 | ``` 49 | python translate.py -data_type img -model demo-model_acc_x_ppl_x_e13.pt -src_dir data/im2text/images -src data/im2text/src-test.txt -output pred.txt -gpu 0 -verbose 50 | ``` 51 | 52 | The above dataset is sampled from the [im2latex-100k-dataset](http://lstm.seas.harvard.edu/latex/im2text.tgz). We provide a trained model [[link]](http://lstm.seas.harvard.edu/latex/py-model.pt) on this dataset. 53 | 54 | ### Options 55 | 56 | * `-src_dir`: The directory containing the images. 57 | 58 | * `-train_tgt`: The file storing the tokenized labels, one label per line. It shall look like: 59 | ``` 60 | ... 61 | ... 62 | ... 63 | ... 64 | ``` 65 | 66 | * `-train_src`: The file storing the paths of the images (relative to `src_dir`). 67 | ``` 68 | 69 | 70 | 71 | ... 72 | ``` 73 | -------------------------------------------------------------------------------- /docs/source/index.md: -------------------------------------------------------------------------------- 1 | 2 | .. toctree:: 3 | :maxdepth: 2 4 | 5 | index.md 6 | quickstart.md 7 | extended.md 8 | 9 | 10 | This portal provides a detailled documentation of the OpenNMT toolkit. It describes how to use the PyTorch project and how it works. 11 | 12 | 13 | 14 | ## Installation 15 | 16 | 1\. [Install PyTorch](http://pytorch.org/) 17 | 18 | 2\. Clone the OpenNMT-py repository: 19 | 20 | ```bash 21 | git clone https://github.com/OpenNMT/OpenNMT-py 22 | cd OpenNMT-py 23 | ``` 24 | 25 | 3\. Install required libraries 26 | 27 | ```bash 28 | pip install -r requirements.txt 29 | ``` 30 | 31 | And you are ready to go! Take a look at the [quickstart](quickstart.md) to familiarize yourself with the main training workflow. 32 | 33 | Alternatively you can use Docker to install with `nvidia-docker`. The main Dockerfile is included 34 | in the root directory. 35 | 36 | ## Citation 37 | 38 | When using OpenNMT for research please cite our 39 | [OpenNMT technical report](https://doi.org/10.18653/v1/P17-4012) 40 | 41 | ``` 42 | @inproceedings{opennmt, 43 | author = {Guillaume Klein and 44 | Yoon Kim and 45 | Yuntian Deng and 46 | Jean Senellart and 47 | Alexander M. Rush}, 48 | title = {OpenNMT: Open-Source Toolkit for Neural Machine Translation}, 49 | booktitle = {Proc. ACL}, 50 | year = {2017}, 51 | url = {https://doi.org/10.18653/v1/P17-4012}, 52 | doi = {10.18653/v1/P17-4012} 53 | } 54 | ``` 55 | 56 | ## Additional resources 57 | 58 | You can find additional help or tutorials in the following resources: 59 | 60 | * [Gitter channel](https://gitter.im/OpenNMT/openmt-py) 61 | -------------------------------------------------------------------------------- /docs/source/index.rst: -------------------------------------------------------------------------------- 1 | Contents 2 | -------- 3 | 4 | .. toctree:: 5 | :maxdepth: 2 6 | 7 | main.md 8 | quickstart.md 9 | onmt.rst 10 | onmt.modules.rst 11 | onmt.translation.rst 12 | onmt.io.rst 13 | Library.md 14 | 15 | options/preprocess.md 16 | options/train.md 17 | options/translate.md 18 | extended.md 19 | Summarization.md 20 | im2text.md 21 | speech2text.md 22 | FAQ.md 23 | CONTRIBUTING.md 24 | ref.rst 25 | -------------------------------------------------------------------------------- /docs/source/main.md: -------------------------------------------------------------------------------- 1 | # Overview 2 | 3 | 4 | This portal provides a detailled documentation of the OpenNMT toolkit. It describes how to use the PyTorch project and how it works. 5 | 6 | 7 | 8 | ## Installation 9 | 10 | 1\. [Install PyTorch](http://pytorch.org/) 11 | 12 | 2\. Clone the OpenNMT-py repository: 13 | 14 | ```bash 15 | git clone https://github.com/OpenNMT/OpenNMT-py 16 | cd OpenNMT-py 17 | ``` 18 | 19 | 3\. Install required libraries 20 | 21 | ```bash 22 | pip install -r requirements.txt 23 | ``` 24 | 25 | And you are ready to go! Take a look at the [quickstart](quickstart) to familiarize yourself with the main training workflow. 26 | 27 | Alternatively you can use Docker to install with `nvidia-docker`. The main Dockerfile is included 28 | in the root directory. 29 | 30 | ## Citation 31 | 32 | When using OpenNMT for research please cite our 33 | [OpenNMT technical report](https://doi.org/10.18653/v1/P17-4012) 34 | 35 | ``` 36 | @inproceedings{opennmt, 37 | author = {Guillaume Klein and 38 | Yoon Kim and 39 | Yuntian Deng and 40 | Jean Senellart and 41 | Alexander M. Rush}, 42 | title = {OpenNMT: Open-Source Toolkit for Neural Machine Translation}, 43 | booktitle = {Proc. ACL}, 44 | year = {2017}, 45 | url = {https://doi.org/10.18653/v1/P17-4012}, 46 | doi = {10.18653/v1/P17-4012} 47 | } 48 | ``` 49 | 50 | ## Additional resources 51 | 52 | You can find additional help or tutorials in the following resources: 53 | 54 | * [Gitter channel](https://gitter.im/OpenNMT/openmt-py) 55 | -------------------------------------------------------------------------------- /docs/source/modules.rst: -------------------------------------------------------------------------------- 1 | onmt 2 | ==== 3 | 4 | .. toctree:: 5 | :maxdepth: 4 6 | 7 | onmt 8 | -------------------------------------------------------------------------------- /docs/source/onmt.io.rst: -------------------------------------------------------------------------------- 1 | Doc: Data Loaders 2 | ================= 3 | 4 | Datasets 5 | --------- 6 | 7 | .. autoclass:: onmt.io.TextDataset 8 | :members: 9 | 10 | .. autoclass:: onmt.io.ImageDataset 11 | :members: 12 | 13 | .. autoclass:: onmt.io.AudioDataset 14 | :members: 15 | -------------------------------------------------------------------------------- /docs/source/onmt.modules.rst: -------------------------------------------------------------------------------- 1 | Doc: Modules 2 | ============= 3 | 4 | Core Modules 5 | ------------ 6 | 7 | .. autoclass:: onmt.modules.Embeddings 8 | :members: 9 | 10 | 11 | Encoders 12 | --------- 13 | 14 | .. autoclass:: onmt.modules.EncoderBase 15 | :members: 16 | 17 | .. autoclass:: onmt.modules.MeanEncoder 18 | :members: 19 | 20 | .. autoclass:: onmt.modules.RNNEncoder 21 | :members: 22 | 23 | 24 | Decoders 25 | --------- 26 | 27 | 28 | .. autoclass:: onmt.modules.RNNDecoderBase 29 | :members: 30 | 31 | 32 | .. autoclass:: onmt.modules.StdRNNDecoder 33 | :members: 34 | 35 | 36 | .. autoclass:: onmt.modules.InputFeedRNNDecoder 37 | :members: 38 | 39 | Attention 40 | ---------- 41 | 42 | .. autoclass:: onmt.modules.GlobalAttention 43 | :members: 44 | 45 | 46 | 47 | Architecture: Transfomer 48 | ---------------------------- 49 | 50 | .. autoclass:: onmt.modules.PositionalEncoding 51 | :members: 52 | 53 | .. autoclass:: onmt.modules.PositionwiseFeedForward 54 | :members: 55 | 56 | .. autoclass:: onmt.modules.TransformerEncoder 57 | :members: 58 | 59 | .. autoclass:: onmt.modules.TransformerDecoder 60 | :members: 61 | 62 | .. autoclass:: onmt.modules.MultiHeadedAttention 63 | :members: 64 | :undoc-members: 65 | 66 | 67 | Architecture: Conv2Conv 68 | ---------------------------- 69 | 70 | (These methods are from a user contribution 71 | and have not been thoroughly tested.) 72 | 73 | 74 | .. autoclass:: onmt.modules.CNNEncoder 75 | :members: 76 | 77 | 78 | .. autoclass:: onmt.modules.CNNDecoder 79 | :members: 80 | 81 | .. autoclass:: onmt.modules.ConvMultiStepAttention 82 | :members: 83 | 84 | .. autoclass:: onmt.modules.WeightNorm 85 | :members: 86 | 87 | Architecture: SRU 88 | ---------------------------- 89 | 90 | .. autoclass:: onmt.modules.SRU 91 | :members: 92 | 93 | 94 | Alternative Encoders 95 | -------------------- 96 | 97 | onmt\.modules\.AudioEncoder 98 | 99 | .. autoclass:: onmt.modules.AudioEncoder 100 | :members: 101 | 102 | 103 | onmt\.modules\.ImageEncoder 104 | 105 | .. autoclass:: onmt.modules.ImageEncoder 106 | :members: 107 | 108 | 109 | Copy Attention 110 | -------------- 111 | 112 | .. autoclass:: onmt.modules.CopyGenerator 113 | :members: 114 | 115 | 116 | Structured Attention 117 | ------------------------------------------- 118 | 119 | .. autoclass:: onmt.modules.MatrixTree 120 | :members: 121 | -------------------------------------------------------------------------------- /docs/source/onmt.rst: -------------------------------------------------------------------------------- 1 | Doc: Framework 2 | ================= 3 | 4 | Model 5 | ----- 6 | 7 | .. autoclass:: onmt.Models.NMTModel 8 | :members: 9 | 10 | .. autoclass:: onmt.Models.DecoderState 11 | :members: 12 | 13 | Trainer 14 | ------- 15 | 16 | .. autoclass:: onmt.Trainer 17 | :members: 18 | 19 | 20 | .. autoclass:: onmt.Statistics 21 | :members: 22 | 23 | Loss 24 | ---- 25 | 26 | 27 | .. autoclass:: onmt.Loss.LossComputeBase 28 | :members: 29 | 30 | 31 | Optim 32 | ----- 33 | 34 | .. autoclass:: onmt.Optim.Optim 35 | :members: 36 | -------------------------------------------------------------------------------- /docs/source/onmt.translation.rst: -------------------------------------------------------------------------------- 1 | Doc: Translation 2 | ================== 3 | 4 | Translations 5 | ------------- 6 | 7 | .. autoclass:: onmt.translate.Translation 8 | :members: 9 | 10 | Translator Class 11 | ----------------- 12 | 13 | .. autoclass:: onmt.translate.Translator 14 | :members: 15 | 16 | .. autoclass:: onmt.translate.TranslationBuilder 17 | :members: 18 | 19 | 20 | Beam Search 21 | ------------- 22 | 23 | .. autoclass:: onmt.translate.Beam 24 | :members: 25 | 26 | .. autoclass:: onmt.translate.GNMTGlobalScorer 27 | :members: 28 | -------------------------------------------------------------------------------- /docs/source/options/preprocess.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | preprocess.py 4 | # Options: preprocess.py: 5 | preprocess.py 6 | 7 | ### **Data**: 8 | * **-data_type [text]** 9 | Type of the source input. Options are [text|img]. 10 | 11 | * **-train_src []** 12 | Path to the training source data 13 | 14 | * **-train_tgt []** 15 | Path to the training target data 16 | 17 | * **-valid_src []** 18 | Path to the validation source data 19 | 20 | * **-valid_tgt []** 21 | Path to the validation target data 22 | 23 | * **-src_dir []** 24 | Source directory for image or audio files. 25 | 26 | * **-save_data []** 27 | Output file for the prepared data 28 | 29 | * **-max_shard_size []** 30 | For text corpus of large volume, it will be divided into shards of this size to 31 | preprocess. If 0, the data will be handled as a whole. The unit is in bytes. 32 | Optimal value should be multiples of 64 bytes. 33 | 34 | ### **Vocab**: 35 | * **-src_vocab []** 36 | Path to an existing source vocabulary. Format: one word per line. 37 | 38 | * **-tgt_vocab []** 39 | Path to an existing target vocabulary. Format: one word per line. 40 | 41 | * **-features_vocabs_prefix []** 42 | Path prefix to existing features vocabularies 43 | 44 | * **-src_vocab_size [50000]** 45 | Size of the source vocabulary 46 | 47 | * **-tgt_vocab_size [50000]** 48 | Size of the target vocabulary 49 | 50 | * **-src_words_min_frequency []** 51 | 52 | * **-tgt_words_min_frequency []** 53 | 54 | * **-dynamic_dict []** 55 | Create dynamic dictionaries 56 | 57 | * **-share_vocab []** 58 | Share source and target vocabulary 59 | 60 | ### **Pruning**: 61 | * **-src_seq_length [50]** 62 | Maximum source sequence length 63 | 64 | * **-src_seq_length_trunc []** 65 | Truncate source sequence length. 66 | 67 | * **-tgt_seq_length [50]** 68 | Maximum target sequence length to keep. 69 | 70 | * **-tgt_seq_length_trunc []** 71 | Truncate target sequence length. 72 | 73 | * **-lower []** 74 | lowercase data 75 | 76 | ### **Random**: 77 | * **-shuffle [1]** 78 | Shuffle data 79 | 80 | * **-seed [3435]** 81 | Random seed 82 | 83 | ### **Logging**: 84 | * **-report_every [100000]** 85 | Report status every this many sentences 86 | 87 | ### **Speech**: 88 | * **-sample_rate [16000]** 89 | Sample rate. 90 | 91 | * **-window_size [0.02]** 92 | Window size for spectrogram in seconds. 93 | 94 | * **-window_stride [0.01]** 95 | Window stride for spectrogram in seconds. 96 | 97 | * **-window [hamming]** 98 | Window type for spectrogram generation. 99 | -------------------------------------------------------------------------------- /docs/source/options/translate.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | translate.py 4 | # Options: translate.py: 5 | translate.py 6 | 7 | ### **Model**: 8 | * **-model []** 9 | Path to model .pt file 10 | 11 | ### **Data**: 12 | * **-data_type [text]** 13 | Type of the source input. Options: [text|img]. 14 | 15 | * **-src []** 16 | Source sequence to decode (one line per sequence) 17 | 18 | * **-src_dir []** 19 | Source directory for image or audio files 20 | 21 | * **-tgt []** 22 | True target sequence (optional) 23 | 24 | * **-output [pred.txt]** 25 | Path to output the predictions (each line will be the decoded sequence 26 | 27 | * **-report_bleu []** 28 | Report bleu score after translation, call tools/multi-bleu.perl on command line 29 | 30 | * **-report_rouge []** 31 | Report rouge 1/2/3/L/SU4 score after translation call tools/test_rouge.py on 32 | command line 33 | 34 | * **-dynamic_dict []** 35 | Create dynamic dictionaries 36 | 37 | * **-share_vocab []** 38 | Share source and target vocabulary 39 | 40 | ### **Beam**: 41 | * **-beam_size [5]** 42 | Beam size 43 | 44 | * **-min_length []** 45 | Minimum prediction length 46 | 47 | * **-max_length [100]** 48 | Maximum prediction length. 49 | 50 | * **-max_sent_length []** 51 | Deprecated, use `-max_length` instead 52 | 53 | * **-stepwise_penalty []** 54 | Apply penalty at every decoding step. Helpful for summary penalty. 55 | 56 | * **-length_penalty [none]** 57 | Length Penalty to use. 58 | 59 | * **-coverage_penalty [none]** 60 | Coverage Penalty to use. 61 | 62 | * **-alpha []** 63 | Google NMT length penalty parameter (higher = longer generation) 64 | 65 | * **-beta []** 66 | Coverage penalty parameter 67 | 68 | * **-block_ngram_repeat []** 69 | Block repetition of ngrams during decoding. 70 | 71 | * **-ignore_when_blocking []** 72 | Ignore these strings when blocking repeats. You want to block sentence 73 | delimiters. 74 | 75 | * **-replace_unk []** 76 | Replace the generated UNK tokens with the source token that had highest 77 | attention weight. If phrase_table is provided, it will lookup the identified 78 | source token and give the corresponding target token. If it is not provided(or 79 | the identified source token does not exist in the table) then it will copy the 80 | source token 81 | 82 | ### **Logging**: 83 | * **-verbose []** 84 | Print scores and predictions for each sentence 85 | 86 | * **-attn_debug []** 87 | Print best attn for each word 88 | 89 | * **-dump_beam []** 90 | File to dump beam information to. 91 | 92 | * **-n_best [1]** 93 | If verbose is set, will output the n_best decoded sentences 94 | 95 | ### **Efficiency**: 96 | * **-batch_size [30]** 97 | Batch size 98 | 99 | * **-gpu [-1]** 100 | Device to run on 101 | 102 | ### **Speech**: 103 | * **-sample_rate [16000]** 104 | Sample rate. 105 | 106 | * **-window_size [0.02]** 107 | Window size for spectrogram in seconds 108 | 109 | * **-window_stride [0.01]** 110 | Window stride for spectrogram in seconds 111 | 112 | * **-window [hamming]** 113 | Window type for spectrogram generation 114 | -------------------------------------------------------------------------------- /docs/source/quickstart.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Quickstart 4 | 5 | 6 | ### Step 1: Preprocess the data 7 | 8 | ```bash 9 | python preprocess.py -train_src data/src-train.txt -train_tgt data/tgt-train.txt -valid_src data/src-val.txt -valid_tgt data/tgt-val.txt -save_data data/demo 10 | ``` 11 | 12 | We will be working with some example data in `data/` folder. 13 | 14 | The data consists of parallel source (`src`) and target (`tgt`) data containing one sentence per line with tokens separated by a space: 15 | 16 | * `src-train.txt` 17 | * `tgt-train.txt` 18 | * `src-val.txt` 19 | * `tgt-val.txt` 20 | 21 | Validation files are required and used to evaluate the convergence of the training. It usually contains no more than 5000 sentences. 22 | 23 | ```text 24 | $ head -n 3 data/src-train.txt 25 | It is not acceptable that , with the help of the national bureaucracies , Parliament 's legislative prerogative should be made null and void by means of implementing provisions whose content , purpose and extent are not laid down in advance . 26 | Federal Master Trainer and Senior Instructor of the Italian Federation of Aerobic Fitness , Group Fitness , Postural Gym , Stretching and Pilates; from 2004 , he has been collaborating with Antiche Terme as personal Trainer and Instructor of Stretching , Pilates and Postural Gym . 27 | " Two soldiers came up to me and told me that if I refuse to sleep with them , they will kill me . They beat me and ripped my clothes . 28 | ``` 29 | 30 | ### Step 2: Train the model 31 | 32 | ```bash 33 | python train.py -data data/demo -save_model demo-model 34 | ``` 35 | 36 | The main train command is quite simple. Minimally it takes a data file 37 | and a save file. This will run the default model, which consists of a 38 | 2-layer LSTM with 500 hidden units on both the encoder/decoder. You 39 | can also add `-gpuid 1` to use (say) GPU 1. 40 | 41 | ### Step 3: Translate 42 | 43 | ```bash 44 | python translate.py -model demo-model_XYZ.pt -src data/src-test.txt -output pred.txt -replace_unk -verbose 45 | ``` 46 | 47 | Now you have a model which you can use to predict on new data. We do this by running beam search. This will output predictions into `pred.txt`. 48 | 49 | Note: 50 | 51 | The predictions are going to be quite terrible, as the demo dataset is small. Try running on some larger datasets! For example you can download millions of parallel sentences for [translation](http://www.statmt.org/wmt16/translation-task.html) or [summarization](https://github.com/harvardnlp/sent-summary). 52 | -------------------------------------------------------------------------------- /docs/source/ref.rst: -------------------------------------------------------------------------------- 1 | ========== 2 | References 3 | ========== 4 | 5 | 6 | 7 | References 8 | 9 | .. bibliography:: refs.bib 10 | 11 | -------------------------------------------------------------------------------- /docs/source/speech2text.md: -------------------------------------------------------------------------------- 1 | # Example: Speech to Text 2 | 3 | A deep learning-based approach to learning the speech-to-text conversion, built on top of the OpenNMT system. 4 | 5 | Given raw audio, we first apply short-time Fourier transform (STFT), then apply Convolutional Neural Networks to get the source features. Based on this source representation, we use an LSTM decoder with attention to produce the text character by character. 6 | 7 | ### Dependencies 8 | 9 | * `torchaudio`: `sudo apt-get install -y sox libsox-dev libsox-fmt-all; pip install git+https://github.com/pytorch/audio` 10 | * `librosa`: `pip install librosa` 11 | 12 | ### Quick Start 13 | 14 | To get started, we provide a toy speech-to-text example. We assume that the working directory is `OpenNMT-py` throughout this document. 15 | 16 | 0) Download the data. 17 | 18 | ``` 19 | wget -O data/speech.tgz http://lstm.seas.harvard.edu/latex/speech.tgz; tar zxf data/speech.tgz -C data/ 20 | ``` 21 | 22 | 23 | 1) Preprocess the data. 24 | 25 | ``` 26 | python preprocess.py -data_type audio -src_dir data/speech/an4_dataset -train_src data/speech/src-train.txt -train_tgt data/speech/tgt-train.txt -valid_src data/speech/src-val.txt -valid_tgt data/speech/tgt-val.txt -save_data data/speech/demo 27 | ``` 28 | 29 | 2) Train the model. 30 | 31 | ``` 32 | python train.py -model_type audio -data data/speech/demo -save_model demo-model -gpuid 0 -batch_size 16 -max_grad_norm 20 -learning_rate 0.1 -learning_rate_decay 0.98 -epochs 60 33 | ``` 34 | 35 | 3) Translate the speechs. 36 | 37 | ``` 38 | python translate.py -data_type audio -model demo-model_acc_x_ppl_x_e13.pt -src_dir data/speech/an4_dataset -src data/speech/src-val.txt -output pred.txt -gpu 0 -verbose 39 | ``` 40 | 41 | 42 | ### Options 43 | 44 | * `-src_dir`: The directory containing the audio files. 45 | 46 | * `-train_tgt`: The file storing the tokenized labels, one label per line. It shall look like: 47 | ``` 48 | ... 49 | ... 50 | ... 51 | ... 52 | ``` 53 | 54 | * `-train_src`: The file storing the paths of the audio files (relative to `src_dir`). 55 | ``` 56 | 57 | 58 | 59 | ... 60 | ``` 61 | 62 | * `sample_rate`: Sample rate. Default: 16000. 63 | * `window_size`: Window size for spectrogram in seconds. Default: 0.02. 64 | * `window_stride`: Window stride for spectrogram in seconds. Default: 0.01. 65 | * `window`: Window type for spectrogram generation. Default: hamming. 66 | 67 | ### Acknowledgement 68 | 69 | Our preprocessing and CNN encoder is adapted from [deepspeech.pytorch](https://github.com/SeanNaren/deepspeech.pytorch). 70 | -------------------------------------------------------------------------------- /github_deploy_key_opennmt_opennmt_py.enc: -------------------------------------------------------------------------------- 1 | gAAAAABaPWC5LTHR5xMoviRbhWsMCxo0FPMTXwcm4DBbG2jYaTxuqdjT78PXu1XxcEfbRuZ-xX8723WjgJMaOVFRuB6k1Oow7Qw8YlO6CV5fyjU8jJFy0D4fSEE40P6A0GbvtMwj2uVKyhrCK341_8roVVegN96S40muebu0oi3cY0sDwLybAOBQYdf_J6gQgWIxf289hPMzmV4iy332V9gRN-cNbmpUYaVxINrxv0Ce6pw3NV99mNNK5izq-g4hlpErnF7LG60Jar7Vh7bw52C0PpEVJmUXWIJOtDGy6d_SuvR4SIj64J4IEDO78s7PyI8jAyP5Nu5emcH_eOV8z7C2nszkNbx6RwtDPh5qK0HILCgGmF4nzOTVK8mE9_8gD-tlWpS7jj7y_IJwNPJB3Gnqt383sg5NIQpgQqJMzmKtacXPF-sDvczsyf4t6GEURhPYobNociBQa3ZZBtJU0O_moUtwdSRsjkk1RdUbIgG3tcX73T_SYJqMLGtMKywmyDzv1CVqFCdCAhlVAcSnLLvP2xlJ1uJSKa46dtSDoUXleWCGMR9SoLz2UpPvtnJ1zZ8YKW7UD9iQfAsznBMSG4wKGEdZdFymvCuLnZQYWmJK9UFSyoYnrW1Jy1pmOJ8a25kfyI6_LiK52iC1zr9DZcn5MP2FGgrJnz0RfuvPtcgKFtvs731LzVycUT-u1I4WftPh_6b6fPxYuSnRPdJ39m7OnaGb5VOobleElaZMkh8niXM4K654i1dQA_ItuYeWjU3HPhwN86aOif6GeZSlq_Xjp3Z2DACSmYqyxKccVBWYBdZO8WSdSt07TEeWUboDDQTu_xCPEh-E8Z-Bb-xjTjVM99jkvZSrbqJn6TeY__nH2thfl9cVMj73o7wIp0EJgSpUuKEnJqPwenPwm-VEj_ODB8qbNYC3y4QkfHBL6nbdUt8Qx6P59i8C54st2v5OdZ31bF6bqbJxE5UElJRyuASmE92vu8QqQqPGjZqLhIE9Tl6EC4JFdwJMZI53gztzfKTYMAQLkbV0zYtSoBYavbBCTwQTlG49qDeZk6r5K4DPwZh9xM-M9j32Yr3NYE6QvS4sPaikPkAGoLqTAWVrfdLDc7IdIgAmZNt1D5E3Wm2n7wlQflrdLu6VgiGT1rZgsax_C1bTvsi7InkjuQuNphzXEn3_9FlWmnatDK0Nb0MFqGtEAd0S5SDGI2cf7drLVOtJzvNw9GUgdMoqn-hutvJNS1vpIZK2KektVoFMB-gBJj4oPp4gx8WDbvmkd88Jbitk3xuQp8JmoxPcVkZhPJYYMouMHnO982N9HiJ7AsvFmML_AEe72_qQCh5jcGpsbMq_U5Cu8S2L6MpaMmcn1Piup9ClCricSNEtJD-QS9EEyn-mCHnXnQ1_z6AQ-An5wwm2eNrsEN1F1DjqLcyO3ziE5pHKNXh5W1H3Ec1_ETpInJRBoZ7DEvPpI1KFyxSnwCCrONAIZwrZzMDHPsXgJbXZZfX8_bah36380_eecZOmeCVE1UsimA2MLE3K-ziv0YhXiyHkdzROSmXruXSmzr1NW1bn26Fwy3M3L3GDmHI4Wd62eiYlPAdiOOGO2rA1H37q47X-65BBdh9XXz0k_5YRPLtQeDUavLKzd9MIHc8Ef4g2PkHJTRp9jdkertDy1NkKg3rV-QZ12fCCce97ftcMJ4BSXLgEx_jvxISTo4mB8R0fAAWYJAYCd0vFc7Q4PRFHhyJsm_5BtrwEC5JFQF6sNQllkIRbixJ-kGaieAwRZ-JKzR7gzQ3MJVjArZKcZJV6N8YYRQvKcR8sEcgLv_lr_1hQNLjmGyFeZ1RYxagaddVLAxwp8W5_vofhnKCc5JpnVcAm4W-h_l7uZd42raso-7HeRYIacW9tuFhmUi7iZBHzsNz9G0XFdsdeD2FKJb2yt30Ze4VA1crIOWwVkHsfXid2tjV4wEkR1GGQXYJ2HSHeiH5W4_9vxyYlpum8swrEWY_vLywnv92Bqerk2pfBi6kJqE1ZyZR-8NQuZMxQO_l8pTurirI-nCeHY5Im-jhs4MmA4-zwthY6RKQqbijYCbEd3HeHHMS0k8c84NlMiVAlEd7cAQZYSvlrAxNsaUWmBazE6HAGhXlB0X5pYDYV0LDalIU4guqpVLx-B4iwvnQ7nA3EzsXSBSJDsYbtVQaOHabG_jTL-SDKpkMEdb1Fh0UAeflB02fSenwj1DmsZysiJDD16IxKq22XjGslQZKNvZqk2XivzbL7JfVkCDU6N8XgyOpImZmh28Cq5iyN0GfgzYBvUscrspXQd7QJmiatoGLA-nkCZae4XRfeEh9l0qj_jiLnDzDXxF8pz9A-2GMTUUiUFwehSw2haTZJ4Ndqj3ekItvVJZxwVPYs_Voim3orgFUKmT1SUWXy5lKWPuqpWpbhBs0W5EJ2gt5EzV_ejsnnMqyDoxS-R03-ZATHRaFtvf96Zz0qo7xP__UONT1c5l8FX4Tf_kBF5JlTFe3FbSk9fa38QJGqH3RiF1mx91VXOwXR4fw-vGy5CuZoCND3QVzrdwmYE3jqxClBo7AnAjLTXD-lUCf7gqFqHFU-on1zypAZaXhwMVmfuKeolQhPsuybzUWTlRQW5OT2rxnwI-xO_6s78sRIyBwtbQba6lcOUnNH5PF9TbGj4Z2ErzA7eBS6ZBlnEE_fx8QrHoF32x2KLbyX6ELgEG4pt6aWfroWTWWC2T1CjUrswmMEfF5F0aA0uvr-vikxFl62Ob2yIuyF39ytmr8mb_o4JBpd3Etj4m_T-5HwmrsNnAf8bUqf0hTHuQlS9ek5jJK-_pNWWL1Q3yQ7x-4eiJkppero7UYyOKXGLRqgWchry26edqEETCybJMvgjmN2kHqcrg3XBM4ItjOPw0s4XklG7YZzEVmq8O3hgp-fVozpX_RAaaFSGmDzuZcQl2R_-Yo13KzjLj8wu3KjBCfVhJoAjc4T2VZMGVL3T4AOZOEN_GXEKjT5rbrEo1E7eQUoKE_PKKxmyDeNZN3W3hULAS_FMKAURyCLT_nfQ-cKU7pg113AyV6juAS_DFnBPZkcwM-PJBKz69QsrN_D3s3M53rART78zbUAab-La7Q803g-eaSgxpGJgCZKqHHafE4OpMnhKJl1eXaO_YekbtNR-JNXxdMS5wMEA_BOpqu_ixwuw_vJx-tZxKJ1p_o75OVFK9YH9ZFT5_--ngM8G-kHZrV6u5XKc5Jymrq9m6nZaH__HdAMvQmRfMWbOsSXl3HrlyEoPK5nyBcKtlHLwANc_1WeMJp3HjpHi5HelTnqNDxi5I5Z0RWP1mU0f8mUMkTvGb5U1wW0pL0Aq_5vSfn5LQhH0QAt2JcHrFasMe_7dABIzMLb8_ph0yQQ57IAIfXUYleOwyD1ZpAFgysnh9V9duxPmg3yswRlJ9MZK9tYkwWcj_nOjq2407qR42aThqWYL4702HVycoQgErx6K4XSkF5mmJdfsZ515IIpqHJt-7Q5n_gzIPQa4Wq5ANgS5-2y97uN61NkoE9eIiLHZMY6OvuORvSdMeL6_84MuLBsKS_3OgXrOQFOgdK5mCn9Iv53UZiMkR0rLGHOLnb2hnTZGq4ao3yiNsauBqf0O4r6ecarYxGty4yWZBxB8aHLFcK-FAlFuoEL8PlRLChOEUqvUoaFs3jzyQY_iRZRyCMszPi0xPrvdiILk4VDaa0NR0XtCC-kA3tdcb_Xbdfv_Djw-wVLf7Dx6iBlPNwtjE4OzweqBaAkNkk5Ij35vk-6QQryHhAgiAHdXDGZoegdHZdKUeC_GSCMud0wpXloEPxDREskWu1VN310OXaa6VvpG0VB1B2CrUlFNvwzmal3PYCrb7XPAT1Lu5C4oSH3bTr6Hk9wtIEv0sAgt4B9RPhZ0Kq-lP85raW748Pkc0PDK1C4g4SzAxl_x7JTSTYUk_fjMnc7yEN0iBRJCMfmUq-ILtj2zOI7f3dazGCp9dXBOTVTYMVNRpcka7vWjlGHMMuVvid3Oz6GgBZl_I3csNzGXTZEvJurp3qXSaXL_THxHmDBDn7T_uY58uPaTC-qjdvkKNDUzg2kRtzejmO7TPEGIRAQghEkVK-ruZU5llxjMg1NOTeXfhXZlRK2Ri8F9QPs6FSFuiqLgOzgbl_rlecf3E6iJ9fgTsdE8OGgekAwmF5hi7Tp5DsGNlKXpWvc4TftLO7len-b9Tqa7XYPU5NKv1hVIIobSRjYuFuW1yDSWtXY0zzzqPsdhtrv97JoM71QL8fZ3tUDBDWhvlBmpXSSfjf4qYQ0PmP7pQWLjb_DuVBDO5EDV0xblgz_stLcNvxRIYChm0ytxN8B2jCaH1n_CLEWTvFloWBP72ovnRWcd1gqbZ4bD4KrI_Tb7VcepWqUg1CO-yTRHR4zQUSBBfM= -------------------------------------------------------------------------------- /onmt/Optim.py: -------------------------------------------------------------------------------- 1 | import torch.optim as optim 2 | from torch.nn.utils import clip_grad_norm 3 | 4 | 5 | class MultipleOptimizer(object): 6 | def __init__(self, op): 7 | self.optimizers = op 8 | 9 | def zero_grad(self): 10 | for op in self.optimizers: 11 | op.zero_grad() 12 | 13 | def step(self): 14 | for op in self.optimizers: 15 | op.step() 16 | 17 | 18 | class Optim(object): 19 | """ 20 | Controller class for optimization. Mostly a thin 21 | wrapper for `optim`, but also useful for implementing 22 | rate scheduling beyond what is currently available. 23 | Also implements necessary methods for training RNNs such 24 | as grad manipulations. 25 | 26 | Args: 27 | method (:obj:`str`): one of [sgd, adagrad, adadelta, adam] 28 | lr (float): learning rate 29 | lr_decay (float, optional): learning rate decay multiplier 30 | start_decay_at (int, optional): epoch to start learning rate decay 31 | beta1, beta2 (float, optional): parameters for adam 32 | adagrad_accum (float, optional): initialization parameter for adagrad 33 | decay_method (str, option): custom decay options 34 | warmup_steps (int, option): parameter for `noam` decay 35 | model_size (int, option): parameter for `noam` decay 36 | """ 37 | # We use the default parameters for Adam that are suggested by 38 | # the original paper https://arxiv.org/pdf/1412.6980.pdf 39 | # These values are also used by other established implementations, 40 | # e.g. https://www.tensorflow.org/api_docs/python/tf/train/AdamOptimizer 41 | # https://keras.io/optimizers/ 42 | # Recently there are slightly different values used in the paper 43 | # "Attention is all you need" 44 | # https://arxiv.org/pdf/1706.03762.pdf, particularly the value beta2=0.98 45 | # was used there however, beta2=0.999 is still arguably the more 46 | # established value, so we use that here as well 47 | def __init__(self, method, lr, max_grad_norm, 48 | lr_decay=1, start_decay_at=None, 49 | beta1=0.9, beta2=0.999, 50 | adagrad_accum=0.0, 51 | decay_method=None, 52 | warmup_steps=4000, 53 | model_size=None): 54 | self.last_ppl = None 55 | self.lr = lr 56 | self.original_lr = lr 57 | self.max_grad_norm = max_grad_norm 58 | self.method = method 59 | self.lr_decay = lr_decay 60 | self.start_decay_at = start_decay_at 61 | self.start_decay = False 62 | self._step = 0 63 | self.betas = [beta1, beta2] 64 | self.adagrad_accum = adagrad_accum 65 | self.decay_method = decay_method 66 | self.warmup_steps = warmup_steps 67 | self.model_size = model_size 68 | 69 | def set_parameters(self, params): 70 | self.params = [] 71 | self.sparse_params = [] 72 | for k, p in params: 73 | if p.requires_grad: 74 | if self.method != 'sparseadam' or "embed" not in k: 75 | self.params.append(p) 76 | else: 77 | self.sparse_params.append(p) 78 | if self.method == 'sgd': 79 | self.optimizer = optim.SGD(self.params, lr=self.lr) 80 | elif self.method == 'adagrad': 81 | self.optimizer = optim.Adagrad(self.params, lr=self.lr) 82 | for group in self.optimizer.param_groups: 83 | for p in group['params']: 84 | self.optimizer.state[p]['sum'] = self.optimizer\ 85 | .state[p]['sum'].fill_(self.adagrad_accum) 86 | elif self.method == 'adadelta': 87 | self.optimizer = optim.Adadelta(self.params, lr=self.lr) 88 | elif self.method == 'adam': 89 | self.optimizer = optim.Adam(self.params, lr=self.lr, 90 | betas=self.betas, eps=1e-9) 91 | elif self.method == 'sparseadam': 92 | self.optimizer = MultipleOptimizer( 93 | [optim.Adam(self.params, lr=self.lr, 94 | betas=self.betas, eps=1e-8), 95 | optim.SparseAdam(self.sparse_params, lr=self.lr, 96 | betas=self.betas, eps=1e-8)]) 97 | else: 98 | raise RuntimeError("Invalid optim method: " + self.method) 99 | 100 | def _set_rate(self, lr): 101 | self.lr = lr 102 | if self.method != 'sparseadam': 103 | self.optimizer.param_groups[0]['lr'] = self.lr 104 | else: 105 | for op in self.optimizer.optimizers: 106 | op.param_groups[0]['lr'] = self.lr 107 | 108 | def step(self): 109 | """Update the model parameters based on current gradients. 110 | 111 | Optionally, will employ gradient modification or update learning 112 | rate. 113 | """ 114 | self._step += 1 115 | 116 | # Decay method used in tensor2tensor. 117 | if self.decay_method == "noam": 118 | self._set_rate( 119 | self.original_lr * 120 | (self.model_size ** (-0.5) * 121 | min(self._step ** (-0.5), 122 | self._step * self.warmup_steps**(-1.5)))) 123 | 124 | if self.max_grad_norm: 125 | clip_grad_norm(self.params, self.max_grad_norm) 126 | self.optimizer.step() 127 | 128 | def update_learning_rate(self, ppl, epoch): 129 | """ 130 | Decay learning rate if val perf does not improve 131 | or we hit the start_decay_at limit. 132 | """ 133 | 134 | if self.start_decay_at is not None and epoch >= self.start_decay_at: 135 | self.start_decay = True 136 | # if self.last_ppl is not None and ppl > self.last_ppl: 137 | # self.start_decay = True 138 | 139 | if self.start_decay: 140 | self.lr = self.lr * self.lr_decay 141 | print("Decaying learning rate to %g" % self.lr) 142 | 143 | self.last_ppl = ppl 144 | if self.method != 'sparseadam': 145 | self.optimizer.param_groups[0]['lr'] = self.lr 146 | -------------------------------------------------------------------------------- /onmt/Utils.py: -------------------------------------------------------------------------------- 1 | import torch 2 | 3 | 4 | def aeq(*args): 5 | """ 6 | Assert all arguments have the same value 7 | """ 8 | arguments = (arg for arg in args) 9 | first = next(arguments) 10 | assert all(arg == first for arg in arguments), \ 11 | "Not all arguments have the same value: " + str(args) 12 | 13 | 14 | def sequence_mask(lengths, max_len=None): 15 | """ 16 | Creates a boolean mask from sequence lengths. 17 | """ 18 | batch_size = lengths.numel() 19 | max_len = max_len or lengths.max() 20 | return (torch.arange(0, max_len) 21 | .type_as(lengths) 22 | .repeat(batch_size, 1) 23 | .lt(lengths.unsqueeze(1))) 24 | 25 | 26 | def use_gpu(opt): 27 | return (hasattr(opt, 'gpuid') and len(opt.gpuid) > 0) or \ 28 | (hasattr(opt, 'gpu') and opt.gpu > -1) 29 | -------------------------------------------------------------------------------- /onmt/__init__.py: -------------------------------------------------------------------------------- 1 | import onmt.io 2 | import onmt.Models 3 | import onmt.Loss 4 | import onmt.translate 5 | import onmt.opts 6 | from onmt.Trainer import Trainer, Statistics 7 | from onmt.Optim import Optim 8 | 9 | # For flake8 compatibility 10 | __all__ = [onmt.Loss, onmt.Models, onmt.opts, 11 | Trainer, Optim, Statistics, onmt.io, onmt.translate] 12 | -------------------------------------------------------------------------------- /onmt/io/DatasetBase.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from itertools import chain 4 | import torchtext 5 | 6 | 7 | PAD_WORD = '' 8 | UNK_WORD = '' 9 | UNK = 0 10 | BOS_WORD = '' 11 | EOS_WORD = '' 12 | 13 | 14 | class ONMTDatasetBase(torchtext.data.Dataset): 15 | """ 16 | A dataset basically supports iteration over all the examples 17 | it contains. We currently have 3 datasets inheriting this base 18 | for 3 types of corpus respectively: "text", "img", "audio". 19 | 20 | Internally it initializes an `torchtext.data.Dataset` object with 21 | the following attributes: 22 | 23 | `examples`: a sequence of `torchtext.data.Example` objects. 24 | `fields`: a dictionary associating str keys with `torchtext.data.Field` 25 | objects, and not necessarily having the same keys as the input fields. 26 | """ 27 | def __getstate__(self): 28 | return self.__dict__ 29 | 30 | def __setstate__(self, d): 31 | self.__dict__.update(d) 32 | 33 | def __reduce_ex__(self, proto): 34 | "This is a hack. Something is broken with torch pickle." 35 | return super(ONMTDatasetBase, self).__reduce_ex__() 36 | 37 | def load_fields(self, vocab_dict): 38 | """ Load fields from vocab.pt, and set the `fields` attribute. 39 | 40 | Args: 41 | vocab_dict (dict): a dict of loaded vocab from vocab.pt file. 42 | """ 43 | from onmt.io.IO import load_fields_from_vocab 44 | 45 | fields = load_fields_from_vocab(vocab_dict.items(), self.data_type) 46 | self.fields = dict([(k, f) for (k, f) in fields.items() 47 | if k in self.examples[0].__dict__]) 48 | 49 | @staticmethod 50 | def extract_text_features(tokens): 51 | """ 52 | Args: 53 | tokens: A list of tokens, where each token consists of a word, 54 | optionally followed by u"│"-delimited features. 55 | Returns: 56 | A sequence of words, a sequence of features, and num of features. 57 | """ 58 | if not tokens: 59 | return [], [], -1 60 | 61 | split_tokens = [token.split(u"│") for token in tokens] 62 | split_tokens = [token for token in split_tokens if token[0]] 63 | if split_tokens: 64 | token_size = len(split_tokens[0]) 65 | else: 66 | token_size = 0 67 | assert all(len(token) == token_size for token in split_tokens), \ 68 | "all words must have the same number of features" 69 | words_and_features = list(zip(*split_tokens)) 70 | if words_and_features: 71 | words = words_and_features[0] 72 | features = words_and_features[1:] 73 | else: 74 | words = [] 75 | features = [] 76 | return words, features, token_size - 1 77 | 78 | # Below are helper functions for intra-class use only. 79 | 80 | def _join_dicts(self, *args): 81 | """ 82 | Args: 83 | dictionaries with disjoint keys. 84 | 85 | Returns: 86 | a single dictionary that has the union of these keys. 87 | """ 88 | return dict(chain(*[d.items() for d in args])) 89 | 90 | def _peek(self, seq): 91 | """ 92 | Args: 93 | seq: an iterator. 94 | 95 | Returns: 96 | the first thing returned by calling next() on the iterator 97 | and an iterator created by re-chaining that value to the beginning 98 | of the iterator. 99 | """ 100 | first = next(seq) 101 | return first, chain([first], seq) 102 | 103 | def _construct_example_fromlist(self, data, fields): 104 | """ 105 | Args: 106 | data: the data to be set as the value of the attributes of 107 | the to-be-created `Example`, associating with respective 108 | `Field` objects with same key. 109 | fields: a dict of `torchtext.data.Field` objects. The keys 110 | are attributes of the to-be-created `Example`. 111 | 112 | Returns: 113 | the created `Example` object. 114 | """ 115 | ex = torchtext.data.Example() 116 | for (name, field), val in zip(fields, data): 117 | if field is not None: 118 | setattr(ex, name, field.preprocess(val)) 119 | else: 120 | setattr(ex, name, val) 121 | return ex 122 | -------------------------------------------------------------------------------- /onmt/io/__init__.py: -------------------------------------------------------------------------------- 1 | from onmt.io.IO import collect_feature_vocabs, make_features, \ 2 | collect_features, get_num_features, \ 3 | load_fields_from_vocab, get_fields, \ 4 | save_fields_to_vocab, build_dataset, \ 5 | build_vocab, merge_vocabs, OrderedIterator 6 | from onmt.io.DatasetBase import ONMTDatasetBase, PAD_WORD, BOS_WORD, \ 7 | EOS_WORD, UNK 8 | from onmt.io.TextDataset import TextDataset, ShardedTextCorpusIterator 9 | from onmt.io.ImageDataset import ImageDataset 10 | from onmt.io.AudioDataset import AudioDataset 11 | 12 | 13 | __all__ = [PAD_WORD, BOS_WORD, EOS_WORD, UNK, ONMTDatasetBase, 14 | collect_feature_vocabs, make_features, 15 | collect_features, get_num_features, 16 | load_fields_from_vocab, get_fields, 17 | save_fields_to_vocab, build_dataset, 18 | build_vocab, merge_vocabs, OrderedIterator, 19 | TextDataset, ImageDataset, AudioDataset, 20 | ShardedTextCorpusIterator] 21 | -------------------------------------------------------------------------------- /onmt/modules/AudioEncoder.py: -------------------------------------------------------------------------------- 1 | import math 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | 5 | 6 | class AudioEncoder(nn.Module): 7 | """ 8 | A simple encoder convolutional -> recurrent neural network for 9 | audio input. 10 | 11 | Args: 12 | num_layers (int): number of encoder layers. 13 | bidirectional (bool): bidirectional encoder. 14 | rnn_size (int): size of hidden states of the rnn. 15 | dropout (float): dropout probablity. 16 | sample_rate (float): input spec 17 | window_size (int): input spec 18 | 19 | """ 20 | def __init__(self, num_layers, bidirectional, rnn_size, dropout, 21 | sample_rate, window_size): 22 | super(AudioEncoder, self).__init__() 23 | self.num_layers = num_layers 24 | self.num_directions = 2 if bidirectional else 1 25 | self.hidden_size = rnn_size 26 | 27 | self.layer1 = nn.Conv2d(1, 32, kernel_size=(41, 11), 28 | padding=(0, 10), stride=(2, 2)) 29 | self.batch_norm1 = nn.BatchNorm2d(32) 30 | self.layer2 = nn.Conv2d(32, 32, kernel_size=(21, 11), 31 | padding=(0, 0), stride=(2, 1)) 32 | self.batch_norm2 = nn.BatchNorm2d(32) 33 | 34 | input_size = int(math.floor((sample_rate * window_size) / 2) + 1) 35 | input_size = int(math.floor(input_size - 41) / 2 + 1) 36 | input_size = int(math.floor(input_size - 21) / 2 + 1) 37 | input_size *= 32 38 | self.rnn = nn.LSTM(input_size, rnn_size, 39 | num_layers=num_layers, 40 | dropout=dropout, 41 | bidirectional=bidirectional) 42 | 43 | def load_pretrained_vectors(self, opt): 44 | # Pass in needed options only when modify function definition. 45 | pass 46 | 47 | def forward(self, input, lengths=None): 48 | "See :obj:`onmt.modules.EncoderBase.forward()`" 49 | # (batch_size, 1, nfft, t) 50 | # layer 1 51 | input = self.batch_norm1(self.layer1(input[:, :, :, :])) 52 | 53 | # (batch_size, 32, nfft/2, t/2) 54 | input = F.hardtanh(input, 0, 20, inplace=True) 55 | 56 | # (batch_size, 32, nfft/2/2, t/2) 57 | # layer 2 58 | input = self.batch_norm2(self.layer2(input)) 59 | 60 | # (batch_size, 32, nfft/2/2, t/2) 61 | input = F.hardtanh(input, 0, 20, inplace=True) 62 | 63 | batch_size = input.size(0) 64 | length = input.size(3) 65 | input = input.view(batch_size, -1, length) 66 | input = input.transpose(0, 2).transpose(1, 2) 67 | 68 | output, hidden = self.rnn(input) 69 | 70 | return hidden, output 71 | -------------------------------------------------------------------------------- /onmt/modules/ConvMultiStepAttention.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | from onmt.Utils import aeq 5 | 6 | 7 | SCALE_WEIGHT = 0.5 ** 0.5 8 | 9 | 10 | def seq_linear(linear, x): 11 | # linear transform for 3-d tensor 12 | batch, hidden_size, length, _ = x.size() 13 | h = linear(torch.transpose(x, 1, 2).contiguous().view( 14 | batch * length, hidden_size)) 15 | return torch.transpose(h.view(batch, length, hidden_size, 1), 1, 2) 16 | 17 | 18 | class ConvMultiStepAttention(nn.Module): 19 | """ 20 | 21 | Conv attention takes a key matrix, a value matrix and a query vector. 22 | Attention weight is calculated by key matrix with the query vector 23 | and sum on the value matrix. And the same operation is applied 24 | in each decode conv layer. 25 | 26 | """ 27 | 28 | def __init__(self, input_size): 29 | super(ConvMultiStepAttention, self).__init__() 30 | self.linear_in = nn.Linear(input_size, input_size) 31 | self.mask = None 32 | 33 | def apply_mask(self, mask): 34 | self.mask = mask 35 | 36 | def forward(self, base_target_emb, input, encoder_out_top, 37 | encoder_out_combine): 38 | """ 39 | Args: 40 | base_target_emb: target emb tensor 41 | input: output of decode conv 42 | encoder_out_t: the key matrix for calculation of attetion weight, 43 | which is the top output of encode conv 44 | encoder_out_combine: 45 | the value matrix for the attention-weighted sum, 46 | which is the combination of base emb and top output of encode 47 | 48 | """ 49 | # checks 50 | batch, channel, height, width = base_target_emb.size() 51 | batch_, channel_, height_, width_ = input.size() 52 | aeq(batch, batch_) 53 | aeq(height, height_) 54 | 55 | enc_batch, enc_channel, enc_height = encoder_out_top.size() 56 | enc_batch_, enc_channel_, enc_height_ = encoder_out_combine.size() 57 | 58 | aeq(enc_batch, enc_batch_) 59 | aeq(enc_height, enc_height_) 60 | 61 | preatt = seq_linear(self.linear_in, input) 62 | target = (base_target_emb + preatt) * SCALE_WEIGHT 63 | target = torch.squeeze(target, 3) 64 | target = torch.transpose(target, 1, 2) 65 | pre_attn = torch.bmm(target, encoder_out_top) 66 | 67 | if self.mask is not None: 68 | pre_attn.data.masked_fill_(self.mask, -float('inf')) 69 | 70 | pre_attn = pre_attn.transpose(0, 2) 71 | attn = F.softmax(pre_attn) 72 | attn = attn.transpose(0, 2).contiguous() 73 | context_output = torch.bmm( 74 | attn, torch.transpose(encoder_out_combine, 1, 2)) 75 | context_output = torch.transpose( 76 | torch.unsqueeze(context_output, 3), 1, 2) 77 | return context_output, attn 78 | -------------------------------------------------------------------------------- /onmt/modules/Gate.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | 4 | 5 | def context_gate_factory(type, embeddings_size, decoder_size, 6 | attention_size, output_size): 7 | """Returns the correct ContextGate class""" 8 | 9 | gate_types = {'source': SourceContextGate, 10 | 'target': TargetContextGate, 11 | 'both': BothContextGate} 12 | 13 | assert type in gate_types, "Not valid ContextGate type: {0}".format(type) 14 | return gate_types[type](embeddings_size, decoder_size, attention_size, 15 | output_size) 16 | 17 | 18 | class ContextGate(nn.Module): 19 | """ 20 | Context gate is a decoder module that takes as input the previous word 21 | embedding, the current decoder state and the attention state, and 22 | produces a gate. 23 | The gate can be used to select the input from the target side context 24 | (decoder state), from the source context (attention state) or both. 25 | """ 26 | def __init__(self, embeddings_size, decoder_size, 27 | attention_size, output_size): 28 | super(ContextGate, self).__init__() 29 | input_size = embeddings_size + decoder_size + attention_size 30 | self.gate = nn.Linear(input_size, output_size, bias=True) 31 | self.sig = nn.Sigmoid() 32 | self.source_proj = nn.Linear(attention_size, output_size) 33 | self.target_proj = nn.Linear(embeddings_size + decoder_size, 34 | output_size) 35 | 36 | def forward(self, prev_emb, dec_state, attn_state): 37 | input_tensor = torch.cat((prev_emb, dec_state, attn_state), dim=1) 38 | z = self.sig(self.gate(input_tensor)) 39 | proj_source = self.source_proj(attn_state) 40 | proj_target = self.target_proj( 41 | torch.cat((prev_emb, dec_state), dim=1)) 42 | return z, proj_source, proj_target 43 | 44 | 45 | class SourceContextGate(nn.Module): 46 | """Apply the context gate only to the source context""" 47 | 48 | def __init__(self, embeddings_size, decoder_size, 49 | attention_size, output_size): 50 | super(SourceContextGate, self).__init__() 51 | self.context_gate = ContextGate(embeddings_size, decoder_size, 52 | attention_size, output_size) 53 | self.tanh = nn.Tanh() 54 | 55 | def forward(self, prev_emb, dec_state, attn_state): 56 | z, source, target = self.context_gate( 57 | prev_emb, dec_state, attn_state) 58 | return self.tanh(target + z * source) 59 | 60 | 61 | class TargetContextGate(nn.Module): 62 | """Apply the context gate only to the target context""" 63 | 64 | def __init__(self, embeddings_size, decoder_size, 65 | attention_size, output_size): 66 | super(TargetContextGate, self).__init__() 67 | self.context_gate = ContextGate(embeddings_size, decoder_size, 68 | attention_size, output_size) 69 | self.tanh = nn.Tanh() 70 | 71 | def forward(self, prev_emb, dec_state, attn_state): 72 | z, source, target = self.context_gate(prev_emb, dec_state, attn_state) 73 | return self.tanh(z * target + source) 74 | 75 | 76 | class BothContextGate(nn.Module): 77 | """Apply the context gate to both contexts""" 78 | 79 | def __init__(self, embeddings_size, decoder_size, 80 | attention_size, output_size): 81 | super(BothContextGate, self).__init__() 82 | self.context_gate = ContextGate(embeddings_size, decoder_size, 83 | attention_size, output_size) 84 | self.tanh = nn.Tanh() 85 | 86 | def forward(self, prev_emb, dec_state, attn_state): 87 | z, source, target = self.context_gate(prev_emb, dec_state, attn_state) 88 | return self.tanh((1. - z) * target + z * source) 89 | -------------------------------------------------------------------------------- /onmt/modules/ImageEncoder.py: -------------------------------------------------------------------------------- 1 | import torch.nn as nn 2 | import torch.nn.functional as F 3 | import torch 4 | from torch.autograd import Variable 5 | 6 | 7 | class ImageEncoder(nn.Module): 8 | """ 9 | A simple encoder convolutional -> recurrent neural network for 10 | image input. 11 | 12 | Args: 13 | num_layers (int): number of encoder layers. 14 | bidirectional (bool): bidirectional encoder. 15 | rnn_size (int): size of hidden states of the rnn. 16 | dropout (float): dropout probablity. 17 | """ 18 | def __init__(self, num_layers, bidirectional, rnn_size, dropout): 19 | super(ImageEncoder, self).__init__() 20 | self.num_layers = num_layers 21 | self.num_directions = 2 if bidirectional else 1 22 | self.hidden_size = rnn_size 23 | 24 | self.layer1 = nn.Conv2d(3, 64, kernel_size=(3, 3), 25 | padding=(1, 1), stride=(1, 1)) 26 | self.layer2 = nn.Conv2d(64, 128, kernel_size=(3, 3), 27 | padding=(1, 1), stride=(1, 1)) 28 | self.layer3 = nn.Conv2d(128, 256, kernel_size=(3, 3), 29 | padding=(1, 1), stride=(1, 1)) 30 | self.layer4 = nn.Conv2d(256, 256, kernel_size=(3, 3), 31 | padding=(1, 1), stride=(1, 1)) 32 | self.layer5 = nn.Conv2d(256, 512, kernel_size=(3, 3), 33 | padding=(1, 1), stride=(1, 1)) 34 | self.layer6 = nn.Conv2d(512, 512, kernel_size=(3, 3), 35 | padding=(1, 1), stride=(1, 1)) 36 | 37 | self.batch_norm1 = nn.BatchNorm2d(256) 38 | self.batch_norm2 = nn.BatchNorm2d(512) 39 | self.batch_norm3 = nn.BatchNorm2d(512) 40 | 41 | input_size = 512 42 | self.rnn = nn.LSTM(input_size, rnn_size, 43 | num_layers=num_layers, 44 | dropout=dropout, 45 | bidirectional=bidirectional) 46 | self.pos_lut = nn.Embedding(1000, input_size) 47 | 48 | def load_pretrained_vectors(self, opt): 49 | # Pass in needed options only when modify function definition. 50 | pass 51 | 52 | def forward(self, input, lengths=None): 53 | "See :obj:`onmt.modules.EncoderBase.forward()`" 54 | 55 | batch_size = input.size(0) 56 | # (batch_size, 64, imgH, imgW) 57 | # layer 1 58 | input = F.relu(self.layer1(input[:, :, :, :]-0.5), True) 59 | 60 | # (batch_size, 64, imgH/2, imgW/2) 61 | input = F.max_pool2d(input, kernel_size=(2, 2), stride=(2, 2)) 62 | 63 | # (batch_size, 128, imgH/2, imgW/2) 64 | # layer 2 65 | input = F.relu(self.layer2(input), True) 66 | 67 | # (batch_size, 128, imgH/2/2, imgW/2/2) 68 | input = F.max_pool2d(input, kernel_size=(2, 2), stride=(2, 2)) 69 | 70 | # (batch_size, 256, imgH/2/2, imgW/2/2) 71 | # layer 3 72 | # batch norm 1 73 | input = F.relu(self.batch_norm1(self.layer3(input)), True) 74 | 75 | # (batch_size, 256, imgH/2/2, imgW/2/2) 76 | # layer4 77 | input = F.relu(self.layer4(input), True) 78 | 79 | # (batch_size, 256, imgH/2/2/2, imgW/2/2) 80 | input = F.max_pool2d(input, kernel_size=(1, 2), stride=(1, 2)) 81 | 82 | # (batch_size, 512, imgH/2/2/2, imgW/2/2) 83 | # layer 5 84 | # batch norm 2 85 | input = F.relu(self.batch_norm2(self.layer5(input)), True) 86 | 87 | # (batch_size, 512, imgH/2/2/2, imgW/2/2/2) 88 | input = F.max_pool2d(input, kernel_size=(2, 1), stride=(2, 1)) 89 | 90 | # (batch_size, 512, imgH/2/2/2, imgW/2/2/2) 91 | input = F.relu(self.batch_norm3(self.layer6(input)), True) 92 | 93 | # # (batch_size, 512, H, W) 94 | all_outputs = [] 95 | for row in range(input.size(2)): 96 | inp = input[:, :, row, :].transpose(0, 2)\ 97 | .transpose(1, 2) 98 | row_vec = torch.Tensor(batch_size).type_as(inp.data)\ 99 | .long().fill_(row) 100 | pos_emb = self.pos_lut(Variable(row_vec)) 101 | with_pos = torch.cat( 102 | (pos_emb.view(1, pos_emb.size(0), pos_emb.size(1)), inp), 0) 103 | outputs, hidden_t = self.rnn(with_pos) 104 | all_outputs.append(outputs) 105 | out = torch.cat(all_outputs, 0) 106 | 107 | return hidden_t, out 108 | -------------------------------------------------------------------------------- /onmt/modules/MultiHeadedAttn.py: -------------------------------------------------------------------------------- 1 | import math 2 | import torch 3 | import torch.nn as nn 4 | from torch.autograd import Variable 5 | 6 | from onmt.Utils import aeq 7 | 8 | 9 | class MultiHeadedAttention(nn.Module): 10 | """ 11 | Multi-Head Attention module from 12 | "Attention is All You Need" 13 | :cite:`DBLP:journals/corr/VaswaniSPUJGKP17`. 14 | 15 | Similar to standard `dot` attention but uses 16 | multiple attention distributions simulataneously 17 | to select relevant items. 18 | 19 | .. mermaid:: 20 | 21 | graph BT 22 | A[key] 23 | B[value] 24 | C[query] 25 | O[output] 26 | subgraph Attn 27 | D[Attn 1] 28 | E[Attn 2] 29 | F[Attn N] 30 | end 31 | A --> D 32 | C --> D 33 | A --> E 34 | C --> E 35 | A --> F 36 | C --> F 37 | D --> O 38 | E --> O 39 | F --> O 40 | B --> O 41 | 42 | Also includes several additional tricks. 43 | 44 | Args: 45 | head_count (int): number of parallel heads 46 | model_dim (int): the dimension of keys/values/queries, 47 | must be divisible by head_count 48 | dropout (float): dropout parameter 49 | """ 50 | def __init__(self, head_count, model_dim, dropout=0.1): 51 | assert model_dim % head_count == 0 52 | self.dim_per_head = model_dim // head_count 53 | self.model_dim = model_dim 54 | 55 | super(MultiHeadedAttention, self).__init__() 56 | self.head_count = head_count 57 | 58 | self.linear_keys = nn.Linear(model_dim, 59 | head_count * self.dim_per_head) 60 | self.linear_values = nn.Linear(model_dim, 61 | head_count * self.dim_per_head) 62 | self.linear_query = nn.Linear(model_dim, 63 | head_count * self.dim_per_head) 64 | self.sm = nn.Softmax(dim=-1) 65 | self.dropout = nn.Dropout(dropout) 66 | self.final_linear = nn.Linear(model_dim, model_dim) 67 | 68 | def forward(self, key, value, query, mask=None): 69 | """ 70 | Compute the context vector and the attention vectors. 71 | 72 | Args: 73 | key (`FloatTensor`): set of `key_len` 74 | key vectors `[batch, key_len, dim]` 75 | value (`FloatTensor`): set of `key_len` 76 | value vectors `[batch, key_len, dim]` 77 | query (`FloatTensor`): set of `query_len` 78 | query vectors `[batch, query_len, dim]` 79 | mask: binary mask indicating which keys have 80 | non-zero attention `[batch, query_len, key_len]` 81 | Returns: 82 | (`FloatTensor`, `FloatTensor`) : 83 | 84 | * output context vectors `[batch, query_len, dim]` 85 | * one of the attention vectors `[batch, query_len, key_len]` 86 | """ 87 | 88 | # CHECKS 89 | batch, k_len, d = key.size() 90 | batch_, k_len_, d_ = value.size() 91 | aeq(batch, batch_) 92 | aeq(k_len, k_len_) 93 | aeq(d, d_) 94 | batch_, q_len, d_ = query.size() 95 | aeq(batch, batch_) 96 | aeq(d, d_) 97 | aeq(self.model_dim % 8, 0) 98 | if mask is not None: 99 | batch_, q_len_, k_len_ = mask.size() 100 | aeq(batch_, batch) 101 | aeq(k_len_, k_len) 102 | aeq(q_len_ == q_len) 103 | # END CHECKS 104 | 105 | batch_size = key.size(0) 106 | dim_per_head = self.dim_per_head 107 | head_count = self.head_count 108 | key_len = key.size(1) 109 | query_len = query.size(1) 110 | 111 | def shape(x): 112 | return x.view(batch_size, -1, head_count, dim_per_head) \ 113 | .transpose(1, 2) 114 | 115 | def unshape(x): 116 | return x.transpose(1, 2).contiguous() \ 117 | .view(batch_size, -1, head_count * dim_per_head) 118 | 119 | # 1) Project key, value, and query. 120 | key_up = shape(self.linear_keys(key)) 121 | value_up = shape(self.linear_values(value)) 122 | query_up = shape(self.linear_query(query)) 123 | 124 | # 2) Calculate and scale scores. 125 | query_up = query_up / math.sqrt(dim_per_head) 126 | scores = torch.matmul(query_up, key_up.transpose(2, 3)) 127 | 128 | if mask is not None: 129 | mask = mask.unsqueeze(1).expand_as(scores) 130 | scores = scores.masked_fill(Variable(mask), -1e18) 131 | 132 | # 3) Apply attention dropout and compute context vectors. 133 | attn = self.sm(scores) 134 | drop_attn = self.dropout(attn) 135 | context = unshape(torch.matmul(drop_attn, value_up)) 136 | 137 | output = self.final_linear(context) 138 | # CHECK 139 | batch_, q_len_, d_ = output.size() 140 | aeq(q_len, q_len_) 141 | aeq(batch, batch_) 142 | aeq(d, d_) 143 | 144 | # Return one attn 145 | top_attn = attn \ 146 | .view(batch_size, head_count, 147 | query_len, key_len)[:, 0, :, :] \ 148 | .contiguous() 149 | # END CHECK 150 | return output, top_attn 151 | -------------------------------------------------------------------------------- /onmt/modules/NGram.py: -------------------------------------------------------------------------------- 1 | from nltk import ngrams 2 | from collections import Counter 3 | import math 4 | 5 | class NGram(object): 6 | def __init__(self, corpus, vocab): 7 | self.vocab = vocab 8 | self.corpus = [] 9 | for w in corpus: 10 | self.corpus.append(vocab.stoi[w]) 11 | self.size = len(self.corpus) 12 | self.ngram = { 13 | 1: Counter(self.corpus), 14 | 2: Counter(ngrams(self.corpus, 2)), 15 | 3: Counter(ngrams(self.corpus, 3)), 16 | 4: Counter(ngrams(self.corpus, 4)), 17 | 5: Counter(ngrams(self.corpus, 5)) 18 | } 19 | self.vocab_size = len(self.ngram) - 2 20 | 21 | def get_MLE_probs(self, word, history=None): 22 | if history: 23 | try: 24 | if len(history) == 1: 25 | result = self.ngram[len(history) + 1][tuple(history + [word])] / \ 26 | self.ngram[len(history)][history[0]] 27 | else: 28 | result = self.ngram[len(history) + 1][tuple(history + [word])] / \ 29 | self.ngram[len(history)][tuple(history)] 30 | except ZeroDivisionError: 31 | result = 0 32 | else: 33 | result = self.ngram[1][word] / self.size 34 | return result 35 | 36 | 37 | if __name__ == '__main__': 38 | corpus = "My girl is learning that a girl is actually a boy".split() 39 | my_ngram = NGram(corpus) 40 | print(my_ngram.get_MLE_probs('girl')) 41 | history = "a".split() 42 | print(my_ngram.get_MLE_probs('girl', history)) 43 | -------------------------------------------------------------------------------- /onmt/modules/StackedRNN.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | 4 | 5 | class StackedLSTM(nn.Module): 6 | """ 7 | Our own implementation of stacked LSTM. 8 | Needed for the decoder, because we do input feeding. 9 | """ 10 | def __init__(self, num_layers, input_size, rnn_size, dropout): 11 | super(StackedLSTM, self).__init__() 12 | self.dropout = nn.Dropout(dropout) 13 | self.num_layers = num_layers 14 | self.layers = nn.ModuleList() 15 | 16 | for i in range(num_layers): 17 | self.layers.append(nn.LSTMCell(input_size, rnn_size)) 18 | input_size = rnn_size 19 | 20 | def forward(self, input, hidden): 21 | h_0, c_0 = hidden 22 | h_1, c_1 = [], [] 23 | for i, layer in enumerate(self.layers): 24 | h_1_i, c_1_i = layer(input, (h_0[i], c_0[i])) 25 | input = h_1_i 26 | if i + 1 != self.num_layers: 27 | input = self.dropout(input) 28 | h_1 += [h_1_i] 29 | c_1 += [c_1_i] 30 | 31 | h_1 = torch.stack(h_1) 32 | c_1 = torch.stack(c_1) 33 | 34 | return input, (h_1, c_1) 35 | 36 | 37 | class StackedGRU(nn.Module): 38 | 39 | def __init__(self, num_layers, input_size, rnn_size, dropout): 40 | super(StackedGRU, self).__init__() 41 | self.dropout = nn.Dropout(dropout) 42 | self.num_layers = num_layers 43 | self.layers = nn.ModuleList() 44 | 45 | for i in range(num_layers): 46 | self.layers.append(nn.GRUCell(input_size, rnn_size)) 47 | input_size = rnn_size 48 | 49 | def forward(self, input, hidden): 50 | h_1 = [] 51 | for i, layer in enumerate(self.layers): 52 | h_1_i = layer(input, hidden[0][i]) 53 | input = h_1_i 54 | if i + 1 != self.num_layers: 55 | input = self.dropout(input) 56 | h_1 += [h_1_i] 57 | 58 | h_1 = torch.stack(h_1) 59 | return input, (h_1,) 60 | -------------------------------------------------------------------------------- /onmt/modules/StructuredAttention.py: -------------------------------------------------------------------------------- 1 | import torch.nn as nn 2 | import torch 3 | import torch.cuda 4 | from torch.autograd import Variable 5 | 6 | 7 | class MatrixTree(nn.Module): 8 | """Implementation of the matrix-tree theorem for computing marginals 9 | of non-projective dependency parsing. This attention layer is used 10 | in the paper "Learning Structured Text Representations." 11 | 12 | 13 | :cite:`DBLP:journals/corr/LiuL17d` 14 | """ 15 | def __init__(self, eps=1e-5): 16 | self.eps = eps 17 | super(MatrixTree, self).__init__() 18 | 19 | def forward(self, input): 20 | laplacian = input.exp() + self.eps 21 | output = input.clone() 22 | for b in range(input.size(0)): 23 | lap = laplacian[b].masked_fill( 24 | Variable(torch.eye(input.size(1)).cuda().ne(0)), 0) 25 | lap = -lap + torch.diag(lap.sum(0)) 26 | # store roots on diagonal 27 | lap[0] = input[b].diag().exp() 28 | inv_laplacian = lap.inverse() 29 | 30 | factor = inv_laplacian.diag().unsqueeze(1)\ 31 | .expand_as(input[b]).transpose(0, 1) 32 | term1 = input[b].exp().mul(factor).clone() 33 | term2 = input[b].exp().mul(inv_laplacian.transpose(0, 1)).clone() 34 | term1[:, 0] = 0 35 | term2[0] = 0 36 | output[b] = term1 - term2 37 | roots_output = input[b].diag().exp().mul( 38 | inv_laplacian.transpose(0, 1)[0]) 39 | output[b] = output[b] + torch.diag(roots_output) 40 | return output 41 | 42 | 43 | if __name__ == "__main__": 44 | dtree = MatrixTree() 45 | q = torch.rand(1, 5, 5).cuda() 46 | marg = dtree.forward(Variable(q)) 47 | print(marg.sum(1)) 48 | -------------------------------------------------------------------------------- /onmt/modules/UtilClass.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | 4 | 5 | class LayerNorm(nn.Module): 6 | def __init__(self, features, eps=1e-6): 7 | super(LayerNorm, self).__init__() 8 | self.a_2 = nn.Parameter(torch.ones(features)) 9 | self.b_2 = nn.Parameter(torch.zeros(features)) 10 | self.eps = eps 11 | 12 | def forward(self, x): 13 | mean = x.mean(-1, keepdim=True) 14 | std = x.std(-1, keepdim=True) 15 | return self.a_2 * (x - mean) / (std + self.eps) + self.b_2 16 | 17 | 18 | class Elementwise(nn.ModuleList): 19 | """ 20 | A simple network container. 21 | Parameters are a list of modules. 22 | Inputs are a 3d Variable whose last dimension is the same length 23 | as the list. 24 | Outputs are the result of applying modules to inputs elementwise. 25 | An optional merge parameter allows the outputs to be reduced to a 26 | single Variable. 27 | """ 28 | 29 | def __init__(self, merge=None, *args): 30 | assert merge in [None, 'first', 'concat', 'sum', 'mlp'] 31 | self.merge = merge 32 | super(Elementwise, self).__init__(*args) 33 | 34 | def forward(self, input): 35 | inputs = [feat.squeeze(2) for feat in input.split(1, dim=2)] 36 | assert len(self) == len(inputs) 37 | outputs = [f(x) for f, x in zip(self, inputs)] 38 | if self.merge == 'first': 39 | return outputs[0] 40 | elif self.merge == 'concat' or self.merge == 'mlp': 41 | return torch.cat(outputs, 2) 42 | elif self.merge == 'sum': 43 | return sum(outputs) 44 | else: 45 | return outputs 46 | -------------------------------------------------------------------------------- /onmt/modules/__init__.py: -------------------------------------------------------------------------------- 1 | from onmt.modules.UtilClass import LayerNorm, Elementwise 2 | from onmt.modules.Gate import context_gate_factory, ContextGate 3 | from onmt.modules.GlobalAttention import GlobalAttention 4 | from onmt.modules.ConvMultiStepAttention import ConvMultiStepAttention 5 | from onmt.modules.ImageEncoder import ImageEncoder 6 | from onmt.modules.AudioEncoder import AudioEncoder 7 | from onmt.modules.CopyGenerator import CopyGenerator, CopyGeneratorLossCompute 8 | from onmt.modules.StructuredAttention import MatrixTree 9 | from onmt.modules.Transformer import \ 10 | TransformerEncoder, TransformerDecoder, PositionwiseFeedForward 11 | from onmt.modules.Conv2Conv import CNNEncoder, CNNDecoder 12 | from onmt.modules.MultiHeadedAttn import MultiHeadedAttention 13 | from onmt.modules.StackedRNN import StackedLSTM, StackedGRU 14 | from onmt.modules.Embeddings import Embeddings, PositionalEncoding 15 | from onmt.modules.WeightNorm import WeightNormConv2d 16 | 17 | from onmt.Models import EncoderBase, MeanEncoder, StdRNNDecoder, \ 18 | RNNDecoderBase, InputFeedRNNDecoder, RNNEncoder, NMTModel 19 | 20 | from onmt.modules.SRU import check_sru_requirement 21 | can_use_sru = check_sru_requirement() 22 | if can_use_sru: 23 | from onmt.modules.SRU import SRU 24 | 25 | 26 | # For flake8 compatibility. 27 | __all__ = [EncoderBase, MeanEncoder, RNNDecoderBase, InputFeedRNNDecoder, 28 | RNNEncoder, NMTModel, 29 | StdRNNDecoder, ContextGate, GlobalAttention, ImageEncoder, 30 | PositionwiseFeedForward, PositionalEncoding, 31 | CopyGenerator, MultiHeadedAttention, 32 | LayerNorm, 33 | TransformerEncoder, TransformerDecoder, Embeddings, Elementwise, 34 | MatrixTree, WeightNormConv2d, ConvMultiStepAttention, 35 | CNNEncoder, CNNDecoder, StackedLSTM, StackedGRU, 36 | context_gate_factory, CopyGeneratorLossCompute, AudioEncoder] 37 | 38 | if can_use_sru: 39 | __all__.extend([SRU, check_sru_requirement]) 40 | -------------------------------------------------------------------------------- /onmt/translate/Penalties.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | import torch 3 | 4 | 5 | class PenaltyBuilder(object): 6 | """ 7 | Returns the Length and Coverage Penalty function for Beam Search. 8 | 9 | Args: 10 | length_pen (str): option name of length pen 11 | cov_pen (str): option name of cov pen 12 | """ 13 | def __init__(self, cov_pen, length_pen): 14 | self.length_pen = length_pen 15 | self.cov_pen = cov_pen 16 | 17 | def coverage_penalty(self): 18 | if self.cov_pen == "wu": 19 | return self.coverage_wu 20 | elif self.cov_pen == "summary": 21 | return self.coverage_summary 22 | else: 23 | return self.coverage_none 24 | 25 | def length_penalty(self): 26 | if self.length_pen == "wu": 27 | return self.length_wu 28 | elif self.length_pen == "avg": 29 | return self.length_average 30 | else: 31 | return self.length_none 32 | 33 | """ 34 | Below are all the different penalty terms implemented so far 35 | """ 36 | 37 | def coverage_wu(self, beam, cov, beta=0.): 38 | """ 39 | NMT coverage re-ranking score from 40 | "Google's Neural Machine Translation System" :cite:`wu2016google`. 41 | """ 42 | penalty = -torch.min(cov, cov.clone().fill_(1.0)).log().sum(1) 43 | return beta * penalty 44 | 45 | def coverage_summary(self, beam, cov, beta=0.): 46 | """ 47 | Our summary penalty. 48 | """ 49 | penalty = torch.max(cov, cov.clone().fill_(1.0)).sum(1) 50 | penalty -= cov.size(1) 51 | return beta * penalty 52 | 53 | def coverage_none(self, beam, cov, beta=0.): 54 | """ 55 | returns zero as penalty 56 | """ 57 | return beam.scores.clone().fill_(0.0) 58 | 59 | def length_wu(self, beam, logprobs, alpha=0.): 60 | """ 61 | NMT length re-ranking score from 62 | "Google's Neural Machine Translation System" :cite:`wu2016google`. 63 | """ 64 | 65 | modifier = (((5 + len(beam.next_ys)) ** alpha) / 66 | ((5 + 1) ** alpha)) 67 | return (logprobs / modifier) 68 | 69 | def length_average(self, beam, logprobs, alpha=0.): 70 | """ 71 | Returns the average probability of tokens in a sequence. 72 | """ 73 | return logprobs / len(beam.next_ys) 74 | 75 | def length_none(self, beam, logprobs, alpha=0., beta=0.): 76 | """ 77 | Returns unmodified scores. 78 | """ 79 | return logprobs 80 | -------------------------------------------------------------------------------- /onmt/translate/Translation.py: -------------------------------------------------------------------------------- 1 | from __future__ import division, unicode_literals 2 | import re 3 | import torch 4 | import onmt.io 5 | 6 | 7 | class TranslationBuilder(object): 8 | """ 9 | Build a word-based translation from the batch output 10 | of translator and the underlying dictionaries. 11 | 12 | Replacement based on "Addressing the Rare Word 13 | Problem in Neural Machine Translation" :cite:`Luong2015b` 14 | 15 | Args: 16 | data (DataSet): 17 | fields (dict of Fields): data fields 18 | n_best (int): number of translations produced 19 | replace_unk (bool): replace unknown words using attention 20 | has_tgt (bool): will the batch have gold targets 21 | """ 22 | def __init__(self, data, fields, n_best=1, replace_unk=False, 23 | has_tgt=False): 24 | self.data = data 25 | self.fields = fields 26 | self.n_best = n_best 27 | self.replace_unk = replace_unk 28 | self.has_tgt = has_tgt 29 | 30 | def _build_target_tokens(self, src, src_vocab, src_raw, pred, attn, b): 31 | vocab = self.fields["tgt"].vocab 32 | tokens = [] 33 | for tok in pred: 34 | if tok < len(vocab): 35 | tokens.append(vocab.itos[tok]) 36 | else: 37 | tokens.append(src_vocab.itos[tok - len(vocab)]) 38 | if tokens[-1] == onmt.io.EOS_WORD: 39 | tokens = tokens[:-1] 40 | break 41 | if self.replace_unk and (attn is not None) and (src is not None): 42 | for i in range(len(tokens)): 43 | phrase_table = None 44 | if hasattr(self.data.examples[b], 'phrase_table'): 45 | phrase_table = { 46 | s.split('|||')[0]: s.split('|||')[1] 47 | for s in self.data.examples[b].phrase_table 48 | } 49 | for key, item in phrase_table.items(): 50 | if 'name' in key: 51 | phrase_table[key] = ' '.join(item.split('_')[1:]) 52 | # pattern = re.compile(r'.*_?(name|entity|num)_[0-9]$') 53 | # if pattern.match(tokens[i]): 54 | # if phrase_table and tokens[i] in phrase_table: 55 | # tokens[i] = phrase_table[tokens[i]] 56 | # else: 57 | # tokens[i] = vocab.itos[onmt.io.UNK] 58 | if tokens[i] == vocab.itos[onmt.io.UNK]: 59 | src_idx = attn[i].max(0)[1][0] 60 | if phrase_table and src_raw[src_idx] in phrase_table: 61 | tokens[i] = phrase_table[src_raw[src_idx]] 62 | elif hasattr(self.data, 'global_phrase_table') \ 63 | and src_raw[src_idx] in self.data.global_phrase_table: 64 | tokens[i] = self.data.global_phrase_table[src_raw[src_idx]] 65 | else: 66 | tokens[i] = src_raw[src_idx] 67 | if tokens[i] == '-lrb-': 68 | tokens[i] = '(' 69 | if tokens[i] == '-rrb-': 70 | tokens[i] = ')' 71 | # tokens[i] = tokens[i] + '_' + str(i) 72 | return tokens 73 | 74 | def from_batch(self, translation_batch): 75 | batch = translation_batch["batch"] 76 | assert(len(translation_batch["gold_score"]) == 77 | len(translation_batch["predictions"])) 78 | batch_size = batch.batch_size 79 | 80 | preds, pred_score, attn, gold_score, indices = list(zip( 81 | *sorted(zip(translation_batch["predictions"], 82 | translation_batch["scores"], 83 | translation_batch["attention"], 84 | translation_batch["gold_score"], 85 | batch.indices.data), 86 | key=lambda x: x[-1]))) 87 | 88 | # Sorting 89 | inds, perm = torch.sort(batch.indices.data) 90 | data_type = self.data.data_type 91 | if data_type == 'text': 92 | src = batch.src[0].data.index_select(1, perm) 93 | else: 94 | src = None 95 | 96 | if self.has_tgt: 97 | tgt = batch.tgt.data.index_select(1, perm) 98 | else: 99 | tgt = None 100 | 101 | translations = [] 102 | for b in range(batch_size): 103 | if data_type == 'text': 104 | src_vocab = self.data.src_vocabs[inds[b]] \ 105 | if self.data.src_vocabs else None 106 | src_raw = self.data.examples[inds[b]].src 107 | else: 108 | src_vocab = None 109 | src_raw = None 110 | pred_sents = [self._build_target_tokens( 111 | src[:, b] if src is not None else None, 112 | src_vocab, src_raw, 113 | preds[b][n], attn[b][n], b) 114 | for n in range(self.n_best)] 115 | gold_sent = None 116 | if tgt is not None: 117 | gold_sent = self._build_target_tokens( 118 | src[:, b] if src is not None else None, 119 | src_vocab, src_raw, 120 | tgt[1:, b] if tgt is not None else None, None, b) 121 | 122 | translation = Translation(src[:, b] if src is not None else None, 123 | src_raw, pred_sents, 124 | attn[b], pred_score[b], gold_sent, 125 | gold_score[b]) 126 | translations.append(translation) 127 | 128 | return translations 129 | 130 | 131 | class Translation(object): 132 | """ 133 | Container for a translated sentence. 134 | 135 | Attributes: 136 | src (`LongTensor`): src word ids 137 | src_raw ([str]): raw src words 138 | 139 | pred_sents ([[str]]): words from the n-best translations 140 | pred_scores ([[float]]): log-probs of n-best translations 141 | attns ([`FloatTensor`]) : attention dist for each translation 142 | gold_sent ([str]): words from gold translation 143 | gold_score ([float]): log-prob of gold translation 144 | 145 | """ 146 | def __init__(self, src, src_raw, pred_sents, 147 | attn, pred_scores, tgt_sent, gold_score): 148 | self.src = src 149 | self.src_raw = src_raw 150 | self.pred_sents = pred_sents 151 | self.attns = attn 152 | self.pred_scores = pred_scores 153 | self.gold_sent = tgt_sent 154 | self.gold_score = gold_score 155 | 156 | def log(self, sent_number): 157 | """ 158 | Log translation to stdout. 159 | """ 160 | output = '\nSENT {}: {}\n'.format(sent_number, self.src_raw) 161 | 162 | best_pred = self.pred_sents[0] 163 | best_score = self.pred_scores[0] 164 | pred_sent = ' '.join(best_pred) 165 | output += 'PRED {}: {}\n'.format(sent_number, pred_sent) 166 | print("PRED SCORE: {:.4f}".format(best_score)) 167 | 168 | if self.gold_sent is not None: 169 | tgt_sent = ' '.join(self.gold_sent) 170 | output += 'GOLD {}: {}\n'.format(sent_number, tgt_sent) 171 | # output += ("GOLD SCORE: {:.4f}".format(self.gold_score)) 172 | print("GOLD SCORE: {:.4f}".format(self.gold_score)) 173 | if len(self.pred_sents) > 1: 174 | print('\nBEST HYP:') 175 | for score, sent in zip(self.pred_scores, self.pred_sents): 176 | output += "[{:.4f}] {}\n".format(score, sent) 177 | 178 | return output 179 | -------------------------------------------------------------------------------- /onmt/translate/__init__.py: -------------------------------------------------------------------------------- 1 | from onmt.translate.Translator import Translator 2 | from onmt.translate.Translation import Translation, TranslationBuilder 3 | from onmt.translate.Beam import Beam, GNMTGlobalScorer 4 | from onmt.translate.Penalties import PenaltyBuilder 5 | from onmt.translate.TranslationServer import TranslationServer, \ 6 | ServerModelError 7 | 8 | __all__ = [Translator, Translation, Beam, 9 | GNMTGlobalScorer, TranslationBuilder, 10 | PenaltyBuilder, TranslationServer, ServerModelError] 11 | -------------------------------------------------------------------------------- /requirements.opt.txt: -------------------------------------------------------------------------------- 1 | cffi 2 | torchvision==0.1.8 3 | librosa 4 | Pillow 5 | git+https://github.com/pytorch/audio 6 | pyrouge 7 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | six 2 | tqdm 3 | torchtext>=0.2.1 4 | future 5 | -------------------------------------------------------------------------------- /server.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import argparse 3 | 4 | from flask import Flask, jsonify, request 5 | from onmt.translate import TranslationServer, ServerModelError 6 | 7 | STATUS_OK = "ok" 8 | STATUS_ERROR = "error" 9 | 10 | 11 | def start(config_file, 12 | url_root="./translator", 13 | host="0.0.0.0", 14 | port=5000, 15 | debug=True): 16 | def prefix_route(route_function, prefix='', mask='{0}{1}'): 17 | def newroute(route, *args, **kwargs): 18 | return route_function(mask.format(prefix, route), *args, **kwargs) 19 | return newroute 20 | 21 | app = Flask(__name__) 22 | app.route = prefix_route(app.route, url_root) 23 | translation_server = TranslationServer() 24 | translation_server.start(config_file) 25 | 26 | @app.route('/models', methods=['GET']) 27 | def get_models(): 28 | out = translation_server.list_models() 29 | return jsonify(out) 30 | 31 | @app.route('/clone_model/', methods=['POST']) 32 | def clone_model(model_id): 33 | out = {} 34 | data = request.get_json(force=True) 35 | timeout = -1 36 | if 'timeout' in data: 37 | timeout = data['timeout'] 38 | del data['timeout'] 39 | 40 | opt = data.get('opt', None) 41 | try: 42 | model_id, load_time = translation_server.clone_model( 43 | model_id, opt, timeout) 44 | except ServerModelError as e: 45 | out['status'] = STATUS_ERROR 46 | out['error'] = str(e) 47 | else: 48 | out['status'] = STATUS_OK 49 | out['model_id'] = model_id 50 | out['load_time'] = load_time 51 | 52 | return jsonify(out) 53 | 54 | @app.route('/unload_model/', methods=['GET']) 55 | def unload_model(model_id): 56 | out = {"model_id": model_id} 57 | 58 | try: 59 | translation_server.unload_model(model_id) 60 | out['status'] = STATUS_OK 61 | except Exception as e: 62 | out['status'] = STATUS_ERROR 63 | out['error'] = str(e) 64 | 65 | return jsonify(out) 66 | 67 | @app.route('/translate', methods=['POST']) 68 | def translate(): 69 | inputs = request.get_json(force=True) 70 | out = {} 71 | try: 72 | translation, scores, n_best, times = translation_server.run(inputs) 73 | assert len(translation) == len(inputs) 74 | assert len(scores) == len(inputs) 75 | 76 | out = [[{"src": inputs[i]['src'], "tgt": translation[i], 77 | "n_best": n_best, 78 | "pred_score": scores[i]} 79 | for i in range(len(translation))]] 80 | except ServerModelError as e: 81 | out['error'] = str(e) 82 | out['status'] = STATUS_ERROR 83 | 84 | return jsonify(out) 85 | 86 | @app.route('/to_cpu/', methods=['GET']) 87 | def to_cpu(model_id): 88 | out = {'model_id': model_id} 89 | translation_server.models[model_id].to_cpu() 90 | 91 | out['status'] = STATUS_OK 92 | return jsonify(out) 93 | 94 | @app.route('/to_gpu/', methods=['GET']) 95 | def to_gpu(model_id): 96 | out = {'model_id': model_id} 97 | translation_server.models[model_id].to_gpu() 98 | 99 | out['status'] = STATUS_OK 100 | return jsonify(out) 101 | 102 | app.run(debug=debug, host=host, port=port, use_reloader=False) 103 | 104 | 105 | if __name__ == '__main__': 106 | parser = argparse.ArgumentParser(description="OpenNMT-py REST Server") 107 | parser.add_argument("--ip", type=str, default="0.0.0.0") 108 | parser.add_argument("--port", type=int, default="5000") 109 | parser.add_argument("--url_root", type=str, default="/translator") 110 | parser.add_argument("--debug", "-d", action="store_true") 111 | parser.add_argument("--config", "-c", type=str, 112 | default="./available_models/conf.json") 113 | args = parser.parse_args() 114 | start(args.config, url_root=args.url_root, host=args.ip, port=args.port, 115 | debug=args.debug) 116 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from setuptools import setup 4 | 5 | setup(name='OpenNMT-py', 6 | description='A python implementation of OpenNMT', 7 | version='0.1', 8 | packages=['onmt', 'onmt.io', 'onmt.translate', 'onmt.modules']) 9 | -------------------------------------------------------------------------------- /test/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sheffieldnlp/AMR2Text-summ/be73a361470a64f5fd13097a7348228e55bb4b8b/test/__init__.py -------------------------------------------------------------------------------- /test/rebuild_test_models.sh: -------------------------------------------------------------------------------- 1 | # # Retrain the models used for CI. 2 | # # Should be done rarely, indicates a major breaking change. 3 | 4 | 5 | python preprocess.py -train_src data/src-train.txt -train_tgt data/tgt-train.txt -valid_src data/src-val.txt -valid_tgt data/tgt-val.txt -save_data data/data -src_vocab_size 1000 -tgt_vocab_size 1000 6 | 7 | python train.py -data data/data -save_model /tmp/tmp -gpuid 0 -rnn_size 100 -word_vec_size 50 -layers 1 -epochs 10 -optim adam -learning_rate 0.001 8 | 9 | mv /tmp/tmp*e10.pt test/test_model.pt 10 | 11 | rm /tmp/tmp*.pt 12 | 13 | python preprocess.py -train_src data/morph/src.train -train_tgt data/morph/tgt.train -valid_src data/morph/src.valid -valid_tgt data/morph/tgt.valid -save_data data/morph/data 14 | 15 | python train.py -data data/morph/data -save_model /tmp/tmp -gpuid 0 -rnn_size 400 -word_vec_size 100 -layers 1 -epochs 8 16 | 17 | mv /tmp/tmp*e8.pt test/test_model2.pt 18 | 19 | rm /tmp/tmp*.pt 20 | -------------------------------------------------------------------------------- /test/test_attention.py: -------------------------------------------------------------------------------- 1 | """ 2 | Here come the tests for attention types and their compatibility 3 | """ 4 | 5 | import unittest 6 | import torch 7 | import onmt 8 | 9 | from torch.autograd import Variable 10 | 11 | 12 | class TestAttention(unittest.TestCase): 13 | 14 | def test_masked_global_attention(self): 15 | source_lengths = torch.IntTensor([7, 3, 5, 2]) 16 | # illegal_weights_mask = torch.ByteTensor([ 17 | # [0, 0, 0, 0, 0, 0, 0], 18 | # [0, 0, 0, 1, 1, 1, 1], 19 | # [0, 0, 0, 0, 0, 1, 1], 20 | # [0, 0, 1, 1, 1, 1, 1]]) 21 | 22 | batch_size = source_lengths.size(0) 23 | dim = 20 24 | 25 | memory_bank = Variable(torch.randn(batch_size, 26 | source_lengths.max(), dim)) 27 | hidden = Variable(torch.randn(batch_size, dim)) 28 | 29 | attn = onmt.modules.GlobalAttention(dim) 30 | 31 | _, alignments = attn(hidden, memory_bank, 32 | memory_lengths=source_lengths) 33 | # TODO: fix for pytorch 0.3 34 | # illegal_weights = alignments.masked_select(illegal_weights_mask) 35 | 36 | # self.assertEqual(0.0, illegal_weights.data.sum()) 37 | -------------------------------------------------------------------------------- /test/test_model.pt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sheffieldnlp/AMR2Text-summ/be73a361470a64f5fd13097a7348228e55bb4b8b/test/test_model.pt -------------------------------------------------------------------------------- /test/test_model2.pt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sheffieldnlp/AMR2Text-summ/be73a361470a64f5fd13097a7348228e55bb4b8b/test/test_model2.pt -------------------------------------------------------------------------------- /test/test_preprocess.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import copy 3 | import unittest 4 | import glob 5 | import os 6 | import codecs 7 | from collections import Counter 8 | 9 | import torchtext 10 | 11 | import onmt 12 | import onmt.io 13 | import onmt.opts 14 | import preprocess 15 | 16 | 17 | parser = argparse.ArgumentParser(description='preprocess.py') 18 | onmt.opts.preprocess_opts(parser) 19 | 20 | 21 | SAVE_DATA_PREFIX = 'data/test_preprocess' 22 | 23 | default_opts = [ 24 | '-data_type', 'text', 25 | '-train_src', 'data/src-train.txt', 26 | '-train_tgt', 'data/tgt-train.txt', 27 | '-valid_src', 'data/src-val.txt', 28 | '-valid_tgt', 'data/tgt-val.txt', 29 | '-save_data', SAVE_DATA_PREFIX 30 | ] 31 | 32 | opt = parser.parse_known_args(default_opts)[0] 33 | 34 | 35 | class TestData(unittest.TestCase): 36 | def __init__(self, *args, **kwargs): 37 | super(TestData, self).__init__(*args, **kwargs) 38 | self.opt = opt 39 | 40 | def dataset_build(self, opt): 41 | fields = onmt.io.get_fields("text", 0, 0) 42 | 43 | if hasattr(opt, 'src_vocab') and len(opt.src_vocab) > 0: 44 | with codecs.open(opt.src_vocab, 'w', 'utf-8') as f: 45 | f.write('a\nb\nc\nd\ne\nf\n') 46 | if hasattr(opt, 'tgt_vocab') and len(opt.tgt_vocab) > 0: 47 | with codecs.open(opt.tgt_vocab, 'w', 'utf-8') as f: 48 | f.write('a\nb\nc\nd\ne\nf\n') 49 | 50 | train_data_files = preprocess.build_save_dataset('train', fields, opt) 51 | 52 | preprocess.build_save_vocab(train_data_files, fields, opt) 53 | 54 | preprocess.build_save_dataset('valid', fields, opt) 55 | 56 | # Remove the generated *pt files. 57 | for pt in glob.glob(SAVE_DATA_PREFIX + '*.pt'): 58 | os.remove(pt) 59 | if hasattr(opt, 'src_vocab') and os.path.exists(opt.src_vocab): 60 | os.remove(opt.src_vocab) 61 | if hasattr(opt, 'tgt_vocab') and os.path.exists(opt.tgt_vocab): 62 | os.remove(opt.tgt_vocab) 63 | 64 | def test_merge_vocab(self): 65 | va = torchtext.vocab.Vocab(Counter('abbccc')) 66 | vb = torchtext.vocab.Vocab(Counter('eeabbcccf')) 67 | 68 | merged = onmt.io.merge_vocabs([va, vb], 2) 69 | 70 | self.assertEqual(Counter({'c': 6, 'b': 4, 'a': 2, 'e': 2, 'f': 1}), 71 | merged.freqs) 72 | # 4 specicials + 2 words (since we pass 2 to merge_vocabs) 73 | self.assertEqual(6, len(merged.itos)) 74 | self.assertTrue('b' in merged.itos) 75 | 76 | 77 | def _add_test(param_setting, methodname): 78 | """ 79 | Adds a Test to TestData according to settings 80 | 81 | Args: 82 | param_setting: list of tuples of (param, setting) 83 | methodname: name of the method that gets called 84 | """ 85 | 86 | def test_method(self): 87 | if param_setting: 88 | opt = copy.deepcopy(self.opt) 89 | for param, setting in param_setting: 90 | setattr(opt, param, setting) 91 | else: 92 | opt = self.opt 93 | getattr(self, methodname)(opt) 94 | if param_setting: 95 | name = 'test_' + methodname + "_" + "_".join( 96 | str(param_setting).split()) 97 | else: 98 | name = 'test_' + methodname + '_standard' 99 | setattr(TestData, name, test_method) 100 | test_method.__name__ = name 101 | 102 | 103 | test_databuild = [[], 104 | [('src_vocab_size', 1), 105 | ('tgt_vocab_size', 1)], 106 | [('src_vocab_size', 10000), 107 | ('tgt_vocab_size', 10000)], 108 | [('src_seq_length', 1)], 109 | [('src_seq_length', 5000)], 110 | [('src_seq_length_trunc', 1)], 111 | [('src_seq_length_trunc', 5000)], 112 | [('tgt_seq_length', 1)], 113 | [('tgt_seq_length', 5000)], 114 | [('tgt_seq_length_trunc', 1)], 115 | [('tgt_seq_length_trunc', 5000)], 116 | [('shuffle', 0)], 117 | [('lower', True)], 118 | [('dynamic_dict', True)], 119 | [('share_vocab', True)], 120 | [('dynamic_dict', True), 121 | ('share_vocab', True)], 122 | [('dynamic_dict', True), 123 | ('max_shard_size', 500000)], 124 | [('src_vocab', '/tmp/src_vocab.txt'), 125 | ('tgt_vocab', '/tmp/tgt_vocab.txt')], 126 | ] 127 | 128 | for p in test_databuild: 129 | _add_test(p, 'dataset_build') 130 | 131 | # Test image preprocessing 132 | for p in copy.deepcopy(test_databuild): 133 | p.append(('data_type', 'img')) 134 | p.append(('src_dir', '/tmp/im2text/images')) 135 | p.append(('train_src', '/tmp/im2text/src-train-head.txt')) 136 | p.append(('train_tgt', '/tmp/im2text/tgt-train-head.txt')) 137 | p.append(('valid_src', '/tmp/im2text/src-val-head.txt')) 138 | p.append(('valid_tgt', '/tmp/im2text/tgt-val-head.txt')) 139 | _add_test(p, 'dataset_build') 140 | 141 | # Test audio preprocessing 142 | for p in copy.deepcopy(test_databuild): 143 | p.append(('data_type', 'audio')) 144 | p.append(('src_dir', '/tmp/speech/an4_dataset')) 145 | p.append(('train_src', '/tmp/speech/src-train-head.txt')) 146 | p.append(('train_tgt', '/tmp/speech/tgt-train-head.txt')) 147 | p.append(('valid_src', '/tmp/speech/src-val-head.txt')) 148 | p.append(('valid_tgt', '/tmp/speech/tgt-val-head.txt')) 149 | p.append(('sample_rate', 16000)) 150 | p.append(('window_size', 0.04)) 151 | p.append(('window_stride', 0.02)) 152 | p.append(('window', 'hamming')) 153 | _add_test(p, 'dataset_build') 154 | -------------------------------------------------------------------------------- /test/test_simple.py: -------------------------------------------------------------------------------- 1 | import onmt 2 | 3 | 4 | def test_load(): 5 | onmt 6 | pass 7 | -------------------------------------------------------------------------------- /tools/README.md: -------------------------------------------------------------------------------- 1 | This directly contains scripts and tools adopted from other open source projects such as Apache Joshua and Moses Decoder. 2 | 3 | TODO: credit the authors and resolve license issues (if any) 4 | -------------------------------------------------------------------------------- /tools/average_models.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import argparse 3 | import torch 4 | 5 | 6 | def average_models(model_files): 7 | vocab = None 8 | opt = None 9 | epoch = None 10 | avg_model = None 11 | avg_generator = None 12 | 13 | for i, model_file in enumerate(model_files): 14 | m = torch.load(model_file) 15 | model_weights = m['model'] 16 | generator_weights = m['generator'] 17 | 18 | if i == 0: 19 | vocab, opt, epoch = m['vocab'], m['opt'], m['epoch'] 20 | avg_model = model_weights 21 | avg_generator = generator_weights 22 | else: 23 | for (k, v) in avg_model.items(): 24 | avg_model[k].mul_(i).add_(model_weights[k]).div_(i + 1) 25 | 26 | for (k, v) in avg_generator.items(): 27 | avg_generator[k].mul_(i).add_(generator_weights[k]).div_(i + 1) 28 | 29 | final = {"vocab": vocab, "opt": opt, "epoch": epoch, "optim": None, 30 | "generator": avg_generator, "model": avg_model} 31 | return final 32 | 33 | 34 | def main(): 35 | parser = argparse.ArgumentParser(description="") 36 | parser.add_argument("-models", "-m", nargs="+", required=True, 37 | help="List of models") 38 | parser.add_argument("-output", "-o", required=True, 39 | help="Output file") 40 | opt = parser.parse_args() 41 | 42 | final = average_models(opt.models) 43 | torch.save(final, opt.output) 44 | 45 | 46 | if __name__ == "__main__": 47 | main() 48 | -------------------------------------------------------------------------------- /tools/bpe_pipeline.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # Author : Thamme Gowda 3 | # Created : Nov 06, 2017 4 | 5 | ONMT="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )" 6 | 7 | #======= EXPERIMENT SETUP ====== 8 | # Activate python environment if needed 9 | source ~/.bashrc 10 | # source activate py3 11 | 12 | # update these variables 13 | NAME="run1" 14 | OUT="onmt-runs/$NAME" 15 | 16 | DATA="$ONMT/onmt-runs/data" 17 | TRAIN_SRC=$DATA/*train.src 18 | TRAIN_TGT=$DATA/*train.tgt 19 | VALID_SRC=$DATA/*dev.src 20 | VALID_TGT=$DATA/*dev.tgt 21 | TEST_SRC=$DATA/*test.src 22 | TEST_TGT=$DATA/*test.tgt 23 | 24 | BPE="" # default 25 | BPE="src" # src, tgt, src+tgt 26 | 27 | # applicable only when BPE="src" or "src+tgt" 28 | BPE_SRC_OPS=10000 29 | 30 | # applicable only when BPE="tgt" or "src+tgt" 31 | BPE_TGT_OPS=10000 32 | 33 | GPUARG="" # default 34 | GPUARG="0" 35 | 36 | 37 | #====== EXPERIMENT BEGIN ====== 38 | 39 | # Check if input exists 40 | for f in $TRAIN_SRC $TRAIN_TGT $VALID_SRC $VALID_TGT $TEST_SRC $TEST_TGT; do 41 | if [[ ! -f "$f" ]]; then 42 | echo "Input File $f doesnt exist. Please fix the paths" 43 | exit 1 44 | fi 45 | done 46 | 47 | function lines_check { 48 | l1=`wc -l $1` 49 | l2=`wc -l $2` 50 | if [[ $l1 != $l2 ]]; then 51 | echo "ERROR: Record counts doesnt match between: $1 and $2" 52 | exit 2 53 | fi 54 | } 55 | lines_check $TRAIN_SRC $TRAIN_TGT 56 | lines_check $VALID_SRC $VALID_TGT 57 | lines_check $TEST_SRC $TEST_TGT 58 | 59 | 60 | echo "Output dir = $OUT" 61 | [ -d $OUT ] || mkdir -p $OUT 62 | [ -d $OUT/data ] || mkdir -p $OUT/data 63 | [ -d $OUT/models ] || mkdir $OUT/models 64 | [ -d $OUT/test ] || mkdir -p $OUT/test 65 | 66 | 67 | echo "Step 1a: Preprocess inputs" 68 | if [[ "$BPE" == *"src"* ]]; then 69 | echo "BPE on source" 70 | # Here we could use more monolingual data 71 | $ONMT/tools/learn_bpe.py -s $BPE_SRC_OPS < $TRAIN_SRC > $OUT/data/bpe-codes.src 72 | 73 | $ONMT/tools/apply_bpe.py -c $OUT/data/bpe-codes.src < $TRAIN_SRC > $OUT/data/train.src 74 | $ONMT/tools/apply_bpe.py -c $OUT/data/bpe-codes.src < $VALID_SRC > $OUT/data/valid.src 75 | $ONMT/tools/apply_bpe.py -c $OUT/data/bpe-codes.src < $TEST_SRC > $OUT/data/test.src 76 | else 77 | ln -sf $TRAIN_SRC $OUT/data/train.src 78 | ln -sf $VALID_SRC $OUT/data/valid.src 79 | ln -sf $TEST_SRC $OUT/data/test.src 80 | fi 81 | 82 | 83 | if [[ "$BPE" == *"tgt"* ]]; then 84 | echo "BPE on target" 85 | # Here we could use more monolingual data 86 | $ONMT/tools/learn_bpe.py -s $BPE_SRC_OPS < $TRAIN_TGT > $OUT/data/bpe-codes.tgt 87 | 88 | $ONMT/tools/apply_bpe.py -c $OUT/data/bpe-codes.tgt < $TRAIN_TGT > $OUT/data/train.tgt 89 | $ONMT/tools/apply_bpe.py -c $OUT/data/bpe-codes.tgt < $VALID_TGT > $OUT/data/valid.tgt 90 | #$ONMT/tools/apply_bpe.py -c $OUT/data/bpe-codes.tgt < $TEST_TGT > $OUT/data/test.tgt 91 | # We dont touch the test References, No BPE on them! 92 | ln -sf $TEST_TGT $OUT/data/test.tgt 93 | else 94 | ln -sf $TRAIN_TGT $OUT/data/train.tgt 95 | ln -sf $VALID_TGT $OUT/data/valid.tgt 96 | ln -sf $TEST_TGT $OUT/data/test.tgt 97 | fi 98 | 99 | 100 | #: < maxv) {maxv=score; max=$0}} END{ print max}'` 124 | echo "Chosen Model = $model" 125 | if [[ -z "$model" ]]; then 126 | echo "Model not found. Looked in $OUT/models/" 127 | exit 1 128 | fi 129 | 130 | GPU_OPTS="" 131 | if [ ! -z $GPUARG ]; then 132 | GPU_OPTS="-gpu $GPUARG" 133 | fi 134 | 135 | echo "Step 3a: Translate Test" 136 | python $ONMT/translate.py -model $model \ 137 | -src $OUT/data/test.src \ 138 | -output $OUT/test/test.out \ 139 | -replace_unk -verbose $GPU_OPTS > $OUT/test/test.log 140 | 141 | echo "Step 3b: Translate Dev" 142 | python $ONMT/translate.py -model $model \ 143 | -src $OUT/data/valid.src \ 144 | -output $OUT/test/valid.out \ 145 | -replace_unk -verbose $GPU_OPTS > $OUT/test/valid.log 146 | 147 | if [[ "$BPE" == *"tgt"* ]]; then 148 | echo "BPE decoding/detokenising target to match with references" 149 | mv $OUT/test/test.out{,.bpe} 150 | mv $OUT/test/valid.out{,.bpe} 151 | cat $OUT/test/valid.out.bpe | sed -E 's/(@@ )|(@@ ?$)//g' > $OUT/test/valid.out 152 | cat $OUT/test/test.out.bpe | sed -E 's/(@@ )|(@@ ?$)//g' > $OUT/test/test.out 153 | fi 154 | 155 | echo "Step 4a: Evaluate Test" 156 | $ONMT/tools/multi-bleu-detok.perl $OUT/data/test.tgt < $OUT/test/test.out > $OUT/test/test.tc.bleu 157 | $ONMT/tools/multi-bleu-detok.perl -lc $OUT/data/test.tgt < $OUT/test/test.out > $OUT/test/test.lc.bleu 158 | 159 | echo "Step 4b: Evaluate Dev" 160 | $ONMT/tools/multi-bleu-detok.perl $OUT/data/valid.tgt < $OUT/test/valid.out > $OUT/test/valid.tc.bleu 161 | $ONMT/tools/multi-bleu-detok.perl -lc $OUT/data/valid.tgt < $OUT/test/valid.out > $OUT/test/valid.lc.bleu 162 | 163 | #===== EXPERIMENT END ====== 164 | -------------------------------------------------------------------------------- /tools/embeddings_to_torch.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from __future__ import print_function 4 | from __future__ import division 5 | import six 6 | import sys 7 | import numpy as np 8 | import argparse 9 | import torch 10 | 11 | 12 | def get_vocabs(dict_file): 13 | vocabs = torch.load(dict_file) 14 | 15 | enc_vocab, dec_vocab = None, None 16 | 17 | # the vocab object is a list of tuple (name, torchtext.Vocab) 18 | # we iterate over this list and associate vocabularies based on the name 19 | for vocab in vocabs: 20 | if vocab[0] == 'src': 21 | enc_vocab = vocab[1] 22 | if vocab[0] == 'tgt': 23 | dec_vocab = vocab[1] 24 | assert type(None) not in [type(enc_vocab), type(dec_vocab)] 25 | 26 | print("From: %s" % dict_file) 27 | print("\t* source vocab: %d words" % len(enc_vocab)) 28 | print("\t* target vocab: %d words" % len(dec_vocab)) 29 | 30 | return enc_vocab, dec_vocab 31 | 32 | 33 | def get_embeddings(file_enc, opt, flag): 34 | embs = dict() 35 | if flag == 'enc': 36 | for (i, l) in enumerate(open(file_enc, 'rb')): 37 | if i < opt.skip_lines: 38 | continue 39 | if not l: 40 | break 41 | if len(l) == 0: 42 | continue 43 | 44 | l_split = l.decode('utf8').strip().split(' ') 45 | if len(l_split) == 2: 46 | continue 47 | embs[l_split[0]] = [float(em) for em in l_split[1:]] 48 | print("Got {} encryption embeddings from {}".format(len(embs), 49 | file_enc)) 50 | else: 51 | 52 | for (i, l) in enumerate(open(file_enc, 'rb')): 53 | if not l: 54 | break 55 | if len(l) == 0: 56 | continue 57 | 58 | l_split = l.decode('utf8').strip().split(' ') 59 | if len(l_split) == 2: 60 | continue 61 | embs[l_split[0]] = [float(em) for em in l_split[1:]] 62 | print("Got {} decryption embeddings from {}".format(len(embs), 63 | file_enc)) 64 | 65 | return embs 66 | 67 | 68 | def match_embeddings(vocab, emb, opt): 69 | dim = len(six.next(six.itervalues(emb))) 70 | filtered_embeddings = np.zeros((len(vocab), dim)) 71 | count = {"match": 0, "miss": 0} 72 | for w, w_id in vocab.stoi.items(): 73 | if w in emb: 74 | filtered_embeddings[w_id] = emb[w] 75 | count['match'] += 1 76 | else: 77 | if opt.verbose: 78 | print(u"not found:\t{}".format(w), file=sys.stderr) 79 | count['miss'] += 1 80 | 81 | return torch.Tensor(filtered_embeddings), count 82 | 83 | 84 | TYPES = ["GloVe", "word2vec"] 85 | 86 | 87 | def main(): 88 | 89 | parser = argparse.ArgumentParser(description='embeddings_to_torch.py') 90 | parser.add_argument('-emb_file_enc', required=True, 91 | help="source Embeddings from this file") 92 | parser.add_argument('-emb_file_dec', required=True, 93 | help="target Embeddings from this file") 94 | parser.add_argument('-output_file', required=True, 95 | help="Output file for the prepared data") 96 | parser.add_argument('-dict_file', required=True, 97 | help="Dictionary file") 98 | parser.add_argument('-verbose', action="store_true", default=False) 99 | parser.add_argument('-skip_lines', type=int, default=0, 100 | help="Skip first lines of the embedding file") 101 | parser.add_argument('-type', choices=TYPES, default="GloVe") 102 | opt = parser.parse_args() 103 | 104 | enc_vocab, dec_vocab = get_vocabs(opt.dict_file) 105 | if opt.type == "word2vec": 106 | opt.skip_lines = 1 107 | 108 | embeddings_enc = get_embeddings(opt.emb_file_enc, opt, flag='enc') 109 | embeddings_dec = get_embeddings(opt.emb_file_dec, opt, flag='dec') 110 | 111 | filtered_enc_embeddings, enc_count = match_embeddings(enc_vocab, 112 | embeddings_enc, 113 | opt) 114 | filtered_dec_embeddings, dec_count = match_embeddings(dec_vocab, 115 | embeddings_dec, 116 | opt) 117 | print("\nMatching: ") 118 | match_percent = [_['match'] / (_['match'] + _['miss']) * 100 119 | for _ in [enc_count, dec_count]] 120 | print("\t* enc: %d match, %d missing, (%.2f%%)" % (enc_count['match'], 121 | enc_count['miss'], 122 | match_percent[0])) 123 | print("\t* dec: %d match, %d missing, (%.2f%%)" % (dec_count['match'], 124 | dec_count['miss'], 125 | match_percent[1])) 126 | 127 | print("\nFiltered embeddings:") 128 | print("\t* enc: ", filtered_enc_embeddings.size()) 129 | print("\t* dec: ", filtered_dec_embeddings.size()) 130 | 131 | enc_output_file = opt.output_file + ".enc.pt" 132 | dec_output_file = opt.output_file + ".dec.pt" 133 | print("\nSaving embedding as:\n\t* enc: %s\n\t* dec: %s" 134 | % (enc_output_file, dec_output_file)) 135 | torch.save(filtered_enc_embeddings, enc_output_file) 136 | torch.save(filtered_dec_embeddings, dec_output_file) 137 | print("\nDone.") 138 | 139 | 140 | if __name__ == "__main__": 141 | main() 142 | -------------------------------------------------------------------------------- /tools/extract_embeddings.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | import torch 3 | import argparse 4 | import onmt 5 | import onmt.ModelConstructor 6 | import onmt.io 7 | import onmt.opts 8 | from onmt.Utils import use_gpu 9 | 10 | parser = argparse.ArgumentParser(description='translate.py') 11 | 12 | parser.add_argument('-model', required=True, 13 | help='Path to model .pt file') 14 | parser.add_argument('-output_dir', default='.', 15 | help="""Path to output the embeddings""") 16 | parser.add_argument('-gpu', type=int, default=-1, 17 | help="Device to run on") 18 | 19 | 20 | def write_embeddings(filename, dict, embeddings): 21 | with open(filename, 'wb') as file: 22 | for i in range(min(len(embeddings), len(dict.itos))): 23 | str = dict.itos[i].encode("utf-8") 24 | for j in range(len(embeddings[0])): 25 | str = str + (" %5f" % (embeddings[i][j])).encode("utf-8") 26 | file.write(str + b"\n") 27 | 28 | 29 | def main(): 30 | dummy_parser = argparse.ArgumentParser(description='train.py') 31 | onmt.opts.model_opts(dummy_parser) 32 | dummy_opt = dummy_parser.parse_known_args([])[0] 33 | opt = parser.parse_args() 34 | opt.cuda = opt.gpu > -1 35 | if opt.cuda: 36 | torch.cuda.set_device(opt.gpu) 37 | 38 | # Add in default model arguments, possibly added since training. 39 | checkpoint = torch.load(opt.model, 40 | map_location=lambda storage, loc: storage) 41 | model_opt = checkpoint['opt'] 42 | src_dict = checkpoint['vocab'][1][1] 43 | tgt_dict = checkpoint['vocab'][0][1] 44 | 45 | fields = onmt.io.load_fields_from_vocab(checkpoint['vocab']) 46 | 47 | model_opt = checkpoint['opt'] 48 | for arg in dummy_opt.__dict__: 49 | if arg not in model_opt: 50 | model_opt.__dict__[arg] = dummy_opt.__dict__[arg] 51 | 52 | model = onmt.ModelConstructor.make_base_model( 53 | model_opt, fields, use_gpu(opt), checkpoint) 54 | encoder = model.encoder 55 | decoder = model.decoder 56 | 57 | encoder_embeddings = encoder.embeddings.word_lut.weight.data.tolist() 58 | decoder_embeddings = decoder.embeddings.word_lut.weight.data.tolist() 59 | 60 | print("Writing source embeddings") 61 | write_embeddings(opt.output_dir + "/src_embeddings.txt", src_dict, 62 | encoder_embeddings) 63 | 64 | print("Writing target embeddings") 65 | write_embeddings(opt.output_dir + "/tgt_embeddings.txt", tgt_dict, 66 | decoder_embeddings) 67 | 68 | print('... done.') 69 | print('Converting model...') 70 | 71 | 72 | if __name__ == "__main__": 73 | main() 74 | -------------------------------------------------------------------------------- /tools/multi-bleu-detok.perl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env perl 2 | # 3 | # This file is part of moses. Its use is licensed under the GNU Lesser General 4 | # Public License version 2.1 or, at your option, any later version. 5 | 6 | # This file uses the internal tokenization of mteval-v13a.pl, 7 | # giving the exact same (case-sensitive) results on untokenized text. 8 | # Using this script with detokenized output and untokenized references is 9 | # preferrable over multi-bleu.perl, since scores aren't affected by tokenization differences. 10 | # 11 | # like multi-bleu.perl , it supports plain text input and multiple references. 12 | 13 | # This file is retrieved from Moses Decoder :: https://github.com/moses-smt/mosesdecoder 14 | # $Id$ 15 | use warnings; 16 | use strict; 17 | 18 | my $lowercase = 0; 19 | if ($ARGV[0] eq "-lc") { 20 | $lowercase = 1; 21 | shift; 22 | } 23 | 24 | my $stem = $ARGV[0]; 25 | if (!defined $stem) { 26 | print STDERR "usage: multi-bleu-detok.pl [-lc] reference < hypothesis\n"; 27 | print STDERR "Reads the references from reference or reference0, reference1, ...\n"; 28 | exit(1); 29 | } 30 | 31 | $stem .= ".ref" if !-e $stem && !-e $stem."0" && -e $stem.".ref0"; 32 | 33 | my @REF; 34 | my $ref=0; 35 | while(-e "$stem$ref") { 36 | &add_to_ref("$stem$ref",\@REF); 37 | $ref++; 38 | } 39 | &add_to_ref($stem,\@REF) if -e $stem; 40 | die("ERROR: could not find reference file $stem") unless scalar @REF; 41 | 42 | # add additional references explicitly specified on the command line 43 | shift; 44 | foreach my $stem (@ARGV) { 45 | &add_to_ref($stem,\@REF) if -e $stem; 46 | } 47 | 48 | 49 | 50 | sub add_to_ref { 51 | my ($file,$REF) = @_; 52 | my $s=0; 53 | if ($file =~ /.gz$/) { 54 | open(REF,"gzip -dc $file|") or die "Can't read $file"; 55 | } else { 56 | open(REF,$file) or die "Can't read $file"; 57 | } 58 | while() { 59 | chop; 60 | $_ = tokenization($_); 61 | push @{$$REF[$s++]}, $_; 62 | } 63 | close(REF); 64 | } 65 | 66 | my(@CORRECT,@TOTAL,$length_translation,$length_reference); 67 | my $s=0; 68 | while() { 69 | chop; 70 | $_ = lc if $lowercase; 71 | $_ = tokenization($_); 72 | my @WORD = split; 73 | my %REF_NGRAM = (); 74 | my $length_translation_this_sentence = scalar(@WORD); 75 | my ($closest_diff,$closest_length) = (9999,9999); 76 | foreach my $reference (@{$REF[$s]}) { 77 | # print "$s $_ <=> $reference\n"; 78 | $reference = lc($reference) if $lowercase; 79 | my @WORD = split(' ',$reference); 80 | my $length = scalar(@WORD); 81 | my $diff = abs($length_translation_this_sentence-$length); 82 | if ($diff < $closest_diff) { 83 | $closest_diff = $diff; 84 | $closest_length = $length; 85 | # print STDERR "$s: closest diff ".abs($length_translation_this_sentence-$length)." = abs($length_translation_this_sentence-$length), setting len: $closest_length\n"; 86 | } elsif ($diff == $closest_diff) { 87 | $closest_length = $length if $length < $closest_length; 88 | # from two references with the same closeness to me 89 | # take the *shorter* into account, not the "first" one. 90 | } 91 | for(my $n=1;$n<=4;$n++) { 92 | my %REF_NGRAM_N = (); 93 | for(my $start=0;$start<=$#WORD-($n-1);$start++) { 94 | my $ngram = "$n"; 95 | for(my $w=0;$w<$n;$w++) { 96 | $ngram .= " ".$WORD[$start+$w]; 97 | } 98 | $REF_NGRAM_N{$ngram}++; 99 | } 100 | foreach my $ngram (keys %REF_NGRAM_N) { 101 | if (!defined($REF_NGRAM{$ngram}) || 102 | $REF_NGRAM{$ngram} < $REF_NGRAM_N{$ngram}) { 103 | $REF_NGRAM{$ngram} = $REF_NGRAM_N{$ngram}; 104 | # print "$i: REF_NGRAM{$ngram} = $REF_NGRAM{$ngram}
\n"; 105 | } 106 | } 107 | } 108 | } 109 | $length_translation += $length_translation_this_sentence; 110 | $length_reference += $closest_length; 111 | for(my $n=1;$n<=4;$n++) { 112 | my %T_NGRAM = (); 113 | for(my $start=0;$start<=$#WORD-($n-1);$start++) { 114 | my $ngram = "$n"; 115 | for(my $w=0;$w<$n;$w++) { 116 | $ngram .= " ".$WORD[$start+$w]; 117 | } 118 | $T_NGRAM{$ngram}++; 119 | } 120 | foreach my $ngram (keys %T_NGRAM) { 121 | $ngram =~ /^(\d+) /; 122 | my $n = $1; 123 | # my $corr = 0; 124 | # print "$i e $ngram $T_NGRAM{$ngram}
\n"; 125 | $TOTAL[$n] += $T_NGRAM{$ngram}; 126 | if (defined($REF_NGRAM{$ngram})) { 127 | if ($REF_NGRAM{$ngram} >= $T_NGRAM{$ngram}) { 128 | $CORRECT[$n] += $T_NGRAM{$ngram}; 129 | # $corr = $T_NGRAM{$ngram}; 130 | # print "$i e correct1 $T_NGRAM{$ngram}
\n"; 131 | } 132 | else { 133 | $CORRECT[$n] += $REF_NGRAM{$ngram}; 134 | # $corr = $REF_NGRAM{$ngram}; 135 | # print "$i e correct2 $REF_NGRAM{$ngram}
\n"; 136 | } 137 | } 138 | # $REF_NGRAM{$ngram} = 0 if !defined $REF_NGRAM{$ngram}; 139 | # print STDERR "$ngram: {$s, $REF_NGRAM{$ngram}, $T_NGRAM{$ngram}, $corr}\n" 140 | } 141 | } 142 | $s++; 143 | } 144 | my $brevity_penalty = 1; 145 | my $bleu = 0; 146 | 147 | my @bleu=(); 148 | 149 | for(my $n=1;$n<=4;$n++) { 150 | if (defined ($TOTAL[$n])){ 151 | $bleu[$n]=($TOTAL[$n])?$CORRECT[$n]/$TOTAL[$n]:0; 152 | # print STDERR "CORRECT[$n]:$CORRECT[$n] TOTAL[$n]:$TOTAL[$n]\n"; 153 | }else{ 154 | $bleu[$n]=0; 155 | } 156 | } 157 | 158 | if ($length_reference==0){ 159 | printf "BLEU = 0, 0/0/0/0 (BP=0, ratio=0, hyp_len=0, ref_len=0)\n"; 160 | exit(1); 161 | } 162 | 163 | if ($length_translation<$length_reference) { 164 | $brevity_penalty = exp(1-$length_reference/$length_translation); 165 | } 166 | $bleu = $brevity_penalty * exp((my_log( $bleu[1] ) + 167 | my_log( $bleu[2] ) + 168 | my_log( $bleu[3] ) + 169 | my_log( $bleu[4] ) ) / 4) ; 170 | printf "BLEU = %.2f, %.1f/%.1f/%.1f/%.1f (BP=%.3f, ratio=%.3f, hyp_len=%d, ref_len=%d)\n", 171 | 100*$bleu, 172 | 100*$bleu[1], 173 | 100*$bleu[2], 174 | 100*$bleu[3], 175 | 100*$bleu[4], 176 | $brevity_penalty, 177 | $length_translation / $length_reference, 178 | $length_translation, 179 | $length_reference; 180 | 181 | sub my_log { 182 | return -9999999999 unless $_[0]; 183 | return log($_[0]); 184 | } 185 | 186 | 187 | 188 | sub tokenization 189 | { 190 | my ($norm_text) = @_; 191 | 192 | # language-independent part: 193 | $norm_text =~ s///g; # strip "skipped" tags 194 | $norm_text =~ s/-\n//g; # strip end-of-line hyphenation and join lines 195 | $norm_text =~ s/\n/ /g; # join lines 196 | $norm_text =~ s/"/"/g; # convert SGML tag for quote to " 197 | $norm_text =~ s/&/&/g; # convert SGML tag for ampersand to & 198 | $norm_text =~ s/</ 199 | $norm_text =~ s/>/>/g; # convert SGML tag for greater-than to < 200 | 201 | # language-dependent part (assuming Western languages): 202 | $norm_text = " $norm_text "; 203 | $norm_text =~ s/([\{-\~\[-\` -\&\(-\+\:-\@\/])/ $1 /g; # tokenize punctuation 204 | $norm_text =~ s/([^0-9])([\.,])/$1 $2 /g; # tokenize period and comma unless preceded by a digit 205 | $norm_text =~ s/([\.,])([^0-9])/ $1 $2/g; # tokenize period and comma unless followed by a digit 206 | $norm_text =~ s/([0-9])(-)/$1 $2 /g; # tokenize dash when preceded by a digit 207 | $norm_text =~ s/\s+/ /g; # one space only between words 208 | $norm_text =~ s/^\s+//; # no leading space 209 | $norm_text =~ s/\s+$//; # no trailing space 210 | 211 | return $norm_text; 212 | } 213 | -------------------------------------------------------------------------------- /tools/multi-bleu.perl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env perl 2 | # 3 | # This file is part of moses. Its use is licensed under the GNU Lesser General 4 | # Public License version 2.1 or, at your option, any later version. 5 | 6 | # $Id$ 7 | use warnings; 8 | use strict; 9 | 10 | my $lowercase = 0; 11 | if ($ARGV[0] eq "-lc") { 12 | $lowercase = 1; 13 | shift; 14 | } 15 | 16 | my $stem = $ARGV[0]; 17 | if (!defined $stem) { 18 | print STDERR "usage: multi-bleu.pl [-lc] reference < hypothesis\n"; 19 | print STDERR "Reads the references from reference or reference0, reference1, ...\n"; 20 | exit(1); 21 | } 22 | 23 | $stem .= ".ref" if !-e $stem && !-e $stem."0" && -e $stem.".ref0"; 24 | 25 | my @REF; 26 | my $ref=0; 27 | while(-e "$stem$ref") { 28 | &add_to_ref("$stem$ref",\@REF); 29 | $ref++; 30 | } 31 | &add_to_ref($stem,\@REF) if -e $stem; 32 | die("ERROR: could not find reference file $stem") unless scalar @REF; 33 | 34 | # add additional references explicitly specified on the command line 35 | shift; 36 | foreach my $stem (@ARGV) { 37 | &add_to_ref($stem,\@REF) if -e $stem; 38 | } 39 | 40 | 41 | 42 | sub add_to_ref { 43 | my ($file,$REF) = @_; 44 | my $s=0; 45 | if ($file =~ /.gz$/) { 46 | open(REF,"gzip -dc $file|") or die "Can't read $file"; 47 | } else { 48 | open(REF,$file) or die "Can't read $file"; 49 | } 50 | while() { 51 | chop; 52 | push @{$$REF[$s++]}, $_; 53 | } 54 | close(REF); 55 | } 56 | 57 | my(@CORRECT,@TOTAL,$length_translation,$length_reference); 58 | my $s=0; 59 | while() { 60 | chop; 61 | $_ = lc if $lowercase; 62 | my @WORD = split; 63 | my %REF_NGRAM = (); 64 | my $length_translation_this_sentence = scalar(@WORD); 65 | my ($closest_diff,$closest_length) = (9999,9999); 66 | foreach my $reference (@{$REF[$s]}) { 67 | # print "$s $_ <=> $reference\n"; 68 | $reference = lc($reference) if $lowercase; 69 | my @WORD = split(' ',$reference); 70 | my $length = scalar(@WORD); 71 | my $diff = abs($length_translation_this_sentence-$length); 72 | if ($diff < $closest_diff) { 73 | $closest_diff = $diff; 74 | $closest_length = $length; 75 | # print STDERR "$s: closest diff ".abs($length_translation_this_sentence-$length)." = abs($length_translation_this_sentence-$length), setting len: $closest_length\n"; 76 | } elsif ($diff == $closest_diff) { 77 | $closest_length = $length if $length < $closest_length; 78 | # from two references with the same closeness to me 79 | # take the *shorter* into account, not the "first" one. 80 | } 81 | for(my $n=1;$n<=4;$n++) { 82 | my %REF_NGRAM_N = (); 83 | for(my $start=0;$start<=$#WORD-($n-1);$start++) { 84 | my $ngram = "$n"; 85 | for(my $w=0;$w<$n;$w++) { 86 | $ngram .= " ".$WORD[$start+$w]; 87 | } 88 | $REF_NGRAM_N{$ngram}++; 89 | } 90 | foreach my $ngram (keys %REF_NGRAM_N) { 91 | if (!defined($REF_NGRAM{$ngram}) || 92 | $REF_NGRAM{$ngram} < $REF_NGRAM_N{$ngram}) { 93 | $REF_NGRAM{$ngram} = $REF_NGRAM_N{$ngram}; 94 | # print "$i: REF_NGRAM{$ngram} = $REF_NGRAM{$ngram}
\n"; 95 | } 96 | } 97 | } 98 | } 99 | $length_translation += $length_translation_this_sentence; 100 | $length_reference += $closest_length; 101 | for(my $n=1;$n<=4;$n++) { 102 | my %T_NGRAM = (); 103 | for(my $start=0;$start<=$#WORD-($n-1);$start++) { 104 | my $ngram = "$n"; 105 | for(my $w=0;$w<$n;$w++) { 106 | $ngram .= " ".$WORD[$start+$w]; 107 | } 108 | $T_NGRAM{$ngram}++; 109 | } 110 | foreach my $ngram (keys %T_NGRAM) { 111 | $ngram =~ /^(\d+) /; 112 | my $n = $1; 113 | # my $corr = 0; 114 | # print "$i e $ngram $T_NGRAM{$ngram}
\n"; 115 | $TOTAL[$n] += $T_NGRAM{$ngram}; 116 | if (defined($REF_NGRAM{$ngram})) { 117 | if ($REF_NGRAM{$ngram} >= $T_NGRAM{$ngram}) { 118 | $CORRECT[$n] += $T_NGRAM{$ngram}; 119 | # $corr = $T_NGRAM{$ngram}; 120 | # print "$i e correct1 $T_NGRAM{$ngram}
\n"; 121 | } 122 | else { 123 | $CORRECT[$n] += $REF_NGRAM{$ngram}; 124 | # $corr = $REF_NGRAM{$ngram}; 125 | # print "$i e correct2 $REF_NGRAM{$ngram}
\n"; 126 | } 127 | } 128 | # $REF_NGRAM{$ngram} = 0 if !defined $REF_NGRAM{$ngram}; 129 | # print STDERR "$ngram: {$s, $REF_NGRAM{$ngram}, $T_NGRAM{$ngram}, $corr}\n" 130 | } 131 | } 132 | $s++; 133 | } 134 | my $brevity_penalty = 1; 135 | my $bleu = 0; 136 | 137 | my @bleu=(); 138 | 139 | for(my $n=1;$n<=4;$n++) { 140 | if (defined ($TOTAL[$n])){ 141 | $bleu[$n]=($TOTAL[$n])?$CORRECT[$n]/$TOTAL[$n]:0; 142 | # print STDERR "CORRECT[$n]:$CORRECT[$n] TOTAL[$n]:$TOTAL[$n]\n"; 143 | }else{ 144 | $bleu[$n]=0; 145 | } 146 | } 147 | 148 | if ($length_reference==0){ 149 | printf "BLEU = 0, 0/0/0/0 (BP=0, ratio=0, hyp_len=0, ref_len=0)\n"; 150 | exit(1); 151 | } 152 | 153 | if ($length_translation<$length_reference) { 154 | $brevity_penalty = exp(1-$length_reference/$length_translation); 155 | } 156 | $bleu = $brevity_penalty * exp((my_log( $bleu[1] ) + 157 | my_log( $bleu[2] ) + 158 | my_log( $bleu[3] ) + 159 | my_log( $bleu[4] ) ) / 4) ; 160 | printf "BLEU = %.2f, %.1f/%.1f/%.1f/%.1f (BP=%.3f, ratio=%.3f, hyp_len=%d, ref_len=%d)\n", 161 | 100*$bleu, 162 | 100*$bleu[1], 163 | 100*$bleu[2], 164 | 100*$bleu[3], 165 | 100*$bleu[4], 166 | $brevity_penalty, 167 | $length_translation / $length_reference, 168 | $length_translation, 169 | $length_reference; 170 | 171 | sub my_log { 172 | return -9999999999 unless $_[0]; 173 | return log($_[0]); 174 | } 175 | -------------------------------------------------------------------------------- /tools/nonbreaking_prefixes/README.txt: -------------------------------------------------------------------------------- 1 | The language suffix can be found here: 2 | 3 | http://www.loc.gov/standards/iso639-2/php/code_list.php 4 | 5 | This code includes data from Daniel Naber's Language Tools (czech abbreviations). 6 | This code includes data from czech wiktionary (also czech abbreviations). 7 | 8 | 9 | -------------------------------------------------------------------------------- /tools/nonbreaking_prefixes/nonbreaking_prefix.ca: -------------------------------------------------------------------------------- 1 | Dr 2 | Dra 3 | pàg 4 | p 5 | c 6 | av 7 | Sr 8 | Sra 9 | adm 10 | esq 11 | Prof 12 | S.A 13 | S.L 14 | p.e 15 | ptes 16 | Sta 17 | St 18 | pl 19 | màx 20 | cast 21 | dir 22 | nre 23 | fra 24 | admdora 25 | Emm 26 | Excma 27 | espf 28 | dc 29 | admdor 30 | tel 31 | angl 32 | aprox 33 | ca 34 | dept 35 | dj 36 | dl 37 | dt 38 | ds 39 | dg 40 | dv 41 | ed 42 | entl 43 | al 44 | i.e 45 | maj 46 | smin 47 | n 48 | núm 49 | pta 50 | A 51 | B 52 | C 53 | D 54 | E 55 | F 56 | G 57 | H 58 | I 59 | J 60 | K 61 | L 62 | M 63 | N 64 | O 65 | P 66 | Q 67 | R 68 | S 69 | T 70 | U 71 | V 72 | W 73 | X 74 | Y 75 | Z 76 | -------------------------------------------------------------------------------- /tools/nonbreaking_prefixes/nonbreaking_prefix.cs: -------------------------------------------------------------------------------- 1 | Bc 2 | BcA 3 | Ing 4 | Ing.arch 5 | MUDr 6 | MVDr 7 | MgA 8 | Mgr 9 | JUDr 10 | PhDr 11 | RNDr 12 | PharmDr 13 | ThLic 14 | ThDr 15 | Ph.D 16 | Th.D 17 | prof 18 | doc 19 | CSc 20 | DrSc 21 | dr. h. c 22 | PaedDr 23 | Dr 24 | PhMr 25 | DiS 26 | abt 27 | ad 28 | a.i 29 | aj 30 | angl 31 | anon 32 | apod 33 | atd 34 | atp 35 | aut 36 | bd 37 | biogr 38 | b.m 39 | b.p 40 | b.r 41 | cca 42 | cit 43 | cizojaz 44 | c.k 45 | col 46 | čes 47 | čín 48 | čj 49 | ed 50 | facs 51 | fasc 52 | fol 53 | fot 54 | franc 55 | h.c 56 | hist 57 | hl 58 | hrsg 59 | ibid 60 | il 61 | ind 62 | inv.č 63 | jap 64 | jhdt 65 | jv 66 | koed 67 | kol 68 | korej 69 | kl 70 | krit 71 | lat 72 | lit 73 | m.a 74 | maď 75 | mj 76 | mp 77 | násl 78 | např 79 | nepubl 80 | něm 81 | no 82 | nr 83 | n.s 84 | okr 85 | odd 86 | odp 87 | obr 88 | opr 89 | orig 90 | phil 91 | pl 92 | pokrač 93 | pol 94 | port 95 | pozn 96 | př.kr 97 | př.n.l 98 | přel 99 | přeprac 100 | příl 101 | pseud 102 | pt 103 | red 104 | repr 105 | resp 106 | revid 107 | rkp 108 | roč 109 | roz 110 | rozš 111 | samost 112 | sect 113 | sest 114 | seš 115 | sign 116 | sl 117 | srv 118 | stol 119 | sv 120 | šk 121 | šk.ro 122 | špan 123 | tab 124 | t.č 125 | tis 126 | tj 127 | tř 128 | tzv 129 | univ 130 | uspoř 131 | vol 132 | vl.jm 133 | vs 134 | vyd 135 | vyobr 136 | zal 137 | zejm 138 | zkr 139 | zprac 140 | zvl 141 | n.p 142 | např 143 | než 144 | MUDr 145 | abl 146 | absol 147 | adj 148 | adv 149 | ak 150 | ak. sl 151 | akt 152 | alch 153 | amer 154 | anat 155 | angl 156 | anglosas 157 | arab 158 | arch 159 | archit 160 | arg 161 | astr 162 | astrol 163 | att 164 | bás 165 | belg 166 | bibl 167 | biol 168 | boh 169 | bot 170 | bulh 171 | círk 172 | csl 173 | č 174 | čas 175 | čes 176 | dat 177 | děj 178 | dep 179 | dět 180 | dial 181 | dór 182 | dopr 183 | dosl 184 | ekon 185 | epic 186 | etnonym 187 | eufem 188 | f 189 | fam 190 | fem 191 | fil 192 | film 193 | form 194 | fot 195 | fr 196 | fut 197 | fyz 198 | gen 199 | geogr 200 | geol 201 | geom 202 | germ 203 | gram 204 | hebr 205 | herald 206 | hist 207 | hl 208 | hovor 209 | hud 210 | hut 211 | chcsl 212 | chem 213 | ie 214 | imp 215 | impf 216 | ind 217 | indoevr 218 | inf 219 | instr 220 | interj 221 | ión 222 | iron 223 | it 224 | kanad 225 | katalán 226 | klas 227 | kniž 228 | komp 229 | konj 230 | 231 | konkr 232 | kř 233 | kuch 234 | lat 235 | lék 236 | les 237 | lid 238 | lit 239 | liturg 240 | lok 241 | log 242 | m 243 | mat 244 | meteor 245 | metr 246 | mod 247 | ms 248 | mysl 249 | n 250 | náb 251 | námoř 252 | neklas 253 | něm 254 | nesklon 255 | nom 256 | ob 257 | obch 258 | obyč 259 | ojed 260 | opt 261 | part 262 | pas 263 | pejor 264 | pers 265 | pf 266 | pl 267 | plpf 268 | 269 | práv 270 | prep 271 | předl 272 | přivl 273 | r 274 | rcsl 275 | refl 276 | reg 277 | rkp 278 | ř 279 | řec 280 | s 281 | samohl 282 | sg 283 | sl 284 | souhl 285 | spec 286 | srov 287 | stfr 288 | střv 289 | stsl 290 | subj 291 | subst 292 | superl 293 | sv 294 | sz 295 | táz 296 | tech 297 | telev 298 | teol 299 | trans 300 | typogr 301 | var 302 | vedl 303 | verb 304 | vl. jm 305 | voj 306 | vok 307 | vůb 308 | vulg 309 | výtv 310 | vztaž 311 | zahr 312 | zájm 313 | zast 314 | zejm 315 | 316 | zeměd 317 | zkr 318 | zř 319 | mj 320 | dl 321 | atp 322 | sport 323 | Mgr 324 | horn 325 | MVDr 326 | JUDr 327 | RSDr 328 | Bc 329 | PhDr 330 | ThDr 331 | Ing 332 | aj 333 | apod 334 | PharmDr 335 | pomn 336 | ev 337 | slang 338 | nprap 339 | odp 340 | dop 341 | pol 342 | st 343 | stol 344 | p. n. l 345 | před n. l 346 | n. l 347 | př. Kr 348 | po Kr 349 | př. n. l 350 | odd 351 | RNDr 352 | tzv 353 | atd 354 | tzn 355 | resp 356 | tj 357 | p 358 | br 359 | č. j 360 | čj 361 | č. p 362 | čp 363 | a. s 364 | s. r. o 365 | spol. s r. o 366 | p. o 367 | s. p 368 | v. o. s 369 | k. s 370 | o. p. s 371 | o. s 372 | v. r 373 | v z 374 | ml 375 | vč 376 | kr 377 | mld 378 | hod 379 | popř 380 | ap 381 | event 382 | rus 383 | slov 384 | rum 385 | švýc 386 | P. T 387 | zvl 388 | hor 389 | dol 390 | S.O.S -------------------------------------------------------------------------------- /tools/nonbreaking_prefixes/nonbreaking_prefix.de: -------------------------------------------------------------------------------- 1 | #Anything in this file, followed by a period (and an upper-case word), does NOT indicate an end-of-sentence marker. 2 | #Special cases are included for prefixes that ONLY appear before 0-9 numbers. 3 | 4 | #any single upper case letter followed by a period is not a sentence ender (excluding I occasionally, but we leave it in) 5 | #usually upper case letters are initials in a name 6 | #no german words end in single lower-case letters, so we throw those in too. 7 | A 8 | B 9 | C 10 | D 11 | E 12 | F 13 | G 14 | H 15 | I 16 | J 17 | K 18 | L 19 | M 20 | N 21 | O 22 | P 23 | Q 24 | R 25 | S 26 | T 27 | U 28 | V 29 | W 30 | X 31 | Y 32 | Z 33 | a 34 | b 35 | c 36 | d 37 | e 38 | f 39 | g 40 | h 41 | i 42 | j 43 | k 44 | l 45 | m 46 | n 47 | o 48 | p 49 | q 50 | r 51 | s 52 | t 53 | u 54 | v 55 | w 56 | x 57 | y 58 | z 59 | 60 | 61 | #Roman Numerals. A dot after one of these is not a sentence break in German. 62 | I 63 | II 64 | III 65 | IV 66 | V 67 | VI 68 | VII 69 | VIII 70 | IX 71 | X 72 | XI 73 | XII 74 | XIII 75 | XIV 76 | XV 77 | XVI 78 | XVII 79 | XVIII 80 | XIX 81 | XX 82 | i 83 | ii 84 | iii 85 | iv 86 | v 87 | vi 88 | vii 89 | viii 90 | ix 91 | x 92 | xi 93 | xii 94 | xiii 95 | xiv 96 | xv 97 | xvi 98 | xvii 99 | xviii 100 | xix 101 | xx 102 | 103 | #Titles and Honorifics 104 | Adj 105 | Adm 106 | Adv 107 | Asst 108 | Bart 109 | Bldg 110 | Brig 111 | Bros 112 | Capt 113 | Cmdr 114 | Col 115 | Comdr 116 | Con 117 | Corp 118 | Cpl 119 | DR 120 | Dr 121 | Ens 122 | Gen 123 | Gov 124 | Hon 125 | Hosp 126 | Insp 127 | Lt 128 | MM 129 | MR 130 | MRS 131 | MS 132 | Maj 133 | Messrs 134 | Mlle 135 | Mme 136 | Mr 137 | Mrs 138 | Ms 139 | Msgr 140 | Op 141 | Ord 142 | Pfc 143 | Ph 144 | Prof 145 | Pvt 146 | Rep 147 | Reps 148 | Res 149 | Rev 150 | Rt 151 | Sen 152 | Sens 153 | Sfc 154 | Sgt 155 | Sr 156 | St 157 | Supt 158 | Surg 159 | 160 | #Misc symbols 161 | Mio 162 | Mrd 163 | bzw 164 | v 165 | vs 166 | usw 167 | d.h 168 | z.B 169 | u.a 170 | etc 171 | Mrd 172 | MwSt 173 | ggf 174 | d.J 175 | D.h 176 | m.E 177 | vgl 178 | I.F 179 | z.T 180 | sogen 181 | ff 182 | u.E 183 | g.U 184 | g.g.A 185 | c.-à-d 186 | Buchst 187 | u.s.w 188 | sog 189 | u.ä 190 | Std 191 | evtl 192 | Zt 193 | Chr 194 | u.U 195 | o.ä 196 | Ltd 197 | b.A 198 | z.Zt 199 | spp 200 | sen 201 | SA 202 | k.o 203 | jun 204 | i.H.v 205 | dgl 206 | dergl 207 | Co 208 | zzt 209 | usf 210 | s.p.a 211 | Dkr 212 | Corp 213 | bzgl 214 | BSE 215 | 216 | #Number indicators 217 | # add #NUMERIC_ONLY# after the word if it should ONLY be non-breaking when a 0-9 digit follows it 218 | No 219 | Nos 220 | Art 221 | Nr 222 | pp 223 | ca 224 | Ca 225 | 226 | #Ordinals are done with . in German - "1." = "1st" in English 227 | 1 228 | 2 229 | 3 230 | 4 231 | 5 232 | 6 233 | 7 234 | 8 235 | 9 236 | 10 237 | 11 238 | 12 239 | 13 240 | 14 241 | 15 242 | 16 243 | 17 244 | 18 245 | 19 246 | 20 247 | 21 248 | 22 249 | 23 250 | 24 251 | 25 252 | 26 253 | 27 254 | 28 255 | 29 256 | 30 257 | 31 258 | 32 259 | 33 260 | 34 261 | 35 262 | 36 263 | 37 264 | 38 265 | 39 266 | 40 267 | 41 268 | 42 269 | 43 270 | 44 271 | 45 272 | 46 273 | 47 274 | 48 275 | 49 276 | 50 277 | 51 278 | 52 279 | 53 280 | 54 281 | 55 282 | 56 283 | 57 284 | 58 285 | 59 286 | 60 287 | 61 288 | 62 289 | 63 290 | 64 291 | 65 292 | 66 293 | 67 294 | 68 295 | 69 296 | 70 297 | 71 298 | 72 299 | 73 300 | 74 301 | 75 302 | 76 303 | 77 304 | 78 305 | 79 306 | 80 307 | 81 308 | 82 309 | 83 310 | 84 311 | 85 312 | 86 313 | 87 314 | 88 315 | 89 316 | 90 317 | 91 318 | 92 319 | 93 320 | 94 321 | 95 322 | 96 323 | 97 324 | 98 325 | 99 326 | -------------------------------------------------------------------------------- /tools/nonbreaking_prefixes/nonbreaking_prefix.en: -------------------------------------------------------------------------------- 1 | #Anything in this file, followed by a period (and an upper-case word), does NOT indicate an end-of-sentence marker. 2 | #Special cases are included for prefixes that ONLY appear before 0-9 numbers. 3 | 4 | #any single upper case letter followed by a period is not a sentence ender (excluding I occasionally, but we leave it in) 5 | #usually upper case letters are initials in a name 6 | A 7 | B 8 | C 9 | D 10 | E 11 | F 12 | G 13 | H 14 | I 15 | J 16 | K 17 | L 18 | M 19 | N 20 | O 21 | P 22 | Q 23 | R 24 | S 25 | T 26 | U 27 | V 28 | W 29 | X 30 | Y 31 | Z 32 | 33 | #List of titles. These are often followed by upper-case names, but do not indicate sentence breaks 34 | Adj 35 | Adm 36 | Adv 37 | Asst 38 | Bart 39 | Bldg 40 | Brig 41 | Bros 42 | Capt 43 | Cmdr 44 | Col 45 | Comdr 46 | Con 47 | Corp 48 | Cpl 49 | DR 50 | Dr 51 | Drs 52 | Ens 53 | Gen 54 | Gov 55 | Hon 56 | Hr 57 | Hosp 58 | Insp 59 | Lt 60 | MM 61 | MR 62 | MRS 63 | MS 64 | Maj 65 | Messrs 66 | Mlle 67 | Mme 68 | Mr 69 | Mrs 70 | Ms 71 | Msgr 72 | Op 73 | Ord 74 | Pfc 75 | Ph 76 | Prof 77 | Pvt 78 | Rep 79 | Reps 80 | Res 81 | Rev 82 | Rt 83 | Sen 84 | Sens 85 | Sfc 86 | Sgt 87 | Sr 88 | St 89 | Supt 90 | Surg 91 | 92 | #misc - odd period-ending items that NEVER indicate breaks (p.m. does NOT fall into this category - it sometimes ends a sentence) 93 | v 94 | vs 95 | i.e 96 | rev 97 | e.g 98 | 99 | #Numbers only. These should only induce breaks when followed by a numeric sequence 100 | # add NUMERIC_ONLY after the word for this function 101 | #This case is mostly for the english "No." which can either be a sentence of its own, or 102 | #if followed by a number, a non-breaking prefix 103 | No #NUMERIC_ONLY# 104 | Nos 105 | Art #NUMERIC_ONLY# 106 | Nr 107 | pp #NUMERIC_ONLY# 108 | 109 | #month abbreviations 110 | Jan 111 | Feb 112 | Mar 113 | Apr 114 | #May is a full word 115 | Jun 116 | Jul 117 | Aug 118 | Sep 119 | Oct 120 | Nov 121 | Dec 122 | -------------------------------------------------------------------------------- /tools/nonbreaking_prefixes/nonbreaking_prefix.es: -------------------------------------------------------------------------------- 1 | #Anything in this file, followed by a period (and an upper-case word), does NOT indicate an end-of-sentence marker. 2 | #Special cases are included for prefixes that ONLY appear before 0-9 numbers. 3 | 4 | #any single upper case letter followed by a period is not a sentence ender 5 | #usually upper case letters are initials in a name 6 | A 7 | B 8 | C 9 | D 10 | E 11 | F 12 | G 13 | H 14 | I 15 | J 16 | K 17 | L 18 | M 19 | N 20 | O 21 | P 22 | Q 23 | R 24 | S 25 | T 26 | U 27 | V 28 | W 29 | X 30 | Y 31 | Z 32 | 33 | # Period-final abbreviation list from http://www.ctspanish.com/words/abbreviations.htm 34 | 35 | A.C 36 | Apdo 37 | Av 38 | Bco 39 | CC.AA 40 | Da 41 | Dep 42 | Dn 43 | Dr 44 | Dra 45 | EE.UU 46 | Excmo 47 | FF.CC 48 | Fil 49 | Gral 50 | J.C 51 | Let 52 | Lic 53 | N.B 54 | P.D 55 | P.V.P 56 | Prof 57 | Pts 58 | Rte 59 | S.A 60 | S.A.R 61 | S.E 62 | S.L 63 | S.R.C 64 | Sr 65 | Sra 66 | Srta 67 | Sta 68 | Sto 69 | T.V.E 70 | Tel 71 | Ud 72 | Uds 73 | V.B 74 | V.E 75 | Vd 76 | Vds 77 | a/c 78 | adj 79 | admón 80 | afmo 81 | apdo 82 | av 83 | c 84 | c.f 85 | c.g 86 | cap 87 | cm 88 | cta 89 | dcha 90 | doc 91 | ej 92 | entlo 93 | esq 94 | etc 95 | f.c 96 | gr 97 | grs 98 | izq 99 | kg 100 | km 101 | mg 102 | mm 103 | núm 104 | núm 105 | p 106 | p.a 107 | p.ej 108 | ptas 109 | pág 110 | págs 111 | pág 112 | págs 113 | q.e.g.e 114 | q.e.s.m 115 | s 116 | s.s.s 117 | vid 118 | vol 119 | -------------------------------------------------------------------------------- /tools/nonbreaking_prefixes/nonbreaking_prefix.fi: -------------------------------------------------------------------------------- 1 | #Anything in this file, followed by a period (and an upper-case word), does NOT 2 | #indicate an end-of-sentence marker. Special cases are included for prefixes 3 | #that ONLY appear before 0-9 numbers. 4 | 5 | #This list is compiled from omorfi database 6 | #by Tommi A Pirinen. 7 | 8 | 9 | #any single upper case letter followed by a period is not a sentence ender 10 | A 11 | B 12 | C 13 | D 14 | E 15 | F 16 | G 17 | H 18 | I 19 | J 20 | K 21 | L 22 | M 23 | N 24 | O 25 | P 26 | Q 27 | R 28 | S 29 | T 30 | U 31 | V 32 | W 33 | X 34 | Y 35 | Z 36 | Å 37 | Ä 38 | Ö 39 | 40 | #List of titles. These are often followed by upper-case names, but do not indicate sentence breaks 41 | alik 42 | alil 43 | amir 44 | apul 45 | apul.prof 46 | arkkit 47 | ass 48 | assist 49 | dipl 50 | dipl.arkkit 51 | dipl.ekon 52 | dipl.ins 53 | dipl.kielenk 54 | dipl.kirjeenv 55 | dipl.kosm 56 | dipl.urk 57 | dos 58 | erikoiseläinl 59 | erikoishammasl 60 | erikoisl 61 | erikoist 62 | ev.luutn 63 | evp 64 | fil 65 | ft 66 | hallinton 67 | hallintot 68 | hammaslääket 69 | jatk 70 | jääk 71 | kansaned 72 | kapt 73 | kapt.luutn 74 | kenr 75 | kenr.luutn 76 | kenr.maj 77 | kers 78 | kirjeenv 79 | kom 80 | kom.kapt 81 | komm 82 | konst 83 | korpr 84 | luutn 85 | maist 86 | maj 87 | Mr 88 | Mrs 89 | Ms 90 | M.Sc 91 | neuv 92 | nimim 93 | Ph.D 94 | prof 95 | puh.joht 96 | pääll 97 | res 98 | san 99 | siht 100 | suom 101 | sähköp 102 | säv 103 | toht 104 | toim 105 | toim.apul 106 | toim.joht 107 | toim.siht 108 | tuom 109 | ups 110 | vänr 111 | vääp 112 | ye.ups 113 | ylik 114 | ylil 115 | ylim 116 | ylimatr 117 | yliop 118 | yliopp 119 | ylip 120 | yliv 121 | 122 | #misc - odd period-ending items that NEVER indicate breaks (p.m. does NOT fall 123 | #into this category - it sometimes ends a sentence) 124 | e.g 125 | ent 126 | esim 127 | huom 128 | i.e 129 | ilm 130 | l 131 | mm 132 | myöh 133 | nk 134 | nyk 135 | par 136 | po 137 | t 138 | v 139 | -------------------------------------------------------------------------------- /tools/nonbreaking_prefixes/nonbreaking_prefix.fr: -------------------------------------------------------------------------------- 1 | #Anything in this file, followed by a period (and an upper-case word), does NOT indicate an end-of-sentence marker. 2 | #Special cases are included for prefixes that ONLY appear before 0-9 numbers. 3 | # 4 | #any single upper case letter followed by a period is not a sentence ender 5 | #usually upper case letters are initials in a name 6 | #no French words end in single lower-case letters, so we throw those in too? 7 | A 8 | B 9 | C 10 | D 11 | E 12 | F 13 | G 14 | H 15 | I 16 | J 17 | K 18 | L 19 | M 20 | N 21 | O 22 | P 23 | Q 24 | R 25 | S 26 | T 27 | U 28 | V 29 | W 30 | X 31 | Y 32 | Z 33 | #a 34 | b 35 | c 36 | d 37 | e 38 | f 39 | g 40 | h 41 | i 42 | j 43 | k 44 | l 45 | m 46 | n 47 | o 48 | p 49 | q 50 | r 51 | s 52 | t 53 | u 54 | v 55 | w 56 | x 57 | y 58 | z 59 | 60 | # Period-final abbreviation list for French 61 | A.C.N 62 | A.M 63 | art 64 | ann 65 | apr 66 | av 67 | auj 68 | lib 69 | B.P 70 | boul 71 | ca 72 | c.-à-d 73 | cf 74 | ch.-l 75 | chap 76 | contr 77 | C.P.I 78 | C.Q.F.D 79 | C.N 80 | C.N.S 81 | C.S 82 | dir 83 | éd 84 | e.g 85 | env 86 | al 87 | etc 88 | E.V 89 | ex 90 | fasc 91 | fém 92 | fig 93 | fr 94 | hab 95 | ibid 96 | id 97 | i.e 98 | inf 99 | LL.AA 100 | LL.AA.II 101 | LL.AA.RR 102 | LL.AA.SS 103 | L.D 104 | LL.EE 105 | LL.MM 106 | LL.MM.II.RR 107 | loc.cit 108 | masc 109 | MM 110 | ms 111 | N.B 112 | N.D.A 113 | N.D.L.R 114 | N.D.T 115 | n/réf 116 | NN.SS 117 | N.S 118 | N.D 119 | N.P.A.I 120 | p.c.c 121 | pl 122 | pp 123 | p.ex 124 | p.j 125 | P.S 126 | R.A.S 127 | R.-V 128 | R.P 129 | R.I.P 130 | SS 131 | S.S 132 | S.A 133 | S.A.I 134 | S.A.R 135 | S.A.S 136 | S.E 137 | sec 138 | sect 139 | sing 140 | S.M 141 | S.M.I.R 142 | sq 143 | sqq 144 | suiv 145 | sup 146 | suppl 147 | tél 148 | T.S.V.P 149 | vb 150 | vol 151 | vs 152 | X.O 153 | Z.I 154 | -------------------------------------------------------------------------------- /tools/nonbreaking_prefixes/nonbreaking_prefix.ga: -------------------------------------------------------------------------------- 1 | 2 | A 3 | B 4 | C 5 | D 6 | E 7 | F 8 | G 9 | H 10 | I 11 | J 12 | K 13 | L 14 | M 15 | N 16 | O 17 | P 18 | Q 19 | R 20 | S 21 | T 22 | U 23 | V 24 | W 25 | X 26 | Y 27 | Z 28 | Á 29 | É 30 | Í 31 | Ó 32 | Ú 33 | 34 | Uacht 35 | Dr 36 | B.Arch 37 | 38 | m.sh 39 | .i 40 | Co 41 | Cf 42 | cf 43 | i.e 44 | r 45 | Chr 46 | lch #NUMERIC_ONLY# 47 | lgh #NUMERIC_ONLY# 48 | uimh #NUMERIC_ONLY# 49 | -------------------------------------------------------------------------------- /tools/nonbreaking_prefixes/nonbreaking_prefix.hu: -------------------------------------------------------------------------------- 1 | #Anything in this file, followed by a period (and an upper-case word), does NOT indicate an end-of-sentence marker. 2 | #Special cases are included for prefixes that ONLY appear before 0-9 numbers. 3 | 4 | #any single upper case letter followed by a period is not a sentence ender (excluding I occasionally, but we leave it in) 5 | #usually upper case letters are initials in a name 6 | A 7 | B 8 | C 9 | D 10 | E 11 | F 12 | G 13 | H 14 | I 15 | J 16 | K 17 | L 18 | M 19 | N 20 | O 21 | P 22 | Q 23 | R 24 | S 25 | T 26 | U 27 | V 28 | W 29 | X 30 | Y 31 | Z 32 | Á 33 | É 34 | Í 35 | Ó 36 | Ö 37 | Ő 38 | Ú 39 | Ü 40 | Ű 41 | 42 | #List of titles. These are often followed by upper-case names, but do not indicate sentence breaks 43 | Dr 44 | dr 45 | kb 46 | Kb 47 | vö 48 | Vö 49 | pl 50 | Pl 51 | ca 52 | Ca 53 | min 54 | Min 55 | max 56 | Max 57 | ún 58 | Ún 59 | prof 60 | Prof 61 | de 62 | De 63 | du 64 | Du 65 | Szt 66 | St 67 | 68 | #Numbers only. These should only induce breaks when followed by a numeric sequence 69 | # add NUMERIC_ONLY after the word for this function 70 | #This case is mostly for the english "No." which can either be a sentence of its own, or 71 | #if followed by a number, a non-breaking prefix 72 | 73 | # Month name abbreviations 74 | jan #NUMERIC_ONLY# 75 | Jan #NUMERIC_ONLY# 76 | Feb #NUMERIC_ONLY# 77 | feb #NUMERIC_ONLY# 78 | márc #NUMERIC_ONLY# 79 | Márc #NUMERIC_ONLY# 80 | ápr #NUMERIC_ONLY# 81 | Ápr #NUMERIC_ONLY# 82 | máj #NUMERIC_ONLY# 83 | Máj #NUMERIC_ONLY# 84 | jún #NUMERIC_ONLY# 85 | Jún #NUMERIC_ONLY# 86 | Júl #NUMERIC_ONLY# 87 | júl #NUMERIC_ONLY# 88 | aug #NUMERIC_ONLY# 89 | Aug #NUMERIC_ONLY# 90 | Szept #NUMERIC_ONLY# 91 | szept #NUMERIC_ONLY# 92 | okt #NUMERIC_ONLY# 93 | Okt #NUMERIC_ONLY# 94 | nov #NUMERIC_ONLY# 95 | Nov #NUMERIC_ONLY# 96 | dec #NUMERIC_ONLY# 97 | Dec #NUMERIC_ONLY# 98 | 99 | # Other abbreviations 100 | tel #NUMERIC_ONLY# 101 | Tel #NUMERIC_ONLY# 102 | Fax #NUMERIC_ONLY# 103 | fax #NUMERIC_ONLY# 104 | -------------------------------------------------------------------------------- /tools/nonbreaking_prefixes/nonbreaking_prefix.is: -------------------------------------------------------------------------------- 1 | no #NUMERIC_ONLY# 2 | No #NUMERIC_ONLY# 3 | nr #NUMERIC_ONLY# 4 | Nr #NUMERIC_ONLY# 5 | nR #NUMERIC_ONLY# 6 | NR #NUMERIC_ONLY# 7 | a 8 | b 9 | c 10 | d 11 | e 12 | f 13 | g 14 | h 15 | i 16 | j 17 | k 18 | l 19 | m 20 | n 21 | o 22 | p 23 | q 24 | r 25 | s 26 | t 27 | u 28 | v 29 | w 30 | x 31 | y 32 | z 33 | ^ 34 | í 35 | á 36 | ó 37 | æ 38 | A 39 | B 40 | C 41 | D 42 | E 43 | F 44 | G 45 | H 46 | I 47 | J 48 | K 49 | L 50 | M 51 | N 52 | O 53 | P 54 | Q 55 | R 56 | S 57 | T 58 | U 59 | V 60 | W 61 | X 62 | Y 63 | Z 64 | ab.fn 65 | a.fn 66 | afs 67 | al 68 | alm 69 | alg 70 | andh 71 | ath 72 | aths 73 | atr 74 | ao 75 | au 76 | aukaf 77 | áfn 78 | áhrl.s 79 | áhrs 80 | ákv.gr 81 | ákv 82 | bh 83 | bls 84 | dr 85 | e.Kr 86 | et 87 | ef 88 | efn 89 | ennfr 90 | eink 91 | end 92 | e.st 93 | erl 94 | fél 95 | fskj 96 | fh 97 | f.hl 98 | físl 99 | fl 100 | fn 101 | fo 102 | forl 103 | frb 104 | frl 105 | frh 106 | frt 107 | fsl 108 | fsh 109 | fs 110 | fsk 111 | fst 112 | f.Kr 113 | ft 114 | fv 115 | fyrrn 116 | fyrrv 117 | germ 118 | gm 119 | gr 120 | hdl 121 | hdr 122 | hf 123 | hl 124 | hlsk 125 | hljsk 126 | hljv 127 | hljóðv 128 | hr 129 | hv 130 | hvk 131 | holl 132 | Hos 133 | höf 134 | hk 135 | hrl 136 | ísl 137 | kaf 138 | kap 139 | Khöfn 140 | kk 141 | kg 142 | kk 143 | km 144 | kl 145 | klst 146 | kr 147 | kt 148 | kgúrsk 149 | kvk 150 | leturbr 151 | lh 152 | lh.nt 153 | lh.þt 154 | lo 155 | ltr 156 | mlja 157 | mljó 158 | millj 159 | mm 160 | mms 161 | m.fl 162 | miðm 163 | mgr 164 | mst 165 | mín 166 | nf 167 | nh 168 | nhm 169 | nl 170 | nk 171 | nmgr 172 | no 173 | núv 174 | nt 175 | o.áfr 176 | o.m.fl 177 | ohf 178 | o.fl 179 | o.s.frv 180 | ófn 181 | ób 182 | óákv.gr 183 | óákv 184 | pfn 185 | PR 186 | pr 187 | Ritstj 188 | Rvík 189 | Rvk 190 | samb 191 | samhlj 192 | samn 193 | samn 194 | sbr 195 | sek 196 | sérn 197 | sf 198 | sfn 199 | sh 200 | sfn 201 | sh 202 | s.hl 203 | sk 204 | skv 205 | sl 206 | sn 207 | so 208 | ss.us 209 | s.st 210 | samþ 211 | sbr 212 | shlj 213 | sign 214 | skál 215 | st 216 | st.s 217 | stk 218 | sþ 219 | teg 220 | tbl 221 | tfn 222 | tl 223 | tvíhlj 224 | tvt 225 | till 226 | to 227 | umr 228 | uh 229 | us 230 | uppl 231 | útg 232 | vb 233 | Vf 234 | vh 235 | vkf 236 | Vl 237 | vl 238 | vlf 239 | vmf 240 | 8vo 241 | vsk 242 | vth 243 | þt 244 | þf 245 | þjs 246 | þgf 247 | þlt 248 | þolm 249 | þm 250 | þml 251 | þýð 252 | -------------------------------------------------------------------------------- /tools/nonbreaking_prefixes/nonbreaking_prefix.it: -------------------------------------------------------------------------------- 1 | #Anything in this file, followed by a period (and an upper-case word), does NOT indicate an end-of-sentence marker. 2 | #Special cases are included for prefixes that ONLY appear before 0-9 numbers. 3 | 4 | #any single upper case letter followed by a period is not a sentence ender (excluding I occasionally, but we leave it in) 5 | #usually upper case letters are initials in a name 6 | A 7 | B 8 | C 9 | D 10 | E 11 | F 12 | G 13 | H 14 | I 15 | J 16 | K 17 | L 18 | M 19 | N 20 | O 21 | P 22 | Q 23 | R 24 | S 25 | T 26 | U 27 | V 28 | W 29 | X 30 | Y 31 | Z 32 | 33 | #List of titles. These are often followed by upper-case names, but do not indicate sentence breaks 34 | Adj 35 | Adm 36 | Adv 37 | Amn 38 | Arch 39 | Asst 40 | Avv 41 | Bart 42 | Bcc 43 | Bldg 44 | Brig 45 | Bros 46 | C.A.P 47 | C.P 48 | Capt 49 | Cc 50 | Cmdr 51 | Co 52 | Col 53 | Comdr 54 | Con 55 | Corp 56 | Cpl 57 | DR 58 | Dott 59 | Dr 60 | Drs 61 | Egr 62 | Ens 63 | Gen 64 | Geom 65 | Gov 66 | Hon 67 | Hosp 68 | Hr 69 | Id 70 | Ing 71 | Insp 72 | Lt 73 | MM 74 | MR 75 | MRS 76 | MS 77 | Maj 78 | Messrs 79 | Mlle 80 | Mme 81 | Mo 82 | Mons 83 | Mr 84 | Mrs 85 | Ms 86 | Msgr 87 | N.B 88 | Op 89 | Ord 90 | P.S 91 | P.T 92 | Pfc 93 | Ph 94 | Prof 95 | Pvt 96 | RP 97 | RSVP 98 | Rag 99 | Rep 100 | Reps 101 | Res 102 | Rev 103 | Rif 104 | Rt 105 | S.A 106 | S.B.F 107 | S.P.M 108 | S.p.A 109 | S.r.l 110 | Sen 111 | Sens 112 | Sfc 113 | Sgt 114 | Sig 115 | Sigg 116 | Soc 117 | Spett 118 | Sr 119 | St 120 | Supt 121 | Surg 122 | V.P 123 | 124 | # other 125 | a.c 126 | acc 127 | all 128 | banc 129 | c.a 130 | c.c.p 131 | c.m 132 | c.p 133 | c.s 134 | c.v 135 | corr 136 | dott 137 | e.p.c 138 | ecc 139 | es 140 | fatt 141 | gg 142 | int 143 | lett 144 | ogg 145 | on 146 | p.c 147 | p.c.c 148 | p.es 149 | p.f 150 | p.r 151 | p.v 152 | post 153 | pp 154 | racc 155 | ric 156 | s.n.c 157 | seg 158 | sgg 159 | ss 160 | tel 161 | u.s 162 | v.r 163 | v.s 164 | 165 | #misc - odd period-ending items that NEVER indicate breaks (p.m. does NOT fall into this category - it sometimes ends a sentence) 166 | v 167 | vs 168 | i.e 169 | rev 170 | e.g 171 | 172 | #Numbers only. These should only induce breaks when followed by a numeric sequence 173 | # add NUMERIC_ONLY after the word for this function 174 | #This case is mostly for the english "No." which can either be a sentence of its own, or 175 | #if followed by a number, a non-breaking prefix 176 | No #NUMERIC_ONLY# 177 | Nos 178 | Art #NUMERIC_ONLY# 179 | Nr 180 | pp #NUMERIC_ONLY# 181 | -------------------------------------------------------------------------------- /tools/nonbreaking_prefixes/nonbreaking_prefix.lv: -------------------------------------------------------------------------------- 1 | #Anything in this file, followed by a period (and an upper-case word), does NOT indicate an end-of-sentence marker. 2 | #Special cases are included for prefixes that ONLY appear before 0-9 numbers. 3 | 4 | #any single upper case letter followed by a period is not a sentence ender (excluding I occasionally, but we leave it in) 5 | #usually upper case letters are initials in a name 6 | A 7 | Ā 8 | B 9 | C 10 | Č 11 | D 12 | E 13 | Ē 14 | F 15 | G 16 | Ģ 17 | H 18 | I 19 | Ī 20 | J 21 | K 22 | Ķ 23 | L 24 | Ļ 25 | M 26 | N 27 | Ņ 28 | O 29 | P 30 | Q 31 | R 32 | S 33 | Š 34 | T 35 | U 36 | Ū 37 | V 38 | W 39 | X 40 | Y 41 | Z 42 | Ž 43 | 44 | #List of titles. These are often followed by upper-case names, but do not indicate sentence breaks 45 | dr 46 | Dr 47 | med 48 | prof 49 | Prof 50 | inž 51 | Inž 52 | ist.loc 53 | Ist.loc 54 | kor.loc 55 | Kor.loc 56 | v.i 57 | vietn 58 | Vietn 59 | 60 | #misc - odd period-ending items that NEVER indicate breaks (p.m. does NOT fall into this category - it sometimes ends a sentence) 61 | a.l 62 | t.p 63 | pārb 64 | Pārb 65 | vec 66 | Vec 67 | inv 68 | Inv 69 | sk 70 | Sk 71 | spec 72 | Spec 73 | vienk 74 | Vienk 75 | virz 76 | Virz 77 | māksl 78 | Māksl 79 | mūz 80 | Mūz 81 | akad 82 | Akad 83 | soc 84 | Soc 85 | galv 86 | Galv 87 | vad 88 | Vad 89 | sertif 90 | Sertif 91 | folkl 92 | Folkl 93 | hum 94 | Hum 95 | 96 | #Numbers only. These should only induce breaks when followed by a numeric sequence 97 | # add NUMERIC_ONLY after the word for this function 98 | #This case is mostly for the english "No." which can either be a sentence of its own, or 99 | #if followed by a number, a non-breaking prefix 100 | Nr #NUMERIC_ONLY# 101 | -------------------------------------------------------------------------------- /tools/nonbreaking_prefixes/nonbreaking_prefix.nl: -------------------------------------------------------------------------------- 1 | #Anything in this file, followed by a period (and an upper-case word), does NOT indicate an end-of-sentence marker. 2 | #Special cases are included for prefixes that ONLY appear before 0-9 numbers. 3 | #Sources: http://nl.wikipedia.org/wiki/Lijst_van_afkortingen 4 | # http://nl.wikipedia.org/wiki/Aanspreekvorm 5 | # http://nl.wikipedia.org/wiki/Titulatuur_in_het_Nederlands_hoger_onderwijs 6 | #any single upper case letter followed by a period is not a sentence ender (excluding I occasionally, but we leave it in) 7 | #usually upper case letters are initials in a name 8 | A 9 | B 10 | C 11 | D 12 | E 13 | F 14 | G 15 | H 16 | I 17 | J 18 | K 19 | L 20 | M 21 | N 22 | O 23 | P 24 | Q 25 | R 26 | S 27 | T 28 | U 29 | V 30 | W 31 | X 32 | Y 33 | Z 34 | 35 | #List of titles. These are often followed by upper-case names, but do not indicate sentence breaks 36 | bacc 37 | bc 38 | bgen 39 | c.i 40 | dhr 41 | dr 42 | dr.h.c 43 | drs 44 | drs 45 | ds 46 | eint 47 | fa 48 | Fa 49 | fam 50 | gen 51 | genm 52 | ing 53 | ir 54 | jhr 55 | jkvr 56 | jr 57 | kand 58 | kol 59 | lgen 60 | lkol 61 | Lt 62 | maj 63 | Mej 64 | mevr 65 | Mme 66 | mr 67 | mr 68 | Mw 69 | o.b.s 70 | plv 71 | prof 72 | ritm 73 | tint 74 | Vz 75 | Z.D 76 | Z.D.H 77 | Z.E 78 | Z.Em 79 | Z.H 80 | Z.K.H 81 | Z.K.M 82 | Z.M 83 | z.v 84 | 85 | #misc - odd period-ending items that NEVER indicate breaks (p.m. does NOT fall into this category - it sometimes ends a sentence) 86 | #we seem to have a lot of these in dutch i.e.: i.p.v - in plaats van (in stead of) never ends a sentence 87 | a.g.v 88 | bijv 89 | bijz 90 | bv 91 | d.w.z 92 | e.c 93 | e.g 94 | e.k 95 | ev 96 | i.p.v 97 | i.s.m 98 | i.t.t 99 | i.v.m 100 | m.a.w 101 | m.b.t 102 | m.b.v 103 | m.h.o 104 | m.i 105 | m.i.v 106 | v.w.t 107 | 108 | #Numbers only. These should only induce breaks when followed by a numeric sequence 109 | # add NUMERIC_ONLY after the word for this function 110 | #This case is mostly for the english "No." which can either be a sentence of its own, or 111 | #if followed by a number, a non-breaking prefix 112 | Nr #NUMERIC_ONLY# 113 | Nrs 114 | nrs 115 | nr #NUMERIC_ONLY# 116 | -------------------------------------------------------------------------------- /tools/nonbreaking_prefixes/nonbreaking_prefix.pl: -------------------------------------------------------------------------------- 1 | adw 2 | afr 3 | akad 4 | al 5 | Al 6 | am 7 | amer 8 | arch 9 | art 10 | Art 11 | artyst 12 | astr 13 | austr 14 | bałt 15 | bdb 16 | bł 17 | bm 18 | br 19 | bryg 20 | bryt 21 | centr 22 | ces 23 | chem 24 | chiń 25 | chir 26 | c.k 27 | c.o 28 | cyg 29 | cyw 30 | cyt 31 | czes 32 | czw 33 | cd 34 | Cd 35 | czyt 36 | ćw 37 | ćwicz 38 | daw 39 | dcn 40 | dekl 41 | demokr 42 | det 43 | diec 44 | dł 45 | dn 46 | dot 47 | dol 48 | dop 49 | dost 50 | dosł 51 | h.c 52 | ds 53 | dst 54 | duszp 55 | dypl 56 | egz 57 | ekol 58 | ekon 59 | elektr 60 | em 61 | ew 62 | fab 63 | farm 64 | fot 65 | fr 66 | gat 67 | gastr 68 | geogr 69 | geol 70 | gimn 71 | głęb 72 | gm 73 | godz 74 | górn 75 | gosp 76 | gr 77 | gram 78 | hist 79 | hiszp 80 | hr 81 | Hr 82 | hot 83 | id 84 | in 85 | im 86 | iron 87 | jn 88 | kard 89 | kat 90 | katol 91 | k.k 92 | kk 93 | kol 94 | kl 95 | k.p.a 96 | kpc 97 | k.p.c 98 | kpt 99 | kr 100 | k.r 101 | krak 102 | k.r.o 103 | kryt 104 | kult 105 | laic 106 | łac 107 | niem 108 | woj 109 | nb 110 | np 111 | Nb 112 | Np 113 | pol 114 | pow 115 | m.in 116 | pt 117 | ps 118 | Pt 119 | Ps 120 | cdn 121 | jw 122 | ryc 123 | rys 124 | Ryc 125 | Rys 126 | tj 127 | tzw 128 | Tzw 129 | tzn 130 | zob 131 | ang 132 | ub 133 | ul 134 | pw 135 | pn 136 | pl 137 | al 138 | k 139 | n 140 | nr #NUMERIC_ONLY# 141 | Nr #NUMERIC_ONLY# 142 | ww 143 | wł 144 | ur 145 | zm 146 | żyd 147 | żarg 148 | żyw 149 | wył 150 | bp 151 | bp 152 | wyst 153 | tow 154 | Tow 155 | o 156 | sp 157 | Sp 158 | st 159 | spółdz 160 | Spółdz 161 | społ 162 | spółgł 163 | stoł 164 | stow 165 | Stoł 166 | Stow 167 | zn 168 | zew 169 | zewn 170 | zdr 171 | zazw 172 | zast 173 | zaw 174 | zał 175 | zal 176 | zam 177 | zak 178 | zakł 179 | zagr 180 | zach 181 | adw 182 | Adw 183 | lek 184 | Lek 185 | med 186 | mec 187 | Mec 188 | doc 189 | Doc 190 | dyw 191 | dyr 192 | Dyw 193 | Dyr 194 | inż 195 | Inż 196 | mgr 197 | Mgr 198 | dh 199 | dr 200 | Dh 201 | Dr 202 | p 203 | P 204 | red 205 | Red 206 | prof 207 | prok 208 | Prof 209 | Prok 210 | hab 211 | płk 212 | Płk 213 | nadkom 214 | Nadkom 215 | podkom 216 | Podkom 217 | ks 218 | Ks 219 | gen 220 | Gen 221 | por 222 | Por 223 | reż 224 | Reż 225 | przyp 226 | Przyp 227 | śp 228 | św 229 | śW 230 | Śp 231 | Św 232 | ŚW 233 | szer 234 | Szer 235 | pkt #NUMERIC_ONLY# 236 | str #NUMERIC_ONLY# 237 | tab #NUMERIC_ONLY# 238 | Tab #NUMERIC_ONLY# 239 | tel 240 | ust #NUMERIC_ONLY# 241 | par #NUMERIC_ONLY# 242 | poz 243 | pok 244 | oo 245 | oO 246 | Oo 247 | OO 248 | r #NUMERIC_ONLY# 249 | l #NUMERIC_ONLY# 250 | s #NUMERIC_ONLY# 251 | najśw 252 | Najśw 253 | A 254 | B 255 | C 256 | D 257 | E 258 | F 259 | G 260 | H 261 | I 262 | J 263 | K 264 | L 265 | M 266 | N 267 | O 268 | P 269 | Q 270 | R 271 | S 272 | T 273 | U 274 | V 275 | W 276 | X 277 | Y 278 | Z 279 | Ś 280 | Ć 281 | Ż 282 | Ź 283 | Dz 284 | -------------------------------------------------------------------------------- /tools/nonbreaking_prefixes/nonbreaking_prefix.ro: -------------------------------------------------------------------------------- 1 | A 2 | B 3 | C 4 | D 5 | E 6 | F 7 | G 8 | H 9 | I 10 | J 11 | K 12 | L 13 | M 14 | N 15 | O 16 | P 17 | Q 18 | R 19 | S 20 | T 21 | U 22 | V 23 | W 24 | X 25 | Y 26 | Z 27 | dpdv 28 | etc 29 | șamd 30 | M.Ap.N 31 | dl 32 | Dl 33 | d-na 34 | D-na 35 | dvs 36 | Dvs 37 | pt 38 | Pt 39 | -------------------------------------------------------------------------------- /tools/nonbreaking_prefixes/nonbreaking_prefix.ru: -------------------------------------------------------------------------------- 1 | # added Cyrillic uppercase letters [А-Я] 2 | # removed 000D carriage return (this is not removed by chomp in tokenizer.perl, and prevents recognition of the prefixes) 3 | # edited by Kate Young (nspaceanalysis@earthlink.net) 21 May 2013 4 | А 5 | Б 6 | В 7 | Г 8 | Д 9 | Е 10 | Ж 11 | З 12 | И 13 | Й 14 | К 15 | Л 16 | М 17 | Н 18 | О 19 | П 20 | Р 21 | С 22 | Т 23 | У 24 | Ф 25 | Х 26 | Ц 27 | Ч 28 | Ш 29 | Щ 30 | Ъ 31 | Ы 32 | Ь 33 | Э 34 | Ю 35 | Я 36 | A 37 | B 38 | C 39 | D 40 | E 41 | F 42 | G 43 | H 44 | I 45 | J 46 | K 47 | L 48 | M 49 | N 50 | O 51 | P 52 | Q 53 | R 54 | S 55 | T 56 | U 57 | V 58 | W 59 | X 60 | Y 61 | Z 62 | 0гг 63 | 1гг 64 | 2гг 65 | 3гг 66 | 4гг 67 | 5гг 68 | 6гг 69 | 7гг 70 | 8гг 71 | 9гг 72 | 0г 73 | 1г 74 | 2г 75 | 3г 76 | 4г 77 | 5г 78 | 6г 79 | 7г 80 | 8г 81 | 9г 82 | Xвв 83 | Vвв 84 | Iвв 85 | Lвв 86 | Mвв 87 | Cвв 88 | Xв 89 | Vв 90 | Iв 91 | Lв 92 | Mв 93 | Cв 94 | 0м 95 | 1м 96 | 2м 97 | 3м 98 | 4м 99 | 5м 100 | 6м 101 | 7м 102 | 8м 103 | 9м 104 | 0мм 105 | 1мм 106 | 2мм 107 | 3мм 108 | 4мм 109 | 5мм 110 | 6мм 111 | 7мм 112 | 8мм 113 | 9мм 114 | 0см 115 | 1см 116 | 2см 117 | 3см 118 | 4см 119 | 5см 120 | 6см 121 | 7см 122 | 8см 123 | 9см 124 | 0дм 125 | 1дм 126 | 2дм 127 | 3дм 128 | 4дм 129 | 5дм 130 | 6дм 131 | 7дм 132 | 8дм 133 | 9дм 134 | 0л 135 | 1л 136 | 2л 137 | 3л 138 | 4л 139 | 5л 140 | 6л 141 | 7л 142 | 8л 143 | 9л 144 | 0км 145 | 1км 146 | 2км 147 | 3км 148 | 4км 149 | 5км 150 | 6км 151 | 7км 152 | 8км 153 | 9км 154 | 0га 155 | 1га 156 | 2га 157 | 3га 158 | 4га 159 | 5га 160 | 6га 161 | 7га 162 | 8га 163 | 9га 164 | 0кг 165 | 1кг 166 | 2кг 167 | 3кг 168 | 4кг 169 | 5кг 170 | 6кг 171 | 7кг 172 | 8кг 173 | 9кг 174 | 0т 175 | 1т 176 | 2т 177 | 3т 178 | 4т 179 | 5т 180 | 6т 181 | 7т 182 | 8т 183 | 9т 184 | 0г 185 | 1г 186 | 2г 187 | 3г 188 | 4г 189 | 5г 190 | 6г 191 | 7г 192 | 8г 193 | 9г 194 | 0мг 195 | 1мг 196 | 2мг 197 | 3мг 198 | 4мг 199 | 5мг 200 | 6мг 201 | 7мг 202 | 8мг 203 | 9мг 204 | бульв 205 | в 206 | вв 207 | г 208 | га 209 | гг 210 | гл 211 | гос 212 | д 213 | дм 214 | доп 215 | др 216 | е 217 | ед 218 | ед 219 | зам 220 | и 221 | инд 222 | исп 223 | Исп 224 | к 225 | кап 226 | кг 227 | кв 228 | кл 229 | км 230 | кол 231 | комн 232 | коп 233 | куб 234 | л 235 | лиц 236 | лл 237 | м 238 | макс 239 | мг 240 | мин 241 | мл 242 | млн 243 | млрд 244 | мм 245 | н 246 | наб 247 | нач 248 | неуд 249 | ном 250 | о 251 | обл 252 | обр 253 | общ 254 | ок 255 | ост 256 | отл 257 | п 258 | пер 259 | перераб 260 | пл 261 | пос 262 | пр 263 | просп 264 | проф 265 | р 266 | ред 267 | руб 268 | с 269 | сб 270 | св 271 | см 272 | соч 273 | ср 274 | ст 275 | стр 276 | т 277 | тел 278 | Тел 279 | тех 280 | тт 281 | туп 282 | тыс 283 | уд 284 | ул 285 | уч 286 | физ 287 | х 288 | хор 289 | ч 290 | чел 291 | шт 292 | экз 293 | э 294 | -------------------------------------------------------------------------------- /tools/nonbreaking_prefixes/nonbreaking_prefix.sk: -------------------------------------------------------------------------------- 1 | Bc 2 | Mgr 3 | RNDr 4 | PharmDr 5 | PhDr 6 | JUDr 7 | PaedDr 8 | ThDr 9 | Ing 10 | MUDr 11 | MDDr 12 | MVDr 13 | Dr 14 | ThLic 15 | PhD 16 | ArtD 17 | ThDr 18 | Dr 19 | DrSc 20 | CSs 21 | prof 22 | obr 23 | Obr 24 | Č 25 | č 26 | absol 27 | adj 28 | admin 29 | adr 30 | Adr 31 | adv 32 | advok 33 | afr 34 | ak 35 | akad 36 | akc 37 | akuz 38 | et 39 | al 40 | alch 41 | amer 42 | anat 43 | angl 44 | Angl 45 | anglosas 46 | anorg 47 | ap 48 | apod 49 | arch 50 | archeol 51 | archit 52 | arg 53 | art 54 | astr 55 | astrol 56 | astron 57 | atp 58 | atď 59 | austr 60 | Austr 61 | aut 62 | belg 63 | Belg 64 | bibl 65 | Bibl 66 | biol 67 | bot 68 | bud 69 | bás 70 | býv 71 | cest 72 | chem 73 | cirk 74 | csl 75 | čs 76 | Čs 77 | dat 78 | dep 79 | det 80 | dial 81 | diaľ 82 | dipl 83 | distrib 84 | dokl 85 | dosl 86 | dopr 87 | dram 88 | duš 89 | dv 90 | dvojčl 91 | dór 92 | ekol 93 | ekon 94 | el 95 | elektr 96 | elektrotech 97 | energet 98 | epic 99 | est 100 | etc 101 | etonym 102 | eufem 103 | európ 104 | Európ 105 | ev 106 | evid 107 | expr 108 | fa 109 | fam 110 | farm 111 | fem 112 | feud 113 | fil 114 | filat 115 | filoz 116 | fi 117 | fon 118 | form 119 | fot 120 | fr 121 | Fr 122 | franc 123 | Franc 124 | fraz 125 | fut 126 | fyz 127 | fyziol 128 | garb 129 | gen 130 | genet 131 | genpor 132 | geod 133 | geogr 134 | geol 135 | geom 136 | germ 137 | gr 138 | Gr 139 | gréc 140 | Gréc 141 | gréckokat 142 | hebr 143 | herald 144 | hist 145 | hlav 146 | hosp 147 | hromad 148 | hud 149 | hypok 150 | ident 151 | i.e 152 | ident 153 | imp 154 | impf 155 | indoeur 156 | inf 157 | inform 158 | instr 159 | int 160 | interj 161 | inšt 162 | inštr 163 | iron 164 | jap 165 | Jap 166 | jaz 167 | jedn 168 | juhoamer 169 | juhových 170 | juhozáp 171 | juž 172 | kanad 173 | Kanad 174 | kanc 175 | kapit 176 | kpt 177 | kart 178 | katastr 179 | knih 180 | kniž 181 | komp 182 | konj 183 | konkr 184 | kozmet 185 | krajč 186 | kresť 187 | kt 188 | kuch 189 | lat 190 | latinskoamer 191 | lek 192 | lex 193 | lingv 194 | lit 195 | litur 196 | log 197 | lok 198 | max 199 | Max 200 | maď 201 | Maď 202 | medzinár 203 | mest 204 | metr 205 | mil 206 | Mil 207 | min 208 | Min 209 | miner 210 | ml 211 | mld 212 | mn 213 | mod 214 | mytol 215 | napr 216 | nar 217 | Nar 218 | nasl 219 | nedok 220 | neg 221 | negat 222 | neklas 223 | nem 224 | Nem 225 | neodb 226 | neos 227 | neskl 228 | nesklon 229 | nespis 230 | nespráv 231 | neved 232 | než 233 | niekt 234 | niž 235 | nom 236 | náb 237 | nákl 238 | námor 239 | nár 240 | obch 241 | obj 242 | obv 243 | obyč 244 | obč 245 | občian 246 | odb 247 | odd 248 | ods 249 | ojed 250 | okr 251 | Okr 252 | opt 253 | opyt 254 | org 255 | os 256 | osob 257 | ot 258 | ovoc 259 | par 260 | part 261 | pejor 262 | pers 263 | pf 264 | Pf 265 | P.f 266 | p.f 267 | pl 268 | Plk 269 | pod 270 | podst 271 | pokl 272 | polit 273 | politol 274 | polygr 275 | pomn 276 | popl 277 | por 278 | porad 279 | porov 280 | posch 281 | potrav 282 | použ 283 | poz 284 | pozit 285 | poľ 286 | poľno 287 | poľnohosp 288 | poľov 289 | pošt 290 | pož 291 | prac 292 | predl 293 | pren 294 | prep 295 | preuk 296 | priezv 297 | Priezv 298 | privl 299 | prof 300 | práv 301 | príd 302 | príj 303 | prík 304 | príp 305 | prír 306 | prísl 307 | príslov 308 | príč 309 | psych 310 | publ 311 | pís 312 | písm 313 | pôv 314 | refl 315 | reg 316 | rep 317 | resp 318 | rozk 319 | rozlič 320 | rozpráv 321 | roč 322 | Roč 323 | ryb 324 | rádiotech 325 | rím 326 | samohl 327 | semest 328 | sev 329 | severoamer 330 | severových 331 | severozáp 332 | sg 333 | skr 334 | skup 335 | sl 336 | Sloven 337 | soc 338 | soch 339 | sociol 340 | sp 341 | spol 342 | Spol 343 | spoloč 344 | spoluhl 345 | správ 346 | spôs 347 | st 348 | star 349 | starogréc 350 | starorím 351 | s.r.o 352 | stol 353 | stor 354 | str 355 | stredoamer 356 | stredoškol 357 | subj 358 | subst 359 | superl 360 | sv 361 | sz 362 | súkr 363 | súp 364 | súvzť 365 | tal 366 | Tal 367 | tech 368 | tel 369 | Tel 370 | telef 371 | teles 372 | telev 373 | teol 374 | trans 375 | turist 376 | tuzem 377 | typogr 378 | tzn 379 | tzv 380 | ukaz 381 | ul 382 | Ul 383 | umel 384 | univ 385 | ust 386 | ved 387 | vedľ 388 | verb 389 | veter 390 | vin 391 | viď 392 | vl 393 | vod 394 | vodohosp 395 | pnl 396 | vulg 397 | vyj 398 | vys 399 | vysokoškol 400 | vzťaž 401 | vôb 402 | vých 403 | výd 404 | výrob 405 | výsk 406 | výsl 407 | výtv 408 | výtvar 409 | význ 410 | včel 411 | vš 412 | všeob 413 | zahr 414 | zar 415 | zariad 416 | zast 417 | zastar 418 | zastaráv 419 | zb 420 | zdravot 421 | združ 422 | zjemn 423 | zlat 424 | zn 425 | Zn 426 | zool 427 | zr 428 | zried 429 | zv 430 | záhr 431 | zák 432 | zákl 433 | zám 434 | záp 435 | západoeur 436 | zázn 437 | územ 438 | účt 439 | čast 440 | čes 441 | Čes 442 | čl 443 | čísl 444 | živ 445 | pr 446 | fak 447 | Kr 448 | p.n.l 449 | A 450 | B 451 | C 452 | D 453 | E 454 | F 455 | G 456 | H 457 | I 458 | J 459 | K 460 | L 461 | M 462 | N 463 | O 464 | P 465 | Q 466 | R 467 | S 468 | T 469 | U 470 | V 471 | W 472 | X 473 | Y 474 | Z 475 | -------------------------------------------------------------------------------- /tools/nonbreaking_prefixes/nonbreaking_prefix.sl: -------------------------------------------------------------------------------- 1 | dr 2 | Dr 3 | itd 4 | itn 5 | št #NUMERIC_ONLY# 6 | Št #NUMERIC_ONLY# 7 | d 8 | jan 9 | Jan 10 | feb 11 | Feb 12 | mar 13 | Mar 14 | apr 15 | Apr 16 | jun 17 | Jun 18 | jul 19 | Jul 20 | avg 21 | Avg 22 | sept 23 | Sept 24 | sep 25 | Sep 26 | okt 27 | Okt 28 | nov 29 | Nov 30 | dec 31 | Dec 32 | tj 33 | Tj 34 | npr 35 | Npr 36 | sl 37 | Sl 38 | op 39 | Op 40 | gl 41 | Gl 42 | oz 43 | Oz 44 | prev 45 | dipl 46 | ing 47 | prim 48 | Prim 49 | cf 50 | Cf 51 | gl 52 | Gl 53 | A 54 | B 55 | C 56 | D 57 | E 58 | F 59 | G 60 | H 61 | I 62 | J 63 | K 64 | L 65 | M 66 | N 67 | O 68 | P 69 | Q 70 | R 71 | S 72 | T 73 | U 74 | V 75 | W 76 | X 77 | Y 78 | Z 79 | -------------------------------------------------------------------------------- /tools/nonbreaking_prefixes/nonbreaking_prefix.sv: -------------------------------------------------------------------------------- 1 | #single upper case letter are usually initials 2 | A 3 | B 4 | C 5 | D 6 | E 7 | F 8 | G 9 | H 10 | I 11 | J 12 | K 13 | L 14 | M 15 | N 16 | O 17 | P 18 | Q 19 | R 20 | S 21 | T 22 | U 23 | V 24 | W 25 | X 26 | Y 27 | Z 28 | #misc abbreviations 29 | AB 30 | G 31 | VG 32 | dvs 33 | etc 34 | from 35 | iaf 36 | jfr 37 | kl 38 | kr 39 | mao 40 | mfl 41 | mm 42 | osv 43 | pga 44 | tex 45 | tom 46 | vs 47 | -------------------------------------------------------------------------------- /tools/nonbreaking_prefixes/nonbreaking_prefix.ta: -------------------------------------------------------------------------------- 1 | #Anything in this file, followed by a period (and an upper-case word), does NOT indicate an end-of-sentence marker. 2 | #Special cases are included for prefixes that ONLY appear before 0-9 numbers. 3 | 4 | #any single upper case letter followed by a period is not a sentence ender (excluding I occasionally, but we leave it in) 5 | #usually upper case letters are initials in a name 6 | அ 7 | ஆ 8 | இ 9 | ஈ 10 | உ 11 | ஊ 12 | எ 13 | ஏ 14 | ஐ 15 | ஒ 16 | ஓ 17 | ஔ 18 | ஃ 19 | க 20 | கா 21 | கி 22 | கீ 23 | கு 24 | கூ 25 | கெ 26 | கே 27 | கை 28 | கொ 29 | கோ 30 | கௌ 31 | க் 32 | ச 33 | சா 34 | சி 35 | சீ 36 | சு 37 | சூ 38 | செ 39 | சே 40 | சை 41 | சொ 42 | சோ 43 | சௌ 44 | ச் 45 | ட 46 | டா 47 | டி 48 | டீ 49 | டு 50 | டூ 51 | டெ 52 | டே 53 | டை 54 | டொ 55 | டோ 56 | டௌ 57 | ட் 58 | த 59 | தா 60 | தி 61 | தீ 62 | து 63 | தூ 64 | தெ 65 | தே 66 | தை 67 | தொ 68 | தோ 69 | தௌ 70 | த் 71 | ப 72 | பா 73 | பி 74 | பீ 75 | பு 76 | பூ 77 | பெ 78 | பே 79 | பை 80 | பொ 81 | போ 82 | பௌ 83 | ப் 84 | ற 85 | றா 86 | றி 87 | றீ 88 | று 89 | றூ 90 | றெ 91 | றே 92 | றை 93 | றொ 94 | றோ 95 | றௌ 96 | ற் 97 | ய 98 | யா 99 | யி 100 | யீ 101 | யு 102 | யூ 103 | யெ 104 | யே 105 | யை 106 | யொ 107 | யோ 108 | யௌ 109 | ய் 110 | ர 111 | ரா 112 | ரி 113 | ரீ 114 | ரு 115 | ரூ 116 | ரெ 117 | ரே 118 | ரை 119 | ரொ 120 | ரோ 121 | ரௌ 122 | ர் 123 | ல 124 | லா 125 | லி 126 | லீ 127 | லு 128 | லூ 129 | லெ 130 | லே 131 | லை 132 | லொ 133 | லோ 134 | லௌ 135 | ல் 136 | வ 137 | வா 138 | வி 139 | வீ 140 | வு 141 | வூ 142 | வெ 143 | வே 144 | வை 145 | வொ 146 | வோ 147 | வௌ 148 | வ் 149 | ள 150 | ளா 151 | ளி 152 | ளீ 153 | ளு 154 | ளூ 155 | ளெ 156 | ளே 157 | ளை 158 | ளொ 159 | ளோ 160 | ளௌ 161 | ள் 162 | ழ 163 | ழா 164 | ழி 165 | ழீ 166 | ழு 167 | ழூ 168 | ழெ 169 | ழே 170 | ழை 171 | ழொ 172 | ழோ 173 | ழௌ 174 | ழ் 175 | ங 176 | ஙா 177 | ஙி 178 | ஙீ 179 | ஙு 180 | ஙூ 181 | ஙெ 182 | ஙே 183 | ஙை 184 | ஙொ 185 | ஙோ 186 | ஙௌ 187 | ங் 188 | ஞ 189 | ஞா 190 | ஞி 191 | ஞீ 192 | ஞு 193 | ஞூ 194 | ஞெ 195 | ஞே 196 | ஞை 197 | ஞொ 198 | ஞோ 199 | ஞௌ 200 | ஞ் 201 | ண 202 | ணா 203 | ணி 204 | ணீ 205 | ணு 206 | ணூ 207 | ணெ 208 | ணே 209 | ணை 210 | ணொ 211 | ணோ 212 | ணௌ 213 | ண் 214 | ந 215 | நா 216 | நி 217 | நீ 218 | நு 219 | நூ 220 | நெ 221 | நே 222 | நை 223 | நொ 224 | நோ 225 | நௌ 226 | ந் 227 | ம 228 | மா 229 | மி 230 | மீ 231 | மு 232 | மூ 233 | மெ 234 | மே 235 | மை 236 | மொ 237 | மோ 238 | மௌ 239 | ம் 240 | ன 241 | னா 242 | னி 243 | னீ 244 | னு 245 | னூ 246 | னெ 247 | னே 248 | னை 249 | னொ 250 | னோ 251 | னௌ 252 | ன் 253 | 254 | 255 | #List of titles. These are often followed by upper-case names, but do not indicate sentence breaks 256 | திரு 257 | திருமதி 258 | வண 259 | கௌரவ 260 | 261 | 262 | #misc - odd period-ending items that NEVER indicate breaks (p.m. does NOT fall into this category - it sometimes ends a sentence) 263 | உ.ம் 264 | #கா.ம் 265 | #எ.ம் 266 | 267 | 268 | #Numbers only. These should only induce breaks when followed by a numeric sequence 269 | # add NUMERIC_ONLY after the word for this function 270 | #This case is mostly for the english "No." which can either be a sentence of its own, or 271 | #if followed by a number, a non-breaking prefix 272 | No #NUMERIC_ONLY# 273 | Nos 274 | Art #NUMERIC_ONLY# 275 | Nr 276 | pp #NUMERIC_ONLY# 277 | -------------------------------------------------------------------------------- /tools/nonbreaking_prefixes/nonbreaking_prefix.yue: -------------------------------------------------------------------------------- 1 | # 2 | # Cantonese (Chinese) 3 | # 4 | # Anything in this file, followed by a period, 5 | # does NOT indicate an end-of-sentence marker. 6 | # 7 | # English/Euro-language given-name initials (appearing in 8 | # news, periodicals, etc.) 9 | A 10 | Ā 11 | B 12 | C 13 | Č 14 | D 15 | E 16 | Ē 17 | F 18 | G 19 | Ģ 20 | H 21 | I 22 | Ī 23 | J 24 | K 25 | Ķ 26 | L 27 | Ļ 28 | M 29 | N 30 | Ņ 31 | O 32 | P 33 | Q 34 | R 35 | S 36 | Š 37 | T 38 | U 39 | Ū 40 | V 41 | W 42 | X 43 | Y 44 | Z 45 | Ž 46 | 47 | # Numbers only. These should only induce breaks when followed by 48 | # a numeric sequence. 49 | # Add NUMERIC_ONLY after the word for this function. This case is 50 | # mostly for the english "No." which can either be a sentence of its 51 | # own, or if followed by a number, a non-breaking prefix. 52 | No #NUMERIC_ONLY# 53 | Nr #NUMERIC_ONLY# 54 | -------------------------------------------------------------------------------- /tools/nonbreaking_prefixes/nonbreaking_prefix.zh: -------------------------------------------------------------------------------- 1 | # 2 | # Mandarin (Chinese) 3 | # 4 | # Anything in this file, followed by a period, 5 | # does NOT indicate an end-of-sentence marker. 6 | # 7 | # English/Euro-language given-name initials (appearing in 8 | # news, periodicals, etc.) 9 | A 10 | Ā 11 | B 12 | C 13 | Č 14 | D 15 | E 16 | Ē 17 | F 18 | G 19 | Ģ 20 | H 21 | I 22 | Ī 23 | J 24 | K 25 | Ķ 26 | L 27 | Ļ 28 | M 29 | N 30 | Ņ 31 | O 32 | P 33 | Q 34 | R 35 | S 36 | Š 37 | T 38 | U 39 | Ū 40 | V 41 | W 42 | X 43 | Y 44 | Z 45 | Ž 46 | 47 | # Numbers only. These should only induce breaks when followed by 48 | # a numeric sequence. 49 | # Add NUMERIC_ONLY after the word for this function. This case is 50 | # mostly for the english "No." which can either be a sentence of its 51 | # own, or if followed by a number, a non-breaking prefix. 52 | No #NUMERIC_ONLY# 53 | Nr #NUMERIC_ONLY# 54 | -------------------------------------------------------------------------------- /tools/release_model.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import argparse 3 | import torch 4 | 5 | if __name__ == "__main__": 6 | parser = argparse.ArgumentParser( 7 | description="Removes the optim data of PyTorch models") 8 | parser.add_argument("--model", "-m", 9 | help="The model filename (*.pt)", required=True) 10 | parser.add_argument("--output", "-o", 11 | help="The output filename (*.pt)", required=True) 12 | opt = parser.parse_args() 13 | 14 | model = torch.load(opt.model) 15 | model['optim'] = None 16 | torch.save(model, opt.output) 17 | -------------------------------------------------------------------------------- /tools/test_rouge.py: -------------------------------------------------------------------------------- 1 | # -*- encoding: utf-8 -*- 2 | import argparse 3 | import os 4 | import time 5 | import pyrouge 6 | import shutil 7 | import sys 8 | 9 | 10 | def test_rouge(cand, ref): 11 | """Calculate ROUGE scores of sequences passed as an iterator 12 | e.g. a list of str, an open file, StringIO or even sys.stdin 13 | """ 14 | current_time = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime()) 15 | tmp_dir = ".rouge-tmp-{}".format(current_time) 16 | try: 17 | if not os.path.isdir(tmp_dir): 18 | os.mkdir(tmp_dir) 19 | os.mkdir(tmp_dir + "/candidate") 20 | os.mkdir(tmp_dir + "/reference") 21 | candidates = [line.strip() for line in open(cand, 'r')] 22 | references = [line.strip() for line in open(ref, 'r')] 23 | assert len(candidates) == len(references) 24 | cnt = len(candidates) 25 | for i in range(cnt): 26 | if len(references[i]) < 1: 27 | continue 28 | with open(tmp_dir + "/candidate/cand.{}.txt".format(i), "w", 29 | encoding="utf-8") as f: 30 | f.write(candidates[i]) 31 | with open(tmp_dir + "/reference/ref.{}.txt".format(i), "w", 32 | encoding="utf-8") as f: 33 | f.write(references[i]) 34 | rouge_dir = '/opt/ROUGE' 35 | rouge_args = '-e /opt/ROUGE/data -n 4 -m -2 4 -u -c 95 -r 1000 -f A -p 0.5 -t 0 -a -d' 36 | r = pyrouge.Rouge155(rouge_dir, rouge_args) 37 | r.model_dir = tmp_dir + "/reference/" 38 | r.system_dir = tmp_dir + "/candidate/" 39 | r.model_filename_pattern = 'ref.#ID#.txt' 40 | r.system_filename_pattern = 'cand.(\d+).txt' 41 | rouge_results = r.convert_and_evaluate() 42 | results_dict = r.output_to_dict(rouge_results) 43 | return results_dict 44 | finally: 45 | pass 46 | if os.path.isdir(tmp_dir): 47 | shutil.rmtree(tmp_dir) 48 | 49 | 50 | def rouge_results_to_str(results_dict): 51 | return ">> ROUGE(1/2/3/L/SU4): {:.2f}/{:.2f}/{:.2f}/{:.2f}".format( 52 | results_dict["rouge_1_f_score"] * 100, 53 | results_dict["rouge_2_f_score"] * 100, 54 | results_dict["rouge_3_f_score"] * 100, 55 | results_dict["rouge_l_f_score"] * 100) 56 | 57 | 58 | if __name__ == "__main__": 59 | parser = argparse.ArgumentParser() 60 | parser.add_argument('-c', type=str, default="candidate.txt", 61 | help='candidate file') 62 | parser.add_argument('-r', type=str, default="reference.txt", 63 | help='reference file') 64 | args = parser.parse_args() 65 | if args.c.upper() == "STDIN": 66 | args.c = sys.stdin 67 | results_dict = test_rouge(args.c, args.r) 68 | print(rouge_results_to_str(results_dict)) 69 | -------------------------------------------------------------------------------- /translate.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from __future__ import division, unicode_literals 3 | import argparse 4 | 5 | from onmt.translate.Translator import make_translator 6 | 7 | import onmt.io 8 | import onmt.translate 9 | import onmt 10 | import onmt.ModelConstructor 11 | import onmt.modules 12 | import onmt.opts 13 | 14 | 15 | def main(opt): 16 | translator = make_translator(opt, report_score=True) 17 | translator.translate(opt.src_dir, opt.src, opt.tgt, opt.phrase_table, opt.global_phrase_table, 18 | opt.batch_size, opt.attn_debug, opt.side_src, opt.side_tgt, opt.oracle, opt.lower, 19 | psi=opt.psi, theta=opt.theta, k=opt.k) 20 | 21 | 22 | if __name__ == "__main__": 23 | parser = argparse.ArgumentParser( 24 | description='translate.py', 25 | formatter_class=argparse.ArgumentDefaultsHelpFormatter) 26 | onmt.opts.add_md_help_argument(parser) 27 | onmt.opts.translate_opts(parser) 28 | 29 | opt = parser.parse_args() 30 | main(opt) 31 | --------------------------------------------------------------------------------