tts_preprocessor.py 5.0 KB

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