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

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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/kernels/no_op.h"
  19. #include "dataset/kernels/data/one_hot_op.h"
  20. #include "dataset/kernels/image/center_crop_op.h"
  21. #include "dataset/kernels/image/cut_out_op.h"
  22. #include "dataset/kernels/image/decode_op.h"
  23. #include "dataset/kernels/image/hwc_to_chw_op.h"
  24. #include "dataset/kernels/image/image_utils.h"
  25. #include "dataset/kernels/image/normalize_op.h"
  26. #include "dataset/kernels/image/pad_op.h"
  27. #include "dataset/kernels/image/random_color_adjust_op.h"
  28. #include "dataset/kernels/image/random_crop_decode_resize_op.h"
  29. #include "dataset/kernels/image/random_crop_and_resize_op.h"
  30. #include "dataset/kernels/image/random_crop_op.h"
  31. #include "dataset/kernels/image/random_horizontal_flip_op.h"
  32. #include "dataset/kernels/image/random_resize_op.h"
  33. #include "dataset/kernels/image/random_rotation_op.h"
  34. #include "dataset/kernels/image/random_vertical_flip_op.h"
  35. #include "dataset/kernels/image/rescale_op.h"
  36. #include "dataset/kernels/image/resize_bilinear_op.h"
  37. #include "dataset/kernels/image/resize_op.h"
  38. #include "dataset/kernels/image/uniform_aug_op.h"
  39. #include "dataset/kernels/data/type_cast_op.h"
  40. #include "dataset/kernels/text/jieba_tokenizer_op.h"
  41. #include "dataset/engine/datasetops/source/cifar_op.h"
  42. #include "dataset/engine/datasetops/source/image_folder_op.h"
  43. #include "dataset/engine/datasetops/source/io_block.h"
  44. #include "dataset/engine/datasetops/source/mnist_op.h"
  45. #include "dataset/engine/datasetops/source/manifest_op.h"
  46. #include "dataset/engine/datasetops/source/mindrecord_op.h"
  47. #include "dataset/engine/datasetops/source/random_data_op.h"
  48. #include "dataset/engine/datasetops/source/sampler/distributed_sampler.h"
  49. #include "dataset/engine/datasetops/source/sampler/pk_sampler.h"
  50. #include "dataset/engine/datasetops/source/sampler/random_sampler.h"
  51. #include "dataset/engine/datasetops/source/sampler/sequential_sampler.h"
  52. #include "dataset/engine/datasetops/source/sampler/subset_random_sampler.h"
  53. #include "dataset/engine/datasetops/source/sampler/weighted_random_sampler.h"
  54. #include "dataset/engine/datasetops/source/sampler/python_sampler.h"
  55. #include "dataset/engine/datasetops/source/tf_reader_op.h"
  56. #include "dataset/engine/jagged_connector.h"
  57. #include "dataset/engine/datasetops/source/text_file_op.h"
  58. #include "dataset/engine/datasetops/source/voc_op.h"
  59. #include "dataset/kernels/data/to_float16_op.h"
  60. #include "dataset/util/random.h"
  61. #include "mindrecord/include/shard_operator.h"
  62. #include "mindrecord/include/shard_pk_sample.h"
  63. #include "mindrecord/include/shard_sample.h"
  64. #include "pybind11/pybind11.h"
  65. #include "pybind11/stl.h"
  66. #include "pybind11/stl_bind.h"
  67. namespace py = pybind11;
  68. namespace mindspore {
  69. namespace dataset {
  70. #define THROW_IF_ERROR(s) \
  71. do { \
  72. Status rc = std::move(s); \
  73. if (rc.IsError()) throw std::runtime_error(rc.ToString()); \
  74. } while (false)
  75. void bindDEPipeline(py::module *m) {
  76. (void)py::class_<DEPipeline>(*m, "DEPipeline")
  77. .def(py::init<>())
  78. .def(
  79. "AddNodeToTree",
  80. [](DEPipeline &de, const OpName &op_name, const py::dict &args) {
  81. DsOpPtr op;
  82. THROW_IF_ERROR(de.AddNodeToTree(op_name, args, &op));
  83. return op;
  84. },
  85. py::return_value_policy::reference)
  86. .def_static("AddChildToParentNode",
  87. [](const DsOpPtr &child_op, const DsOpPtr &parent_op) {
  88. THROW_IF_ERROR(DEPipeline::AddChildToParentNode(child_op, parent_op));
  89. })
  90. .def("AssignRootNode",
  91. [](DEPipeline &de, const DsOpPtr &dataset_op) { THROW_IF_ERROR(de.AssignRootNode(dataset_op)); })
  92. .def("SetBatchParameters",
  93. [](DEPipeline &de, const py::dict &args) { THROW_IF_ERROR(de.SetBatchParameters(args)); })
  94. .def("LaunchTreeExec", [](DEPipeline &de) { THROW_IF_ERROR(de.LaunchTreeExec()); })
  95. .def("GetNextAsMap",
  96. [](DEPipeline &de) {
  97. py::dict out;
  98. THROW_IF_ERROR(de.GetNextAsMap(&out));
  99. return out;
  100. })
  101. .def("GetNextAsList",
  102. [](DEPipeline &de) {
  103. py::list out;
  104. THROW_IF_ERROR(de.GetNextAsList(&out));
  105. return out;
  106. })
  107. .def("GetOutputShapes",
  108. [](DEPipeline &de) {
  109. py::list out;
  110. THROW_IF_ERROR(de.GetOutputShapes(&out));
  111. return out;
  112. })
  113. .def("GetOutputTypes",
  114. [](DEPipeline &de) {
  115. py::list out;
  116. THROW_IF_ERROR(de.GetOutputTypes(&out));
  117. return out;
  118. })
  119. .def("GetDatasetSize", &DEPipeline::GetDatasetSize)
  120. .def("GetBatchSize", &DEPipeline::GetBatchSize)
  121. .def("GetNumClasses", &DEPipeline::GetNumClasses)
  122. .def("GetRepeatCount", &DEPipeline::GetRepeatCount);
  123. }
  124. void bindDatasetOps(py::module *m) {
  125. (void)py::class_<TFReaderOp, DatasetOp, std::shared_ptr<TFReaderOp>>(*m, "TFReaderOp")
  126. .def_static("get_num_rows", [](const py::list &files, int64_t numParallelWorkers, bool estimate = false) {
  127. int64_t count = 0;
  128. std::vector<std::string> filenames;
  129. for (auto l : files) {
  130. !l.is_none() ? filenames.push_back(py::str(l)) : (void)filenames.emplace_back("");
  131. }
  132. THROW_IF_ERROR(TFReaderOp::CountTotalRows(&count, filenames, numParallelWorkers, estimate));
  133. return count;
  134. });
  135. (void)py::class_<CifarOp, DatasetOp, std::shared_ptr<CifarOp>>(*m, "CifarOp")
  136. .def_static("get_num_rows", [](const std::string &dir, int64_t numSamples, bool isCifar10) {
  137. int64_t count = 0;
  138. THROW_IF_ERROR(CifarOp::CountTotalRows(dir, numSamples, isCifar10, &count));
  139. return count;
  140. });
  141. (void)py::class_<ImageFolderOp, DatasetOp, std::shared_ptr<ImageFolderOp>>(*m, "ImageFolderOp")
  142. .def_static("get_num_rows_and_classes", [](const std::string &path, int64_t numSamples) {
  143. int64_t count = 0, num_classes = 0;
  144. THROW_IF_ERROR(
  145. ImageFolderOp::CountRowsAndClasses(path, numSamples, std::set<std::string>{}, &count, &num_classes));
  146. return py::make_tuple(count, num_classes);
  147. });
  148. (void)py::class_<MindRecordOp, DatasetOp, std::shared_ptr<MindRecordOp>>(*m, "MindRecordOp")
  149. .def_static("get_num_rows",
  150. [](const std::vector<std::string> &paths, bool load_dataset, const py::object &sampler) {
  151. int64_t count = 0;
  152. std::shared_ptr<mindrecord::ShardOperator> op;
  153. if (py::hasattr(sampler, "_create_for_minddataset")) {
  154. auto create = sampler.attr("_create_for_minddataset");
  155. op = create().cast<std::shared_ptr<mindrecord::ShardOperator>>();
  156. }
  157. THROW_IF_ERROR(MindRecordOp::CountTotalRows(paths, load_dataset, op, &count));
  158. return count;
  159. });
  160. (void)py::class_<ManifestOp, DatasetOp, std::shared_ptr<ManifestOp>>(*m, "ManifestOp")
  161. .def_static("get_num_rows_and_classes",
  162. [](const std::string &file, int64_t numSamples, const py::dict &dict, const std::string &usage) {
  163. int64_t count = 0, num_classes = 0;
  164. THROW_IF_ERROR(ManifestOp::CountTotalRows(file, numSamples, dict, usage, &count, &num_classes));
  165. return py::make_tuple(count, num_classes);
  166. })
  167. .def_static("get_class_indexing",
  168. [](const std::string &file, int64_t numSamples, const py::dict &dict, const std::string &usage) {
  169. std::map<std::string, int32_t> output_class_indexing;
  170. THROW_IF_ERROR(ManifestOp::GetClassIndexing(file, numSamples, dict, usage, &output_class_indexing));
  171. return output_class_indexing;
  172. });
  173. (void)py::class_<MnistOp, DatasetOp, std::shared_ptr<MnistOp>>(*m, "MnistOp")
  174. .def_static("get_num_rows", [](const std::string &dir, int64_t numSamples) {
  175. int64_t count = 0;
  176. THROW_IF_ERROR(MnistOp::CountTotalRows(dir, numSamples, &count));
  177. return count;
  178. });
  179. (void)py::class_<TextFileOp, DatasetOp, std::shared_ptr<TextFileOp>>(*m, "TextFileOp")
  180. .def_static("get_num_rows", [](const py::list &files) {
  181. int64_t count = 0;
  182. std::vector<std::string> filenames;
  183. for (auto file : files) {
  184. !file.is_none() ? filenames.push_back(py::str(file)) : (void)filenames.emplace_back("");
  185. }
  186. THROW_IF_ERROR(TextFileOp::CountAllFileRows(filenames, &count));
  187. return count;
  188. });
  189. (void)py::class_<VOCOp, DatasetOp, std::shared_ptr<VOCOp>>(*m, "VOCOp")
  190. .def_static("get_class_indexing", [](const std::string &dir, const std::string &task_type,
  191. const std::string &task_mode, const py::dict &dict, int64_t numSamples) {
  192. std::map<std::string, int32_t> output_class_indexing;
  193. THROW_IF_ERROR(VOCOp::GetClassIndexing(dir, task_type, task_mode, dict, numSamples, &output_class_indexing));
  194. return output_class_indexing;
  195. });
  196. }
  197. void bindTensor(py::module *m) {
  198. (void)py::class_<GlobalContext>(*m, "GlobalContext")
  199. .def_static("config_manager", &GlobalContext::config_manager, py::return_value_policy::reference);
  200. (void)py::class_<ConfigManager, std::shared_ptr<ConfigManager>>(*m, "ConfigManager")
  201. .def("__str__", &ConfigManager::ToString)
  202. .def("set_rows_per_buffer", &ConfigManager::set_rows_per_buffer)
  203. .def("set_num_parallel_workers", &ConfigManager::set_num_parallel_workers)
  204. .def("set_worker_connector_size", &ConfigManager::set_worker_connector_size)
  205. .def("set_op_connector_size", &ConfigManager::set_op_connector_size)
  206. .def("set_seed", &ConfigManager::set_seed)
  207. .def("get_rows_per_buffer", &ConfigManager::rows_per_buffer)
  208. .def("get_num_parallel_workers", &ConfigManager::num_parallel_workers)
  209. .def("get_worker_connector_size", &ConfigManager::worker_connector_size)
  210. .def("get_op_connector_size", &ConfigManager::op_connector_size)
  211. .def("get_seed", &ConfigManager::seed)
  212. .def("load", [](ConfigManager &c, std::string s) { (void)c.LoadFile(s); });
  213. (void)py::class_<Tensor, std::shared_ptr<Tensor>>(*m, "Tensor", py::buffer_protocol())
  214. .def(py::init([](py::array arr) {
  215. std::shared_ptr<Tensor> out;
  216. THROW_IF_ERROR(Tensor::CreateTensor(&out, arr));
  217. return out;
  218. }))
  219. .def_buffer([](Tensor &tensor) {
  220. py::buffer_info info;
  221. THROW_IF_ERROR(Tensor::GetBufferInfo(tensor, &info));
  222. return info;
  223. })
  224. .def("__str__", &Tensor::ToString)
  225. .def("shape", &Tensor::shape)
  226. .def("type", &Tensor::type)
  227. .def("as_array", [](py::object &t) {
  228. auto &tensor = py::cast<Tensor &>(t);
  229. if (tensor.type() == DataType::DE_STRING) {
  230. py::array res;
  231. tensor.GetDataAsNumpyStrings(&res);
  232. return res;
  233. }
  234. py::buffer_info info;
  235. THROW_IF_ERROR(Tensor::GetBufferInfo(tensor, &info));
  236. return py::array(pybind11::dtype(info), info.shape, info.strides, info.ptr, t);
  237. });
  238. (void)py::class_<TensorShape>(*m, "TensorShape")
  239. .def(py::init<py::list>())
  240. .def("__str__", &TensorShape::ToString)
  241. .def("as_list", &TensorShape::AsPyList)
  242. .def("is_known", &TensorShape::known);
  243. (void)py::class_<DataType>(*m, "DataType")
  244. .def(py::init<std::string>())
  245. .def(py::self == py::self)
  246. .def("__str__", &DataType::ToString)
  247. .def("__deepcopy__", [](py::object &t, py::dict memo) { return t; });
  248. }
  249. void bindTensorOps1(py::module *m) {
  250. (void)py::class_<TensorOp, std::shared_ptr<TensorOp>>(*m, "TensorOp")
  251. .def("__deepcopy__", [](py::object &t, py::dict memo) { return t; });
  252. (void)py::class_<NormalizeOp, TensorOp, std::shared_ptr<NormalizeOp>>(
  253. *m, "NormalizeOp", "Tensor operation to normalize an image. Takes mean and std.")
  254. .def(py::init<float, float, float, float, float, float>(), py::arg("meanR"), py::arg("meanG"), py::arg("meanB"),
  255. py::arg("stdR"), py::arg("stdG"), py::arg("stdB"));
  256. (void)py::class_<RescaleOp, TensorOp, std::shared_ptr<RescaleOp>>(
  257. *m, "RescaleOp", "Tensor operation to rescale an image. Takes scale and shift.")
  258. .def(py::init<float, float>(), py::arg("rescale"), py::arg("shift"));
  259. (void)py::class_<CenterCropOp, TensorOp, std::shared_ptr<CenterCropOp>>(
  260. *m, "CenterCropOp", "Tensor operation to crop and image in the middle. Takes height and width (optional)")
  261. .def(py::init<int32_t, int32_t>(), py::arg("height"), py::arg("width") = CenterCropOp::kDefWidth);
  262. (void)py::class_<ResizeOp, TensorOp, std::shared_ptr<ResizeOp>>(
  263. *m, "ResizeOp", "Tensor operation to resize an image. Takes height, width and mode")
  264. .def(py::init<int32_t, int32_t, InterpolationMode>(), py::arg("targetHeight"),
  265. py::arg("targetWidth") = ResizeOp::kDefWidth, py::arg("interpolation") = ResizeOp::kDefInterpolation);
  266. (void)py::class_<UniformAugOp, TensorOp, std::shared_ptr<UniformAugOp>>(
  267. *m, "UniformAugOp", "Tensor operation to apply random augmentation(s).")
  268. .def(py::init<py::list, int32_t>(), py::arg("operations"), py::arg("NumOps") = UniformAugOp::kDefNumOps);
  269. (void)py::class_<ResizeBilinearOp, TensorOp, std::shared_ptr<ResizeBilinearOp>>(
  270. *m, "ResizeBilinearOp",
  271. "Tensor operation to resize an image using "
  272. "Bilinear mode. Takes height and width.")
  273. .def(py::init<int32_t, int32_t>(), py::arg("targetHeight"), py::arg("targetWidth") = ResizeBilinearOp::kDefWidth);
  274. (void)py::class_<DecodeOp, TensorOp, std::shared_ptr<DecodeOp>>(*m, "DecodeOp",
  275. "Tensor operation to decode a jpg image")
  276. .def(py::init<>())
  277. .def(py::init<bool>(), py::arg("rgb_format") = DecodeOp::kDefRgbFormat);
  278. (void)py::class_<RandomHorizontalFlipOp, TensorOp, std::shared_ptr<RandomHorizontalFlipOp>>(
  279. *m, "RandomHorizontalFlipOp", "Tensor operation to randomly flip an image horizontally.")
  280. .def(py::init<float>(), py::arg("probability") = RandomHorizontalFlipOp::kDefProbability);
  281. }
  282. void bindTensorOps2(py::module *m) {
  283. (void)py::class_<RandomVerticalFlipOp, TensorOp, std::shared_ptr<RandomVerticalFlipOp>>(
  284. *m, "RandomVerticalFlipOp", "Tensor operation to randomly flip an image vertically.")
  285. .def(py::init<float>(), py::arg("probability") = RandomVerticalFlipOp::kDefProbability);
  286. (void)py::class_<RandomCropOp, TensorOp, std::shared_ptr<RandomCropOp>>(*m, "RandomCropOp",
  287. "Gives random crop of specified size "
  288. "Takes crop size")
  289. .def(py::init<int32_t, int32_t, int32_t, int32_t, int32_t, int32_t, BorderType, bool, uint8_t, uint8_t, uint8_t>(),
  290. py::arg("cropHeight"), py::arg("cropWidth"), py::arg("padTop") = RandomCropOp::kDefPadTop,
  291. py::arg("padBottom") = RandomCropOp::kDefPadBottom, py::arg("padLeft") = RandomCropOp::kDefPadLeft,
  292. py::arg("padRight") = RandomCropOp::kDefPadRight, py::arg("borderType") = RandomCropOp::kDefBorderType,
  293. py::arg("padIfNeeded") = RandomCropOp::kDefPadIfNeeded, py::arg("fillR") = RandomCropOp::kDefFillR,
  294. py::arg("fillG") = RandomCropOp::kDefFillG, py::arg("fillB") = RandomCropOp::kDefFillB);
  295. (void)py::class_<HwcToChwOp, TensorOp, std::shared_ptr<HwcToChwOp>>(*m, "ChannelSwapOp").def(py::init<>());
  296. (void)py::class_<OneHotOp, TensorOp, std::shared_ptr<OneHotOp>>(
  297. *m, "OneHotOp", "Tensor operation to apply one hot encoding. Takes number of classes.")
  298. .def(py::init<int32_t>());
  299. (void)py::class_<RandomRotationOp, TensorOp, std::shared_ptr<RandomRotationOp>>(
  300. *m, "RandomRotationOp",
  301. "Tensor operation to apply RandomRotation."
  302. "Takes a range for degrees and "
  303. "optional parameters for rotation center and image expand")
  304. .def(py::init<float, float, float, float, InterpolationMode, bool, uint8_t, uint8_t, uint8_t>(),
  305. py::arg("startDegree"), py::arg("endDegree"), py::arg("centerX") = RandomRotationOp::kDefCenterX,
  306. py::arg("centerY") = RandomRotationOp::kDefCenterY,
  307. py::arg("interpolation") = RandomRotationOp::kDefInterpolation,
  308. py::arg("expand") = RandomRotationOp::kDefExpand, py::arg("fillR") = RandomRotationOp::kDefFillR,
  309. py::arg("fillG") = RandomRotationOp::kDefFillG, py::arg("fillB") = RandomRotationOp::kDefFillB);
  310. }
  311. void bindTensorOps3(py::module *m) {
  312. (void)py::class_<RandomCropAndResizeOp, TensorOp, std::shared_ptr<RandomCropAndResizeOp>>(
  313. *m, "RandomCropAndResizeOp",
  314. "Tensor operation to randomly crop an image and resize to a given size."
  315. "Takes output height and width and"
  316. "optional parameters for lower and upper bound for aspect ratio (h/w) and scale,"
  317. "interpolation mode, and max attempts to crop")
  318. .def(py::init<int32_t, int32_t, float, float, float, float, InterpolationMode, int32_t>(), py::arg("targetHeight"),
  319. py::arg("targetWidth"), py::arg("scaleLb") = RandomCropAndResizeOp::kDefScaleLb,
  320. py::arg("scaleUb") = RandomCropAndResizeOp::kDefScaleUb,
  321. py::arg("aspectLb") = RandomCropAndResizeOp::kDefAspectLb,
  322. py::arg("aspectUb") = RandomCropAndResizeOp::kDefAspectUb,
  323. py::arg("interpolation") = RandomCropAndResizeOp::kDefInterpolation,
  324. py::arg("maxIter") = RandomCropAndResizeOp::kDefMaxIter);
  325. (void)py::class_<RandomColorAdjustOp, TensorOp, std::shared_ptr<RandomColorAdjustOp>>(
  326. *m, "RandomColorAdjustOp",
  327. "Tensor operation to adjust an image's color randomly."
  328. "Takes range for brightness, contrast, saturation, hue and")
  329. .def(py::init<float, float, float, float, float, float, float, float>(), py::arg("bright_factor_start"),
  330. py::arg("bright_factor_end"), py::arg("contrast_factor_start"), py::arg("contrast_factor_end"),
  331. py::arg("saturation_factor_start"), py::arg("saturation_factor_end"), py::arg("hue_factor_start"),
  332. py::arg("hue_factor_end"));
  333. (void)py::class_<RandomResizeOp, TensorOp, std::shared_ptr<RandomResizeOp>>(
  334. *m, "RandomResizeOp",
  335. "Tensor operation to resize an image using a randomly selected interpolation. Takes height and width.")
  336. .def(py::init<int32_t, int32_t>(), py::arg("targetHeight"),
  337. py::arg("targetWidth") = RandomResizeOp::kDefTargetWidth);
  338. (void)py::class_<CutOutOp, TensorOp, std::shared_ptr<CutOutOp>>(
  339. *m, "CutOutOp", "Tensor operation to randomly erase a portion of the image. Takes height and width.")
  340. .def(py::init<int32_t, int32_t, int32_t, bool, uint8_t, uint8_t, uint8_t>(), py::arg("boxHeight"),
  341. py::arg("boxWidth"), py::arg("numPatches"), py::arg("randomColor") = CutOutOp::kDefRandomColor,
  342. py::arg("fillR") = CutOutOp::kDefFillR, py::arg("fillG") = CutOutOp::kDefFillG,
  343. py::arg("fillB") = CutOutOp::kDefFillB);
  344. }
  345. void bindTensorOps4(py::module *m) {
  346. (void)py::class_<TypeCastOp, TensorOp, std::shared_ptr<TypeCastOp>>(
  347. *m, "TypeCastOp", "Tensor operator to type cast data to a specified type.")
  348. .def(py::init<DataType>(), py::arg("data_type"))
  349. .def(py::init<std::string>(), py::arg("data_type"));
  350. (void)py::class_<NoOp, TensorOp, std::shared_ptr<NoOp>>(*m, "NoOp",
  351. "TensorOp that does nothing, for testing purposes only.")
  352. .def(py::init<>());
  353. (void)py::class_<ToFloat16Op, TensorOp, std::shared_ptr<ToFloat16Op>>(
  354. *m, "ToFloat16Op", py::dynamic_attr(), "Tensor operator to type cast float32 data to a float16 type.")
  355. .def(py::init<>());
  356. (void)py::class_<RandomCropDecodeResizeOp, TensorOp, std::shared_ptr<RandomCropDecodeResizeOp>>(
  357. *m, "RandomCropDecodeResizeOp", "equivalent to RandomCropAndResize but crops before decoding")
  358. .def(py::init<int32_t, int32_t, float, float, float, float, InterpolationMode, int32_t>(), py::arg("targetHeight"),
  359. py::arg("targetWidth"), py::arg("scaleLb") = RandomCropDecodeResizeOp::kDefScaleLb,
  360. py::arg("scaleUb") = RandomCropDecodeResizeOp::kDefScaleUb,
  361. py::arg("aspectLb") = RandomCropDecodeResizeOp::kDefAspectLb,
  362. py::arg("aspectUb") = RandomCropDecodeResizeOp::kDefAspectUb,
  363. py::arg("interpolation") = RandomCropDecodeResizeOp::kDefInterpolation,
  364. py::arg("maxIter") = RandomCropDecodeResizeOp::kDefMaxIter);
  365. (void)py::class_<PadOp, TensorOp, std::shared_ptr<PadOp>>(
  366. *m, "PadOp",
  367. "Pads image with specified color, default black, "
  368. "Takes amount to pad for top, bottom, left, right of image, boarder type and color")
  369. .def(py::init<int32_t, int32_t, int32_t, int32_t, BorderType, uint8_t, uint8_t, uint8_t>(), py::arg("padTop"),
  370. py::arg("padBottom"), py::arg("padLeft"), py::arg("padRight"), py::arg("borderTypes") = PadOp::kDefBorderType,
  371. py::arg("fillR") = PadOp::kDefFillR, py::arg("fillG") = PadOp::kDefFillG, py::arg("fillB") = PadOp::kDefFillB);
  372. }
  373. void bindTensorOps6(py::module *m) {
  374. (void)py::class_<JiebaTokenizerOp, TensorOp, std::shared_ptr<JiebaTokenizerOp>>(*m, "JiebaTokenizerOp", "")
  375. .def(py::init<const std::string, std::string, JiebaMode>(), py::arg("hmm_path"), py::arg("mp_path"),
  376. py::arg("mode") = JiebaMode::kMix)
  377. .def("add_word",
  378. [](JiebaTokenizerOp &self, const std::string word, int freq) { THROW_IF_ERROR(self.AddWord(word, freq)); });
  379. }
  380. void bindSamplerOps(py::module *m) {
  381. (void)py::class_<Sampler, std::shared_ptr<Sampler>>(*m, "Sampler")
  382. .def("set_num_rows", [](Sampler &self, int64_t rows) { THROW_IF_ERROR(self.SetNumRowsInDataset(rows)); })
  383. .def("set_num_samples", [](Sampler &self, int64_t samples) { THROW_IF_ERROR(self.SetNumSamples(samples)); })
  384. .def("initialize", [](Sampler &self) { THROW_IF_ERROR(self.InitSampler()); })
  385. .def("get_indices", [](Sampler &self) {
  386. py::array ret;
  387. THROW_IF_ERROR(self.GetAllIdsThenReset(&ret));
  388. return ret;
  389. });
  390. (void)py::class_<mindrecord::ShardOperator, std::shared_ptr<mindrecord::ShardOperator>>(*m, "ShardOperator");
  391. (void)py::class_<DistributedSampler, Sampler, std::shared_ptr<DistributedSampler>>(*m, "DistributedSampler")
  392. .def(py::init<int64_t, int64_t, bool, uint32_t>(), py::arg("numDev"), py::arg("devId"), py::arg("shuffle"),
  393. py::arg("seed"));
  394. (void)py::class_<PKSampler, Sampler, std::shared_ptr<PKSampler>>(*m, "PKSampler")
  395. .def(py::init<int64_t, bool>(), py::arg("kVal"), py::arg("shuffle"));
  396. (void)py::class_<RandomSampler, Sampler, std::shared_ptr<RandomSampler>>(*m, "RandomSampler")
  397. .def(py::init<bool, int64_t>(), py::arg("replacement"), py::arg("numSamples"))
  398. .def(py::init<bool>(), py::arg("replacement"));
  399. (void)py::class_<SequentialSampler, Sampler, std::shared_ptr<SequentialSampler>>(*m, "SequentialSampler")
  400. .def(py::init<>());
  401. (void)py::class_<SubsetRandomSampler, Sampler, std::shared_ptr<SubsetRandomSampler>>(*m, "SubsetRandomSampler")
  402. .def(py::init<std::vector<int64_t>>(), py::arg("indices"));
  403. (void)py::class_<mindrecord::ShardSample, mindrecord::ShardOperator, std::shared_ptr<mindrecord::ShardSample>>(
  404. *m, "MindrecordSubsetRandomSampler")
  405. .def(py::init<std::vector<int64_t>, uint32_t>(), py::arg("indices"), py::arg("seed") = GetSeed());
  406. (void)py::class_<mindrecord::ShardPkSample, mindrecord::ShardOperator, std::shared_ptr<mindrecord::ShardPkSample>>(
  407. *m, "MindrecordPkSampler")
  408. .def(py::init([](int64_t kVal, std::string kColumn, bool shuffle) {
  409. if (shuffle == true) {
  410. return std::make_shared<mindrecord::ShardPkSample>(kColumn, kVal, std::numeric_limits<int64_t>::max(),
  411. GetSeed());
  412. } else {
  413. return std::make_shared<mindrecord::ShardPkSample>(kColumn, kVal);
  414. }
  415. }));
  416. (void)py::class_<WeightedRandomSampler, Sampler, std::shared_ptr<WeightedRandomSampler>>(*m, "WeightedRandomSampler")
  417. .def(py::init<std::vector<double>, int64_t, bool>(), py::arg("weights"), py::arg("numSamples"),
  418. py::arg("replacement"));
  419. (void)py::class_<PythonSampler, Sampler, std::shared_ptr<PythonSampler>>(*m, "PythonSampler")
  420. .def(py::init<py::object>(), py::arg("pySampler"));
  421. }
  422. void bindInfoObjects(py::module *m) {
  423. (void)py::class_<BatchOp::CBatchInfo>(*m, "CBatchInfo")
  424. .def(py::init<int64_t, int64_t, int64_t>())
  425. .def("get_epoch_num", &BatchOp::CBatchInfo::get_epoch_num)
  426. .def("get_batch_num", &BatchOp::CBatchInfo::get_batch_num);
  427. }
  428. // This is where we externalize the C logic as python modules
  429. PYBIND11_MODULE(_c_dataengine, m) {
  430. m.doc() = "pybind11 for _c_dataengine";
  431. (void)py::class_<DatasetOp, std::shared_ptr<DatasetOp>>(m, "DatasetOp");
  432. (void)py::enum_<OpName>(m, "OpName", py::arithmetic())
  433. .value("STORAGE", OpName::kStorage)
  434. .value("SHUFFLE", OpName::kShuffle)
  435. .value("BATCH", OpName::kBatch)
  436. .value("BARRIER", OpName::kBarrier)
  437. .value("MINDRECORD", OpName::kMindrecord)
  438. .value("CACHE", OpName::kCache)
  439. .value("REPEAT", OpName::kRepeat)
  440. .value("SKIP", OpName::kSkip)
  441. .value("TAKE", OpName::kTake)
  442. .value("ZIP", OpName::kZip)
  443. .value("CONCAT", OpName::kConcat)
  444. .value("MAP", OpName::kMap)
  445. .value("FILTER", OpName::kFilter)
  446. .value("DEVICEQUEUE", OpName::kDeviceQueue)
  447. .value("GENERATOR", OpName::kGenerator)
  448. .export_values()
  449. .value("RENAME", OpName::kRename)
  450. .value("TFREADER", OpName::kTfReader)
  451. .value("PROJECT", OpName::kProject)
  452. .value("IMAGEFOLDER", OpName::kImageFolder)
  453. .value("MNIST", OpName::kMnist)
  454. .value("MANIFEST", OpName::kManifest)
  455. .value("VOC", OpName::kVoc)
  456. .value("CIFAR10", OpName::kCifar10)
  457. .value("CIFAR100", OpName::kCifar100)
  458. .value("RANDOMDATA", OpName::kRandomData)
  459. .value("CELEBA", OpName::kCelebA)
  460. .value("TEXTFILE", OpName::kTextFile);
  461. (void)py::enum_<JiebaMode>(m, "JiebaMode", py::arithmetic())
  462. .value("DE_INTER_JIEBA_MIX", JiebaMode::kMix)
  463. .value("DE_INTER_JIEBA_MP", JiebaMode::kMp)
  464. .value("DE_INTER_JIEBA_HMM", JiebaMode::kHmm)
  465. .export_values();
  466. (void)py::enum_<InterpolationMode>(m, "InterpolationMode", py::arithmetic())
  467. .value("DE_INTER_LINEAR", InterpolationMode::kLinear)
  468. .value("DE_INTER_CUBIC", InterpolationMode::kCubic)
  469. .value("DE_INTER_AREA", InterpolationMode::kArea)
  470. .value("DE_INTER_NEAREST_NEIGHBOUR", InterpolationMode::kNearestNeighbour)
  471. .export_values();
  472. (void)py::enum_<BorderType>(m, "BorderType", py::arithmetic())
  473. .value("DE_BORDER_CONSTANT", BorderType::kConstant)
  474. .value("DE_BORDER_EDGE", BorderType::kEdge)
  475. .value("DE_BORDER_REFLECT", BorderType::kReflect)
  476. .value("DE_BORDER_SYMMETRIC", BorderType::kSymmetric)
  477. .export_values();
  478. bindDEPipeline(&m);
  479. bindTensor(&m);
  480. bindTensorOps1(&m);
  481. bindTensorOps2(&m);
  482. bindTensorOps3(&m);
  483. bindTensorOps4(&m);
  484. bindTensorOps6(&m);
  485. bindSamplerOps(&m);
  486. bindDatasetOps(&m);
  487. bindInfoObjects(&m);
  488. }
  489. } // namespace dataset
  490. } // namespace mindspore