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