You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

text.cc 17 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. /**
  2. * Copyright 2020-2021 Huawei Technologies Co., Ltd
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <unistd.h>
  17. #include <fstream>
  18. #include <regex>
  19. #include "minddata/dataset/include/dataset/text.h"
  20. #include "minddata/dataset/core/type_id.h"
  21. #include "minddata/dataset/text/ir/kernels/text_ir.h"
  22. #include "mindspore/core/ir/dtype/type_id.h"
  23. namespace mindspore {
  24. namespace dataset {
  25. // Transform operations for text.
  26. namespace text {
  27. // FUNCTIONS TO CREATE TEXT OPERATIONS
  28. // (In alphabetical order)
  29. #ifndef _WIN32
  30. // BasicTokenizer
  31. struct BasicTokenizer::Data {
  32. Data(bool lower_case, bool keep_whitespace, const NormalizeForm normalize_form, bool preserve_unused_token,
  33. bool with_offsets)
  34. : lower_case_(lower_case),
  35. keep_whitespace_(keep_whitespace),
  36. normalize_form_(normalize_form),
  37. preserve_unused_token_(preserve_unused_token),
  38. with_offsets_(with_offsets) {}
  39. bool lower_case_;
  40. bool keep_whitespace_;
  41. NormalizeForm normalize_form_;
  42. bool preserve_unused_token_;
  43. bool with_offsets_;
  44. };
  45. BasicTokenizer::BasicTokenizer(bool lower_case, bool keep_whitespace, const NormalizeForm normalize_form,
  46. bool preserve_unused_token, bool with_offsets)
  47. : data_(std::make_shared<Data>(lower_case, keep_whitespace, normalize_form, preserve_unused_token, with_offsets)) {}
  48. std::shared_ptr<TensorOperation> BasicTokenizer::Parse() {
  49. return std::make_shared<BasicTokenizerOperation>(data_->lower_case_, data_->keep_whitespace_, data_->normalize_form_,
  50. data_->preserve_unused_token_, data_->with_offsets_);
  51. }
  52. // BertTokenizer
  53. struct BertTokenizer::Data {
  54. Data(const std::shared_ptr<Vocab> &vocab, const std::vector<char> &suffix_indicator, int32_t max_bytes_per_token,
  55. const std::vector<char> &unknown_token, bool lower_case, bool keep_whitespace,
  56. const NormalizeForm normalize_form, bool preserve_unused_token, bool with_offsets)
  57. : vocab_(vocab),
  58. suffix_indicator_(CharToString(suffix_indicator)),
  59. max_bytes_per_token_(max_bytes_per_token),
  60. unknown_token_(CharToString(unknown_token)),
  61. lower_case_(lower_case),
  62. keep_whitespace_(keep_whitespace),
  63. normalize_form_(normalize_form),
  64. preserve_unused_token_(preserve_unused_token),
  65. with_offsets_(with_offsets) {}
  66. std::shared_ptr<Vocab> vocab_;
  67. std::string suffix_indicator_;
  68. int32_t max_bytes_per_token_;
  69. std::string unknown_token_;
  70. bool lower_case_;
  71. bool keep_whitespace_;
  72. NormalizeForm normalize_form_;
  73. bool preserve_unused_token_;
  74. bool with_offsets_;
  75. };
  76. BertTokenizer::BertTokenizer(const std::shared_ptr<Vocab> &vocab, const std::vector<char> &suffix_indicator,
  77. int32_t max_bytes_per_token, const std::vector<char> &unknown_token, bool lower_case,
  78. bool keep_whitespace, const NormalizeForm normalize_form, bool preserve_unused_token,
  79. bool with_offsets)
  80. : data_(std::make_shared<Data>(vocab, suffix_indicator, max_bytes_per_token, unknown_token, lower_case,
  81. keep_whitespace, normalize_form, preserve_unused_token, with_offsets)) {}
  82. std::shared_ptr<TensorOperation> BertTokenizer::Parse() {
  83. return std::make_shared<BertTokenizerOperation>(
  84. data_->vocab_, data_->suffix_indicator_, data_->max_bytes_per_token_, data_->unknown_token_, data_->lower_case_,
  85. data_->keep_whitespace_, data_->normalize_form_, data_->preserve_unused_token_, data_->with_offsets_);
  86. }
  87. // CaseFold
  88. CaseFold::CaseFold() {}
  89. std::shared_ptr<TensorOperation> CaseFold::Parse() { return std::make_shared<CaseFoldOperation>(); }
  90. #endif
  91. // JiebaTokenizer
  92. struct JiebaTokenizer::Data {
  93. Data(const std::vector<char> &hmm_path, const std::vector<char> &mp_path, const JiebaMode &mode, bool with_offsets)
  94. : hmm_path_(CharToString(hmm_path)),
  95. mp_path_(CharToString(mp_path)),
  96. mode_(mode),
  97. with_offsets_(with_offsets),
  98. words_list_({}) {}
  99. std::string hmm_path_;
  100. std::string mp_path_;
  101. JiebaMode mode_;
  102. bool with_offsets_;
  103. std::vector<std::pair<std::string, int64_t>> words_list_;
  104. };
  105. JiebaTokenizer::JiebaTokenizer(const std::vector<char> &hmm_path, const std::vector<char> &mp_path,
  106. const JiebaMode &mode, bool with_offsets)
  107. : data_(std::make_shared<Data>(hmm_path, mp_path, mode, with_offsets)) {}
  108. std::shared_ptr<TensorOperation> JiebaTokenizer::Parse() {
  109. std::shared_ptr<JiebaTokenizerOperation> jieba_tokenizer =
  110. std::make_shared<JiebaTokenizerOperation>(data_->hmm_path_, data_->mp_path_, data_->mode_, data_->with_offsets_);
  111. for (auto &word : data_->words_list_) {
  112. Status rc = jieba_tokenizer->AddWord(word.first, word.second);
  113. if (rc.IsError()) {
  114. MS_LOG(ERROR) << rc;
  115. return {};
  116. }
  117. }
  118. return jieba_tokenizer;
  119. }
  120. Status JiebaTokenizer::AddWordChar(const std::vector<char> &word, int64_t freq) {
  121. if (word.empty()) {
  122. std::string err_msg = "JiebaTokenizer : The parameter word is empty or not provided.";
  123. MS_LOG(ERROR) << err_msg;
  124. RETURN_STATUS_SYNTAX_ERROR(err_msg);
  125. }
  126. if (freq < 0) {
  127. std::string err_msg = "JiebaTokenizer : The parameter freq must be greater than or equal to 0.";
  128. MS_LOG(ERROR) << err_msg;
  129. RETURN_STATUS_SYNTAX_ERROR(err_msg);
  130. }
  131. data_->words_list_.emplace_back(CharToString(word), freq);
  132. return Status::OK();
  133. }
  134. Status JiebaTokenizer::AddDictChar(const std::vector<std::pair<std::vector<char>, int64_t>> &user_dict) {
  135. for (auto &word_freq_pair : user_dict) {
  136. RETURN_IF_NOT_OK(AddWordChar(word_freq_pair.first, word_freq_pair.second));
  137. }
  138. return Status::OK();
  139. }
  140. Status JiebaTokenizer::AddDictChar(const std::vector<char> &file_path) {
  141. std::vector<std::pair<std::string, int64_t>> user_dict;
  142. RETURN_IF_NOT_OK(ParserFile(CharToString(file_path), &user_dict));
  143. RETURN_IF_NOT_OK(AddDictChar(PairStringInt64ToPairCharInt64(user_dict)));
  144. return Status::OK();
  145. }
  146. Status JiebaTokenizer::ParserFile(const std::string &file_path,
  147. std::vector<std::pair<std::string, int64_t>> *const user_dict) {
  148. std::ifstream ifs(file_path);
  149. if (!ifs) {
  150. std::string err_msg = "JiebaTokenizer : Fail to load dictionary from the input file, check the file path.";
  151. MS_LOG(ERROR) << err_msg;
  152. RETURN_STATUS_SYNTAX_ERROR(err_msg);
  153. }
  154. std::string line;
  155. while (std::getline(ifs, line)) {
  156. if (line.empty()) {
  157. continue;
  158. }
  159. std::regex regex("^\\s*([^\\s*]+?)\\s*([0-9]+)?\\s*$");
  160. std::smatch tokens;
  161. std::regex_match(line, tokens, regex);
  162. if (std::regex_match(line, tokens, regex)) {
  163. if (tokens.size() == 2) {
  164. user_dict->emplace_back(tokens.str(1), 0);
  165. } else if (tokens.size() == 3) {
  166. user_dict->emplace_back(tokens.str(1), strtoll(tokens.str(2).c_str(), NULL, 0));
  167. } else {
  168. continue;
  169. }
  170. } else {
  171. continue;
  172. }
  173. }
  174. MS_LOG(INFO) << "JiebaTokenizer::AddDict: The size of user input dictionary is: " << user_dict->size();
  175. MS_LOG(INFO) << "Valid rows in input dictionary (Maximum of first 10 rows are shown.):";
  176. for (std::size_t i = 0; i != user_dict->size(); ++i) {
  177. if (i >= 10) break;
  178. MS_LOG(INFO) << user_dict->at(i).first << " " << user_dict->at(i).second;
  179. }
  180. return Status::OK();
  181. }
  182. // Lookup
  183. struct Lookup::Data {
  184. Data(const std::shared_ptr<Vocab> &vocab, const std::optional<std::vector<char>> &unknown_token,
  185. mindspore::DataType data_type)
  186. : vocab_(vocab),
  187. unknown_token_(OptionalCharToString(unknown_token)),
  188. data_type_(dataset::MSTypeToDEType(static_cast<TypeId>(data_type))) {}
  189. std::shared_ptr<Vocab> vocab_;
  190. std::optional<std::string> unknown_token_;
  191. dataset::DataType data_type_;
  192. };
  193. Lookup::Lookup(const std::shared_ptr<Vocab> &vocab, const std::optional<std::vector<char>> &unknown_token,
  194. mindspore::DataType data_type)
  195. : data_(std::make_shared<Data>(vocab, unknown_token, data_type)) {
  196. data_->data_type_ = dataset::MSTypeToDEType(static_cast<TypeId>(data_type));
  197. }
  198. std::shared_ptr<TensorOperation> Lookup::Parse() {
  199. return std::make_shared<LookupOperation>(data_->vocab_, data_->unknown_token_, data_->data_type_);
  200. }
  201. // Ngram
  202. struct Ngram::Data {
  203. Data(const std::vector<int32_t> &ngrams, const std::pair<std::vector<char>, int32_t> &left_pad,
  204. const std::pair<std::vector<char>, int32_t> &right_pad, const std::vector<char> &separator)
  205. : ngrams_(ngrams),
  206. left_pad_(PairCharToString(left_pad)),
  207. right_pad_(PairCharToString(right_pad)),
  208. separator_(CharToString(separator)) {}
  209. std::vector<int32_t> ngrams_;
  210. std::pair<std::string, int32_t> left_pad_;
  211. std::pair<std::string, int32_t> right_pad_;
  212. std::string separator_;
  213. };
  214. Ngram::Ngram(const std::vector<int32_t> &ngrams, const std::pair<std::vector<char>, int32_t> &left_pad,
  215. const std::pair<std::vector<char>, int32_t> &right_pad, const std::vector<char> &separator)
  216. : data_(std::make_shared<Data>(ngrams, left_pad, right_pad, separator)) {}
  217. std::shared_ptr<TensorOperation> Ngram::Parse() {
  218. return std::make_shared<NgramOperation>(data_->ngrams_, data_->left_pad_, data_->right_pad_, data_->separator_);
  219. }
  220. #ifndef _WIN32
  221. // NormalizeUTF8
  222. struct NormalizeUTF8::Data {
  223. explicit Data(NormalizeForm normalize_form) : normalize_form_(normalize_form) {}
  224. NormalizeForm normalize_form_;
  225. };
  226. NormalizeUTF8::NormalizeUTF8(NormalizeForm normalize_form) : data_(std::make_shared<Data>(normalize_form)) {}
  227. std::shared_ptr<TensorOperation> NormalizeUTF8::Parse() {
  228. return std::make_shared<NormalizeUTF8Operation>(data_->normalize_form_);
  229. }
  230. // RegexReplace
  231. struct RegexReplace::Data {
  232. Data(const std::vector<char> &pattern, const std::vector<char> &replace, bool replace_all)
  233. : pattern_(CharToString(pattern)), replace_(CharToString(replace)), replace_all_(replace_all) {}
  234. std::string pattern_;
  235. std::string replace_;
  236. bool replace_all_;
  237. };
  238. RegexReplace::RegexReplace(const std::vector<char> &pattern, const std::vector<char> &replace, bool replace_all)
  239. : data_(std::make_shared<Data>(pattern, replace, replace_all)) {}
  240. std::shared_ptr<TensorOperation> RegexReplace::Parse() {
  241. return std::make_shared<RegexReplaceOperation>(data_->pattern_, data_->replace_, data_->replace_all_);
  242. }
  243. // RegexTokenizer
  244. struct RegexTokenizer::Data {
  245. Data(const std::vector<char> &delim_pattern, const std::vector<char> &keep_delim_pattern, bool with_offsets)
  246. : delim_pattern_(CharToString(delim_pattern)),
  247. keep_delim_pattern_(CharToString(keep_delim_pattern)),
  248. with_offsets_(with_offsets) {}
  249. std::string delim_pattern_;
  250. std::string keep_delim_pattern_;
  251. bool with_offsets_;
  252. };
  253. RegexTokenizer::RegexTokenizer(const std::vector<char> &delim_pattern, const std::vector<char> &keep_delim_pattern,
  254. bool with_offsets)
  255. : data_(std::make_shared<Data>(delim_pattern, keep_delim_pattern, with_offsets)) {}
  256. std::shared_ptr<TensorOperation> RegexTokenizer::Parse() {
  257. return std::make_shared<RegexTokenizerOperation>(data_->delim_pattern_, data_->keep_delim_pattern_,
  258. data_->with_offsets_);
  259. }
  260. #endif
  261. // SentencePieceTokenizer
  262. struct SentencePieceTokenizer::Data {
  263. Data(const std::shared_ptr<SentencePieceVocab> &vocab, SPieceTokenizerOutType out_type)
  264. : vocab_(vocab), out_type_(out_type) {}
  265. Data(const std::vector<char> &vocab_path, SPieceTokenizerOutType out_type)
  266. : vocab_path_(CharToString(vocab_path)), out_type_(out_type) {}
  267. std::shared_ptr<SentencePieceVocab> vocab_;
  268. std::string vocab_path_;
  269. SPieceTokenizerOutType out_type_;
  270. };
  271. SentencePieceTokenizer::SentencePieceTokenizer(const std::shared_ptr<SentencePieceVocab> &vocab,
  272. SPieceTokenizerOutType out_type)
  273. : data_(std::make_shared<Data>(vocab, out_type)) {}
  274. SentencePieceTokenizer::SentencePieceTokenizer(const std::vector<char> &vocab_path, SPieceTokenizerOutType out_type)
  275. : data_(std::make_shared<Data>(vocab_path, out_type)) {}
  276. std::shared_ptr<TensorOperation> SentencePieceTokenizer::Parse() {
  277. if (data_->vocab_ != nullptr) {
  278. return std::make_shared<SentencePieceTokenizerOperation>(data_->vocab_, data_->out_type_);
  279. } else {
  280. return std::make_shared<SentencePieceTokenizerOperation>(data_->vocab_path_, data_->out_type_);
  281. }
  282. }
  283. // SlidingWindow
  284. struct SlidingWindow::Data {
  285. Data(const int32_t width, const int32_t axis) : width_(width), axis_(axis) {}
  286. int32_t width_;
  287. int32_t axis_;
  288. };
  289. SlidingWindow::SlidingWindow(const int32_t width, const int32_t axis) : data_(std::make_shared<Data>(width, axis)) {}
  290. std::shared_ptr<TensorOperation> SlidingWindow::Parse() {
  291. return std::make_shared<SlidingWindowOperation>(data_->width_, data_->axis_);
  292. }
  293. // ToNumber
  294. struct ToNumber::Data {
  295. dataset::DataType data_type_;
  296. };
  297. ToNumber::ToNumber(mindspore::DataType data_type) : data_(std::make_shared<Data>()) {
  298. data_->data_type_ = dataset::MSTypeToDEType(static_cast<TypeId>(data_type));
  299. }
  300. std::shared_ptr<TensorOperation> ToNumber::Parse() { return std::make_shared<ToNumberOperation>(data_->data_type_); }
  301. // TruncateSequencePair
  302. struct TruncateSequencePair::Data {
  303. explicit Data(int32_t max_length) : max_length_(max_length) {}
  304. int32_t max_length_;
  305. };
  306. TruncateSequencePair::TruncateSequencePair(int32_t max_length) : data_(std::make_shared<Data>(max_length)) {}
  307. std::shared_ptr<TensorOperation> TruncateSequencePair::Parse() {
  308. return std::make_shared<TruncateSequencePairOperation>(data_->max_length_);
  309. }
  310. // UnicodeCharTokenizer
  311. struct UnicodeCharTokenizer::Data {
  312. explicit Data(bool with_offsets) : with_offsets_(with_offsets) {}
  313. bool with_offsets_;
  314. };
  315. UnicodeCharTokenizer::UnicodeCharTokenizer(bool with_offsets) : data_(std::make_shared<Data>(with_offsets)) {}
  316. std::shared_ptr<TensorOperation> UnicodeCharTokenizer::Parse() {
  317. return std::make_shared<UnicodeCharTokenizerOperation>(data_->with_offsets_);
  318. }
  319. // WordpieceTokenizer
  320. struct WordpieceTokenizer::Data {
  321. Data(const std::shared_ptr<Vocab> &vocab, const std::vector<char> &suffix_indicator, int32_t max_bytes_per_token,
  322. const std::vector<char> &unknown_token, bool with_offsets)
  323. : vocab_(vocab),
  324. suffix_indicator_(CharToString(suffix_indicator)),
  325. max_bytes_per_token_(max_bytes_per_token),
  326. unknown_token_(CharToString(unknown_token)),
  327. with_offsets_(with_offsets) {}
  328. std::shared_ptr<Vocab> vocab_;
  329. std::string suffix_indicator_;
  330. int32_t max_bytes_per_token_;
  331. std::string unknown_token_;
  332. bool with_offsets_;
  333. };
  334. WordpieceTokenizer::WordpieceTokenizer(const std::shared_ptr<Vocab> &vocab, const std::vector<char> &suffix_indicator,
  335. int32_t max_bytes_per_token, const std::vector<char> &unknown_token,
  336. bool with_offsets)
  337. : data_(std::make_shared<Data>(vocab, suffix_indicator, max_bytes_per_token, unknown_token, with_offsets)) {}
  338. std::shared_ptr<TensorOperation> WordpieceTokenizer::Parse() {
  339. return std::make_shared<WordpieceTokenizerOperation>(
  340. data_->vocab_, data_->suffix_indicator_, data_->max_bytes_per_token_, data_->unknown_token_, data_->with_offsets_);
  341. }
  342. #ifndef _WIN32
  343. // UnicodeScriptTokenizer
  344. struct UnicodeScriptTokenizer::Data {
  345. Data(bool keep_whitespace, bool with_offsets) : keep_whitespace_(keep_whitespace), with_offsets_(with_offsets) {}
  346. bool keep_whitespace_;
  347. bool with_offsets_;
  348. };
  349. UnicodeScriptTokenizer::UnicodeScriptTokenizer(bool keep_whitespace, bool with_offsets)
  350. : data_(std::make_shared<Data>(keep_whitespace, with_offsets)) {}
  351. std::shared_ptr<TensorOperation> UnicodeScriptTokenizer::Parse() {
  352. return std::make_shared<UnicodeScriptTokenizerOperation>(data_->keep_whitespace_, data_->with_offsets_);
  353. }
  354. // WhitespaceTokenizer
  355. struct WhitespaceTokenizer::Data {
  356. explicit Data(bool with_offsets) : with_offsets_(with_offsets) {}
  357. bool with_offsets_;
  358. };
  359. WhitespaceTokenizer::WhitespaceTokenizer(bool with_offsets) : data_(std::make_shared<Data>(with_offsets)) {}
  360. std::shared_ptr<TensorOperation> WhitespaceTokenizer::Parse() {
  361. return std::make_shared<WhitespaceTokenizerOperation>(data_->with_offsets_);
  362. }
  363. #endif
  364. } // namespace text
  365. } // namespace dataset
  366. } // namespace mindspore