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