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.h 21 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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. #ifndef MINDSPORE_CCSRC_MINDDATA_DATASET_INCLUDE_TEXT_H_
  17. #define MINDSPORE_CCSRC_MINDDATA_DATASET_INCLUDE_TEXT_H_
  18. #include <memory>
  19. #include <optional>
  20. #include <string>
  21. #include <utility>
  22. #include <vector>
  23. #include "include/api/dual_abi_helper.h"
  24. #include "include/api/status.h"
  25. #include "minddata/dataset/include/constants.h"
  26. #include "minddata/dataset/include/transforms.h"
  27. namespace mindspore {
  28. namespace dataset {
  29. class Vocab;
  30. class SentencePieceVocab;
  31. class TensorOperation;
  32. // Transform operations for text
  33. namespace text {
  34. #ifndef _WIN32
  35. /// \brief Tokenize a scalar tensor of UTF-8 string by specific rules.
  36. /// \notes BasicTokenizer is not supported on Windows platform yet.
  37. class BasicTokenizer final : public TensorTransform {
  38. public:
  39. /// \brief Constructor.
  40. /// \param[in] lower_case If true, apply CaseFold, NormalizeUTF8(NFD mode), RegexReplace operation on input text to
  41. /// fold the text to lower case and strip accents characters. If false, only apply
  42. /// NormalizeUTF8('normalization_form' mode) operation on input text (default=false).
  43. /// \param[in] keep_whitespace If true, the whitespace will be kept in out tokens (default=false).
  44. /// \param[in] normalize_form Used to specify a specific normalize mode. This is only effective when 'lower_case' is
  45. /// false. See NormalizeUTF8 for details (default=NormalizeForm::kNone).
  46. /// \param[in] preserve_unused_token If true, do not split special tokens like '[CLS]', '[SEP]', '[UNK]', '[PAD]',
  47. /// '[MASK]' (default=true).
  48. /// \param[in] with_offsets If or not output offsets of tokens (default=false).
  49. explicit BasicTokenizer(bool lower_case = false, bool keep_whitespace = false,
  50. const NormalizeForm normalize_form = NormalizeForm::kNone, bool preserve_unused_token = true,
  51. bool with_offsets = false);
  52. /// \brief Destructor
  53. ~BasicTokenizer() = default;
  54. protected:
  55. /// \brief Function to convert TensorTransform object into a TensorOperation object.
  56. /// \return Shared pointer to TensorOperation object.
  57. std::shared_ptr<TensorOperation> Parse() override;
  58. private:
  59. struct Data;
  60. std::shared_ptr<Data> data_;
  61. };
  62. /// \brief Tokenizer used for Bert text process.
  63. /// \notes BertTokenizer is not supported on Windows platform yet.
  64. class BertTokenizer final : public TensorTransform {
  65. public:
  66. /// \brief Constructor.
  67. /// \param[in] vocab A Vocab object.
  68. /// \param[in] suffix_indicator Used to show that the subword is the last part of a word (default='##').
  69. /// \param[in] max_bytes_per_token Tokens exceeding this length will not be further split (default=100).
  70. /// \param[in] unknown_token When a token cannot be found, return the token directly if 'unknown_token' is an empty
  71. /// string, else return the string specified(default='[UNK]').
  72. /// \param[in] lower_case If true, apply CaseFold, NormalizeUTF8(NFD mode), RegexReplace operation on input text to
  73. /// fold the text to lower case and strip accents characters. If false, only apply
  74. /// NormalizeUTF8('normalization_form' mode) operation on input text (default=false).
  75. /// \param[in] keep_whitespace If true, the whitespace will be kept in out tokens (default=false).
  76. /// \param[in] normalize_form Used to specify a specific normalize mode. This is only effective when 'lower_case' is
  77. /// false. See NormalizeUTF8 for details (default=NormalizeForm::kNone).
  78. /// \param[in] preserve_unused_token If true, do not split special tokens like '[CLS]', '[SEP]', '[UNK]', '[PAD]',
  79. /// '[MASK]' (default=true).
  80. /// \param[in] with_offsets If or not output offsets of tokens (default=false).
  81. explicit BertTokenizer(const std::shared_ptr<Vocab> &vocab, const std::string &suffix_indicator = "##",
  82. int32_t max_bytes_per_token = 100, const std::string &unknown_token = "[UNK]",
  83. bool lower_case = false, bool keep_whitespace = false,
  84. const NormalizeForm normalize_form = NormalizeForm::kNone, bool preserve_unused_token = true,
  85. bool with_offsets = false)
  86. : BertTokenizer(vocab, StringToChar(suffix_indicator), max_bytes_per_token, StringToChar(unknown_token),
  87. lower_case, keep_whitespace, normalize_form, preserve_unused_token, with_offsets) {}
  88. explicit BertTokenizer(const std::shared_ptr<Vocab> &vocab, const std::vector<char> &suffix_indicator,
  89. int32_t max_bytes_per_token, const std::vector<char> &unknown_token, bool lower_case,
  90. bool keep_whitespace, const NormalizeForm normalize_form, bool preserve_unused_token,
  91. bool with_offsets);
  92. /// \brief Destructor
  93. ~BertTokenizer() = default;
  94. protected:
  95. /// \brief Function to convert TensorTransform object into a TensorOperation object.
  96. /// \return Shared pointer to TensorOperation object.
  97. std::shared_ptr<TensorOperation> Parse() override;
  98. private:
  99. struct Data;
  100. std::shared_ptr<Data> data_;
  101. };
  102. /// \brief Apply case fold operation on UTF-8 string tensor.
  103. /// \return Shared pointer to the current TensorOperation.
  104. class CaseFold final : public TensorTransform {
  105. public:
  106. /// \brief Constructor.
  107. CaseFold();
  108. /// \brief Destructor
  109. ~CaseFold() = default;
  110. protected:
  111. /// \brief Function to convert TensorTransform object into a TensorOperation object.
  112. //// \return Shared pointer to TensorOperation object.
  113. std::shared_ptr<TensorOperation> Parse() override;
  114. };
  115. #endif
  116. /// \brief Tokenize Chinese string into words based on dictionary.
  117. /// \notes The integrity of the HMMSEgment algorithm and MPSegment algorithm files must be confirmed.
  118. class JiebaTokenizer final : public TensorTransform {
  119. public:
  120. /// \brief Constructor.
  121. /// \param[in] hmm_path Dictionary file is used by HMMSegment algorithm. The dictionary can be obtained on the
  122. /// official website of cppjieba.
  123. /// \param[in] mp_path Dictionary file is used by MPSegment algorithm. The dictionary can be obtained on the
  124. /// official website of cppjieba.
  125. /// \param[in] mode Valid values can be any of [JiebaMode.MP, JiebaMode.HMM, JiebaMode.MIX](default=JiebaMode.MIX).
  126. /// - JiebaMode.kMP, tokenize with MPSegment algorithm.
  127. /// - JiebaMode.kHMM, tokenize with Hiddel Markov Model Segment algorithm.
  128. /// - JiebaMode.kMIX, tokenize with a mix of MPSegment and HMMSegment algorithm.
  129. /// \param[in] with_offsets If or not output offsets of tokens (default=false).
  130. explicit JiebaTokenizer(const std::string &hmm_path, const std::string &mp_path,
  131. const JiebaMode &mode = JiebaMode::kMix, bool with_offsets = false)
  132. : JiebaTokenizer(StringToChar(hmm_path), StringToChar(mp_path), mode, with_offsets) {}
  133. explicit JiebaTokenizer(const std::vector<char> &hmm_path, const std::vector<char> &mp_path, const JiebaMode &mode,
  134. bool with_offsets);
  135. /// \brief Destructor
  136. ~JiebaTokenizer() = default;
  137. Status AddWord(const std::string &word, int64_t freq = 0);
  138. protected:
  139. /// \brief Function to convert TensorTransform object into a TensorOperation object.
  140. /// \return Shared pointer to TensorOperation object.
  141. std::shared_ptr<TensorOperation> Parse() override;
  142. private:
  143. struct Data;
  144. std::shared_ptr<Data> data_;
  145. };
  146. /// \brief Look up a word into an id according to the input vocabulary table.
  147. class Lookup final : public TensorTransform {
  148. public:
  149. /// \brief Constructor.
  150. /// \param[in] vocab a Vocab object.
  151. /// \param[in] unknown_token word to use for lookup if the word being looked up is out of Vocabulary (oov).
  152. /// If unknown_token is oov, runtime error will be thrown. If unknown_token is {}, which means that not to
  153. /// specify unknown_token when word being out of Vocabulary (default={}).
  154. /// \param[in] data_type type of the tensor after lookup, typically int32.
  155. explicit Lookup(const std::shared_ptr<Vocab> &vocab, const std::optional<std::string> &unknown_token = {},
  156. const std::string &data_type = "int32")
  157. : Lookup(vocab, OptionalStringToChar(unknown_token), StringToChar(data_type)) {}
  158. explicit Lookup(const std::shared_ptr<Vocab> &vocab, const std::optional<std::vector<char>> &unknown_token,
  159. const std::vector<char> &data_type);
  160. /// \brief Destructor
  161. ~Lookup() = default;
  162. protected:
  163. /// \brief Function to convert TensorTransform object into a TensorOperation object.
  164. /// \return Shared pointer to TensorOperation object.
  165. std::shared_ptr<TensorOperation> Parse() override;
  166. private:
  167. struct Data;
  168. std::shared_ptr<Data> data_;
  169. };
  170. /// \brief TensorOp to generate n-gram from a 1-D string Tensor.
  171. class Ngram final : public TensorTransform {
  172. public:
  173. /// \brief Constructor.
  174. /// \param[in] ngrams ngrams is a vector of positive integers. For example, if ngrams={4, 3}, then the result
  175. /// would be a 4-gram followed by a 3-gram in the same tensor. If the number of words is not enough to make up
  176. /// for a n-gram, an empty string will be returned.
  177. /// \param[in] left_pad {"pad_token", pad_width}. Padding performed on left side of the sequence. pad_width will
  178. /// be capped at n-1. left_pad=("_",2) would pad left side of the sequence with "__" (default={"", 0}}).
  179. /// \param[in] right_pad {"pad_token", pad_width}. Padding performed on right side of the sequence.pad_width will
  180. /// be capped at n-1. right_pad=("-":2) would pad right side of the sequence with "--" (default={"", 0}}).
  181. /// \param[in] separator Symbol used to join strings together (default=" ").
  182. explicit Ngram(const std::vector<int32_t> &ngrams, const std::pair<std::string, int32_t> &left_pad = {"", 0},
  183. const std::pair<std::string, int32_t> &right_pad = {"", 0}, const std::string &separator = " ")
  184. : Ngram(ngrams, PairStringToChar(left_pad), PairStringToChar(right_pad), StringToChar(separator)) {}
  185. explicit Ngram(const std::vector<int32_t> &ngrams, const std::pair<std::vector<char>, int32_t> &left_pad,
  186. const std::pair<std::vector<char>, int32_t> &right_pad, const std::vector<char> &separator);
  187. /// \brief Destructor
  188. ~Ngram() = default;
  189. protected:
  190. /// \brief Function to convert TensorTransform object into a TensorOperation object.
  191. /// \return Shared pointer to TensorOperation object.
  192. std::shared_ptr<TensorOperation> Parse() override;
  193. private:
  194. struct Data;
  195. std::shared_ptr<Data> data_;
  196. };
  197. #ifndef _WIN32
  198. /// \brief Apply normalize operation on UTF-8 string tensor.
  199. class NormalizeUTF8 final : public TensorTransform {
  200. public:
  201. /// \brief Constructor.
  202. /// \param[in] normalize_form Valid values can be any of [NormalizeForm::kNone,NormalizeForm::kNfc,
  203. /// NormalizeForm::kNfkc,
  204. /// NormalizeForm::kNfd, NormalizeForm::kNfkd](default=NormalizeForm::kNfkc).
  205. /// See http://unicode.org/reports/tr15/ for details.
  206. /// - NormalizeForm.NONE, do nothing for input string tensor.
  207. /// - NormalizeForm.NFC, normalize with Normalization Form C.
  208. /// - NormalizeForm.NFKC, normalize with Normalization Form KC.
  209. /// - NormalizeForm.NFD, normalize with Normalization Form D.
  210. /// - NormalizeForm.NFKD, normalize with Normalization Form KD.
  211. explicit NormalizeUTF8(NormalizeForm normalize_form = NormalizeForm::kNfkc);
  212. /// \brief Destructor
  213. ~NormalizeUTF8() = default;
  214. protected:
  215. /// \brief Function to convert TensorTransform object into a TensorOperation object.
  216. /// \return Shared pointer to TensorOperation object.
  217. std::shared_ptr<TensorOperation> Parse() override;
  218. private:
  219. struct Data;
  220. std::shared_ptr<Data> data_;
  221. };
  222. /// \brief Replace UTF-8 string tensor with 'replace' according to regular expression 'pattern'.
  223. class RegexReplace final : public TensorTransform {
  224. public:
  225. /// \brief Constructor.
  226. /// \param[in] pattern The regex expression patterns.
  227. /// \param[in] replace The string to replace matched element.
  228. /// \param[in] replace_all Confirm whether to replace all. If false, only replace first matched element;
  229. /// if true, replace all matched elements (default=true).
  230. explicit RegexReplace(std::string pattern, std::string replace, bool replace_all = true)
  231. : RegexReplace(StringToChar(pattern), StringToChar(replace), replace_all) {}
  232. explicit RegexReplace(const std::vector<char> &pattern, const std::vector<char> &replace, bool replace_all);
  233. /// \brief Destructor
  234. ~RegexReplace() = default;
  235. protected:
  236. /// \brief Function to convert TensorTransform object into a TensorOperation object.
  237. /// \return Shared pointer to TensorOperation object.
  238. std::shared_ptr<TensorOperation> Parse() override;
  239. private:
  240. struct Data;
  241. std::shared_ptr<Data> data_;
  242. };
  243. /// \brief Tokenize a scalar tensor of UTF-8 string by regex expression pattern.
  244. class RegexTokenizer final : public TensorTransform {
  245. public:
  246. /// \brief Constructor.
  247. /// \param[in] delim_pattern The pattern of regex delimiters.
  248. /// \param[in] keep_delim_pattern The string matched by 'delim_pattern' can be kept as a token if it can be
  249. /// matched by 'keep_delim_pattern'. The default value is an empty string ("")
  250. /// which means that delimiters will not be kept as an output token (default="").
  251. /// \param[in] with_offsets If or not output offsets of tokens (default=false).
  252. explicit RegexTokenizer(std::string delim_pattern, std::string keep_delim_pattern = "", bool with_offsets = false)
  253. : RegexTokenizer(StringToChar(delim_pattern), StringToChar(keep_delim_pattern), with_offsets) {}
  254. explicit RegexTokenizer(const std::vector<char> &delim_pattern, const std::vector<char> &keep_delim_pattern,
  255. bool with_offsets);
  256. /// \brief Destructor
  257. ~RegexTokenizer() = default;
  258. protected:
  259. /// \brief Function to convert TensorTransform object into a TensorOperation object.
  260. /// \return Shared pointer to TensorOperation object.
  261. std::shared_ptr<TensorOperation> Parse() override;
  262. private:
  263. struct Data;
  264. std::shared_ptr<Data> data_;
  265. };
  266. #endif
  267. /// \brief Tokenize scalar token or 1-D tokens to tokens by sentencepiece.
  268. class SentencePieceTokenizer final : public TensorTransform {
  269. public:
  270. /// \brief Constructor.
  271. /// \param[in] vocab a SentencePieceVocab object.
  272. /// \param[in] out_type The type of output.
  273. SentencePieceTokenizer(const std::shared_ptr<SentencePieceVocab> &vocab,
  274. mindspore::dataset::SPieceTokenizerOutType out_typee);
  275. /// \brief Constructor.
  276. /// \param[in] vocab_path vocab model file path.
  277. /// \param[in] out_type The type of output.
  278. SentencePieceTokenizer(const std::string &vocab_path, mindspore::dataset::SPieceTokenizerOutType out_type)
  279. : SentencePieceTokenizer(StringToChar(vocab_path), out_type) {}
  280. SentencePieceTokenizer(const std::vector<char> &vocab_path, mindspore::dataset::SPieceTokenizerOutType out_type);
  281. /// \brief Destructor
  282. ~SentencePieceTokenizer() = default;
  283. protected:
  284. /// \brief Function to convert TensorTransform object into a TensorOperation object.
  285. /// \return Shared pointer to TensorOperation object.
  286. std::shared_ptr<TensorOperation> Parse() override;
  287. private:
  288. struct Data;
  289. std::shared_ptr<Data> data_;
  290. };
  291. /// \brief TensorOp to construct a tensor from data (only 1-D for now), where each element in the dimension
  292. /// axis is a slice of data starting at the corresponding position, with a specified width.
  293. class SlidingWindow final : public TensorTransform {
  294. public:
  295. /// \brief Constructor.
  296. /// \param[in] width The width of the window. It must be an integer and greater than zero.
  297. /// \param[in] axis The axis along which the sliding window is computed (default=0), axis support 0 or -1 only
  298. /// for now.
  299. explicit SlidingWindow(const int32_t width, const int32_t axis = 0);
  300. /// \brief Destructor
  301. ~SlidingWindow() = default;
  302. protected:
  303. /// \brief Function to convert TensorTransform object into a TensorOperation object.
  304. /// \return Shared pointer to TensorOperation object.
  305. std::shared_ptr<TensorOperation> Parse() override;
  306. private:
  307. struct Data;
  308. std::shared_ptr<Data> data_;
  309. };
  310. /// \brief Tensor operation to convert every element of a string tensor to a number.
  311. /// Strings are casted according to the rules specified in the following links:
  312. /// https://en.cppreference.com/w/cpp/string/basic_string/stof,
  313. /// https://en.cppreference.com/w/cpp/string/basic_string/stoul,
  314. /// except that any strings which represent negative numbers cannot be cast to an unsigned integer type.
  315. class ToNumber final : public TensorTransform {
  316. public:
  317. /// \brief Constructor.
  318. /// \param[in] data_type of the tensor to be casted to. Must be a numeric type.
  319. explicit ToNumber(const std::string &data_type) : ToNumber(StringToChar(data_type)) {}
  320. explicit ToNumber(const std::vector<char> &data_type);
  321. /// \brief Destructor
  322. ~ToNumber() = default;
  323. protected:
  324. /// \brief Function to convert TensorTransform object into a TensorOperation object.
  325. /// \return Shared pointer to TensorOperation object.
  326. std::shared_ptr<TensorOperation> Parse() override;
  327. private:
  328. struct Data;
  329. std::shared_ptr<Data> data_;
  330. };
  331. /// \brief Truncate a pair of rank-1 tensors such that the total length is less than max_length.
  332. class TruncateSequencePair final : public TensorTransform {
  333. public:
  334. /// \brief Constructor.
  335. /// \param[in] max_length Maximum length required.
  336. explicit TruncateSequencePair(int32_t max_length);
  337. /// \brief Destructor
  338. ~TruncateSequencePair() = default;
  339. protected:
  340. /// \brief Function to convert TensorTransform object into a TensorOperation object.
  341. /// \return Shared pointer to TensorOperation object.
  342. std::shared_ptr<TensorOperation> Parse() override;
  343. private:
  344. struct Data;
  345. std::shared_ptr<Data> data_;
  346. };
  347. /// \brief Tokenize a scalar tensor of UTF-8 string to Unicode characters.
  348. class UnicodeCharTokenizer final : public TensorTransform {
  349. public:
  350. /// \brief Constructor.
  351. /// \param[in] with_offsets If or not output offsets of tokens (default=false).
  352. explicit UnicodeCharTokenizer(bool with_offsets = false);
  353. /// \brief Destructor
  354. ~UnicodeCharTokenizer() = default;
  355. protected:
  356. /// \brief Function to convert TensorTransform object into a TensorOperation object.
  357. /// \return Shared pointer to TensorOperation object.
  358. std::shared_ptr<TensorOperation> Parse() override;
  359. private:
  360. struct Data;
  361. std::shared_ptr<Data> data_;
  362. };
  363. #ifndef _WIN32
  364. /// \brief Tokenize a scalar tensor of UTF-8 string on Unicode script boundaries.
  365. class UnicodeScriptTokenizer final : public TensorTransform {
  366. public:
  367. /// \brief Constructor.
  368. /// \param[in] keep_whitespace If or not emit whitespace tokens (default=false).
  369. /// \param[in] with_offsets If or not output offsets of tokens (default=false).
  370. explicit UnicodeScriptTokenizer(bool keep_whitespace = false, bool with_offsets = false);
  371. /// \brief Destructor
  372. ~UnicodeScriptTokenizer() = default;
  373. protected:
  374. /// \brief Function to convert TensorTransform object into a TensorOperation object.
  375. /// \return Shared pointer to TensorOperation object.
  376. std::shared_ptr<TensorOperation> Parse() override;
  377. private:
  378. struct Data;
  379. std::shared_ptr<Data> data_;
  380. };
  381. /// \brief Tokenize a scalar tensor of UTF-8 string on ICU4C defined whitespaces.
  382. class WhitespaceTokenizer final : public TensorTransform {
  383. public:
  384. /// \brief Constructor.
  385. /// \param[in] with_offsets If or not output offsets of tokens (default=false).
  386. explicit WhitespaceTokenizer(bool with_offsets = false);
  387. /// \brief Destructor
  388. ~WhitespaceTokenizer() = default;
  389. protected:
  390. /// \brief Function to convert TensorTransform object into a TensorOperation object.
  391. /// \return Shared pointer to TensorOperation object.
  392. std::shared_ptr<TensorOperation> Parse() override;
  393. private:
  394. struct Data;
  395. std::shared_ptr<Data> data_;
  396. };
  397. #endif
  398. } // namespace text
  399. } // namespace dataset
  400. } // namespace mindspore
  401. #endif // MINDSPORE_CCSRC_MINDDATA_DATASET_INCLUDE_TEXT_H_