tokenize.py 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #!/usr/bin/env python
  2. import re
  3. import numpy as np
  4. from funasr.datasets.large_datasets.utils.hotword_utils import sample_hotword
  5. def forward_segment(text, seg_dict):
  6. word_list = []
  7. i = 0
  8. while i < len(text):
  9. longest_word = text[i]
  10. for j in range(i + 1, len(text) + 1):
  11. word = text[i:j]
  12. if word in seg_dict:
  13. if len(word) > len(longest_word):
  14. longest_word = word
  15. word_list.append(longest_word)
  16. i += len(longest_word)
  17. return word_list
  18. def seg_tokenize(txt, seg_dict):
  19. pattern = re.compile(r'^[\u4E00-\u9FA50-9]+$')
  20. out_txt = ""
  21. for word in txt:
  22. word = word.lower()
  23. if word in seg_dict:
  24. out_txt += seg_dict[word] + " "
  25. else:
  26. if pattern.match(word):
  27. for char in word:
  28. if char in seg_dict:
  29. out_txt += seg_dict[char] + " "
  30. else:
  31. out_txt += "<unk>" + " "
  32. else:
  33. out_txt += "<unk>" + " "
  34. return out_txt.strip().split()
  35. def tokenize(data,
  36. vocab=None,
  37. seg_dict=None,
  38. punc_dict=None,
  39. bpe_tokenizer=None,
  40. hw_config=None):
  41. assert "text" in data
  42. assert isinstance(vocab, dict)
  43. text = data["text"]
  44. token = []
  45. vad = -2
  46. if bpe_tokenizer is not None:
  47. text = bpe_tokenizer.text2tokens(" ".join(text))
  48. if seg_dict is not None:
  49. assert isinstance(seg_dict, dict)
  50. text = seg_tokenize(text, seg_dict)
  51. length = len(text)
  52. if 'hw_tag' in data:
  53. if hw_config['pre_hwlist'] is not None and hw_config['pre_prob'] > 0:
  54. # enable preset hotword detect in sampling
  55. pre_index = None
  56. for hw in hw_config['pre_hwlist']:
  57. hw = " ".join(seg_tokenize(hw, seg_dict))
  58. _find = " ".join(text).find(hw)
  59. if _find != -1:
  60. # _find = text[:_find].count(" ") # bpe sometimes
  61. pre_index = [_find, _find + max(hw.count(" "), 1)]
  62. break
  63. hotword_indxs = sample_hotword(length, **hw_config, pre_index=pre_index)
  64. data['hotword_indxs'] = hotword_indxs
  65. del data['hw_tag']
  66. for i in range(length):
  67. x = text[i]
  68. if i == length-1 and "punc" in data and x.startswith("vad:"):
  69. vad = x[4:]
  70. if len(vad) == 0:
  71. vad = -1
  72. else:
  73. vad = int(vad)
  74. elif x in vocab:
  75. token.append(vocab[x])
  76. else:
  77. token.append(vocab['<unk>'])
  78. if "punc" in data and punc_dict is not None:
  79. punc_token = []
  80. for punc in data["punc"]:
  81. if punc in punc_dict:
  82. punc_token.append(punc_dict[punc])
  83. else:
  84. punc_token.append(punc_dict["_"])
  85. data["punc"] = np.array(punc_token)
  86. data["text"] = np.array(token)
  87. if vad is not -2:
  88. data["vad_indexes"]=np.array([vad], dtype=np.int64)
  89. return data