| 390 | } |
| 391 | |
| 392 | ndarray_handle* ndarray_import(PyObject* o, const ndarray_req* req, bool convert) noexcept |
| 393 | { |
| 394 | object capsule; |
| 395 | |
| 396 | // If this is not a capsule, try calling o.__dlpack__() |
| 397 | if (!PyCapsule_CheckExact(o)) |
| 398 | { |
| 399 | // BACKPORT |
| 400 | // capsule = steal(PyObject_CallMethod(o, "__dlpack__", nullptr)); |
| 401 | capsule = reinterpret_steal<object>(PyObject_CallMethod(o, "__dlpack__", nullptr)); |
| 402 | |
| 403 | // BACKPORT |
| 404 | // if (!capsule.is_valid()) |
| 405 | if (!capsule) |
| 406 | { |
| 407 | PyErr_Clear(); |
| 408 | PyTypeObject* tp = Py_TYPE(o); |
| 409 | |
| 410 | try |
| 411 | { |
| 412 | // BACKPORT |
| 413 | // const char* module_name = borrow<str>(handle(tp).attr("__module__")).c_str(); |
| 414 | std::string module_name = reinterpret_borrow<str>(handle(tp->tp_dict).attr("__module__")); |
| 415 | |
| 416 | object package; |
| 417 | if (strncmp(module_name.c_str(), "tensorflow.", 11) == 0) |
| 418 | package = module_::import("tensorflow.experimental.dlpack"); |
| 419 | else if (strcmp(module_name.c_str(), "torch") == 0) |
| 420 | package = module_::import("torch.utils.dlpack"); |
| 421 | else if (strncmp(module_name.c_str(), "jaxlib", 6) == 0) |
| 422 | package = module_::import("jax.dlpack"); |
| 423 | |
| 424 | // BACKPORT |
| 425 | // if (package.is_valid()) |
| 426 | if (package) |
| 427 | capsule = package.attr("to_dlpack")(handle(o)); |
| 428 | } |
| 429 | catch (...) |
| 430 | { |
| 431 | // BACKPORT |
| 432 | // capsule.reset(); |
| 433 | capsule.release(); |
| 434 | } |
| 435 | } |
| 436 | |
| 437 | // Try creating a ndarray via the buffer protocol |
| 438 | // BACKPORT |
| 439 | // if (!capsule.is_valid()) |
| 440 | // capsule = steal(dlpack_from_buffer_protocol(o)); |
| 441 | if (!capsule) |
| 442 | capsule = reinterpret_steal<object>(dlpack_from_buffer_protocol(o)); |
| 443 | |
| 444 | // BACKPORT |
| 445 | // if (!capsule.is_valid()) |
| 446 | if (!capsule) |
| 447 | return nullptr; |
| 448 | } |
| 449 | else |
no test coverage detected