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.

python_bindings.cc 60 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  1. /**
  2. * Copyright 2019 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 <exception>
  17. #include "minddata/dataset/api/de_pipeline.h"
  18. #include "minddata/dataset/engine/cache/cache_client.h"
  19. #include "minddata/dataset/engine/datasetops/source/cifar_op.h"
  20. #include "minddata/dataset/engine/datasetops/source/clue_op.h"
  21. #include "minddata/dataset/engine/datasetops/source/csv_op.h"
  22. #include "minddata/dataset/engine/datasetops/source/coco_op.h"
  23. #include "minddata/dataset/engine/datasetops/source/image_folder_op.h"
  24. #include "minddata/dataset/engine/datasetops/source/io_block.h"
  25. #include "minddata/dataset/engine/datasetops/source/manifest_op.h"
  26. #include "minddata/dataset/engine/datasetops/source/mindrecord_op.h"
  27. #include "minddata/dataset/engine/datasetops/source/mnist_op.h"
  28. #include "minddata/dataset/engine/datasetops/source/random_data_op.h"
  29. #include "minddata/dataset/engine/datasetops/source/sampler/distributed_sampler.h"
  30. #include "minddata/dataset/engine/datasetops/source/sampler/pk_sampler.h"
  31. #include "minddata/dataset/engine/datasetops/source/sampler/python_sampler.h"
  32. #include "minddata/dataset/engine/datasetops/source/sampler/random_sampler.h"
  33. #include "minddata/dataset/engine/datasetops/source/sampler/sequential_sampler.h"
  34. #include "minddata/dataset/engine/datasetops/source/sampler/subset_random_sampler.h"
  35. #include "minddata/dataset/engine/datasetops/source/sampler/weighted_random_sampler.h"
  36. #include "minddata/dataset/engine/datasetops/source/text_file_op.h"
  37. #include "minddata/dataset/engine/datasetops/source/tf_reader_op.h"
  38. #include "minddata/dataset/engine/datasetops/source/voc_op.h"
  39. #include "minddata/dataset/engine/gnn/graph.h"
  40. #include "minddata/dataset/engine/jagged_connector.h"
  41. #include "minddata/dataset/kernels/compose_op.h"
  42. #include "minddata/dataset/kernels/data/concatenate_op.h"
  43. #include "minddata/dataset/kernels/data/duplicate_op.h"
  44. #include "minddata/dataset/kernels/data/fill_op.h"
  45. #include "minddata/dataset/kernels/data/mask_op.h"
  46. #include "minddata/dataset/kernels/data/one_hot_op.h"
  47. #include "minddata/dataset/kernels/data/pad_end_op.h"
  48. #include "minddata/dataset/kernels/data/slice_op.h"
  49. #include "minddata/dataset/kernels/data/to_float16_op.h"
  50. #include "minddata/dataset/kernels/data/type_cast_op.h"
  51. #include "minddata/dataset/kernels/image/auto_contrast_op.h"
  52. #include "minddata/dataset/kernels/image/bounding_box_augment_op.h"
  53. #include "minddata/dataset/kernels/image/center_crop_op.h"
  54. #include "minddata/dataset/kernels/image/cut_out_op.h"
  55. #include "minddata/dataset/kernels/image/decode_op.h"
  56. #include "minddata/dataset/kernels/image/equalize_op.h"
  57. #include "minddata/dataset/kernels/image/hwc_to_chw_op.h"
  58. #include "minddata/dataset/kernels/image/image_utils.h"
  59. #include "minddata/dataset/kernels/image/invert_op.h"
  60. #include "minddata/dataset/kernels/image/normalize_op.h"
  61. #include "minddata/dataset/kernels/image/pad_op.h"
  62. #include "minddata/dataset/kernels/image/random_color_adjust_op.h"
  63. #include "minddata/dataset/kernels/image/random_crop_and_resize_op.h"
  64. #include "minddata/dataset/kernels/image/random_crop_and_resize_with_bbox_op.h"
  65. #include "minddata/dataset/kernels/image/random_crop_decode_resize_op.h"
  66. #include "minddata/dataset/kernels/image/random_crop_op.h"
  67. #include "minddata/dataset/kernels/image/random_crop_with_bbox_op.h"
  68. #include "minddata/dataset/kernels/image/random_horizontal_flip_op.h"
  69. #include "minddata/dataset/kernels/image/random_horizontal_flip_with_bbox_op.h"
  70. #include "minddata/dataset/kernels/image/random_resize_op.h"
  71. #include "minddata/dataset/kernels/image/random_resize_with_bbox_op.h"
  72. #include "minddata/dataset/kernels/image/random_rotation_op.h"
  73. #include "minddata/dataset/kernels/image/random_select_subpolicy_op.h"
  74. #include "minddata/dataset/kernels/image/random_vertical_flip_op.h"
  75. #include "minddata/dataset/kernels/image/random_vertical_flip_with_bbox_op.h"
  76. #include "minddata/dataset/kernels/image/rescale_op.h"
  77. #include "minddata/dataset/kernels/image/resize_bilinear_op.h"
  78. #include "minddata/dataset/kernels/image/resize_op.h"
  79. #include "minddata/dataset/kernels/image/resize_with_bbox_op.h"
  80. #include "minddata/dataset/kernels/image/uniform_aug_op.h"
  81. #include "minddata/dataset/kernels/no_op.h"
  82. #include "minddata/dataset/kernels/py_func_op.h"
  83. #include "minddata/dataset/kernels/random_apply_op.h"
  84. #include "minddata/dataset/kernels/random_choice_op.h"
  85. #include "minddata/dataset/text/kernels/jieba_tokenizer_op.h"
  86. #include "minddata/dataset/text/kernels/lookup_op.h"
  87. #include "minddata/dataset/text/kernels/ngram_op.h"
  88. #include "minddata/dataset/text/kernels/sliding_window_op.h"
  89. #include "minddata/dataset/text/kernels/to_number_op.h"
  90. #include "minddata/dataset/text/kernels/unicode_char_tokenizer_op.h"
  91. #include "minddata/dataset/text/kernels/wordpiece_tokenizer_op.h"
  92. #include "minddata/dataset/text/kernels/sentence_piece_tokenizer_op.h"
  93. #include "minddata/dataset/text/vocab.h"
  94. #include "minddata/dataset/text/sentence_piece_vocab.h"
  95. #include "minddata/dataset/util/random.h"
  96. #include "minddata/mindrecord/include/shard_distributed_sample.h"
  97. #include "minddata/mindrecord/include/shard_operator.h"
  98. #include "minddata/mindrecord/include/shard_pk_sample.h"
  99. #include "minddata/mindrecord/include/shard_sample.h"
  100. #include "minddata/mindrecord/include/shard_sequential_sample.h"
  101. #include "mindspore/ccsrc/minddata/dataset/text/kernels/truncate_sequence_pair_op.h"
  102. #include "pybind11/pybind11.h"
  103. #include "pybind11/stl.h"
  104. #include "pybind11/stl_bind.h"
  105. #ifdef ENABLE_ICU4C
  106. #include "minddata/dataset/text/kernels/basic_tokenizer_op.h"
  107. #include "minddata/dataset/text/kernels/bert_tokenizer_op.h"
  108. #include "minddata/dataset/text/kernels/case_fold_op.h"
  109. #include "minddata/dataset/text/kernels/normalize_utf8_op.h"
  110. #include "minddata/dataset/text/kernels/regex_replace_op.h"
  111. #include "minddata/dataset/text/kernels/regex_tokenizer_op.h"
  112. #include "minddata/dataset/text/kernels/unicode_script_tokenizer_op.h"
  113. #include "minddata/dataset/text/kernels/whitespace_tokenizer_op.h"
  114. #endif
  115. namespace py = pybind11;
  116. namespace mindspore {
  117. namespace dataset {
  118. #define THROW_IF_ERROR(s) \
  119. do { \
  120. Status rc = std::move(s); \
  121. if (rc.IsError()) throw std::runtime_error(rc.ToString()); \
  122. } while (false)
  123. Status PyListToTensorOps(const py::list &py_ops, std::vector<std::shared_ptr<TensorOp>> *ops) {
  124. RETURN_UNEXPECTED_IF_NULL(ops);
  125. for (auto op : py_ops) {
  126. if (py::isinstance<TensorOp>(op)) {
  127. ops->emplace_back(op.cast<std::shared_ptr<TensorOp>>());
  128. } else if (py::isinstance<py::function>(op)) {
  129. ops->emplace_back(std::make_shared<PyFuncOp>(op.cast<py::function>()));
  130. } else {
  131. RETURN_STATUS_UNEXPECTED("element is neither a TensorOp nor a pyfunc.");
  132. }
  133. }
  134. CHECK_FAIL_RETURN_UNEXPECTED(!ops->empty(), "TensorOp list is empty.");
  135. for (auto const &op : *ops) {
  136. RETURN_UNEXPECTED_IF_NULL(op);
  137. }
  138. return Status::OK();
  139. }
  140. void bindDEPipeline(py::module *m) {
  141. (void)py::class_<DEPipeline>(*m, "DEPipeline")
  142. .def(py::init<>())
  143. .def(
  144. "AddNodeToTree",
  145. [](DEPipeline &de, const OpName &op_name, const py::dict &args) {
  146. py::dict out;
  147. THROW_IF_ERROR(de.AddNodeToTree(op_name, args, &out));
  148. return out;
  149. },
  150. py::return_value_policy::reference)
  151. .def_static("AddChildToParentNode",
  152. [](const DsOpPtr &child_op, const DsOpPtr &parent_op) {
  153. THROW_IF_ERROR(DEPipeline::AddChildToParentNode(child_op, parent_op));
  154. })
  155. .def("AssignRootNode",
  156. [](DEPipeline &de, const DsOpPtr &dataset_op) { THROW_IF_ERROR(de.AssignRootNode(dataset_op)); })
  157. .def("SetBatchParameters",
  158. [](DEPipeline &de, const py::dict &args) { THROW_IF_ERROR(de.SetBatchParameters(args)); })
  159. .def("LaunchTreeExec", [](DEPipeline &de, int32_t num_epochs) { THROW_IF_ERROR(de.LaunchTreeExec(num_epochs)); })
  160. .def("GetNextAsMap",
  161. [](DEPipeline &de) {
  162. py::dict out;
  163. THROW_IF_ERROR(de.GetNextAsMap(&out));
  164. return out;
  165. })
  166. .def("GetNextAsList",
  167. [](DEPipeline &de) {
  168. py::list out;
  169. THROW_IF_ERROR(de.GetNextAsList(&out));
  170. return out;
  171. })
  172. .def("GetOutputShapes",
  173. [](DEPipeline &de) {
  174. py::list out;
  175. THROW_IF_ERROR(de.GetOutputShapes(&out));
  176. return out;
  177. })
  178. .def("GetOutputTypes",
  179. [](DEPipeline &de) {
  180. py::list out;
  181. THROW_IF_ERROR(de.GetOutputTypes(&out));
  182. return out;
  183. })
  184. .def("GetDatasetSize", &DEPipeline::GetDatasetSize)
  185. .def("GetBatchSize", &DEPipeline::GetBatchSize)
  186. .def("GetNumClasses", &DEPipeline::GetNumClasses)
  187. .def("GetRepeatCount", &DEPipeline::GetRepeatCount)
  188. .def("StopSend", [](DEPipeline &de) { THROW_IF_ERROR(de.StopSend()); })
  189. .def("SaveDataset", [](DEPipeline &de, const std::vector<std::string> &file_names, const std::string &file_type) {
  190. THROW_IF_ERROR(de.SaveDataset(file_names, file_type));
  191. return true;
  192. });
  193. }
  194. void bindDatasetOps(py::module *m) {
  195. (void)py::class_<TFReaderOp, DatasetOp, std::shared_ptr<TFReaderOp>>(*m, "TFReaderOp")
  196. .def_static("get_num_rows", [](const py::list &files, int64_t numParallelWorkers, bool estimate = false) {
  197. int64_t count = 0;
  198. std::vector<std::string> filenames;
  199. for (auto l : files) {
  200. !l.is_none() ? filenames.push_back(py::str(l)) : (void)filenames.emplace_back("");
  201. }
  202. THROW_IF_ERROR(TFReaderOp::CountTotalRows(&count, filenames, numParallelWorkers, estimate));
  203. return count;
  204. });
  205. (void)py::class_<CifarOp, DatasetOp, std::shared_ptr<CifarOp>>(*m, "CifarOp")
  206. .def_static("get_num_rows", [](const std::string &dir, bool isCifar10) {
  207. int64_t count = 0;
  208. THROW_IF_ERROR(CifarOp::CountTotalRows(dir, isCifar10, &count));
  209. return count;
  210. });
  211. (void)py::class_<ImageFolderOp, DatasetOp, std::shared_ptr<ImageFolderOp>>(*m, "ImageFolderOp")
  212. .def_static("get_num_rows_and_classes", [](const std::string &path) {
  213. int64_t count = 0, num_classes = 0;
  214. THROW_IF_ERROR(ImageFolderOp::CountRowsAndClasses(path, std::set<std::string>{}, &count, &num_classes));
  215. return py::make_tuple(count, num_classes);
  216. });
  217. (void)py::class_<MindRecordOp, DatasetOp, std::shared_ptr<MindRecordOp>>(*m, "MindRecordOp")
  218. .def_static("get_num_rows", [](const std::vector<std::string> &paths, bool load_dataset, const py::object &sampler,
  219. const int64_t num_padded) {
  220. int64_t count = 0;
  221. std::shared_ptr<mindrecord::ShardOperator> op;
  222. if (py::hasattr(sampler, "create_for_minddataset")) {
  223. auto create = sampler.attr("create_for_minddataset");
  224. op = create().cast<std::shared_ptr<mindrecord::ShardOperator>>();
  225. }
  226. THROW_IF_ERROR(MindRecordOp::CountTotalRows(paths, load_dataset, op, &count, num_padded));
  227. return count;
  228. });
  229. (void)py::class_<ManifestOp, DatasetOp, std::shared_ptr<ManifestOp>>(*m, "ManifestOp")
  230. .def_static("get_num_rows_and_classes",
  231. [](const std::string &file, const py::dict &dict, const std::string &usage) {
  232. int64_t count = 0, num_classes = 0;
  233. THROW_IF_ERROR(ManifestOp::CountTotalRows(file, dict, usage, &count, &num_classes));
  234. return py::make_tuple(count, num_classes);
  235. })
  236. .def_static("get_class_indexing", [](const std::string &file, const py::dict &dict, const std::string &usage) {
  237. std::map<std::string, int32_t> output_class_indexing;
  238. THROW_IF_ERROR(ManifestOp::GetClassIndexing(file, dict, usage, &output_class_indexing));
  239. return output_class_indexing;
  240. });
  241. (void)py::class_<MnistOp, DatasetOp, std::shared_ptr<MnistOp>>(*m, "MnistOp")
  242. .def_static("get_num_rows", [](const std::string &dir) {
  243. int64_t count = 0;
  244. THROW_IF_ERROR(MnistOp::CountTotalRows(dir, &count));
  245. return count;
  246. });
  247. (void)py::class_<TextFileOp, DatasetOp, std::shared_ptr<TextFileOp>>(*m, "TextFileOp")
  248. .def_static("get_num_rows", [](const py::list &files) {
  249. int64_t count = 0;
  250. std::vector<std::string> filenames;
  251. for (auto file : files) {
  252. !file.is_none() ? filenames.push_back(py::str(file)) : (void)filenames.emplace_back("");
  253. }
  254. THROW_IF_ERROR(TextFileOp::CountAllFileRows(filenames, &count));
  255. return count;
  256. });
  257. (void)py::class_<ClueOp, DatasetOp, std::shared_ptr<ClueOp>>(*m, "ClueOp")
  258. .def_static("get_num_rows", [](const py::list &files) {
  259. int64_t count = 0;
  260. std::vector<std::string> filenames;
  261. for (auto file : files) {
  262. file.is_none() ? (void)filenames.emplace_back("") : filenames.push_back(py::str(file));
  263. }
  264. THROW_IF_ERROR(ClueOp::CountAllFileRows(filenames, &count));
  265. return count;
  266. });
  267. (void)py::class_<CsvOp, DatasetOp, std::shared_ptr<CsvOp>>(*m, "CsvOp")
  268. .def_static("get_num_rows", [](const py::list &files, bool csv_header) {
  269. int64_t count = 0;
  270. std::vector<std::string> filenames;
  271. for (auto file : files) {
  272. file.is_none() ? (void)filenames.emplace_back("") : filenames.push_back(py::str(file));
  273. }
  274. THROW_IF_ERROR(CsvOp::CountAllFileRows(filenames, csv_header, &count));
  275. return count;
  276. });
  277. (void)py::class_<VOCOp, DatasetOp, std::shared_ptr<VOCOp>>(*m, "VOCOp")
  278. .def_static("get_num_rows",
  279. [](const std::string &dir, const std::string &task_type, const std::string &task_mode,
  280. const py::dict &dict, int64_t numSamples) {
  281. int64_t count = 0;
  282. THROW_IF_ERROR(VOCOp::CountTotalRows(dir, task_type, task_mode, dict, &count));
  283. return count;
  284. })
  285. .def_static("get_class_indexing", [](const std::string &dir, const std::string &task_type,
  286. const std::string &task_mode, const py::dict &dict) {
  287. std::map<std::string, int32_t> output_class_indexing;
  288. THROW_IF_ERROR(VOCOp::GetClassIndexing(dir, task_type, task_mode, dict, &output_class_indexing));
  289. return output_class_indexing;
  290. });
  291. (void)py::class_<CocoOp, DatasetOp, std::shared_ptr<CocoOp>>(*m, "CocoOp")
  292. .def_static("get_class_indexing",
  293. [](const std::string &dir, const std::string &file, const std::string &task) {
  294. std::vector<std::pair<std::string, std::vector<int32_t>>> output_class_indexing;
  295. THROW_IF_ERROR(CocoOp::GetClassIndexing(dir, file, task, &output_class_indexing));
  296. return output_class_indexing;
  297. })
  298. .def_static("get_num_rows", [](const std::string &dir, const std::string &file, const std::string &task) {
  299. int64_t count = 0;
  300. THROW_IF_ERROR(CocoOp::CountTotalRows(dir, file, task, &count));
  301. return count;
  302. });
  303. }
  304. void bindTensor(py::module *m) {
  305. (void)py::class_<GlobalContext>(*m, "GlobalContext")
  306. .def_static("config_manager", &GlobalContext::config_manager, py::return_value_policy::reference);
  307. (void)py::class_<ConfigManager, std::shared_ptr<ConfigManager>>(*m, "ConfigManager")
  308. .def("__str__", &ConfigManager::ToString)
  309. .def("set_rows_per_buffer", &ConfigManager::set_rows_per_buffer)
  310. .def("set_num_parallel_workers", &ConfigManager::set_num_parallel_workers)
  311. .def("set_worker_connector_size", &ConfigManager::set_worker_connector_size)
  312. .def("set_op_connector_size", &ConfigManager::set_op_connector_size)
  313. .def("set_seed", &ConfigManager::set_seed)
  314. .def("set_monitor_sampling_interval", &ConfigManager::set_monitor_sampling_interval)
  315. .def("get_rows_per_buffer", &ConfigManager::rows_per_buffer)
  316. .def("get_num_parallel_workers", &ConfigManager::num_parallel_workers)
  317. .def("get_worker_connector_size", &ConfigManager::worker_connector_size)
  318. .def("get_op_connector_size", &ConfigManager::op_connector_size)
  319. .def("get_seed", &ConfigManager::seed)
  320. .def("get_monitor_sampling_interval", &ConfigManager::monitor_sampling_interval)
  321. .def("load", [](ConfigManager &c, std::string s) { THROW_IF_ERROR(c.LoadFile(s)); });
  322. (void)py::class_<Tensor, std::shared_ptr<Tensor>>(*m, "Tensor", py::buffer_protocol())
  323. .def(py::init([](py::array arr) {
  324. std::shared_ptr<Tensor> out;
  325. THROW_IF_ERROR(Tensor::CreateTensor(&out, arr));
  326. return out;
  327. }))
  328. .def_buffer([](Tensor &tensor) {
  329. py::buffer_info info;
  330. THROW_IF_ERROR(Tensor::GetBufferInfo(&tensor, &info));
  331. return info;
  332. })
  333. .def("__str__", &Tensor::ToString)
  334. .def("shape", &Tensor::shape)
  335. .def("type", &Tensor::type)
  336. .def("as_array", [](py::object &t) {
  337. auto &tensor = py::cast<Tensor &>(t);
  338. if (tensor.type() == DataType::DE_STRING) {
  339. py::array res;
  340. tensor.GetDataAsNumpyStrings(&res);
  341. return res;
  342. }
  343. py::buffer_info info;
  344. THROW_IF_ERROR(Tensor::GetBufferInfo(&tensor, &info));
  345. return py::array(pybind11::dtype(info), info.shape, info.strides, info.ptr, t);
  346. });
  347. (void)py::class_<TensorShape>(*m, "TensorShape")
  348. .def(py::init<py::list>())
  349. .def("__str__", &TensorShape::ToString)
  350. .def("as_list", &TensorShape::AsPyList)
  351. .def("is_known", &TensorShape::known);
  352. (void)py::class_<DataType>(*m, "DataType")
  353. .def(py::init<std::string>())
  354. .def(py::self == py::self)
  355. .def("__str__", &DataType::ToString)
  356. .def("__deepcopy__", [](py::object &t, py::dict memo) { return t; });
  357. }
  358. void bindTensorOps1(py::module *m) {
  359. (void)py::class_<TensorOp, std::shared_ptr<TensorOp>>(*m, "TensorOp")
  360. .def("__deepcopy__", [](py::object &t, py::dict memo) { return t; });
  361. (void)py::class_<AutoContrastOp, TensorOp, std::shared_ptr<AutoContrastOp>>(
  362. *m, "AutoContrastOp", "Tensor operation to apply autocontrast on an image.")
  363. .def(py::init<float, std::vector<uint32_t>>(), py::arg("cutoff") = AutoContrastOp::kCutOff,
  364. py::arg("ignore") = AutoContrastOp::kIgnore);
  365. (void)py::class_<NormalizeOp, TensorOp, std::shared_ptr<NormalizeOp>>(
  366. *m, "NormalizeOp", "Tensor operation to normalize an image. Takes mean and std.")
  367. .def(py::init<float, float, float, float, float, float>(), py::arg("meanR"), py::arg("meanG"), py::arg("meanB"),
  368. py::arg("stdR"), py::arg("stdG"), py::arg("stdB"));
  369. (void)py::class_<EqualizeOp, TensorOp, std::shared_ptr<EqualizeOp>>(
  370. *m, "EqualizeOp", "Tensor operation to apply histogram equalization on images.")
  371. .def(py::init<>());
  372. (void)py::class_<InvertOp, TensorOp, std::shared_ptr<InvertOp>>(*m, "InvertOp",
  373. "Tensor operation to apply invert on RGB images.")
  374. .def(py::init<>());
  375. (void)py::class_<RescaleOp, TensorOp, std::shared_ptr<RescaleOp>>(
  376. *m, "RescaleOp", "Tensor operation to rescale an image. Takes scale and shift.")
  377. .def(py::init<float, float>(), py::arg("rescale"), py::arg("shift"));
  378. (void)py::class_<CenterCropOp, TensorOp, std::shared_ptr<CenterCropOp>>(
  379. *m, "CenterCropOp", "Tensor operation to crop and image in the middle. Takes height and width (optional)")
  380. .def(py::init<int32_t, int32_t>(), py::arg("height"), py::arg("width") = CenterCropOp::kDefWidth);
  381. (void)py::class_<ResizeOp, TensorOp, std::shared_ptr<ResizeOp>>(
  382. *m, "ResizeOp", "Tensor operation to resize an image. Takes height, width and mode")
  383. .def(py::init<int32_t, int32_t, InterpolationMode>(), py::arg("targetHeight"),
  384. py::arg("targetWidth") = ResizeOp::kDefWidth, py::arg("interpolation") = ResizeOp::kDefInterpolation);
  385. (void)py::class_<ResizeWithBBoxOp, TensorOp, std::shared_ptr<ResizeWithBBoxOp>>(
  386. *m, "ResizeWithBBoxOp", "Tensor operation to resize an image. Takes height, width and mode.")
  387. .def(py::init<int32_t, int32_t, InterpolationMode>(), py::arg("targetHeight"),
  388. py::arg("targetWidth") = ResizeWithBBoxOp::kDefWidth,
  389. py::arg("interpolation") = ResizeWithBBoxOp::kDefInterpolation);
  390. (void)py::class_<RandomResizeWithBBoxOp, TensorOp, std::shared_ptr<RandomResizeWithBBoxOp>>(
  391. *m, "RandomResizeWithBBoxOp",
  392. "Tensor operation to resize an image using a randomly selected interpolation. Takes height and width.")
  393. .def(py::init<int32_t, int32_t>(), py::arg("targetHeight"),
  394. py::arg("targetWidth") = RandomResizeWithBBoxOp::kDefTargetWidth);
  395. (void)py::class_<UniformAugOp, TensorOp, std::shared_ptr<UniformAugOp>>(
  396. *m, "UniformAugOp", "Tensor operation to apply random augmentation(s).")
  397. .def(py::init<std::vector<std::shared_ptr<TensorOp>>, int32_t>(), py::arg("transforms"),
  398. py::arg("NumOps") = UniformAugOp::kDefNumOps);
  399. (void)py::class_<BoundingBoxAugmentOp, TensorOp, std::shared_ptr<BoundingBoxAugmentOp>>(
  400. *m, "BoundingBoxAugmentOp", "Tensor operation to apply a transformation on a random choice of bounding boxes.")
  401. .def(py::init<std::shared_ptr<TensorOp>, float>(), py::arg("transform"),
  402. py::arg("ratio") = BoundingBoxAugmentOp::kDefRatio);
  403. (void)py::class_<ResizeBilinearOp, TensorOp, std::shared_ptr<ResizeBilinearOp>>(
  404. *m, "ResizeBilinearOp",
  405. "Tensor operation to resize an image using "
  406. "Bilinear mode. Takes height and width.")
  407. .def(py::init<int32_t, int32_t>(), py::arg("targetHeight"), py::arg("targetWidth") = ResizeBilinearOp::kDefWidth);
  408. (void)py::class_<DecodeOp, TensorOp, std::shared_ptr<DecodeOp>>(*m, "DecodeOp",
  409. "Tensor operation to decode a jpg image")
  410. .def(py::init<>())
  411. .def(py::init<bool>(), py::arg("rgb_format") = DecodeOp::kDefRgbFormat);
  412. (void)py::class_<RandomHorizontalFlipOp, TensorOp, std::shared_ptr<RandomHorizontalFlipOp>>(
  413. *m, "RandomHorizontalFlipOp", "Tensor operation to randomly flip an image horizontally.")
  414. .def(py::init<float>(), py::arg("probability") = RandomHorizontalFlipOp::kDefProbability);
  415. (void)py::class_<RandomHorizontalFlipWithBBoxOp, TensorOp, std::shared_ptr<RandomHorizontalFlipWithBBoxOp>>(
  416. *m, "RandomHorizontalFlipWithBBoxOp",
  417. "Tensor operation to randomly flip an image horizontally, while flipping bounding boxes.")
  418. .def(py::init<float>(), py::arg("probability") = RandomHorizontalFlipWithBBoxOp::kDefProbability);
  419. }
  420. void bindTensorOps2(py::module *m) {
  421. (void)py::class_<RandomVerticalFlipOp, TensorOp, std::shared_ptr<RandomVerticalFlipOp>>(
  422. *m, "RandomVerticalFlipOp", "Tensor operation to randomly flip an image vertically.")
  423. .def(py::init<float>(), py::arg("probability") = RandomVerticalFlipOp::kDefProbability);
  424. (void)py::class_<RandomVerticalFlipWithBBoxOp, TensorOp, std::shared_ptr<RandomVerticalFlipWithBBoxOp>>(
  425. *m, "RandomVerticalFlipWithBBoxOp",
  426. "Tensor operation to randomly flip an image vertically"
  427. " and adjust bounding boxes.")
  428. .def(py::init<float>(), py::arg("probability") = RandomVerticalFlipWithBBoxOp::kDefProbability);
  429. (void)py::class_<RandomCropOp, TensorOp, std::shared_ptr<RandomCropOp>>(*m, "RandomCropOp",
  430. "Gives random crop of specified size "
  431. "Takes crop size")
  432. .def(py::init<int32_t, int32_t, int32_t, int32_t, int32_t, int32_t, BorderType, bool, uint8_t, uint8_t, uint8_t>(),
  433. py::arg("cropHeight"), py::arg("cropWidth"), py::arg("padTop") = RandomCropOp::kDefPadTop,
  434. py::arg("padBottom") = RandomCropOp::kDefPadBottom, py::arg("padLeft") = RandomCropOp::kDefPadLeft,
  435. py::arg("padRight") = RandomCropOp::kDefPadRight, py::arg("borderType") = RandomCropOp::kDefBorderType,
  436. py::arg("padIfNeeded") = RandomCropOp::kDefPadIfNeeded, py::arg("fillR") = RandomCropOp::kDefFillR,
  437. py::arg("fillG") = RandomCropOp::kDefFillG, py::arg("fillB") = RandomCropOp::kDefFillB);
  438. (void)py::class_<HwcToChwOp, TensorOp, std::shared_ptr<HwcToChwOp>>(*m, "ChannelSwapOp").def(py::init<>());
  439. (void)py::class_<RandomCropWithBBoxOp, TensorOp, std::shared_ptr<RandomCropWithBBoxOp>>(*m, "RandomCropWithBBoxOp",
  440. "Gives random crop of given "
  441. "size + adjusts bboxes "
  442. "Takes crop size")
  443. .def(py::init<int32_t, int32_t, int32_t, int32_t, int32_t, int32_t, BorderType, bool, uint8_t, uint8_t, uint8_t>(),
  444. py::arg("cropHeight"), py::arg("cropWidth"), py::arg("padTop") = RandomCropWithBBoxOp::kDefPadTop,
  445. py::arg("padBottom") = RandomCropWithBBoxOp::kDefPadBottom,
  446. py::arg("padLeft") = RandomCropWithBBoxOp::kDefPadLeft,
  447. py::arg("padRight") = RandomCropWithBBoxOp::kDefPadRight,
  448. py::arg("borderType") = RandomCropWithBBoxOp::kDefBorderType,
  449. py::arg("padIfNeeded") = RandomCropWithBBoxOp::kDefPadIfNeeded,
  450. py::arg("fillR") = RandomCropWithBBoxOp::kDefFillR, py::arg("fillG") = RandomCropWithBBoxOp::kDefFillG,
  451. py::arg("fillB") = RandomCropWithBBoxOp::kDefFillB);
  452. (void)py::class_<OneHotOp, TensorOp, std::shared_ptr<OneHotOp>>(
  453. *m, "OneHotOp", "Tensor operation to apply one hot encoding. Takes number of classes.")
  454. .def(py::init<int32_t>());
  455. (void)py::class_<FillOp, TensorOp, std::shared_ptr<FillOp>>(
  456. *m, "FillOp", "Tensor operation to return tensor filled with same value as input fill value.")
  457. .def(py::init<std::shared_ptr<Tensor>>());
  458. (void)py::class_<SliceOp, TensorOp, std::shared_ptr<SliceOp>>(*m, "SliceOp", "Tensor slice operation.")
  459. .def(py::init<bool>())
  460. .def(py::init([](const py::list &py_list) {
  461. std::vector<dsize_t> c_list;
  462. for (auto l : py_list) {
  463. if (!l.is_none()) {
  464. c_list.push_back(py::reinterpret_borrow<py::int_>(l));
  465. }
  466. }
  467. return std::make_shared<SliceOp>(c_list);
  468. }))
  469. .def(py::init([](const py::tuple &py_slice) {
  470. if (py_slice.size() != 3) {
  471. THROW_IF_ERROR(Status(StatusCode::kUnexpectedError, __LINE__, __FILE__, "Wrong slice object"));
  472. }
  473. Slice c_slice;
  474. if (!py_slice[0].is_none() && !py_slice[1].is_none() && !py_slice[2].is_none()) {
  475. c_slice = Slice(py::reinterpret_borrow<py::int_>(py_slice[0]), py::reinterpret_borrow<py::int_>(py_slice[1]),
  476. py::reinterpret_borrow<py::int_>(py_slice[2]));
  477. } else if (py_slice[0].is_none() && py_slice[2].is_none()) {
  478. c_slice = Slice(py::reinterpret_borrow<py::int_>(py_slice[1]));
  479. } else if (!py_slice[0].is_none() && !py_slice[1].is_none()) {
  480. c_slice = Slice(py::reinterpret_borrow<py::int_>(py_slice[0]), py::reinterpret_borrow<py::int_>(py_slice[1]));
  481. }
  482. if (!c_slice.valid()) {
  483. THROW_IF_ERROR(Status(StatusCode::kUnexpectedError, __LINE__, __FILE__, "Wrong slice object"));
  484. }
  485. return std::make_shared<SliceOp>(c_slice);
  486. }));
  487. (void)py::enum_<RelationalOp>(*m, "RelationalOp", py::arithmetic())
  488. .value("EQ", RelationalOp::kEqual)
  489. .value("NE", RelationalOp::kNotEqual)
  490. .value("LT", RelationalOp::kLess)
  491. .value("LE", RelationalOp::kLessEqual)
  492. .value("GT", RelationalOp::kGreater)
  493. .value("GE", RelationalOp::kGreaterEqual)
  494. .export_values();
  495. (void)py::class_<MaskOp, TensorOp, std::shared_ptr<MaskOp>>(*m, "MaskOp",
  496. "Tensor mask operation using relational comparator")
  497. .def(py::init<RelationalOp, std::shared_ptr<Tensor>, DataType>());
  498. (void)py::class_<DuplicateOp, TensorOp, std::shared_ptr<DuplicateOp>>(*m, "DuplicateOp", "Duplicate tensor.")
  499. .def(py::init<>());
  500. (void)py::class_<TruncateSequencePairOp, TensorOp, std::shared_ptr<TruncateSequencePairOp>>(
  501. *m, "TruncateSequencePairOp", "Tensor operation to truncate two tensors to a max_length")
  502. .def(py::init<int64_t>());
  503. (void)py::class_<ConcatenateOp, TensorOp, std::shared_ptr<ConcatenateOp>>(*m, "ConcatenateOp",
  504. "Tensor operation concatenate tensors.")
  505. .def(py::init<int8_t, std::shared_ptr<Tensor>, std::shared_ptr<Tensor>>(), py::arg("axis"),
  506. py::arg("prepend").none(true), py::arg("append").none(true));
  507. (void)py::class_<RandomRotationOp, TensorOp, std::shared_ptr<RandomRotationOp>>(
  508. *m, "RandomRotationOp",
  509. "Tensor operation to apply RandomRotation."
  510. "Takes a range for degrees and "
  511. "optional parameters for rotation center and image expand")
  512. .def(py::init<float, float, float, float, InterpolationMode, bool, uint8_t, uint8_t, uint8_t>(),
  513. py::arg("startDegree"), py::arg("endDegree"), py::arg("centerX") = RandomRotationOp::kDefCenterX,
  514. py::arg("centerY") = RandomRotationOp::kDefCenterY,
  515. py::arg("interpolation") = RandomRotationOp::kDefInterpolation,
  516. py::arg("expand") = RandomRotationOp::kDefExpand, py::arg("fillR") = RandomRotationOp::kDefFillR,
  517. py::arg("fillG") = RandomRotationOp::kDefFillG, py::arg("fillB") = RandomRotationOp::kDefFillB);
  518. (void)py::class_<PadEndOp, TensorOp, std::shared_ptr<PadEndOp>>(
  519. *m, "PadEndOp", "Tensor operation to pad end of tensor with a pad value.")
  520. .def(py::init<TensorShape, std::shared_ptr<Tensor>>());
  521. }
  522. void bindTensorOps3(py::module *m) {
  523. (void)py::class_<RandomCropAndResizeOp, TensorOp, std::shared_ptr<RandomCropAndResizeOp>>(
  524. *m, "RandomCropAndResizeOp",
  525. "Tensor operation to randomly crop an image and resize to a given size."
  526. "Takes output height and width and"
  527. "optional parameters for lower and upper bound for aspect ratio (h/w) and scale,"
  528. "interpolation mode, and max attempts to crop")
  529. .def(py::init<int32_t, int32_t, float, float, float, float, InterpolationMode, int32_t>(), py::arg("targetHeight"),
  530. py::arg("targetWidth"), py::arg("scaleLb") = RandomCropAndResizeOp::kDefScaleLb,
  531. py::arg("scaleUb") = RandomCropAndResizeOp::kDefScaleUb,
  532. py::arg("aspectLb") = RandomCropAndResizeOp::kDefAspectLb,
  533. py::arg("aspectUb") = RandomCropAndResizeOp::kDefAspectUb,
  534. py::arg("interpolation") = RandomCropAndResizeOp::kDefInterpolation,
  535. py::arg("maxIter") = RandomCropAndResizeOp::kDefMaxIter);
  536. (void)py::class_<RandomCropAndResizeWithBBoxOp, TensorOp, std::shared_ptr<RandomCropAndResizeWithBBoxOp>>(
  537. *m, "RandomCropAndResizeWithBBoxOp",
  538. "Tensor operation to randomly crop an image (with BBoxes) and resize to a given size."
  539. "Takes output height and width and"
  540. "optional parameters for lower and upper bound for aspect ratio (h/w) and scale,"
  541. "interpolation mode, and max attempts to crop")
  542. .def(py::init<int32_t, int32_t, float, float, float, float, InterpolationMode, int32_t>(), py::arg("targetHeight"),
  543. py::arg("targetWidth"), py::arg("scaleLb") = RandomCropAndResizeWithBBoxOp::kDefScaleLb,
  544. py::arg("scaleUb") = RandomCropAndResizeWithBBoxOp::kDefScaleUb,
  545. py::arg("aspectLb") = RandomCropAndResizeWithBBoxOp::kDefAspectLb,
  546. py::arg("aspectUb") = RandomCropAndResizeWithBBoxOp::kDefAspectUb,
  547. py::arg("interpolation") = RandomCropAndResizeWithBBoxOp::kDefInterpolation,
  548. py::arg("maxIter") = RandomCropAndResizeWithBBoxOp::kDefMaxIter);
  549. (void)py::class_<RandomColorAdjustOp, TensorOp, std::shared_ptr<RandomColorAdjustOp>>(
  550. *m, "RandomColorAdjustOp",
  551. "Tensor operation to adjust an image's color randomly."
  552. "Takes range for brightness, contrast, saturation, hue and")
  553. .def(py::init<float, float, float, float, float, float, float, float>(), py::arg("bright_factor_start"),
  554. py::arg("bright_factor_end"), py::arg("contrast_factor_start"), py::arg("contrast_factor_end"),
  555. py::arg("saturation_factor_start"), py::arg("saturation_factor_end"), py::arg("hue_factor_start"),
  556. py::arg("hue_factor_end"));
  557. (void)py::class_<RandomResizeOp, TensorOp, std::shared_ptr<RandomResizeOp>>(
  558. *m, "RandomResizeOp",
  559. "Tensor operation to resize an image using a randomly selected interpolation. Takes height and width.")
  560. .def(py::init<int32_t, int32_t>(), py::arg("targetHeight"),
  561. py::arg("targetWidth") = RandomResizeOp::kDefTargetWidth);
  562. (void)py::class_<CutOutOp, TensorOp, std::shared_ptr<CutOutOp>>(
  563. *m, "CutOutOp", "Tensor operation to randomly erase a portion of the image. Takes height and width.")
  564. .def(py::init<int32_t, int32_t, int32_t, bool, uint8_t, uint8_t, uint8_t>(), py::arg("boxHeight"),
  565. py::arg("boxWidth"), py::arg("numPatches"), py::arg("randomColor") = CutOutOp::kDefRandomColor,
  566. py::arg("fillR") = CutOutOp::kDefFillR, py::arg("fillG") = CutOutOp::kDefFillG,
  567. py::arg("fillB") = CutOutOp::kDefFillB);
  568. }
  569. void bindTensorOps4(py::module *m) {
  570. (void)py::class_<TypeCastOp, TensorOp, std::shared_ptr<TypeCastOp>>(
  571. *m, "TypeCastOp", "Tensor operator to type cast data to a specified type.")
  572. .def(py::init<DataType>(), py::arg("data_type"))
  573. .def(py::init<std::string>(), py::arg("data_type"));
  574. (void)py::class_<NoOp, TensorOp, std::shared_ptr<NoOp>>(*m, "NoOp",
  575. "TensorOp that does nothing, for testing purposes only.")
  576. .def(py::init<>());
  577. (void)py::class_<ToFloat16Op, TensorOp, std::shared_ptr<ToFloat16Op>>(
  578. *m, "ToFloat16Op", py::dynamic_attr(), "Tensor operator to type cast float32 data to a float16 type.")
  579. .def(py::init<>());
  580. (void)py::class_<RandomCropDecodeResizeOp, TensorOp, std::shared_ptr<RandomCropDecodeResizeOp>>(
  581. *m, "RandomCropDecodeResizeOp", "equivalent to RandomCropAndResize but crops before decoding")
  582. .def(py::init<int32_t, int32_t, float, float, float, float, InterpolationMode, int32_t>(), py::arg("targetHeight"),
  583. py::arg("targetWidth"), py::arg("scaleLb") = RandomCropDecodeResizeOp::kDefScaleLb,
  584. py::arg("scaleUb") = RandomCropDecodeResizeOp::kDefScaleUb,
  585. py::arg("aspectLb") = RandomCropDecodeResizeOp::kDefAspectLb,
  586. py::arg("aspectUb") = RandomCropDecodeResizeOp::kDefAspectUb,
  587. py::arg("interpolation") = RandomCropDecodeResizeOp::kDefInterpolation,
  588. py::arg("maxIter") = RandomCropDecodeResizeOp::kDefMaxIter);
  589. (void)py::class_<PadOp, TensorOp, std::shared_ptr<PadOp>>(
  590. *m, "PadOp",
  591. "Pads image with specified color, default black, "
  592. "Takes amount to pad for top, bottom, left, right of image, boarder type and color")
  593. .def(py::init<int32_t, int32_t, int32_t, int32_t, BorderType, uint8_t, uint8_t, uint8_t>(), py::arg("padTop"),
  594. py::arg("padBottom"), py::arg("padLeft"), py::arg("padRight"), py::arg("borderTypes") = PadOp::kDefBorderType,
  595. py::arg("fillR") = PadOp::kDefFillR, py::arg("fillG") = PadOp::kDefFillG, py::arg("fillB") = PadOp::kDefFillB);
  596. (void)py::class_<ToNumberOp, TensorOp, std::shared_ptr<ToNumberOp>>(*m, "ToNumberOp",
  597. "TensorOp to convert strings to numbers.")
  598. .def(py::init<DataType>(), py::arg("data_type"))
  599. .def(py::init<std::string>(), py::arg("data_type"));
  600. }
  601. void bindTokenizerOps(py::module *m) {
  602. (void)py::class_<JiebaTokenizerOp, TensorOp, std::shared_ptr<JiebaTokenizerOp>>(*m, "JiebaTokenizerOp", "")
  603. .def(py::init<const std::string &, const std::string &, const JiebaMode &, const bool &>(), py::arg("hmm_path"),
  604. py::arg("mp_path"), py::arg("mode") = JiebaMode::kMix,
  605. py::arg("with_offsets") = JiebaTokenizerOp::kDefWithOffsets)
  606. .def("add_word",
  607. [](JiebaTokenizerOp &self, const std::string word, int freq) { THROW_IF_ERROR(self.AddWord(word, freq)); });
  608. (void)py::class_<UnicodeCharTokenizerOp, TensorOp, std::shared_ptr<UnicodeCharTokenizerOp>>(
  609. *m, "UnicodeCharTokenizerOp", "Tokenize a scalar tensor of UTF-8 string to Unicode characters.")
  610. .def(py::init<const bool &>(), py::arg("with_offsets") = UnicodeCharTokenizerOp::kDefWithOffsets);
  611. (void)py::class_<LookupOp, TensorOp, std::shared_ptr<LookupOp>>(*m, "LookupOp",
  612. "Tensor operation to LookUp each word.")
  613. .def(py::init([](std::shared_ptr<Vocab> vocab, const py::object &py_word) {
  614. if (vocab == nullptr) {
  615. THROW_IF_ERROR(Status(StatusCode::kUnexpectedError, "vocab object type is incorrect or null."));
  616. }
  617. if (py_word.is_none()) {
  618. return std::make_shared<LookupOp>(vocab, Vocab::kNoTokenExists);
  619. }
  620. std::string word = py::reinterpret_borrow<py::str>(py_word);
  621. WordIdType default_id = vocab->Lookup(word);
  622. if (default_id == Vocab::kNoTokenExists) {
  623. THROW_IF_ERROR(
  624. Status(StatusCode::kUnexpectedError, "default unknown token: " + word + " doesn't exist in vocab."));
  625. }
  626. return std::make_shared<LookupOp>(vocab, default_id);
  627. }));
  628. (void)py::class_<NgramOp, TensorOp, std::shared_ptr<NgramOp>>(*m, "NgramOp", "TensorOp performs ngram mapping.")
  629. .def(py::init<const std::vector<int32_t> &, int32_t, int32_t, const std::string &, const std::string &,
  630. const std::string &>(),
  631. py::arg("ngrams"), py::arg("l_pad_len"), py::arg("r_pad_len"), py::arg("l_pad_token"), py::arg("r_pad_token"),
  632. py::arg("separator"));
  633. (void)py::class_<WordpieceTokenizerOp, TensorOp, std::shared_ptr<WordpieceTokenizerOp>>(
  634. *m, "WordpieceTokenizerOp", "Tokenize scalar token or 1-D tokens to subword tokens.")
  635. .def(
  636. py::init<const std::shared_ptr<Vocab> &, const std::string &, const int &, const std::string &, const bool &>(),
  637. py::arg("vocab"), py::arg("suffix_indicator") = std::string(WordpieceTokenizerOp::kDefSuffixIndicator),
  638. py::arg("max_bytes_per_token") = WordpieceTokenizerOp::kDefMaxBytesPerToken,
  639. py::arg("unknown_token") = std::string(WordpieceTokenizerOp::kDefUnknownToken),
  640. py::arg("with_offsets") = WordpieceTokenizerOp::kDefWithOffsets);
  641. (void)py::class_<SlidingWindowOp, TensorOp, std::shared_ptr<SlidingWindowOp>>(
  642. *m, "SlidingWindowOp", "TensorOp to apply sliding window to a 1-D Tensor.")
  643. .def(py::init<uint32_t, int32_t>(), py::arg("width"), py::arg("axis"));
  644. (void)py::class_<SentencePieceTokenizerOp, TensorOp, std::shared_ptr<SentencePieceTokenizerOp>>(
  645. *m, "SentencePieceTokenizerOp", "Tokenize scalar token or 1-D tokens to tokens by sentence piece.")
  646. .def(py::init<std::shared_ptr<SentencePieceVocab> &, const SPieceTokenizerLoadType, const SPieceTokenizerOutType>(),
  647. py::arg("vocab"), py::arg("load_type") = SPieceTokenizerLoadType::kModel,
  648. py::arg("out_type") = SPieceTokenizerOutType::kString)
  649. .def(
  650. py::init<const std::string &, const std::string &, const SPieceTokenizerLoadType, const SPieceTokenizerOutType>(),
  651. py::arg("model_path"), py::arg("model_filename"), py::arg("load_type") = SPieceTokenizerLoadType::kFile,
  652. py::arg("out_type") = SPieceTokenizerOutType::kString);
  653. }
  654. void bindDependIcuTokenizerOps(py::module *m) {
  655. #ifdef ENABLE_ICU4C
  656. (void)py::class_<WhitespaceTokenizerOp, TensorOp, std::shared_ptr<WhitespaceTokenizerOp>>(
  657. *m, "WhitespaceTokenizerOp", "Tokenize a scalar tensor of UTF-8 string on ICU defined whitespaces.")
  658. .def(py::init<const bool &>(), py::arg("with_offsets") = WhitespaceTokenizerOp::kDefWithOffsets);
  659. (void)py::class_<UnicodeScriptTokenizerOp, TensorOp, std::shared_ptr<UnicodeScriptTokenizerOp>>(
  660. *m, "UnicodeScriptTokenizerOp", "Tokenize a scalar tensor of UTF-8 string on Unicode script boundaries.")
  661. .def(py::init<>())
  662. .def(py::init<const bool &, const bool &>(),
  663. py::arg("keep_whitespace") = UnicodeScriptTokenizerOp::kDefKeepWhitespace,
  664. py::arg("with_offsets") = UnicodeScriptTokenizerOp::kDefWithOffsets);
  665. (void)py::class_<CaseFoldOp, TensorOp, std::shared_ptr<CaseFoldOp>>(
  666. *m, "CaseFoldOp", "Apply case fold operation on utf-8 string tensor")
  667. .def(py::init<>());
  668. (void)py::class_<NormalizeUTF8Op, TensorOp, std::shared_ptr<NormalizeUTF8Op>>(
  669. *m, "NormalizeUTF8Op", "Apply normalize operation on utf-8 string tensor.")
  670. .def(py::init<>())
  671. .def(py::init<NormalizeForm>(), py::arg("normalize_form") = NormalizeUTF8Op::kDefNormalizeForm);
  672. (void)py::class_<RegexReplaceOp, TensorOp, std::shared_ptr<RegexReplaceOp>>(
  673. *m, "RegexReplaceOp", "Replace utf-8 string tensor with 'replace' according to regular expression 'pattern'.")
  674. .def(py::init<const std::string &, const std::string &, bool>(), py::arg("pattern"), py::arg("replace"),
  675. py::arg("replace_all"));
  676. (void)py::class_<RegexTokenizerOp, TensorOp, std::shared_ptr<RegexTokenizerOp>>(
  677. *m, "RegexTokenizerOp", "Tokenize a scalar tensor of UTF-8 string by regex expression pattern.")
  678. .def(py::init<const std::string &, const std::string &, const bool &>(), py::arg("delim_pattern"),
  679. py::arg("keep_delim_pattern"), py::arg("with_offsets") = RegexTokenizerOp::kDefWithOffsets);
  680. (void)py::class_<BasicTokenizerOp, TensorOp, std::shared_ptr<BasicTokenizerOp>>(
  681. *m, "BasicTokenizerOp", "Tokenize a scalar tensor of UTF-8 string by specific rules.")
  682. .def(py::init<const bool &, const bool &, const NormalizeForm &, const bool &, const bool &>(),
  683. py::arg("lower_case") = BasicTokenizerOp::kDefLowerCase,
  684. py::arg("keep_whitespace") = BasicTokenizerOp::kDefKeepWhitespace,
  685. py::arg("normalization_form") = BasicTokenizerOp::kDefNormalizationForm,
  686. py::arg("preserve_unused_token") = BasicTokenizerOp::kDefPreserveUnusedToken,
  687. py::arg("with_offsets") = BasicTokenizerOp::kDefWithOffsets);
  688. (void)py::class_<BertTokenizerOp, TensorOp, std::shared_ptr<BertTokenizerOp>>(*m, "BertTokenizerOp",
  689. "Tokenizer used for Bert text process.")
  690. .def(py::init<const std::shared_ptr<Vocab> &, const std::string &, const int &, const std::string &, const bool &,
  691. const bool &, const NormalizeForm &, const bool &, const bool &>(),
  692. py::arg("vocab"), py::arg("suffix_indicator") = std::string(WordpieceTokenizerOp::kDefSuffixIndicator),
  693. py::arg("max_bytes_per_token") = WordpieceTokenizerOp::kDefMaxBytesPerToken,
  694. py::arg("unknown_token") = std::string(WordpieceTokenizerOp::kDefUnknownToken),
  695. py::arg("lower_case") = BasicTokenizerOp::kDefLowerCase,
  696. py::arg("keep_whitespace") = BasicTokenizerOp::kDefKeepWhitespace,
  697. py::arg("normalization_form") = BasicTokenizerOp::kDefNormalizationForm,
  698. py::arg("preserve_unused_token") = BasicTokenizerOp::kDefPreserveUnusedToken,
  699. py::arg("with_offsets") = WordpieceTokenizerOp::kDefWithOffsets);
  700. #endif
  701. }
  702. void bindSamplerOps(py::module *m) {
  703. (void)py::class_<Sampler, std::shared_ptr<Sampler>>(*m, "Sampler")
  704. .def("set_num_rows", [](Sampler &self, int64_t rows) { THROW_IF_ERROR(self.SetNumRowsInDataset(rows)); })
  705. .def("set_num_samples", [](Sampler &self, int64_t samples) { THROW_IF_ERROR(self.SetNumSamples(samples)); })
  706. .def("initialize", [](Sampler &self) { THROW_IF_ERROR(self.InitSampler()); })
  707. .def("get_indices",
  708. [](Sampler &self) {
  709. py::array ret;
  710. THROW_IF_ERROR(self.GetAllIdsThenReset(&ret));
  711. return ret;
  712. })
  713. .def("add_child",
  714. [](std::shared_ptr<Sampler> self, std::shared_ptr<Sampler> child) { THROW_IF_ERROR(self->AddChild(child)); });
  715. (void)py::class_<mindrecord::ShardOperator, std::shared_ptr<mindrecord::ShardOperator>>(*m, "ShardOperator")
  716. .def("add_child", [](std::shared_ptr<mindrecord::ShardOperator> self,
  717. std::shared_ptr<mindrecord::ShardOperator> child) { self->SetChildOp(child); });
  718. (void)py::class_<DistributedSampler, Sampler, std::shared_ptr<DistributedSampler>>(*m, "DistributedSampler")
  719. .def(py::init<int64_t, int64_t, int64_t, bool, uint32_t>());
  720. (void)py::class_<PKSampler, Sampler, std::shared_ptr<PKSampler>>(*m, "PKSampler")
  721. .def(py::init<int64_t, int64_t, bool>());
  722. (void)py::class_<RandomSampler, Sampler, std::shared_ptr<RandomSampler>>(*m, "RandomSampler")
  723. .def(py::init<int64_t, bool, bool>());
  724. (void)py::class_<SequentialSampler, Sampler, std::shared_ptr<SequentialSampler>>(*m, "SequentialSampler")
  725. .def(py::init<int64_t, int64_t>());
  726. (void)py::class_<SubsetRandomSampler, Sampler, std::shared_ptr<SubsetRandomSampler>>(*m, "SubsetRandomSampler")
  727. .def(py::init<int64_t, std::vector<int64_t>>());
  728. (void)py::class_<mindrecord::ShardSample, mindrecord::ShardOperator, std::shared_ptr<mindrecord::ShardSample>>(
  729. *m, "MindrecordSubsetRandomSampler")
  730. .def(py::init<std::vector<int64_t>, uint32_t>(), py::arg("indices"), py::arg("seed") = GetSeed());
  731. (void)py::class_<mindrecord::ShardPkSample, mindrecord::ShardOperator, std::shared_ptr<mindrecord::ShardPkSample>>(
  732. *m, "MindrecordPkSampler")
  733. .def(py::init([](int64_t kVal, std::string kColumn, bool shuffle) {
  734. if (shuffle == true) {
  735. return std::make_shared<mindrecord::ShardPkSample>(kColumn, kVal, std::numeric_limits<int64_t>::max(),
  736. GetSeed());
  737. } else {
  738. return std::make_shared<mindrecord::ShardPkSample>(kColumn, kVal);
  739. }
  740. }));
  741. (void)py::class_<mindrecord::ShardDistributedSample, mindrecord::ShardSample,
  742. std::shared_ptr<mindrecord::ShardDistributedSample>>(*m, "MindrecordDistributedSampler")
  743. .def(py::init<int64_t, int64_t, bool, uint32_t, int64_t>());
  744. (void)py::class_<mindrecord::ShardShuffle, mindrecord::ShardOperator, std::shared_ptr<mindrecord::ShardShuffle>>(
  745. *m, "MindrecordRandomSampler")
  746. .def(py::init([](int64_t num_samples, bool replacement, bool reshuffle_each_epoch) {
  747. return std::make_shared<mindrecord::ShardShuffle>(GetSeed(), num_samples, replacement, reshuffle_each_epoch);
  748. }));
  749. (void)py::class_<mindrecord::ShardSequentialSample, mindrecord::ShardSample,
  750. std::shared_ptr<mindrecord::ShardSequentialSample>>(*m, "MindrecordSequentialSampler")
  751. .def(py::init([](int num_samples, int start_index) {
  752. return std::make_shared<mindrecord::ShardSequentialSample>(num_samples, start_index);
  753. }));
  754. (void)py::class_<WeightedRandomSampler, Sampler, std::shared_ptr<WeightedRandomSampler>>(*m, "WeightedRandomSampler")
  755. .def(py::init<int64_t, std::vector<double>, bool>());
  756. (void)py::class_<PythonSampler, Sampler, std::shared_ptr<PythonSampler>>(*m, "PythonSampler")
  757. .def(py::init<int64_t, py::object>());
  758. }
  759. void bindInfoObjects(py::module *m) {
  760. (void)py::class_<BatchOp::CBatchInfo>(*m, "CBatchInfo")
  761. .def(py::init<int64_t, int64_t, int64_t>())
  762. .def("get_epoch_num", &BatchOp::CBatchInfo::get_epoch_num)
  763. .def("get_batch_num", &BatchOp::CBatchInfo::get_batch_num);
  764. }
  765. void bindCacheClient(py::module *m) {
  766. (void)py::class_<CacheClient, std::shared_ptr<CacheClient>>(*m, "CacheClient")
  767. .def(py::init<uint32_t, uint64_t, bool>());
  768. }
  769. void bindVocabObjects(py::module *m) {
  770. (void)py::class_<Vocab, std::shared_ptr<Vocab>>(*m, "Vocab")
  771. .def(py::init<>())
  772. .def_static("from_list",
  773. [](const py::list &words, const py::list &special_tokens, bool special_first) {
  774. std::shared_ptr<Vocab> v;
  775. THROW_IF_ERROR(Vocab::BuildFromPyList(words, special_tokens, special_first, &v));
  776. return v;
  777. })
  778. .def_static("from_file",
  779. [](const std::string &path, const std::string &dlm, int32_t vocab_size, const py::list &special_tokens,
  780. bool special_first) {
  781. std::shared_ptr<Vocab> v;
  782. THROW_IF_ERROR(Vocab::BuildFromFile(path, dlm, vocab_size, special_tokens, special_first, &v));
  783. return v;
  784. })
  785. .def_static("from_dict", [](const py::dict &words) {
  786. std::shared_ptr<Vocab> v;
  787. THROW_IF_ERROR(Vocab::BuildFromPyDict(words, &v));
  788. return v;
  789. });
  790. (void)py::class_<SentencePieceVocab, std::shared_ptr<SentencePieceVocab>>(*m, "SentencePieceVocab")
  791. .def(py::init<>())
  792. .def_static("from_file",
  793. [](const py::list &paths, const int vocab_size, const float character_coverage,
  794. const SentencePieceModel model_type, const py::dict &params) {
  795. std::shared_ptr<SentencePieceVocab> v;
  796. std::vector<std::string> path_list;
  797. for (auto path : paths) {
  798. path_list.emplace_back(py::str(path));
  799. }
  800. std::unordered_map<std::string, std::string> param_map;
  801. for (auto param : params) {
  802. std::string key = py::reinterpret_borrow<py::str>(param.first);
  803. if (key == "input" || key == "vocab_size" || key == "model_prefix" || key == "character_coverage" ||
  804. key == "model_type") {
  805. continue;
  806. }
  807. param_map[key] = py::reinterpret_borrow<py::str>(param.second);
  808. }
  809. THROW_IF_ERROR(SentencePieceVocab::BuildFromFile(path_list, vocab_size, character_coverage,
  810. model_type, param_map, &v));
  811. return v;
  812. })
  813. .def_static("save_model",
  814. [](const std::shared_ptr<SentencePieceVocab> *vocab, std::string path, std::string filename) {
  815. THROW_IF_ERROR(SentencePieceVocab::SaveModel(vocab, path, filename));
  816. });
  817. }
  818. void bindGraphData(py::module *m) {
  819. (void)py::class_<gnn::Graph, std::shared_ptr<gnn::Graph>>(*m, "Graph")
  820. .def(py::init([](std::string dataset_file, int32_t num_workers) {
  821. std::shared_ptr<gnn::Graph> g_out = std::make_shared<gnn::Graph>(dataset_file, num_workers);
  822. THROW_IF_ERROR(g_out->Init());
  823. return g_out;
  824. }))
  825. .def("get_all_nodes",
  826. [](gnn::Graph &g, gnn::NodeType node_type) {
  827. std::shared_ptr<Tensor> out;
  828. THROW_IF_ERROR(g.GetAllNodes(node_type, &out));
  829. return out;
  830. })
  831. .def("get_all_edges",
  832. [](gnn::Graph &g, gnn::EdgeType edge_type) {
  833. std::shared_ptr<Tensor> out;
  834. THROW_IF_ERROR(g.GetAllEdges(edge_type, &out));
  835. return out;
  836. })
  837. .def("get_nodes_from_edges",
  838. [](gnn::Graph &g, std::vector<gnn::NodeIdType> edge_list) {
  839. std::shared_ptr<Tensor> out;
  840. THROW_IF_ERROR(g.GetNodesFromEdges(edge_list, &out));
  841. return out;
  842. })
  843. .def("get_all_neighbors",
  844. [](gnn::Graph &g, std::vector<gnn::NodeIdType> node_list, gnn::NodeType neighbor_type) {
  845. std::shared_ptr<Tensor> out;
  846. THROW_IF_ERROR(g.GetAllNeighbors(node_list, neighbor_type, &out));
  847. return out;
  848. })
  849. .def("get_sampled_neighbors",
  850. [](gnn::Graph &g, std::vector<gnn::NodeIdType> node_list, std::vector<gnn::NodeIdType> neighbor_nums,
  851. std::vector<gnn::NodeType> neighbor_types) {
  852. std::shared_ptr<Tensor> out;
  853. THROW_IF_ERROR(g.GetSampledNeighbors(node_list, neighbor_nums, neighbor_types, &out));
  854. return out;
  855. })
  856. .def("get_neg_sampled_neighbors",
  857. [](gnn::Graph &g, std::vector<gnn::NodeIdType> node_list, gnn::NodeIdType neighbor_num,
  858. gnn::NodeType neg_neighbor_type) {
  859. std::shared_ptr<Tensor> out;
  860. THROW_IF_ERROR(g.GetNegSampledNeighbors(node_list, neighbor_num, neg_neighbor_type, &out));
  861. return out;
  862. })
  863. .def("get_node_feature",
  864. [](gnn::Graph &g, std::shared_ptr<Tensor> node_list, std::vector<gnn::FeatureType> feature_types) {
  865. TensorRow out;
  866. THROW_IF_ERROR(g.GetNodeFeature(node_list, feature_types, &out));
  867. return out.getRow();
  868. })
  869. .def("get_edge_feature",
  870. [](gnn::Graph &g, std::shared_ptr<Tensor> edge_list, std::vector<gnn::FeatureType> feature_types) {
  871. TensorRow out;
  872. THROW_IF_ERROR(g.GetEdgeFeature(edge_list, feature_types, &out));
  873. return out.getRow();
  874. })
  875. .def("graph_info",
  876. [](gnn::Graph &g) {
  877. py::dict out;
  878. THROW_IF_ERROR(g.GraphInfo(&out));
  879. return out;
  880. })
  881. .def("random_walk", [](gnn::Graph &g, std::vector<gnn::NodeIdType> node_list, std::vector<gnn::NodeType> meta_path,
  882. float step_home_param, float step_away_param, gnn::NodeIdType default_node) {
  883. std::shared_ptr<Tensor> out;
  884. THROW_IF_ERROR(g.RandomWalk(node_list, meta_path, step_home_param, step_away_param, default_node, &out));
  885. return out;
  886. });
  887. }
  888. void bindRandomTransformTensorOps(py::module *m) {
  889. (void)py::class_<ComposeOp, TensorOp, std::shared_ptr<ComposeOp>>(*m, "ComposeOp")
  890. .def(py::init([](const py::list &ops) {
  891. std::vector<std::shared_ptr<TensorOp>> t_ops;
  892. THROW_IF_ERROR(PyListToTensorOps(ops, &t_ops));
  893. return std::make_shared<ComposeOp>(t_ops);
  894. }));
  895. (void)py::class_<RandomChoiceOp, TensorOp, std::shared_ptr<RandomChoiceOp>>(*m, "RandomChoiceOp")
  896. .def(py::init([](const py::list &ops) {
  897. std::vector<std::shared_ptr<TensorOp>> t_ops;
  898. THROW_IF_ERROR(PyListToTensorOps(ops, &t_ops));
  899. return std::make_shared<RandomChoiceOp>(t_ops);
  900. }));
  901. (void)py::class_<RandomApplyOp, TensorOp, std::shared_ptr<RandomApplyOp>>(*m, "RandomApplyOp")
  902. .def(py::init([](double prob, const py::list &ops) {
  903. std::vector<std::shared_ptr<TensorOp>> t_ops;
  904. THROW_IF_ERROR(PyListToTensorOps(ops, &t_ops));
  905. if (prob < 0 || prob > 1) {
  906. THROW_IF_ERROR(Status(StatusCode::kUnexpectedError, "prob needs to be within [0,1]."));
  907. }
  908. return std::make_shared<RandomApplyOp>(prob, t_ops);
  909. }));
  910. (void)py::class_<RandomSelectSubpolicyOp, TensorOp, std::shared_ptr<RandomSelectSubpolicyOp>>(
  911. *m, "RandomSelectSubpolicyOp")
  912. .def(py::init([](const py::list &py_policy) {
  913. std::vector<Subpolicy> cpp_policy;
  914. for (auto &py_sub : py_policy) {
  915. cpp_policy.push_back({});
  916. for (auto handle : py_sub.cast<py::list>()) {
  917. py::tuple tp = handle.cast<py::tuple>();
  918. if (tp.is_none() || tp.size() != 2) {
  919. THROW_IF_ERROR(Status(StatusCode::kUnexpectedError, "Each tuple in subpolicy should be (op, prob)."));
  920. }
  921. std::shared_ptr<TensorOp> t_op;
  922. if (py::isinstance<TensorOp>(tp[0])) {
  923. t_op = (tp[0]).cast<std::shared_ptr<TensorOp>>();
  924. } else if (py::isinstance<py::function>(tp[0])) {
  925. t_op = std::make_shared<PyFuncOp>((tp[0]).cast<py::function>());
  926. } else {
  927. THROW_IF_ERROR(Status(StatusCode::kUnexpectedError, "op is neither a tensorOp nor a pyfunc."));
  928. }
  929. double prob = (tp[1]).cast<py::float_>();
  930. if (prob < 0 || prob > 1) {
  931. THROW_IF_ERROR(Status(StatusCode::kUnexpectedError, "prob needs to be with [0,1]."));
  932. }
  933. cpp_policy.back().emplace_back(std::make_pair(t_op, prob));
  934. }
  935. }
  936. return std::make_shared<RandomSelectSubpolicyOp>(cpp_policy);
  937. }));
  938. }
  939. // This is where we externalize the C logic as python modules
  940. PYBIND11_MODULE(_c_dataengine, m) {
  941. m.doc() = "pybind11 for _c_dataengine";
  942. (void)py::class_<DatasetOp, std::shared_ptr<DatasetOp>>(m, "DatasetOp");
  943. (void)py::enum_<OpName>(m, "OpName", py::arithmetic())
  944. .value("SHUFFLE", OpName::kShuffle)
  945. .value("BATCH", OpName::kBatch)
  946. .value("BUCKETBATCH", OpName::kBucketBatch)
  947. .value("BARRIER", OpName::kBarrier)
  948. .value("MINDRECORD", OpName::kMindrecord)
  949. .value("CACHE", OpName::kCache)
  950. .value("REPEAT", OpName::kRepeat)
  951. .value("SKIP", OpName::kSkip)
  952. .value("TAKE", OpName::kTake)
  953. .value("ZIP", OpName::kZip)
  954. .value("CONCAT", OpName::kConcat)
  955. .value("MAP", OpName::kMap)
  956. .value("FILTER", OpName::kFilter)
  957. .value("DEVICEQUEUE", OpName::kDeviceQueue)
  958. .value("GENERATOR", OpName::kGenerator)
  959. .export_values()
  960. .value("RENAME", OpName::kRename)
  961. .value("TFREADER", OpName::kTfReader)
  962. .value("PROJECT", OpName::kProject)
  963. .value("IMAGEFOLDER", OpName::kImageFolder)
  964. .value("MNIST", OpName::kMnist)
  965. .value("MANIFEST", OpName::kManifest)
  966. .value("VOC", OpName::kVoc)
  967. .value("COCO", OpName::kCoco)
  968. .value("CIFAR10", OpName::kCifar10)
  969. .value("CIFAR100", OpName::kCifar100)
  970. .value("RANDOMDATA", OpName::kRandomData)
  971. .value("BUILDVOCAB", OpName::kBuildVocab)
  972. .value("SENTENCEPIECEVOCAB", OpName::kSentencePieceVocab)
  973. .value("CELEBA", OpName::kCelebA)
  974. .value("TEXTFILE", OpName::kTextFile)
  975. .value("EPOCHCTRL", OpName::kEpochCtrl)
  976. .value("CSV", OpName::kCsv)
  977. .value("CLUE", OpName::kClue);
  978. (void)py::enum_<JiebaMode>(m, "JiebaMode", py::arithmetic())
  979. .value("DE_JIEBA_MIX", JiebaMode::kMix)
  980. .value("DE_JIEBA_MP", JiebaMode::kMp)
  981. .value("DE_JIEBA_HMM", JiebaMode::kHmm)
  982. .export_values();
  983. #ifdef ENABLE_ICU4C
  984. (void)py::enum_<NormalizeForm>(m, "NormalizeForm", py::arithmetic())
  985. .value("DE_NORMALIZE_NONE", NormalizeForm::kNone)
  986. .value("DE_NORMALIZE_NFC", NormalizeForm::kNfc)
  987. .value("DE_NORMALIZE_NFKC", NormalizeForm::kNfkc)
  988. .value("DE_NORMALIZE_NFD", NormalizeForm::kNfd)
  989. .value("DE_NORMALIZE_NFKD", NormalizeForm::kNfkd)
  990. .export_values();
  991. #endif
  992. (void)py::enum_<InterpolationMode>(m, "InterpolationMode", py::arithmetic())
  993. .value("DE_INTER_LINEAR", InterpolationMode::kLinear)
  994. .value("DE_INTER_CUBIC", InterpolationMode::kCubic)
  995. .value("DE_INTER_AREA", InterpolationMode::kArea)
  996. .value("DE_INTER_NEAREST_NEIGHBOUR", InterpolationMode::kNearestNeighbour)
  997. .export_values();
  998. (void)py::enum_<BorderType>(m, "BorderType", py::arithmetic())
  999. .value("DE_BORDER_CONSTANT", BorderType::kConstant)
  1000. .value("DE_BORDER_EDGE", BorderType::kEdge)
  1001. .value("DE_BORDER_REFLECT", BorderType::kReflect)
  1002. .value("DE_BORDER_SYMMETRIC", BorderType::kSymmetric)
  1003. .export_values();
  1004. (void)py::enum_<SentencePieceModel>(m, "SentencePieceModel", py::arithmetic())
  1005. .value("DE_SENTENCE_PIECE_UNIGRAM", SentencePieceModel::kUnigram)
  1006. .value("DE_SENTENCE_PIECE_BPE", SentencePieceModel::kBpe)
  1007. .value("DE_SENTENCE_PIECE_CHAR", SentencePieceModel::kChar)
  1008. .value("DE_SENTENCE_PIECE_WORD", SentencePieceModel::kWord)
  1009. .export_values();
  1010. (void)py::enum_<SPieceTokenizerOutType>(m, "SPieceTokenizerOutType", py::arithmetic())
  1011. .value("DE_SPIECE_TOKENIZER_OUTTYPE_KString", SPieceTokenizerOutType::kString)
  1012. .value("DE_SPIECE_TOKENIZER_OUTTYPE_KINT", SPieceTokenizerOutType::kInt)
  1013. .export_values();
  1014. (void)py::enum_<SPieceTokenizerLoadType>(m, "SPieceTokenizerLoadType", py::arithmetic())
  1015. .value("DE_SPIECE_TOKENIZER_LOAD_KFILE", SPieceTokenizerLoadType::kFile)
  1016. .value("DE_SPIECE_TOKENIZER_LOAD_KMODEL", SPieceTokenizerLoadType::kModel)
  1017. .export_values();
  1018. bindDEPipeline(&m);
  1019. bindTensor(&m);
  1020. bindTensorOps1(&m);
  1021. bindTensorOps2(&m);
  1022. bindTensorOps3(&m);
  1023. bindTensorOps4(&m);
  1024. bindTokenizerOps(&m);
  1025. bindSamplerOps(&m);
  1026. bindDatasetOps(&m);
  1027. bindInfoObjects(&m);
  1028. bindCacheClient(&m);
  1029. bindVocabObjects(&m);
  1030. bindGraphData(&m);
  1031. bindDependIcuTokenizerOps(&m);
  1032. bindRandomTransformTensorOps(&m);
  1033. }
  1034. } // namespace dataset
  1035. } // namespace mindspore