verbalize_final.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # Copyright NeMo (https://github.com/NVIDIA/NeMo). All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import os
  15. import pynini
  16. from fun_text_processing.text_normalization.de.verbalizers.verbalize import VerbalizeFst
  17. from fun_text_processing.text_normalization.en.graph_utils import (
  18. GraphFst,
  19. delete_extra_space,
  20. delete_space,
  21. generator_main,
  22. )
  23. from fun_text_processing.text_normalization.en.verbalizers.word import WordFst
  24. from pynini.lib import pynutil
  25. import logging
  26. class VerbalizeFinalFst(GraphFst):
  27. """
  28. Finite state transducer that verbalizes an entire sentence
  29. Args:
  30. deterministic: if True will provide a single transduction option,
  31. for False multiple options (used for audio-based normalization)
  32. cache_dir: path to a dir with .far grammar file. Set to None to avoid using cache.
  33. overwrite_cache: set to True to overwrite .far files
  34. """
  35. def __init__(self, deterministic: bool = True, cache_dir: str = None, overwrite_cache: bool = False):
  36. super().__init__(name="verbalize_final", kind="verbalize", deterministic=deterministic)
  37. far_file = None
  38. if cache_dir is not None and cache_dir != "None":
  39. os.makedirs(cache_dir, exist_ok=True)
  40. far_file = os.path.join(cache_dir, f"de_tn_{deterministic}_deterministic_verbalizer.far")
  41. if not overwrite_cache and far_file and os.path.exists(far_file):
  42. self.fst = pynini.Far(far_file, mode="r")["verbalize"]
  43. logging.info(f'VerbalizeFinalFst graph was restored from {far_file}.')
  44. else:
  45. verbalize = VerbalizeFst(deterministic=deterministic).fst
  46. word = WordFst(deterministic=deterministic).fst
  47. types = verbalize | word
  48. graph = (
  49. pynutil.delete("tokens")
  50. + delete_space
  51. + pynutil.delete("{")
  52. + delete_space
  53. + types
  54. + delete_space
  55. + pynutil.delete("}")
  56. )
  57. graph = delete_space + pynini.closure(graph + delete_extra_space) + graph + delete_space
  58. self.fst = graph.optimize()
  59. if far_file:
  60. generator_main(far_file, {"verbalize": self.fst})
  61. logging.info(f"VerbalizeFinalFst grammars are saved to {far_file}.")