tts_preprocessor.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. import re
  2. from num2words import num2words
  3. alphabet_map = {
  4. "A": " Ei ",
  5. "B": " Bee ",
  6. "C": " See ",
  7. "D": " Dee ",
  8. "E": " Ii ",
  9. "F": " Eff ",
  10. "G": " Jee ",
  11. "H": " Eich ",
  12. "I": " Eye ",
  13. "J": " Jay ",
  14. "K": " Kay ",
  15. "L": " El ",
  16. "M": " Emm ",
  17. "N": " Enn ",
  18. "O": " Ohh ",
  19. "P": " Pii ",
  20. "Q": " Queue ",
  21. "R": " Are ",
  22. "S": " Ess ",
  23. "T": " Tee ",
  24. "U": " You ",
  25. "V": " Vii ",
  26. "W": " Double You ",
  27. "X": " Ex ",
  28. "Y": " Why ",
  29. "Z": " Zed " # Zed is weird, as I (da3dsoul) am American, but most of the voice models sound British, so it matches
  30. }
  31. def preprocess(string):
  32. # the order for some of these matter
  33. # For example, you need to remove the commas in numbers before expanding them
  34. string = remove_surrounded_chars(string)
  35. string = string.replace('"', '')
  36. string = string.replace('“', '')
  37. string = string.replace('\n', ' ')
  38. string = convert_num_locale(string)
  39. string = replace_negative(string)
  40. string = replace_roman(string)
  41. string = hyphen_range_to(string)
  42. string = num_to_words(string)
  43. # TODO Try to use a ML predictor to expand abbreviations. It's hard, dependent on context, and whether to actually
  44. # try to say the abbreviation or spell it out as I've done below is not agreed upon
  45. # For now, expand abbreviations to pronunciations
  46. # replace_abbreviations adds a lot of unnecessary whitespace to ensure separation
  47. string = replace_abbreviations(string)
  48. # cleanup whitespaces
  49. # remove whitespace before punctuation
  50. string = re.sub(r'\s+([,.?!\'])', r'\1', string)
  51. string = string.strip()
  52. # compact whitespace
  53. string = ' '.join(string.split())
  54. return string
  55. def remove_surrounded_chars(string):
  56. # this expression matches to 'as few symbols as possible (0 upwards) between any asterisks' OR
  57. # 'as few symbols as possible (0 upwards) between an asterisk and the end of the string'
  58. return re.sub(r'\*[^*]*?(\*|$)', '', string)
  59. def replace_negative(string):
  60. # handles situations like -5. -5 would become negative 5, which would then be expanded to negative five
  61. return re.sub(r'(\s)(-)(\d+)([\s,.?!)"\'\]>])', r'\1negative \3\4', string)
  62. def replace_roman(string):
  63. # find a string of roman numerals.
  64. # Only 2 or more, to avoid capturing I and single character abbreviations, like names
  65. pattern = re.compile(r'\s[IVXLCDM]{2,}[\s,.?!)"\'\]>]')
  66. result = string
  67. while True:
  68. match = pattern.search(result)
  69. if match is None:
  70. break
  71. start = match.start()
  72. end = match.end()
  73. result = result[0:start+1] + str(roman_to_int(result[start+1:end-1])) + result[end-1:len(result)]
  74. return result
  75. def roman_to_int(s):
  76. rom_val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
  77. int_val = 0
  78. for i in range(len(s)):
  79. if i > 0 and rom_val[s[i]] > rom_val[s[i - 1]]:
  80. int_val += rom_val[s[i]] - 2 * rom_val[s[i - 1]]
  81. else:
  82. int_val += rom_val[s[i]]
  83. return int_val
  84. def hyphen_range_to(text):
  85. pattern = re.compile(r'(\d+)[-–](\d+)')
  86. result = pattern.sub(lambda x: x.group(1) + ' to ' + x.group(2), text)
  87. return result
  88. def num_to_words(text):
  89. # 1000 or 10.23
  90. pattern = re.compile(r'\d+\.\d+|\d+')
  91. result = pattern.sub(lambda x: num2words(float(x.group())), text)
  92. return result
  93. def replace_abbreviations(string):
  94. # abbreviations 1 to 4 characters long. It will get things like A and I, but those are pronounced with their letter
  95. pattern = re.compile(r'(^|[\s("\'\[<])([A-Z]{1,4})([\s,.?!)"\'\]>]|$)')
  96. result = string
  97. while True:
  98. match = pattern.search(result)
  99. if match is None:
  100. break
  101. start = match.start()
  102. end = match.end()
  103. result = result[0:start] + replace_abbreviation(result[start:end]) + result[end:len(result)]
  104. return result
  105. def replace_abbreviation(string):
  106. result = ""
  107. for char in string:
  108. result = match_mapping(char, result)
  109. return result
  110. def match_mapping(char, result):
  111. for mapping in alphabet_map.keys():
  112. if char == mapping:
  113. return result + alphabet_map[char]
  114. return result + char
  115. def convert_num_locale(text):
  116. # This detects locale and converts it to American without comma separators
  117. pattern = re.compile(r'(?:\s|^)\d{1,3}(?:\.\d{3})*(?:,\d+)?(?:\s|$)')
  118. result = text
  119. while True:
  120. match = pattern.search(result)
  121. if match is None:
  122. break
  123. start = match.start()
  124. end = match.end()
  125. result = result[0:start] + result[start:end].replace('.', '').replace(',', '.') + result[end:len(result)]
  126. # removes comma separators from existing American numbers
  127. pattern = re.compile(r'(\d),(\d)')
  128. result = pattern.sub(r'\1\2', result)
  129. return result
  130. def __main__(args):
  131. print(preprocess(args[1]))
  132. if __name__ == "__main__":
  133. import sys
  134. __main__(sys.argv)