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 18 kB

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