From 50682fc3727666df5dc4f5f294aa0b6913e31df5 Mon Sep 17 00:00:00 2001 From: Doruk Dumlu Date: Sat, 28 Nov 2026 11:11:50 -0500 Subject: [PATCH 1/6] Turkish TN MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds Turkish text normalization: cardinal, ordinal, decimal, fraction, money, measure (with percent), date, time, telephone, whitelist and word. - Suffixes written after an apostrophe are attached to the spoken number ("4'e" -> "dörde", "1990'lı" -> "bin dokuz yüz doksanlı", "%14'ü" -> "yüzde on dördü"); "dört" softens before a vowel. - "5." is an ordinal only before a lower-case word ("3. taksit" -> "üçüncü taksit"); at the end of a sentence it stays a number. - Fractions are read denominator first ("3/4" -> "dörtte üç"), dates day-month-year, the percent sign first. Signed-off-by: Doruk Dumlu --- Jenkinsfile | 13 +- .../text_normalization/normalize.py | 5 +- .../text_normalization/run_evaluate.py | 2 +- .../text_normalization/tr/__init__.py | 13 ++ .../text_normalization/tr/data/__init__.py | 13 ++ .../tr/data/dates/__init__.py | 13 ++ .../tr/data/dates/month_names.tsv | 24 +++ .../tr/data/dates/months.tsv | 12 ++ .../tr/data/fractions/__init__.py | 13 ++ .../data/fractions/denominator_locative.tsv | 22 +++ .../tr/data/fractions/fraction_symbols.tsv | 7 + .../tr/data/measures/__init__.py | 13 ++ .../tr/data/measures/units.tsv | 31 ++++ .../tr/data/money/__init__.py | 13 ++ .../tr/data/money/currency.tsv | 9 + .../tr/data/money/lira_suffix.tsv | 14 ++ .../tr/data/number/__init__.py | 13 ++ .../tr/data/number/digit.tsv | 9 + .../tr/data/number/tens.tsv | 9 + .../tr/data/number/zero.tsv | 1 + .../tr/data/ordinals/__init__.py | 13 ++ .../tr/data/ordinals/ordinal_endings.tsv | 25 +++ .../text_normalization/tr/data/whitelist.tsv | 22 +++ .../text_normalization/tr/graph_utils.py | 47 +++++ .../text_normalization/tr/taggers/__init__.py | 13 ++ .../text_normalization/tr/taggers/cardinal.py | 139 +++++++++++++++ .../text_normalization/tr/taggers/date.py | 101 +++++++++++ .../text_normalization/tr/taggers/decimal.py | 79 +++++++++ .../text_normalization/tr/taggers/fraction.py | 85 +++++++++ .../text_normalization/tr/taggers/measure.py | 68 ++++++++ .../text_normalization/tr/taggers/money.py | 93 ++++++++++ .../text_normalization/tr/taggers/ordinal.py | 57 ++++++ .../tr/taggers/telephone.py | 85 +++++++++ .../text_normalization/tr/taggers/time.py | 82 +++++++++ .../tr/taggers/tokenize_and_classify.py | 164 ++++++++++++++++++ .../tr/taggers/whitelist.py | 56 ++++++ .../text_normalization/tr/taggers/word.py | 34 ++++ .../text_normalization/tr/utils.py | 42 +++++ .../tr/verbalizers/__init__.py | 13 ++ .../tr/verbalizers/cardinal.py | 43 +++++ .../text_normalization/tr/verbalizers/date.py | 51 ++++++ .../tr/verbalizers/decimal.py | 50 ++++++ .../tr/verbalizers/fraction.py | 53 ++++++ .../tr/verbalizers/measure.py | 47 +++++ .../tr/verbalizers/money.py | 53 ++++++ .../tr/verbalizers/ordinal.py | 40 +++++ .../tr/verbalizers/telephone.py | 46 +++++ .../text_normalization/tr/verbalizers/time.py | 50 ++++++ .../tr/verbalizers/verbalize.py | 55 ++++++ .../tr/verbalizers/verbalize_final.py | 74 ++++++++ tests/nemo_text_processing/tr/__init__.py | 13 ++ .../tr/data_text_normalization/__init__.py | 13 ++ .../test_cases_cardinal.txt | 26 +++ .../test_cases_date.txt | 9 + .../test_cases_decimal.txt | 10 ++ .../test_cases_fraction.txt | 10 ++ .../test_cases_measure.txt | 13 ++ .../test_cases_money.txt | 14 ++ .../test_cases_ordinal.txt | 12 ++ .../test_cases_telephone.txt | 8 + .../test_cases_time.txt | 11 ++ .../test_cases_whitelist.txt | 8 + .../test_cases_word.txt | 5 + .../nemo_text_processing/tr/test_cardinal.py | 31 ++++ tests/nemo_text_processing/tr/test_date.py | 31 ++++ tests/nemo_text_processing/tr/test_decimal.py | 31 ++++ .../nemo_text_processing/tr/test_fraction.py | 31 ++++ tests/nemo_text_processing/tr/test_measure.py | 31 ++++ tests/nemo_text_processing/tr/test_money.py | 31 ++++ tests/nemo_text_processing/tr/test_ordinal.py | 31 ++++ .../tr/test_sparrowhawk_normalization.sh | 81 +++++++++ .../nemo_text_processing/tr/test_telephone.py | 31 ++++ tests/nemo_text_processing/tr/test_time.py | 31 ++++ .../nemo_text_processing/tr/test_whitelist.py | 31 ++++ tests/nemo_text_processing/tr/test_word.py | 31 ++++ .../pynini_export.py | 6 + 76 files changed, 2606 insertions(+), 3 deletions(-) create mode 100644 nemo_text_processing/text_normalization/tr/__init__.py create mode 100644 nemo_text_processing/text_normalization/tr/data/__init__.py create mode 100644 nemo_text_processing/text_normalization/tr/data/dates/__init__.py create mode 100644 nemo_text_processing/text_normalization/tr/data/dates/month_names.tsv create mode 100644 nemo_text_processing/text_normalization/tr/data/dates/months.tsv create mode 100644 nemo_text_processing/text_normalization/tr/data/fractions/__init__.py create mode 100644 nemo_text_processing/text_normalization/tr/data/fractions/denominator_locative.tsv create mode 100644 nemo_text_processing/text_normalization/tr/data/fractions/fraction_symbols.tsv create mode 100644 nemo_text_processing/text_normalization/tr/data/measures/__init__.py create mode 100644 nemo_text_processing/text_normalization/tr/data/measures/units.tsv create mode 100644 nemo_text_processing/text_normalization/tr/data/money/__init__.py create mode 100644 nemo_text_processing/text_normalization/tr/data/money/currency.tsv create mode 100644 nemo_text_processing/text_normalization/tr/data/money/lira_suffix.tsv create mode 100644 nemo_text_processing/text_normalization/tr/data/number/__init__.py create mode 100644 nemo_text_processing/text_normalization/tr/data/number/digit.tsv create mode 100644 nemo_text_processing/text_normalization/tr/data/number/tens.tsv create mode 100644 nemo_text_processing/text_normalization/tr/data/number/zero.tsv create mode 100644 nemo_text_processing/text_normalization/tr/data/ordinals/__init__.py create mode 100644 nemo_text_processing/text_normalization/tr/data/ordinals/ordinal_endings.tsv create mode 100644 nemo_text_processing/text_normalization/tr/data/whitelist.tsv create mode 100644 nemo_text_processing/text_normalization/tr/graph_utils.py create mode 100644 nemo_text_processing/text_normalization/tr/taggers/__init__.py create mode 100644 nemo_text_processing/text_normalization/tr/taggers/cardinal.py create mode 100644 nemo_text_processing/text_normalization/tr/taggers/date.py create mode 100644 nemo_text_processing/text_normalization/tr/taggers/decimal.py create mode 100644 nemo_text_processing/text_normalization/tr/taggers/fraction.py create mode 100644 nemo_text_processing/text_normalization/tr/taggers/measure.py create mode 100644 nemo_text_processing/text_normalization/tr/taggers/money.py create mode 100644 nemo_text_processing/text_normalization/tr/taggers/ordinal.py create mode 100644 nemo_text_processing/text_normalization/tr/taggers/telephone.py create mode 100644 nemo_text_processing/text_normalization/tr/taggers/time.py create mode 100644 nemo_text_processing/text_normalization/tr/taggers/tokenize_and_classify.py create mode 100644 nemo_text_processing/text_normalization/tr/taggers/whitelist.py create mode 100644 nemo_text_processing/text_normalization/tr/taggers/word.py create mode 100644 nemo_text_processing/text_normalization/tr/utils.py create mode 100644 nemo_text_processing/text_normalization/tr/verbalizers/__init__.py create mode 100644 nemo_text_processing/text_normalization/tr/verbalizers/cardinal.py create mode 100644 nemo_text_processing/text_normalization/tr/verbalizers/date.py create mode 100644 nemo_text_processing/text_normalization/tr/verbalizers/decimal.py create mode 100644 nemo_text_processing/text_normalization/tr/verbalizers/fraction.py create mode 100644 nemo_text_processing/text_normalization/tr/verbalizers/measure.py create mode 100644 nemo_text_processing/text_normalization/tr/verbalizers/money.py create mode 100644 nemo_text_processing/text_normalization/tr/verbalizers/ordinal.py create mode 100644 nemo_text_processing/text_normalization/tr/verbalizers/telephone.py create mode 100644 nemo_text_processing/text_normalization/tr/verbalizers/time.py create mode 100644 nemo_text_processing/text_normalization/tr/verbalizers/verbalize.py create mode 100644 nemo_text_processing/text_normalization/tr/verbalizers/verbalize_final.py create mode 100644 tests/nemo_text_processing/tr/__init__.py create mode 100644 tests/nemo_text_processing/tr/data_text_normalization/__init__.py create mode 100644 tests/nemo_text_processing/tr/data_text_normalization/test_cases_cardinal.txt create mode 100644 tests/nemo_text_processing/tr/data_text_normalization/test_cases_date.txt create mode 100644 tests/nemo_text_processing/tr/data_text_normalization/test_cases_decimal.txt create mode 100644 tests/nemo_text_processing/tr/data_text_normalization/test_cases_fraction.txt create mode 100644 tests/nemo_text_processing/tr/data_text_normalization/test_cases_measure.txt create mode 100644 tests/nemo_text_processing/tr/data_text_normalization/test_cases_money.txt create mode 100644 tests/nemo_text_processing/tr/data_text_normalization/test_cases_ordinal.txt create mode 100644 tests/nemo_text_processing/tr/data_text_normalization/test_cases_telephone.txt create mode 100644 tests/nemo_text_processing/tr/data_text_normalization/test_cases_time.txt create mode 100644 tests/nemo_text_processing/tr/data_text_normalization/test_cases_whitelist.txt create mode 100644 tests/nemo_text_processing/tr/data_text_normalization/test_cases_word.txt create mode 100644 tests/nemo_text_processing/tr/test_cardinal.py create mode 100644 tests/nemo_text_processing/tr/test_date.py create mode 100644 tests/nemo_text_processing/tr/test_decimal.py create mode 100644 tests/nemo_text_processing/tr/test_fraction.py create mode 100644 tests/nemo_text_processing/tr/test_measure.py create mode 100644 tests/nemo_text_processing/tr/test_money.py create mode 100644 tests/nemo_text_processing/tr/test_ordinal.py create mode 100644 tests/nemo_text_processing/tr/test_sparrowhawk_normalization.sh create mode 100644 tests/nemo_text_processing/tr/test_telephone.py create mode 100644 tests/nemo_text_processing/tr/test_time.py create mode 100644 tests/nemo_text_processing/tr/test_whitelist.py create mode 100644 tests/nemo_text_processing/tr/test_word.py diff --git a/Jenkinsfile b/Jenkinsfile index f5d114f84..a5a1a0a90 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -30,6 +30,7 @@ pipeline { JA_TN_CACHE='/home/jenkins/TestData/text_norm/ci/grammars/07-17-26-0' KO_TN_CACHE='/home/jenkins/TestData/text_norm/ci/grammars/09-15-26-0' HI_TN_CACHE='/home/jenkins/TestData/text_norm/ci/grammars/09-15-26-0' + TR_TN_CACHE='/home/jenkins/TestData/text_norm/ci/grammars/11-28-26-0' DEFAULT_TN_CACHE='/home/jenkins/TestData/text_norm/ci/grammars/06-08-23-0' } stages { @@ -176,7 +177,7 @@ pipeline { } } - stage('L0: Create FR TN/ITN & VI TN/ITN & HU TN & IT TN') { + stage('L0: Create FR TN/ITN & VI TN/ITN & HU TN & IT TN & TR TN') { when { anyOf { branch 'main' @@ -212,6 +213,11 @@ pipeline { sh 'CUDA_VISIBLE_DEVICES="" python nemo_text_processing/text_normalization/normalize.py --lang=hu --text="100" --cache_dir ${HU_TN_CACHE}' } } + stage('L0: TR TN grammars') { + steps { + sh 'CUDA_VISIBLE_DEVICES="" python nemo_text_processing/text_normalization/normalize.py --lang=tr --text="100" --cache_dir ${TR_TN_CACHE}' + } + } stage('L0: IT TN grammars') { steps { sh 'CUDA_VISIBLE_DEVICES="" python nemo_text_processing/text_normalization/normalize.py --lang=it --text="122" --cache_dir ${IT_TN_CACHE}' @@ -483,6 +489,11 @@ pipeline { sh 'CUDA_VISIBLE_DEVICES="" pytest tests/nemo_text_processing/ko/ -m "not pleasefixme" --cpu --tn_cache_dir ${KO_TN_CACHE}' } } + stage('L1: Run all TR TN tests (restore grammars from cache)') { + steps { + sh 'CUDA_VISIBLE_DEVICES="" pytest tests/nemo_text_processing/tr/ -m "not pleasefixme" --cpu --tn_cache_dir ${TR_TN_CACHE}' + } + } } } diff --git a/nemo_text_processing/text_normalization/normalize.py b/nemo_text_processing/text_normalization/normalize.py index c6a256eb5..75f1a64df 100644 --- a/nemo_text_processing/text_normalization/normalize.py +++ b/nemo_text_processing/text_normalization/normalize.py @@ -153,6 +153,9 @@ def __init__( elif lang == 'hu': from nemo_text_processing.text_normalization.hu.taggers.tokenize_and_classify import ClassifyFst from nemo_text_processing.text_normalization.hu.verbalizers.verbalize_final import VerbalizeFinalFst + elif lang == 'tr': + from nemo_text_processing.text_normalization.tr.taggers.tokenize_and_classify import ClassifyFst + from nemo_text_processing.text_normalization.tr.verbalizers.verbalize_final import VerbalizeFinalFst elif lang == 'zh': from nemo_text_processing.text_normalization.zh.taggers.tokenize_and_classify import ClassifyFst from nemo_text_processing.text_normalization.zh.verbalizers.verbalize_final import VerbalizeFinalFst @@ -745,7 +748,7 @@ def parse_args(): parser.add_argument( "--language", help="language", - choices=["en", "de", "es", "fr", "hu", "sv", "zh", "ar", "it", "hy", "ja", "hi", "ko", "vi", "pt"], + choices=["en", "de", "es", "fr", "hu", "sv", "zh", "ar", "it", "hy", "ja", "hi", "ko", "vi", "pt", "tr"], default="en", type=str, ) diff --git a/nemo_text_processing/text_normalization/run_evaluate.py b/nemo_text_processing/text_normalization/run_evaluate.py index 3a1964bbd..57679dc72 100644 --- a/nemo_text_processing/text_normalization/run_evaluate.py +++ b/nemo_text_processing/text_normalization/run_evaluate.py @@ -35,7 +35,7 @@ def parse_args(): parser.add_argument( "--lang", help="language", - choices=['ar', 'de', 'en', 'es', 'fr', 'hu', 'it', 'ru', 'sv', 'zh', 'hy', 'hi', 'ko', 'vi', 'pt'], + choices=['ar', 'de', 'en', 'es', 'fr', 'hu', 'it', 'ru', 'sv', 'zh', 'hy', 'hi', 'ko', 'vi', 'pt', 'tr'], default="en", type=str, ) diff --git a/nemo_text_processing/text_normalization/tr/__init__.py b/nemo_text_processing/text_normalization/tr/__init__.py new file mode 100644 index 000000000..9e3fb699d --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/nemo_text_processing/text_normalization/tr/data/__init__.py b/nemo_text_processing/text_normalization/tr/data/__init__.py new file mode 100644 index 000000000..9e3fb699d --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/data/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/nemo_text_processing/text_normalization/tr/data/dates/__init__.py b/nemo_text_processing/text_normalization/tr/data/dates/__init__.py new file mode 100644 index 000000000..9e3fb699d --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/data/dates/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/nemo_text_processing/text_normalization/tr/data/dates/month_names.tsv b/nemo_text_processing/text_normalization/tr/data/dates/month_names.tsv new file mode 100644 index 000000000..e04b965a8 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/data/dates/month_names.tsv @@ -0,0 +1,24 @@ +Ocak ocak +Şubat şubat +Mart mart +Nisan nisan +Mayıs mayıs +Haziran haziran +Temmuz temmuz +Ağustos ağustos +Eylül eylül +Ekim ekim +Kasım kasım +Aralık aralık +ocak ocak +şubat şubat +mart mart +nisan nisan +mayıs mayıs +haziran haziran +temmuz temmuz +ağustos ağustos +eylül eylül +ekim ekim +kasım kasım +aralık aralık diff --git a/nemo_text_processing/text_normalization/tr/data/dates/months.tsv b/nemo_text_processing/text_normalization/tr/data/dates/months.tsv new file mode 100644 index 000000000..ff3ce2bc6 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/data/dates/months.tsv @@ -0,0 +1,12 @@ +1 ocak +2 şubat +3 mart +4 nisan +5 mayıs +6 haziran +7 temmuz +8 ağustos +9 eylül +10 ekim +11 kasım +12 aralık diff --git a/nemo_text_processing/text_normalization/tr/data/fractions/__init__.py b/nemo_text_processing/text_normalization/tr/data/fractions/__init__.py new file mode 100644 index 000000000..9e3fb699d --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/data/fractions/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/nemo_text_processing/text_normalization/tr/data/fractions/denominator_locative.tsv b/nemo_text_processing/text_normalization/tr/data/fractions/denominator_locative.tsv new file mode 100644 index 000000000..05b8e046b --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/data/fractions/denominator_locative.tsv @@ -0,0 +1,22 @@ +bir birde +iki ikide +üç üçte +dört dörtte +beş beşte +altı altıda +yedi yedide +sekiz sekizde +dokuz dokuzda +on onda +yirmi yirmide +otuz otuzda +kırk kırkta +elli ellide +altmış altmışta +yetmiş yetmişte +seksen seksende +doksan doksanda +yüz yüzde +bin binde +milyon milyonda +milyar milyarda diff --git a/nemo_text_processing/text_normalization/tr/data/fractions/fraction_symbols.tsv b/nemo_text_processing/text_normalization/tr/data/fractions/fraction_symbols.tsv new file mode 100644 index 000000000..fb849671b --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/data/fractions/fraction_symbols.tsv @@ -0,0 +1,7 @@ +½ 1 2 +⅓ 1 3 +⅔ 2 3 +¼ 1 4 +¾ 3 4 +⅕ 1 5 +⅛ 1 8 diff --git a/nemo_text_processing/text_normalization/tr/data/measures/__init__.py b/nemo_text_processing/text_normalization/tr/data/measures/__init__.py new file mode 100644 index 000000000..9e3fb699d --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/data/measures/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/nemo_text_processing/text_normalization/tr/data/measures/units.tsv b/nemo_text_processing/text_normalization/tr/data/measures/units.tsv new file mode 100644 index 000000000..f0f26402e --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/data/measures/units.tsv @@ -0,0 +1,31 @@ +km kilometre +m metre +cm santimetre +mm milimetre +km² kilometrekare +m² metrekare +m2 metrekare +m³ metreküp +m3 metreküp +ha hektar +kg kilogram +g gram +mg miligram +lt litre +l litre +L litre +ml mililitre +°C santigrat derece +° derece +kWh kilovatsaat +kW kilovat +W vat +V volt +mAh miliamper saat +GB gigabayt +MB megabayt +KB kilobayt +TB terabayt +dk dakika +sn saniye +ms milisaniye diff --git a/nemo_text_processing/text_normalization/tr/data/money/__init__.py b/nemo_text_processing/text_normalization/tr/data/money/__init__.py new file mode 100644 index 000000000..9e3fb699d --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/data/money/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/nemo_text_processing/text_normalization/tr/data/money/currency.tsv b/nemo_text_processing/text_normalization/tr/data/money/currency.tsv new file mode 100644 index 000000000..ce7d61b40 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/data/money/currency.tsv @@ -0,0 +1,9 @@ +TL lira kuruş +₺ lira kuruş +TRY lira kuruş +$ dolar sent +USD dolar sent +€ avro sent +EUR avro sent +£ sterlin peni +GBP sterlin peni diff --git a/nemo_text_processing/text_normalization/tr/data/money/lira_suffix.tsv b/nemo_text_processing/text_normalization/tr/data/money/lira_suffix.tsv new file mode 100644 index 000000000..6f1c63e01 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/data/money/lira_suffix.tsv @@ -0,0 +1,14 @@ +ye ya +ya ya +yi yı +yı yı +den dan +dan dan +de da +da da +nin nın +nın nın +lik lık +lık lık +yle yla +yla yla diff --git a/nemo_text_processing/text_normalization/tr/data/number/__init__.py b/nemo_text_processing/text_normalization/tr/data/number/__init__.py new file mode 100644 index 000000000..9e3fb699d --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/data/number/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/nemo_text_processing/text_normalization/tr/data/number/digit.tsv b/nemo_text_processing/text_normalization/tr/data/number/digit.tsv new file mode 100644 index 000000000..40d73015f --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/data/number/digit.tsv @@ -0,0 +1,9 @@ +1 bir +2 iki +3 üç +4 dört +5 beş +6 altı +7 yedi +8 sekiz +9 dokuz diff --git a/nemo_text_processing/text_normalization/tr/data/number/tens.tsv b/nemo_text_processing/text_normalization/tr/data/number/tens.tsv new file mode 100644 index 000000000..38b4a62cc --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/data/number/tens.tsv @@ -0,0 +1,9 @@ +1 on +2 yirmi +3 otuz +4 kırk +5 elli +6 altmış +7 yetmiş +8 seksen +9 doksan diff --git a/nemo_text_processing/text_normalization/tr/data/number/zero.tsv b/nemo_text_processing/text_normalization/tr/data/number/zero.tsv new file mode 100644 index 000000000..37da9d4a7 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/data/number/zero.tsv @@ -0,0 +1 @@ +0 sıfır diff --git a/nemo_text_processing/text_normalization/tr/data/ordinals/__init__.py b/nemo_text_processing/text_normalization/tr/data/ordinals/__init__.py new file mode 100644 index 000000000..9e3fb699d --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/data/ordinals/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/nemo_text_processing/text_normalization/tr/data/ordinals/ordinal_endings.tsv b/nemo_text_processing/text_normalization/tr/data/ordinals/ordinal_endings.tsv new file mode 100644 index 000000000..f5336c5fc --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/data/ordinals/ordinal_endings.tsv @@ -0,0 +1,25 @@ +sıfır sıfırıncı +bir birinci +iki ikinci +üç üçüncü +dört dördüncü +beş beşinci +altı altıncı +yedi yedinci +sekiz sekizinci +dokuz dokuzuncu +on onuncu +yirmi yirminci +otuz otuzuncu +kırk kırkıncı +elli ellinci +altmış altmışıncı +yetmiş yetmişinci +seksen sekseninci +doksan doksanıncı +yüz yüzüncü +bin bininci +milyon milyonuncu +milyar milyarıncı +trilyon trilyonuncu +katrilyon katrilyonuncu diff --git a/nemo_text_processing/text_normalization/tr/data/whitelist.tsv b/nemo_text_processing/text_normalization/tr/data/whitelist.tsv new file mode 100644 index 000000000..6bb290c00 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/data/whitelist.tsv @@ -0,0 +1,22 @@ +Dr. doktor +Prof. profesör +Doç. doçent +Av. avukat +Sn. sayın +vb. ve benzeri +vs. vesaire +vd. ve diğerleri +örn. örneğin +bkz. bakınız +Tel. telefon +Cad. caddesi +Sok. sokağı +Mah. mahallesi +No. numara +A.Ş. anonim şirketi +M.Ö. milattan önce +M.S. milattan sonra +T.C. te ce +KDV katma değer vergisi +TL lira +24/7 yirmi dört yedi diff --git a/nemo_text_processing/text_normalization/tr/graph_utils.py b/nemo_text_processing/text_normalization/tr/graph_utils.py new file mode 100644 index 000000000..b0be4f562 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/graph_utils.py @@ -0,0 +1,47 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pynini +from pynini.lib import pynutil + +from nemo_text_processing.text_normalization.en.graph_utils import NEMO_SIGMA + +TR_LOWER = pynini.union(*"abcçdefgğhıijklmnoöprsştuüvyzâîûqwx").optimize() +TR_UPPER = pynini.union(*"ABCÇDEFGĞHIİJKLMNOÖPRSŞTUÜVYZÂÎÛQWX").optimize() +TR_ALPHA = pynini.union(TR_LOWER, TR_UPPER).optimize() +TR_VOWEL = pynini.union(*"aeıioöuüâîû").optimize() + +# Turkish separates a case or possessive suffix from a numeral with an apostrophe: "4'e", "2024'te", "10:30'da". +APOSTROPHE = pynini.union("'", "’") +SUFFIX = pynini.closure(TR_LOWER, 1).optimize() + +# "dört" is the only number word whose final consonant softens before a vowel: "4'e" -> "dörde", "4'ü" -> "dördü". +SOFTEN_DORT = pynini.cdrewrite(pynini.cross("dört", "dörd"), "", TR_VOWEL, NEMO_SIGMA).optimize() + + +def attach_suffix(graph: "pynini.FstLike") -> "pynini.FstLike": + """ + Appends the suffix written after an apostrophe to the spoken form of a number, e.g. + "4'e" -> "dörde", "1990'da" -> "bin dokuz yüz doksanda", "3,5'e" -> "üç virgül beşe" + + The written suffix already agrees with how the number is read (vowel harmony and voicing follow the spoken + number), so it is copied as written; only "dört" changes its final consonant. + + Args: + graph: an fst whose output is the spoken form of a number + + Returns: + an fst that accepts the input of graph followed by an apostrophe and a suffix + """ + return ((graph + pynutil.delete(APOSTROPHE) + SUFFIX) @ SOFTEN_DORT).optimize() diff --git a/nemo_text_processing/text_normalization/tr/taggers/__init__.py b/nemo_text_processing/text_normalization/tr/taggers/__init__.py new file mode 100644 index 000000000..9e3fb699d --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/taggers/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/nemo_text_processing/text_normalization/tr/taggers/cardinal.py b/nemo_text_processing/text_normalization/tr/taggers/cardinal.py new file mode 100644 index 000000000..0f02f7c2d --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/taggers/cardinal.py @@ -0,0 +1,139 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pynini +from pynini.lib import pynutil + +from nemo_text_processing.text_normalization.en.graph_utils import ( + NEMO_DIGIT, + NEMO_SIGMA, + NEMO_SPACE, + GraphFst, + delete_space, +) +from nemo_text_processing.text_normalization.tr.graph_utils import TR_ALPHA, attach_suffix +from nemo_text_processing.text_normalization.tr.utils import get_abs_path + +# Turkish groups thousands with a dot: "1.250.000" +THOUSANDS_SEPARATOR = "." +MAX_DIGITS = 18 + + +def filter_thousands(fst: "pynini.FstLike") -> "pynini.FstLike": + """ + Accepts a plain digit string, or one grouped in threes with dots, removes the dots and composes the result + onto fst: + "1250" -> "1250", "1.250.000" -> "1250000" + + Args: + fst: an fst over digit strings + + Returns: + fst: the composition + """ + up_to_three_digits = pynini.closure(NEMO_DIGIT, 1, 3) - pynini.union("0", "00", "000") + grouped = up_to_three_digits + pynini.closure(pynutil.delete(THOUSANDS_SEPARATOR) + NEMO_DIGIT**3, 1) + return (pynini.closure(NEMO_DIGIT, 1) | grouped) @ fst + + +class CardinalFst(GraphFst): + """ + Finite state transducer for classifying cardinals, e.g. + "1000" -> cardinal { integer: "bin" } + "1.250.000" -> cardinal { integer: "bir milyon iki yüz elli bin" } + "-5" -> cardinal { negative: "true" integer: "beş" } + "4'e" -> cardinal { integer: "dörde" } + "0532" -> cardinal { integer: "sıfır beş üç iki" } + + Turkish says "yüz" and "bin" for 100 and 1000 (not "bir yüz", "bir bin"), but "bir milyon" and up. + A number written with a leading zero is an identifier and is read digit by digit. + + Args: + deterministic: if True will provide a single transduction option, + for False multiple transduction are generated (used for audio-based normalization) + """ + + def __init__(self, deterministic: bool = True): + super().__init__(name="cardinal", kind="classify", deterministic=deterministic) + + zero = pynini.string_file(get_abs_path("data/number/zero.tsv")) + digit = pynini.string_file(get_abs_path("data/number/digit.tsv")) + tens = pynini.string_file(get_abs_path("data/number/tens.tsv")) + insert_space = pynutil.insert(NEMO_SPACE) + + # "00".."99" with at least one non-zero digit: "05" -> "beş", "40" -> "kırk", "45" -> "kırk beş" + two_digits = pynini.union( + pynutil.delete("0") + digit, + tens + pynutil.delete("0"), + tens + insert_space + digit, + ) + self.two_digits = two_digits.optimize() + + hundred = pynini.union( + pynini.cross("1", "yüz"), + ((NEMO_DIGIT - "0" - "1") @ digit) + pynutil.insert(" yüz"), + ) + # "000".."999" with at least one non-zero digit + three_digits = pynini.union( + hundred + pynutil.delete("00"), + hundred + insert_space + two_digits, + pynutil.delete("0") + two_digits, + ) + self.three_digits = three_digits.optimize() + + def scale(word: str) -> "pynini.FstLike": + return pynini.union(pynutil.delete("000"), three_digits + pynutil.insert(f" {word} ")) + + thousands = pynini.union( + pynutil.delete("000"), + pynini.cross("001", "bin "), + ((NEMO_DIGIT**3 - "000" - "001") @ three_digits) + pynutil.insert(" bin "), + ) + units = pynini.union(pynutil.delete("000"), three_digits) + + graph = scale("katrilyon") + scale("trilyon") + scale("milyar") + scale("milyon") + thousands + units + + clean_output = ( + pynini.cdrewrite(delete_space, "[BOS]", "", NEMO_SIGMA) + @ pynini.cdrewrite(delete_space, "", "[EOS]", NEMO_SIGMA) + @ pynini.cdrewrite( + pynini.cross(pynini.closure(NEMO_SPACE, 2), NEMO_SPACE), + TR_ALPHA, + TR_ALPHA, + NEMO_SIGMA, + ) + ).optimize() + + positive = ( + ((NEMO_DIGIT - "0") + pynini.closure(NEMO_DIGIT, 0, MAX_DIGITS - 1)) + @ pynini.cdrewrite(pynini.closure(pynutil.insert("0")), "[BOS]", "", NEMO_SIGMA) + @ NEMO_DIGIT**MAX_DIGITS + @ graph + @ clean_output + ) + + # The spoken form of a plain number, with optional thousand dots: used inside decimals, money, dates... + self.graph = (filter_thousands(positive) | zero).optimize() + + # Digit by digit, for identifiers and the digits after a decimal comma: "0532" -> "sıfır beş üç iki" + single_digit = zero | digit + self.digits = (single_digit + pynini.closure(insert_space + single_digit)).optimize() + leading_zero = ("0" + pynini.closure(NEMO_DIGIT, 1)) @ self.digits + + number = self.graph | pynutil.add_weight(leading_zero, 0.01) + number |= attach_suffix(number) + + optional_minus = pynini.closure(pynutil.insert("negative: ") + pynini.cross("-", '"true" '), 0, 1) + final_graph = optional_minus + pynutil.insert('integer: "') + number + pynutil.insert('"') + self.fst = self.add_tokens(final_graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/taggers/date.py b/nemo_text_processing/text_normalization/tr/taggers/date.py new file mode 100644 index 000000000..295ef8097 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/taggers/date.py @@ -0,0 +1,101 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pynini +from pynini.lib import pynutil, rewrite + +from nemo_text_processing.text_normalization.en.graph_utils import NEMO_DIGIT, NEMO_SPACE, GraphFst +from nemo_text_processing.text_normalization.tr.graph_utils import APOSTROPHE, SUFFIX, attach_suffix +from nemo_text_processing.text_normalization.tr.utils import get_abs_path, load_labels + + +class DateFst(GraphFst): + """ + Finite state transducer for classifying dates, e.g. + "14.03.1988" -> date { day: "on dört" month: "mart" year: "bin dokuz yüz seksen sekiz" preserve_order: true } + "05/12/2026" -> date { day: "beş" month: "aralık" year: "iki bin yirmi altı" preserve_order: true } + "2026-03-15" -> date { day: "on beş" month: "mart" year: "iki bin yirmi altı" preserve_order: true } + "14 Mart 2026" -> date { day: "on dört" month: "mart" year: "iki bin yirmi altı" preserve_order: true } + "01.01.2027'de" -> date { day: "bir" month: "ocak" year: "iki bin yirmi yedide" preserve_order: true } + "15 Kasım'da" -> date { day: "on beş" month: "kasımda" preserve_order: true } + + Turkish reads day, month, year. In ISO dates (year first) the day and month are enumerated so the tagger can + emit them first. + + Args: + cardinal: CardinalFst + deterministic: if True will provide a single transduction option, + for False multiple transduction are generated (used for audio-based normalization) + """ + + def __init__(self, cardinal: GraphFst, deterministic: bool = True): + super().__init__(name="date", kind="classify", deterministic=deterministic) + + month_numbers = load_labels(get_abs_path("data/dates/months.tsv")) + month_names = pynini.string_file(get_abs_path("data/dates/month_names.tsv")) + + day_values = [str(d) for d in range(1, 32)] + day_digits = pynini.union(*day_values, *[f"0{d}" for d in range(1, 10)]) + day = (day_digits @ (pynini.closure(pynutil.delete("0"), 0, 1) + cardinal.graph)).optimize() + + month_digits = pynini.union( + *[n for n, _ in month_numbers], + *[f"0{n}" for n, _ in month_numbers if len(n) == 1], + ) + month = ( + month_digits @ (pynini.closure(pynutil.delete("0"), 0, 1) + pynini.string_map(month_numbers)) + ).optimize() + + year_digits = pynini.union("1", "2") + NEMO_DIGIT**3 + plain_year = (year_digits @ cardinal.graph).optimize() + year = plain_year | attach_suffix(plain_year) + + def field(name, graph, first=False): + return pynutil.insert(("" if first else " ") + f'{name}: "') + graph + pynutil.insert('"') + + preserve = pynutil.insert(" preserve_order: true") + + numeric = [] + for sep in [".", "/", "-"]: + numeric.append( + field("day", day, first=True) + + pynutil.delete(sep) + + field("month", month) + + pynutil.delete(sep) + + field("year", year) + ) + numeric = pynini.union(*numeric) + + # ISO: the day and month come last in writing but first in speech + iso = [] + for month_number, month_name in month_numbers: + for day_value in day_values: + spoken_day = rewrite.top_rewrite(day_value, cardinal.graph) + iso.append( + pynutil.insert(f'day: "{spoken_day}" month: "{month_name}"') + + field("year", plain_year) + + pynutil.delete(f"-{int(month_number):02d}-{int(day_value):02d}") + ) + iso = pynini.union(*iso) + + month_name = month_names | month_names + pynutil.delete(APOSTROPHE) + SUFFIX + textual = ( + field("day", day, first=True) + + pynutil.delete(NEMO_SPACE) + + field("month", month_name) + + pynini.closure(pynutil.delete(NEMO_SPACE) + field("year", year), 0, 1) + ) + + self.graph = (numeric | iso | textual) + preserve + self.fst = self.add_tokens(self.graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/taggers/decimal.py b/nemo_text_processing/text_normalization/tr/taggers/decimal.py new file mode 100644 index 000000000..76a5ba8f7 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/taggers/decimal.py @@ -0,0 +1,79 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pynini +from pynini.lib import pynutil + +from nemo_text_processing.text_normalization.en.graph_utils import NEMO_DIGIT, GraphFst +from nemo_text_processing.text_normalization.tr.graph_utils import attach_suffix + + +def get_fractional_graph(cardinal: GraphFst) -> "pynini.FstLike": + """ + The digits after the decimal separator, read as written: leading zeros one by one, the rest as a number, e.g. + "5" -> "beş", "05" -> "sıfır beş", "50" -> "elli", "0" / "00" -> "sıfır" + + Args: + cardinal: CardinalFst + + Returns: + an fst over digit strings + """ + zeros = pynini.closure(pynini.cross("0", "sıfır ")) + rest = ((NEMO_DIGIT - "0") + pynini.closure(NEMO_DIGIT)) @ cardinal.graph + all_zeros = pynini.cross(pynini.closure("0", 1), "sıfır") + return (zeros + rest | all_zeros).optimize() + + +class DecimalFst(GraphFst): + """ + Finite state transducer for classifying decimals, e.g. + "3,5" -> decimal { integer_part: "üç" fractional_part: "beş" } + "-0,05" -> decimal { negative: "true" integer_part: "sıfır" fractional_part: "sıfır beş" } + "1.250,75" -> decimal { integer_part: "bin iki yüz elli" fractional_part: "yetmiş beş" } + "3,5'e" -> decimal { integer_part: "üç" fractional_part: "beşe" } + "3.5" -> decimal { integer_part: "üç" fractional_part: "beş" } + + Turkish writes a decimal comma. A dot followed by one, two or four or more digits is also read as a decimal + point (English style, common in generated text); a dot followed by exactly three digits groups thousands. + + Args: + cardinal: CardinalFst + deterministic: if True will provide a single transduction option, + for False multiple transduction are generated (used for audio-based normalization) + """ + + def __init__(self, cardinal: GraphFst, deterministic: bool = True): + super().__init__(name="decimal", kind="classify", deterministic=deterministic) + + fractional = get_fractional_graph(cardinal) + dot_fraction_digits = pynini.union(NEMO_DIGIT, NEMO_DIGIT**2, NEMO_DIGIT**4 + pynini.closure(NEMO_DIGIT)) + plain_integer = ((NEMO_DIGIT - "0") + pynini.closure(NEMO_DIGIT) | "0") @ cardinal.graph + + integer_part = pynutil.insert('integer_part: "') + cardinal.graph + pynutil.insert('"') + plain_integer_part = pynutil.insert('integer_part: "') + plain_integer + pynutil.insert('"') + + def fractional_part(digits: "pynini.FstLike") -> "pynini.FstLike": + spoken = digits @ fractional + spoken |= attach_suffix(spoken) + return pynutil.insert(' fractional_part: "') + spoken + pynutil.insert('"') + + comma = integer_part + pynutil.delete(",") + fractional_part(pynini.closure(NEMO_DIGIT, 1)) + dot = plain_integer_part + pynutil.delete(".") + fractional_part(dot_fraction_digits) + + self.final_graph_wo_negative = (comma | pynutil.add_weight(dot, 0.01)).optimize() + + optional_minus = pynini.closure(pynutil.insert("negative: ") + pynini.cross("-", '"true" '), 0, 1) + self.final_graph = optional_minus + self.final_graph_wo_negative + self.fst = self.add_tokens(self.final_graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/taggers/fraction.py b/nemo_text_processing/text_normalization/tr/taggers/fraction.py new file mode 100644 index 000000000..744e0c85e --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/taggers/fraction.py @@ -0,0 +1,85 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pynini +from pynini.lib import pynutil, rewrite + +from nemo_text_processing.text_normalization.en.graph_utils import NEMO_DIGIT, NEMO_SIGMA, NEMO_SPACE, GraphFst +from nemo_text_processing.text_normalization.tr.graph_utils import attach_suffix +from nemo_text_processing.text_normalization.tr.utils import get_abs_path, load_labels + +# Denominators read the Turkish way, denominator first in the locative: "3/4" -> "dörtte üç" +NAMED_DENOMINATORS = list(range(2, 101)) + [1000] + + +class FractionFst(GraphFst): + """ + Finite state transducer for classifying fractions, e.g. + "3/4" -> fraction { denominator: "dörtte" numerator: "üç" preserve_order: true } + "2 1/2" -> fraction { integer_part: "iki" denominator: "ikide" numerator: "bir" preserve_order: true } + "½" -> fraction { denominator: "ikide" numerator: "bir" preserve_order: true } + "7/365" -> fraction { numerator: "yedi" denominator: "bölü üç yüz altmış beş" } + + Turkish reads the denominator first, with the locative suffix: "1/2" is "ikide bir", "1/100" is "yüzde bir". + The tagger emits the denominator first, so the order survives Sparrowhawk (preserve_order). Since an fst cannot + swap two unbounded strings, denominators 2-100 and 1000 are enumerated; other fractions are read with "bölü" + ("divided by"), which is also common. + + Args: + cardinal: CardinalFst + deterministic: if True will provide a single transduction option, + for False multiple transduction are generated (used for audio-based normalization) + """ + + def __init__(self, cardinal: GraphFst, deterministic: bool = True): + super().__init__(name="fraction", kind="classify", deterministic=deterministic) + + locative = pynini.string_file(get_abs_path("data/fractions/denominator_locative.tsv")) + to_locative = cardinal.graph @ pynini.union(locative, NEMO_SIGMA + NEMO_SPACE + locative) + plain_number = ((NEMO_DIGIT - "0") + pynini.closure(NEMO_DIGIT)) @ cardinal.graph + numerator = ((NEMO_DIGIT - "0") + pynini.closure(NEMO_DIGIT, 0, 2)) @ cardinal.graph + + named = [] + for denominator in NAMED_DENOMINATORS: + spoken = rewrite.top_rewrite(str(denominator), to_locative) + # a suffix goes on the numerator, the last word read: "3/4'ü" -> "dörtte üçü" + body = numerator + pynutil.delete(f"/{denominator}") + named.append( + pynutil.insert(f'denominator: "{spoken}" numerator: "') + + (body | attach_suffix(body)) + + pynutil.insert('" preserve_order: true') + ) + named = pynini.union(*named) + for symbol, num, den in load_labels(get_abs_path("data/fractions/fraction_symbols.tsv")): + spoken_den = rewrite.top_rewrite(den, to_locative) + spoken_num = rewrite.top_rewrite(num, cardinal.graph) + named |= pynini.cross( + symbol, + f'denominator: "{spoken_den}" numerator: "{spoken_num}" preserve_order: true', + ) + + other = ( + pynutil.insert('numerator: "') + + plain_number + + pynini.cross("/", '" denominator: "bölü ') + + plain_number + + pynutil.insert('"') + ) + + fraction = named | pynutil.add_weight(other, 0.1) + integer_part = pynutil.insert('integer_part: "') + plain_number + pynutil.insert('" ') + mixed = integer_part + pynini.closure(pynutil.delete(NEMO_SPACE), 0, 1) + named + + self.graph = (fraction | mixed).optimize() + self.fst = self.add_tokens(self.graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/taggers/measure.py b/nemo_text_processing/text_normalization/tr/taggers/measure.py new file mode 100644 index 000000000..02e21f499 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/taggers/measure.py @@ -0,0 +1,68 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pynini +from pynini.lib import pynutil + +from nemo_text_processing.text_normalization.en.graph_utils import NEMO_SPACE, GraphFst +from nemo_text_processing.text_normalization.tr.graph_utils import APOSTROPHE, SUFFIX, attach_suffix +from nemo_text_processing.text_normalization.tr.utils import get_abs_path + + +class MeasureFst(GraphFst): + """ + Finite state transducer for classifying measures, e.g. + "5 km" -> measure { cardinal { integer: "beş" } units: "kilometre" } + "2,5 kg" -> measure { decimal { integer_part: "iki" fractional_part: "beş" } units: "kilogram" } + "5 km'ye" -> measure { cardinal { integer: "beş" } units: "kilometreye" } + "%18" -> measure { units: "yüzde" cardinal { integer: "on sekiz" } preserve_order: true } + "%14'ü" -> measure { units: "yüzde" cardinal { integer: "on dördü" } preserve_order: true } + + Turkish writes the percent sign before the number and reads it first ("yüzde on sekiz"); the English order + "15%" is read the same way. A suffix after a unit abbreviation follows the full word ("km'ye" -> "kilometreye"). + + Args: + cardinal: CardinalFst + decimal: DecimalFst + deterministic: if True will provide a single transduction option, + for False multiple transduction are generated (used for audio-based normalization) + """ + + def __init__(self, cardinal: GraphFst, decimal: GraphFst, deterministic: bool = True): + super().__init__(name="measure", kind="classify", deterministic=deterministic) + + units = pynini.string_file(get_abs_path("data/measures/units.tsv")) + units |= units + pynutil.delete(APOSTROPHE) + SUFFIX + optional_space = pynini.closure(pynutil.delete(NEMO_SPACE), 0, 1) + + def wrap_cardinal(graph): + return pynutil.insert('cardinal { integer: "') + graph + pynutil.insert('" }') + + def wrap_decimal(graph): + return pynutil.insert("decimal { ") + graph + pynutil.insert(" }") + + number = wrap_cardinal(cardinal.graph) | wrap_decimal(decimal.final_graph_wo_negative) + number_with_suffix = wrap_cardinal(cardinal.graph | attach_suffix(cardinal.graph)) | wrap_decimal( + decimal.final_graph_wo_negative + ) + + unit_graph = number + optional_space + pynutil.insert(' units: "') + units + pynutil.insert('"') + + percent = pynutil.insert('units: "yüzde" ') + preserve = pynutil.insert(" preserve_order: true") + percent_first = pynutil.delete("%") + optional_space + percent + number_with_suffix + preserve + percent_last = percent + number + optional_space + pynutil.delete("%") + preserve + + self.graph = (unit_graph | percent_first | percent_last).optimize() + self.fst = self.add_tokens(self.graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/taggers/money.py b/nemo_text_processing/text_normalization/tr/taggers/money.py new file mode 100644 index 000000000..4689d058d --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/taggers/money.py @@ -0,0 +1,93 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pynini +from pynini.lib import pynutil + +from nemo_text_processing.text_normalization.en.graph_utils import NEMO_DIGIT, NEMO_SPACE, GraphFst +from nemo_text_processing.text_normalization.tr.graph_utils import APOSTROPHE +from nemo_text_processing.text_normalization.tr.utils import get_abs_path, load_labels + +# Symbols that may also stand before the amount: "$100", "₺1.250,50" +PREFIX_SYMBOLS = {"$", "€", "£", "₺"} +LIRA_CODES = {"TL", "₺", "TRY"} + + +class MoneyFst(GraphFst): + """ + Finite state transducer for classifying money, e.g. + "1.250,50 TL" -> money { integer_part: "bin iki yüz elli" currency_maj: "lira" fractional_part: "elli" + currency_min: "kuruş" preserve_order: true } + "2450.75 TL" -> money { integer_part: "iki bin dört yüz elli" currency_maj: "lira" fractional_part: "yetmiş beş" + currency_min: "kuruş" preserve_order: true } + "$100" -> money { integer_part: "yüz" currency_maj: "dolar" preserve_order: true } + "0,50 TL" -> money { fractional_part: "elli" currency_min: "kuruş" preserve_order: true } + "100 TL'ye" -> money { integer_part: "yüz" currency_maj: "liraya" preserve_order: true } + + The minor unit is read as a number of hundredths: "1,5 TL" is "bir lira elli kuruş". A dot followed by one or two + digits is a decimal point ("2450.75 TL"); followed by three it groups thousands ("1.250 TL"). + + A suffix written after "TL" follows how the letters are read ("TL'ye"), so it is re-harmonised for "lira" + ("liraya"). + + Args: + cardinal: CardinalFst + deterministic: if True will provide a single transduction option, + for False multiple transduction are generated (used for audio-based normalization) + """ + + def __init__(self, cardinal: GraphFst, deterministic: bool = True): + super().__init__(name="money", kind="classify", deterministic=deterministic) + + lira_suffix = pynini.string_file(get_abs_path("data/money/lira_suffix.tsv")) + integer = pynutil.insert('integer_part: "') + cardinal.graph + pynutil.insert('"') + + # minor unit as hundredths: "5" -> "elli", "05" -> "beş", "50" -> "elli"; "0" / "00" is not read + minor_digits = ( + pynini.union((NEMO_DIGIT - "0") + pynutil.insert("0"), NEMO_DIGIT**2 - "00") @ cardinal.two_digits + ).optimize() + no_minor = pynutil.delete(pynini.union(",", ".") + pynini.union("0", "00")) + separator = pynutil.delete(pynini.union(",", ".")) + optional_space = pynini.closure(pynutil.delete(NEMO_SPACE), 0, 1) + + graphs = [] + for code, major, minor in load_labels(get_abs_path("data/money/currency.tsv")): + maj = pynutil.insert(f' currency_maj: "{major}"') + fractional = pynutil.insert(' fractional_part: "') + separator + minor_digits + pynutil.insert('"') + mino = pynutil.insert(f' currency_min: "{minor}"') + amount = pynini.union( + integer + pynini.closure(no_minor, 0, 1) + maj, + integer + maj + fractional + mino, + pynutil.delete("0") + fractional + mino, + ) + amount += pynutil.insert(" preserve_order: true") + delete_code = pynutil.delete(code) + graphs.append(amount + optional_space + delete_code) + if code in PREFIX_SYMBOLS: + graphs.append(delete_code + optional_space + amount) + if code in LIRA_CODES: + inflected = ( + integer + + pynini.closure(no_minor, 0, 1) + + pynutil.insert(f' currency_maj: "{major}') + + optional_space + + delete_code + + pynutil.delete(APOSTROPHE) + + lira_suffix + + pynutil.insert('" preserve_order: true') + ) + graphs.append(inflected) + + self.graph = pynini.union(*graphs).optimize() + self.fst = self.add_tokens(self.graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/taggers/ordinal.py b/nemo_text_processing/text_normalization/tr/taggers/ordinal.py new file mode 100644 index 000000000..385ac8f15 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/taggers/ordinal.py @@ -0,0 +1,57 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pynini +from pynini.lib import pynutil + +from nemo_text_processing.text_normalization.en.graph_utils import NEMO_SIGMA, NEMO_SPACE, GraphFst +from nemo_text_processing.text_normalization.tr.graph_utils import APOSTROPHE +from nemo_text_processing.text_normalization.tr.utils import get_abs_path + +# Written ordinal endings after the digits: "5'inci", "3üncü", "2'nci" +WRITTEN_ENDINGS = pynini.union("inci", "ıncı", "uncu", "üncü", "nci", "ncı", "ncu", "ncü") + + +class OrdinalFst(GraphFst): + """ + Finite state transducer for classifying ordinals, e.g. + "5'inci" -> ordinal { integer: "beşinci" } + "3üncü" -> ordinal { integer: "üçüncü" } + "21." -> ordinal { integer: "yirmi birinci" } (only through self.fst_dot, see below) + + The ordinal suffix follows vowel harmony with the last number word, so the last word is replaced from a table + ("bir" -> "birinci", "üç" -> "üçüncü", "altı" -> "altıncı"). + + A number followed by a dot is an ordinal only before a word ("5. sırada" -> "beşinci sırada"); at the end of a + sentence it is a number and a full stop. self.fst_dot is therefore kept apart and used by ClassifyFst only in + front of a lower-case word. + + Args: + cardinal: CardinalFst + deterministic: if True will provide a single transduction option, + for False multiple transduction are generated (used for audio-based normalization) + """ + + def __init__(self, cardinal: GraphFst, deterministic: bool = True): + super().__init__(name="ordinal", kind="classify", deterministic=deterministic) + + endings = pynini.string_file(get_abs_path("data/ordinals/ordinal_endings.tsv")) + last_word_to_ordinal = pynini.union(endings, NEMO_SIGMA + NEMO_SPACE + endings) + self.graph = (cardinal.graph @ last_word_to_ordinal).optimize() + + written = self.graph + pynini.closure(pynutil.delete(APOSTROPHE), 0, 1) + pynutil.delete(WRITTEN_ENDINGS) + dotted = self.graph + pynutil.delete(".") + + self.fst = self.add_tokens(pynutil.insert('integer: "') + written + pynutil.insert('"')).optimize() + self.fst_dot = self.add_tokens(pynutil.insert('integer: "') + dotted + pynutil.insert('"')).optimize() diff --git a/nemo_text_processing/text_normalization/tr/taggers/telephone.py b/nemo_text_processing/text_normalization/tr/taggers/telephone.py new file mode 100644 index 000000000..ac4fe684e --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/taggers/telephone.py @@ -0,0 +1,85 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pynini +from pynini.lib import pynutil + +from nemo_text_processing.text_normalization.en.graph_utils import NEMO_DIGIT, GraphFst + + +class TelephoneFst(GraphFst): + """ + Finite state transducer for classifying Turkish telephone numbers, e.g. + "0532 123 45 67" -> telephone { number_part: "sıfır beş yüz otuz iki, yüz yirmi üç, kırk beş, altmış yedi" } + "0850-222-23-35" -> telephone { number_part: "sıfır sekiz yüz elli, iki yüz yirmi iki, yirmi üç, otuz beş" } + "(0212) 555 44 33" -> telephone { number_part: "sıfır iki yüz on iki, beş yüz elli beş, kırk dört, otuz üç" } + "+90 532 123 45 67" -> telephone { country_code: "artı doksan" number_part: "beş yüz otuz iki, ..." } + "444 0 123" -> telephone { number_part: "dört yüz kırk dört, sıfır, yüz yirmi üç" } + + Turkish reads a phone number in its written groups, each group as a number: the area code "0532" as "sıfır beş + yüz otuz iki", the pairs "45 67" as "kırk beş, altmış yedi". A leading zero inside a group is read ("05" -> + "sıfır beş"). Commas between the groups give a speech synthesiser the pauses a person makes. + + Args: + cardinal: CardinalFst + deterministic: if True will provide a single transduction option, + for False multiple transduction are generated (used for audio-based normalization) + """ + + def __init__(self, cardinal: GraphFst, deterministic: bool = True): + super().__init__(name="telephone", kind="classify", deterministic=deterministic) + + zero = pynini.cross("0", "sıfır") + zero_space = zero + pynutil.insert(" ") + + def group(n): + """A group of n digits read as a number, leading zeros one by one: "45" -> "kırk beş", "05" -> "sıfır beş".""" + readings = ((NEMO_DIGIT - "0") + NEMO_DIGIT ** (n - 1)) @ cardinal.graph + readings |= pynini.closure(zero_space, n - 1, n - 1) + zero + if n > 1: + readings |= pynini.closure(zero_space, 1, n - 1) + ( + ((NEMO_DIGIT - "0") + pynini.closure(NEMO_DIGIT)) @ cardinal.graph + ) + return (NEMO_DIGIT**n @ readings).optimize() + + comma = pynutil.insert(", ") + sep = pynini.union(" ", "-", ".") + delete_sep = pynutil.delete(sep) + optional_sep = pynini.closure(delete_sep, 0, 1) + + # subscriber number: "123 45 67" + subscriber = group(3) + optional_sep + comma + group(2) + optional_sep + comma + group(2) + operator = ((NEMO_DIGIT - "0") + NEMO_DIGIT**2) @ cardinal.graph # "532" + area = zero + pynutil.insert(" ") + operator # "0532" + area |= pynutil.delete("(") + area + pynutil.delete(")") + + national = area + optional_sep + comma + subscriber + international = ( + pynutil.insert('country_code: "') + + pynini.cross("+90", "artı doksan") + + pynutil.insert('" ') + + pynutil.delete(pynini.closure(" ", 0, 1)) + + pynutil.insert('number_part: "') + + operator + + optional_sep + + comma + + subscriber + + pynutil.insert('"') + ) + # call centre numbers: "444 0 123" + call_centre = group(3) + delete_sep + comma + group(1) + delete_sep + comma + group(3) + + number_part = pynutil.insert('number_part: "') + (national | call_centre) + pynutil.insert('"') + self.graph = (number_part | international).optimize() + self.fst = self.add_tokens(self.graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/taggers/time.py b/nemo_text_processing/text_normalization/tr/taggers/time.py new file mode 100644 index 000000000..49269abe4 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/taggers/time.py @@ -0,0 +1,82 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pynini +from pynini.lib import pynutil + +from nemo_text_processing.text_normalization.en.graph_utils import NEMO_DIGIT, GraphFst +from nemo_text_processing.text_normalization.tr.graph_utils import attach_suffix + + +class TimeFst(GraphFst): + """ + Finite state transducer for classifying time, e.g. + "14:30" -> time { hours: "on dört" minutes: "otuz" } + "09:05" -> time { hours: "dokuz" minutes: "sıfır beş" } + "10:00" -> time { hours: "on" } + "14:30'da" -> time { hours: "on dört" minutes: "otuzda" } + "10:00'a" -> time { hours: "ona" } + "14.30'da" -> time { hours: "on dört" minutes: "otuzda" } + "09.30" -> time { hours: "dokuz" minutes: "otuz" } + + Full hours drop the minutes ("saat on"). A suffix goes on the last word read. With a dot, "14.30" is a time + only when a suffix follows or the hour has a leading zero; otherwise it is left to the decimal grammar. + + Args: + cardinal: CardinalFst + deterministic: if True will provide a single transduction option, + for False multiple transduction are generated (used for audio-based normalization) + """ + + def __init__(self, cardinal: GraphFst, deterministic: bool = True): + super().__init__(name="time", kind="classify", deterministic=deterministic) + + hour_values = pynini.union(*[str(h) for h in range(0, 24)]) + hours_padded = pynini.union(*[f"0{h}" for h in range(0, 10)]) + to_words = pynini.closure(pynutil.delete("0"), 0, 1) + cardinal.graph + hours = ((hour_values | hours_padded) @ to_words).optimize() + hours_leading_zero = (hours_padded @ to_words).optimize() + + # "01".."59": "05" -> "sıfır beş", "30" -> "otuz"; "00" is handled by the callers + minutes = pynini.union( + pynini.cross("0", "sıfır ") + ((NEMO_DIGIT - "0") @ cardinal.graph), + (pynini.union("1", "2", "3", "4", "5") + NEMO_DIGIT) @ cardinal.graph, + ).optimize() + + def field(name, graph, first=False): + return pynutil.insert(("" if first else " ") + f'{name}: "') + graph + pynutil.insert('"') + + def build(hour_graph, sep, with_suffix): + suffix = attach_suffix if with_suffix else (lambda g: g) + with_minutes = ( + field("hours", hour_graph, first=True) + pynutil.delete(sep) + field("minutes", suffix(minutes)) + ) + full_hour = field("hours", suffix(hour_graph + pynutil.delete(sep + "00")), first=True) + with_seconds = ( + field("hours", hour_graph, first=True) + + pynutil.delete(sep) + + field("minutes", minutes | pynini.cross("00", "sıfır")) + + pynutil.delete(sep) + + field("seconds", suffix(minutes | pynini.cross("00", "sıfır"))) + ) + graphs = [with_minutes, full_hour] + if sep == ":": + graphs.append(with_seconds) + return pynini.union(*graphs) + + colon = build(hours, ":", False) | build(hours, ":", True) + dot = build(hours, ".", True) | build(hours_leading_zero, ".", False) + + self.graph = (colon | dot).optimize() + self.fst = self.add_tokens(self.graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/taggers/tokenize_and_classify.py b/nemo_text_processing/text_normalization/tr/taggers/tokenize_and_classify.py new file mode 100644 index 000000000..c27616f54 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/taggers/tokenize_and_classify.py @@ -0,0 +1,164 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os + +import pynini +from pynini.lib import pynutil + +from nemo_text_processing.text_normalization.en.graph_utils import ( + NEMO_NOT_SPACE, + NEMO_WHITE_SPACE, + GraphFst, + delete_extra_space, + delete_space, + generator_main, +) +from nemo_text_processing.text_normalization.en.taggers.punctuation import PunctuationFst +from nemo_text_processing.text_normalization.tr.graph_utils import TR_LOWER +from nemo_text_processing.text_normalization.tr.taggers.cardinal import CardinalFst +from nemo_text_processing.text_normalization.tr.taggers.date import DateFst +from nemo_text_processing.text_normalization.tr.taggers.decimal import DecimalFst +from nemo_text_processing.text_normalization.tr.taggers.fraction import FractionFst +from nemo_text_processing.text_normalization.tr.taggers.measure import MeasureFst +from nemo_text_processing.text_normalization.tr.taggers.money import MoneyFst +from nemo_text_processing.text_normalization.tr.taggers.ordinal import OrdinalFst +from nemo_text_processing.text_normalization.tr.taggers.telephone import TelephoneFst +from nemo_text_processing.text_normalization.tr.taggers.time import TimeFst +from nemo_text_processing.text_normalization.tr.taggers.whitelist import WhiteListFst +from nemo_text_processing.text_normalization.tr.taggers.word import WordFst +from nemo_text_processing.utils.logging import logger + + +class ClassifyFst(GraphFst): + """ + Final class that composes all other classification grammars. This class can process an entire sentence. + For deployment, this grammar will be compiled and exported to OpenFst Finite State Archive (FAR) File. + More details to deployment at NeMo/tools/text_processing_deployment. + + Args: + input_case: accepting either "lower_cased" or "cased" input. + deterministic: if True will provide a single transduction option, + for False multiple options (used for audio-based normalization) + cache_dir: path to a dir with .far grammar file. Set to None to avoid using cache. + overwrite_cache: set to True to overwrite .far files + whitelist: path to a file with whitelist replacements + """ + + def __init__( + self, + input_case: str, + deterministic: bool = True, + cache_dir: str = None, + overwrite_cache: bool = False, + whitelist: str = None, + ): + super().__init__(name="tokenize_and_classify", kind="classify", deterministic=deterministic) + far_file = None + if cache_dir is not None and cache_dir != "None": + os.makedirs(cache_dir, exist_ok=True) + whitelist_file = os.path.basename(whitelist) if whitelist else "" + far_file = os.path.join( + cache_dir, + f"_{input_case}_tr_tn_{deterministic}_deterministic{whitelist_file}.far", + ) + if not overwrite_cache and far_file and os.path.exists(far_file): + self.fst = pynini.Far(far_file, mode="r")["tokenize_and_classify"] + logger.info(f"ClassifyFst.fst was restored from {far_file}.") + else: + logger.info("Creating ClassifyFst grammars. This might take some time...") + + self.cardinal = CardinalFst(deterministic=deterministic) + cardinal_graph = self.cardinal.fst + self.ordinal = OrdinalFst(cardinal=self.cardinal, deterministic=deterministic) + ordinal_graph = self.ordinal.fst + self.decimal = DecimalFst(cardinal=self.cardinal, deterministic=deterministic) + decimal_graph = self.decimal.fst + self.fraction = FractionFst(cardinal=self.cardinal, deterministic=deterministic) + fraction_graph = self.fraction.fst + self.measure = MeasureFst( + cardinal=self.cardinal, + decimal=self.decimal, + deterministic=deterministic, + ) + measure_graph = self.measure.fst + self.date = DateFst(cardinal=self.cardinal, deterministic=deterministic) + date_graph = self.date.fst + self.time = TimeFst(cardinal=self.cardinal, deterministic=deterministic) + time_graph = self.time.fst + self.money = MoneyFst(cardinal=self.cardinal, deterministic=deterministic) + money_graph = self.money.fst + self.telephone = TelephoneFst(cardinal=self.cardinal, deterministic=deterministic) + telephone_graph = self.telephone.fst + self.whitelist = WhiteListFst(input_case=input_case, deterministic=deterministic, input_file=whitelist) + whitelist_graph = self.whitelist.fst + self.word = WordFst(deterministic=deterministic) + word_graph = self.word.fst + punct_graph = PunctuationFst(deterministic=deterministic).fst + + classify = ( + pynutil.add_weight(whitelist_graph, 1.01) + | pynutil.add_weight(time_graph, 1.09) + | pynutil.add_weight(date_graph, 1.09) + | pynutil.add_weight(money_graph, 1.09) + | pynutil.add_weight(measure_graph, 1.09) + | pynutil.add_weight(telephone_graph, 1.09) + | pynutil.add_weight(fraction_graph, 1.1) + | pynutil.add_weight(decimal_graph, 1.1) + | pynutil.add_weight(ordinal_graph, 1.1) + | pynutil.add_weight(cardinal_graph, 1.1) + | pynutil.add_weight(word_graph, 200) + ) + punct = pynutil.insert("tokens { ") + pynutil.add_weight(punct_graph, weight=2.1) + pynutil.insert(" }") + punct = pynini.closure( + pynini.compose(pynini.closure(NEMO_WHITE_SPACE, 1), delete_extra_space) + | (pynutil.insert(" ") + punct), + 1, + ) + token = pynutil.insert("tokens { ") + classify + pynutil.insert(" }") + + # "5. sırada" -> "beşinci sırada": a number with a dot is an ordinal only before a lower-case word; + # at the end of a sentence ("Sırada 5.") it stays a number and a full stop. + lower_word = pynini.compose(TR_LOWER + pynini.closure(NEMO_NOT_SPACE), self.word.fst) + ordinal_dot = ( + pynutil.insert("tokens { ") + + pynutil.add_weight(self.ordinal.fst_dot, 1.1) + + pynutil.insert(" }") + + pynutil.delete(pynini.closure(NEMO_WHITE_SPACE, 1)) + + pynutil.insert(" tokens { ") + + pynutil.add_weight(lower_word, 200) + + pynutil.insert(" }") + ) + token |= ordinal_dot + + token_plus_punct = ( + pynini.closure(punct + pynutil.insert(" ")) + token + pynini.closure(pynutil.insert(" ") + punct) + ) + + graph = token_plus_punct + pynini.closure( + ( + pynini.compose(pynini.closure(NEMO_WHITE_SPACE, 1), delete_extra_space) + | (pynutil.insert(" ") + punct + pynutil.insert(" ")) + ) + + token_plus_punct + ) + + graph = delete_space + graph + delete_space + graph |= punct + + self.fst = graph.optimize() + + if far_file: + generator_main(far_file, {"tokenize_and_classify": self.fst}) + logger.info(f"ClassifyFst grammars are saved to {far_file}.") diff --git a/nemo_text_processing/text_normalization/tr/taggers/whitelist.py b/nemo_text_processing/text_normalization/tr/taggers/whitelist.py new file mode 100644 index 000000000..dde405cc6 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/taggers/whitelist.py @@ -0,0 +1,56 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pynini +from pynini.lib import pynutil + +from nemo_text_processing.text_normalization.en.graph_utils import GraphFst, convert_space +from nemo_text_processing.text_normalization.tr.utils import get_abs_path, load_labels + + +def turkish_lower(text: str) -> str: + """Lower-cases with the Turkish dotted and dotless i: "İ" -> "i", "I" -> "ı".""" + return text.replace("İ", "i").replace("I", "ı").lower() + + +class WhiteListFst(GraphFst): + """ + Finite state transducer for classifying whitelist, e.g. + "Dr." -> tokens { name: "doktor" } + "vb." -> tokens { name: "ve benzeri" } + This class has highest priority among all classifier grammars. Whitelisted tokens are defined and loaded from + "data/whitelist.tsv". + + Args: + input_case: accepting either "lower_cased" or "cased" input. + deterministic: if True will provide a single transduction option, + for False multiple options (used for audio-based normalization) + input_file: path to a file with whitelist replacements + """ + + def __init__(self, input_case: str, deterministic: bool = True, input_file: str = None): + super().__init__(name="whitelist", kind="classify", deterministic=deterministic) + + def _get_whitelist_graph(input_case, file): + whitelist = load_labels(file) + if input_case == "lower_cased": + whitelist = [[turkish_lower(x[0])] + x[1:] for x in whitelist] + return pynini.string_map(whitelist) + + graph = _get_whitelist_graph(input_case, get_abs_path("data/whitelist.tsv")) + if input_file: + graph = _get_whitelist_graph(input_case, input_file) + + self.graph = convert_space(graph).optimize() + self.fst = (pynutil.insert('name: "') + self.graph + pynutil.insert('"')).optimize() diff --git a/nemo_text_processing/text_normalization/tr/taggers/word.py b/nemo_text_processing/text_normalization/tr/taggers/word.py new file mode 100644 index 000000000..483829141 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/taggers/word.py @@ -0,0 +1,34 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pynini +from pynini.lib import pynutil + +from nemo_text_processing.text_normalization.en.graph_utils import NEMO_NOT_SPACE, GraphFst + + +class WordFst(GraphFst): + """ + Finite state transducer for classifying word. + e.g. sırada -> tokens { name: "sırada" } + + Args: + deterministic: if True will provide a single transduction option, + for False multiple transduction are generated (used for audio-based normalization) + """ + + def __init__(self, deterministic: bool = True): + super().__init__(name="word", kind="classify", deterministic=deterministic) + self.graph = pynini.closure(NEMO_NOT_SPACE, 1).optimize() + self.fst = (pynutil.insert('name: "') + self.graph + pynutil.insert('"')).optimize() diff --git a/nemo_text_processing/text_normalization/tr/utils.py b/nemo_text_processing/text_normalization/tr/utils.py new file mode 100644 index 000000000..e502bbf39 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/utils.py @@ -0,0 +1,42 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import csv +import os + + +def get_abs_path(rel_path): + """ + Get absolute path + + Args: + rel_path: relative path to this file + + Returns absolute path + """ + return os.path.dirname(os.path.abspath(__file__)) + "/" + rel_path + + +def load_labels(abs_path): + """ + loads relative path file as dictionary + + Args: + abs_path: absolute path + + Returns dictionary of mappings + """ + with open(abs_path, encoding="utf-8") as label_tsv: + labels = list(csv.reader(label_tsv, delimiter="\t")) + return labels diff --git a/nemo_text_processing/text_normalization/tr/verbalizers/__init__.py b/nemo_text_processing/text_normalization/tr/verbalizers/__init__.py new file mode 100644 index 000000000..9e3fb699d --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/verbalizers/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/nemo_text_processing/text_normalization/tr/verbalizers/cardinal.py b/nemo_text_processing/text_normalization/tr/verbalizers/cardinal.py new file mode 100644 index 000000000..46bb9312e --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/verbalizers/cardinal.py @@ -0,0 +1,43 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pynini +from pynini.lib import pynutil + +from nemo_text_processing.text_normalization.en.graph_utils import NEMO_NOT_QUOTE, GraphFst, delete_space + + +class CardinalFst(GraphFst): + """ + Finite state transducer for verbalizing cardinals, e.g. + cardinal { negative: "true" integer: "beş" } -> eksi beş + + Args: + deterministic: if True will provide a single transduction option, + for False multiple transduction are generated (used for audio-based normalization) + """ + + def __init__(self, deterministic: bool = True): + super().__init__(name="cardinal", kind="verbalize", deterministic=deterministic) + + self.optional_sign = pynini.closure(pynini.cross('negative: "true"', "eksi ") + delete_space, 0, 1) + self.integer = ( + pynutil.delete("integer:") + + delete_space + + pynutil.delete('"') + + pynini.closure(NEMO_NOT_QUOTE, 1) + + pynutil.delete('"') + ) + self.numbers = self.optional_sign + self.integer + self.fst = self.delete_tokens(self.numbers).optimize() diff --git a/nemo_text_processing/text_normalization/tr/verbalizers/date.py b/nemo_text_processing/text_normalization/tr/verbalizers/date.py new file mode 100644 index 000000000..b5b46fa09 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/verbalizers/date.py @@ -0,0 +1,51 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pynini +from pynini.lib import pynutil + +from nemo_text_processing.text_normalization.en.graph_utils import ( + NEMO_NOT_QUOTE, + GraphFst, + delete_preserve_order, + delete_space, +) + + +class DateFst(GraphFst): + """ + Finite state transducer for verbalizing dates, e.g. + date { day: "on dört" month: "mart" year: "bin dokuz yüz seksen sekiz" preserve_order: true } + -> on dört mart bin dokuz yüz seksen sekiz + + Args: + deterministic: if True will provide a single transduction option, + for False multiple transduction are generated (used for audio-based normalization) + """ + + def __init__(self, deterministic: bool = True): + super().__init__(name="date", kind="verbalize", deterministic=deterministic) + + def field(name): + return ( + pynutil.delete(f"{name}:") + + delete_space + + pynutil.delete('"') + + pynini.closure(NEMO_NOT_QUOTE, 1) + + pynutil.delete('"') + ) + + space = delete_space + pynutil.insert(" ") + graph = field("day") + space + field("month") + pynini.closure(space + field("year"), 0, 1) + self.fst = self.delete_tokens(graph + delete_preserve_order).optimize() diff --git a/nemo_text_processing/text_normalization/tr/verbalizers/decimal.py b/nemo_text_processing/text_normalization/tr/verbalizers/decimal.py new file mode 100644 index 000000000..85875b2cc --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/verbalizers/decimal.py @@ -0,0 +1,50 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pynini +from pynini.lib import pynutil + +from nemo_text_processing.text_normalization.en.graph_utils import NEMO_NOT_QUOTE, GraphFst, delete_space + + +class DecimalFst(GraphFst): + """ + Finite state transducer for verbalizing decimals, e.g. + decimal { negative: "true" integer_part: "üç" fractional_part: "beş" } -> eksi üç virgül beş + + Args: + deterministic: if True will provide a single transduction option, + for False multiple transduction are generated (used for audio-based normalization) + """ + + def __init__(self, deterministic: bool = True): + super().__init__(name="decimal", kind="verbalize", deterministic=deterministic) + + optional_sign = pynini.closure(pynini.cross('negative: "true"', "eksi ") + delete_space, 0, 1) + integer = ( + pynutil.delete("integer_part:") + + delete_space + + pynutil.delete('"') + + pynini.closure(NEMO_NOT_QUOTE, 1) + + pynutil.delete('"') + ) + fractional = ( + pynutil.delete("fractional_part:") + + delete_space + + pynutil.delete('"') + + pynini.closure(NEMO_NOT_QUOTE, 1) + + pynutil.delete('"') + ) + self.numbers = optional_sign + integer + delete_space + pynutil.insert(" virgül ") + fractional + self.fst = self.delete_tokens(self.numbers).optimize() diff --git a/nemo_text_processing/text_normalization/tr/verbalizers/fraction.py b/nemo_text_processing/text_normalization/tr/verbalizers/fraction.py new file mode 100644 index 000000000..fa9038bbe --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/verbalizers/fraction.py @@ -0,0 +1,53 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pynini +from pynini.lib import pynutil + +from nemo_text_processing.text_normalization.en.graph_utils import ( + NEMO_NOT_QUOTE, + GraphFst, + delete_preserve_order, + delete_space, +) + + +class FractionFst(GraphFst): + """ + Finite state transducer for verbalizing fractions, e.g. + fraction { integer_part: "iki" denominator: "ikide" numerator: "bir" preserve_order: true } -> iki tam ikide bir + fraction { numerator: "yedi" denominator: "bölü üç yüz altmış beş" } -> yedi bölü üç yüz altmış beş + + Args: + deterministic: if True will provide a single transduction option, + for False multiple transduction are generated (used for audio-based normalization) + """ + + def __init__(self, deterministic: bool = True): + super().__init__(name="fraction", kind="verbalize", deterministic=deterministic) + + def field(name): + return ( + pynutil.delete(f"{name}:") + + delete_space + + pynutil.delete('"') + + pynini.closure(NEMO_NOT_QUOTE, 1) + + pynutil.delete('"') + ) + + integer = pynini.closure(field("integer_part") + delete_space + pynutil.insert(" tam "), 0, 1) + denominator_first = field("denominator") + delete_space + pynutil.insert(" ") + field("numerator") + numerator_first = field("numerator") + delete_space + pynutil.insert(" ") + field("denominator") + graph = integer + (denominator_first | numerator_first) + delete_preserve_order + self.fst = self.delete_tokens(graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/verbalizers/measure.py b/nemo_text_processing/text_normalization/tr/verbalizers/measure.py new file mode 100644 index 000000000..80cbf5d65 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/verbalizers/measure.py @@ -0,0 +1,47 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pynini +from pynini.lib import pynutil + +from nemo_text_processing.text_normalization.en.graph_utils import ( + NEMO_NOT_QUOTE, + GraphFst, + delete_preserve_order, + delete_space, +) + + +class MeasureFst(GraphFst): + """ + Finite state transducer for verbalizing measures, e.g. + measure { cardinal { integer: "beş" } units: "kilometre" } -> beş kilometre + measure { units: "yüzde" cardinal { integer: "on sekiz" } preserve_order: true } -> yüzde on sekiz + + Args: + cardinal: CardinalFst verbalizer + decimal: DecimalFst verbalizer + deterministic: if True will provide a single transduction option, + for False multiple transduction are generated (used for audio-based normalization) + """ + + def __init__(self, cardinal: GraphFst, decimal: GraphFst, deterministic: bool = True): + super().__init__(name="measure", kind="verbalize", deterministic=deterministic) + + unit = pynutil.delete("units:") + delete_space + pynutil.delete('"') + pynini.closure(NEMO_NOT_QUOTE, 1) + unit += pynutil.delete('"') + number = cardinal.fst | decimal.fst + space = delete_space + pynutil.insert(" ") + graph = (number + space + unit | unit + space + number) + delete_preserve_order + self.fst = self.delete_tokens(graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/verbalizers/money.py b/nemo_text_processing/text_normalization/tr/verbalizers/money.py new file mode 100644 index 000000000..634391d8d --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/verbalizers/money.py @@ -0,0 +1,53 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pynini +from pynini.lib import pynutil + +from nemo_text_processing.text_normalization.en.graph_utils import ( + NEMO_NOT_QUOTE, + GraphFst, + delete_preserve_order, + delete_space, +) + + +class MoneyFst(GraphFst): + """ + Finite state transducer for verbalizing money, e.g. + money { integer_part: "bin iki yüz elli" currency_maj: "lira" fractional_part: "elli" currency_min: "kuruş" + preserve_order: true } -> bin iki yüz elli lira elli kuruş + + Args: + deterministic: if True will provide a single transduction option, + for False multiple transduction are generated (used for audio-based normalization) + """ + + def __init__(self, deterministic: bool = True): + super().__init__(name="money", kind="verbalize", deterministic=deterministic) + + def field(name): + return ( + pynutil.delete(f"{name}:") + + delete_space + + pynutil.delete('"') + + pynini.closure(NEMO_NOT_QUOTE, 1) + + pynutil.delete('"') + ) + + space = delete_space + pynutil.insert(" ") + major = field("integer_part") + space + field("currency_maj") + minor = field("fractional_part") + space + field("currency_min") + graph = (major | major + space + minor | minor) + delete_preserve_order + self.fst = self.delete_tokens(graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/verbalizers/ordinal.py b/nemo_text_processing/text_normalization/tr/verbalizers/ordinal.py new file mode 100644 index 000000000..3b9d20a98 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/verbalizers/ordinal.py @@ -0,0 +1,40 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pynini +from pynini.lib import pynutil + +from nemo_text_processing.text_normalization.en.graph_utils import NEMO_NOT_QUOTE, GraphFst, delete_space + + +class OrdinalFst(GraphFst): + """ + Finite state transducer for verbalizing ordinals, e.g. + ordinal { integer: "beşinci" } -> beşinci + + Args: + deterministic: if True will provide a single transduction option, + for False multiple transduction are generated (used for audio-based normalization) + """ + + def __init__(self, deterministic: bool = True): + super().__init__(name="ordinal", kind="verbalize", deterministic=deterministic) + graph = ( + pynutil.delete("integer:") + + delete_space + + pynutil.delete('"') + + pynini.closure(NEMO_NOT_QUOTE, 1) + + pynutil.delete('"') + ) + self.fst = self.delete_tokens(graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/verbalizers/telephone.py b/nemo_text_processing/text_normalization/tr/verbalizers/telephone.py new file mode 100644 index 000000000..a372ac2ad --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/verbalizers/telephone.py @@ -0,0 +1,46 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pynini +from pynini.lib import pynutil + +from nemo_text_processing.text_normalization.en.graph_utils import NEMO_NOT_QUOTE, GraphFst, delete_space + + +class TelephoneFst(GraphFst): + """ + Finite state transducer for verbalizing telephone numbers, e.g. + telephone { country_code: "artı doksan" number_part: "beş yüz otuz iki, yüz yirmi üç, kırk beş, altmış yedi" } + -> artı doksan, beş yüz otuz iki, yüz yirmi üç, kırk beş, altmış yedi + + Args: + deterministic: if True will provide a single transduction option, + for False multiple transduction are generated (used for audio-based normalization) + """ + + def __init__(self, deterministic: bool = True): + super().__init__(name="telephone", kind="verbalize", deterministic=deterministic) + + def field(name): + return ( + pynutil.delete(f"{name}:") + + delete_space + + pynutil.delete('"') + + pynini.closure(NEMO_NOT_QUOTE, 1) + + pynutil.delete('"') + ) + + country_code = pynini.closure(field("country_code") + delete_space + pynutil.insert(", "), 0, 1) + graph = country_code + field("number_part") + self.fst = self.delete_tokens(graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/verbalizers/time.py b/nemo_text_processing/text_normalization/tr/verbalizers/time.py new file mode 100644 index 000000000..193e252da --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/verbalizers/time.py @@ -0,0 +1,50 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pynini +from pynini.lib import pynutil + +from nemo_text_processing.text_normalization.en.graph_utils import NEMO_NOT_QUOTE, GraphFst, delete_space + + +class TimeFst(GraphFst): + """ + Finite state transducer for verbalizing time, e.g. + time { hours: "on dört" minutes: "otuzda" } -> on dört otuzda + time { hours: "on" } -> on + + Args: + deterministic: if True will provide a single transduction option, + for False multiple transduction are generated (used for audio-based normalization) + """ + + def __init__(self, deterministic: bool = True): + super().__init__(name="time", kind="verbalize", deterministic=deterministic) + + def field(name): + return ( + pynutil.delete(f"{name}:") + + delete_space + + pynutil.delete('"') + + pynini.closure(NEMO_NOT_QUOTE, 1) + + pynutil.delete('"') + ) + + space = delete_space + pynutil.insert(" ") + graph = field("hours") + pynini.closure( + space + field("minutes") + pynini.closure(space + field("seconds"), 0, 1), + 0, + 1, + ) + self.fst = self.delete_tokens(graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/verbalizers/verbalize.py b/nemo_text_processing/text_normalization/tr/verbalizers/verbalize.py new file mode 100644 index 000000000..e30f1ba18 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/verbalizers/verbalize.py @@ -0,0 +1,55 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from nemo_text_processing.text_normalization.en.graph_utils import GraphFst +from nemo_text_processing.text_normalization.en.verbalizers.whitelist import WhiteListFst +from nemo_text_processing.text_normalization.tr.verbalizers.cardinal import CardinalFst +from nemo_text_processing.text_normalization.tr.verbalizers.date import DateFst +from nemo_text_processing.text_normalization.tr.verbalizers.decimal import DecimalFst +from nemo_text_processing.text_normalization.tr.verbalizers.fraction import FractionFst +from nemo_text_processing.text_normalization.tr.verbalizers.measure import MeasureFst +from nemo_text_processing.text_normalization.tr.verbalizers.money import MoneyFst +from nemo_text_processing.text_normalization.tr.verbalizers.ordinal import OrdinalFst +from nemo_text_processing.text_normalization.tr.verbalizers.telephone import TelephoneFst +from nemo_text_processing.text_normalization.tr.verbalizers.time import TimeFst + + +class VerbalizeFst(GraphFst): + """ + Composes other verbalizer grammars. + For deployment, this grammar will be compiled and exported to OpenFst Finite State Archive (FAR) File. + More details to deployment at NeMo/tools/text_processing_deployment. + + Args: + deterministic: if True will provide a single transduction option, + for False multiple options (used for audio-based normalization) + """ + + def __init__(self, deterministic: bool = True): + super().__init__(name="verbalize", kind="verbalize", deterministic=deterministic) + cardinal = CardinalFst(deterministic=deterministic) + decimal = DecimalFst(deterministic=deterministic) + graph = ( + cardinal.fst + | decimal.fst + | OrdinalFst(deterministic=deterministic).fst + | FractionFst(deterministic=deterministic).fst + | MeasureFst(cardinal=cardinal, decimal=decimal, deterministic=deterministic).fst + | MoneyFst(deterministic=deterministic).fst + | DateFst(deterministic=deterministic).fst + | TimeFst(deterministic=deterministic).fst + | TelephoneFst(deterministic=deterministic).fst + | WhiteListFst(deterministic=deterministic).fst + ) + self.fst = graph diff --git a/nemo_text_processing/text_normalization/tr/verbalizers/verbalize_final.py b/nemo_text_processing/text_normalization/tr/verbalizers/verbalize_final.py new file mode 100644 index 000000000..eff5234b1 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/verbalizers/verbalize_final.py @@ -0,0 +1,74 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os + +import pynini +from pynini.lib import pynutil + +from nemo_text_processing.text_normalization.en.graph_utils import ( + GraphFst, + delete_extra_space, + delete_space, + generator_main, +) +from nemo_text_processing.text_normalization.en.verbalizers.word import WordFst +from nemo_text_processing.text_normalization.tr.verbalizers.verbalize import VerbalizeFst +from nemo_text_processing.utils.logging import logger + + +class VerbalizeFinalFst(GraphFst): + """ + Finite state transducer that verbalizes an entire sentence + + Args: + deterministic: if True will provide a single transduction option, + for False multiple options (used for audio-based normalization) + cache_dir: path to a dir with .far grammar file. Set to None to avoid using cache. + overwrite_cache: set to True to overwrite .far files + """ + + def __init__( + self, + deterministic: bool = True, + cache_dir: str = None, + overwrite_cache: bool = False, + ): + super().__init__(name="verbalize_final", kind="verbalize", deterministic=deterministic) + + far_file = None + if cache_dir is not None and cache_dir != "None": + os.makedirs(cache_dir, exist_ok=True) + far_file = os.path.join(cache_dir, f"tr_tn_{deterministic}_deterministic_verbalizer.far") + if not overwrite_cache and far_file and os.path.exists(far_file): + self.fst = pynini.Far(far_file, mode="r")["verbalize"] + logger.info(f"VerbalizeFinalFst graph was restored from {far_file}.") + else: + verbalize = VerbalizeFst(deterministic=deterministic).fst + word = WordFst(deterministic=deterministic).fst + types = verbalize | word + graph = ( + pynutil.delete("tokens") + + delete_space + + pynutil.delete("{") + + delete_space + + types + + delete_space + + pynutil.delete("}") + ) + graph = delete_space + pynini.closure(graph + delete_extra_space) + graph + delete_space + self.fst = graph.optimize() + if far_file: + generator_main(far_file, {"verbalize": self.fst}) + logger.info(f"VerbalizeFinalFst grammars are saved to {far_file}.") diff --git a/tests/nemo_text_processing/tr/__init__.py b/tests/nemo_text_processing/tr/__init__.py new file mode 100644 index 000000000..9e3fb699d --- /dev/null +++ b/tests/nemo_text_processing/tr/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/nemo_text_processing/tr/data_text_normalization/__init__.py b/tests/nemo_text_processing/tr/data_text_normalization/__init__.py new file mode 100644 index 000000000..9e3fb699d --- /dev/null +++ b/tests/nemo_text_processing/tr/data_text_normalization/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_cardinal.txt b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_cardinal.txt new file mode 100644 index 000000000..b98fc7fec --- /dev/null +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_cardinal.txt @@ -0,0 +1,26 @@ +1~bir +10~on +11~on bir +45~kırk beş +100~yüz +101~yüz bir +999~dokuz yüz doksan dokuz +1000~bin +1001~bin bir +1250~bin iki yüz elli +2000~iki bin +11000~on bir bin +100000~yüz bin +1000000~bir milyon +1.250.000~bir milyon iki yüz elli bin +2.000.000.000~iki milyar +123456789012~yüz yirmi üç milyar dört yüz elli altı milyon yedi yüz seksen dokuz bin on iki +-5~eksi beş +4'e~dörde +4'ü~dördü +2024'te~iki bin yirmi dörtte +1990'lı~bin dokuz yüz doksanlı +100'den~yüzden +6'ya~altıya +0532~sıfır beş üç iki +004512~sıfır sıfır dört beş bir iki diff --git a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_date.txt b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_date.txt new file mode 100644 index 000000000..b596a4680 --- /dev/null +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_date.txt @@ -0,0 +1,9 @@ +14.03.1988~on dört mart bin dokuz yüz seksen sekiz +21.11.2026~yirmi bir kasım iki bin yirmi altı +05/12/2026~beş aralık iki bin yirmi altı +1.3.2026~bir mart iki bin yirmi altı +01.01.2027'de~bir ocak iki bin yirmi yedide +2026-03-15~on beş mart iki bin yirmi altı +14 Mart 2026~on dört mart iki bin yirmi altı +15 Kasım'da~on beş kasımda +29 ekim~yirmi dokuz ekim diff --git a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_decimal.txt b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_decimal.txt new file mode 100644 index 000000000..b08b2aa8e --- /dev/null +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_decimal.txt @@ -0,0 +1,10 @@ +3,5~üç virgül beş +0,25~sıfır virgül yirmi beş +3,05~üç virgül sıfır beş +3,50~üç virgül elli +1.250,75~bin iki yüz elli virgül yetmiş beş +-0,5~eksi sıfır virgül beş +3.5~üç virgül beş +3,5'e~üç virgül beşe +3,4'ü~üç virgül dördü +1,5 milyon~bir virgül beş milyon diff --git a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_fraction.txt b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_fraction.txt new file mode 100644 index 000000000..4dbd3381c --- /dev/null +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_fraction.txt @@ -0,0 +1,10 @@ +1/2~ikide bir +3/4~dörtte üç +1/100~yüzde bir +1/1000~binde bir +2 1/2~iki tam ikide bir +½~ikide bir +¾~dörtte üç +3/4'ü~dörtte üçü +4/5'ü~beşte dördü +7/365~yedi bölü üç yüz altmış beş diff --git a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_measure.txt b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_measure.txt new file mode 100644 index 000000000..432dd0a05 --- /dev/null +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_measure.txt @@ -0,0 +1,13 @@ +5 km~beş kilometre +5km~beş kilometre +2,5 kg~iki virgül beş kilogram +120 m²~yüz yirmi metrekare +25 °C~yirmi beş santigrat derece +5 km'ye~beş kilometreye +30 dk~otuz dakika +%18~yüzde on sekiz +% 18~yüzde on sekiz +%3,5~yüzde üç virgül beş +%3.5~yüzde üç virgül beş +%14'ü~yüzde on dördü +15%~yüzde on beş diff --git a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_money.txt b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_money.txt new file mode 100644 index 000000000..586f5420e --- /dev/null +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_money.txt @@ -0,0 +1,14 @@ +1.250,50 TL~bin iki yüz elli lira elli kuruş +2450.75 TL~iki bin dört yüz elli lira yetmiş beş kuruş +100 TL~yüz lira +5 ₺~beş lira +₺1.250~bin iki yüz elli lira +1,5 TL~bir lira elli kuruş +0,50 TL~elli kuruş +100,00 TL~yüz lira +100 TL'ye~yüz liraya +50 TL'lik~elli liralık +$100~yüz dolar +25 €~yirmi beş avro +10,50 USD~on dolar elli sent +£5~beş sterlin diff --git a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_ordinal.txt b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_ordinal.txt new file mode 100644 index 000000000..092ad0b58 --- /dev/null +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_ordinal.txt @@ -0,0 +1,12 @@ +1'inci~birinci +2'nci~ikinci +3'üncü~üçüncü +4üncü~dördüncü +6'ncı~altıncı +9'uncu~dokuzuncu +21'inci~yirmi birinci +40'ıncı~kırkıncı +100'üncü~yüzüncü +1000'inci~bininci +3. taksit~üçüncü taksit +1. ve 2. sırada~birinci ve ikinci sırada diff --git a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_telephone.txt b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_telephone.txt new file mode 100644 index 000000000..8890bf22a --- /dev/null +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_telephone.txt @@ -0,0 +1,8 @@ +0532 123 45 67~sıfır beş yüz otuz iki, yüz yirmi üç, kırk beş, altmış yedi +0850-222-23-35~sıfır sekiz yüz elli, iki yüz yirmi iki, yirmi üç, otuz beş +0212 555 04 33~sıfır iki yüz on iki, beş yüz elli beş, sıfır dört, otuz üç +(0212) 555 44 33~sıfır iki yüz on iki, beş yüz elli beş, kırk dört, otuz üç +05321234567~sıfır beş yüz otuz iki, yüz yirmi üç, kırk beş, altmış yedi ++90 532 123 45 67~artı doksan, beş yüz otuz iki, yüz yirmi üç, kırk beş, altmış yedi ++905321234567~artı doksan, beş yüz otuz iki, yüz yirmi üç, kırk beş, altmış yedi +444 0 123~dört yüz kırk dört, sıfır, yüz yirmi üç diff --git a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_time.txt b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_time.txt new file mode 100644 index 000000000..bdd01a653 --- /dev/null +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_time.txt @@ -0,0 +1,11 @@ +14:30~on dört otuz +09:05~dokuz sıfır beş +10:00~on +00:15~sıfır on beş +23:59~yirmi üç elli dokuz +14:30'da~on dört otuzda +10:00'a~ona +14:04'e~on dört sıfır dörde +09.30~dokuz otuz +14.30'da~on dört otuzda +12:30:15~on iki otuz on beş diff --git a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_whitelist.txt b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_whitelist.txt new file mode 100644 index 000000000..4184162ef --- /dev/null +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_whitelist.txt @@ -0,0 +1,8 @@ +Dr.~doktor +Prof.~profesör +vb.~ve benzeri +vs.~vesaire +T.C.~te ce +KDV~katma değer vergisi +M.Ö.~milattan önce +24/7~yirmi dört yedi diff --git a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_word.txt b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_word.txt new file mode 100644 index 000000000..475cd6f47 --- /dev/null +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_word.txt @@ -0,0 +1,5 @@ +merhaba~merhaba +Türkiye'nin~Türkiye'nin +İstanbul~İstanbul +ışık~ışık +şubeye gidin~şubeye gidin diff --git a/tests/nemo_text_processing/tr/test_cardinal.py b/tests/nemo_text_processing/tr/test_cardinal.py new file mode 100644 index 000000000..b37ce7103 --- /dev/null +++ b/tests/nemo_text_processing/tr/test_cardinal.py @@ -0,0 +1,31 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pytest +from parameterized import parameterized + +from nemo_text_processing.text_normalization.normalize import Normalizer + +from ..utils import CACHE_DIR, parse_test_case_file + + +class TestCardinal: + normalizer_tr = Normalizer(input_case="cased", lang="tr", cache_dir=CACHE_DIR, overwrite_cache=False) + + @parameterized.expand(parse_test_case_file("tr/data_text_normalization/test_cases_cardinal.txt")) + @pytest.mark.run_only_on("CPU") + @pytest.mark.unit + def test_norm(self, test_input, expected): + pred = self.normalizer_tr.normalize(test_input, verbose=False) + assert pred == expected diff --git a/tests/nemo_text_processing/tr/test_date.py b/tests/nemo_text_processing/tr/test_date.py new file mode 100644 index 000000000..cc21dfe3f --- /dev/null +++ b/tests/nemo_text_processing/tr/test_date.py @@ -0,0 +1,31 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pytest +from parameterized import parameterized + +from nemo_text_processing.text_normalization.normalize import Normalizer + +from ..utils import CACHE_DIR, parse_test_case_file + + +class TestDate: + normalizer_tr = Normalizer(input_case="cased", lang="tr", cache_dir=CACHE_DIR, overwrite_cache=False) + + @parameterized.expand(parse_test_case_file("tr/data_text_normalization/test_cases_date.txt")) + @pytest.mark.run_only_on("CPU") + @pytest.mark.unit + def test_norm(self, test_input, expected): + pred = self.normalizer_tr.normalize(test_input, verbose=False) + assert pred == expected diff --git a/tests/nemo_text_processing/tr/test_decimal.py b/tests/nemo_text_processing/tr/test_decimal.py new file mode 100644 index 000000000..093ac9f43 --- /dev/null +++ b/tests/nemo_text_processing/tr/test_decimal.py @@ -0,0 +1,31 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pytest +from parameterized import parameterized + +from nemo_text_processing.text_normalization.normalize import Normalizer + +from ..utils import CACHE_DIR, parse_test_case_file + + +class TestDecimal: + normalizer_tr = Normalizer(input_case="cased", lang="tr", cache_dir=CACHE_DIR, overwrite_cache=False) + + @parameterized.expand(parse_test_case_file("tr/data_text_normalization/test_cases_decimal.txt")) + @pytest.mark.run_only_on("CPU") + @pytest.mark.unit + def test_norm(self, test_input, expected): + pred = self.normalizer_tr.normalize(test_input, verbose=False) + assert pred == expected diff --git a/tests/nemo_text_processing/tr/test_fraction.py b/tests/nemo_text_processing/tr/test_fraction.py new file mode 100644 index 000000000..27090d41e --- /dev/null +++ b/tests/nemo_text_processing/tr/test_fraction.py @@ -0,0 +1,31 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pytest +from parameterized import parameterized + +from nemo_text_processing.text_normalization.normalize import Normalizer + +from ..utils import CACHE_DIR, parse_test_case_file + + +class TestFraction: + normalizer_tr = Normalizer(input_case="cased", lang="tr", cache_dir=CACHE_DIR, overwrite_cache=False) + + @parameterized.expand(parse_test_case_file("tr/data_text_normalization/test_cases_fraction.txt")) + @pytest.mark.run_only_on("CPU") + @pytest.mark.unit + def test_norm(self, test_input, expected): + pred = self.normalizer_tr.normalize(test_input, verbose=False) + assert pred == expected diff --git a/tests/nemo_text_processing/tr/test_measure.py b/tests/nemo_text_processing/tr/test_measure.py new file mode 100644 index 000000000..c90496528 --- /dev/null +++ b/tests/nemo_text_processing/tr/test_measure.py @@ -0,0 +1,31 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pytest +from parameterized import parameterized + +from nemo_text_processing.text_normalization.normalize import Normalizer + +from ..utils import CACHE_DIR, parse_test_case_file + + +class TestMeasure: + normalizer_tr = Normalizer(input_case="cased", lang="tr", cache_dir=CACHE_DIR, overwrite_cache=False) + + @parameterized.expand(parse_test_case_file("tr/data_text_normalization/test_cases_measure.txt")) + @pytest.mark.run_only_on("CPU") + @pytest.mark.unit + def test_norm(self, test_input, expected): + pred = self.normalizer_tr.normalize(test_input, verbose=False) + assert pred == expected diff --git a/tests/nemo_text_processing/tr/test_money.py b/tests/nemo_text_processing/tr/test_money.py new file mode 100644 index 000000000..144f7d28a --- /dev/null +++ b/tests/nemo_text_processing/tr/test_money.py @@ -0,0 +1,31 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pytest +from parameterized import parameterized + +from nemo_text_processing.text_normalization.normalize import Normalizer + +from ..utils import CACHE_DIR, parse_test_case_file + + +class TestMoney: + normalizer_tr = Normalizer(input_case="cased", lang="tr", cache_dir=CACHE_DIR, overwrite_cache=False) + + @parameterized.expand(parse_test_case_file("tr/data_text_normalization/test_cases_money.txt")) + @pytest.mark.run_only_on("CPU") + @pytest.mark.unit + def test_norm(self, test_input, expected): + pred = self.normalizer_tr.normalize(test_input, verbose=False) + assert pred == expected diff --git a/tests/nemo_text_processing/tr/test_ordinal.py b/tests/nemo_text_processing/tr/test_ordinal.py new file mode 100644 index 000000000..16f22cbbc --- /dev/null +++ b/tests/nemo_text_processing/tr/test_ordinal.py @@ -0,0 +1,31 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pytest +from parameterized import parameterized + +from nemo_text_processing.text_normalization.normalize import Normalizer + +from ..utils import CACHE_DIR, parse_test_case_file + + +class TestOrdinal: + normalizer_tr = Normalizer(input_case="cased", lang="tr", cache_dir=CACHE_DIR, overwrite_cache=False) + + @parameterized.expand(parse_test_case_file("tr/data_text_normalization/test_cases_ordinal.txt")) + @pytest.mark.run_only_on("CPU") + @pytest.mark.unit + def test_norm(self, test_input, expected): + pred = self.normalizer_tr.normalize(test_input, verbose=False) + assert pred == expected diff --git a/tests/nemo_text_processing/tr/test_sparrowhawk_normalization.sh b/tests/nemo_text_processing/tr/test_sparrowhawk_normalization.sh new file mode 100644 index 000000000..b6281fa60 --- /dev/null +++ b/tests/nemo_text_processing/tr/test_sparrowhawk_normalization.sh @@ -0,0 +1,81 @@ +#! /bin/sh + +GRAMMARS_DIR=${1:-"/workspace/sparrowhawk/documentation/grammars"} +PROJECT_DIR=${2:-"/workspace/tests/"} + +runtest () { + input=$1 + echo "INPUT is $input" + cd ${GRAMMARS_DIR} + + # read test file + while read testcase; do + IFS='~' read written spoken <<< $testcase + denorm_pred=$(echo $written | normalizer_main --config=sparrowhawk_configuration.ascii_proto 2>&1 | tail -n 1) + + # trim white space + spoken="$(echo -e "${spoken}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')" + denorm_pred="$(echo -e "${denorm_pred}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')" + + # input expected actual + assertEquals "$written" "$spoken" "$denorm_pred" + done < "$input" +} + +testTNCardinal() { + input=$PROJECT_DIR/tr/data_text_normalization/test_cases_cardinal.txt + runtest $input +} + +testTNOrdinal() { + input=$PROJECT_DIR/tr/data_text_normalization/test_cases_ordinal.txt + runtest $input +} + +testTNDecimal() { + input=$PROJECT_DIR/tr/data_text_normalization/test_cases_decimal.txt + runtest $input +} + +testTNFraction() { + input=$PROJECT_DIR/tr/data_text_normalization/test_cases_fraction.txt + runtest $input +} + +testTNMoney() { + input=$PROJECT_DIR/tr/data_text_normalization/test_cases_money.txt + runtest $input +} + +testTNMeasure() { + input=$PROJECT_DIR/tr/data_text_normalization/test_cases_measure.txt + runtest $input +} + +testTNDate() { + input=$PROJECT_DIR/tr/data_text_normalization/test_cases_date.txt + runtest $input +} + +testTNTime() { + input=$PROJECT_DIR/tr/data_text_normalization/test_cases_time.txt + runtest $input +} + +testTNTelephone() { + input=$PROJECT_DIR/tr/data_text_normalization/test_cases_telephone.txt + runtest $input +} + +testTNWhitelist() { + input=$PROJECT_DIR/tr/data_text_normalization/test_cases_whitelist.txt + runtest $input +} + +testTNWord() { + input=$PROJECT_DIR/tr/data_text_normalization/test_cases_word.txt + runtest $input +} + +# Load shUnit2 +. $PROJECT_DIR/../shunit2/shunit2 diff --git a/tests/nemo_text_processing/tr/test_telephone.py b/tests/nemo_text_processing/tr/test_telephone.py new file mode 100644 index 000000000..a29d5782e --- /dev/null +++ b/tests/nemo_text_processing/tr/test_telephone.py @@ -0,0 +1,31 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pytest +from parameterized import parameterized + +from nemo_text_processing.text_normalization.normalize import Normalizer + +from ..utils import CACHE_DIR, parse_test_case_file + + +class TestTelephone: + normalizer_tr = Normalizer(input_case="cased", lang="tr", cache_dir=CACHE_DIR, overwrite_cache=False) + + @parameterized.expand(parse_test_case_file("tr/data_text_normalization/test_cases_telephone.txt")) + @pytest.mark.run_only_on("CPU") + @pytest.mark.unit + def test_norm(self, test_input, expected): + pred = self.normalizer_tr.normalize(test_input, verbose=False) + assert pred == expected diff --git a/tests/nemo_text_processing/tr/test_time.py b/tests/nemo_text_processing/tr/test_time.py new file mode 100644 index 000000000..c3846443a --- /dev/null +++ b/tests/nemo_text_processing/tr/test_time.py @@ -0,0 +1,31 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pytest +from parameterized import parameterized + +from nemo_text_processing.text_normalization.normalize import Normalizer + +from ..utils import CACHE_DIR, parse_test_case_file + + +class TestTime: + normalizer_tr = Normalizer(input_case="cased", lang="tr", cache_dir=CACHE_DIR, overwrite_cache=False) + + @parameterized.expand(parse_test_case_file("tr/data_text_normalization/test_cases_time.txt")) + @pytest.mark.run_only_on("CPU") + @pytest.mark.unit + def test_norm(self, test_input, expected): + pred = self.normalizer_tr.normalize(test_input, verbose=False) + assert pred == expected diff --git a/tests/nemo_text_processing/tr/test_whitelist.py b/tests/nemo_text_processing/tr/test_whitelist.py new file mode 100644 index 000000000..274418402 --- /dev/null +++ b/tests/nemo_text_processing/tr/test_whitelist.py @@ -0,0 +1,31 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pytest +from parameterized import parameterized + +from nemo_text_processing.text_normalization.normalize import Normalizer + +from ..utils import CACHE_DIR, parse_test_case_file + + +class TestWhitelist: + normalizer_tr = Normalizer(input_case="cased", lang="tr", cache_dir=CACHE_DIR, overwrite_cache=False) + + @parameterized.expand(parse_test_case_file("tr/data_text_normalization/test_cases_whitelist.txt")) + @pytest.mark.run_only_on("CPU") + @pytest.mark.unit + def test_norm(self, test_input, expected): + pred = self.normalizer_tr.normalize(test_input, verbose=False) + assert pred == expected diff --git a/tests/nemo_text_processing/tr/test_word.py b/tests/nemo_text_processing/tr/test_word.py new file mode 100644 index 000000000..0a49380fd --- /dev/null +++ b/tests/nemo_text_processing/tr/test_word.py @@ -0,0 +1,31 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pytest +from parameterized import parameterized + +from nemo_text_processing.text_normalization.normalize import Normalizer + +from ..utils import CACHE_DIR, parse_test_case_file + + +class TestWord: + normalizer_tr = Normalizer(input_case="cased", lang="tr", cache_dir=CACHE_DIR, overwrite_cache=False) + + @parameterized.expand(parse_test_case_file("tr/data_text_normalization/test_cases_word.txt")) + @pytest.mark.run_only_on("CPU") + @pytest.mark.unit + def test_norm(self, test_input, expected): + pred = self.normalizer_tr.normalize(test_input, verbose=False) + assert pred == expected diff --git a/tools/text_processing_deployment/pynini_export.py b/tools/text_processing_deployment/pynini_export.py index 73a4fc138..f1b467015 100644 --- a/tools/text_processing_deployment/pynini_export.py +++ b/tools/text_processing_deployment/pynini_export.py @@ -95,6 +95,7 @@ def parse_args(): "ru", 'fr', 'hu', + 'tr', 'sv', 'vi', 'zh', @@ -229,6 +230,11 @@ def parse_args(): ClassifyFst as TNClassifyFst, ) from nemo_text_processing.text_normalization.hu.verbalizers.verbalize import VerbalizeFst as TNVerbalizeFst + elif args.language == 'tr': + from nemo_text_processing.text_normalization.tr.taggers.tokenize_and_classify import ( + ClassifyFst as TNClassifyFst, + ) + from nemo_text_processing.text_normalization.tr.verbalizers.verbalize import VerbalizeFst as TNVerbalizeFst elif args.language == 'sv': from nemo_text_processing.inverse_text_normalization.sv.taggers.tokenize_and_classify import ( ClassifyFst as ITNClassifyFst, From 8d62bf955c9c364e5644ff778953c6ec5f65c909 Mon Sep 17 00:00:00 2001 From: Doruk Dumlu Date: Sat, 28 Nov 2026 11:48:29 -0500 Subject: [PATCH 2/6] Turkish TN: pass the Sparrowhawk tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A multi-word whitelist expansion is emitted as one name token per word: Sparrowhawk prints name tokens as they are, so the non-breaking space from convert_space stayed in its output ("vb." -> "ve benzeri"). - "0,50 TL" had two paths of equal weight ("elli kuruş" and "sıfır lira elli kuruş"); pynini and Sparrowhawk broke the tie differently. The zero major path is gone when a minor part follows. Signed-off-by: Doruk Dumlu --- .../text_normalization/tr/taggers/money.py | 9 ++++++++- .../text_normalization/tr/taggers/whitelist.py | 9 ++++++--- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/nemo_text_processing/text_normalization/tr/taggers/money.py b/nemo_text_processing/text_normalization/tr/taggers/money.py index 4689d058d..459f3e998 100644 --- a/nemo_text_processing/text_normalization/tr/taggers/money.py +++ b/nemo_text_processing/text_normalization/tr/taggers/money.py @@ -52,6 +52,13 @@ def __init__(self, cardinal: GraphFst, deterministic: bool = True): lira_suffix = pynini.string_file(get_abs_path("data/money/lira_suffix.tsv")) integer = pynutil.insert('integer_part: "') + cardinal.graph + pynutil.insert('"') + # with a minor part, "0,50 TL" is only "elli kuruş": no zero major path, so there is no tie for Sparrowhawk + # to break differently from pynini + nonzero_integer = ( + pynutil.insert('integer_part: "') + + ((pynini.closure(NEMO_DIGIT | ".", 1) - "0") @ cardinal.graph) + + pynutil.insert('"') + ) # minor unit as hundredths: "5" -> "elli", "05" -> "beş", "50" -> "elli"; "0" / "00" is not read minor_digits = ( @@ -68,7 +75,7 @@ def __init__(self, cardinal: GraphFst, deterministic: bool = True): mino = pynutil.insert(f' currency_min: "{minor}"') amount = pynini.union( integer + pynini.closure(no_minor, 0, 1) + maj, - integer + maj + fractional + mino, + nonzero_integer + maj + fractional + mino, pynutil.delete("0") + fractional + mino, ) amount += pynutil.insert(" preserve_order: true") diff --git a/nemo_text_processing/text_normalization/tr/taggers/whitelist.py b/nemo_text_processing/text_normalization/tr/taggers/whitelist.py index dde405cc6..cb96ad311 100644 --- a/nemo_text_processing/text_normalization/tr/taggers/whitelist.py +++ b/nemo_text_processing/text_normalization/tr/taggers/whitelist.py @@ -15,7 +15,7 @@ import pynini from pynini.lib import pynutil -from nemo_text_processing.text_normalization.en.graph_utils import GraphFst, convert_space +from nemo_text_processing.text_normalization.en.graph_utils import NEMO_SIGMA, GraphFst from nemo_text_processing.text_normalization.tr.utils import get_abs_path, load_labels @@ -28,7 +28,7 @@ class WhiteListFst(GraphFst): """ Finite state transducer for classifying whitelist, e.g. "Dr." -> tokens { name: "doktor" } - "vb." -> tokens { name: "ve benzeri" } + "vb." -> tokens { name: "ve" } tokens { name: "benzeri" } This class has highest priority among all classifier grammars. Whitelisted tokens are defined and loaded from "data/whitelist.tsv". @@ -52,5 +52,8 @@ def _get_whitelist_graph(input_case, file): if input_file: graph = _get_whitelist_graph(input_case, input_file) - self.graph = convert_space(graph).optimize() + # A multi-word expansion becomes one name token per word ("vb." -> "ve", "benzeri"). Sparrowhawk prints a name + # token as it is, so a non-breaking space (convert_space) would stay in its output. + split_words = pynini.cdrewrite(pynini.cross(" ", '" } tokens { name: "'), "", "", NEMO_SIGMA) + self.graph = (graph @ split_words).optimize() self.fst = (pynutil.insert('name: "') + self.graph + pynutil.insert('"')).optimize() From a912db9cc00fe953ea00b3a66072ebbf1be3fa0d Mon Sep 17 00:00:00 2001 From: Doruk Dumlu Date: Sat, 28 Nov 2026 14:49:16 -0500 Subject: [PATCH 3/6] Turkish TN: rebuild suffixes for the word read, general-domain coverage MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Suffixes after an apostrophe are rebuilt for the last word read (vowel harmony, d/t, buffer consonants, softening), so 'TL'ye' -> 'liraya', 'Aralık'a' -> 'aralığa', '%2,5'luk' -> 'yüzde iki buçukluk', '4'de' -> 'dörtte'. Adds ranges and scores, Roman numerals, ratios, dimensions, speeds, versions, codes after 'kodunuz', 'saat 17.30', and fixes amounts with kuruş plus a suffix, lower-cased currency codes and English number formats. Signed-off-by: Doruk Dumlu --- .../tr/data/dates/month_names.tsv | 22 ++ .../tr/data/measures/units.tsv | 14 ++ .../tr/data/money/currency.tsv | 4 +- .../tr/data/money/lira_suffix.tsv | 14 -- .../tr/data/ordinals/ordinal_nouns.tsv | 39 ++++ .../text_normalization/tr/data/whitelist.tsv | 1 - .../text_normalization/tr/graph_utils.py | 23 +- .../text_normalization/tr/inflection.py | 147 ++++++++++++ .../text_normalization/tr/taggers/date.py | 45 +++- .../text_normalization/tr/taggers/decimal.py | 9 +- .../text_normalization/tr/taggers/fraction.py | 3 +- .../text_normalization/tr/taggers/measure.py | 50 +++- .../text_normalization/tr/taggers/money.py | 114 +++++---- .../text_normalization/tr/taggers/ordinal.py | 17 ++ .../tr/taggers/telephone.py | 5 +- .../text_normalization/tr/taggers/time.py | 30 ++- .../tr/taggers/tokenize_and_classify.py | 219 ++++++++++++++---- .../tr/taggers/whitelist.py | 12 +- .../text_normalization/tr/utils.py | 15 -- .../text_normalization/tr/verbalizers/date.py | 1 + .../tr/verbalizers/decimal.py | 5 +- .../tr/verbalizers/measure.py | 1 - .../tr/verbalizers/verbalize.py | 2 +- .../test_cases_cardinal.txt | 8 + .../test_cases_date.txt | 5 + .../test_cases_decimal.txt | 11 +- .../test_cases_fraction.txt | 1 + .../test_cases_lower_cased.txt | 5 + .../test_cases_measure.txt | 28 ++- .../test_cases_money.txt | 13 +- .../test_cases_ordinal.txt | 1 + .../test_cases_sentences.txt | 31 +++ .../test_cases_telephone.txt | 2 +- .../test_cases_time.txt | 8 +- .../nemo_text_processing/tr/test_cardinal.py | 6 +- tests/nemo_text_processing/tr/test_date.py | 6 +- tests/nemo_text_processing/tr/test_decimal.py | 6 +- .../nemo_text_processing/tr/test_fraction.py | 6 +- .../tr/test_lower_cased.py | 31 +++ tests/nemo_text_processing/tr/test_measure.py | 6 +- tests/nemo_text_processing/tr/test_money.py | 6 +- tests/nemo_text_processing/tr/test_ordinal.py | 6 +- .../nemo_text_processing/tr/test_sentences.py | 31 +++ .../tr/test_sparrowhawk_normalization.sh | 25 +- .../nemo_text_processing/tr/test_telephone.py | 6 +- tests/nemo_text_processing/tr/test_time.py | 6 +- .../nemo_text_processing/tr/test_whitelist.py | 6 +- tests/nemo_text_processing/tr/test_word.py | 6 +- 48 files changed, 827 insertions(+), 231 deletions(-) delete mode 100644 nemo_text_processing/text_normalization/tr/data/money/lira_suffix.tsv create mode 100644 nemo_text_processing/text_normalization/tr/data/ordinals/ordinal_nouns.tsv create mode 100644 nemo_text_processing/text_normalization/tr/inflection.py create mode 100644 tests/nemo_text_processing/tr/data_text_normalization/test_cases_lower_cased.txt create mode 100644 tests/nemo_text_processing/tr/data_text_normalization/test_cases_sentences.txt create mode 100644 tests/nemo_text_processing/tr/test_lower_cased.py create mode 100644 tests/nemo_text_processing/tr/test_sentences.py diff --git a/nemo_text_processing/text_normalization/tr/data/dates/month_names.tsv b/nemo_text_processing/text_normalization/tr/data/dates/month_names.tsv index e04b965a8..e53bb85fb 100644 --- a/nemo_text_processing/text_normalization/tr/data/dates/month_names.tsv +++ b/nemo_text_processing/text_normalization/tr/data/dates/month_names.tsv @@ -22,3 +22,25 @@ eylül eylül ekim ekim kasım kasım aralık aralık +Oca ocak +Oca. ocak +Şub şubat +Şub. şubat +Mar mart +Mar. mart +Nis nisan +Nis. nisan +Haz haziran +Haz. haziran +Tem temmuz +Tem. temmuz +Ağu ağustos +Ağu. ağustos +Eyl eylül +Eyl. eylül +Eki ekim +Eki. ekim +Kas kasım +Kas. kasım +Ara aralık +Ara. aralık diff --git a/nemo_text_processing/text_normalization/tr/data/measures/units.tsv b/nemo_text_processing/text_normalization/tr/data/measures/units.tsv index f0f26402e..30c232f86 100644 --- a/nemo_text_processing/text_normalization/tr/data/measures/units.tsv +++ b/nemo_text_processing/text_normalization/tr/data/measures/units.tsv @@ -29,3 +29,17 @@ TB terabayt dk dakika sn saniye ms milisaniye +gr gram +GHz gigahertz +MHz megahertz +Hz hertz +Gbps gigabit +Mbps megabit +IU ünite +ng/ml nanogram bölü mililitre +mg/dl miligram bölü desilitre +mg/kg miligram bölü kilogram +dk. dakika +sn. saniye +sa. saat +mmHg milimetre cıva diff --git a/nemo_text_processing/text_normalization/tr/data/money/currency.tsv b/nemo_text_processing/text_normalization/tr/data/money/currency.tsv index ce7d61b40..b3b6d8011 100644 --- a/nemo_text_processing/text_normalization/tr/data/money/currency.tsv +++ b/nemo_text_processing/text_normalization/tr/data/money/currency.tsv @@ -3,7 +3,7 @@ TL lira kuruş TRY lira kuruş $ dolar sent USD dolar sent -€ avro sent -EUR avro sent +€ euro sent +EUR euro sent £ sterlin peni GBP sterlin peni diff --git a/nemo_text_processing/text_normalization/tr/data/money/lira_suffix.tsv b/nemo_text_processing/text_normalization/tr/data/money/lira_suffix.tsv deleted file mode 100644 index 6f1c63e01..000000000 --- a/nemo_text_processing/text_normalization/tr/data/money/lira_suffix.tsv +++ /dev/null @@ -1,14 +0,0 @@ -ye ya -ya ya -yi yı -yı yı -den dan -dan dan -de da -da da -nin nın -nın nın -lik lık -lık lık -yle yla -yla yla diff --git a/nemo_text_processing/text_normalization/tr/data/ordinals/ordinal_nouns.tsv b/nemo_text_processing/text_normalization/tr/data/ordinals/ordinal_nouns.tsv new file mode 100644 index 000000000..747993013 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/data/ordinals/ordinal_nouns.tsv @@ -0,0 +1,39 @@ +taksit +sıra +kat +madde +gün +hafta +ay +yıl +sınıf +bölüm +cadde +sokak +kez +defa +dönem +yarı +çeyrek +sezon +tur +etap +aşama +kademe +derece +seviye +adım +sayfa +satır +paragraf +fıkra +bent +kısım +yüzyıl +kuşak +nesil +hat +şube +ödeme +fatura +vade diff --git a/nemo_text_processing/text_normalization/tr/data/whitelist.tsv b/nemo_text_processing/text_normalization/tr/data/whitelist.tsv index 6bb290c00..ae20bfeb4 100644 --- a/nemo_text_processing/text_normalization/tr/data/whitelist.tsv +++ b/nemo_text_processing/text_normalization/tr/data/whitelist.tsv @@ -18,5 +18,4 @@ M.Ö. milattan önce M.S. milattan sonra T.C. te ce KDV katma değer vergisi -TL lira 24/7 yirmi dört yedi diff --git a/nemo_text_processing/text_normalization/tr/graph_utils.py b/nemo_text_processing/text_normalization/tr/graph_utils.py index b0be4f562..49ba28824 100644 --- a/nemo_text_processing/text_normalization/tr/graph_utils.py +++ b/nemo_text_processing/text_normalization/tr/graph_utils.py @@ -13,35 +13,28 @@ # limitations under the License. import pynini -from pynini.lib import pynutil -from nemo_text_processing.text_normalization.en.graph_utils import NEMO_SIGMA +from nemo_text_processing.text_normalization.tr.inflection import MARK, get_suffix_rewrite TR_LOWER = pynini.union(*"abcçdefgğhıijklmnoöprsştuüvyzâîûqwx").optimize() TR_UPPER = pynini.union(*"ABCÇDEFGĞHIİJKLMNOÖPRSŞTUÜVYZÂÎÛQWX").optimize() TR_ALPHA = pynini.union(TR_LOWER, TR_UPPER).optimize() -TR_VOWEL = pynini.union(*"aeıioöuüâîû").optimize() # Turkish separates a case or possessive suffix from a numeral with an apostrophe: "4'e", "2024'te", "10:30'da". -APOSTROPHE = pynini.union("'", "’") -SUFFIX = pynini.closure(TR_LOWER, 1).optimize() - -# "dört" is the only number word whose final consonant softens before a vowel: "4'e" -> "dörde", "4'ü" -> "dördü". -SOFTEN_DORT = pynini.cdrewrite(pynini.cross("dört", "dörd"), "", TR_VOWEL, NEMO_SIGMA).optimize() +APOSTROPHE = pynini.union("'", "’", "‘", "´") +SUFFIX = pynini.closure(TR_ALPHA, 1).optimize() def attach_suffix(graph: "pynini.FstLike") -> "pynini.FstLike": """ - Appends the suffix written after an apostrophe to the spoken form of a number, e.g. - "4'e" -> "dörde", "1990'da" -> "bin dokuz yüz doksanda", "3,5'e" -> "üç virgül beşe" - - The written suffix already agrees with how the number is read (vowel harmony and voicing follow the spoken - number), so it is copied as written; only "dört" changes its final consonant. + Appends the suffix written after an apostrophe to the spoken form, rebuilt for its last word, e.g. + "4'e" -> "dörde", "1990'lı" -> "bin dokuz yüz doksanlı", "4'de" -> "dörtte", "100 TL'ye" -> "yüz liraya" + See inflection.py. Args: - graph: an fst whose output is the spoken form of a number + graph: an fst whose output is spoken words Returns: an fst that accepts the input of graph followed by an apostrophe and a suffix """ - return ((graph + pynutil.delete(APOSTROPHE) + SUFFIX) @ SOFTEN_DORT).optimize() + return ((graph + pynini.cross(APOSTROPHE, MARK) + SUFFIX) @ get_suffix_rewrite()).optimize() diff --git a/nemo_text_processing/text_normalization/tr/inflection.py b/nemo_text_processing/text_normalization/tr/inflection.py new file mode 100644 index 000000000..a9fba7062 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/inflection.py @@ -0,0 +1,147 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Suffixes written after a number, a currency code or a month name, re-built for the word that is read. + +Turkish writes a suffix after an apostrophe: "4'e", "100 TL'ye", "%2,5'luk", "31 Aralık'a". The writer chooses the +suffix for what they have in mind ("TL" read as letters, "2,5" as "iki buçuk") and sometimes misspells it ("4'de"), +so copying it after the spoken word gives non-words ("liraye", "beşluk", "aralıka", "dörtde"). + +The words a suffix can land on are a closed set: number words, currency names, month names and "buçuk". For each of +them, every surface form of the common suffixes is mapped to the form that word takes (vowel harmony, d/t and c/ç +assimilation, buffer consonants y/n/s/ş, and softening: "dört" -> "dördü", "aralık" -> "aralığa"). A suffix that is +not in the table is copied as written, at a higher cost. +""" + +import re +from functools import lru_cache + +import pynini +from pynini.lib import pynutil + +from nemo_text_processing.text_normalization.en.graph_utils import NEMO_CHAR, NEMO_SPACE +from nemo_text_processing.text_normalization.en.utils import load_labels +from nemo_text_processing.text_normalization.tr.utils import get_abs_path + +VOWELS = "aeıioöuüâîû" +BACK_VOWELS = "aıouâû" +ROUNDED_VOWELS = "ouöüû" +VOICELESS = "fstkçşhp" + +# Final consonants that soften before a vowel in these words ("dört" -> "dördü", "ocak" -> "ocağa"). +SOFTENING = {"dört": "dörd", "ocak": "ocağ", "aralık": "aralığ", "buçuk": "buçuğ"} + +# Common suffixes after numbers, currencies and months, in archiphoneme notation: +# A = a/e, I = ı/i/u/ü, D = d/t, C = c/ç, (y)(n)(s)(ş) = buffer consonant after a vowel. +# Where two suffixes share a surface form ("ü": accusative or possessive), the first one wins. +SUFFIXES = [ + "(y)I", "(y)A", "DA", "DAn", "(n)In", "(y)lA", + "(s)I", "(s)InI", "(s)InA", "(s)InDA", "(s)InDAn", "(s)InIn", "(s)I(y)lA", + "lI", "lIk", "lIk(y)A", "lIk(y)I", "lIkDA", "lIkDAn", "lIk(s)I", "lIk(y)lA", + "sIz", "lAr", "lArI", "lArA", "lArDA", "lArDAn", "lArIn", "lArDAki", "DAki", + "CA", "DIr", "(y)DI", "(y)mIş", "(y)sA", "(ş)Ar", +] # fmt: skip + +MARK = "|" # stands for the apostrophe between the spoken word and the suffix while the suffix is rebuilt + + +def _last_vowel(text: str) -> str: + if text.endswith("saat"): # takes front suffixes: "saate", "kilovatsaati" + return "e" + for char in reversed(text): + if char in VOWELS: + return char + return "e" + + +def inflect_word(word: str, suffix: str) -> str: + """ + Attaches a suffix given in archiphoneme notation to a word, e.g. + inflect_word("lira", "(y)A") -> "liraya", inflect_word("dört", "(y)I") -> "dördü", + inflect_word("buçuk", "lIk") -> "buçukluk", inflect_word("aralık", "(y)A") -> "aralığa" + """ + out = word + soft_k = False # the "k" of -lIk softens before a vowel: "liralığı" + for match in re.finditer(r"\(([ynsş])\)|[AIDC]|[^AIDC()]", suffix): + token = match.group(0) + if match.group(1): + if out[-1] in VOWELS: + out += match.group(1) + continue + if token == "A": + char = "a" if _last_vowel(out) in BACK_VOWELS else "e" + elif token == "I": + last = _last_vowel(out) + back, rounded = last in BACK_VOWELS, last in ROUNDED_VOWELS + char = {(True, False): "ı", (False, False): "i", (True, True): "u", (False, True): "ü"}[(back, rounded)] + elif token == "D": + char = "t" if out[-1] in VOICELESS else "d" + elif token == "C": + char = "ç" if out[-1] in VOICELESS else "c" + else: + char = token + if char in VOWELS: + if out == word and word in SOFTENING: + out = SOFTENING[word] + elif soft_k and out.endswith("k"): + out = out[:-1] + "ğ" + out += char + soft_k = char == "k" and len(out) >= 3 and out[-3] == "l" and out[-2] in "ıiuü" + return out + + +def surface_forms() -> dict: + """Every way each suffix is written, after any vowel and any final consonant: surface -> archiphoneme form.""" + stems = [f"k{v}{end}" for v in "aeıioöuü" for end in ("", "n", "t")] + forms = {} + for suffix in SUFFIXES: + for stem in stems: + surface = inflect_word(stem, suffix)[len(stem) :] + forms.setdefault(surface, suffix) + upper = {s.replace("i", "İ").replace("ı", "I").upper(): a for s, a in forms.items()} + return {**forms, **upper} + + +def _target_words() -> list: + """The closed set of words a written suffix can land on.""" + words = {"sıfır", "yüz", "bin", "milyon", "milyar", "trilyon", "katrilyon", "buçuk"} + for name in ("digit", "tens"): + words |= {row[1] for row in load_labels(get_abs_path(f"data/number/{name}.tsv"))} + words |= {row[1] for row in load_labels(get_abs_path("data/dates/months.tsv"))} + for _, major, minor in load_labels(get_abs_path("data/money/currency.tsv")): + words |= {major, minor} + words |= {row[1].split()[-1] for row in load_labels(get_abs_path("data/measures/units.tsv"))} + return sorted(words) + + +@lru_cache(maxsize=None) +def get_suffix_rewrite() -> 'pynini.FstLike': + """ + Maps "|" to the spoken words with the suffix rebuilt for the last word; a suffix + not in the table is copied as written at cost 1. + """ + forms = surface_forms() + pairs = [ + (f"{word}{MARK}{surface}", inflect_word(word, suffix)) + for word in _target_words() + for surface, suffix in forms.items() + ] + table = pynini.string_map(pairs) + no_mark = pynini.closure(pynini.difference(NEMO_CHAR, MARK)) + known = table | no_mark + NEMO_SPACE + table + letters = pynini.union(*"abcçdefgğhıijklmnoöprsştuüvyzâîûqwxABCÇDEFGĞHIİJKLMNOÖPRSŞTUÜVYZÂÎÛQWX") + copied = no_mark + pynutil.delete(MARK) + pynini.closure(letters, 1) + copied @= pynini.cdrewrite(pynini.cross("dört", "dörd"), "", pynini.union(*VOWELS), pynini.closure(NEMO_CHAR)) + return (known | pynutil.add_weight(copied, 1.0)).optimize() diff --git a/nemo_text_processing/text_normalization/tr/taggers/date.py b/nemo_text_processing/text_normalization/tr/taggers/date.py index 295ef8097..b0ec53dcb 100644 --- a/nemo_text_processing/text_normalization/tr/taggers/date.py +++ b/nemo_text_processing/text_normalization/tr/taggers/date.py @@ -15,9 +15,10 @@ import pynini from pynini.lib import pynutil, rewrite -from nemo_text_processing.text_normalization.en.graph_utils import NEMO_DIGIT, NEMO_SPACE, GraphFst +from nemo_text_processing.text_normalization.en.graph_utils import NEMO_CHAR, NEMO_DIGIT, NEMO_SPACE, GraphFst +from nemo_text_processing.text_normalization.en.utils import load_labels from nemo_text_processing.text_normalization.tr.graph_utils import APOSTROPHE, SUFFIX, attach_suffix -from nemo_text_processing.text_normalization.tr.utils import get_abs_path, load_labels +from nemo_text_processing.text_normalization.tr.utils import get_abs_path class DateFst(GraphFst): @@ -60,6 +61,9 @@ def __init__(self, cardinal: GraphFst, deterministic: bool = True): year_digits = pynini.union("1", "2") + NEMO_DIGIT**3 plain_year = (year_digits @ cardinal.graph).optimize() year = plain_year | attach_suffix(plain_year) + # "14.03.88": a two-digit year is read as written + short_year = (NEMO_DIGIT**2 @ cardinal.two_digits).optimize() + short_year |= attach_suffix(short_year) def field(name, graph, first=False): return pynutil.insert(("" if first else " ") + f'{name}: "') + graph + pynutil.insert('"') @@ -68,28 +72,35 @@ def field(name, graph, first=False): numeric = [] for sep in [".", "/", "-"]: + years = year | short_year if sep != "-" else year numeric.append( field("day", day, first=True) + pynutil.delete(sep) + field("month", month) + pynutil.delete(sep) - + field("year", year) + + field("year", years) ) numeric = pynini.union(*numeric) - # ISO: the day and month come last in writing but first in speech - iso = [] + # ISO: the day and month come last in writing but first in speech, so they are enumerated; a suffix written + # after the day goes on the year, the last word read ("2026-03-15'te" -> "... iki bin yirmi altıda") + iso_year = plain_year + pynutil.delete("-" + NEMO_DIGIT**2 + "-" + NEMO_DIGIT**2) + iso_year = (iso_year | attach_suffix(iso_year)).optimize() + # Each branch inserts its day and month and copies the input; one composition then reads the year. + branches = [] for month_number, month_name in month_numbers: for day_value in day_values: spoken_day = rewrite.top_rewrite(day_value, cardinal.graph) - iso.append( - pynutil.insert(f'day: "{spoken_day}" month: "{month_name}"') - + field("year", plain_year) - + pynutil.delete(f"-{int(month_number):02d}-{int(day_value):02d}") + branches.append( + pynutil.insert(f'day: "{spoken_day}" month: "{month_name}" year: "') + + year_digits + + f"-{int(month_number):02d}-{int(day_value):02d}" + + pynini.closure(APOSTROPHE + SUFFIX, 0, 1) ) - iso = pynini.union(*iso) + read_year = pynini.closure(pynini.difference(NEMO_CHAR, NEMO_DIGIT)) + iso_year + pynutil.insert('"') + iso = pynini.compose(pynini.union(*branches).optimize(), read_year) - month_name = month_names | month_names + pynutil.delete(APOSTROPHE) + SUFFIX + month_name = month_names | attach_suffix(month_names) textual = ( field("day", day, first=True) + pynutil.delete(NEMO_SPACE) @@ -97,5 +108,15 @@ def field(name, graph, first=False): + pynini.closure(pynutil.delete(NEMO_SPACE) + field("year", year), 0, 1) ) - self.graph = (numeric | iso | textual) + preserve + # month and year only, as on a card: "08/2028" -> "ağustos iki bin yirmi sekiz"; the month is written with two + # digits and the year is 19xx or 20xx, so that fractions such as "1/1000" are not taken for dates + two_digit_month = pynini.compose(NEMO_DIGIT**2, month) + modern_year = pynini.compose(pynini.union("19", "20") + NEMO_DIGIT**2, plain_year) + month_year = ( + field("month", two_digit_month, first=True) + + pynutil.delete("/") + + field("year", modern_year | attach_suffix(modern_year)) + ) + + self.graph = (numeric | iso | textual | month_year) + preserve self.fst = self.add_tokens(self.graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/taggers/decimal.py b/nemo_text_processing/text_normalization/tr/taggers/decimal.py index 76a5ba8f7..c4199e5dc 100644 --- a/nemo_text_processing/text_normalization/tr/taggers/decimal.py +++ b/nemo_text_processing/text_normalization/tr/taggers/decimal.py @@ -72,7 +72,14 @@ def fractional_part(digits: "pynini.FstLike") -> "pynini.FstLike": comma = integer_part + pynutil.delete(",") + fractional_part(pynini.closure(NEMO_DIGIT, 1)) dot = plain_integer_part + pynutil.delete(".") + fractional_part(dot_fraction_digits) - self.final_graph_wo_negative = (comma | pynutil.add_weight(dot, 0.01)).optimize() + # ",5" after a non-zero integer is "buçuk": "2,5" -> "iki buçuk", "%2,5'luk" -> "yüzde iki buçukluk" + nonzero = (pynini.closure(NEMO_DIGIT | ".", 1) - "0") @ cardinal.graph + half = (nonzero + pynutil.delete(pynini.union(",", ".") + "5") + pynutil.insert(" buçuk")).optimize() + half = pynutil.insert('integer_part: "') + (half | attach_suffix(half)) + pynutil.insert('"') + + self.final_graph_wo_negative = ( + half | pynutil.add_weight(comma, 0.01) | pynutil.add_weight(dot, 0.02) + ).optimize() optional_minus = pynini.closure(pynutil.insert("negative: ") + pynini.cross("-", '"true" '), 0, 1) self.final_graph = optional_minus + self.final_graph_wo_negative diff --git a/nemo_text_processing/text_normalization/tr/taggers/fraction.py b/nemo_text_processing/text_normalization/tr/taggers/fraction.py index 744e0c85e..b977d3d86 100644 --- a/nemo_text_processing/text_normalization/tr/taggers/fraction.py +++ b/nemo_text_processing/text_normalization/tr/taggers/fraction.py @@ -16,8 +16,9 @@ from pynini.lib import pynutil, rewrite from nemo_text_processing.text_normalization.en.graph_utils import NEMO_DIGIT, NEMO_SIGMA, NEMO_SPACE, GraphFst +from nemo_text_processing.text_normalization.en.utils import load_labels from nemo_text_processing.text_normalization.tr.graph_utils import attach_suffix -from nemo_text_processing.text_normalization.tr.utils import get_abs_path, load_labels +from nemo_text_processing.text_normalization.tr.utils import get_abs_path # Denominators read the Turkish way, denominator first in the locative: "3/4" -> "dörtte üç" NAMED_DENOMINATORS = list(range(2, 101)) + [1000] diff --git a/nemo_text_processing/text_normalization/tr/taggers/measure.py b/nemo_text_processing/text_normalization/tr/taggers/measure.py index 02e21f499..3d8b4492e 100644 --- a/nemo_text_processing/text_normalization/tr/taggers/measure.py +++ b/nemo_text_processing/text_normalization/tr/taggers/measure.py @@ -16,21 +16,22 @@ from pynini.lib import pynutil from nemo_text_processing.text_normalization.en.graph_utils import NEMO_SPACE, GraphFst -from nemo_text_processing.text_normalization.tr.graph_utils import APOSTROPHE, SUFFIX, attach_suffix +from nemo_text_processing.text_normalization.tr.graph_utils import attach_suffix from nemo_text_processing.text_normalization.tr.utils import get_abs_path class MeasureFst(GraphFst): """ - Finite state transducer for classifying measures, e.g. + Finite state transducer for classifying measures and percentages, e.g. "5 km" -> measure { cardinal { integer: "beş" } units: "kilometre" } - "2,5 kg" -> measure { decimal { integer_part: "iki" fractional_part: "beş" } units: "kilogram" } - "5 km'ye" -> measure { cardinal { integer: "beş" } units: "kilometreye" } + "5 kg'ye" -> measure { cardinal { integer: "beş" } units: "kilograma" } "%18" -> measure { units: "yüzde" cardinal { integer: "on sekiz" } preserve_order: true } + "%2,5" -> measure { units: "yüzde" decimal { integer_part: "iki buçuk" } preserve_order: true } "%14'ü" -> measure { units: "yüzde" cardinal { integer: "on dördü" } preserve_order: true } + "15%" -> measure { units: "yüzde" cardinal { integer: "on beş" } preserve_order: true } Turkish writes the percent sign before the number and reads it first ("yüzde on sekiz"); the English order - "15%" is read the same way. A suffix after a unit abbreviation follows the full word ("km'ye" -> "kilometreye"). + "15%" is read the same way. Args: cardinal: CardinalFst @@ -42,12 +43,10 @@ class MeasureFst(GraphFst): def __init__(self, cardinal: GraphFst, decimal: GraphFst, deterministic: bool = True): super().__init__(name="measure", kind="classify", deterministic=deterministic) - units = pynini.string_file(get_abs_path("data/measures/units.tsv")) - units |= units + pynutil.delete(APOSTROPHE) + SUFFIX optional_space = pynini.closure(pynutil.delete(NEMO_SPACE), 0, 1) def wrap_cardinal(graph): - return pynutil.insert('cardinal { integer: "') + graph + pynutil.insert('" }') + return pynutil.insert("cardinal { integer: \"") + graph + pynutil.insert("\" }") def wrap_decimal(graph): return pynutil.insert("decimal { ") + graph + pynutil.insert(" }") @@ -57,12 +56,41 @@ def wrap_decimal(graph): decimal.final_graph_wo_negative ) - unit_graph = number + optional_space + pynutil.insert(' units: "') + units + pynutil.insert('"') - - percent = pynutil.insert('units: "yüzde" ') + percent = pynutil.insert("units: \"yüzde\" ") preserve = pynutil.insert(" preserve_order: true") percent_first = pynutil.delete("%") + optional_space + percent + number_with_suffix + preserve percent_last = percent + number + optional_space + pynutil.delete("%") + preserve + # "5 km", "2,5 kg", "5 km'ye" -> "beş kilometreye" (the suffix is rebuilt for the full word); "-3 °C" + units = pynini.string_file(get_abs_path("data/measures/units.tsv")) + units |= attach_suffix(units) + minus = pynini.closure(pynutil.insert("negative: ") + pynini.cross("-", "\"true\" "), 0, 1) + signed = ( + pynutil.insert("cardinal { ") + + minus + + pynutil.insert("integer: \"") + + cardinal.graph + + pynutil.insert("\" }") + ) | wrap_decimal(decimal.final_graph) + + def with_units(number_graph, unit_graph): + return number_graph + optional_space + pynutil.insert(" units: \"") + unit_graph + pynutil.insert("\"") + + unit_graph = with_units(signed, units) + + # dimensions: "30x20x10 cm" -> "otuz çarpı yirmi çarpı on santimetre" + times = pynini.closure(pynutil.delete(NEMO_SPACE), 0, 1) + pynini.cross(pynini.union("x", "×"), " çarpı ") + times += pynini.closure(pynutil.delete(NEMO_SPACE), 0, 1) + dimensions = cardinal.graph + pynini.closure(times + cardinal.graph, 1, 2) + unit_graph |= with_units(wrap_cardinal(dimensions), units) + + # speeds read "per hour first": "120 km/sa" -> "saatte yüz yirmi kilometre", "10 m/s" -> "saniyede on metre" + for written, per, unit in (("km/sa", "saatte", "kilometre"), ("km/saat", "saatte", "kilometre"), + ("m/s", "saniyede", "metre")): # fmt: skip + speed_unit = pynini.cross(written, unit) + speed_unit |= attach_suffix(speed_unit) + per_number = wrap_cardinal(pynutil.insert(per + " ") + cardinal.graph) + unit_graph |= with_units(per_number, speed_unit) + self.graph = (unit_graph | percent_first | percent_last).optimize() self.fst = self.add_tokens(self.graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/taggers/money.py b/nemo_text_processing/text_normalization/tr/taggers/money.py index 459f3e998..54be80c21 100644 --- a/nemo_text_processing/text_normalization/tr/taggers/money.py +++ b/nemo_text_processing/text_normalization/tr/taggers/money.py @@ -16,12 +16,12 @@ from pynini.lib import pynutil from nemo_text_processing.text_normalization.en.graph_utils import NEMO_DIGIT, NEMO_SPACE, GraphFst -from nemo_text_processing.text_normalization.tr.graph_utils import APOSTROPHE -from nemo_text_processing.text_normalization.tr.utils import get_abs_path, load_labels +from nemo_text_processing.text_normalization.en.utils import load_labels +from nemo_text_processing.text_normalization.tr.graph_utils import attach_suffix +from nemo_text_processing.text_normalization.tr.utils import get_abs_path # Symbols that may also stand before the amount: "$100", "₺1.250,50" PREFIX_SYMBOLS = {"$", "€", "£", "₺"} -LIRA_CODES = {"TL", "₺", "TRY"} class MoneyFst(GraphFst): @@ -31,15 +31,17 @@ class MoneyFst(GraphFst): currency_min: "kuruş" preserve_order: true } "2450.75 TL" -> money { integer_part: "iki bin dört yüz elli" currency_maj: "lira" fractional_part: "yetmiş beş" currency_min: "kuruş" preserve_order: true } - "$100" -> money { integer_part: "yüz" currency_maj: "dolar" preserve_order: true } "0,50 TL" -> money { fractional_part: "elli" currency_min: "kuruş" preserve_order: true } - "100 TL'ye" -> money { integer_part: "yüz" currency_maj: "liraya" preserve_order: true } + "1.250,50 TL'ye" -> money { ... fractional_part: "elli" currency_min: "kuruşa" preserve_order: true } + "100 TL'dir" -> money { integer_part: "yüz" currency_maj: "liradır" preserve_order: true } + "$1,250.00" -> money { integer_part: "bin iki yüz elli" currency_maj: "dolar" preserve_order: true } - The minor unit is read as a number of hundredths: "1,5 TL" is "bir lira elli kuruş". A dot followed by one or two - digits is a decimal point ("2450.75 TL"); followed by three it groups thousands ("1.250 TL"). + The minor unit is read as hundredths: "1,5 TL" is "bir lira elli kuruş". A dot followed by one or two digits is a + decimal point ("2450.75 TL"); followed by three it groups thousands ("1.250 TL"). A comma followed by three digits + groups thousands the English way ("10,000 TL"), since an amount has at most two minor digits. - A suffix written after "TL" follows how the letters are read ("TL'ye"), so it is re-harmonised for "lira" - ("liraya"). + A suffix after the currency goes on the last word read (the minor unit if there is one) and is rebuilt for it, + since the writer chose it for the letters ("TL'ye" -> "liraya"). Args: cardinal: CardinalFst @@ -50,51 +52,73 @@ class MoneyFst(GraphFst): def __init__(self, cardinal: GraphFst, deterministic: bool = True): super().__init__(name="money", kind="classify", deterministic=deterministic) - lira_suffix = pynini.string_file(get_abs_path("data/money/lira_suffix.tsv")) - integer = pynutil.insert('integer_part: "') + cardinal.graph + pynutil.insert('"') - # with a minor part, "0,50 TL" is only "elli kuruş": no zero major path, so there is no tie for Sparrowhawk - # to break differently from pynini - nonzero_integer = ( - pynutil.insert('integer_part: "') - + ((pynini.closure(NEMO_DIGIT | ".", 1) - "0") @ cardinal.graph) - + pynutil.insert('"') - ) + def field(name, graph, first=False): + return pynutil.insert(("" if first else " ") + f"{name}: \"") + graph + pynutil.insert("\"") + + def with_optional_suffix(graph): + return graph | attach_suffix(graph) + + up_to_three = pynini.closure(NEMO_DIGIT, 1, 3) - pynini.union("0", "00", "000") + english_thousands = up_to_three + pynini.closure(pynutil.delete(",") + NEMO_DIGIT**3, 1) + nonzero = pynini.closure(NEMO_DIGIT | pynini.union(".", ","), 1) - "0" # written amounts other than "0" # minor unit as hundredths: "5" -> "elli", "05" -> "beş", "50" -> "elli"; "0" / "00" is not read minor_digits = ( pynini.union((NEMO_DIGIT - "0") + pynutil.insert("0"), NEMO_DIGIT**2 - "00") @ cardinal.two_digits ).optimize() - no_minor = pynutil.delete(pynini.union(",", ".") + pynini.union("0", "00")) - separator = pynutil.delete(pynini.union(",", ".")) + zero_minor = pynini.union("0", "00") + + # (integer reading, separator before the minor unit) + amounts = [ + (cardinal.graph, pynini.union(",", ".")), + (english_thousands @ cardinal.graph, pynini.accep(".")), + ] optional_space = pynini.closure(pynutil.delete(NEMO_SPACE), 0, 1) graphs = [] - for code, major, minor in load_labels(get_abs_path("data/money/currency.tsv")): - maj = pynutil.insert(f' currency_maj: "{major}"') - fractional = pynutil.insert(' fractional_part: "') + separator + minor_digits + pynutil.insert('"') - mino = pynutil.insert(f' currency_min: "{minor}"') - amount = pynini.union( - integer + pynini.closure(no_minor, 0, 1) + maj, - nonzero_integer + maj + fractional + mino, - pynutil.delete("0") + fractional + mino, - ) - amount += pynutil.insert(" preserve_order: true") + currencies = load_labels(get_abs_path("data/money/currency.tsv")) + currencies += [[code.lower(), major, minor] for code, major, minor in currencies if code.lower() != code] + for code, major, minor in currencies: delete_code = pynutil.delete(code) - graphs.append(amount + optional_space + delete_code) - if code in PREFIX_SYMBOLS: - graphs.append(delete_code + optional_space + amount) - if code in LIRA_CODES: - inflected = ( - integer - + pynini.closure(no_minor, 0, 1) - + pynutil.insert(f' currency_maj: "{major}') - + optional_space - + delete_code - + pynutil.delete(APOSTROPHE) - + lira_suffix - + pynutil.insert('" preserve_order: true') + for integer, sep in amounts: + integer_part = field("integer_part", integer, first=True) + nonzero_part = field("integer_part", nonzero @ integer, first=True) + fractional = field("fractional_part", pynutil.delete(sep) + minor_digits) + fractional_first = field("fractional_part", pynutil.delete(sep) + minor_digits, first=True) + no_minor = pynini.closure(pynutil.delete(sep + zero_minor), 0, 1) + + after = optional_space + delete_code # "100 TL" + major_only = ( + integer_part + + no_minor + + field("currency_maj", with_optional_suffix(after + pynutil.insert(major))) ) - graphs.append(inflected) + with_minor = ( + nonzero_part + + field("currency_maj", pynutil.insert(major)) + + fractional + + field("currency_min", with_optional_suffix(after + pynutil.insert(minor))) + ) + minor_only = ( + pynutil.delete("0") + + fractional_first + + field("currency_min", with_optional_suffix(after + pynutil.insert(minor))) + ) + graphs += [major_only, with_minor, minor_only] + + if code in PREFIX_SYMBOLS: # "$100", "₺1.250,50"; a suffix follows the digits: "$100'e" + before = delete_code + optional_space + graphs += [ + before + + integer_part + + no_minor + + field("currency_maj", with_optional_suffix(pynutil.insert(major))), + before + + nonzero_part + + field("currency_maj", pynutil.insert(major)) + + fractional + + field("currency_min", with_optional_suffix(pynutil.insert(minor))), + ] - self.graph = pynini.union(*graphs).optimize() + self.graph = (pynini.union(*graphs) + pynutil.insert(" preserve_order: true")).optimize() self.fst = self.add_tokens(self.graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/taggers/ordinal.py b/nemo_text_processing/text_normalization/tr/taggers/ordinal.py index 385ac8f15..b31281935 100644 --- a/nemo_text_processing/text_normalization/tr/taggers/ordinal.py +++ b/nemo_text_processing/text_normalization/tr/taggers/ordinal.py @@ -23,6 +23,16 @@ WRITTEN_ENDINGS = pynini.union("inci", "ıncı", "uncu", "üncü", "nci", "ncı", "ncu", "ncü") +def to_roman(number: int) -> str: + """1 -> "I", 14 -> "XIV", 100 -> "C".""" + out = "" + for value, letters in ((100, "C"), (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV")): + while number >= value: + out += letters + number -= value + return out + "I" * number + + class OrdinalFst(GraphFst): """ Finite state transducer for classifying ordinals, e.g. @@ -55,3 +65,10 @@ def __init__(self, cardinal: GraphFst, deterministic: bool = True): self.fst = self.add_tokens(pynutil.insert('integer: "') + written + pynutil.insert('"')).optimize() self.fst_dot = self.add_tokens(pynutil.insert('integer: "') + dotted + pynutil.insert('"')).optimize() + + # Roman numerals with a dot are ordinals: "XX. yüzyıl", "II. Mehmet", "XVI. Louis". Single letters other + # than I, V and X are left alone, so that initials ("Lyndon B. Johnson", "C. Fernandez") stay names. + romans = [(to_roman(n), str(n)) for n in range(1, 101)] + romans = [(r, n) for r, n in romans if len(r) > 1 or r in ("I", "V", "X")] + roman = (pynini.string_map(romans) @ self.graph) + pynutil.delete(".") + self.fst_roman_dot = self.add_tokens(pynutil.insert('integer: "') + roman + pynutil.insert('"')).optimize() diff --git a/nemo_text_processing/text_normalization/tr/taggers/telephone.py b/nemo_text_processing/text_normalization/tr/taggers/telephone.py index ac4fe684e..c4f2bfed5 100644 --- a/nemo_text_processing/text_normalization/tr/taggers/telephone.py +++ b/nemo_text_processing/text_normalization/tr/taggers/telephone.py @@ -16,6 +16,7 @@ from pynini.lib import pynutil from nemo_text_processing.text_normalization.en.graph_utils import NEMO_DIGIT, GraphFst +from nemo_text_processing.text_normalization.tr.graph_utils import attach_suffix class TelephoneFst(GraphFst): @@ -80,6 +81,8 @@ def group(n): # call centre numbers: "444 0 123" call_centre = group(3) + delete_sep + comma + group(1) + delete_sep + comma + group(3) - number_part = pynutil.insert('number_part: "') + (national | call_centre) + pynutil.insert('"') + # a suffix goes on the last group: "0532 123 45 67'den" -> "... altmış yediden" + numbers = national | call_centre + number_part = pynutil.insert('number_part: "') + (numbers | attach_suffix(numbers)) + pynutil.insert('"') self.graph = (number_part | international).optimize() self.fst = self.add_tokens(self.graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/taggers/time.py b/nemo_text_processing/text_normalization/tr/taggers/time.py index 49269abe4..6c797c646 100644 --- a/nemo_text_processing/text_normalization/tr/taggers/time.py +++ b/nemo_text_processing/text_normalization/tr/taggers/time.py @@ -42,11 +42,12 @@ class TimeFst(GraphFst): def __init__(self, cardinal: GraphFst, deterministic: bool = True): super().__init__(name="time", kind="classify", deterministic=deterministic) - hour_values = pynini.union(*[str(h) for h in range(0, 24)]) + hour_values = pynini.union(*[str(h) for h in range(0, 25)]) hours_padded = pynini.union(*[f"0{h}" for h in range(0, 10)]) to_words = pynini.closure(pynutil.delete("0"), 0, 1) + cardinal.graph hours = ((hour_values | hours_padded) @ to_words).optimize() hours_leading_zero = (hours_padded @ to_words).optimize() + zero_hour = pynini.union("0", "00") # "01".."59": "05" -> "sıfır beş", "30" -> "otuz"; "00" is handled by the callers minutes = pynini.union( @@ -59,24 +60,37 @@ def field(name, graph, first=False): def build(hour_graph, sep, with_suffix): suffix = attach_suffix if with_suffix else (lambda g: g) + no_seconds = pynini.closure(pynutil.delete(sep + "00"), 0, 1) if sep == ":" else pynini.accep("") with_minutes = ( - field("hours", hour_graph, first=True) + pynutil.delete(sep) + field("minutes", suffix(minutes)) - ) - full_hour = field("hours", suffix(hour_graph + pynutil.delete(sep + "00")), first=True) - with_seconds = ( field("hours", hour_graph, first=True) + pynutil.delete(sep) - + field("minutes", minutes | pynini.cross("00", "sıfır")) - + pynutil.delete(sep) - + field("seconds", suffix(minutes | pynini.cross("00", "sıfır"))) + + field("minutes", suffix(minutes + no_seconds)) ) + # "10:00" -> "on", "24:00'te" -> "yirmi dörtte"; midnight is "sıfır sıfır" + full = pynini.difference(pynini.project(hour_graph, "input"), zero_hour) @ hour_graph + midnight = pynini.cross(zero_hour, "sıfır sıfır") + full_hour = field("hours", suffix((full | midnight) + pynutil.delete(sep + "00") + no_seconds), first=True) graphs = [with_minutes, full_hour] if sep == ":": + with_seconds = ( + field("hours", hour_graph, first=True) + + pynutil.delete(sep) + + field("minutes", minutes | pynini.cross("00", "sıfır")) + + pynutil.delete(sep) + + field("seconds", suffix(minutes)) + ) graphs.append(with_seconds) return pynini.union(*graphs) colon = build(hours, ":", False) | build(hours, ":", True) dot = build(hours, ".", True) | build(hours_leading_zero, ".", False) + # a full hour with a dot ("akşam 19.00") is a time; a decimal is not written with ".00" + dot |= pynini.compose(pynini.closure(NEMO_DIGIT, 1, 2) + ".00", build(hours, ".", False)) + + # without a suffix or a leading zero, "17.30" is a time only in context ("saat 17.30", "09.00-17.30"); + # tokenize_and_classify uses these + self.colon = build(hours, ":", False).optimize() + self.dot_in_context = build(hours, ".", False).optimize() self.graph = (colon | dot).optimize() self.fst = self.add_tokens(self.graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/taggers/tokenize_and_classify.py b/nemo_text_processing/text_normalization/tr/taggers/tokenize_and_classify.py index c27616f54..1bb8378f7 100644 --- a/nemo_text_processing/text_normalization/tr/taggers/tokenize_and_classify.py +++ b/nemo_text_processing/text_normalization/tr/taggers/tokenize_and_classify.py @@ -18,6 +18,7 @@ from pynini.lib import pynutil from nemo_text_processing.text_normalization.en.graph_utils import ( + NEMO_DIGIT, NEMO_NOT_SPACE, NEMO_WHITE_SPACE, GraphFst, @@ -26,7 +27,8 @@ generator_main, ) from nemo_text_processing.text_normalization.en.taggers.punctuation import PunctuationFst -from nemo_text_processing.text_normalization.tr.graph_utils import TR_LOWER +from nemo_text_processing.text_normalization.tr.graph_utils import APOSTROPHE, TR_ALPHA, TR_LOWER, attach_suffix +from nemo_text_processing.text_normalization.tr.inflection import surface_forms from nemo_text_processing.text_normalization.tr.taggers.cardinal import CardinalFst from nemo_text_processing.text_normalization.tr.taggers.date import DateFst from nemo_text_processing.text_normalization.tr.taggers.decimal import DecimalFst @@ -38,8 +40,28 @@ from nemo_text_processing.text_normalization.tr.taggers.time import TimeFst from nemo_text_processing.text_normalization.tr.taggers.whitelist import WhiteListFst from nemo_text_processing.text_normalization.tr.taggers.word import WordFst +from nemo_text_processing.text_normalization.tr.utils import get_abs_path from nemo_text_processing.utils.logging import logger +# Words after which a number is a code, read digit by digit: "Doğrulama kodunuz 482913" +CODE_WORDS = [ + "kod", + "kodu", + "kodunuz", + "kodum", + "şifre", + "şifreniz", + "şifrem", + "parola", + "parolanız", + "PIN", + "pin", + "OTP", +] +# Words that join list items: "1., 2. ve 3. taksit" +CONNECTORS = ["ve", "veya", "ile", "ya", "da"] +TIME_WORDS = ["saat", "Saat", "SAAT"] + class ClassifyFst(GraphFst): """ @@ -47,6 +69,12 @@ class ClassifyFst(GraphFst): For deployment, this grammar will be compiled and exported to OpenFst Finite State Archive (FAR) File. More details to deployment at NeMo/tools/text_processing_deployment. + Besides the single-token classes, a few patterns look at the neighbouring token: + "5. sırada", "1., 2. ve 3. taksit" -> ordinals (a number with a dot before a noun) + "saat 17.30" -> time (otherwise "17.30" is a decimal) + "09.00-17.30", "2025-2026", "%10-20" -> ranges read with "ile" + "kodunuz 482913" -> the code read digit by digit + Args: input_case: accepting either "lower_cased" or "cased" input. deterministic: if True will provide a single transduction option, @@ -80,45 +108,30 @@ def __init__( logger.info("Creating ClassifyFst grammars. This might take some time...") self.cardinal = CardinalFst(deterministic=deterministic) - cardinal_graph = self.cardinal.fst self.ordinal = OrdinalFst(cardinal=self.cardinal, deterministic=deterministic) - ordinal_graph = self.ordinal.fst self.decimal = DecimalFst(cardinal=self.cardinal, deterministic=deterministic) - decimal_graph = self.decimal.fst - self.fraction = FractionFst(cardinal=self.cardinal, deterministic=deterministic) - fraction_graph = self.fraction.fst - self.measure = MeasureFst( - cardinal=self.cardinal, - decimal=self.decimal, - deterministic=deterministic, - ) - measure_graph = self.measure.fst + self.measure = MeasureFst(cardinal=self.cardinal, decimal=self.decimal, deterministic=deterministic) self.date = DateFst(cardinal=self.cardinal, deterministic=deterministic) - date_graph = self.date.fst self.time = TimeFst(cardinal=self.cardinal, deterministic=deterministic) - time_graph = self.time.fst self.money = MoneyFst(cardinal=self.cardinal, deterministic=deterministic) - money_graph = self.money.fst self.telephone = TelephoneFst(cardinal=self.cardinal, deterministic=deterministic) - telephone_graph = self.telephone.fst + self.fraction = FractionFst(cardinal=self.cardinal, deterministic=deterministic) self.whitelist = WhiteListFst(input_case=input_case, deterministic=deterministic, input_file=whitelist) - whitelist_graph = self.whitelist.fst self.word = WordFst(deterministic=deterministic) - word_graph = self.word.fst punct_graph = PunctuationFst(deterministic=deterministic).fst classify = ( - pynutil.add_weight(whitelist_graph, 1.01) - | pynutil.add_weight(time_graph, 1.09) - | pynutil.add_weight(date_graph, 1.09) - | pynutil.add_weight(money_graph, 1.09) - | pynutil.add_weight(measure_graph, 1.09) - | pynutil.add_weight(telephone_graph, 1.09) - | pynutil.add_weight(fraction_graph, 1.1) - | pynutil.add_weight(decimal_graph, 1.1) - | pynutil.add_weight(ordinal_graph, 1.1) - | pynutil.add_weight(cardinal_graph, 1.1) - | pynutil.add_weight(word_graph, 200) + pynutil.add_weight(self.whitelist.fst, 1.01) + | pynutil.add_weight(self.time.fst, 1.09) + | pynutil.add_weight(self.date.fst, 1.09) + | pynutil.add_weight(self.money.fst, 1.09) + | pynutil.add_weight(self.measure.fst, 1.09) + | pynutil.add_weight(self.telephone.fst, 1.09) + | pynutil.add_weight(self.fraction.fst, 1.1) + | pynutil.add_weight(self.decimal.fst, 1.1) + | pynutil.add_weight(self.ordinal.fst, 1.1) + | pynutil.add_weight(self.cardinal.fst, 1.1) + | pynutil.add_weight(self.word.fst, 200) ) punct = pynutil.insert("tokens { ") + pynutil.add_weight(punct_graph, weight=2.1) + pynutil.insert(" }") punct = pynini.closure( @@ -127,20 +140,7 @@ def __init__( 1, ) token = pynutil.insert("tokens { ") + classify + pynutil.insert(" }") - - # "5. sırada" -> "beşinci sırada": a number with a dot is an ordinal only before a lower-case word; - # at the end of a sentence ("Sırada 5.") it stays a number and a full stop. - lower_word = pynini.compose(TR_LOWER + pynini.closure(NEMO_NOT_SPACE), self.word.fst) - ordinal_dot = ( - pynutil.insert("tokens { ") - + pynutil.add_weight(self.ordinal.fst_dot, 1.1) - + pynutil.insert(" }") - + pynutil.delete(pynini.closure(NEMO_WHITE_SPACE, 1)) - + pynutil.insert(" tokens { ") - + pynutil.add_weight(lower_word, 200) - + pynutil.insert(" }") - ) - token |= ordinal_dot + token |= self._context_patterns(input_case) token_plus_punct = ( pynini.closure(punct + pynutil.insert(" ")) + token + pynini.closure(pynutil.insert(" ") + punct) @@ -162,3 +162,136 @@ def __init__( if far_file: generator_main(far_file, {"tokenize_and_classify": self.fst}) logger.info(f"ClassifyFst grammars are saved to {far_file}.") + + def _context_patterns(self, input_case: str) -> 'pynini.FstLike': + """Patterns of two or more tokens; each emits the tokens it covers.""" + + def tok(graph, weight): + return pynutil.insert("tokens { ") + pynutil.add_weight(graph, weight) + pynutil.insert(" }") + + def words(word_list): + return tok(pynini.compose(pynini.union(*word_list), self.word.fst), 200) + + space = pynutil.delete(pynini.closure(NEMO_WHITE_SPACE, 1)) + pynutil.insert(" ") + dash = ( + pynini.closure(pynutil.delete(" "), 0, 1) + + pynutil.delete(pynini.union("-", "–")) + + pynini.closure(pynutil.delete(" "), 0, 1) + ) + ile = pynutil.insert(" tokens { name: \"ile\" } ") + + # ordinals: a number with a dot before a noun; in lower-cased text, where a sentence end cannot be told + # from a following word, only before known nouns ("taksit", "sıra", "kat" ...) + nouns = [line.strip() for line in open(get_abs_path("data/ordinals/ordinal_nouns.tsv"), encoding="utf-8")] + noun_forms = pynini.union(*nouns, *[n[0].upper() + n[1:] for n in nouns]) + noun_forms += pynini.closure(pynini.union(*surface_forms().keys()), 0, 1) + noun = pynini.compose(noun_forms + pynini.closure(pynini.union(",", ".", "?", "!"), 0, 1), self.word.fst) + following = noun + if input_case != "lower_cased": + following |= pynini.compose(TR_LOWER + pynini.closure(NEMO_NOT_SPACE), self.word.fst) + ordinal_dot = tok(self.ordinal.fst_dot, 1.1) + comma = pynini.cross(",", " tokens { name: \",\" }") + item_separator = pynini.closure(comma, 0, 1) + space + pynini.closure(words(CONNECTORS) + space, 0, 1) + ordinals = ordinal_dot + pynini.closure(item_separator + ordinal_dot) + space + tok(following, 200) + # "1.sırada": written without the space + # (cheaper than the word alone, which would otherwise swallow "1.sırada" as one token) + glued_word = pynini.compose(TR_LOWER + pynini.closure(NEMO_NOT_SPACE), self.word.fst) + ordinals |= ordinal_dot + pynutil.insert(" ") + tok(glued_word, 1.0) + # "XX. yüzyıl", "II. Mehmet" + any_word = pynini.compose(TR_ALPHA + pynini.closure(NEMO_NOT_SPACE), self.word.fst) + ordinals |= tok(self.ordinal.fst_roman_dot, 1.1) + space + tok(any_word, 200) + + # "saat 17.30" + time_in_context = self.time.add_tokens(self.time.dot_in_context | self.time.colon) + clock = words(TIME_WORDS) + space + tok(time_in_context, 1.0) + + # ranges + time_any = tok(self.time.fst, 1.09) | tok(time_in_context, 1.09) + year = self.cardinal.add_tokens( + pynutil.insert("integer: \"") + + ((pynini.union("1", "2") + NEMO_DIGIT**3) @ self.cardinal.graph) + + pynutil.insert("\"") + ) + cardinal, decimal, measure = ( + tok(self.cardinal.fst, 1.1), + tok(self.decimal.fst, 1.1), + tok(self.measure.fst, 1.09), + ) + ranges = ( + time_any + dash + ile + time_any + | tok(year, 1.1) + dash + ile + tok(year, 1.1) + | measure + dash + ile + (measure | cardinal | decimal) + | (cardinal | decimal) + dash + ile + measure + | decimal + dash + ile + (decimal | cardinal) + | cardinal + dash + ile + decimal + | cardinal + dash + ile + tok(self.date.fst, 1.09) # "23-25 Aralık" + ) + # small numbers: "3-5 iş günü" is a range (a < b), "11-9" and "6-6'ya" are scores (a >= b) + written_suffix = pynini.closure(APOSTROPHE + pynini.closure(TR_ALPHA, 1), 0, 1) + less, not_less = number_pairs() + ranges |= pynini.compose(less + written_suffix, cardinal + dash + ile + cardinal) + ranges |= pynini.compose(not_less + written_suffix, cardinal + dash + pynutil.insert(" ") + cardinal) + + # ratios: "3:2" -> "üçe iki" + to_dative = pynini.compose( + ((NEMO_DIGIT - "0") + pynini.closure(NEMO_DIGIT, 0, 1)) + pynini.cross(":", "'e"), + attach_suffix(self.cardinal.graph), + ) + ratio = to_dative + pynutil.insert(" ") + ((NEMO_DIGIT - "0") @ self.cardinal.graph) + ratios = tok(self.cardinal.add_tokens(pynutil.insert("integer: \"") + ratio + pynutil.insert("\"")), 1.1) + + # versions: "3.12.1" -> "üç nokta on iki nokta bir" (not dates, not thousand groups) + part = (NEMO_DIGIT - "0") + pynini.closure(NEMO_DIGIT) | "0" + thousands = pynini.closure(NEMO_DIGIT, 1, 3) + pynini.closure("." + NEMO_DIGIT**3, 1) + version_written = pynini.difference(part + pynini.closure("." + part, 2), thousands) + version = pynini.compose( + version_written, + (part @ self.cardinal.graph) + + pynini.closure(pynini.cross(".", " nokta ") + (part @ self.cardinal.graph), 2), + ) + versions = tok(self.cardinal.add_tokens(pynutil.insert("integer: \"") + version + pynutil.insert("\"")), 1.1) + + # codes + code_digits = (NEMO_DIGIT**4 + pynini.closure(NEMO_DIGIT, 0, 4)) @ self.cardinal.digits + code_digits |= attach_suffix(code_digits) # "kodunuz 218456'dır" -> "... beş altıdır" + code = self.cardinal.add_tokens(pynutil.insert("integer: \"") + code_digits + pynutil.insert("\"")) + code_words = CODE_WORDS + [w[0].upper() + w[1:] for w in CODE_WORDS if w[0].islower()] + codes = words(code_words) + space + tok(code, 1.0) + + return (ordinals | clock | ranges | ratios | versions | codes).optimize() + + +def number_pairs(): + """ + Acceptors over "a-b" for numbers of up to three digits: (a < b, a >= b). An fst cannot compare two numbers in + general, but up to three digits the pairs can be enumerated by length and first differing digit. + """ + digit = [str(d) for d in range(10)] + separator = pynini.closure(" ", 0, 1) + pynini.union("-", "–") + pynini.closure(" ", 0, 1) + + def digits(n): # exactly n digits; note that fst ** 0 is an unbounded closure in pynini + return NEMO_DIGIT**n if n > 0 else pynini.accep("") + + def number(n): + return (NEMO_DIGIT - "0") + digits(n - 1) + + less, more, equal = [], [], [] + for na in range(1, 4): + for nb in range(1, 4): + if na < nb: + less.append(number(na) + separator + number(nb)) + elif na > nb: + more.append(number(na) + separator + number(nb)) + for n in range(1, 4): + for k in range(n): # length of the shared prefix + prefixes = [""] if k == 0 else [str(p) for p in range(10 ** (k - 1), 10**k)] + rest = digits(n - k - 1) + for p in prefixes: + for d1 in digit: + for d2 in digit: + if k == 0 and "0" in (d1, d2) or d1 == d2: + continue + branch = p + d1 + rest + separator + p + d2 + rest + (less if d1 < d2 else more).append(branch) + equal += [str(x) + separator + str(x) for x in range(10 ** (n - 1), 10**n)] + return pynini.union(*less).optimize(), pynini.union(*more, *equal).optimize() diff --git a/nemo_text_processing/text_normalization/tr/taggers/whitelist.py b/nemo_text_processing/text_normalization/tr/taggers/whitelist.py index cb96ad311..7325d526c 100644 --- a/nemo_text_processing/text_normalization/tr/taggers/whitelist.py +++ b/nemo_text_processing/text_normalization/tr/taggers/whitelist.py @@ -16,7 +16,9 @@ from pynini.lib import pynutil from nemo_text_processing.text_normalization.en.graph_utils import NEMO_SIGMA, GraphFst -from nemo_text_processing.text_normalization.tr.utils import get_abs_path, load_labels +from nemo_text_processing.text_normalization.en.utils import load_labels +from nemo_text_processing.text_normalization.tr.graph_utils import attach_suffix +from nemo_text_processing.text_normalization.tr.utils import get_abs_path def turkish_lower(text: str) -> str: @@ -52,6 +54,14 @@ def _get_whitelist_graph(input_case, file): if input_file: graph = _get_whitelist_graph(input_case, input_file) + # a currency code on its own, after a scale word: "3,7 milyar TL'ye" -> "... milyar liraya" + codes = [ + (code, major) for code, major, _ in load_labels(get_abs_path("data/money/currency.tsv")) if code.isalpha() + ] + codes += [(code.lower(), major) for code, major in codes] + currency = pynini.string_map(codes) + graph |= currency | attach_suffix(currency) + # A multi-word expansion becomes one name token per word ("vb." -> "ve", "benzeri"). Sparrowhawk prints a name # token as it is, so a non-breaking space (convert_space) would stay in its output. split_words = pynini.cdrewrite(pynini.cross(" ", '" } tokens { name: "'), "", "", NEMO_SIGMA) diff --git a/nemo_text_processing/text_normalization/tr/utils.py b/nemo_text_processing/text_normalization/tr/utils.py index e502bbf39..1f92dd8f1 100644 --- a/nemo_text_processing/text_normalization/tr/utils.py +++ b/nemo_text_processing/text_normalization/tr/utils.py @@ -12,7 +12,6 @@ # See the License for the specific language governing permissions and # limitations under the License. -import csv import os @@ -26,17 +25,3 @@ def get_abs_path(rel_path): Returns absolute path """ return os.path.dirname(os.path.abspath(__file__)) + "/" + rel_path - - -def load_labels(abs_path): - """ - loads relative path file as dictionary - - Args: - abs_path: absolute path - - Returns dictionary of mappings - """ - with open(abs_path, encoding="utf-8") as label_tsv: - labels = list(csv.reader(label_tsv, delimiter="\t")) - return labels diff --git a/nemo_text_processing/text_normalization/tr/verbalizers/date.py b/nemo_text_processing/text_normalization/tr/verbalizers/date.py index b5b46fa09..6b952d92a 100644 --- a/nemo_text_processing/text_normalization/tr/verbalizers/date.py +++ b/nemo_text_processing/text_normalization/tr/verbalizers/date.py @@ -48,4 +48,5 @@ def field(name): space = delete_space + pynutil.insert(" ") graph = field("day") + space + field("month") + pynini.closure(space + field("year"), 0, 1) + graph |= field("month") + space + field("year") self.fst = self.delete_tokens(graph + delete_preserve_order).optimize() diff --git a/nemo_text_processing/text_normalization/tr/verbalizers/decimal.py b/nemo_text_processing/text_normalization/tr/verbalizers/decimal.py index 85875b2cc..752122325 100644 --- a/nemo_text_processing/text_normalization/tr/verbalizers/decimal.py +++ b/nemo_text_processing/text_normalization/tr/verbalizers/decimal.py @@ -46,5 +46,8 @@ def __init__(self, deterministic: bool = True): + pynini.closure(NEMO_NOT_QUOTE, 1) + pynutil.delete('"') ) - self.numbers = optional_sign + integer + delete_space + pynutil.insert(" virgül ") + fractional + # "iki buçuk" comes as an integer part alone + self.numbers = ( + optional_sign + integer + pynini.closure(delete_space + pynutil.insert(" virgül ") + fractional, 0, 1) + ) self.fst = self.delete_tokens(self.numbers).optimize() diff --git a/nemo_text_processing/text_normalization/tr/verbalizers/measure.py b/nemo_text_processing/text_normalization/tr/verbalizers/measure.py index 80cbf5d65..40481f335 100644 --- a/nemo_text_processing/text_normalization/tr/verbalizers/measure.py +++ b/nemo_text_processing/text_normalization/tr/verbalizers/measure.py @@ -26,7 +26,6 @@ class MeasureFst(GraphFst): """ Finite state transducer for verbalizing measures, e.g. - measure { cardinal { integer: "beş" } units: "kilometre" } -> beş kilometre measure { units: "yüzde" cardinal { integer: "on sekiz" } preserve_order: true } -> yüzde on sekiz Args: diff --git a/nemo_text_processing/text_normalization/tr/verbalizers/verbalize.py b/nemo_text_processing/text_normalization/tr/verbalizers/verbalize.py index e30f1ba18..dc6a2cf8c 100644 --- a/nemo_text_processing/text_normalization/tr/verbalizers/verbalize.py +++ b/nemo_text_processing/text_normalization/tr/verbalizers/verbalize.py @@ -44,12 +44,12 @@ def __init__(self, deterministic: bool = True): cardinal.fst | decimal.fst | OrdinalFst(deterministic=deterministic).fst - | FractionFst(deterministic=deterministic).fst | MeasureFst(cardinal=cardinal, decimal=decimal, deterministic=deterministic).fst | MoneyFst(deterministic=deterministic).fst | DateFst(deterministic=deterministic).fst | TimeFst(deterministic=deterministic).fst | TelephoneFst(deterministic=deterministic).fst + | FractionFst(deterministic=deterministic).fst | WhiteListFst(deterministic=deterministic).fst ) self.fst = graph diff --git a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_cardinal.txt b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_cardinal.txt index b98fc7fec..c40f1d9c2 100644 --- a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_cardinal.txt +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_cardinal.txt @@ -20,7 +20,15 @@ 4'ü~dördü 2024'te~iki bin yirmi dörtte 1990'lı~bin dokuz yüz doksanlı +1990'larda~bin dokuz yüz doksanlarda 100'den~yüzden 6'ya~altıya +2'şer~ikişer +4'er~dörder +4'de~dörtte +2024'da~iki bin yirmi dörtte +5'ı~beşi +2024'TE~iki bin yirmi dörtte +4’e~dörde 0532~sıfır beş üç iki 004512~sıfır sıfır dört beş bir iki diff --git a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_date.txt b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_date.txt index b596a4680..e05f31396 100644 --- a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_date.txt +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_date.txt @@ -2,8 +2,13 @@ 21.11.2026~yirmi bir kasım iki bin yirmi altı 05/12/2026~beş aralık iki bin yirmi altı 1.3.2026~bir mart iki bin yirmi altı +14.03.88~on dört mart seksen sekiz 01.01.2027'de~bir ocak iki bin yirmi yedide 2026-03-15~on beş mart iki bin yirmi altı +2026-03-15'te~on beş mart iki bin yirmi altıda 14 Mart 2026~on dört mart iki bin yirmi altı 15 Kasım'da~on beş kasımda +31 Aralık'a~otuz bir aralığa +28 Kas 2026~yirmi sekiz kasım iki bin yirmi altı +08/2028~ağustos iki bin yirmi sekiz 29 ekim~yirmi dokuz ekim diff --git a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_decimal.txt b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_decimal.txt index b08b2aa8e..1b4b65fe3 100644 --- a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_decimal.txt +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_decimal.txt @@ -1,10 +1,13 @@ -3,5~üç virgül beş +3,5~üç buçuk +3.5~üç buçuk +1,5 milyon~bir buçuk milyon +3,5'e~üç buçuğa +1,5'tan~bir buçuktan 0,25~sıfır virgül yirmi beş +0,5~sıfır virgül beş 3,05~üç virgül sıfır beş 3,50~üç virgül elli +2,75~iki virgül yetmiş beş 1.250,75~bin iki yüz elli virgül yetmiş beş -0,5~eksi sıfır virgül beş -3.5~üç virgül beş -3,5'e~üç virgül beşe 3,4'ü~üç virgül dördü -1,5 milyon~bir virgül beş milyon diff --git a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_fraction.txt b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_fraction.txt index 4dbd3381c..1bc03e540 100644 --- a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_fraction.txt +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_fraction.txt @@ -7,4 +7,5 @@ ¾~dörtte üç 3/4'ü~dörtte üçü 4/5'ü~beşte dördü +1/2'si~ikide biri 7/365~yedi bölü üç yüz altmış beş diff --git a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_lower_cased.txt b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_lower_cased.txt new file mode 100644 index 000000000..fb78a62a0 --- /dev/null +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_lower_cased.txt @@ -0,0 +1,5 @@ +borcunuz 1.250,50 tl'ye ulaştı.~borcunuz bin iki yüz elli lira elli kuruşa ulaştı. +tutar 100. sonra ödeme yapın.~tutar yüz . sonra ödeme yapın. +kredinizin 3. taksiti ödendi.~kredinizin üçüncü taksiti ödendi. +faiz %2,5 oldu.~faiz yüzde iki buçuk oldu. +toplantı 14:30'da.~toplantı on dört otuzda . diff --git a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_measure.txt b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_measure.txt index 432dd0a05..68177f627 100644 --- a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_measure.txt +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_measure.txt @@ -1,13 +1,25 @@ +%18~yüzde on sekiz +% 18~yüzde on sekiz +%3,5~yüzde üç buçuk +%3.5~yüzde üç buçuk +%0,25~yüzde sıfır virgül yirmi beş +%14'ü~yüzde on dördü +%20'si~yüzde yirmisi +%2,5'luk~yüzde iki buçukluk +15%~yüzde on beş 5 km~beş kilometre 5km~beş kilometre -2,5 kg~iki virgül beş kilogram +2,5 kg~iki buçuk kilogram 120 m²~yüz yirmi metrekare 25 °C~yirmi beş santigrat derece -5 km'ye~beş kilometreye 30 dk~otuz dakika -%18~yüzde on sekiz -% 18~yüzde on sekiz -%3,5~yüzde üç virgül beş -%3.5~yüzde üç virgül beş -%14'ü~yüzde on dördü -15%~yüzde on beş +5 km'ye~beş kilometreye +5 kg'ye~beş kilograma +35 mm'dir~otuz beş milimetredir +500 gr~beş yüz gram +-3 °C~eksi üç santigrat derece +30x20x10 cm~otuz çarpı yirmi çarpı on santimetre +120 km/sa~saatte yüz yirmi kilometre +50 km/sa'tir~saatte elli kilometredir +6 GHz~altı gigahertz +15 dk.~on beş dakika diff --git a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_money.txt b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_money.txt index 586f5420e..83b4660f8 100644 --- a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_money.txt +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_money.txt @@ -8,7 +8,18 @@ 100,00 TL~yüz lira 100 TL'ye~yüz liraya 50 TL'lik~elli liralık +100 TL'dir~yüz liradır +10 TL'si~on lirası +50 TL'ydi~elli liraydı +1.250,50 TL'ye~bin iki yüz elli lira elli kuruşa +12.450,75 TL'dir~on iki bin dört yüz elli lira yetmiş beş kuruştur +0,50 TL'ye~elli kuruşa +10,000 TL~on bin lira +$1,250.00~bin iki yüz elli dolar +1,000.50 USD~bin dolar elli sent +100 tl~yüz lira $100~yüz dolar -25 €~yirmi beş avro +$100'e~yüz dolara +25 €~yirmi beş euro 10,50 USD~on dolar elli sent £5~beş sterlin diff --git a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_ordinal.txt b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_ordinal.txt index 092ad0b58..101bb46b0 100644 --- a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_ordinal.txt +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_ordinal.txt @@ -10,3 +10,4 @@ 1000'inci~bininci 3. taksit~üçüncü taksit 1. ve 2. sırada~birinci ve ikinci sırada +1., 2. ve 3. taksit~birinci , ikinci ve üçüncü taksit diff --git a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_sentences.txt b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_sentences.txt new file mode 100644 index 000000000..caac21563 --- /dev/null +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_sentences.txt @@ -0,0 +1,31 @@ +Borcunuz 1.250,50 TL'ye ulaştı.~Borcunuz bin iki yüz elli lira elli kuruşa ulaştı. +Şube saat 17.30 kapanır.~Şube saat on yedi otuz kapanır. +Şubelerimiz 09.00-17.30 arası açık.~Şubelerimiz dokuz ile on yedi otuz arası açık. +Mesai 09:00 - 18:00 arasıdır.~Mesai dokuz ile on sekiz arasıdır. +Kredinizin 3. taksiti 15 Kasım'da ödenecek.~Kredinizin üçüncü taksiti on beş kasımda ödenecek. +Sırada 5.~Sırada beş . +Faiz oranı %2,5'tan %3,5'a çıktı.~Faiz oranı yüzde iki buçuktan yüzde üç buçuğa çıktı. +Doğrulama kodunuz 482913.~Doğrulama kodunuz dört sekiz iki dokuz bir üç . +Toplantı 14:30'da başlıyor.~Toplantı on dört otuzda başlıyor. +2025-2026 döneminde kampanya var.~iki bin yirmi beş ile iki bin yirmi altı döneminde kampanya var. +Kampanya %10-20 indirim sunuyor.~Kampanya yüzde on ile yirmi indirim sunuyor. +Son ödeme 31 Aralık'a kadar.~Son ödeme otuz bir aralığa kadar. +Bakiye 0,50 TL'nin altına düştü.~Bakiye elli kuruşun altına düştü. +Dr. Ayşe 09:00'da gelecek.~doktor Ayşe dokuzda gelecek. +Kodunuz 7305 olarak gönderildi.~Kodunuz yedi üç sıfır beş olarak gönderildi. +Size gönderilen kodunuz 218456'dır.~Size gönderilen kodunuz iki bir sekiz dört beş altıdır . +Sizi akşam 19.00 gibi arayabiliriz.~Sizi akşam on dokuz gibi arayabiliriz. +Son kullanma tarihi 08/2028 olarak kayıtlı.~Son kullanma tarihi ağustos iki bin yirmi sekiz olarak kayıtlı. +Kurabiyeleri 12-15 dakika pişirin.~Kurabiyeleri on iki ile on beş dakika pişirin. +Teslimat 23-25 Aralık tarihleri arasında.~Teslimat yirmi üç ile yirmi beş aralık tarihleri arasında. +Rakibine 11-9 yenildi.~Rakibine on bir dokuz yenildi. +Set 6-6'ya geldi.~Set altı altıya geldi. +Vücut sıcaklığı 36,5-37,2 °C arasındadır.~Vücut sıcaklığı otuz altı buçuk ile otuz yedi virgül iki santigrat derece arasındadır. +Savaş 1914-1918 yılları arasında sürdü.~Savaş bin dokuz yüz on dört ile bin dokuz yüz on sekiz yılları arasında sürdü. +İstanbul II. Mehmet tarafından fethedildi.~İstanbul ikinci Mehmet tarafından fethedildi. +XX. yüzyılda büyük değişimler oldu.~yirminci yüzyılda büyük değişimler oldu. +Lyndon B. Johnson yönetiminde çalıştı.~Lyndon B. Johnson yönetiminde çalıştı. +Görüntü oranı 3:2 olarak belirlendi.~Görüntü oranı üçe iki olarak belirlendi. +Python 3.12.1 sürümü yayımlandı.~Python üç nokta on iki nokta bir sürümü yayımlandı. +Şirketin karı 3,7 milyar TL'ye ulaştı.~Şirketin karı üç virgül yedi milyar liraya ulaştı. +Tahminlere göre 1.sırada yer alan takım.~Tahminlere göre birinci sırada yer alan takım. diff --git a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_telephone.txt b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_telephone.txt index 8890bf22a..75f06bdd1 100644 --- a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_telephone.txt +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_telephone.txt @@ -4,5 +4,5 @@ (0212) 555 44 33~sıfır iki yüz on iki, beş yüz elli beş, kırk dört, otuz üç 05321234567~sıfır beş yüz otuz iki, yüz yirmi üç, kırk beş, altmış yedi +90 532 123 45 67~artı doksan, beş yüz otuz iki, yüz yirmi üç, kırk beş, altmış yedi -+905321234567~artı doksan, beş yüz otuz iki, yüz yirmi üç, kırk beş, altmış yedi 444 0 123~dört yüz kırk dört, sıfır, yüz yirmi üç +0532 123 45 67'den~sıfır beş yüz otuz iki, yüz yirmi üç, kırk beş, altmış yediden diff --git a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_time.txt b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_time.txt index bdd01a653..d63736fc9 100644 --- a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_time.txt +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_time.txt @@ -2,10 +2,16 @@ 09:05~dokuz sıfır beş 10:00~on 00:15~sıfır on beş +00:00~sıfır sıfır 23:59~yirmi üç elli dokuz +24:00~yirmi dört +14:30:00~on dört otuz +12:30:15~on iki otuz on beş 14:30'da~on dört otuzda 10:00'a~ona +09:00'dan~dokuzdan +24:00'te~yirmi dörtte 14:04'e~on dört sıfır dörde 09.30~dokuz otuz +19.00~on dokuz 14.30'da~on dört otuzda -12:30:15~on iki otuz on beş diff --git a/tests/nemo_text_processing/tr/test_cardinal.py b/tests/nemo_text_processing/tr/test_cardinal.py index b37ce7103..e8100a2bd 100644 --- a/tests/nemo_text_processing/tr/test_cardinal.py +++ b/tests/nemo_text_processing/tr/test_cardinal.py @@ -21,10 +21,10 @@ class TestCardinal: - normalizer_tr = Normalizer(input_case="cased", lang="tr", cache_dir=CACHE_DIR, overwrite_cache=False) + normalizer_tr = Normalizer(input_case='cased', lang='tr', cache_dir=CACHE_DIR, overwrite_cache=False) - @parameterized.expand(parse_test_case_file("tr/data_text_normalization/test_cases_cardinal.txt")) - @pytest.mark.run_only_on("CPU") + @parameterized.expand(parse_test_case_file('tr/data_text_normalization/test_cases_cardinal.txt')) + @pytest.mark.run_only_on('CPU') @pytest.mark.unit def test_norm(self, test_input, expected): pred = self.normalizer_tr.normalize(test_input, verbose=False) diff --git a/tests/nemo_text_processing/tr/test_date.py b/tests/nemo_text_processing/tr/test_date.py index cc21dfe3f..2bb01ffee 100644 --- a/tests/nemo_text_processing/tr/test_date.py +++ b/tests/nemo_text_processing/tr/test_date.py @@ -21,10 +21,10 @@ class TestDate: - normalizer_tr = Normalizer(input_case="cased", lang="tr", cache_dir=CACHE_DIR, overwrite_cache=False) + normalizer_tr = Normalizer(input_case='cased', lang='tr', cache_dir=CACHE_DIR, overwrite_cache=False) - @parameterized.expand(parse_test_case_file("tr/data_text_normalization/test_cases_date.txt")) - @pytest.mark.run_only_on("CPU") + @parameterized.expand(parse_test_case_file('tr/data_text_normalization/test_cases_date.txt')) + @pytest.mark.run_only_on('CPU') @pytest.mark.unit def test_norm(self, test_input, expected): pred = self.normalizer_tr.normalize(test_input, verbose=False) diff --git a/tests/nemo_text_processing/tr/test_decimal.py b/tests/nemo_text_processing/tr/test_decimal.py index 093ac9f43..b453ffac0 100644 --- a/tests/nemo_text_processing/tr/test_decimal.py +++ b/tests/nemo_text_processing/tr/test_decimal.py @@ -21,10 +21,10 @@ class TestDecimal: - normalizer_tr = Normalizer(input_case="cased", lang="tr", cache_dir=CACHE_DIR, overwrite_cache=False) + normalizer_tr = Normalizer(input_case='cased', lang='tr', cache_dir=CACHE_DIR, overwrite_cache=False) - @parameterized.expand(parse_test_case_file("tr/data_text_normalization/test_cases_decimal.txt")) - @pytest.mark.run_only_on("CPU") + @parameterized.expand(parse_test_case_file('tr/data_text_normalization/test_cases_decimal.txt')) + @pytest.mark.run_only_on('CPU') @pytest.mark.unit def test_norm(self, test_input, expected): pred = self.normalizer_tr.normalize(test_input, verbose=False) diff --git a/tests/nemo_text_processing/tr/test_fraction.py b/tests/nemo_text_processing/tr/test_fraction.py index 27090d41e..a9033d502 100644 --- a/tests/nemo_text_processing/tr/test_fraction.py +++ b/tests/nemo_text_processing/tr/test_fraction.py @@ -21,10 +21,10 @@ class TestFraction: - normalizer_tr = Normalizer(input_case="cased", lang="tr", cache_dir=CACHE_DIR, overwrite_cache=False) + normalizer_tr = Normalizer(input_case='cased', lang='tr', cache_dir=CACHE_DIR, overwrite_cache=False) - @parameterized.expand(parse_test_case_file("tr/data_text_normalization/test_cases_fraction.txt")) - @pytest.mark.run_only_on("CPU") + @parameterized.expand(parse_test_case_file('tr/data_text_normalization/test_cases_fraction.txt')) + @pytest.mark.run_only_on('CPU') @pytest.mark.unit def test_norm(self, test_input, expected): pred = self.normalizer_tr.normalize(test_input, verbose=False) diff --git a/tests/nemo_text_processing/tr/test_lower_cased.py b/tests/nemo_text_processing/tr/test_lower_cased.py new file mode 100644 index 000000000..e7d950a01 --- /dev/null +++ b/tests/nemo_text_processing/tr/test_lower_cased.py @@ -0,0 +1,31 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pytest +from parameterized import parameterized + +from nemo_text_processing.text_normalization.normalize import Normalizer + +from ..utils import CACHE_DIR, parse_test_case_file + + +class TestLowerCased: + normalizer_tr = Normalizer(input_case='lower_cased', lang='tr', cache_dir=CACHE_DIR, overwrite_cache=False) + + @parameterized.expand(parse_test_case_file('tr/data_text_normalization/test_cases_lower_cased.txt')) + @pytest.mark.run_only_on('CPU') + @pytest.mark.unit + def test_norm(self, test_input, expected): + pred = self.normalizer_tr.normalize(test_input, verbose=False) + assert pred == expected diff --git a/tests/nemo_text_processing/tr/test_measure.py b/tests/nemo_text_processing/tr/test_measure.py index c90496528..dfd7064ad 100644 --- a/tests/nemo_text_processing/tr/test_measure.py +++ b/tests/nemo_text_processing/tr/test_measure.py @@ -21,10 +21,10 @@ class TestMeasure: - normalizer_tr = Normalizer(input_case="cased", lang="tr", cache_dir=CACHE_DIR, overwrite_cache=False) + normalizer_tr = Normalizer(input_case='cased', lang='tr', cache_dir=CACHE_DIR, overwrite_cache=False) - @parameterized.expand(parse_test_case_file("tr/data_text_normalization/test_cases_measure.txt")) - @pytest.mark.run_only_on("CPU") + @parameterized.expand(parse_test_case_file('tr/data_text_normalization/test_cases_measure.txt')) + @pytest.mark.run_only_on('CPU') @pytest.mark.unit def test_norm(self, test_input, expected): pred = self.normalizer_tr.normalize(test_input, verbose=False) diff --git a/tests/nemo_text_processing/tr/test_money.py b/tests/nemo_text_processing/tr/test_money.py index 144f7d28a..fe1334a2e 100644 --- a/tests/nemo_text_processing/tr/test_money.py +++ b/tests/nemo_text_processing/tr/test_money.py @@ -21,10 +21,10 @@ class TestMoney: - normalizer_tr = Normalizer(input_case="cased", lang="tr", cache_dir=CACHE_DIR, overwrite_cache=False) + normalizer_tr = Normalizer(input_case='cased', lang='tr', cache_dir=CACHE_DIR, overwrite_cache=False) - @parameterized.expand(parse_test_case_file("tr/data_text_normalization/test_cases_money.txt")) - @pytest.mark.run_only_on("CPU") + @parameterized.expand(parse_test_case_file('tr/data_text_normalization/test_cases_money.txt')) + @pytest.mark.run_only_on('CPU') @pytest.mark.unit def test_norm(self, test_input, expected): pred = self.normalizer_tr.normalize(test_input, verbose=False) diff --git a/tests/nemo_text_processing/tr/test_ordinal.py b/tests/nemo_text_processing/tr/test_ordinal.py index 16f22cbbc..c91f051aa 100644 --- a/tests/nemo_text_processing/tr/test_ordinal.py +++ b/tests/nemo_text_processing/tr/test_ordinal.py @@ -21,10 +21,10 @@ class TestOrdinal: - normalizer_tr = Normalizer(input_case="cased", lang="tr", cache_dir=CACHE_DIR, overwrite_cache=False) + normalizer_tr = Normalizer(input_case='cased', lang='tr', cache_dir=CACHE_DIR, overwrite_cache=False) - @parameterized.expand(parse_test_case_file("tr/data_text_normalization/test_cases_ordinal.txt")) - @pytest.mark.run_only_on("CPU") + @parameterized.expand(parse_test_case_file('tr/data_text_normalization/test_cases_ordinal.txt')) + @pytest.mark.run_only_on('CPU') @pytest.mark.unit def test_norm(self, test_input, expected): pred = self.normalizer_tr.normalize(test_input, verbose=False) diff --git a/tests/nemo_text_processing/tr/test_sentences.py b/tests/nemo_text_processing/tr/test_sentences.py new file mode 100644 index 000000000..99757366e --- /dev/null +++ b/tests/nemo_text_processing/tr/test_sentences.py @@ -0,0 +1,31 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pytest +from parameterized import parameterized + +from nemo_text_processing.text_normalization.normalize import Normalizer + +from ..utils import CACHE_DIR, parse_test_case_file + + +class TestSentences: + normalizer_tr = Normalizer(input_case='cased', lang='tr', cache_dir=CACHE_DIR, overwrite_cache=False) + + @parameterized.expand(parse_test_case_file('tr/data_text_normalization/test_cases_sentences.txt')) + @pytest.mark.run_only_on('CPU') + @pytest.mark.unit + def test_norm(self, test_input, expected): + pred = self.normalizer_tr.normalize(test_input, verbose=False) + assert pred == expected diff --git a/tests/nemo_text_processing/tr/test_sparrowhawk_normalization.sh b/tests/nemo_text_processing/tr/test_sparrowhawk_normalization.sh index b6281fa60..fa2561ce6 100644 --- a/tests/nemo_text_processing/tr/test_sparrowhawk_normalization.sh +++ b/tests/nemo_text_processing/tr/test_sparrowhawk_normalization.sh @@ -37,11 +37,6 @@ testTNDecimal() { runtest $input } -testTNFraction() { - input=$PROJECT_DIR/tr/data_text_normalization/test_cases_fraction.txt - runtest $input -} - testTNMoney() { input=$PROJECT_DIR/tr/data_text_normalization/test_cases_money.txt runtest $input @@ -52,6 +47,11 @@ testTNMeasure() { runtest $input } +testTNTelephone() { + input=$PROJECT_DIR/tr/data_text_normalization/test_cases_telephone.txt + runtest $input +} + testTNDate() { input=$PROJECT_DIR/tr/data_text_normalization/test_cases_date.txt runtest $input @@ -62,11 +62,6 @@ testTNTime() { runtest $input } -testTNTelephone() { - input=$PROJECT_DIR/tr/data_text_normalization/test_cases_telephone.txt - runtest $input -} - testTNWhitelist() { input=$PROJECT_DIR/tr/data_text_normalization/test_cases_whitelist.txt runtest $input @@ -77,5 +72,15 @@ testTNWord() { runtest $input } +testTNSentences() { + input=$PROJECT_DIR/tr/data_text_normalization/test_cases_sentences.txt + runtest $input +} + +testTNFraction() { + input=$PROJECT_DIR/tr/data_text_normalization/test_cases_fraction.txt + runtest $input +} + # Load shUnit2 . $PROJECT_DIR/../shunit2/shunit2 diff --git a/tests/nemo_text_processing/tr/test_telephone.py b/tests/nemo_text_processing/tr/test_telephone.py index a29d5782e..118c2674f 100644 --- a/tests/nemo_text_processing/tr/test_telephone.py +++ b/tests/nemo_text_processing/tr/test_telephone.py @@ -21,10 +21,10 @@ class TestTelephone: - normalizer_tr = Normalizer(input_case="cased", lang="tr", cache_dir=CACHE_DIR, overwrite_cache=False) + normalizer_tr = Normalizer(input_case='cased', lang='tr', cache_dir=CACHE_DIR, overwrite_cache=False) - @parameterized.expand(parse_test_case_file("tr/data_text_normalization/test_cases_telephone.txt")) - @pytest.mark.run_only_on("CPU") + @parameterized.expand(parse_test_case_file('tr/data_text_normalization/test_cases_telephone.txt')) + @pytest.mark.run_only_on('CPU') @pytest.mark.unit def test_norm(self, test_input, expected): pred = self.normalizer_tr.normalize(test_input, verbose=False) diff --git a/tests/nemo_text_processing/tr/test_time.py b/tests/nemo_text_processing/tr/test_time.py index c3846443a..396d3d6dd 100644 --- a/tests/nemo_text_processing/tr/test_time.py +++ b/tests/nemo_text_processing/tr/test_time.py @@ -21,10 +21,10 @@ class TestTime: - normalizer_tr = Normalizer(input_case="cased", lang="tr", cache_dir=CACHE_DIR, overwrite_cache=False) + normalizer_tr = Normalizer(input_case='cased', lang='tr', cache_dir=CACHE_DIR, overwrite_cache=False) - @parameterized.expand(parse_test_case_file("tr/data_text_normalization/test_cases_time.txt")) - @pytest.mark.run_only_on("CPU") + @parameterized.expand(parse_test_case_file('tr/data_text_normalization/test_cases_time.txt')) + @pytest.mark.run_only_on('CPU') @pytest.mark.unit def test_norm(self, test_input, expected): pred = self.normalizer_tr.normalize(test_input, verbose=False) diff --git a/tests/nemo_text_processing/tr/test_whitelist.py b/tests/nemo_text_processing/tr/test_whitelist.py index 274418402..c30cdbc8a 100644 --- a/tests/nemo_text_processing/tr/test_whitelist.py +++ b/tests/nemo_text_processing/tr/test_whitelist.py @@ -21,10 +21,10 @@ class TestWhitelist: - normalizer_tr = Normalizer(input_case="cased", lang="tr", cache_dir=CACHE_DIR, overwrite_cache=False) + normalizer_tr = Normalizer(input_case='cased', lang='tr', cache_dir=CACHE_DIR, overwrite_cache=False) - @parameterized.expand(parse_test_case_file("tr/data_text_normalization/test_cases_whitelist.txt")) - @pytest.mark.run_only_on("CPU") + @parameterized.expand(parse_test_case_file('tr/data_text_normalization/test_cases_whitelist.txt')) + @pytest.mark.run_only_on('CPU') @pytest.mark.unit def test_norm(self, test_input, expected): pred = self.normalizer_tr.normalize(test_input, verbose=False) diff --git a/tests/nemo_text_processing/tr/test_word.py b/tests/nemo_text_processing/tr/test_word.py index 0a49380fd..151485096 100644 --- a/tests/nemo_text_processing/tr/test_word.py +++ b/tests/nemo_text_processing/tr/test_word.py @@ -21,10 +21,10 @@ class TestWord: - normalizer_tr = Normalizer(input_case="cased", lang="tr", cache_dir=CACHE_DIR, overwrite_cache=False) + normalizer_tr = Normalizer(input_case='cased', lang='tr', cache_dir=CACHE_DIR, overwrite_cache=False) - @parameterized.expand(parse_test_case_file("tr/data_text_normalization/test_cases_word.txt")) - @pytest.mark.run_only_on("CPU") + @parameterized.expand(parse_test_case_file('tr/data_text_normalization/test_cases_word.txt')) + @pytest.mark.run_only_on('CPU') @pytest.mark.unit def test_norm(self, test_input, expected): pred = self.normalizer_tr.normalize(test_input, verbose=False) From c8b431b69009390bb7353a3ef7a1001c859959c3 Mon Sep 17 00:00:00 2001 From: Doruk Dumlu Date: Sat, 28 Nov 2026 18:49:28 -0500 Subject: [PATCH 4/6] Turkish TN: fractions, measures and telephone back; held-out fixes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Restores fraction, measure units and telephone. Only proper fractions are read denominator first; others use 'bölü' (140/90 mmHg). A unit written without a space needs two or more letters (802.11g, 5G stay names). Adds scores with zero, date and four-digit ranges, 'saatte ... km/sa', an area code before a call-centre number, and kcal, g/dl, IU/ml, nm, MP. Signed-off-by: Doruk Dumlu --- .../tr/data/measures/units.tsv | 5 +++++ .../text_normalization/tr/taggers/fraction.py | 17 +++++++++++------ .../text_normalization/tr/taggers/measure.py | 19 +++++++++++++++++-- .../tr/taggers/telephone.py | 2 ++ .../tr/taggers/tokenize_and_classify.py | 9 ++++++++- .../test_cases_sentences.txt | 12 ++++++++++++ 6 files changed, 55 insertions(+), 9 deletions(-) diff --git a/nemo_text_processing/text_normalization/tr/data/measures/units.tsv b/nemo_text_processing/text_normalization/tr/data/measures/units.tsv index 30c232f86..8bbd5269c 100644 --- a/nemo_text_processing/text_normalization/tr/data/measures/units.tsv +++ b/nemo_text_processing/text_normalization/tr/data/measures/units.tsv @@ -43,3 +43,8 @@ dk. dakika sn. saniye sa. saat mmHg milimetre cıva +kcal kilokalori +g/dl gram bölü desilitre +IU/ml ünite bölü mililitre +nm nanometre +MP megapiksel diff --git a/nemo_text_processing/text_normalization/tr/taggers/fraction.py b/nemo_text_processing/text_normalization/tr/taggers/fraction.py index b977d3d86..a85f5c312 100644 --- a/nemo_text_processing/text_normalization/tr/taggers/fraction.py +++ b/nemo_text_processing/text_normalization/tr/taggers/fraction.py @@ -54,21 +54,24 @@ def __init__(self, cardinal: GraphFst, deterministic: bool = True): named = [] for denominator in NAMED_DENOMINATORS: spoken = rewrite.top_rewrite(str(denominator), to_locative) + # only proper fractions: "140/90" (a blood pressure) is not "doksanda yüz kırk" but "yüz kırk bölü doksan" + proper = pynini.union(*[str(n) for n in range(1, min(denominator, 1000))]) @ numerator # a suffix goes on the numerator, the last word read: "3/4'ü" -> "dörtte üçü" - body = numerator + pynutil.delete(f"/{denominator}") + body = proper + pynutil.delete(f"/{denominator}") named.append( pynutil.insert(f'denominator: "{spoken}" numerator: "') + (body | attach_suffix(body)) + pynutil.insert('" preserve_order: true') ) named = pynini.union(*named) + symbols = [] for symbol, num, den in load_labels(get_abs_path("data/fractions/fraction_symbols.tsv")): spoken_den = rewrite.top_rewrite(den, to_locative) spoken_num = rewrite.top_rewrite(num, cardinal.graph) - named |= pynini.cross( - symbol, - f'denominator: "{spoken_den}" numerator: "{spoken_num}" preserve_order: true', + symbols.append( + pynini.cross(symbol, f'denominator: "{spoken_den}" numerator: "{spoken_num}" preserve_order: true') ) + symbols = pynini.union(*symbols) other = ( pynutil.insert('numerator: "') @@ -78,9 +81,11 @@ def __init__(self, cardinal: GraphFst, deterministic: bool = True): + pynutil.insert('"') ) - fraction = named | pynutil.add_weight(other, 0.1) + fraction = named | symbols | pynutil.add_weight(other, 0.1) integer_part = pynutil.insert('integer_part: "') + plain_number + pynutil.insert('" ') - mixed = integer_part + pynini.closure(pynutil.delete(NEMO_SPACE), 0, 1) + named + # "2 1/2" needs the space ("140/90" is not "1" and "40/90"); "2½" does not + mixed = integer_part + pynutil.delete(NEMO_SPACE) + named + mixed |= integer_part + pynini.closure(pynutil.delete(NEMO_SPACE), 0, 1) + symbols self.graph = (fraction | mixed).optimize() self.fst = self.add_tokens(self.graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/taggers/measure.py b/nemo_text_processing/text_normalization/tr/taggers/measure.py index 3d8b4492e..9b73133c8 100644 --- a/nemo_text_processing/text_normalization/tr/taggers/measure.py +++ b/nemo_text_processing/text_normalization/tr/taggers/measure.py @@ -15,7 +15,7 @@ import pynini from pynini.lib import pynutil -from nemo_text_processing.text_normalization.en.graph_utils import NEMO_SPACE, GraphFst +from nemo_text_processing.text_normalization.en.graph_utils import NEMO_CHAR, NEMO_DIGIT, NEMO_SPACE, GraphFst from nemo_text_processing.text_normalization.tr.graph_utils import attach_suffix from nemo_text_processing.text_normalization.tr.utils import get_abs_path @@ -76,7 +76,18 @@ def wrap_decimal(graph): def with_units(number_graph, unit_graph): return number_graph + optional_space + pynutil.insert(" units: \"") + unit_graph + pynutil.insert("\"") - unit_graph = with_units(signed, units) + # A unit written without a space must have two or more letters and follow a number without a dot ("5km", + # "2,5kg"): a single letter right after a number is too often part of a name ("802.11g", "5G", "M3"). + space = pynutil.delete(NEMO_SPACE) + no_dot = pynini.closure(pynini.difference(NEMO_CHAR, ".")) + long_written = pynini.closure(NEMO_CHAR, 2) - pynini.union("m²", "m³", "m2", "m3") + long_units = pynini.compose(long_written, units) + unit_graph = signed + space + pynutil.insert(" units: \"") + units + pynutil.insert("\"") + unit_graph |= pynini.compose(no_dot, signed) + pynutil.insert(" units: \"") + long_units + pynutil.insert("\"") + + # "140/90 mmHg" -> "yüz kırk bölü doksan milimetre cıva" + plain = ((NEMO_DIGIT - "0") + pynini.closure(NEMO_DIGIT)) @ cardinal.graph + unit_graph |= with_units(wrap_cardinal(plain + pynini.cross("/", " bölü ") + plain), units) # dimensions: "30x20x10 cm" -> "otuz çarpı yirmi çarpı on santimetre" times = pynini.closure(pynutil.delete(NEMO_SPACE), 0, 1) + pynini.cross(pynini.union("x", "×"), " çarpı ") @@ -85,12 +96,16 @@ def with_units(number_graph, unit_graph): unit_graph |= with_units(wrap_cardinal(dimensions), units) # speeds read "per hour first": "120 km/sa" -> "saatte yüz yirmi kilometre", "10 m/s" -> "saniyede on metre" + after_per_word = [] # for "saatte 330 km/sa", where the text already says "saatte" for written, per, unit in (("km/sa", "saatte", "kilometre"), ("km/saat", "saatte", "kilometre"), ("m/s", "saniyede", "metre")): # fmt: skip speed_unit = pynini.cross(written, unit) speed_unit |= attach_suffix(speed_unit) per_number = wrap_cardinal(pynutil.insert(per + " ") + cardinal.graph) unit_graph |= with_units(per_number, speed_unit) + if per == "saatte": + after_per_word.append(with_units(wrap_cardinal(cardinal.graph), speed_unit)) + self.fst_speed_after_per_word = self.add_tokens(pynini.union(*after_per_word)).optimize() self.graph = (unit_graph | percent_first | percent_last).optimize() self.fst = self.add_tokens(self.graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/taggers/telephone.py b/nemo_text_processing/text_normalization/tr/taggers/telephone.py index c4f2bfed5..04e1205a7 100644 --- a/nemo_text_processing/text_normalization/tr/taggers/telephone.py +++ b/nemo_text_processing/text_normalization/tr/taggers/telephone.py @@ -80,6 +80,8 @@ def group(n): ) # call centre numbers: "444 0 123" call_centre = group(3) + delete_sep + comma + group(1) + delete_sep + comma + group(3) + # with an area code: "0212 444 0 123" + call_centre |= area + delete_sep + comma + call_centre # a suffix goes on the last group: "0532 123 45 67'den" -> "... altmış yediden" numbers = national | call_centre diff --git a/nemo_text_processing/text_normalization/tr/taggers/tokenize_and_classify.py b/nemo_text_processing/text_normalization/tr/taggers/tokenize_and_classify.py index 1bb8378f7..dc57db8fb 100644 --- a/nemo_text_processing/text_normalization/tr/taggers/tokenize_and_classify.py +++ b/nemo_text_processing/text_normalization/tr/taggers/tokenize_and_classify.py @@ -207,9 +207,10 @@ def words(word_list): # ranges time_any = tok(self.time.fst, 1.09) | tok(time_in_context, 1.09) + # four-digit numbers on both sides: years ("1914-1918"), also before Christ ("MÖ 3000-1200") year = self.cardinal.add_tokens( pynutil.insert("integer: \"") - + ((pynini.union("1", "2") + NEMO_DIGIT**3) @ self.cardinal.graph) + + (((NEMO_DIGIT - "0") + NEMO_DIGIT**3) @ self.cardinal.graph) + pynutil.insert("\"") ) cardinal, decimal, measure = ( @@ -225,7 +226,10 @@ def words(word_list): | decimal + dash + ile + (decimal | cardinal) | cardinal + dash + ile + decimal | cardinal + dash + ile + tok(self.date.fst, 1.09) # "23-25 Aralık" + | tok(self.date.fst, 1.09) + dash + ile + tok(self.date.fst, 1.09) # "12 Nisan - 30 Haziran 2024" ) + # "saatte 330 km/sa": the text already says "saatte" + ranges |= words(["saatte", "Saatte"]) + space + tok(self.measure.fst_speed_after_per_word, 1.0) # small numbers: "3-5 iş günü" is a range (a < b), "11-9" and "6-6'ya" are scores (a >= b) written_suffix = pynini.closure(APOSTROPHE + pynini.closure(TR_ALPHA, 1), 0, 1) less, not_less = number_pairs() @@ -276,6 +280,9 @@ def number(n): return (NEMO_DIGIT - "0") + digits(n - 1) less, more, equal = [], [], [] + # zero on either side is a score: "3-0", "2-0'lık", "0-3 yenildi", "0-0" + more.append(pynini.union("0") + separator + pynini.union(*[number(n) for n in range(1, 4)], "0")) + more.append(pynini.union(*[number(n) for n in range(1, 4)]) + separator + "0") for na in range(1, 4): for nb in range(1, 4): if na < nb: diff --git a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_sentences.txt b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_sentences.txt index caac21563..ce5f47883 100644 --- a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_sentences.txt +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_sentences.txt @@ -29,3 +29,15 @@ Görüntü oranı 3:2 olarak belirlendi.~Görüntü oranı üçe iki olarak beli Python 3.12.1 sürümü yayımlandı.~Python üç nokta on iki nokta bir sürümü yayımlandı. Şirketin karı 3,7 milyar TL'ye ulaştı.~Şirketin karı üç virgül yedi milyar liraya ulaştı. Tahminlere göre 1.sırada yer alan takım.~Tahminlere göre birinci sırada yer alan takım. +Cihaz 802.11g ile uyumlu.~Cihaz 802.11g ile uyumlu. +Tansiyon 140/90 mmHg üzerinde.~Tansiyon yüz kırk bölü doksan milimetre cıva üzerinde. +Bizi 0212 444 0 123 numarasından arayın.~Bizi sıfır iki yüz on iki, dört yüz kırk dört, sıfır, yüz yirmi üç numarasından arayın. +Takım 2-0'lık skorla turladı.~Takım iki sıfırlık skorla turladı. +Sırbistan'a 0-3 yenildi.~Sırbistan'a sıfır üç yenildi. +Sergi 12 Nisan - 30 Haziran 2024 tarihleri arasında açık.~Sergi on iki nisan ile otuz haziran iki bin yirmi dört tarihleri arasında açık. +Eserler MÖ 3000-1200 yıllarına ait.~Eserler MÖ üç bin ile bin iki yüz yıllarına ait. +Araç saatte 330 km/sa hıza ulaştı.~Araç saatte üç yüz otuz kilometre hıza ulaştı. +Porsiyonda 320 kcal var.~Porsiyonda üç yüz yirmi kilokalori var. +Paket 500 g geldi.~Paket beş yüz gram geldi. +Paket 2,5kg geldi.~Paket iki buçuk kilogram geldi. +Şirket 5G altyapısına yatırım yaptı.~Şirket 5G altyapısına yatırım yaptı. From e0df12b0db120d65f2507dc46fcdfd33f178593a Mon Sep 17 00:00:00 2001 From: Doruk Dumlu Date: Sat, 28 Nov 2026 21:52:59 -0500 Subject: [PATCH 5/6] Turkish TN: split context patterns into classes, smaller grammar MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - RangeFst, SerialFst and ContextFst (like en's range and serial classes) replace the context patterns that lived in tokenize_and_classify; they read their neighbours with composed taggers and verbalizers and emit name tokens. - "bölü" and "saatte" are morphosyntactic_features instead of text inside fields; "ile" and "nokta" are part of the composed readings instead of injected tokens. - Multi-word names keep plain spaces (no per-word name tokens), ISO dates rely on the Date proto field order instead of enumerating day and month, and suffixes are attached once per fraction: the tagger goes from 1.15M to 365k states and the FAR from 39.5 MB to 16.6 MB. - Fixes: lower-case currency codes only after an amount and never "try"; a dotted time needs a case suffix ("1.25'lik" is a decimal); the unbounded fst ** 0 in telephone groups. - Unit tests for the suffix engine, negative tests for over-matches. A suffix after an ISO date is no longer supported. Signed-off-by: Doruk Dumlu --- .../text_normalization/tr/graph_utils.py | 29 +- .../text_normalization/tr/inflection.py | 16 +- .../text_normalization/tr/taggers/context.py | 105 ++++++ .../text_normalization/tr/taggers/date.py | 55 ++- .../text_normalization/tr/taggers/fraction.py | 57 +-- .../text_normalization/tr/taggers/measure.py | 109 +++--- .../text_normalization/tr/taggers/money.py | 5 +- .../text_normalization/tr/taggers/range.py | 135 ++++++++ .../text_normalization/tr/taggers/serial.py | 56 +++ .../tr/taggers/telephone.py | 10 +- .../text_normalization/tr/taggers/time.py | 30 +- .../tr/taggers/tokenize_and_classify.py | 327 ++++++------------ .../tr/taggers/whitelist.py | 20 +- .../tr/verbalizers/fraction.py | 15 +- .../tr/verbalizers/measure.py | 28 +- .../tr/verbalizers/verbalize.py | 6 +- .../tr/verbalizers/verbalize_final.py | 12 +- .../test_cases_date.txt | 1 - .../test_cases_sentences.txt | 4 + .../tr/test_inflection.py | 68 ++++ 20 files changed, 699 insertions(+), 389 deletions(-) create mode 100644 nemo_text_processing/text_normalization/tr/taggers/context.py create mode 100644 nemo_text_processing/text_normalization/tr/taggers/range.py create mode 100644 nemo_text_processing/text_normalization/tr/taggers/serial.py create mode 100644 tests/nemo_text_processing/tr/test_inflection.py diff --git a/nemo_text_processing/text_normalization/tr/graph_utils.py b/nemo_text_processing/text_normalization/tr/graph_utils.py index 49ba28824..aee9f69b2 100644 --- a/nemo_text_processing/text_normalization/tr/graph_utils.py +++ b/nemo_text_processing/text_normalization/tr/graph_utils.py @@ -13,11 +13,12 @@ # limitations under the License. import pynini +from pynini.lib import pynutil -from nemo_text_processing.text_normalization.tr.inflection import MARK, get_suffix_rewrite - -TR_LOWER = pynini.union(*"abcçdefgğhıijklmnoöprsştuüvyzâîûqwx").optimize() -TR_UPPER = pynini.union(*"ABCÇDEFGĞHIİJKLMNOÖPRSŞTUÜVYZÂÎÛQWX").optimize() +LOWER_LETTERS = "abcçdefgğhıijklmnoöprsştuüvyzâîûqwx" +UPPER_LETTERS = "ABCÇDEFGĞHIİJKLMNOÖPRSŞTUÜVYZÂÎÛQWX" +TR_LOWER = pynini.union(*LOWER_LETTERS).optimize() +TR_UPPER = pynini.union(*UPPER_LETTERS).optimize() TR_ALPHA = pynini.union(TR_LOWER, TR_UPPER).optimize() # Turkish separates a case or possessive suffix from a numeral with an apostrophe: "4'e", "2024'te", "10:30'da". @@ -25,7 +26,7 @@ SUFFIX = pynini.closure(TR_ALPHA, 1).optimize() -def attach_suffix(graph: "pynini.FstLike") -> "pynini.FstLike": +def attach_suffix(graph: "pynini.FstLike", suffixes: list = None) -> "pynini.FstLike": """ Appends the suffix written after an apostrophe to the spoken form, rebuilt for its last word, e.g. "4'e" -> "dörde", "1990'lı" -> "bin dokuz yüz doksanlı", "4'de" -> "dörtte", "100 TL'ye" -> "yüz liraya" @@ -33,8 +34,24 @@ def attach_suffix(graph: "pynini.FstLike") -> "pynini.FstLike": Args: graph: an fst whose output is spoken words + suffixes: if given, only these suffixes (archiphoneme notation, e.g. ["DA", "(y)A"]) are accepted Returns: an fst that accepts the input of graph followed by an apostrophe and a suffix """ - return ((graph + pynini.cross(APOSTROPHE, MARK) + SUFFIX) @ get_suffix_rewrite()).optimize() + from nemo_text_processing.text_normalization.tr.inflection import MARK, get_suffix_rewrite, surface_forms + + written = SUFFIX + if suffixes is not None: + written = pynini.union(*[s for s, a in surface_forms().items() if a in suffixes]) + return ((graph + pynini.cross(APOSTROPHE, MARK) + written) @ get_suffix_rewrite()).optimize() + + +def name_tokens(graph: "pynini.FstLike") -> "pynini.FstLike": + """ + Wraps a reading of one or more words as a name token: "3-5" -> name: "üç ile beş". + + The words keep plain spaces, not the non-breaking spaces of convert_space: Sparrowhawk prints a name token as it + is, so a non-breaking space would stay in its output. VerbalizeFinalFst verbalizes such names. + """ + return pynutil.insert('name: "') + graph + pynutil.insert('"') diff --git a/nemo_text_processing/text_normalization/tr/inflection.py b/nemo_text_processing/text_normalization/tr/inflection.py index a9fba7062..20993bb1f 100644 --- a/nemo_text_processing/text_normalization/tr/inflection.py +++ b/nemo_text_processing/text_normalization/tr/inflection.py @@ -33,6 +33,7 @@ from nemo_text_processing.text_normalization.en.graph_utils import NEMO_CHAR, NEMO_SPACE from nemo_text_processing.text_normalization.en.utils import load_labels +from nemo_text_processing.text_normalization.tr.graph_utils import SUFFIX from nemo_text_processing.text_normalization.tr.utils import get_abs_path VOWELS = "aeıioöuüâîû" @@ -42,10 +43,13 @@ # Final consonants that soften before a vowel in these words ("dört" -> "dördü", "ocak" -> "ocağa"). SOFTENING = {"dört": "dörd", "ocak": "ocağ", "aralık": "aralığ", "buçuk": "buçuğ"} +# Words that take front suffixes although their last vowel is back ("saate", "kilovatsaati"). +FRONT_HARMONY = ("saat",) # Common suffixes after numbers, currencies and months, in archiphoneme notation: # A = a/e, I = ı/i/u/ü, D = d/t, C = c/ç, (y)(n)(s)(ş) = buffer consonant after a vowel. -# Where two suffixes share a surface form ("ü": accusative or possessive), the first one wins. +# Two suffixes can share a surface form: the bare "ü" is an accusative or a possessive. The order below decides which +# one a written form is read as; after a consonant both give the same word ("dört" + "ü" -> "dördü"). SUFFIXES = [ "(y)I", "(y)A", "DA", "DAn", "(n)In", "(y)lA", "(s)I", "(s)InI", "(s)InA", "(s)InDA", "(s)InDAn", "(s)InIn", "(s)I(y)lA", @@ -58,7 +62,7 @@ def _last_vowel(text: str) -> str: - if text.endswith("saat"): # takes front suffixes: "saate", "kilovatsaati" + if text.endswith(FRONT_HARMONY): return "e" for char in reversed(text): if char in VOWELS: @@ -102,6 +106,7 @@ def inflect_word(word: str, suffix: str) -> str: return out +@lru_cache(maxsize=None) def surface_forms() -> dict: """Every way each suffix is written, after any vowel and any final consonant: surface -> archiphoneme form.""" stems = [f"k{v}{end}" for v in "aeıioöuü" for end in ("", "n", "t")] @@ -141,7 +146,8 @@ def get_suffix_rewrite() -> 'pynini.FstLike': table = pynini.string_map(pairs) no_mark = pynini.closure(pynini.difference(NEMO_CHAR, MARK)) known = table | no_mark + NEMO_SPACE + table - letters = pynini.union(*"abcçdefgğhıijklmnoöprsştuüvyzâîûqwxABCÇDEFGĞHIİJKLMNOÖPRSŞTUÜVYZÂÎÛQWX") - copied = no_mark + pynutil.delete(MARK) + pynini.closure(letters, 1) - copied @= pynini.cdrewrite(pynini.cross("dört", "dörd"), "", pynini.union(*VOWELS), pynini.closure(NEMO_CHAR)) + # an unknown suffix is copied as written; the words in SOFTENING still soften before it + soften = pynini.union(*[pynini.cross(word, soft) for word, soft in SOFTENING.items()]) + copied = no_mark + pynutil.delete(MARK) + SUFFIX + copied @= pynini.cdrewrite(soften, "", pynini.union(*VOWELS), pynini.closure(NEMO_CHAR)) return (known | pynutil.add_weight(copied, 1.0)).optimize() diff --git a/nemo_text_processing/text_normalization/tr/taggers/context.py b/nemo_text_processing/text_normalization/tr/taggers/context.py new file mode 100644 index 000000000..2d821b1f2 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/taggers/context.py @@ -0,0 +1,105 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pynini +from pynini.lib import pynutil + +from nemo_text_processing.text_normalization.en.graph_utils import NEMO_DIGIT, NEMO_NOT_SPACE, NEMO_SPACE, GraphFst +from nemo_text_processing.text_normalization.en.utils import load_labels +from nemo_text_processing.text_normalization.tr.graph_utils import TR_ALPHA, TR_LOWER, attach_suffix, name_tokens +from nemo_text_processing.text_normalization.tr.inflection import surface_forms +from nemo_text_processing.text_normalization.tr.utils import get_abs_path + +# Words after which a number is a code, read digit by digit: "Doğrulama kodunuz 482913" +CODE_WORDS = [ + "kod", + "kodu", + "kodunuz", + "kodum", + "şifre", + "şifreniz", + "şifrem", + "parola", + "parolanız", + "pin", + "PIN", + "OTP", +] +# Words that join list items: "1., 2. ve 3. taksit" +CONNECTORS = ["ve", "veya", "ile", "ya", "da"] + + +def capitalized(words): + return words + [w[0].upper() + w[1:] for w in words if w[0].islower()] + + +class ContextFst(GraphFst): + """ + Finite state transducer for numbers whose reading depends on the word next to them, emitted (with that word) + as name tokens, e.g. + "5. sırada" -> tokens { name: "beşinci" } tokens { name: "sırada" } + "1., 2. ve 3. taksit" -> "birinci , ikinci ve üçüncü taksit" + "1.sırada" -> "birinci sırada" + "XX. yüzyıl", "II. Mehmet" -> "yirminci yüzyıl", "ikinci Mehmet" + "saat 17.30" -> "saat on yedi otuz" (without "saat", "17.30" is a decimal) + "saatte 330 km/sa" -> "saatte üç yüz otuz kilometre" (the text already says "saatte") + "kodunuz 482913" -> "kodunuz dört sekiz iki dokuz bir üç" + + A number with a dot is an ordinal only before a word; at the end of a sentence ("Sırada 5.") it stays a number + and a full stop. In lower-cased text a sentence end cannot be told from a following word, so only known nouns + ("taksit", "sıra", "kat" ..., data/ordinals/ordinal_nouns.tsv) are accepted there. + + Args: + composed: dict of tagger @ verbalizer fsts for "ordinal_dot", "ordinal_roman", "time_in_context", + "speed_after_per_word" + cardinal: CardinalFst + input_case: "cased" or "lower_cased" + deterministic: if True will provide a single transduction option, + for False multiple transduction are generated (used for audio-based normalization) + """ + + def __init__(self, composed: dict, cardinal: GraphFst, input_case: str, deterministic: bool = True): + super().__init__(name="context", kind="classify", deterministic=deterministic) + + space = pynini.cross(pynini.closure(NEMO_SPACE, 1), " ") + punctuation = pynini.closure(pynini.union(",", ".", "?", "!", ";", ":"), 0, 1) + + def word(first_letters): + return first_letters + pynini.closure(NEMO_NOT_SPACE) + + def word_list(words): + return pynini.union(*words) + + # ordinals + nouns = [row[0] for row in load_labels(get_abs_path("data/ordinals/ordinal_nouns.tsv"))] + noun = word_list(capitalized(nouns)) + pynini.closure(word_list(list(surface_forms())), 0, 1) + punctuation + following = noun if input_case == "lower_cased" else noun | word(TR_LOWER) + ordinal_dot = composed["ordinal_dot"] + item_separator = ( + pynini.closure(pynini.cross(",", " ,"), 0, 1) + space + pynini.closure(word_list(CONNECTORS) + space, 0, 1) + ) + ordinals = ordinal_dot + pynini.closure(item_separator + ordinal_dot) + space + following + ordinals |= ordinal_dot + pynutil.insert(" ") + word(TR_LOWER) # "1.sırada" + ordinals |= composed["ordinal_roman"] + space + word(TR_ALPHA) # "XX. yüzyıl", "II. Mehmet" + + # times and speeds + clock = word_list(capitalized(["saat"])) + space + composed["time_in_context"] + speed = word_list(capitalized(["saatte"])) + space + composed["speed_after_per_word"] + + # codes: four to eight digits read one by one, a suffix on the last one ("218456'dır" -> "... altıdır") + code = (NEMO_DIGIT**4 + pynini.closure(NEMO_DIGIT, 0, 4)) @ cardinal.digits + codes = word_list(capitalized(CODE_WORDS)) + space + (code | attach_suffix(code)) + + self.graph = (ordinals | clock | speed | codes).optimize() + self.fst = name_tokens(self.graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/taggers/date.py b/nemo_text_processing/text_normalization/tr/taggers/date.py index b0ec53dcb..b04253bf0 100644 --- a/nemo_text_processing/text_normalization/tr/taggers/date.py +++ b/nemo_text_processing/text_normalization/tr/taggers/date.py @@ -13,26 +13,28 @@ # limitations under the License. import pynini -from pynini.lib import pynutil, rewrite +from pynini.lib import pynutil -from nemo_text_processing.text_normalization.en.graph_utils import NEMO_CHAR, NEMO_DIGIT, NEMO_SPACE, GraphFst +from nemo_text_processing.text_normalization.en.graph_utils import NEMO_DIGIT, NEMO_SPACE, GraphFst from nemo_text_processing.text_normalization.en.utils import load_labels -from nemo_text_processing.text_normalization.tr.graph_utils import APOSTROPHE, SUFFIX, attach_suffix +from nemo_text_processing.text_normalization.tr.graph_utils import attach_suffix from nemo_text_processing.text_normalization.tr.utils import get_abs_path class DateFst(GraphFst): """ Finite state transducer for classifying dates, e.g. - "14.03.1988" -> date { day: "on dört" month: "mart" year: "bin dokuz yüz seksen sekiz" preserve_order: true } - "05/12/2026" -> date { day: "beş" month: "aralık" year: "iki bin yirmi altı" preserve_order: true } - "2026-03-15" -> date { day: "on beş" month: "mart" year: "iki bin yirmi altı" preserve_order: true } - "14 Mart 2026" -> date { day: "on dört" month: "mart" year: "iki bin yirmi altı" preserve_order: true } - "01.01.2027'de" -> date { day: "bir" month: "ocak" year: "iki bin yirmi yedide" preserve_order: true } - "15 Kasım'da" -> date { day: "on beş" month: "kasımda" preserve_order: true } - - Turkish reads day, month, year. In ISO dates (year first) the day and month are enumerated so the tagger can - emit them first. + "14.03.1988" -> date { day: "on dört" month: "mart" year: "bin dokuz yüz seksen sekiz" } + "05/12/2026" -> date { day: "beş" month: "aralık" year: "iki bin yirmi altı" } + "2026-03-15" -> date { year: "iki bin yirmi altı" month: "mart" day: "on beş" } + "14 Mart 2026" -> date { day: "on dört" month: "mart" year: "iki bin yirmi altı" } + "01.01.2027'de" -> date { day: "bir" month: "ocak" year: "iki bin yirmi yedide" } + "15 Kasım'da" -> date { day: "on beş" month: "kasımda" } + + Turkish reads day, month, year, which is also the field order of the Date proto. Fields are emitted in the + written order without preserve_order, so an ISO date (year first) is put in that order by Sparrowhawk and by the + Normalizer's permutation of fields. A suffix after an ISO date ("2026-03-15'te") is not supported: it would have + to go on the year, which is read last. Args: cardinal: CardinalFst @@ -68,8 +70,6 @@ def __init__(self, cardinal: GraphFst, deterministic: bool = True): def field(name, graph, first=False): return pynutil.insert(("" if first else " ") + f'{name}: "') + graph + pynutil.insert('"') - preserve = pynutil.insert(" preserve_order: true") - numeric = [] for sep in [".", "/", "-"]: years = year | short_year if sep != "-" else year @@ -82,23 +82,14 @@ def field(name, graph, first=False): ) numeric = pynini.union(*numeric) - # ISO: the day and month come last in writing but first in speech, so they are enumerated; a suffix written - # after the day goes on the year, the last word read ("2026-03-15'te" -> "... iki bin yirmi altıda") - iso_year = plain_year + pynutil.delete("-" + NEMO_DIGIT**2 + "-" + NEMO_DIGIT**2) - iso_year = (iso_year | attach_suffix(iso_year)).optimize() - # Each branch inserts its day and month and copies the input; one composition then reads the year. - branches = [] - for month_number, month_name in month_numbers: - for day_value in day_values: - spoken_day = rewrite.top_rewrite(day_value, cardinal.graph) - branches.append( - pynutil.insert(f'day: "{spoken_day}" month: "{month_name}" year: "') - + year_digits - + f"-{int(month_number):02d}-{int(day_value):02d}" - + pynini.closure(APOSTROPHE + SUFFIX, 0, 1) - ) - read_year = pynini.closure(pynini.difference(NEMO_CHAR, NEMO_DIGIT)) + iso_year + pynutil.insert('"') - iso = pynini.compose(pynini.union(*branches).optimize(), read_year) + # ISO: written year first, emitted in that order (see above) + iso = ( + field("year", plain_year, first=True) + + pynutil.delete("-") + + field("month", pynini.compose(NEMO_DIGIT**2, month)) + + pynutil.delete("-") + + field("day", pynini.compose(NEMO_DIGIT**2, day)) + ) month_name = month_names | attach_suffix(month_names) textual = ( @@ -118,5 +109,5 @@ def field(name, graph, first=False): + field("year", modern_year | attach_suffix(modern_year)) ) - self.graph = (numeric | iso | textual | month_year) + preserve + self.graph = numeric | iso | textual | month_year self.fst = self.add_tokens(self.graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/taggers/fraction.py b/nemo_text_processing/text_normalization/tr/taggers/fraction.py index a85f5c312..dafa35c3f 100644 --- a/nemo_text_processing/text_normalization/tr/taggers/fraction.py +++ b/nemo_text_processing/text_normalization/tr/taggers/fraction.py @@ -15,9 +15,15 @@ import pynini from pynini.lib import pynutil, rewrite -from nemo_text_processing.text_normalization.en.graph_utils import NEMO_DIGIT, NEMO_SIGMA, NEMO_SPACE, GraphFst +from nemo_text_processing.text_normalization.en.graph_utils import ( + NEMO_CHAR, + NEMO_DIGIT, + NEMO_SIGMA, + NEMO_SPACE, + GraphFst, +) from nemo_text_processing.text_normalization.en.utils import load_labels -from nemo_text_processing.text_normalization.tr.graph_utils import attach_suffix +from nemo_text_processing.text_normalization.tr.graph_utils import APOSTROPHE, SUFFIX, attach_suffix from nemo_text_processing.text_normalization.tr.utils import get_abs_path # Denominators read the Turkish way, denominator first in the locative: "3/4" -> "dörtte üç" @@ -29,13 +35,14 @@ class FractionFst(GraphFst): Finite state transducer for classifying fractions, e.g. "3/4" -> fraction { denominator: "dörtte" numerator: "üç" preserve_order: true } "2 1/2" -> fraction { integer_part: "iki" denominator: "ikide" numerator: "bir" preserve_order: true } + "3/4'ü" -> fraction { denominator: "dörtte" numerator: "üçü" preserve_order: true } "½" -> fraction { denominator: "ikide" numerator: "bir" preserve_order: true } - "7/365" -> fraction { numerator: "yedi" denominator: "bölü üç yüz altmış beş" } + "7/365" -> fraction { numerator: "yedi" denominator: "üç yüz altmış beş" morphosyntactic_features: "bölü" } - Turkish reads the denominator first, with the locative suffix: "1/2" is "ikide bir", "1/100" is "yüzde bir". - The tagger emits the denominator first, so the order survives Sparrowhawk (preserve_order). Since an fst cannot - swap two unbounded strings, denominators 2-100 and 1000 are enumerated; other fractions are read with "bölü" - ("divided by"), which is also common. + Turkish reads a fraction denominator first, in the locative: "1/2" is "ikide bir", "1/100" is "yüzde bir". The + tagger emits the denominator first and keeps the order with preserve_order. An fst cannot swap two unbounded + strings, so proper fractions with denominators 2-100 and 1000 are enumerated. Any other a/b ("7/365", + "140/90") is read "a bölü b" ("divided by"), marked with morphosyntactic_features. Args: cardinal: CardinalFst @@ -51,19 +58,25 @@ def __init__(self, cardinal: GraphFst, deterministic: bool = True): plain_number = ((NEMO_DIGIT - "0") + pynini.closure(NEMO_DIGIT)) @ cardinal.graph numerator = ((NEMO_DIGIT - "0") + pynini.closure(NEMO_DIGIT, 0, 2)) @ cardinal.graph - named = [] + # Each branch inserts its spoken denominator and copies the input, restricted to proper fractions ("140/90" + # is not "doksanda yüz kırk"); one composition then reads the numerator and any suffix, which goes on the + # numerator, the last word read ("3/4'ü" -> "dörtte üçü"). + branches = [] for denominator in NAMED_DENOMINATORS: spoken = rewrite.top_rewrite(str(denominator), to_locative) - # only proper fractions: "140/90" (a blood pressure) is not "doksanda yüz kırk" but "yüz kırk bölü doksan" - proper = pynini.union(*[str(n) for n in range(1, min(denominator, 1000))]) @ numerator - # a suffix goes on the numerator, the last word read: "3/4'ü" -> "dörtte üçü" - body = proper + pynutil.delete(f"/{denominator}") - named.append( + proper = pynini.union(*[str(n) for n in range(1, min(denominator, 1000))]) + branches.append( pynutil.insert(f'denominator: "{spoken}" numerator: "') - + (body | attach_suffix(body)) - + pynutil.insert('" preserve_order: true') + + proper + + f"/{denominator}" + + pynini.closure(APOSTROPHE + SUFFIX, 0, 1) ) - named = pynini.union(*named) + read_numerator = numerator + pynutil.delete("/" + pynini.closure(NEMO_DIGIT, 1)) + read_numerator |= attach_suffix(read_numerator) + no_digits = pynini.closure(pynini.difference(NEMO_CHAR, NEMO_DIGIT)) + named = pynini.compose(pynini.union(*branches).optimize(), no_digits + read_numerator) + named += pynutil.insert('" preserve_order: true') + symbols = [] for symbol, num, den in load_labels(get_abs_path("data/fractions/fraction_symbols.tsv")): spoken_den = rewrite.top_rewrite(den, to_locative) @@ -73,15 +86,17 @@ def __init__(self, cardinal: GraphFst, deterministic: bool = True): ) symbols = pynini.union(*symbols) - other = ( + # "a/b" read "a bölü b"; also used by MeasureFst ("140/90 mmHg") + self.division = ( pynutil.insert('numerator: "') + plain_number - + pynini.cross("/", '" denominator: "bölü ') + + pynini.cross("/", '" denominator: "') + plain_number - + pynutil.insert('"') - ) + + pynutil.insert('" morphosyntactic_features: "bölü"') + ).optimize() - fraction = named | symbols | pynutil.add_weight(other, 0.1) + # a named fraction is preferred to "bölü" where both apply ("3/4") + fraction = named | symbols | pynutil.add_weight(self.division, 0.1) integer_part = pynutil.insert('integer_part: "') + plain_number + pynutil.insert('" ') # "2 1/2" needs the space ("140/90" is not "1" and "40/90"); "2½" does not mixed = integer_part + pynutil.delete(NEMO_SPACE) + named diff --git a/nemo_text_processing/text_normalization/tr/taggers/measure.py b/nemo_text_processing/text_normalization/tr/taggers/measure.py index 9b73133c8..fad686377 100644 --- a/nemo_text_processing/text_normalization/tr/taggers/measure.py +++ b/nemo_text_processing/text_normalization/tr/taggers/measure.py @@ -15,97 +15,88 @@ import pynini from pynini.lib import pynutil -from nemo_text_processing.text_normalization.en.graph_utils import NEMO_CHAR, NEMO_DIGIT, NEMO_SPACE, GraphFst +from nemo_text_processing.text_normalization.en.graph_utils import NEMO_CHAR, NEMO_SPACE, GraphFst from nemo_text_processing.text_normalization.tr.graph_utils import attach_suffix from nemo_text_processing.text_normalization.tr.utils import get_abs_path +# Speeds are read "per hour" first: "120 km/sa" -> "saatte yüz yirmi kilometre" +SPEEDS = [("km/sa", "saatte", "kilometre"), ("km/saat", "saatte", "kilometre"), ("m/s", "saniyede", "metre")] + class MeasureFst(GraphFst): """ Finite state transducer for classifying measures and percentages, e.g. "5 km" -> measure { cardinal { integer: "beş" } units: "kilometre" } + "-3 °C" -> measure { cardinal { negative: "true" integer: "üç" } units: "santigrat derece" } "5 kg'ye" -> measure { cardinal { integer: "beş" } units: "kilograma" } + "140/90 mmHg" -> measure { fraction { numerator: "yüz kırk" denominator: "doksan" + morphosyntactic_features: "bölü" } units: "milimetre cıva" } + "120 km/sa" -> measure { morphosyntactic_features: "saatte" cardinal { integer: "yüz yirmi" } + units: "kilometre" preserve_order: true } "%18" -> measure { units: "yüzde" cardinal { integer: "on sekiz" } preserve_order: true } - "%2,5" -> measure { units: "yüzde" decimal { integer_part: "iki buçuk" } preserve_order: true } "%14'ü" -> measure { units: "yüzde" cardinal { integer: "on dördü" } preserve_order: true } - "15%" -> measure { units: "yüzde" cardinal { integer: "on beş" } preserve_order: true } Turkish writes the percent sign before the number and reads it first ("yüzde on sekiz"); the English order - "15%" is read the same way. + "15%" is read the same way. A suffix after a unit is rebuilt for the full word ("km'ye" -> "kilometreye"). Args: cardinal: CardinalFst decimal: DecimalFst + fraction: FractionFst deterministic: if True will provide a single transduction option, for False multiple transduction are generated (used for audio-based normalization) """ - def __init__(self, cardinal: GraphFst, decimal: GraphFst, deterministic: bool = True): + def __init__(self, cardinal: GraphFst, decimal: GraphFst, fraction: GraphFst, deterministic: bool = True): super().__init__(name="measure", kind="classify", deterministic=deterministic) optional_space = pynini.closure(pynutil.delete(NEMO_SPACE), 0, 1) + space = pynutil.delete(NEMO_SPACE) + preserve = pynutil.insert(" preserve_order: true") - def wrap_cardinal(graph): - return pynutil.insert("cardinal { integer: \"") + graph + pynutil.insert("\" }") + def wrap(name, graph): + return pynutil.insert(name + " { ") + graph + pynutil.insert(" }") - def wrap_decimal(graph): - return pynutil.insert("decimal { ") + graph + pynutil.insert(" }") + def units_field(graph): + return pynutil.insert(' units: "') + graph + pynutil.insert('"') - number = wrap_cardinal(cardinal.graph) | wrap_decimal(decimal.final_graph_wo_negative) - number_with_suffix = wrap_cardinal(cardinal.graph | attach_suffix(cardinal.graph)) | wrap_decimal( - decimal.final_graph_wo_negative - ) + integer = pynutil.insert('integer: "') + cardinal.graph + pynutil.insert('"') + minus = pynini.closure(pynutil.insert("negative: ") + pynini.cross("-", '"true" '), 0, 1) + number = wrap("cardinal", integer) | wrap("decimal", decimal.final_graph_wo_negative) + signed = wrap("cardinal", minus + integer) | wrap("decimal", decimal.final_graph) - percent = pynutil.insert("units: \"yüzde\" ") - preserve = pynutil.insert(" preserve_order: true") - percent_first = pynutil.delete("%") + optional_space + percent + number_with_suffix + preserve + # percent + percent_number = number | wrap( + "cardinal", pynutil.insert('integer: "') + attach_suffix(cardinal.graph) + pynutil.insert('"') + ) + percent = pynutil.insert('units: "yüzde" ') + percent_first = pynutil.delete("%") + optional_space + percent + percent_number + preserve percent_last = percent + number + optional_space + pynutil.delete("%") + preserve - # "5 km", "2,5 kg", "5 km'ye" -> "beş kilometreye" (the suffix is rebuilt for the full word); "-3 °C" + # units: "5 km", "2,5 kg", "5 km'ye" units = pynini.string_file(get_abs_path("data/measures/units.tsv")) units |= attach_suffix(units) - minus = pynini.closure(pynutil.insert("negative: ") + pynini.cross("-", "\"true\" "), 0, 1) - signed = ( - pynutil.insert("cardinal { ") - + minus - + pynutil.insert("integer: \"") - + cardinal.graph - + pynutil.insert("\" }") - ) | wrap_decimal(decimal.final_graph) - - def with_units(number_graph, unit_graph): - return number_graph + optional_space + pynutil.insert(" units: \"") + unit_graph + pynutil.insert("\"") - - # A unit written without a space must have two or more letters and follow a number without a dot ("5km", - # "2,5kg"): a single letter right after a number is too often part of a name ("802.11g", "5G", "M3"). - space = pynutil.delete(NEMO_SPACE) + self.units = units.optimize() # written unit -> spoken unit, also used by RangeFst + unit_graph = signed + space + units_field(units) + # Without a space only units of two or more letters after a number without a dot ("5km", "2,5kg"): a single + # letter right after a number is too often part of a name ("802.11g", "5G"). + long_units = pynini.compose(pynini.closure(NEMO_CHAR, 2) - pynini.union("m2", "m3"), units) no_dot = pynini.closure(pynini.difference(NEMO_CHAR, ".")) - long_written = pynini.closure(NEMO_CHAR, 2) - pynini.union("m²", "m³", "m2", "m3") - long_units = pynini.compose(long_written, units) - unit_graph = signed + space + pynutil.insert(" units: \"") + units + pynutil.insert("\"") - unit_graph |= pynini.compose(no_dot, signed) + pynutil.insert(" units: \"") + long_units + pynutil.insert("\"") - - # "140/90 mmHg" -> "yüz kırk bölü doksan milimetre cıva" - plain = ((NEMO_DIGIT - "0") + pynini.closure(NEMO_DIGIT)) @ cardinal.graph - unit_graph |= with_units(wrap_cardinal(plain + pynini.cross("/", " bölü ") + plain), units) - - # dimensions: "30x20x10 cm" -> "otuz çarpı yirmi çarpı on santimetre" - times = pynini.closure(pynutil.delete(NEMO_SPACE), 0, 1) + pynini.cross(pynini.union("x", "×"), " çarpı ") - times += pynini.closure(pynutil.delete(NEMO_SPACE), 0, 1) - dimensions = cardinal.graph + pynini.closure(times + cardinal.graph, 1, 2) - unit_graph |= with_units(wrap_cardinal(dimensions), units) - - # speeds read "per hour first": "120 km/sa" -> "saatte yüz yirmi kilometre", "10 m/s" -> "saniyede on metre" - after_per_word = [] # for "saatte 330 km/sa", where the text already says "saatte" - for written, per, unit in (("km/sa", "saatte", "kilometre"), ("km/saat", "saatte", "kilometre"), - ("m/s", "saniyede", "metre")): # fmt: skip + unit_graph |= pynini.compose(no_dot, signed) + units_field(long_units) + # "140/90 mmHg" + unit_graph |= wrap("fraction", fraction.division) + space + units_field(units) + + # speeds: the "per" word is read first, so it is a feature emitted before the number + speed_graphs, self.speeds_after_per_word = [], [] + for written, per, unit in SPEEDS: speed_unit = pynini.cross(written, unit) - speed_unit |= attach_suffix(speed_unit) - per_number = wrap_cardinal(pynutil.insert(per + " ") + cardinal.graph) - unit_graph |= with_units(per_number, speed_unit) - if per == "saatte": - after_per_word.append(with_units(wrap_cardinal(cardinal.graph), speed_unit)) - self.fst_speed_after_per_word = self.add_tokens(pynini.union(*after_per_word)).optimize() - - self.graph = (unit_graph | percent_first | percent_last).optimize() + speed_unit = units_field(speed_unit | attach_suffix(speed_unit)) + speed_graphs.append( + pynutil.insert(f'morphosyntactic_features: "{per}" ') + number + optional_space + speed_unit + preserve + ) + if per == "saatte": # "saatte 330 km/sa", where the text already says "saatte" (see ContextFst) + self.speeds_after_per_word.append(number + optional_space + speed_unit) + self.speeds_after_per_word = self.add_tokens(pynini.union(*self.speeds_after_per_word)).optimize() + + self.graph = (unit_graph | pynini.union(*speed_graphs) | percent_first | percent_last).optimize() self.fst = self.add_tokens(self.graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/taggers/money.py b/nemo_text_processing/text_normalization/tr/taggers/money.py index 54be80c21..b44ce3656 100644 --- a/nemo_text_processing/text_normalization/tr/taggers/money.py +++ b/nemo_text_processing/text_normalization/tr/taggers/money.py @@ -77,7 +77,10 @@ def with_optional_suffix(graph): graphs = [] currencies = load_labels(get_abs_path("data/money/currency.tsv")) - currencies += [[code.lower(), major, minor] for code, major, minor in currencies if code.lower() != code] + # lower-case codes after an amount ("100 tl"), but not "try", which is an English word + currencies += [ + [code.lower(), major, minor] for code, major, minor in currencies if code.isupper() and code != "TRY" + ] for code, major, minor in currencies: delete_code = pynutil.delete(code) for integer, sep in amounts: diff --git a/nemo_text_processing/text_normalization/tr/taggers/range.py b/nemo_text_processing/text_normalization/tr/taggers/range.py new file mode 100644 index 000000000..2c00f2091 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/taggers/range.py @@ -0,0 +1,135 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pynini +from pynini.lib import pynutil + +from nemo_text_processing.text_normalization.en.graph_utils import NEMO_CHAR, NEMO_DIGIT, NEMO_SPACE, GraphFst +from nemo_text_processing.text_normalization.en.utils import load_labels +from nemo_text_processing.text_normalization.tr.graph_utils import APOSTROPHE, SUFFIX, name_tokens +from nemo_text_processing.text_normalization.tr.utils import get_abs_path + + +def number_pairs(): + """ + Acceptors over "a-b" for numbers of up to three digits: (a < b, a >= b or a zero on either side). + + An fst cannot compare two numbers in general, but up to three digits the pairs can be enumerated by length and + by the first digit where they differ. Note that fst ** 0 is an unbounded closure in pynini, hence digits(). + """ + separator = pynini.closure(" ", 0, 1) + pynini.union("-", "–") + pynini.closure(" ", 0, 1) + + def digits(n): + return NEMO_DIGIT**n if n > 0 else pynini.accep("") + + def number(n): + return (NEMO_DIGIT - "0") + digits(n - 1) + + any_number = pynini.union(*[number(n) for n in range(1, 4)]) + less, not_less = [], [] + # a zero on either side is a score: "3-0", "2-0'lık", "0-3 yenildi", "0-0" + not_less += ["0" + separator + (any_number | "0"), any_number + separator + "0"] + for na in range(1, 4): + for nb in range(1, 4): + if na != nb: + (less if na < nb else not_less).append(number(na) + separator + number(nb)) + for n in range(1, 4): + for k in range(n): # length of the shared prefix + prefixes = [""] if k == 0 else [str(p) for p in range(10 ** (k - 1), 10**k)] + rest = digits(n - k - 1) + for prefix in prefixes: + for d1 in "0123456789": + for d2 in "0123456789": + if d1 == d2 or (k == 0 and "0" in (d1, d2)): + continue + branch = prefix + d1 + rest + separator + prefix + d2 + rest + (less if d1 < d2 else not_less).append(branch) + not_less += [str(x) + separator + str(x) for x in range(10 ** (n - 1), 10**n)] + return pynini.union(*less).optimize(), pynini.union(*not_less).optimize() + + +class RangeFst(GraphFst): + """ + Finite state transducer for ranges, scores and dimensions, read with the composed taggers and verbalizers of the + classes on both sides and emitted as name tokens, e.g. + "3-5 iş günü" -> tokens { name: "üç" } tokens { name: "ile" } tokens { name: "beş" } ... + "09.00-17.30" -> ... "dokuz ile on yedi otuz" + "1914-1918", "MÖ 3000-1200" -> ... "bin dokuz yüz on dört ile bin dokuz yüz on sekiz" + "23-25 Aralık", "12 Nisan - 30 Haziran 2024" + "36,5-37,2 °C" -> "otuz altı buçuk ile otuz yedi virgül iki santigrat derece" (the unit is read once) + "%10-20", "10-20%" -> "yüzde on ile yirmi" (the English order only for small numbers) + "11-9", "2-0'lık" -> "on bir dokuz", "iki sıfırlık" (scores) + "30x20x10 cm" -> "otuz çarpı yirmi çarpı on santimetre" + + Two numbers of up to three digits are compared: a < b is a range ("3-5"), a >= b or a zero is a score ("11-9", + "2-0"). This is a heuristic: "0-24 ay" and "5-3 kişi" are read as scores. + + Args: + units: written unit -> spoken unit (MeasureFst.units) + composed: dict of tagger @ verbalizer fsts for "cardinal", "decimal", "date", "time", "time_in_context" + deterministic: if True will provide a single transduction option, + for False multiple transduction are generated (used for audio-based normalization) + """ + + def __init__(self, units: GraphFst, composed: dict, deterministic: bool = True): + super().__init__(name="range", kind="classify", deterministic=deterministic) + + # Each concatenation copies its operands, so the sides are shared: one union of side readings is put on + # both sides of "ile" rather than listing every pair of classes. + number, decimal = composed["cardinal"], composed["decimal"] + small_written = (NEMO_DIGIT - "0") + pynini.closure(NEMO_DIGIT, 0, 2) | "0" # 0-999 + written_suffix = pynini.closure(APOSTROPHE + SUFFIX, 0, 1) + small = pynini.compose(small_written + written_suffix, number) + large = pynini.compose(pynini.closure(NEMO_DIGIT | ".", 4), number) # "1914", "10.000" + time = composed["time"] | composed["time_in_context"] + # dates written with words only: an ISO or slashed date does not appear in a range + date = pynini.compose(pynini.closure(pynini.difference(NEMO_CHAR, pynini.union("-", "/"))), composed["date"]) + optional_space = pynini.closure(pynutil.delete(NEMO_SPACE), 0, 1) + to = optional_space + pynini.cross(pynini.union("-", "–"), " ile ") + optional_space + unit = optional_space + pynutil.insert(" ") + units # read once, after the second number + optional_unit = pynini.closure(unit, 0, 1) + + # "1914-1918", "36,5-37,2 °C", "09.00-17.30", "12 Nisan - 30 Haziran 2024", "23-25 Aralık"; two small + # numbers are left to the comparison below + separator = pynini.closure(" ", 0, 1) + pynini.union("-", "–") + pynini.closure(" ", 0, 1) + unit_names = pynini.union(*[row[0] for row in load_labels(get_abs_path("data/measures/units.tsv"))]) + written_unit = pynini.closure(pynini.closure(" ", 0, 1) + unit_names + written_suffix, 0, 1) + two_small = (small_written + separator + small_written + written_suffix + written_unit).optimize() + not_two_small = pynini.difference(pynini.closure(NEMO_CHAR), two_small) + side = (time | date | decimal | large | small).optimize() + numeric = pynini.compose(not_two_small, side + to + side) + + # two small numbers: a range ("3-5 gün") or a score ("11-9", "2-0'lık") + less, not_less = number_pairs() + small_pair = small + to + small + numeric |= pynini.compose(less + written_suffix, small_pair) + + # dimensions: "30x20x10 cm" + times = optional_space + pynini.cross(pynini.union("x", "×"), " çarpı ") + optional_space + numeric |= pynini.closure(small + times, 1, 2) + small + + graph = numeric + optional_unit # the unit is read once, after the second number + score = optional_space + pynini.cross(pynini.union("-", "–"), " ") + optional_space + graph |= pynini.compose(not_less + written_suffix, small + score + small) + + # percent: "%10-20", "%10-%20", "10-20%" + percent = pynutil.delete("%") + optional_space + percent_number = small | decimal + graph |= ( + percent + pynutil.insert("yüzde ") + percent_number + to + pynini.closure(percent, 0, 1) + percent_number + ) + graph |= pynutil.insert("yüzde ") + pynini.compose(less, small_pair) + optional_space + pynutil.delete("%") + + self.graph = graph.optimize() + self.fst = name_tokens(self.graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/taggers/serial.py b/nemo_text_processing/text_normalization/tr/taggers/serial.py new file mode 100644 index 000000000..89f75b114 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/taggers/serial.py @@ -0,0 +1,56 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pynini +from pynini.lib import pynutil + +from nemo_text_processing.text_normalization.en.graph_utils import NEMO_DIGIT, GraphFst +from nemo_text_processing.text_normalization.tr.graph_utils import attach_suffix, name_tokens + + +class SerialFst(GraphFst): + """ + Finite state transducer for numbers joined by symbols that are read as words, emitted as name tokens, e.g. + "3.12.1" -> tokens { name: "üç" } tokens { name: "nokta" } tokens { name: "on" } ... (a version) + "3:2" -> tokens { name: "üçe" } tokens { name: "iki" } (a ratio) + + A version has three or more parts and is not a thousands grouping ("1.250.000") nor a date (DateFst wins on + weight). A ratio has a single digit after the colon, so it does not overlap with a time. + + Args: + cardinal: CardinalFst + deterministic: if True will provide a single transduction option, + for False multiple transduction are generated (used for audio-based normalization) + """ + + def __init__(self, cardinal: GraphFst, deterministic: bool = True): + super().__init__(name="serial", kind="classify", deterministic=deterministic) + + part = (NEMO_DIGIT - "0") + pynini.closure(NEMO_DIGIT) | "0" + spoken_part = part @ cardinal.graph + thousands = pynini.closure(NEMO_DIGIT, 1, 3) + pynini.closure("." + NEMO_DIGIT**3, 1) + version_written = pynini.difference(part + pynini.closure("." + part, 2), thousands) + version = pynini.compose( + version_written, spoken_part + pynini.closure(pynini.cross(".", " nokta ") + spoken_part, 2) + ) + + # "3:2" -> "üçe iki": the first number takes the dative, built like a written suffix "3'e" + to_dative = pynini.compose( + ((NEMO_DIGIT - "0") + pynini.closure(NEMO_DIGIT, 0, 1)) + pynini.cross(":", "'e"), + attach_suffix(cardinal.graph), + ) + ratio = to_dative + pynutil.insert(" ") + ((NEMO_DIGIT - "0") @ cardinal.graph) + + self.graph = (version | ratio).optimize() + self.fst = name_tokens(self.graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/taggers/telephone.py b/nemo_text_processing/text_normalization/tr/taggers/telephone.py index 04e1205a7..29e449d1c 100644 --- a/nemo_text_processing/text_normalization/tr/taggers/telephone.py +++ b/nemo_text_processing/text_normalization/tr/taggers/telephone.py @@ -46,12 +46,10 @@ def __init__(self, cardinal: GraphFst, deterministic: bool = True): def group(n): """A group of n digits read as a number, leading zeros one by one: "45" -> "kırk beş", "05" -> "sıfır beş".""" - readings = ((NEMO_DIGIT - "0") + NEMO_DIGIT ** (n - 1)) @ cardinal.graph - readings |= pynini.closure(zero_space, n - 1, n - 1) + zero - if n > 1: - readings |= pynini.closure(zero_space, 1, n - 1) + ( - ((NEMO_DIGIT - "0") + pynini.closure(NEMO_DIGIT)) @ cardinal.graph - ) + readings = ((NEMO_DIGIT - "0") + pynini.closure(NEMO_DIGIT)) @ cardinal.graph # no leading zero + readings |= pynini.closure(zero_space, 1) + readings # leading zeros: "05", "004" + readings |= pynini.closure(zero_space) + zero # all zeros: "0", "00" + # (the closures are bounded by composing with exactly n digits) return (NEMO_DIGIT**n @ readings).optimize() comma = pynutil.insert(", ") diff --git a/nemo_text_processing/text_normalization/tr/taggers/time.py b/nemo_text_processing/text_normalization/tr/taggers/time.py index 6c797c646..3ffb5457f 100644 --- a/nemo_text_processing/text_normalization/tr/taggers/time.py +++ b/nemo_text_processing/text_normalization/tr/taggers/time.py @@ -18,6 +18,8 @@ from nemo_text_processing.text_normalization.en.graph_utils import NEMO_DIGIT, GraphFst from nemo_text_processing.text_normalization.tr.graph_utils import attach_suffix +CASE_SUFFIXES = ["DA", "DAn", "(y)A", "DAki"] + class TimeFst(GraphFst): """ @@ -30,8 +32,8 @@ class TimeFst(GraphFst): "14.30'da" -> time { hours: "on dört" minutes: "otuzda" } "09.30" -> time { hours: "dokuz" minutes: "otuz" } - Full hours drop the minutes ("saat on"). A suffix goes on the last word read. With a dot, "14.30" is a time - only when a suffix follows or the hour has a leading zero; otherwise it is left to the decimal grammar. + Full hours drop the minutes ("saat on"). A suffix goes on the last word read. With a dot, "14.30" is a time only + with a case suffix, a leading zero or ".00", or in context (self.dot_in_context); otherwise it is a decimal. Args: cardinal: CardinalFst @@ -58,8 +60,10 @@ def __init__(self, cardinal: GraphFst, deterministic: bool = True): def field(name, graph, first=False): return pynutil.insert(("" if first else " ") + f'{name}: "') + graph + pynutil.insert('"') - def build(hour_graph, sep, with_suffix): - suffix = attach_suffix if with_suffix else (lambda g: g) + def build(hour_graph, sep, suffixes=None, with_suffix=False): + def suffix(graph): + return attach_suffix(graph, suffixes) if with_suffix else graph + no_seconds = pynini.closure(pynutil.delete(sep + "00"), 0, 1) if sep == ":" else pynini.accep("") with_minutes = ( field("hours", hour_graph, first=True) @@ -82,15 +86,17 @@ def build(hour_graph, sep, with_suffix): graphs.append(with_seconds) return pynini.union(*graphs) - colon = build(hours, ":", False) | build(hours, ":", True) - dot = build(hours, ".", True) | build(hours_leading_zero, ".", False) - # a full hour with a dot ("akşam 19.00") is a time; a decimal is not written with ".00" - dot |= pynini.compose(pynini.closure(NEMO_DIGIT, 1, 2) + ".00", build(hours, ".", False)) + self.colon = build(hours, ":").optimize() + # with a dot and no suffix, "17.30" is a time only in context ("saat 17.30", "09.00-17.30", see ContextFst + # and RangeFst); on its own it is left to the decimal grammar + self.dot_in_context = build(hours, ".").optimize() - # without a suffix or a leading zero, "17.30" is a time only in context ("saat 17.30", "09.00-17.30"); - # tokenize_and_classify uses these - self.colon = build(hours, ":", False).optimize() - self.dot_in_context = build(hours, ".", False).optimize() + colon = self.colon | build(hours, ":", with_suffix=True) + # With a dot, a case suffix makes it a time ("14.30'da", "9.00'dan"); other suffixes do not ("1.25'lik oran"). + dot = build(hours, ".", suffixes=CASE_SUFFIXES, with_suffix=True) + dot |= build(hours_leading_zero, ".") # "09.30" + # a full hour ("akşam 19.00") is a time; a decimal is not written with ".00" + dot |= pynini.compose(pynini.closure(NEMO_DIGIT, 1, 2) + ".00", self.dot_in_context) self.graph = (colon | dot).optimize() self.fst = self.add_tokens(self.graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/taggers/tokenize_and_classify.py b/nemo_text_processing/text_normalization/tr/taggers/tokenize_and_classify.py index dc57db8fb..6685980ba 100644 --- a/nemo_text_processing/text_normalization/tr/taggers/tokenize_and_classify.py +++ b/nemo_text_processing/text_normalization/tr/taggers/tokenize_and_classify.py @@ -18,8 +18,6 @@ from pynini.lib import pynutil from nemo_text_processing.text_normalization.en.graph_utils import ( - NEMO_DIGIT, - NEMO_NOT_SPACE, NEMO_WHITE_SPACE, GraphFst, delete_extra_space, @@ -27,40 +25,49 @@ generator_main, ) from nemo_text_processing.text_normalization.en.taggers.punctuation import PunctuationFst -from nemo_text_processing.text_normalization.tr.graph_utils import APOSTROPHE, TR_ALPHA, TR_LOWER, attach_suffix -from nemo_text_processing.text_normalization.tr.inflection import surface_forms from nemo_text_processing.text_normalization.tr.taggers.cardinal import CardinalFst +from nemo_text_processing.text_normalization.tr.taggers.context import ContextFst from nemo_text_processing.text_normalization.tr.taggers.date import DateFst from nemo_text_processing.text_normalization.tr.taggers.decimal import DecimalFst from nemo_text_processing.text_normalization.tr.taggers.fraction import FractionFst from nemo_text_processing.text_normalization.tr.taggers.measure import MeasureFst from nemo_text_processing.text_normalization.tr.taggers.money import MoneyFst from nemo_text_processing.text_normalization.tr.taggers.ordinal import OrdinalFst +from nemo_text_processing.text_normalization.tr.taggers.range import RangeFst +from nemo_text_processing.text_normalization.tr.taggers.serial import SerialFst from nemo_text_processing.text_normalization.tr.taggers.telephone import TelephoneFst from nemo_text_processing.text_normalization.tr.taggers.time import TimeFst from nemo_text_processing.text_normalization.tr.taggers.whitelist import WhiteListFst from nemo_text_processing.text_normalization.tr.taggers.word import WordFst -from nemo_text_processing.text_normalization.tr.utils import get_abs_path +from nemo_text_processing.text_normalization.tr.verbalizers.cardinal import CardinalFst as CardinalVerbalizer +from nemo_text_processing.text_normalization.tr.verbalizers.date import DateFst as DateVerbalizer +from nemo_text_processing.text_normalization.tr.verbalizers.decimal import DecimalFst as DecimalVerbalizer +from nemo_text_processing.text_normalization.tr.verbalizers.fraction import FractionFst as FractionVerbalizer +from nemo_text_processing.text_normalization.tr.verbalizers.measure import MeasureFst as MeasureVerbalizer +from nemo_text_processing.text_normalization.tr.verbalizers.ordinal import OrdinalFst as OrdinalVerbalizer +from nemo_text_processing.text_normalization.tr.verbalizers.time import TimeFst as TimeVerbalizer from nemo_text_processing.utils.logging import logger -# Words after which a number is a code, read digit by digit: "Doğrulama kodunuz 482913" -CODE_WORDS = [ - "kod", - "kodu", - "kodunuz", - "kodum", - "şifre", - "şifreniz", - "şifrem", - "parola", - "parolanız", - "PIN", - "pin", - "OTP", -] -# Words that join list items: "1., 2. ve 3. taksit" -CONNECTORS = ["ve", "veya", "ile", "ya", "da"] -TIME_WORDS = ["saat", "Saat", "SAAT"] +# Weights: lower wins. A word token costs 200, so a class that also covers its neighbouring word (ContextFst) still +# wins at 1.1. Among single tokens, the classes at 1.09 beat cardinal and decimal (1.1) on the same input: "05321234567" +# is a phone number, not digits; "19.00" and "14.30'da" are times, not decimals; "1.250,50 TL" is money, not a +# decimal followed by a word. Range and serial (1.1) cover several tokens, whose separate parses cost more. +WEIGHTS = { + "whitelist": 1.01, + "time": 1.09, + "date": 1.09, + "money": 1.09, + "measure": 1.09, + "telephone": 1.09, + "fraction": 1.1, + "range": 1.1, + "serial": 1.1, + "context": 1.1, + "decimal": 1.1, + "ordinal": 1.1, + "cardinal": 1.1, + "word": 200, +} class ClassifyFst(GraphFst): @@ -69,11 +76,8 @@ class ClassifyFst(GraphFst): For deployment, this grammar will be compiled and exported to OpenFst Finite State Archive (FAR) File. More details to deployment at NeMo/tools/text_processing_deployment. - Besides the single-token classes, a few patterns look at the neighbouring token: - "5. sırada", "1., 2. ve 3. taksit" -> ordinals (a number with a dot before a noun) - "saat 17.30" -> time (otherwise "17.30" is a decimal) - "09.00-17.30", "2025-2026", "%10-20" -> ranges read with "ile" - "kodunuz 482913" -> the code read digit by digit + Only deterministic normalization is implemented: with deterministic=False the grammars give the same single + reading. Args: input_case: accepting either "lower_cased" or "cased" input. @@ -104,201 +108,80 @@ def __init__( if not overwrite_cache and far_file and os.path.exists(far_file): self.fst = pynini.Far(far_file, mode="r")["tokenize_and_classify"] logger.info(f"ClassifyFst.fst was restored from {far_file}.") - else: - logger.info("Creating ClassifyFst grammars. This might take some time...") - - self.cardinal = CardinalFst(deterministic=deterministic) - self.ordinal = OrdinalFst(cardinal=self.cardinal, deterministic=deterministic) - self.decimal = DecimalFst(cardinal=self.cardinal, deterministic=deterministic) - self.measure = MeasureFst(cardinal=self.cardinal, decimal=self.decimal, deterministic=deterministic) - self.date = DateFst(cardinal=self.cardinal, deterministic=deterministic) - self.time = TimeFst(cardinal=self.cardinal, deterministic=deterministic) - self.money = MoneyFst(cardinal=self.cardinal, deterministic=deterministic) - self.telephone = TelephoneFst(cardinal=self.cardinal, deterministic=deterministic) - self.fraction = FractionFst(cardinal=self.cardinal, deterministic=deterministic) - self.whitelist = WhiteListFst(input_case=input_case, deterministic=deterministic, input_file=whitelist) - self.word = WordFst(deterministic=deterministic) - punct_graph = PunctuationFst(deterministic=deterministic).fst - - classify = ( - pynutil.add_weight(self.whitelist.fst, 1.01) - | pynutil.add_weight(self.time.fst, 1.09) - | pynutil.add_weight(self.date.fst, 1.09) - | pynutil.add_weight(self.money.fst, 1.09) - | pynutil.add_weight(self.measure.fst, 1.09) - | pynutil.add_weight(self.telephone.fst, 1.09) - | pynutil.add_weight(self.fraction.fst, 1.1) - | pynutil.add_weight(self.decimal.fst, 1.1) - | pynutil.add_weight(self.ordinal.fst, 1.1) - | pynutil.add_weight(self.cardinal.fst, 1.1) - | pynutil.add_weight(self.word.fst, 200) - ) - punct = pynutil.insert("tokens { ") + pynutil.add_weight(punct_graph, weight=2.1) + pynutil.insert(" }") - punct = pynini.closure( - pynini.compose(pynini.closure(NEMO_WHITE_SPACE, 1), delete_extra_space) - | (pynutil.insert(" ") + punct), - 1, - ) - token = pynutil.insert("tokens { ") + classify + pynutil.insert(" }") - token |= self._context_patterns(input_case) - - token_plus_punct = ( - pynini.closure(punct + pynutil.insert(" ")) + token + pynini.closure(pynutil.insert(" ") + punct) - ) - - graph = token_plus_punct + pynini.closure( - ( - pynini.compose(pynini.closure(NEMO_WHITE_SPACE, 1), delete_extra_space) - | (pynutil.insert(" ") + punct + pynutil.insert(" ")) - ) - + token_plus_punct - ) - - graph = delete_space + graph + delete_space - graph |= punct - - self.fst = graph.optimize() - - if far_file: - generator_main(far_file, {"tokenize_and_classify": self.fst}) - logger.info(f"ClassifyFst grammars are saved to {far_file}.") - - def _context_patterns(self, input_case: str) -> 'pynini.FstLike': - """Patterns of two or more tokens; each emits the tokens it covers.""" - - def tok(graph, weight): - return pynutil.insert("tokens { ") + pynutil.add_weight(graph, weight) + pynutil.insert(" }") - - def words(word_list): - return tok(pynini.compose(pynini.union(*word_list), self.word.fst), 200) - - space = pynutil.delete(pynini.closure(NEMO_WHITE_SPACE, 1)) + pynutil.insert(" ") - dash = ( - pynini.closure(pynutil.delete(" "), 0, 1) - + pynutil.delete(pynini.union("-", "–")) - + pynini.closure(pynutil.delete(" "), 0, 1) - ) - ile = pynutil.insert(" tokens { name: \"ile\" } ") - - # ordinals: a number with a dot before a noun; in lower-cased text, where a sentence end cannot be told - # from a following word, only before known nouns ("taksit", "sıra", "kat" ...) - nouns = [line.strip() for line in open(get_abs_path("data/ordinals/ordinal_nouns.tsv"), encoding="utf-8")] - noun_forms = pynini.union(*nouns, *[n[0].upper() + n[1:] for n in nouns]) - noun_forms += pynini.closure(pynini.union(*surface_forms().keys()), 0, 1) - noun = pynini.compose(noun_forms + pynini.closure(pynini.union(",", ".", "?", "!"), 0, 1), self.word.fst) - following = noun - if input_case != "lower_cased": - following |= pynini.compose(TR_LOWER + pynini.closure(NEMO_NOT_SPACE), self.word.fst) - ordinal_dot = tok(self.ordinal.fst_dot, 1.1) - comma = pynini.cross(",", " tokens { name: \",\" }") - item_separator = pynini.closure(comma, 0, 1) + space + pynini.closure(words(CONNECTORS) + space, 0, 1) - ordinals = ordinal_dot + pynini.closure(item_separator + ordinal_dot) + space + tok(following, 200) - # "1.sırada": written without the space - # (cheaper than the word alone, which would otherwise swallow "1.sırada" as one token) - glued_word = pynini.compose(TR_LOWER + pynini.closure(NEMO_NOT_SPACE), self.word.fst) - ordinals |= ordinal_dot + pynutil.insert(" ") + tok(glued_word, 1.0) - # "XX. yüzyıl", "II. Mehmet" - any_word = pynini.compose(TR_ALPHA + pynini.closure(NEMO_NOT_SPACE), self.word.fst) - ordinals |= tok(self.ordinal.fst_roman_dot, 1.1) + space + tok(any_word, 200) - - # "saat 17.30" - time_in_context = self.time.add_tokens(self.time.dot_in_context | self.time.colon) - clock = words(TIME_WORDS) + space + tok(time_in_context, 1.0) - - # ranges - time_any = tok(self.time.fst, 1.09) | tok(time_in_context, 1.09) - # four-digit numbers on both sides: years ("1914-1918"), also before Christ ("MÖ 3000-1200") - year = self.cardinal.add_tokens( - pynutil.insert("integer: \"") - + (((NEMO_DIGIT - "0") + NEMO_DIGIT**3) @ self.cardinal.graph) - + pynutil.insert("\"") + return + + logger.info("Creating ClassifyFst grammars. This might take some time...") + d = deterministic + cardinal = CardinalFst(deterministic=d) + ordinal = OrdinalFst(cardinal=cardinal, deterministic=d) + decimal = DecimalFst(cardinal=cardinal, deterministic=d) + fraction = FractionFst(cardinal=cardinal, deterministic=d) + measure = MeasureFst(cardinal=cardinal, decimal=decimal, fraction=fraction, deterministic=d) + date = DateFst(cardinal=cardinal, deterministic=d) + time = TimeFst(cardinal=cardinal, deterministic=d) + money = MoneyFst(cardinal=cardinal, deterministic=d) + telephone = TelephoneFst(cardinal=cardinal, deterministic=d) + whitelist_graph = WhiteListFst(input_case=input_case, deterministic=d, input_file=whitelist) + word = WordFst(deterministic=d) + + # the classes that read their neighbours use the other classes' readings (tagger @ verbalizer) + cardinal_v, decimal_v = CardinalVerbalizer(deterministic=d), DecimalVerbalizer(deterministic=d) + fraction_v, time_v = FractionVerbalizer(deterministic=d), TimeVerbalizer(deterministic=d) + measure_v = MeasureVerbalizer(cardinal=cardinal_v, decimal=decimal_v, fraction=fraction_v, deterministic=d) + ordinal_v = OrdinalVerbalizer(deterministic=d) + composed = { + "cardinal": cardinal.fst @ cardinal_v.fst, + "decimal": decimal.fst @ decimal_v.fst, + "date": date.fst @ DateVerbalizer(deterministic=d).fst, + "time": time.fst @ time_v.fst, + "time_in_context": time.add_tokens(time.dot_in_context | time.colon) @ time_v.fst, + "ordinal_dot": ordinal.fst_dot @ ordinal_v.fst, + "ordinal_roman": ordinal.fst_roman_dot @ ordinal_v.fst, + "speed_after_per_word": measure.speeds_after_per_word @ measure_v.fst, + } + range_graph = RangeFst(measure.units, composed, deterministic=d) + serial = SerialFst(cardinal, deterministic=d) + context = ContextFst(composed, cardinal, input_case, deterministic=d) + + classes = { + "whitelist": whitelist_graph.fst, + "time": time.fst, + "date": date.fst, + "money": money.fst, + "measure": measure.fst, + "telephone": telephone.fst, + "fraction": fraction.fst, + "range": range_graph.fst, + "serial": serial.fst, + "context": context.fst, + "decimal": decimal.fst, + "ordinal": ordinal.fst, + "cardinal": cardinal.fst, + "word": word.fst, + } + classify = pynini.union(*[pynutil.add_weight(fst, WEIGHTS[name]) for name, fst in classes.items()]) + + punct = pynutil.insert("tokens { ") + pynutil.add_weight(PunctuationFst(deterministic=d).fst, 2.1) + punct += pynutil.insert(" }") + punct = pynini.closure( + pynini.compose(pynini.closure(NEMO_WHITE_SPACE, 1), delete_extra_space) | (pynutil.insert(" ") + punct), + 1, ) - cardinal, decimal, measure = ( - tok(self.cardinal.fst, 1.1), - tok(self.decimal.fst, 1.1), - tok(self.measure.fst, 1.09), + token = pynutil.insert("tokens { ") + classify + pynutil.insert(" }") + token_plus_punct = ( + pynini.closure(punct + pynutil.insert(" ")) + token + pynini.closure(pynutil.insert(" ") + punct) ) - ranges = ( - time_any + dash + ile + time_any - | tok(year, 1.1) + dash + ile + tok(year, 1.1) - | measure + dash + ile + (measure | cardinal | decimal) - | (cardinal | decimal) + dash + ile + measure - | decimal + dash + ile + (decimal | cardinal) - | cardinal + dash + ile + decimal - | cardinal + dash + ile + tok(self.date.fst, 1.09) # "23-25 Aralık" - | tok(self.date.fst, 1.09) + dash + ile + tok(self.date.fst, 1.09) # "12 Nisan - 30 Haziran 2024" - ) - # "saatte 330 km/sa": the text already says "saatte" - ranges |= words(["saatte", "Saatte"]) + space + tok(self.measure.fst_speed_after_per_word, 1.0) - # small numbers: "3-5 iş günü" is a range (a < b), "11-9" and "6-6'ya" are scores (a >= b) - written_suffix = pynini.closure(APOSTROPHE + pynini.closure(TR_ALPHA, 1), 0, 1) - less, not_less = number_pairs() - ranges |= pynini.compose(less + written_suffix, cardinal + dash + ile + cardinal) - ranges |= pynini.compose(not_less + written_suffix, cardinal + dash + pynutil.insert(" ") + cardinal) - - # ratios: "3:2" -> "üçe iki" - to_dative = pynini.compose( - ((NEMO_DIGIT - "0") + pynini.closure(NEMO_DIGIT, 0, 1)) + pynini.cross(":", "'e"), - attach_suffix(self.cardinal.graph), - ) - ratio = to_dative + pynutil.insert(" ") + ((NEMO_DIGIT - "0") @ self.cardinal.graph) - ratios = tok(self.cardinal.add_tokens(pynutil.insert("integer: \"") + ratio + pynutil.insert("\"")), 1.1) - - # versions: "3.12.1" -> "üç nokta on iki nokta bir" (not dates, not thousand groups) - part = (NEMO_DIGIT - "0") + pynini.closure(NEMO_DIGIT) | "0" - thousands = pynini.closure(NEMO_DIGIT, 1, 3) + pynini.closure("." + NEMO_DIGIT**3, 1) - version_written = pynini.difference(part + pynini.closure("." + part, 2), thousands) - version = pynini.compose( - version_written, - (part @ self.cardinal.graph) - + pynini.closure(pynini.cross(".", " nokta ") + (part @ self.cardinal.graph), 2), + graph = token_plus_punct + pynini.closure( + ( + pynini.compose(pynini.closure(NEMO_WHITE_SPACE, 1), delete_extra_space) + | (pynutil.insert(" ") + punct + pynutil.insert(" ")) + ) + + token_plus_punct ) - versions = tok(self.cardinal.add_tokens(pynutil.insert("integer: \"") + version + pynutil.insert("\"")), 1.1) - - # codes - code_digits = (NEMO_DIGIT**4 + pynini.closure(NEMO_DIGIT, 0, 4)) @ self.cardinal.digits - code_digits |= attach_suffix(code_digits) # "kodunuz 218456'dır" -> "... beş altıdır" - code = self.cardinal.add_tokens(pynutil.insert("integer: \"") + code_digits + pynutil.insert("\"")) - code_words = CODE_WORDS + [w[0].upper() + w[1:] for w in CODE_WORDS if w[0].islower()] - codes = words(code_words) + space + tok(code, 1.0) - - return (ordinals | clock | ranges | ratios | versions | codes).optimize() - - -def number_pairs(): - """ - Acceptors over "a-b" for numbers of up to three digits: (a < b, a >= b). An fst cannot compare two numbers in - general, but up to three digits the pairs can be enumerated by length and first differing digit. - """ - digit = [str(d) for d in range(10)] - separator = pynini.closure(" ", 0, 1) + pynini.union("-", "–") + pynini.closure(" ", 0, 1) - - def digits(n): # exactly n digits; note that fst ** 0 is an unbounded closure in pynini - return NEMO_DIGIT**n if n > 0 else pynini.accep("") - - def number(n): - return (NEMO_DIGIT - "0") + digits(n - 1) + graph = delete_space + graph + delete_space + graph |= punct + self.fst = graph.optimize() - less, more, equal = [], [], [] - # zero on either side is a score: "3-0", "2-0'lık", "0-3 yenildi", "0-0" - more.append(pynini.union("0") + separator + pynini.union(*[number(n) for n in range(1, 4)], "0")) - more.append(pynini.union(*[number(n) for n in range(1, 4)]) + separator + "0") - for na in range(1, 4): - for nb in range(1, 4): - if na < nb: - less.append(number(na) + separator + number(nb)) - elif na > nb: - more.append(number(na) + separator + number(nb)) - for n in range(1, 4): - for k in range(n): # length of the shared prefix - prefixes = [""] if k == 0 else [str(p) for p in range(10 ** (k - 1), 10**k)] - rest = digits(n - k - 1) - for p in prefixes: - for d1 in digit: - for d2 in digit: - if k == 0 and "0" in (d1, d2) or d1 == d2: - continue - branch = p + d1 + rest + separator + p + d2 + rest - (less if d1 < d2 else more).append(branch) - equal += [str(x) + separator + str(x) for x in range(10 ** (n - 1), 10**n)] - return pynini.union(*less).optimize(), pynini.union(*more, *equal).optimize() + if far_file: + generator_main(far_file, {"tokenize_and_classify": self.fst}) + logger.info(f"ClassifyFst grammars are saved to {far_file}.") diff --git a/nemo_text_processing/text_normalization/tr/taggers/whitelist.py b/nemo_text_processing/text_normalization/tr/taggers/whitelist.py index 7325d526c..c7f988d4b 100644 --- a/nemo_text_processing/text_normalization/tr/taggers/whitelist.py +++ b/nemo_text_processing/text_normalization/tr/taggers/whitelist.py @@ -13,11 +13,10 @@ # limitations under the License. import pynini -from pynini.lib import pynutil -from nemo_text_processing.text_normalization.en.graph_utils import NEMO_SIGMA, GraphFst +from nemo_text_processing.text_normalization.en.graph_utils import GraphFst from nemo_text_processing.text_normalization.en.utils import load_labels -from nemo_text_processing.text_normalization.tr.graph_utils import attach_suffix +from nemo_text_processing.text_normalization.tr.graph_utils import attach_suffix, name_tokens from nemo_text_processing.text_normalization.tr.utils import get_abs_path @@ -54,16 +53,15 @@ def _get_whitelist_graph(input_case, file): if input_file: graph = _get_whitelist_graph(input_case, input_file) - # a currency code on its own, after a scale word: "3,7 milyar TL'ye" -> "... milyar liraya" + # a currency code on its own, after a scale word: "3,7 milyar TL'ye" -> "... milyar liraya". Upper case only + # and not "TRY", which would catch the English word in mixed text. codes = [ - (code, major) for code, major, _ in load_labels(get_abs_path("data/money/currency.tsv")) if code.isalpha() + (code, major) + for code, major, _ in load_labels(get_abs_path("data/money/currency.tsv")) + if code.isalpha() and code != "TRY" ] - codes += [(code.lower(), major) for code, major in codes] currency = pynini.string_map(codes) graph |= currency | attach_suffix(currency) - # A multi-word expansion becomes one name token per word ("vb." -> "ve", "benzeri"). Sparrowhawk prints a name - # token as it is, so a non-breaking space (convert_space) would stay in its output. - split_words = pynini.cdrewrite(pynini.cross(" ", '" } tokens { name: "'), "", "", NEMO_SIGMA) - self.graph = (graph @ split_words).optimize() - self.fst = (pynutil.insert('name: "') + self.graph + pynutil.insert('"')).optimize() + self.graph = graph.optimize() + self.fst = name_tokens(self.graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/verbalizers/fraction.py b/nemo_text_processing/text_normalization/tr/verbalizers/fraction.py index fa9038bbe..019e351ec 100644 --- a/nemo_text_processing/text_normalization/tr/verbalizers/fraction.py +++ b/nemo_text_processing/text_normalization/tr/verbalizers/fraction.py @@ -27,7 +27,10 @@ class FractionFst(GraphFst): """ Finite state transducer for verbalizing fractions, e.g. fraction { integer_part: "iki" denominator: "ikide" numerator: "bir" preserve_order: true } -> iki tam ikide bir - fraction { numerator: "yedi" denominator: "bölü üç yüz altmış beş" } -> yedi bölü üç yüz altmış beş + fraction { numerator: "yedi" denominator: "üç yüz altmış beş" morphosyntactic_features: "bölü" } + -> yedi bölü üç yüz altmış beş + + A division carries the "bölü" feature; a named fraction is tagged denominator first with preserve_order. Args: deterministic: if True will provide a single transduction option, @@ -47,7 +50,9 @@ def field(name): ) integer = pynini.closure(field("integer_part") + delete_space + pynutil.insert(" tam "), 0, 1) - denominator_first = field("denominator") + delete_space + pynutil.insert(" ") + field("numerator") - numerator_first = field("numerator") + delete_space + pynutil.insert(" ") + field("denominator") - graph = integer + (denominator_first | numerator_first) + delete_preserve_order - self.fst = self.delete_tokens(graph).optimize() + named = integer + field("denominator") + delete_space + pynutil.insert(" ") + field("numerator") + named += delete_space + delete_preserve_order + division = field("numerator") + delete_space + pynutil.insert(" bölü ") + field("denominator") + division += delete_space + pynutil.delete('morphosyntactic_features: "bölü"') + self.numbers = (named | division).optimize() + self.fst = self.delete_tokens(self.numbers).optimize() diff --git a/nemo_text_processing/text_normalization/tr/verbalizers/measure.py b/nemo_text_processing/text_normalization/tr/verbalizers/measure.py index 40481f335..94ad48570 100644 --- a/nemo_text_processing/text_normalization/tr/verbalizers/measure.py +++ b/nemo_text_processing/text_normalization/tr/verbalizers/measure.py @@ -26,21 +26,39 @@ class MeasureFst(GraphFst): """ Finite state transducer for verbalizing measures, e.g. + measure { cardinal { integer: "beş" } units: "kilometre" } -> beş kilometre measure { units: "yüzde" cardinal { integer: "on sekiz" } preserve_order: true } -> yüzde on sekiz + measure { morphosyntactic_features: "saatte" cardinal { integer: "yüz yirmi" } units: "kilometre" + preserve_order: true } -> saatte yüz yirmi kilometre + + The unit first (percent) is tagged with preserve_order; the "per" word first (speeds) carries its feature. Args: cardinal: CardinalFst verbalizer decimal: DecimalFst verbalizer + fraction: FractionFst verbalizer deterministic: if True will provide a single transduction option, for False multiple transduction are generated (used for audio-based normalization) """ - def __init__(self, cardinal: GraphFst, decimal: GraphFst, deterministic: bool = True): + def __init__(self, cardinal: GraphFst, decimal: GraphFst, fraction: GraphFst, deterministic: bool = True): super().__init__(name="measure", kind="verbalize", deterministic=deterministic) - unit = pynutil.delete("units:") + delete_space + pynutil.delete('"') + pynini.closure(NEMO_NOT_QUOTE, 1) - unit += pynutil.delete('"') - number = cardinal.fst | decimal.fst + def field(name): + return ( + pynutil.delete(f"{name}:") + + delete_space + + pynutil.delete('"') + + pynini.closure(NEMO_NOT_QUOTE, 1) + + pynutil.delete('"') + ) + space = delete_space + pynutil.insert(" ") - graph = (number + space + unit | unit + space + number) + delete_preserve_order + # preserve_order is optional here: Sparrowhawk keeps the order but does not print the field + preserved = delete_space + delete_preserve_order + number = cardinal.fst | decimal.fst | fraction.fst + unit = field("units") + graph = number + space + unit + graph |= unit + space + number + preserved + graph |= field("morphosyntactic_features") + space + number + space + unit + preserved self.fst = self.delete_tokens(graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/verbalizers/verbalize.py b/nemo_text_processing/text_normalization/tr/verbalizers/verbalize.py index dc6a2cf8c..e1375c3f7 100644 --- a/nemo_text_processing/text_normalization/tr/verbalizers/verbalize.py +++ b/nemo_text_processing/text_normalization/tr/verbalizers/verbalize.py @@ -40,16 +40,18 @@ def __init__(self, deterministic: bool = True): super().__init__(name="verbalize", kind="verbalize", deterministic=deterministic) cardinal = CardinalFst(deterministic=deterministic) decimal = DecimalFst(deterministic=deterministic) + fraction = FractionFst(deterministic=deterministic) + # range, serial, context and whitelist tokens are name tokens, verbalized by WordFst in VerbalizeFinalFst graph = ( cardinal.fst | decimal.fst + | fraction.fst | OrdinalFst(deterministic=deterministic).fst - | MeasureFst(cardinal=cardinal, decimal=decimal, deterministic=deterministic).fst + | MeasureFst(cardinal=cardinal, decimal=decimal, fraction=fraction, deterministic=deterministic).fst | MoneyFst(deterministic=deterministic).fst | DateFst(deterministic=deterministic).fst | TimeFst(deterministic=deterministic).fst | TelephoneFst(deterministic=deterministic).fst - | FractionFst(deterministic=deterministic).fst | WhiteListFst(deterministic=deterministic).fst ) self.fst = graph diff --git a/nemo_text_processing/text_normalization/tr/verbalizers/verbalize_final.py b/nemo_text_processing/text_normalization/tr/verbalizers/verbalize_final.py index eff5234b1..4d72a1e0c 100644 --- a/nemo_text_processing/text_normalization/tr/verbalizers/verbalize_final.py +++ b/nemo_text_processing/text_normalization/tr/verbalizers/verbalize_final.py @@ -18,6 +18,7 @@ from pynini.lib import pynutil from nemo_text_processing.text_normalization.en.graph_utils import ( + NEMO_NOT_QUOTE, GraphFst, delete_extra_space, delete_space, @@ -57,7 +58,16 @@ def __init__( else: verbalize = VerbalizeFst(deterministic=deterministic).fst word = WordFst(deterministic=deterministic).fst - types = verbalize | word + # names of several words with plain spaces (see graph_utils.name_tokens); without quotes inside, so + # they cannot run past the end of the token + spaced_name = ( + pynutil.delete("name:") + + delete_space + + pynutil.delete('"') + + pynini.closure(NEMO_NOT_QUOTE, 1) + + pynutil.delete('"') + ) + types = verbalize | word | spaced_name graph = ( pynutil.delete("tokens") + delete_space diff --git a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_date.txt b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_date.txt index e05f31396..7a8928d54 100644 --- a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_date.txt +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_date.txt @@ -5,7 +5,6 @@ 14.03.88~on dört mart seksen sekiz 01.01.2027'de~bir ocak iki bin yirmi yedide 2026-03-15~on beş mart iki bin yirmi altı -2026-03-15'te~on beş mart iki bin yirmi altıda 14 Mart 2026~on dört mart iki bin yirmi altı 15 Kasım'da~on beş kasımda 31 Aralık'a~otuz bir aralığa diff --git a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_sentences.txt b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_sentences.txt index ce5f47883..dc91ee618 100644 --- a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_sentences.txt +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_sentences.txt @@ -41,3 +41,7 @@ Porsiyonda 320 kcal var.~Porsiyonda üç yüz yirmi kilokalori var. Paket 500 g geldi.~Paket beş yüz gram geldi. Paket 2,5kg geldi.~Paket iki buçuk kilogram geldi. Şirket 5G altyapısına yatırım yaptı.~Şirket 5G altyapısına yatırım yaptı. +Please try again later.~Please try again later. +Faiz 1.25'lik oranla hesaplandı.~Faiz bir virgül yirmi beşlik oranla hesaplandı. +Oran 7/365 olarak hesaplandı.~Oran yedi bölü üç yüz altmış beş olarak hesaplandı. +Kampanya 10-20% indirim sunuyor.~Kampanya yüzde on ile yirmi indirim sunuyor. diff --git a/tests/nemo_text_processing/tr/test_inflection.py b/tests/nemo_text_processing/tr/test_inflection.py new file mode 100644 index 000000000..e7c677b4c --- /dev/null +++ b/tests/nemo_text_processing/tr/test_inflection.py @@ -0,0 +1,68 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pytest + +from nemo_text_processing.text_normalization.tr.inflection import inflect_word, surface_forms + +# (word, suffix in archiphoneme notation, expected) +INFLECTIONS = [ + ("lira", "(y)A", "liraya"), # buffer y after a vowel + ("lira", "DIr", "liradır"), + ("lira", "(s)I", "lirası"), + ("lira", "lIk(s)I", "liralığı"), # the k of -lIk softens before a vowel + ("kuruş", "DAn", "kuruştan"), # D -> t after a voiceless consonant + ("dört", "(y)I", "dördü"), # dört softens + ("dört", "DA", "dörtte"), # but not before a consonant + ("dört", "(ş)Ar", "dörder"), + ("iki", "(ş)Ar", "ikişer"), + ("bir", "(s)I", "biri"), + ("altı", "DA", "altıda"), + ("on", "(n)In", "onun"), + ("kırk", "(y)A", "kırka"), # a monosyllable does not soften + ("aralık", "(y)A", "aralığa"), + ("ocak", "DA", "ocakta"), + ("buçuk", "lIk", "buçukluk"), + ("buçuk", "(y)A", "buçuğa"), + ("doksan", "lArDA", "doksanlarda"), + ("sterlin", "(y)A", "sterline"), # front harmony + ("saat", "(y)I", "saati"), # front suffix after a back vowel +] + + +@pytest.mark.run_only_on('CPU') +@pytest.mark.unit +@pytest.mark.parametrize("word,suffix,expected", INFLECTIONS) +def test_inflect_word(word, suffix, expected): + assert inflect_word(word, suffix) == expected + + +@pytest.mark.run_only_on('CPU') +@pytest.mark.unit +@pytest.mark.parametrize( + "written,suffix", + [ + ("ye", "(y)A"), + ("e", "(y)A"), + ("de", "DA"), + ("te", "DA"), + ("TE", "DA"), + ("lık", "lIk"), + ("si", "(s)I"), + ("ü", "(y)I"), + ], +) +def test_surface_forms(written, suffix): + # how a written suffix is read, whatever word it was written for ("4'de" is read as the locative) + assert surface_forms()[written] == suffix From 1b972390344c84882fcdb5a7caa83fbd573f289b Mon Sep 17 00:00:00 2001 From: Doruk Dumlu Date: Sat, 28 Nov 2026 23:27:00 -0500 Subject: [PATCH 6/6] Turkish TN: quotes, saat ranges, code chains, fixed-phrase ordinals - Double quotes are left to PunctuationFst: a quote inside a name token breaks Sparrowhawk parsing; quoted cases are pytest-only (as in en). - ContextFst: saat with a time range, codes after a colon and in dash groups, capitalised fixed-phrase nouns (1. Dunya Savasi, 1. Lig). - SerialFst: three or more dash-separated groups read as a code. - Lower-case unit variants; stale docstrings fixed. Signed-off-by: Doruk Dumlu --- .../tr/data/measures/units.tsv | 17 ++++++ .../tr/data/ordinals/ordinal_nouns.tsv | 6 ++ .../text_normalization/tr/taggers/context.py | 55 +++++++++++++------ .../text_normalization/tr/taggers/ordinal.py | 4 +- .../text_normalization/tr/taggers/range.py | 8 +-- .../text_normalization/tr/taggers/serial.py | 19 +++++-- .../tr/taggers/whitelist.py | 2 +- .../text_normalization/tr/taggers/word.py | 4 +- .../test_cases_lower_cased.txt | 2 + .../test_cases_punctuation.txt | 3 + .../test_cases_sentences.txt | 7 +++ .../tr/test_punctuation.py | 31 +++++++++++ 12 files changed, 127 insertions(+), 31 deletions(-) create mode 100644 tests/nemo_text_processing/tr/data_text_normalization/test_cases_punctuation.txt create mode 100644 tests/nemo_text_processing/tr/test_punctuation.py diff --git a/nemo_text_processing/text_normalization/tr/data/measures/units.tsv b/nemo_text_processing/text_normalization/tr/data/measures/units.tsv index 8bbd5269c..77208c2df 100644 --- a/nemo_text_processing/text_normalization/tr/data/measures/units.tsv +++ b/nemo_text_processing/text_normalization/tr/data/measures/units.tsv @@ -48,3 +48,20 @@ g/dl gram bölü desilitre IU/ml ünite bölü mililitre nm nanometre MP megapiksel +°c santigrat derece +kwh kilovatsaat +kw kilovat +mah miliamper saat +gb gigabayt +mb megabayt +kb kilobayt +tb terabayt +ghz gigahertz +mhz megahertz +hz hertz +gbps gigabit +mbps megabit +iu ünite +mmhg milimetre cıva +iu/ml ünite bölü mililitre +mp megapiksel diff --git a/nemo_text_processing/text_normalization/tr/data/ordinals/ordinal_nouns.tsv b/nemo_text_processing/text_normalization/tr/data/ordinals/ordinal_nouns.tsv index 747993013..0211ffd45 100644 --- a/nemo_text_processing/text_normalization/tr/data/ordinals/ordinal_nouns.tsv +++ b/nemo_text_processing/text_normalization/tr/data/ordinals/ordinal_nouns.tsv @@ -37,3 +37,9 @@ hat ödeme fatura vade +dünya +lig +ordu +kolordu +tümen +grup diff --git a/nemo_text_processing/text_normalization/tr/taggers/context.py b/nemo_text_processing/text_normalization/tr/taggers/context.py index 2d821b1f2..fe4f8e03e 100644 --- a/nemo_text_processing/text_normalization/tr/taggers/context.py +++ b/nemo_text_processing/text_normalization/tr/taggers/context.py @@ -17,7 +17,14 @@ from nemo_text_processing.text_normalization.en.graph_utils import NEMO_DIGIT, NEMO_NOT_SPACE, NEMO_SPACE, GraphFst from nemo_text_processing.text_normalization.en.utils import load_labels -from nemo_text_processing.text_normalization.tr.graph_utils import TR_ALPHA, TR_LOWER, attach_suffix, name_tokens +from nemo_text_processing.text_normalization.tr.graph_utils import ( + APOSTROPHE, + SUFFIX, + TR_ALPHA, + TR_LOWER, + attach_suffix, + name_tokens, +) from nemo_text_processing.text_normalization.tr.inflection import surface_forms from nemo_text_processing.text_normalization.tr.utils import get_abs_path @@ -46,19 +53,21 @@ def capitalized(words): class ContextFst(GraphFst): """ - Finite state transducer for numbers whose reading depends on the word next to them, emitted (with that word) - as name tokens, e.g. - "5. sırada" -> tokens { name: "beşinci" } tokens { name: "sırada" } + Finite state transducer for numbers whose reading depends on the word next to them, emitted together with that + word as a name token, e.g. + "5. sırada" -> tokens { name: "beşinci sırada" } "1., 2. ve 3. taksit" -> "birinci , ikinci ve üçüncü taksit" - "1.sırada" -> "birinci sırada" + "1.sırada", "1. Dünya Savaşı" -> "birinci sırada", "birinci Dünya Savaşı" "XX. yüzyıl", "II. Mehmet" -> "yirminci yüzyıl", "ikinci Mehmet" - "saat 17.30" -> "saat on yedi otuz" (without "saat", "17.30" is a decimal) + "saat 17.30", "saat 09.00-17.30" -> "saat on yedi otuz", "saat dokuz ile on yedi otuz" (without "saat", + "17.30" is a decimal) "saatte 330 km/sa" -> "saatte üç yüz otuz kilometre" (the text already says "saatte") - "kodunuz 482913" -> "kodunuz dört sekiz iki dokuz bir üç" + "kodunuz 482913", "şifreniz: 1234-5678" -> "kodunuz dört sekiz iki dokuz bir üç", "şifreniz: bir iki üç dört, + beş altı yedi sekiz" - A number with a dot is an ordinal only before a word; at the end of a sentence ("Sırada 5.") it stays a number - and a full stop. In lower-cased text a sentence end cannot be told from a following word, so only known nouns - ("taksit", "sıra", "kat" ..., data/ordinals/ordinal_nouns.tsv) are accepted there. + A number with a dot is an ordinal only before a lower-case word or a known noun (data/ordinals/ordinal_nouns.tsv, + also capitalised: "Dünya", "Lig", "Kat"); at the end of a sentence ("Sırada 5.") it stays a number and a full + stop. In lower-cased text a sentence end cannot be told from a following word, so only the known nouns count. Args: composed: dict of tagger @ verbalizer fsts for "ordinal_dot", "ordinal_roman", "time_in_context", @@ -74,16 +83,19 @@ def __init__(self, composed: dict, cardinal: GraphFst, input_case: str, determin space = pynini.cross(pynini.closure(NEMO_SPACE, 1), " ") punctuation = pynini.closure(pynini.union(",", ".", "?", "!", ";", ":"), 0, 1) + # a name token's value cannot hold a double quote: a quoted word ('1. oldum"') stays outside the token + not_quote = pynini.difference(NEMO_NOT_SPACE, '"') def word(first_letters): - return first_letters + pynini.closure(NEMO_NOT_SPACE) + return first_letters + pynini.closure(not_quote) def word_list(words): return pynini.union(*words) - # ordinals + # ordinals; the noun list also has capitalised nouns of fixed phrases ("1. Dünya Savaşı", "1. Lig'de") nouns = [row[0] for row in load_labels(get_abs_path("data/ordinals/ordinal_nouns.tsv"))] - noun = word_list(capitalized(nouns)) + pynini.closure(word_list(list(surface_forms())), 0, 1) + punctuation + suffix = pynini.closure(word_list(list(surface_forms())) | APOSTROPHE + SUFFIX, 0, 1) + noun = word_list(capitalized(nouns)) + suffix + punctuation following = noun if input_case == "lower_cased" else noun | word(TR_LOWER) ordinal_dot = composed["ordinal_dot"] item_separator = ( @@ -93,13 +105,20 @@ def word_list(words): ordinals |= ordinal_dot + pynutil.insert(" ") + word(TR_LOWER) # "1.sırada" ordinals |= composed["ordinal_roman"] + space + word(TR_ALPHA) # "XX. yüzyıl", "II. Mehmet" - # times and speeds - clock = word_list(capitalized(["saat"])) + space + composed["time_in_context"] + # times, also a range after "saat" ("saat 09.00-17.30"), and speeds + time = composed["time"] | composed["time_in_context"] + to = pynini.closure(pynutil.delete(" "), 0, 1) + pynini.cross(pynini.union("-", "–"), " ile ") + to += pynini.closure(pynutil.delete(" "), 0, 1) + clock = word_list(capitalized(["saat"])) + space + (composed["time_in_context"] | time + to + time) speed = word_list(capitalized(["saatte"])) + space + composed["speed_after_per_word"] - # codes: four to eight digits read one by one, a suffix on the last one ("218456'dır" -> "... altıdır") - code = (NEMO_DIGIT**4 + pynini.closure(NEMO_DIGIT, 0, 4)) @ cardinal.digits - codes = word_list(capitalized(CODE_WORDS)) + space + (code | attach_suffix(code)) + # codes: four to eight digits read one by one, also in dash-separated groups ("1234-5678"), after an optional + # colon ("kodunuz: 482913"); a suffix goes on the last digit ("218456'dır" -> "... altıdır") + digits = (NEMO_DIGIT**4 + pynini.closure(NEMO_DIGIT, 0, 4)) @ cardinal.digits + group = (NEMO_DIGIT**2 + pynini.closure(NEMO_DIGIT, 0, 6)) @ cardinal.digits + code = digits | group + pynini.closure(pynini.cross("-", ", ") + group, 1) + code_word = word_list(capitalized(CODE_WORDS)) + pynini.closure(pynini.accep(":"), 0, 1) + codes = code_word + space + (code | attach_suffix(code)) self.graph = (ordinals | clock | speed | codes).optimize() self.fst = name_tokens(self.graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/taggers/ordinal.py b/nemo_text_processing/text_normalization/tr/taggers/ordinal.py index b31281935..8353f66eb 100644 --- a/nemo_text_processing/text_normalization/tr/taggers/ordinal.py +++ b/nemo_text_processing/text_normalization/tr/taggers/ordinal.py @@ -44,8 +44,8 @@ class OrdinalFst(GraphFst): ("bir" -> "birinci", "üç" -> "üçüncü", "altı" -> "altıncı"). A number followed by a dot is an ordinal only before a word ("5. sırada" -> "beşinci sırada"); at the end of a - sentence it is a number and a full stop. self.fst_dot is therefore kept apart and used by ClassifyFst only in - front of a lower-case word. + sentence it is a number and a full stop. self.fst_dot is therefore kept apart and used by ContextFst only in + front of a lower-case word or a known noun. Args: cardinal: CardinalFst diff --git a/nemo_text_processing/text_normalization/tr/taggers/range.py b/nemo_text_processing/text_normalization/tr/taggers/range.py index 2c00f2091..a91e0cf88 100644 --- a/nemo_text_processing/text_normalization/tr/taggers/range.py +++ b/nemo_text_processing/text_normalization/tr/taggers/range.py @@ -62,10 +62,10 @@ def number(n): class RangeFst(GraphFst): """ Finite state transducer for ranges, scores and dimensions, read with the composed taggers and verbalizers of the - classes on both sides and emitted as name tokens, e.g. - "3-5 iş günü" -> tokens { name: "üç" } tokens { name: "ile" } tokens { name: "beş" } ... - "09.00-17.30" -> ... "dokuz ile on yedi otuz" - "1914-1918", "MÖ 3000-1200" -> ... "bin dokuz yüz on dört ile bin dokuz yüz on sekiz" + classes on both sides and emitted as a name token, e.g. + "3-5 iş günü" -> tokens { name: "üç ile beş" } ... + "09.00-17.30" -> "dokuz ile on yedi otuz" + "1914-1918", "MÖ 3000-1200" -> "bin dokuz yüz on dört ile bin dokuz yüz on sekiz" "23-25 Aralık", "12 Nisan - 30 Haziran 2024" "36,5-37,2 °C" -> "otuz altı buçuk ile otuz yedi virgül iki santigrat derece" (the unit is read once) "%10-20", "10-20%" -> "yüzde on ile yirmi" (the English order only for small numbers) diff --git a/nemo_text_processing/text_normalization/tr/taggers/serial.py b/nemo_text_processing/text_normalization/tr/taggers/serial.py index 89f75b114..1cbc0330c 100644 --- a/nemo_text_processing/text_normalization/tr/taggers/serial.py +++ b/nemo_text_processing/text_normalization/tr/taggers/serial.py @@ -21,12 +21,14 @@ class SerialFst(GraphFst): """ - Finite state transducer for numbers joined by symbols that are read as words, emitted as name tokens, e.g. - "3.12.1" -> tokens { name: "üç" } tokens { name: "nokta" } tokens { name: "on" } ... (a version) - "3:2" -> tokens { name: "üçe" } tokens { name: "iki" } (a ratio) + Finite state transducer for numbers joined by symbols, emitted as a name token, e.g. + "3.12.1" -> tokens { name: "üç nokta on iki nokta bir" } (a version) + "3:2" -> tokens { name: "üçe iki" } (a ratio) + "12-34-56" -> tokens { name: "on iki, otuz dört, elli altı" } (a code) A version has three or more parts and is not a thousands grouping ("1.250.000") nor a date (DateFst wins on - weight). A ratio has a single digit after the colon, so it does not overlap with a time. + weight). A ratio has a single digit after the colon, so it does not overlap with a time. Three or more + dash-separated groups are a code; two are left to RangeFst. Args: cardinal: CardinalFst @@ -52,5 +54,12 @@ def __init__(self, cardinal: GraphFst, deterministic: bool = True): ) ratio = to_dative + pynutil.insert(" ") + ((NEMO_DIGIT - "0") @ cardinal.graph) - self.graph = (version | ratio).optimize() + # three or more dash-separated groups are a code, not a range: "12-34-56", "1234-5678-9012"; groups of up + # to three digits are read as numbers, longer ones digit by digit + group = pynini.compose((NEMO_DIGIT - "0") + pynini.closure(NEMO_DIGIT, 0, 2) | "0", cardinal.graph) + group |= pynini.compose("0" + pynini.closure(NEMO_DIGIT, 1, 2), cardinal.digits) # leading zero: "05" + group |= pynini.compose(pynini.closure(NEMO_DIGIT, 4), cardinal.digits) + chain = group + pynini.closure(pynini.cross("-", ", ") + group, 2) + + self.graph = (version | ratio | chain).optimize() self.fst = name_tokens(self.graph).optimize() diff --git a/nemo_text_processing/text_normalization/tr/taggers/whitelist.py b/nemo_text_processing/text_normalization/tr/taggers/whitelist.py index c7f988d4b..6eb49cb11 100644 --- a/nemo_text_processing/text_normalization/tr/taggers/whitelist.py +++ b/nemo_text_processing/text_normalization/tr/taggers/whitelist.py @@ -29,7 +29,7 @@ class WhiteListFst(GraphFst): """ Finite state transducer for classifying whitelist, e.g. "Dr." -> tokens { name: "doktor" } - "vb." -> tokens { name: "ve" } tokens { name: "benzeri" } + "vb." -> tokens { name: "ve benzeri" } This class has highest priority among all classifier grammars. Whitelisted tokens are defined and loaded from "data/whitelist.tsv". diff --git a/nemo_text_processing/text_normalization/tr/taggers/word.py b/nemo_text_processing/text_normalization/tr/taggers/word.py index 483829141..f309fe512 100644 --- a/nemo_text_processing/text_normalization/tr/taggers/word.py +++ b/nemo_text_processing/text_normalization/tr/taggers/word.py @@ -30,5 +30,7 @@ class WordFst(GraphFst): def __init__(self, deterministic: bool = True): super().__init__(name="word", kind="classify", deterministic=deterministic) - self.graph = pynini.closure(NEMO_NOT_SPACE, 1).optimize() + # a double quote cannot appear in a name token's value (Sparrowhawk fails to parse it), so it is left to + # PunctuationFst: '"Ben' -> a punctuation token and a word + self.graph = pynini.closure(pynini.difference(NEMO_NOT_SPACE, '"'), 1).optimize() self.fst = (pynutil.insert('name: "') + self.graph + pynutil.insert('"')).optimize() diff --git a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_lower_cased.txt b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_lower_cased.txt index fb78a62a0..5ff2f5f4d 100644 --- a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_lower_cased.txt +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_lower_cased.txt @@ -3,3 +3,5 @@ tutar 100. sonra ödeme yapın.~tutar yüz . sonra ödeme yapın. kredinizin 3. taksiti ödendi.~kredinizin üçüncü taksiti ödendi. faiz %2,5 oldu.~faiz yüzde iki buçuk oldu. toplantı 14:30'da.~toplantı on dört otuzda . +paket 5 gb geldi.~paket beş gigabayt geldi. +1. dünya savaşı başladı.~birinci dünya savaşı başladı. diff --git a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_punctuation.txt b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_punctuation.txt new file mode 100644 index 000000000..29b99f1f8 --- /dev/null +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_punctuation.txt @@ -0,0 +1,3 @@ +"Ben bu yarışta 1. oldum" dedi.~" Ben bu yarışta birinci oldum " dedi. +O "evet" dedi.~O " evet " dedi. +"Borcunuz 100 TL" dedi.~" Borcunuz yüz lira " dedi. diff --git a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_sentences.txt b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_sentences.txt index dc91ee618..8ef2de135 100644 --- a/tests/nemo_text_processing/tr/data_text_normalization/test_cases_sentences.txt +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_sentences.txt @@ -45,3 +45,10 @@ Please try again later.~Please try again later. Faiz 1.25'lik oranla hesaplandı.~Faiz bir virgül yirmi beşlik oranla hesaplandı. Oran 7/365 olarak hesaplandı.~Oran yedi bölü üç yüz altmış beş olarak hesaplandı. Kampanya 10-20% indirim sunuyor.~Kampanya yüzde on ile yirmi indirim sunuyor. +Saat 09.00-17.30 arası açığız.~Saat dokuz ile on yedi otuz arası açığız. +Parça numarası 12-34-56.~Parça numarası on iki, otuz dört, elli altı . +Ürün kodu 12-34-56.~Ürün kodu bir iki, üç dört, beş altı . +Şifreniz 1234-5678 olarak belirlendi.~Şifreniz bir iki üç dört, beş altı yedi sekiz olarak belirlendi. +Doğrulama kodunuz: 482913.~Doğrulama kodunuz: dört sekiz iki dokuz bir üç . +1. Dünya Savaşı 1914'te başladı.~birinci Dünya Savaşı bin dokuz yüz on dörtte başladı. +Takım 1. Lig'de oynuyor.~Takım birinci Lig'de oynuyor. diff --git a/tests/nemo_text_processing/tr/test_punctuation.py b/tests/nemo_text_processing/tr/test_punctuation.py new file mode 100644 index 000000000..aefc171a6 --- /dev/null +++ b/tests/nemo_text_processing/tr/test_punctuation.py @@ -0,0 +1,31 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pytest +from parameterized import parameterized + +from nemo_text_processing.text_normalization.normalize import Normalizer + +from ..utils import CACHE_DIR, parse_test_case_file + + +class TestPunctuation: + normalizer_tr = Normalizer(input_case='cased', lang='tr', cache_dir=CACHE_DIR, overwrite_cache=False) + + @parameterized.expand(parse_test_case_file('tr/data_text_normalization/test_cases_punctuation.txt')) + @pytest.mark.run_only_on('CPU') + @pytest.mark.unit + def test_norm(self, test_input, expected): + pred = self.normalizer_tr.normalize(test_input, verbose=False) + assert pred == expected