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..e53bb85fb --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/data/dates/month_names.tsv @@ -0,0 +1,46 @@ +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 +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/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..77208c2df --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/data/measures/units.tsv @@ -0,0 +1,67 @@ +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 +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 +kcal kilokalori +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/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..b3b6d8011 --- /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 +€ euro sent +EUR euro sent +£ sterlin peni +GBP sterlin peni 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/ordinals/ordinal_nouns.tsv b/nemo_text_processing/text_normalization/tr/data/ordinals/ordinal_nouns.tsv new file mode 100644 index 000000000..0211ffd45 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/data/ordinals/ordinal_nouns.tsv @@ -0,0 +1,45 @@ +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 +dünya +lig +ordu +kolordu +tümen +grup 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..ae20bfeb4 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/data/whitelist.tsv @@ -0,0 +1,21 @@ +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 +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..aee9f69b2 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/graph_utils.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 + +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". +APOSTROPHE = pynini.union("'", "’", "‘", "´") +SUFFIX = pynini.closure(TR_ALPHA, 1).optimize() + + +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" + See inflection.py. + + 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 + """ + 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 new file mode 100644 index 000000000..20993bb1f --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/inflection.py @@ -0,0 +1,153 @@ +# 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.graph_utils import SUFFIX +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ğ"} +# 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. +# 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", + "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(FRONT_HARMONY): + 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 + + +@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")] + 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 + # 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/__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/context.py b/nemo_text_processing/text_normalization/tr/taggers/context.py new file mode 100644 index 000000000..fe4f8e03e --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/taggers/context.py @@ -0,0 +1,124 @@ +# 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 ( + 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 + +# 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 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", "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 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", "ş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 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", + "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) + # 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(not_quote) + + def word_list(words): + return pynini.union(*words) + + # 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"))] + 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 = ( + 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, 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, 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/date.py b/nemo_text_processing/text_normalization/tr/taggers/date.py new file mode 100644 index 000000000..b04253bf0 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/taggers/date.py @@ -0,0 +1,113 @@ +# 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.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 + + +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" } + "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 + 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) + # "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('"') + + 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", years) + ) + numeric = pynini.union(*numeric) + + # 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 = ( + field("day", day, first=True) + + pynutil.delete(NEMO_SPACE) + + field("month", month_name) + + pynini.closure(pynutil.delete(NEMO_SPACE) + field("year", year), 0, 1) + ) + + # 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 + 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..c4199e5dc --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/taggers/decimal.py @@ -0,0 +1,86 @@ +# 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) + + # ",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 + 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..dafa35c3f --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/taggers/fraction.py @@ -0,0 +1,106 @@ +# 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_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 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 üç" +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 } + "3/4'ü" -> fraction { denominator: "dörtte" numerator: "üçü" preserve_order: true } + "½" -> fraction { denominator: "ikide" numerator: "bir" preserve_order: true } + "7/365" -> fraction { numerator: "yedi" denominator: "üç yüz altmış beş" morphosyntactic_features: "bölü" } + + 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 + 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 + + # 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) + proper = pynini.union(*[str(n) for n in range(1, min(denominator, 1000))]) + branches.append( + pynutil.insert(f'denominator: "{spoken}" numerator: "') + + proper + + f"/{denominator}" + + pynini.closure(APOSTROPHE + SUFFIX, 0, 1) + ) + 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) + spoken_num = rewrite.top_rewrite(num, cardinal.graph) + symbols.append( + pynini.cross(symbol, f'denominator: "{spoken_den}" numerator: "{spoken_num}" preserve_order: true') + ) + symbols = pynini.union(*symbols) + + # "a/b" read "a bölü b"; also used by MeasureFst ("140/90 mmHg") + self.division = ( + pynutil.insert('numerator: "') + + plain_number + + pynini.cross("/", '" denominator: "') + + plain_number + + pynutil.insert('" morphosyntactic_features: "bölü"') + ).optimize() + + # 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 + 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 new file mode 100644 index 000000000..fad686377 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/taggers/measure.py @@ -0,0 +1,102 @@ +# 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_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 } + "%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 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, 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(name, graph): + return pynutil.insert(name + " { ") + graph + pynutil.insert(" }") + + def units_field(graph): + return pynutil.insert(' units: "') + graph + pynutil.insert('"') + + 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 + 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 + + # units: "5 km", "2,5 kg", "5 km'ye" + units = pynini.string_file(get_abs_path("data/measures/units.tsv")) + units |= attach_suffix(units) + 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, ".")) + 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 = 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 new file mode 100644 index 000000000..b44ce3656 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/taggers/money.py @@ -0,0 +1,127 @@ +# 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.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 = {"$", "€", "£", "₺"} + + +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 } + "0,50 TL" -> money { fractional_part: "elli" currency_min: "kuruş" 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 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 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 + 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) + + 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() + 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 = [] + currencies = load_labels(get_abs_path("data/money/currency.tsv")) + # 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: + 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))) + ) + 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) + 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 new file mode 100644 index 000000000..8353f66eb --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/taggers/ordinal.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 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ü") + + +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. + "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 ContextFst only in + front of a lower-case word or a known noun. + + 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() + + # 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/range.py b/nemo_text_processing/text_normalization/tr/taggers/range.py new file mode 100644 index 000000000..a91e0cf88 --- /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 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) + "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..1cbc0330c --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/taggers/serial.py @@ -0,0 +1,65 @@ +# 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, 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. Three or more + dash-separated groups are a code; two are left to RangeFst. + + 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) + + # 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/telephone.py b/nemo_text_processing/text_normalization/tr/taggers/telephone.py new file mode 100644 index 000000000..29e449d1c --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/taggers/telephone.py @@ -0,0 +1,88 @@ +# 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 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") + 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(", ") + 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) + # 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 + 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 new file mode 100644 index 000000000..3ffb5457f --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/taggers/time.py @@ -0,0 +1,102 @@ +# 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 + +CASE_SUFFIXES = ["DA", "DAn", "(y)A", "DAki"] + + +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 + with a case suffix, a leading zero or ".00", or in context (self.dot_in_context); otherwise it is a decimal. + + 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, 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( + 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, 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) + + pynutil.delete(sep) + + 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) + + 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() + + 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 new file mode 100644 index 000000000..6685980ba --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/taggers/tokenize_and_classify.py @@ -0,0 +1,187 @@ +# 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_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.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.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 + +# 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): + """ + 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. + + 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. + 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}.") + 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, + ) + token = pynutil.insert("tokens { ") + classify + pynutil.insert(" }") + 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..6eb49cb11 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/taggers/whitelist.py @@ -0,0 +1,67 @@ +# 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 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, name_tokens +from nemo_text_processing.text_normalization.tr.utils import get_abs_path + + +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) + + # 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() and code != "TRY" + ] + currency = pynini.string_map(codes) + graph |= currency | attach_suffix(currency) + + self.graph = graph.optimize() + self.fst = name_tokens(self.graph).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..f309fe512 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/taggers/word.py @@ -0,0 +1,36 @@ +# 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) + # 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/nemo_text_processing/text_normalization/tr/utils.py b/nemo_text_processing/text_normalization/tr/utils.py new file mode 100644 index 000000000..1f92dd8f1 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/utils.py @@ -0,0 +1,27 @@ +# 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 + + +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 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..6b952d92a --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/verbalizers/date.py @@ -0,0 +1,52 @@ +# 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) + 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 new file mode 100644 index 000000000..752122325 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/verbalizers/decimal.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_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('"') + ) + # "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/fraction.py b/nemo_text_processing/text_normalization/tr/verbalizers/fraction.py new file mode 100644 index 000000000..019e351ec --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/verbalizers/fraction.py @@ -0,0 +1,58 @@ +# 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: "üç 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, + 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) + 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 new file mode 100644 index 000000000..94ad48570 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/verbalizers/measure.py @@ -0,0 +1,64 @@ +# 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 + 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, fraction: GraphFst, deterministic: bool = True): + super().__init__(name="measure", 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(" ") + # 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/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..e1375c3f7 --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/verbalizers/verbalize.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. + +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) + 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, fraction=fraction, 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..4d72a1e0c --- /dev/null +++ b/nemo_text_processing/text_normalization/tr/verbalizers/verbalize_final.py @@ -0,0 +1,84 @@ +# 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_QUOTE, + 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 + # 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 + + 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..c40f1d9c2 --- /dev/null +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_cardinal.txt @@ -0,0 +1,34 @@ +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ı +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 new file mode 100644 index 000000000..7a8928d54 --- /dev/null +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_date.txt @@ -0,0 +1,13 @@ +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ı +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ı +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 new file mode 100644 index 000000000..1b4b65fe3 --- /dev/null +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_decimal.txt @@ -0,0 +1,13 @@ +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,4'ü~üç virgül dördü 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..1bc03e540 --- /dev/null +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_fraction.txt @@ -0,0 +1,11 @@ +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ü +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..5ff2f5f4d --- /dev/null +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_lower_cased.txt @@ -0,0 +1,7 @@ +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 . +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_measure.txt b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_measure.txt new file mode 100644 index 000000000..68177f627 --- /dev/null +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_measure.txt @@ -0,0 +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 buçuk kilogram +120 m²~yüz yirmi metrekare +25 °C~yirmi beş santigrat derece +30 dk~otuz dakika +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 new file mode 100644 index 000000000..83b4660f8 --- /dev/null +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_money.txt @@ -0,0 +1,25 @@ +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 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 +$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 new file mode 100644 index 000000000..101bb46b0 --- /dev/null +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_ordinal.txt @@ -0,0 +1,13 @@ +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 +1., 2. ve 3. taksit~birinci , ikinci ve üçüncü taksit 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 new file mode 100644 index 000000000..8ef2de135 --- /dev/null +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_sentences.txt @@ -0,0 +1,54 @@ +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. +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ı. +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/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..75f06bdd1 --- /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 +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 new file mode 100644 index 000000000..d63736fc9 --- /dev/null +++ b/tests/nemo_text_processing/tr/data_text_normalization/test_cases_time.txt @@ -0,0 +1,17 @@ +14:30~on dört otuz +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 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..e8100a2bd --- /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..2bb01ffee --- /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..b453ffac0 --- /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..a9033d502 --- /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_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 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 new file mode 100644 index 000000000..dfd7064ad --- /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..fe1334a2e --- /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..c91f051aa --- /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_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 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 new file mode 100644 index 000000000..fa2561ce6 --- /dev/null +++ b/tests/nemo_text_processing/tr/test_sparrowhawk_normalization.sh @@ -0,0 +1,86 @@ +#! /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 +} + +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 +} + +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 +} + +testTNTime() { + input=$PROJECT_DIR/tr/data_text_normalization/test_cases_time.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 +} + +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 new file mode 100644 index 000000000..118c2674f --- /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..396d3d6dd --- /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..c30cdbc8a --- /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..151485096 --- /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,