english.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import os
  2. import pickle
  3. import re
  4. from functools import lru_cache
  5. from g2p_en import G2p
  6. current_file_path = os.path.dirname(__file__)
  7. CMU_DICT_PATH = os.path.join(current_file_path, "cmudict.rep")
  8. CACHE_PATH = os.path.join(current_file_path, "cmudict_cache.pickle")
  9. _g2p = G2p()
  10. def read_dict():
  11. g2p_dict = {}
  12. start_line = 49
  13. with open(CMU_DICT_PATH) as f:
  14. line = f.readline()
  15. line_index = 1
  16. while line:
  17. if line_index >= start_line:
  18. line = line.strip()
  19. word_split = line.split(" ")
  20. word = word_split[0]
  21. syllable_split = word_split[1].split(" - ")
  22. g2p_dict[word] = []
  23. for syllable in syllable_split:
  24. phone_split = syllable.split(" ")
  25. g2p_dict[word].append(phone_split)
  26. line_index = line_index + 1
  27. line = f.readline()
  28. return g2p_dict
  29. def cache_dict(g2p_dict, file_path):
  30. with open(file_path, "wb") as pickle_file:
  31. pickle.dump(g2p_dict, pickle_file)
  32. @lru_cache(maxsize=1)
  33. def get_dict():
  34. if os.path.exists(CACHE_PATH):
  35. with open(CACHE_PATH, "rb") as pickle_file:
  36. g2p_dict = pickle.load(pickle_file)
  37. else:
  38. g2p_dict = read_dict()
  39. cache_dict(g2p_dict, CACHE_PATH)
  40. return g2p_dict
  41. def g2p(text):
  42. eng_dict = get_dict()
  43. phones = []
  44. words = re.split(r"([,;.\-\?\!\s+])", text)
  45. for w in words:
  46. if w.upper() in eng_dict:
  47. phns = eng_dict[w.upper()]
  48. for ph in phns:
  49. phones += ph
  50. continue
  51. phones.extend(list(filter(lambda p: p != " ", _g2p(w))))
  52. return phones
  53. if __name__ == "__main__":
  54. print(g2p("Hugging face, BGM"))