tokenize.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. hotword_indxs = sample_hotword(length, **hw_config)
  54. data['hotword_indxs'] = hotword_indxs
  55. del data['hw_tag']
  56. for i in range(length):
  57. x = text[i]
  58. if i == length-1 and "punc" in data and x.startswith("vad:"):
  59. vad = x[4:]
  60. if len(vad) == 0:
  61. vad = -1
  62. else:
  63. vad = int(vad)
  64. elif x in vocab:
  65. token.append(vocab[x])
  66. else:
  67. token.append(vocab['<unk>'])
  68. if "punc" in data and punc_dict is not None:
  69. punc_token = []
  70. for punc in data["punc"]:
  71. if punc in punc_dict:
  72. punc_token.append(punc_dict[punc])
  73. else:
  74. punc_token.append(punc_dict["_"])
  75. data["punc"] = np.array(punc_token)
  76. data["text"] = np.array(token)
  77. if vad is not -2:
  78. data["vad_indexes"]=np.array([vad], dtype=np.int64)
  79. return data