diff --git a/Jenkinsfile b/Jenkinsfile index 38e05bb00..9d65fbf3a 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -28,6 +28,9 @@ pipeline { HY_TN_CACHE='/home/jenkins/TestData/text_norm/ci/grammars/03-12-24-0' MR_TN_CACHE='/home/jenkins/TestData/text_norm/ci/grammars/03-12-24-1' JA_TN_CACHE='/home/jenkins/TestData/text_norm/ci/grammars/10-17-24-1' + KO_TN_CACHE='/home/jenkins/TestData/text_norm/ci/grammars/04-23-26-0' + HI_TN_CACHE='/home/jenkins/TestData/text_norm/ci/grammars/04-23-26-0' + TE_TN_CACHE='/home/jenkins/TestData/text_norm/ci/grammars/07-21-26-0' HI_TN_CACHE='/home/jenkins/TestData/text_norm/ci/grammars/06-04-26-5' KO_TN_CACHE='/home/jenkins/TestData/text_norm/ci/grammars/06-04-25-6' DEFAULT_TN_CACHE='/home/jenkins/TestData/text_norm/ci/grammars/06-08-23-0' @@ -112,6 +115,30 @@ pipeline { } } } + stage('L0: Create TE TN/ITN Grammars') { + when { + anyOf { + branch 'main' + branch 'staging/**' + branch 'staging_*' + changeRequest target: 'main' + } + } + failFast true + parallel { + stage('L0: TE TN grammars') { + steps { + sh 'CUDA_VISIBLE_DEVICES="" python nemo_text_processing/text_normalization/normalize.py --lang=te --text="౧" --cache_dir ${TE_TN_CACHE}' + } + } + // stage('L0: TE ITN grammars') { + // steps { + // sh 'CUDA_VISIBLE_DEVICES="" python nemo_text_processing/inverse_text_normalization/inverse_normalize.py --lang=te --text="ఒకటి" --cache_dir ${TE_TN_CACHE}' + // } + // } + + } + } stage('L0: Create DE/ES TN/ITN Grammars') { when { @@ -407,6 +434,11 @@ pipeline { steps { sh 'CUDA_VISIBLE_DEVICES="" pytest tests/nemo_text_processing/hi/ -m "not pleasefixme" --cpu --tn_cache_dir ${HI_TN_CACHE}' } + } + stage('L1: Run all TE TN/ITN tests (restore grammars from cache)') { + steps { + sh 'CUDA_VISIBLE_DEVICES="" pytest tests/nemo_text_processing/te/ -m "not pleasefixme" --cpu --tn_cache_dir ${TE_TN_CACHE}' + } } stage('L1: Run all Codeswitched ES/EN TN/ITN tests (restore grammars from cache)') { steps { diff --git a/nemo_text_processing/text_normalization/normalize.py b/nemo_text_processing/text_normalization/normalize.py index d8ebf2f4d..9101ae604 100644 --- a/nemo_text_processing/text_normalization/normalize.py +++ b/nemo_text_processing/text_normalization/normalize.py @@ -166,6 +166,7 @@ def __init__( if post_process: self.post_processor = PostProcessingFst(cache_dir=cache_dir, overwrite_cache=overwrite_cache) + elif lang == 'it': from nemo_text_processing.text_normalization.it.taggers.tokenize_and_classify import ClassifyFst from nemo_text_processing.text_normalization.it.verbalizers.verbalize_final import VerbalizeFinalFst @@ -191,6 +192,13 @@ def __init__( elif lang == 'ko': from nemo_text_processing.text_normalization.ko.taggers.tokenize_and_classify import ClassifyFst from nemo_text_processing.text_normalization.ko.verbalizers.verbalize_final import VerbalizeFinalFst + elif lang == 'te': + from nemo_text_processing.text_normalization.te.taggers.tokenize_and_classify import ClassifyFst + from nemo_text_processing.text_normalization.te.verbalizers.post_processing import PostProcessingFst + from nemo_text_processing.text_normalization.te.verbalizers.verbalize_final import VerbalizeFinalFst + + if post_process: + self.post_processor = PostProcessingFst(cache_dir=cache_dir, overwrite_cache=overwrite_cache) else: raise NotImplementedError(f"Language {lang} has not been supported yet.") @@ -391,7 +399,11 @@ def normalize( return text output = SPACE_DUP.sub(' ', output[1:]) - if self.lang in ["en", "hi", "vi"] and hasattr(self, 'post_processor') and self.post_processor is not None: + if ( + self.lang in ["en", "hi", "te", "vi"] + and hasattr(self, 'post_processor') + and self.post_processor is not None + ): output = self.post_process(output) if punct_post_process: @@ -737,7 +749,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", "te", "ko", "vi", "pt"], 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..1df194042 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', 'te', 'ko', 'vi', 'pt'], default="en", type=str, ) diff --git a/nemo_text_processing/text_normalization/te/__init__.py b/nemo_text_processing/text_normalization/te/__init__.py new file mode 100644 index 000000000..4fc25d0d3 --- /dev/null +++ b/nemo_text_processing/text_normalization/te/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2026, NVIDIA CORPORATION. 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/te/data/numbers/__init__.py b/nemo_text_processing/text_normalization/te/data/numbers/__init__.py new file mode 100644 index 000000000..4fc25d0d3 --- /dev/null +++ b/nemo_text_processing/text_normalization/te/data/numbers/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2026, NVIDIA CORPORATION. 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/te/data/numbers/digit.tsv b/nemo_text_processing/text_normalization/te/data/numbers/digit.tsv new file mode 100644 index 000000000..ab878ec99 --- /dev/null +++ b/nemo_text_processing/text_normalization/te/data/numbers/digit.tsv @@ -0,0 +1,18 @@ +1 ఒకటి +2 రెండు +3 మూడు +4 నాలుగు +5 ఐదు +6 ఆరు +7 ఏడు +8 ఎనిమిది +9 తొమ్మిది +౧ ఒకటి +౨ రెండు +౩ మూడు +౪ నాలుగు +౫ ఐదు +౬ ఆరు +౭ ఏడు +౮ ఎనిమిది +౯ తొమ్మిది \ No newline at end of file diff --git a/nemo_text_processing/text_normalization/te/data/numbers/magnitudes.tsv b/nemo_text_processing/text_normalization/te/data/numbers/magnitudes.tsv new file mode 100644 index 000000000..b47f7e50b --- /dev/null +++ b/nemo_text_processing/text_normalization/te/data/numbers/magnitudes.tsv @@ -0,0 +1,15 @@ +hundred వంద +hundred_prefix నూట +hundreds_plural వందలు +hundreds_before వందల +thousand వెయ్యి +thousands_plural వేలు +thousands_before వేల +lakh లక్ష +lakh_before_digit లక్షా +lakhs_plural లక్షలు +lakhs_before లక్షల +crore కోటి +crores_plural కోట్లు +crores_before కోట్ల +one ఒక diff --git a/nemo_text_processing/text_normalization/te/data/numbers/teens_and_ties.tsv b/nemo_text_processing/text_normalization/te/data/numbers/teens_and_ties.tsv new file mode 100644 index 000000000..e07b7925e --- /dev/null +++ b/nemo_text_processing/text_normalization/te/data/numbers/teens_and_ties.tsv @@ -0,0 +1,10 @@ +౧౦ పది +౧౧ పదకొండు +౧౨ పన్నెండు +౧౩ పదమూడు +౧౪ పద్నాలుగు +౧౫ పదిహేను +౧౬ పదహారు +౧౭ పదిహేడు +౧౮ పధ్ధెనిమిది +౧౯ పంతొమ్మిది diff --git a/nemo_text_processing/text_normalization/te/data/numbers/teens_and_ties_en.tsv b/nemo_text_processing/text_normalization/te/data/numbers/teens_and_ties_en.tsv new file mode 100644 index 000000000..cdbb3c069 --- /dev/null +++ b/nemo_text_processing/text_normalization/te/data/numbers/teens_and_ties_en.tsv @@ -0,0 +1,10 @@ +10 పది +11 పదకొండు +12 పన్నెండు +13 పదమూడు +14 పద్నాలుగు +15 పదిహేను +16 పదహారు +17 పదిహేడు +18 పధ్ధెనిమిది +19 పంతొమ్మిది diff --git a/nemo_text_processing/text_normalization/te/data/numbers/teens_and_ties_thousand.tsv b/nemo_text_processing/text_normalization/te/data/numbers/teens_and_ties_thousand.tsv new file mode 100644 index 000000000..a6bcff46b --- /dev/null +++ b/nemo_text_processing/text_normalization/te/data/numbers/teens_and_ties_thousand.tsv @@ -0,0 +1,16 @@ +21 ఇరవై ఒక +31 ముప్పై ఒక +41 నలభై ఒక +51 యాభై ఒక +61 అరవై ఒక +71 డెబ్బై ఒక +81 ఎనభై ఒక +91 తొంభై ఒక +౨౧ ఇరవై ఒక +౩౧ ముప్పై ఒక +౪౧ నలభై ఒక +౫౧ యాభై ఒక +౬౧ అరవై ఒక +౭౧ డెబ్బై ఒక +౮౧ ఎనభై ఒక +౯౧ తొంభై ఒక \ No newline at end of file diff --git a/nemo_text_processing/text_normalization/te/data/numbers/ties.tsv b/nemo_text_processing/text_normalization/te/data/numbers/ties.tsv new file mode 100644 index 000000000..a8d7d7227 --- /dev/null +++ b/nemo_text_processing/text_normalization/te/data/numbers/ties.tsv @@ -0,0 +1,16 @@ +2 ఇరవై +3 ముప్పై +4 నలభై +5 యాభై +6 అరవై +7 డెబ్బై +8 ఎనభై +9 తొంభై +౨ ఇరవై +౩ ముప్పై +౪ నలభై +౫ యాభై +౬ అరవై +౭ డెబ్బై +౮ ఎనభై +౯ తొంభై diff --git a/nemo_text_processing/text_normalization/te/data/numbers/zero.tsv b/nemo_text_processing/text_normalization/te/data/numbers/zero.tsv new file mode 100644 index 000000000..309aab75e --- /dev/null +++ b/nemo_text_processing/text_normalization/te/data/numbers/zero.tsv @@ -0,0 +1,2 @@ +0 సున్నా +౦ సున్నా \ No newline at end of file diff --git a/nemo_text_processing/text_normalization/te/graph_utils.py b/nemo_text_processing/text_normalization/te/graph_utils.py new file mode 100644 index 000000000..1bb247162 --- /dev/null +++ b/nemo_text_processing/text_normalization/te/graph_utils.py @@ -0,0 +1,145 @@ +# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. +# Copyright 2015 and onwards Google, Inc. +# +# 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 logging +import os +from pathlib import Path +from typing import Dict + +import pynini +from pynini import Far +from pynini.export import export +from pynini.lib import byte, pynutil, utf8 + +NEMO_CHAR = utf8.VALID_UTF8_CHAR +NEMO_DIGIT = byte.DIGIT + +# Telugu native digits (౦, ౧, ౨, ౩, ౪, ౫, ౬, ౭, ౮, ౯) +NEMO_TE_DIGIT = pynini.union("౦", "౧", "౨", "౩", "౪", "౫", "౬", "౭", "౮", "౯").optimize() + +# Combined Telugu and Arabic digits for graphs that need to accept both +NEMO_ALL_DIGIT = pynini.union(NEMO_TE_DIGIT, NEMO_DIGIT).optimize() +NEMO_ALL_ZERO = pynini.union("౦", "0").optimize() + +NEMO_NON_BREAKING_SPACE = u"\u00a0" +NEMO_SPACE = " " +NEMO_WHITE_SPACE = pynini.union(" ", "\t", "\n", "\r", u"\u00a0").optimize() +NEMO_NOT_SPACE = pynini.difference(NEMO_CHAR, NEMO_WHITE_SPACE).optimize() +NEMO_NOT_QUOTE = pynini.difference(NEMO_CHAR, r'"').optimize() +NEMO_SIGMA = pynini.closure(NEMO_CHAR) + +delete_space = pynutil.delete(pynini.closure(NEMO_WHITE_SPACE)) +insert_space = pynutil.insert(" ") +delete_extra_space = pynini.cross(pynini.closure(NEMO_WHITE_SPACE, 1), " ") + +MIN_NEG_WEIGHT = -0.0001 + + +def generator_main(file_name: str, graphs: Dict[str, 'pynini.FstLike']): + """ + Exports graph as OpenFst finite state archive (FAR) file with given file name and rule name. + + Args: + file_name: exported file name + graphs: Mapping of a rule name and Pynini WFST graph to be exported + """ + exporter = export.Exporter(file_name) + for rule, graph in graphs.items(): + exporter[rule] = graph.optimize() + exporter.close() + logging.info(f'Created {file_name}') + + +def convert_space(fst) -> 'pynini.FstLike': + """ + Converts space to nonbreaking space. + Used only in tagger grammars for transducing token values within quotes, e.g. name: "hello kitty" + This is making transducer significantly slower, so only use when there could be potential spaces within quotes, otherwise leave it. + + Args: + fst: input fst + + Returns output fst where breaking spaces are converted to non breaking spaces + """ + return fst @ pynini.cdrewrite(pynini.cross(NEMO_SPACE, NEMO_NON_BREAKING_SPACE), "", "", NEMO_SIGMA) + + +class GraphFst: + """ + Base class for all grammar fsts. + + Args: + name: name of grammar class + kind: either 'classify' or 'verbalize' + deterministic: if True will provide a single transduction option, + for False multiple transduction are generated (used for audio-based normalization) + """ + + def __init__(self, name: str, kind: str, deterministic: bool = True): + self.name = name + self.kind = kind + self._fst = None + self.deterministic = deterministic + + self.far_path = Path(os.path.dirname(__file__) + '/grammars/' + kind + '/' + name + '.far') + if self.far_exist(): + self._fst = Far(self.far_path, mode="r", arc_type="standard", far_type="default").get_fst() + + def far_exist(self) -> bool: + """ + Returns true if FAR can be loaded + """ + return self.far_path.exists() + + @property + def fst(self) -> 'pynini.FstLike': + return self._fst + + @fst.setter + def fst(self, fst): + self._fst = fst + + def add_tokens(self, fst) -> 'pynini.FstLike': + """ + Wraps class name around to given fst + + Args: + fst: input fst + + Returns: + Fst: fst + """ + return pynutil.insert(f"{self.name} {{ ") + fst + pynutil.insert(" }") + + def delete_tokens(self, fst) -> 'pynini.FstLike': + """ + Deletes class name wrap around output of given fst + + Args: + fst: input fst + + Returns: + Fst: fst + """ + res = ( + pynutil.delete(f"{self.name}") + + delete_space + + pynutil.delete("{") + + delete_space + + fst + + delete_space + + pynutil.delete("}") + ) + return res @ pynini.cdrewrite(pynini.cross(u"\u00a0", " "), "", "", NEMO_SIGMA) diff --git a/nemo_text_processing/text_normalization/te/taggers/__init__.py b/nemo_text_processing/text_normalization/te/taggers/__init__.py new file mode 100644 index 000000000..4fc25d0d3 --- /dev/null +++ b/nemo_text_processing/text_normalization/te/taggers/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2026, NVIDIA CORPORATION. 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/te/taggers/cardinal.py b/nemo_text_processing/text_normalization/te/taggers/cardinal.py new file mode 100644 index 000000000..b941970d4 --- /dev/null +++ b/nemo_text_processing/text_normalization/te/taggers/cardinal.py @@ -0,0 +1,429 @@ +# Copyright (c) 2026, NVIDIA CORPORATION. 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.te.graph_utils import ( + NEMO_ALL_DIGIT, + NEMO_ALL_ZERO, + NEMO_DIGIT, + NEMO_TE_DIGIT, + GraphFst, + insert_space, +) +from nemo_text_processing.text_normalization.te.utils import get_abs_path + + +class CardinalFst(GraphFst): + """ + Finite state transducer for classifying cardinals, e.g. + -౨౩ -> cardinal { negative: "true" integer: "ఇరవై మూడు" } + + 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) + + digit = pynini.string_file(get_abs_path("data/numbers/digit.tsv")) + zero = pynini.string_file(get_abs_path("data/numbers/zero.tsv")) + teens_te = pynini.string_file(get_abs_path("data/numbers/teens_and_ties.tsv")) + teens_en = pynini.string_file(get_abs_path("data/numbers/teens_and_ties_en.tsv")) + ties = pynini.string_file(get_abs_path("data/numbers/ties.tsv")) + teens_ties_thousand = pynutil.add_weight( + pynini.string_file(get_abs_path("data/numbers/teens_and_ties_thousand.tsv")), + -0.2, + ) + + magnitude = {} + with open(get_abs_path("data/numbers/magnitudes.tsv"), encoding="utf-8") as magnitude_file: + for magnitude_line in magnitude_file: + magnitude_line = magnitude_line.rstrip("\r\n") + if not magnitude_line: + continue + magnitude_key, magnitude_word = magnitude_line.split("\t") + magnitude[magnitude_key] = magnitude_word + + hundred = magnitude["hundred"] + hundred_prefix = magnitude["hundred_prefix"] + " " + thousand = magnitude["thousand"] + lakh = magnitude["lakh"] + crore = magnitude["crore"] + hundreds_before_one = " " + magnitude["hundreds_before"] + " " + magnitude["one"] + + ins_hundreds_plural = pynutil.insert(" " + magnitude["hundreds_plural"]) + ins_hundreds_before = pynutil.insert(" " + magnitude["hundreds_before"]) + ins_thousand = pynutil.insert(thousand) + ins_thousand_spaced = pynutil.insert(" " + thousand) + ins_thousands_plural = pynutil.insert(" " + magnitude["thousands_plural"]) + ins_thousands_before = pynutil.insert(" " + magnitude["thousands_before"]) + ins_lakh = pynutil.insert(lakh) + ins_lakh_spaced = pynutil.insert(" " + lakh) + ins_lakha_digit = pynutil.insert(magnitude["lakh_before_digit"]) + ins_lakhs_plural = pynutil.insert(" " + magnitude["lakhs_plural"]) + ins_lakhs_before = pynutil.insert(" " + magnitude["lakhs_before"]) + ins_crore = pynutil.insert(crore) + ins_crore_spaced = pynutil.insert(" " + crore) + ins_crores_plural = pynutil.insert(" " + magnitude["crores_plural"]) + ins_crores_before = pynutil.insert(" " + magnitude["crores_before"]) + + digit_en = (NEMO_DIGIT @ digit).optimize() + digit_te = (NEMO_TE_DIGIT @ digit).optimize() + ties_en = (NEMO_DIGIT @ ties).optimize() + ties_te = (NEMO_TE_DIGIT @ ties).optimize() + + teens_ties_en = teens_en | (ties_en + pynutil.delete("0")) | (ties_en + insert_space + digit_en) + teens_ties_te = teens_te | (ties_te + pynutil.delete("౦")) | (ties_te + insert_space + digit_te) + teens_ties = pynini.union(teens_ties_te, teens_ties_en) + + single_digit_graph = digit | zero + self.single_digits_graph = single_digit_graph + pynini.closure(insert_space + single_digit_graph) + + delete_zero = pynutil.delete(NEMO_ALL_ZERO) + + zero_pow = {0: pynini.accep("")} + for _n in range(1, 8): + zero_pow[_n] = (zero_pow[_n - 1] + delete_zero).optimize() + + def create_graph_suffix(digit_graph, suffix, zeros_counts): + if zeros_counts == 0: + return digit_graph + suffix + + return digit_graph + zero_pow[zeros_counts] + suffix + + def create_larger_number_graph(digit_graph, suffix, zeros_counts, sub_graph): + if zeros_counts == 0: + return digit_graph + suffix + insert_space + sub_graph + + return digit_graph + suffix + zero_pow[zeros_counts] + insert_space + sub_graph + + def build_group(prefix, rung_suffix, ladder, head_suffix=None, head_zeros=None): + """Union over a "ladder" of (zeros_count, remainder_graph) rungs.""" + graph = create_graph_suffix(prefix, head_suffix, head_zeros) if head_suffix is not None else None + for zeros, sub in ladder: + rung = create_larger_number_graph(prefix, rung_suffix, zeros, sub) + graph = rung if graph is None else graph | rung + return graph + + one_digit = pynini.union("1", "౧") + digit_except_one = (pynini.difference(NEMO_ALL_DIGIT, NEMO_ALL_ZERO | one_digit) @ digit).optimize() + + one_prefix = pynutil.delete(one_digit) + + graph_hundreds = pynini.cross("100", hundred) | pynini.cross("౧౦౦", hundred) + graph_hundreds |= (pynini.cross("10", hundred_prefix) | pynini.cross("౧౦", hundred_prefix)) + digit + graph_hundreds |= (pynini.cross("1", hundred_prefix) | pynini.cross("౧", hundred_prefix)) + teens_ties + graph_hundreds |= create_graph_suffix(digit_except_one, ins_hundreds_plural, 2) + graph_hundreds |= create_larger_number_graph(digit_except_one, ins_hundreds_before, 1, digit) + graph_hundreds |= create_larger_number_graph(digit_except_one, ins_hundreds_before, 0, teens_ties) + graph_hundreds = graph_hundreds.optimize() + + thousand_ladder = [ + (2, digit), + (1, teens_ties), + (0, graph_hundreds), + ] + + graph_thousands = pynini.cross("1000", thousand) | pynini.cross("౧౦౦౦", thousand) + graph_thousands |= build_group(one_prefix, ins_thousand, thousand_ladder) + graph_thousands |= build_group( + digit_except_one, ins_thousands_before, thousand_ladder, head_suffix=ins_thousands_plural, head_zeros=3 + ) + graph_thousands = graph_thousands.optimize() + + graph_ten_thousands = build_group( + teens_ties_thousand, ins_thousands_before, thousand_ladder, head_suffix=ins_thousand_spaced, head_zeros=3 + ) + graph_ten_thousands |= build_group( + teens_ties, ins_thousands_before, thousand_ladder, head_suffix=ins_thousands_plural, head_zeros=3 + ) + graph_ten_thousands = graph_ten_thousands.optimize() + + lakh_ladder = [ + (4, digit), + (3, teens_ties), + (2, graph_hundreds), + (1, graph_thousands), + (0, graph_ten_thousands), + ] + + graph_lakhs = pynini.cross("100000", lakh) | pynini.cross("౧౦౦౦౦౦", lakh) + graph_lakhs |= create_larger_number_graph(one_prefix, ins_lakha_digit, 4, digit) + graph_lakhs |= build_group(one_prefix, ins_lakh, lakh_ladder[1:]) + graph_lakhs |= build_group( + digit_except_one, ins_lakhs_before, lakh_ladder, head_suffix=ins_lakhs_plural, head_zeros=5 + ) + graph_lakhs = graph_lakhs.optimize() + + graph_ten_lakhs = build_group( + teens_ties_thousand, ins_lakhs_before, lakh_ladder, head_suffix=ins_lakh_spaced, head_zeros=5 + ) + graph_ten_lakhs |= build_group( + teens_ties, ins_lakhs_before, lakh_ladder, head_suffix=ins_lakhs_plural, head_zeros=5 + ) + graph_ten_lakhs = graph_ten_lakhs.optimize() + + crore_ladder = [ + (6, digit), + (5, teens_ties), + (4, graph_hundreds), + (3, graph_thousands), + (2, graph_ten_thousands), + (1, graph_lakhs), + (0, graph_ten_lakhs), + ] + + graph_crores = pynini.cross("10000000", crore) | pynini.cross("౧౦౦౦౦౦౦౦", crore) + graph_crores |= build_group(one_prefix, ins_crore, crore_ladder) + graph_crores |= build_group( + digit_except_one, ins_crores_before, crore_ladder, head_suffix=ins_crores_plural, head_zeros=7 + ) + graph_crores = graph_crores.optimize() + + graph_ten_crores = build_group( + teens_ties_thousand, ins_crore_spaced, crore_ladder, head_suffix=ins_crore_spaced, head_zeros=7 + ) + graph_ten_crores |= build_group( + teens_ties, ins_crores_before, crore_ladder, head_suffix=ins_crores_plural, head_zeros=7 + ) + graph_ten_crores = graph_ten_crores.optimize() + + hundred_crore_prefix = ( + pynini.cross("100", hundred) + | pynini.cross("౧౦౦", hundred) + | ((pynini.cross("10", hundred_prefix) | pynini.cross("౧౦", hundred_prefix)) + digit) + | ((pynini.cross("1", hundred_prefix) | pynini.cross("౧", hundred_prefix)) + teens_ties) + | create_graph_suffix(digit_except_one, ins_hundreds_before, 2) + | create_larger_number_graph(digit_except_one, ins_hundreds_before, 1, digit_except_one) + | create_larger_number_graph(digit_except_one, ins_hundreds_before, 0, teens_ties) + ).optimize() + + hundred_one_crore_prefix = ( + digit_except_one + + pynutil.delete(NEMO_ALL_ZERO | pynini.accep("౦")) + + (pynini.cross("1", hundreds_before_one) | pynini.cross("౧", hundreds_before_one)) + ) + + graph_arabs = build_group( + hundred_one_crore_prefix, ins_crore_spaced, crore_ladder, head_suffix=ins_crore_spaced, head_zeros=7 + ) + graph_arabs |= build_group( + hundred_crore_prefix, ins_crores_before, crore_ladder, head_suffix=ins_crores_plural, head_zeros=7 + ) + graph_arabs |= create_larger_number_graph(hundred_crore_prefix, ins_crores_before, 0, graph_crores) + graph_arabs = graph_arabs.optimize() + + thousand_crore_ladder = [ + (2, digit), + (1, teens_ties), + (0, hundred_crore_prefix), + ] + + thousand_crore_prefix = ( + pynini.cross("1000", thousand) + | pynini.cross("౧౦౦౦", thousand) + | build_group( + digit_except_one, + ins_thousands_before, + thousand_crore_ladder, + head_suffix=ins_thousands_before, + head_zeros=3, + ) + | build_group(one_prefix, ins_thousand, thousand_crore_ladder) + ).optimize() + + ten_thousand_crore_prefix = ( + build_group( + teens_ties_thousand, + ins_thousands_before, + thousand_crore_ladder, + head_suffix=ins_thousand_spaced, + head_zeros=3, + ) + | build_group( + teens_ties, ins_thousands_before, thousand_crore_ladder, head_suffix=ins_thousands_before, head_zeros=3 + ) + ).optimize() + + crore_count_prefix = (thousand_crore_prefix | ten_thousand_crore_prefix).optimize() + + graph_ten_arabs = pynutil.add_weight( + build_group( + crore_count_prefix, ins_crores_before, crore_ladder, head_suffix=ins_crores_plural, head_zeros=7 + ), + -0.1, + ).optimize() + + graph_kharabs = pynutil.add_weight( + build_group( + ten_thousand_crore_prefix, ins_crores_before, crore_ladder, head_suffix=ins_crores_plural, head_zeros=7 + ), + -0.2, + ).optimize() + + lakh_crore_ladder = [ + (4, digit), + (3, teens_ties), + (2, graph_hundreds), + (1, graph_thousands), + (0, ten_thousand_crore_prefix), + ] + + lakh_crore_prefix = ( + pynini.cross("100000", lakh) + | pynini.cross("౧౦౦౦౦౦", lakh) + | build_group(one_prefix, ins_lakh, lakh_crore_ladder) + | build_group( + digit_except_one, ins_lakhs_before, lakh_crore_ladder, head_suffix=ins_lakhs_before, head_zeros=5 + ) + ).optimize() + + ten_lakh_crore_prefix = ( + build_group( + teens_ties_thousand, ins_lakhs_before, lakh_crore_ladder, head_suffix=ins_lakh_spaced, head_zeros=5 + ) + | build_group(teens_ties, ins_lakhs_before, lakh_crore_ladder, head_suffix=ins_lakhs_before, head_zeros=5) + ).optimize() + + lakh_crore_count_prefix = (lakh_crore_prefix | ten_lakh_crore_prefix).optimize() + + graph_ten_kharabs = pynutil.add_weight( + build_group( + lakh_crore_count_prefix, ins_crores_before, crore_ladder, head_suffix=ins_crores_plural, head_zeros=7 + ), + -0.3, + ).optimize() + + graph_nils = pynutil.add_weight( + build_group( + lakh_crore_count_prefix, ins_crores_before, crore_ladder, head_suffix=ins_crores_plural, head_zeros=7 + ), + -0.4, + ).optimize() + + ten_nil_lakh_remainder_before_kotlu = build_group( + teens_ties, ins_lakhs_before, lakh_ladder, head_suffix=ins_lakhs_before, head_zeros=5 + ).optimize() + + koti_ladder = [ + (6, digit), + (5, teens_ties), + (4, graph_hundreds), + (3, graph_thousands), + (2, graph_ten_thousands), + (1, graph_lakhs), + (0, ten_nil_lakh_remainder_before_kotlu), + ] + + ten_nil_crore_count_prefix = ( + graph_crores + | graph_ten_crores + | create_larger_number_graph(one_prefix, ins_crore, 0, ten_nil_lakh_remainder_before_kotlu) + | create_larger_number_graph(digit_except_one, ins_crores_before, 0, ten_nil_lakh_remainder_before_kotlu) + | create_larger_number_graph(teens_ties, ins_crores_before, 0, ten_nil_lakh_remainder_before_kotlu) + ).optimize() + + graph_ten_nils = pynutil.add_weight( + build_group( + ten_nil_crore_count_prefix, + ins_crores_before, + crore_ladder, + head_suffix=ins_crores_plural, + head_zeros=7, + ), + -0.5, + ).optimize() + + padma_crore_count_prefix = ( + build_group(teens_ties_thousand, ins_crore_spaced, koti_ladder, head_suffix=ins_crore_spaced, head_zeros=7) + | build_group(teens_ties, ins_crore_spaced, koti_ladder, head_suffix=ins_crore_spaced, head_zeros=7) + ).optimize() + + graph_padmas = pynutil.add_weight( + build_group( + padma_crore_count_prefix, ins_crores_before, crore_ladder, head_suffix=ins_crores_plural, head_zeros=7 + ), + -0.6, + ).optimize() + + ten_padma_one_crore_count_prefix = create_graph_suffix( + hundred_one_crore_prefix, ins_crore_spaced, 7 + ).optimize() + + ten_padma_crore_count_prefix = ( + ten_padma_one_crore_count_prefix + | build_group( + hundred_crore_prefix, ins_crore_spaced, koti_ladder, head_suffix=ins_crore_spaced, head_zeros=7 + ) + ).optimize() + + graph_ten_padmas = pynutil.add_weight( + build_group( + ten_padma_crore_count_prefix, + ins_crores_before, + crore_ladder, + head_suffix=ins_crores_plural, + head_zeros=7, + ), + -0.7, + ).optimize() + + shankh_koti_count_prefix = build_group( + crore_count_prefix, ins_crore_spaced, koti_ladder, head_suffix=ins_crore_spaced, head_zeros=7 + ).optimize() + + graph_shankhs = pynutil.add_weight( + build_group( + shankh_koti_count_prefix, ins_crores_before, crore_ladder, head_suffix=ins_crores_plural, head_zeros=7 + ), + -0.8, + ).optimize() + + graph_without_leading_zeros = ( + digit + | zero + | teens_ties + | graph_hundreds + | graph_thousands + | graph_ten_thousands + | graph_lakhs + | graph_ten_lakhs + | graph_crores + | graph_ten_crores + | graph_arabs + | graph_ten_arabs + | graph_kharabs + | graph_ten_kharabs + | graph_nils + | graph_ten_nils + | graph_padmas + | graph_ten_padmas + | graph_shankhs + ) + + cardinal_with_leading_zeros = pynini.compose( + NEMO_ALL_ZERO + pynini.closure(NEMO_ALL_DIGIT), self.single_digits_graph + ) + + final_graph = graph_without_leading_zeros | cardinal_with_leading_zeros + + optional_minus_graph = pynini.closure(pynutil.insert("negative: ") + pynini.cross("-", "\"true\" "), 0, 1) + + self.final_graph = final_graph.optimize() + final_graph = optional_minus_graph + pynutil.insert("integer: \"") + self.final_graph + pynutil.insert("\"") + final_graph = self.add_tokens(final_graph) + self.fst = final_graph diff --git a/nemo_text_processing/text_normalization/te/taggers/punctuation.py b/nemo_text_processing/text_normalization/te/taggers/punctuation.py new file mode 100644 index 000000000..47c5c5314 --- /dev/null +++ b/nemo_text_processing/text_normalization/te/taggers/punctuation.py @@ -0,0 +1,62 @@ +# Copyright (c) 2026, NVIDIA CORPORATION. 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 sys +from unicodedata import category + +import pynini +from pynini.examples import plurals +from pynini.lib import pynutil + +from nemo_text_processing.text_normalization.te.graph_utils import NEMO_NOT_SPACE, NEMO_SIGMA, GraphFst + + +class PunctuationFst(GraphFst): + """ + Finite state transducer for classifying punctuation + e.g. a, -> tokens { name: "a" } tokens { name: "," } + + Args: + deterministic: if True will provide a single transduction option, + for False multiple transductions are generated (used for audio-based normalization) + """ + + def __init__(self, deterministic: bool = True): + super().__init__(name="punctuation", kind="classify", deterministic=deterministic) + s = "!#%&\'()*+,-./:;<=>?@^_`{|}~\"" + + punct_symbols_to_exclude = ["[", "]"] + punct_unicode = [ + chr(i) + for i in range(sys.maxunicode) + if category(chr(i)).startswith("P") and chr(i) not in punct_symbols_to_exclude + ] + + self.punct_marks = [p for p in punct_unicode + list(s)] + + punct = pynini.union(*self.punct_marks) + punct = pynini.closure(punct, 1) + + emphasis = ( + pynini.accep("<") + + pynini.union( + (pynini.closure(NEMO_NOT_SPACE - pynini.union("<", ">"), 1) + pynini.closure(pynini.accep("/"), 0, 1)), + (pynini.accep("/") + pynini.closure(NEMO_NOT_SPACE - pynini.union("<", ">"), 1)), + ) + + pynini.accep(">") + ) + punct = plurals._priority_union(emphasis, punct, NEMO_SIGMA) + + self.graph = punct + self.fst = (pynutil.insert("name: \"") + self.graph + pynutil.insert("\"")).optimize() diff --git a/nemo_text_processing/text_normalization/te/taggers/tokenize_and_classify.py b/nemo_text_processing/text_normalization/te/taggers/tokenize_and_classify.py new file mode 100644 index 000000000..c2b1d07fb --- /dev/null +++ b/nemo_text_processing/text_normalization/te/taggers/tokenize_and_classify.py @@ -0,0 +1,115 @@ +# Copyright (c) 2026, NVIDIA CORPORATION. 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 logging +import os + +import pynini +from pynini.lib import pynutil + +from nemo_text_processing.text_normalization.te.graph_utils import ( + NEMO_SPACE, + NEMO_WHITE_SPACE, + GraphFst, + delete_extra_space, + delete_space, + generator_main, +) +from nemo_text_processing.text_normalization.te.taggers.cardinal import CardinalFst +from nemo_text_processing.text_normalization.te.taggers.punctuation import PunctuationFst +from nemo_text_processing.text_normalization.te.taggers.word import WordFst + + +class ClassifyFst(GraphFst): + """ + Final class that composes all other classification grammars. This class can process an entire sentence including punctuation. + For deployment, this grammar will be compiled and exported to OpenFst Finite State Archive (FAR) File. + More details to deployment at NeMo/tools/text_processing_deployment. + + Args: + input_case: accepting either "lower_cased" or "cased" input. + deterministic: if True will provide a single transduction option, + for False multiple options (used for audio-based normalization) + cache_dir: path to a dir with .far grammar file. Set to None to avoid using cache. + overwrite_cache: set to True to overwrite .far files + whitelist: path to a file with whitelist replacements + """ + + def __init__( + self, + input_case: str, + deterministic: bool = True, + cache_dir: str = None, + overwrite_cache: bool = False, + whitelist: str = None, + ): + super().__init__(name="tokenize_and_classify", kind="classify", deterministic=deterministic) + + far_file = None + if cache_dir is not None and cache_dir != "None": + os.makedirs(cache_dir, exist_ok=True) + whitelist_file = os.path.basename(whitelist) if whitelist else "" + far_file = os.path.join( + cache_dir, + f"te_tn_{deterministic}_deterministic_{input_case}_{whitelist_file}_tokenize.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"] + logging.info(f"ClassifyFst.fst was restored from {far_file}.") + else: + logging.info(f"Creating ClassifyFst grammars.") + + cardinal = CardinalFst(deterministic=deterministic) + cardinal_graph = cardinal.fst + + punctuation = PunctuationFst(deterministic=deterministic) + punct_graph = punctuation.fst + + classify = pynutil.add_weight(cardinal_graph, 1.1) + + word_graph = WordFst(punctuation=punctuation, deterministic=deterministic).fst + + punct = pynutil.insert("tokens { ") + pynutil.add_weight(punct_graph, weight=2.1) + pynutil.insert(" }") + punct = pynini.closure( + pynini.union( + pynini.compose(pynini.closure(NEMO_WHITE_SPACE, 1), delete_extra_space), + (pynutil.insert(NEMO_SPACE) + punct), + ), + 1, + ) + + classify = pynini.union(classify, pynutil.add_weight(word_graph, 100)) + token = pynutil.insert("tokens { ") + classify + pynutil.insert(" }") + token_plus_punct = ( + pynini.closure(punct + pynutil.insert(NEMO_SPACE)) + + token + + pynini.closure(pynutil.insert(NEMO_SPACE) + punct) + ) + + graph = token_plus_punct + pynini.closure( + pynini.union( + pynini.compose(pynini.closure(NEMO_WHITE_SPACE, 1), delete_extra_space), + (pynutil.insert(NEMO_SPACE) + punct + pynutil.insert(NEMO_SPACE)), + ) + + token_plus_punct + ) + + graph = delete_space + graph + delete_space + graph = pynini.union(graph, punct) + + self.fst = graph.optimize() + + if far_file: + generator_main(far_file, {"tokenize_and_classify": self.fst}) + logging.info(f"ClassifyFst grammars are saved to {far_file}.") diff --git a/nemo_text_processing/text_normalization/te/taggers/word.py b/nemo_text_processing/text_normalization/te/taggers/word.py new file mode 100644 index 000000000..2d73e412b --- /dev/null +++ b/nemo_text_processing/text_normalization/te/taggers/word.py @@ -0,0 +1,61 @@ +# Copyright (c) 2026, NVIDIA CORPORATION. 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.te.graph_utils import ( + MIN_NEG_WEIGHT, + NEMO_NOT_SPACE, + GraphFst, + convert_space, +) +from nemo_text_processing.text_normalization.te.taggers.punctuation import PunctuationFst + + +class WordFst(GraphFst): + """ + Finite state transducer for classifying Telugu words. + e.g. సోనా -> tokens { name: "సోనా" } + + Args: + punctuation: PunctuationFst + deterministic: if True will provide a single transduction option, + for False multiple transductions are generated (used for audio-based normalization) + """ + + def __init__(self, punctuation: PunctuationFst, deterministic: bool = True): + super().__init__(name="word", kind="classify", deterministic=deterministic) + + # Define Telugu characters and symbols using pynini.union + TELUGU_CHAR = pynini.union( + *[chr(i) for i in range(0x0C00, 0x0C03 + 1)], # Telugu signs (Anusvara, Visarga) + *[chr(i) for i in range(0x0C05, 0x0C39 + 1)], # Telugu vowels and consonants + *[chr(i) for i in range(0x0C3E, 0x0C4D + 1)], # Telugu vowel signs (diacritics) and Virama + ).optimize() + + # Include punctuation in the graph + punct = punctuation.graph + default_graph = pynini.closure(pynini.difference(NEMO_NOT_SPACE, punct.project("input")), 1) + symbols_to_exclude = (pynini.union("$", "€", "₩", "£", "¥", "#", "%") | punct).optimize() + + # Use TELUGU_CHAR in the graph + graph = pynini.closure(pynini.difference(TELUGU_CHAR, symbols_to_exclude), 1) + graph = pynutil.add_weight(graph, MIN_NEG_WEIGHT) | default_graph + + # Ensure no spaces around punctuation + graph = pynini.closure(graph + pynini.closure(punct + graph, 0, 1)) + + self.graph = convert_space(graph) + self.fst = (pynutil.insert("name: \"") + self.graph + pynutil.insert("\"")).optimize() diff --git a/nemo_text_processing/text_normalization/te/utils.py b/nemo_text_processing/text_normalization/te/utils.py new file mode 100644 index 000000000..2bcba780d --- /dev/null +++ b/nemo_text_processing/text_normalization/te/utils.py @@ -0,0 +1,27 @@ +# Copyright (c) 2026, NVIDIA CORPORATION. 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/te/verbalizers/__init__.py b/nemo_text_processing/text_normalization/te/verbalizers/__init__.py new file mode 100644 index 000000000..4fc25d0d3 --- /dev/null +++ b/nemo_text_processing/text_normalization/te/verbalizers/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2026, NVIDIA CORPORATION. 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/te/verbalizers/cardinal.py b/nemo_text_processing/text_normalization/te/verbalizers/cardinal.py new file mode 100644 index 000000000..bf00734c3 --- /dev/null +++ b/nemo_text_processing/text_normalization/te/verbalizers/cardinal.py @@ -0,0 +1,49 @@ +# Copyright (c) 2026, NVIDIA CORPORATION. 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.te.graph_utils import NEMO_NOT_QUOTE, GraphFst, delete_space + + +class CardinalFst(GraphFst): + """ + Finite state transducer for verbalizing cardinal, e.g. + cardinal { negative: "true" integer: "23" } -> minus twenty three + + 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="cardinal", kind="verbalize", deterministic=deterministic) + + self.optional_sign = pynini.cross("negative: \"true\"", "minus ") + if not deterministic: + self.optional_sign |= pynini.cross("negative: \"true\"", "negative ") + self.optional_sign |= pynini.cross("negative: \"true\"", "dash ") + + self.optional_sign = pynini.closure(self.optional_sign + delete_space, 0, 1) + + integer = pynini.closure(NEMO_NOT_QUOTE) + + self.integer = delete_space + pynutil.delete("\"") + integer + pynutil.delete("\"") + integer = pynutil.delete("integer:") + self.integer + + self.numbers = self.optional_sign + integer + delete_tokens = self.delete_tokens(self.numbers) + + self.fst = delete_tokens.optimize() diff --git a/nemo_text_processing/text_normalization/te/verbalizers/post_processing.py b/nemo_text_processing/text_normalization/te/verbalizers/post_processing.py new file mode 100644 index 000000000..6dd341b1d --- /dev/null +++ b/nemo_text_processing/text_normalization/te/verbalizers/post_processing.py @@ -0,0 +1,96 @@ +# 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.te.graph_utils import ( + MIN_NEG_WEIGHT, + NEMO_CHAR, + NEMO_SIGMA, + generator_main, +) +from nemo_text_processing.text_normalization.te.taggers.punctuation import PunctuationFst +from nemo_text_processing.utils.logging import logger + + +class PostProcessingFst: + """ + Finite state transducer that post-processing an entire sentence after verbalization is complete, e.g. + removes extra spaces around punctuation marks " ( one hundred and twenty three ) " -> "(one hundred and twenty three)" + + Args: + 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, cache_dir: str = None, overwrite_cache: bool = False): + + 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, "te_tn_post_processing.far") + if not overwrite_cache and far_file and os.path.exists(far_file): + self.fst = pynini.Far(far_file, mode="r")["post_process_graph"] + logger.info(f'Post processing graph was restored from {far_file}.') + else: + self.fst = self.get_punct_postprocess_graph() + + if far_file: + generator_main(far_file, {"post_process_graph": self.fst}) + + def get_punct_postprocess_graph(self): + """ + Returns graph to post process punctuation marks. + + By default, spaces are removed before punctuation marks like comma, period, etc. + """ + punct_marks_all = PunctuationFst().punct_marks + + # Punctuation marks that should NOT have space before them + # (most punctuation except quotes, dashes, and opening brackets) + quotes = ["'", "\"", "«"] + dashes = ["-", "—"] + brackets = ["<", "{", "(", r"\["] + allow_space_before_punct = quotes + dashes + brackets + + no_space_before_punct = [m for m in punct_marks_all if m not in allow_space_before_punct] + # Add Telugu-specific punctuation + no_space_before_punct.extend(["।", ",", ".", ";", ":", "!", "?"]) + # Remove duplicates + no_space_before_punct = list(set(no_space_before_punct)) + no_space_before_punct = pynini.union(*no_space_before_punct) + + delete_space = pynutil.delete(" ") + + # Delete space before no_space_before_punct marks + non_punct = pynini.difference(NEMO_CHAR, no_space_before_punct).optimize() + graph = ( + pynini.closure(non_punct) + + pynini.closure( + no_space_before_punct | pynutil.add_weight(delete_space + no_space_before_punct, MIN_NEG_WEIGHT) + ) + + pynini.closure(non_punct) + ) + graph = pynini.closure(graph).optimize() + + # Remove space after opening brackets + no_space_after_punct = pynini.union(*brackets) + no_space_after_punct = pynini.cdrewrite(delete_space, no_space_after_punct, NEMO_SIGMA, NEMO_SIGMA).optimize() + graph = pynini.compose(graph, no_space_after_punct).optimize() + + return graph diff --git a/nemo_text_processing/text_normalization/te/verbalizers/verbalize.py b/nemo_text_processing/text_normalization/te/verbalizers/verbalize.py new file mode 100644 index 000000000..f2564e504 --- /dev/null +++ b/nemo_text_processing/text_normalization/te/verbalizers/verbalize.py @@ -0,0 +1,38 @@ +# Copyright (c) 2026, NVIDIA CORPORATION. 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.te.graph_utils import GraphFst +from nemo_text_processing.text_normalization.te.verbalizers.cardinal import CardinalFst + + +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) + cardinal_graph = cardinal.fst + + graph = cardinal_graph + + self.fst = graph diff --git a/nemo_text_processing/text_normalization/te/verbalizers/verbalize_final.py b/nemo_text_processing/text_normalization/te/verbalizers/verbalize_final.py new file mode 100644 index 000000000..ee41577c6 --- /dev/null +++ b/nemo_text_processing/text_normalization/te/verbalizers/verbalize_final.py @@ -0,0 +1,76 @@ +# Copyright (c) 2026, NVIDIA CORPORATION. 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 logging +import os + +import pynini +from pynini.lib import pynutil + +from nemo_text_processing.text_normalization.te.graph_utils import ( + GraphFst, + delete_extra_space, + delete_space, + generator_main, +) +from nemo_text_processing.text_normalization.te.verbalizers.verbalize import VerbalizeFst +from nemo_text_processing.text_normalization.te.verbalizers.word import WordFst + + +class VerbalizeFinalFst(GraphFst): + """ + Finite state transducer that verbalizes an entire sentence, e.g. + tokens { name: "its" } tokens { time { hours: "twelve" minutes: "thirty" } } tokens { name: "now" } tokens { name: "." } -> its twelve thirty now . + + 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"en_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"] + logging.info(f'VerbalizeFinalFst graph was restored from {far_file}.') + else: + verbalize = VerbalizeFst(deterministic=deterministic).fst + word = WordFst(deterministic=deterministic).fst + types = verbalize | word + + if deterministic: + graph = ( + pynutil.delete("tokens") + + delete_space + + pynutil.delete("{") + + delete_space + + types + + delete_space + + pynutil.delete("}") + ) + else: + graph = delete_space + types + delete_space + + 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}) + logging.info(f"VerbalizeFinalFst grammars are saved to {far_file}.") diff --git a/nemo_text_processing/text_normalization/te/verbalizers/word.py b/nemo_text_processing/text_normalization/te/verbalizers/word.py new file mode 100644 index 000000000..cb4f41784 --- /dev/null +++ b/nemo_text_processing/text_normalization/te/verbalizers/word.py @@ -0,0 +1,43 @@ +# Copyright (c) 2026, NVIDIA CORPORATION. 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.te.graph_utils import NEMO_CHAR, NEMO_SIGMA, GraphFst, delete_space + + +class WordFst(GraphFst): + """ + Finite state transducer for verbalizing Telugu words. + e.g. tokens { name: "ఏడు" } -> ఏడు + + 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="verbalize", deterministic=deterministic) + chars = pynini.closure(NEMO_CHAR - " ", 1) + punct = pynini.union("!", "?", ".", ",", "-", ":", ";", "।") # Add other punctuation marks as needed + char = pynutil.delete("name:") + delete_space + pynutil.delete("\"") + chars + pynutil.delete("\"") + + # Ensure no spaces around punctuation + graph = char + pynini.closure(delete_space + punct, 0, 1) + + # Explicitly remove spaces before punctuation + remove_space_before_punct = pynini.cdrewrite(pynini.cross(" ", ""), "", punct, NEMO_SIGMA) + graph = graph @ remove_space_before_punct + + self.fst = graph.optimize() diff --git a/tests/nemo_text_processing/te/__init__.py b/tests/nemo_text_processing/te/__init__.py new file mode 100644 index 000000000..4fc25d0d3 --- /dev/null +++ b/tests/nemo_text_processing/te/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2026, NVIDIA CORPORATION. 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/te/data_text_normalization/test_cases_cardinal.txt b/tests/nemo_text_processing/te/data_text_normalization/test_cases_cardinal.txt new file mode 100644 index 000000000..068c67f66 --- /dev/null +++ b/tests/nemo_text_processing/te/data_text_normalization/test_cases_cardinal.txt @@ -0,0 +1,51 @@ +4 నాలుగులు~నాలుగు నాలుగులు +౬ మంది ఆటగాళ్లు బయటకు~ఆరు మంది ఆటగాళ్లు బయటకు +4 ఓవర్లలో 17 పరుగులు~నాలుగు ఓవర్లలో పదిహేడు పరుగులు +౫ చాక్లెట్లు ౯ టాఫీలు~ఐదు చాక్లెట్లు తొమ్మిది టాఫీలు +10099~పది వేల తొంభై తొమ్మిది +100001~లక్షా ఒకటి +౫ నాలుగులు~ఐదు నాలుగులు +4 మంది మృతి 18 మందికి గాయాలు~నాలుగు మంది మృతి పధ్ధెనిమిది మందికి గాయాలు +51022345567~ఐదు వేల నూట రెండు కోట్ల ఇరవై మూడు లక్షల నలభై ఐదు వేల ఐదు వందల అరవై ఏడు +అధ్యాయం ౧౦ శ్లోకం ౨~అధ్యాయం పది శ్లోకం రెండు +101~నూట ఒకటి +100~వంద +౧౦౦~వంద +౧౦౫~నూట ఐదు +200~రెండు వందలు +౨౦౦~రెండు వందలు +203~రెండు వందల మూడు +౫౦౨~ఐదు వందల రెండు +111~నూట పదకొండు +౧౧౯~నూట పంతొమ్మిది +130~నూట ముప్పై +౧౫౦~నూట యాభై +312~మూడు వందల పన్నెండు +౫౨౫~ఐదు వందల ఇరవై ఐదు +425~నాలుగు వందల ఇరవై ఐదు +౯౧౫~తొమ్మిది వందల పదిహేను +1001~వెయ్యి ఒకటి +5551 అరటిపండ్లు~ఐదు వేల ఐదు వందల యాభై ఒకటి అరటిపండ్లు +౫౫౫౧ అరటిపండ్లు~ఐదు వేల ఐదు వందల యాభై ఒకటి అరటిపండ్లు +85~ఎనభై ఐదు +౯౧~తొంభై ఒకటి +౧౩౨౩~వెయ్యి మూడు వందల ఇరవై మూడు +1345~వెయ్యి మూడు వందల నలభై ఐదు +౧౩౪౫౬~పదమూడు వేల నాలుగు వందల యాభై ఆరు +12346~పన్నెండు వేల మూడు వందల నలభై ఆరు +౧౨౩౪౫౬~లక్ష ఇరవై మూడు వేల నాలుగు వందల యాభై ఆరు +872987~ఎనిమిది లక్షల డెబ్బై రెండు వేల తొమ్మిది వందల ఎనభై ఏడు +౯౮౭౬౦౯~తొమ్మిది లక్షల ఎనభై ఏడు వేల ఆరు వందల తొమ్మిది +9876789~తొంభై ఎనిమిది లక్షల డెబ్బై ఆరు వేల ఏడు వందల ఎనభై తొమ్మిది +౨౩౪౫౫౬౭~ఇరవై మూడు లక్షల నలభై ఐదు వేల ఐదు వందల అరవై ఏడు +12345567~కోటి ఇరవై మూడు లక్షల నలభై ఐదు వేల ఐదు వందల అరవై ఏడు +౧౨౧౨౧౨౧౨~కోటి ఇరవై ఒక లక్షల ఇరవై ఒక వేల రెండు వందల పన్నెండు +1122345567~నూట పన్నెండు కోట్ల ఇరవై మూడు లక్షల నలభై ఐదు వేల ఐదు వందల అరవై ఏడు +౧౦౨౨౩౪౫౫౬౭~నూట రెండు కోట్ల ఇరవై మూడు లక్షల నలభై ఐదు వేల ఐదు వందల అరవై ఏడు +11022345567~వెయ్యి నూట రెండు కోట్ల ఇరవై మూడు లక్షల నలభై ఐదు వేల ఐదు వందల అరవై ఏడు +౫౧౦౨౨౩౪౫౫౬౭~ఐదు వేల నూట రెండు కోట్ల ఇరవై మూడు లక్షల నలభై ఐదు వేల ఐదు వందల అరవై ఏడు +౦౫~సున్నా ఐదు +01~సున్నా ఒకటి +౦౭౩~సున్నా ఏడు మూడు +0001~సున్నా సున్నా సున్నా ఒకటి +౦౦౦~సున్నా సున్నా సున్నా diff --git a/tests/nemo_text_processing/te/test_cardinal.py b/tests/nemo_text_processing/te/test_cardinal.py new file mode 100644 index 000000000..799cf29c4 --- /dev/null +++ b/tests/nemo_text_processing/te/test_cardinal.py @@ -0,0 +1,37 @@ +# Copyright (c) 2026, NVIDIA CORPORATION. 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 = Normalizer( + input_case='cased', + lang='te', + cache_dir=CACHE_DIR, + overwrite_cache=False, + post_process=False, + ) + + @parameterized.expand(parse_test_case_file('te/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.normalize(test_input, verbose=False) + assert pred.strip() == expected.strip() diff --git a/tests/nemo_text_processing/te/test_sparrowhawk_normalization.sh b/tests/nemo_text_processing/te/test_sparrowhawk_normalization.sh new file mode 100644 index 000000000..01b3b5260 --- /dev/null +++ b/tests/nemo_text_processing/te/test_sparrowhawk_normalization.sh @@ -0,0 +1,36 @@ +#! /bin/sh + +PROJECT_DIR=/workspace/tests + +runtest () { + input=$1 + cd /workspace/sparrowhawk/documentation/grammars + + # read test file + while IFS= read -r testcase; do + IFS='~' read -r written spoken <<< "$testcase" + + # Escape backslashes and replace non breaking space with breaking space + escaped_written=$(printf '%s' "$written" | sed 's/\\/\\\\/g') + denorm_pred=$(echo "$escaped_written" | normalizer_main --config=sparrowhawk_configuration.ascii_proto 2>&1 | tail -n 1 | sed 's/\xC2\xA0/ /g') + + # 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:]]*$//')" + + # trim white space and remove space before punctuation + spoken="$(echo -e "${spoken}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's/ \([!?.]\)/\1/g')" + denorm_pred="$(echo -e "${denorm_pred}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's/ \([!?.]\)/\1/g')" + + # input expected actual + assertEquals "$written" "$spoken" "$denorm_pred" + done < "$input" +} + +testTNCardinal() { + input=$PROJECT_DIR/te/data_text_normalization/test_cases_cardinal.txt + runtest $input +} + +# Load shUnit2 +. $PROJECT_DIR/../shunit2/shunit2 diff --git a/tools/text_processing_deployment/pynini_export.py b/tools/text_processing_deployment/pynini_export.py index 73a4fc138..4146dd4b6 100644 --- a/tools/text_processing_deployment/pynini_export.py +++ b/tools/text_processing_deployment/pynini_export.py @@ -109,6 +109,7 @@ def parse_args(): 'ja', 'rw', 'ko', + 'te', ], type=str, default='en', @@ -224,6 +225,20 @@ def parse_args(): PostProcessingFst as TNPostProcessingFst, ) from nemo_text_processing.text_normalization.hi.verbalizers.verbalize import VerbalizeFst as TNVerbalizeFst + elif args.language == 'te': + # from nemo_text_processing.inverse_text_normalization.te.taggers.tokenize_and_classify import ( + # ClassifyFst as ITNClassifyFst, + # ) + # from nemo_text_processing.inverse_text_normalization.te.verbalizers.verbalize import ( + # VerbalizeFst as ITNVerbalizeFst, + # ) + from nemo_text_processing.text_normalization.te.taggers.tokenize_and_classify import ( + ClassifyFst as TNClassifyFst, + ) + from nemo_text_processing.text_normalization.te.verbalizers.post_processing import ( + PostProcessingFst as TNPostProcessingFst, + ) + from nemo_text_processing.text_normalization.te.verbalizers.verbalize import VerbalizeFst as TNVerbalizeFst elif args.language == 'hu': from nemo_text_processing.text_normalization.hu.taggers.tokenize_and_classify import ( ClassifyFst as TNClassifyFst,