tts_preprocessor.py 5.0 KB

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