decimal.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 pynini
  15. from fun_text_processing.text_normalization.de.taggers.decimal import quantities
  16. from fun_text_processing.text_normalization.en.graph_utils import (
  17. DAMO_NOT_QUOTE,
  18. GraphFst,
  19. delete_preserve_order,
  20. insert_space,
  21. )
  22. from pynini.lib import pynutil
  23. class DecimalFst(GraphFst):
  24. """
  25. Finite state transducer for classifying decimal, e.g.
  26. decimal { negative: "true" integer_part: "elf" fractional_part: "vier null sechs" quantity: "billionen" } -> minus elf komma vier null sechs billionen
  27. decimal { integer_part: "eins" quantity: "billion" } -> eins billion
  28. """
  29. def __init__(self, deterministic: bool = True):
  30. super().__init__(name="decimal", kind="classify", deterministic=deterministic)
  31. delete_space = pynutil.delete(" ")
  32. self.optional_sign = pynini.closure(pynini.cross("negative: \"true\"", "minus ") + delete_space, 0, 1)
  33. self.integer = pynutil.delete("integer_part: \"") + pynini.closure(DAMO_NOT_QUOTE, 1) + pynutil.delete("\"")
  34. self.fractional_default = (
  35. pynutil.delete("fractional_part: \"") + pynini.closure(DAMO_NOT_QUOTE, 1) + pynutil.delete("\"")
  36. )
  37. self.fractional = pynutil.insert(" komma ") + self.fractional_default
  38. self.quantity = (
  39. delete_space + insert_space + pynutil.delete("quantity: \"") + quantities + pynutil.delete("\"")
  40. )
  41. self.optional_quantity = pynini.closure(self.quantity, 0, 1)
  42. graph = self.optional_sign + (
  43. self.integer + self.quantity | self.integer + delete_space + self.fractional + self.optional_quantity
  44. )
  45. self.numbers = graph
  46. graph += delete_preserve_order
  47. delete_tokens = self.delete_tokens(graph)
  48. self.fst = delete_tokens.optimize()