OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[Py OV] Unify system path handling in Python API (#34195)
Alicja Miloszewskaef4a0b8e89a7
diff --git a/src/bindings/python/src/pyopenvino/core/core.cpp b/src/bindings/python/src/pyopenvino/core/core.cppindex 6a76e6dd4f9..6656dd3b38f 100644--- a/src/bindings/python/src/pyopenvino/core/core.cpp+++ b/src/bindings/python/src/pyopenvino/core/core.cpp@@ -5,8 +5,10 @@#include "pyopenvino/core/core.hpp"#include <pybind11/stl.h>+#include <pybind11/stl/filesystem.h>#include <pybind11/typing.h>+#include <filesystem>#include <fstream>#include <openvino/core/any.hpp>#include <openvino/runtime/core.hpp>@@ -215,7 +217,7 @@ void regclass_Core(py::module m) {const std::string& device_name,const std::map<std::string, py::object>& properties) {auto _properties = Common::utils::properties_to_any_map(properties);- std::string path = Common::utils::convert_path_to_string(model_path);+ const auto path = Common::utils::to_fs_path(model_path);py::gil_scoped_release release;return self.compile_model(path, device_name, _properties);},@@ -230,7 +232,7 @@ void regclass_Core(py::module m) {GIL is released while running this function.:param model_path: A path to a model in IR / ONNX / PDPD / TF and TFLite format.- :type model_path: typing.Union[str, pathlib.Path]+ :type model_path: Union[str, bytes, pathlib.Path]:param device_name: Name of the device to load the model to.:type device_name: str:param properties: Optional dict of pairs: (property name, property value) relevant only for this load operation.@@ -291,7 +293,7 @@ void regclass_Core(py::module m) {"compile_model",[](ov::Core& self, const py::object& model_path, const std::map<std::string, py::object>& properties) {auto _properties = Common::utils::properties_to_any_map(properties);- std::string path = Common::utils::convert_path_to_string(model_path);+ const auto path = Common::utils::to_fs_path(model_path);py::gil_scoped_release release;return self.compile_model(path, _properties);},@@ -305,7 +307,7 @@ void regclass_Core(py::module m) {GIL is released while running this function.:param model_path: A path to a model in IR / ONNX / PDPD / TF and TFLite format.- :type model_path: typing.Union[str, pathlib.Path]+ :type model_path: Union[str, bytes, pathlib.Path]:param properties: Optional dict of pairs: (property name, property value) relevant only for this load operation.:type properties: dict[str, typing.Any]:return: A compiled model.@@ -418,40 +420,6 @@ void regclass_Core(py::module m) {:rtype: openvino.Model)");- cls.def(- "read_model",- [](ov::Core& self,- const std::string& model_path,- const std::string& weight_path,- const std::map<std::string, py::object>& config) {- const auto any_map = Common::utils::properties_to_any_map(config);- py::gil_scoped_release release;- return self.read_model(model_path, weight_path, any_map);- },- py::arg("model"),- py::arg("weights") = "",- py::arg("config") = py::dict(),- R"(- Reads models from IR / ONNX / PDPD / TF and TFLite formats.-- GIL is released while running this function.-- :param model: A path to a model in IR / ONNX / PDPD / TF and TFLite format.- :type model: str- :param weights: A path to a data file For IR format (*.bin): if path is empty,- it tries to read a bin file with the same name as xml and if the bin- file with the same name was not found, loads IR without weights.- For ONNX format (*.onnx): weights parameter is not used.- For PDPD format (*.pdmodel) weights parameter is not used.- For TF format (*.pb) weights parameter is not used.- For TFLite format (*.tflite) weights parameter is not used.- :type weights: str- :param config: Optional map of pairs: (property name, property value) relevant only for this read operation.- :type config: dict[str, typing.Any], optional- :return: A model.- :rtype: openvino.Model- )");-cls.def("read_model",(std::shared_ptr<ov::Model>(ov::Core::*)(const std::string&, const ov::Tensor&) const) & ov::Core::read_model,@@ -498,10 +466,10 @@ void regclass_Core(py::module m) {return self.read_model(std::string(static_cast<char*>(buffer_info.ptr), buffer_info.size), tensor);} else if (py::isinstance(model_path, py::module_::import("pathlib").attr("Path")) ||py::isinstance<py::str>(model_path)) {- const std::string model_path_cpp{py::str(model_path)};- std::string weights_path_cpp;+ const auto model_path_cpp = Common::utils::to_fs_path(model_path);+ std::filesystem::path weights_path_cpp;if (!py::isinstance<py::none>(weights_path)) {- weights_path_cpp = py::str(weights_path);+ weights_path_cpp = Common::utils::to_fs_path(weights_path);}const auto any_map = Common::utils::properties_to_any_map(config);py::gil_scoped_release release;@@ -519,8 +487,8 @@ void regclass_Core(py::module m) {GIL is released while running this function.- :param model: A path to a model in IR / ONNX / PDPD / TF and TFLite format or a model itself wrapped in io.ByesIO format.- :type model: typing.Union[pathlib.Path, io.BytesIO]+ :param model: A path to a model in IR / ONNX / PDPD / TF and TFLite format or a model itself wrapped in io.BytesIO format.+ :type model: Union[str, pathlib.Path, io.BytesIO]:param weights: A path to a data file For IR format (*.bin): if path is empty,it tries to read a bin file with the same name as xml and if the binfile with the same name was not found, loads IR without weights.@@ -528,7 +496,7 @@ void regclass_Core(py::module m) {For PDPD format (*.pdmodel) weights parameter is not used.For TF format (*.pb): weights parameter is not used.For TFLite format (*.tflite) weights parameter is not used.- :type weights: typing.Union[pathlib.Path, io.BytesIO]+ :type weights: Union[str, pathlib.Path, io.BytesIO]:param config: Optional map of pairs: (property name, property value) relevant only for this read operation.:type config: dict[str, typing.Any], optional:return: A model.@@ -709,7 +677,7 @@ void regclass_Core(py::module m) {)");cls.def("add_extension",- static_cast<void (ov::Core::*)(const std::string&)>(&ov::Core::add_extension),+ static_cast<void (ov::Core::*)(const std::filesystem::path&)>(&ov::Core::add_extension),py::arg("library_path"),R"(Registers an extension to a Core object.diff --git a/src/bindings/python/src/pyopenvino/frontend/frontend.cpp b/src/bindings/python/src/pyopenvino/frontend/frontend.cppindex 3810de1f1ff..c58d061c93e 100644--- a/src/bindings/python/src/pyopenvino/frontend/frontend.cpp+++ b/src/bindings/python/src/pyopenvino/frontend/frontend.cpp@@ -35,19 +35,7 @@ void regclass_frontend_FrontEnd(py::module m) {[](FrontEnd& self, const py::object& py_obj, const bool enable_mmap = true) {if (py::isinstance(py_obj, py::module_::import("pathlib").attr("Path")) ||py::isinstance<py::str>(py_obj) || py::isinstance<py::bytes>(py_obj)) {- // check if model path is either a string/pathlib.Path/bytes- std::string model_path = Common::utils::convert_path_to_string(py_obj);- if (py::isinstance(py_obj, py::module_::import("pathlib").attr("Path")) ||- py::isinstance<py::str>(py_obj)) {-- // Fix unicode path-#if defined(OPENVINO_ENABLE_UNICODE_PATH_SUPPORT) && defined(_WIN32)- return self.load(ov::util::string_to_wstring(model_path.c_str()));-#else- return self.load(model_path.c_str());-#endif- }- return self.load(model_path, enable_mmap);+ return self.load({Common::utils::to_fs_path(py_obj), enable_mmap});} else if (py::isinstance(py_obj, pybind11::module::import("io").attr("BytesIO"))) {// support of BytesIOpy::buffer_info info = py::buffer(py_obj.attr("getbuffer")()).request();@@ -77,18 +65,7 @@ void regclass_frontend_FrontEnd(py::module m) {[](FrontEnd& self, const py::object& model) {if (py::isinstance(model, py::module_::import("pathlib").attr("Path")) || py::isinstance<py::str>(model) ||py::isinstance<py::bytes>(model)) {- // check if model path is either a string/pathlib.Path/bytes- std::string model_path = Common::utils::convert_path_to_string(model);- if (py::isinstance(model, py::module_::import("pathlib").attr("Path")) ||- py::isinstance<py::str>(model)) {-- // Fix unicode path-#if defined(OPENVINO_ENABLE_UNICODE_PATH_SUPPORT) && defined(_WIN32)- return self.supported(ov::util::string_to_wstring(model_path.c_str()));-#else- return self.supported(model_path.c_str());-#endif- }+ return self.supported({Common::utils::to_fs_path(model)});}return self.supported({Common::utils::py_object_to_any(model)});},@@ -204,7 +181,7 @@ void regclass_frontend_FrontEnd(py::module m) {fem.def("add_extension",[](FrontEnd& self, const py::object& extension_path) {- return self.add_extension(Common::utils::convert_path_to_string(extension_path));+ return self.add_extension(Common::utils::to_fs_path(extension_path));},R"(Add extension defined in external library indicated by a extension_pathdiff --git a/src/bindings/python/src/pyopenvino/frontend/manager.cpp b/src/bindings/python/src/pyopenvino/frontend/manager.cppindex 05e0e7ec587..6efa1adda79 100644--- a/src/bindings/python/src/pyopenvino/frontend/manager.cpp+++ b/src/bindings/python/src/pyopenvino/frontend/manager.cpp@@ -45,8 +45,8 @@ void regclass_frontend_FrontEndManager(py::module m) {"register_front_end",[](const std::shared_ptr<ov::frontend::FrontEndManager>& fem,const std::string& name,- const std::string& library_path) {- return fem->register_front_end(name, library_path);+ const py::object& library_path) {+ return fem->register_front_end(name, Common::utils::to_fs_path(library_path));},py::arg("name"),py::arg("library_path"),@@ -59,7 +59,7 @@ void regclass_frontend_FrontEndManager(py::module m) {:param library_path: Path (absolute or relative) or name of a frontend library. If name isprovided, depending on platform, it will be wrapped with shared library suffix and prefixto identify library full name.- :type library_path: str+ :type library_path: Union[str, pathlib.Path]:return: None)");@@ -80,15 +80,7 @@ void regclass_frontend_FrontEndManager(py::module m) {"load_by_model",[](const std::shared_ptr<ov::frontend::FrontEndManager>& fem, const py::object& model) {if (py::isinstance(model, py::module_::import("pathlib").attr("Path")) || py::isinstance<py::str>(model)) {- std::string model_path = Common::utils::convert_path_to_string(model);-- // Fix unicode path-#if defined(OPENVINO_ENABLE_UNICODE_PATH_SUPPORT) && defined(_WIN32)- return fem->load_by_model(ov::util::string_to_wstring(model_path.c_str()));-#else- std::string model_path_str = model_path;- return fem->load_by_model(model_path_str);-#endif+ return fem->load_by_model(Common::utils::to_fs_path(model));}return fem->load_by_model({Common::utils::py_object_to_any(model)});},@@ -96,8 +88,8 @@ void regclass_frontend_FrontEndManager(py::module m) {R"(Selects and loads appropriate frontend depending on model type or model file extension and other file info (header).- :param model_path: A model object or path to a model file/directory.- :type model_path: Any+ :param model: A model object or path to a model file/directory.+ :type model: Any:return: Frontend interface for further loading of models. 'None' if no suitable frontend is found.:rtype: openvino.frontend.FrontEnd)");diff --git a/src/bindings/python/src/pyopenvino/graph/node_factory.cpp b/src/bindings/python/src/pyopenvino/graph/node_factory.cppindex b2c3bc0d7ce..5bcbe87c2ad 100644--- a/src/bindings/python/src/pyopenvino/graph/node_factory.cpp+++ b/src/bindings/python/src/pyopenvino/graph/node_factory.cpp@@ -121,7 +121,7 @@ public:}}- void add_extension(const std::string& lib_path) {+ void add_extension(const std::filesystem::path& lib_path) {// Load extension library, seach for operation extensions (derived from ov::BaseOpExtension) and keep// them in m_opset_so_extensions for future use in create methods.// NodeFactory provides a simplified API for node creation without involving version of operation.@@ -185,7 +185,7 @@ void regclass_graph_NodeFactory(py::module m) {});node_factory.def("add_extension", [](NodeFactory& self, const py::object& lib_path) {- return self.add_extension(Common::utils::convert_path_to_string(lib_path));+ return self.add_extension(Common::utils::to_fs_path(lib_path));});node_factory.def("__repr__", [](const NodeFactory& self) {diff --git a/src/bindings/python/src/pyopenvino/utils/utils.cpp b/src/bindings/python/src/pyopenvino/utils/utils.cppindex dc795a9702e..4c4a12bd600 100644--- a/src/bindings/python/src/pyopenvino/utils/utils.cpp+++ b/src/bindings/python/src/pyopenvino/utils/utils.cpp@@ -336,24 +336,6 @@ std::map<std::string, ov::Any> properties_to_any_map(const std::map<std::string,return properties_to_cpp;}-std::string convert_path_to_string(const py::object& path) {- // import pathlib.Path- py::object Path = py::module_::import("pathlib").attr("Path");- // check if model path is either a string or pathlib.Path- if (py::isinstance(path, Path) || py::isinstance<py::str>(path)) {- return py::str(path);- }- // Convert bytes to string- if (py::isinstance<py::bytes>(path)) {- return path.cast<std::string>();- }- std::stringstream str;- str << "Path: '" << path << "'"- << " does not exist. Please provide valid model's path either as a string, bytes or pathlib.Path. "- "Examples:\n(1) '/home/user/models/model.onnx'\n(2) Path('/home/user/models/model/model.onnx')";- OPENVINO_THROW(str.str());-}-std::shared_ptr<ov::Model> convert_to_model(const py::object& obj) {if (!py::isinstance(obj, py::module_::import("openvino").attr("Model"))) {throw py::type_error("Incompatible `model` argument. Please provide a valid openvino.Model instance.");diff --git a/src/bindings/python/src/pyopenvino/utils/utils.hpp b/src/bindings/python/src/pyopenvino/utils/utils.hppindex d77cf92717b..70c1bf39b55 100644--- a/src/bindings/python/src/pyopenvino/utils/utils.hpp+++ b/src/bindings/python/src/pyopenvino/utils/utils.hpp@@ -99,8 +99,6 @@ private:std::map<std::string, ov::Any> properties_to_any_map(const std::map<std::string, py::object>& properties);- std::string convert_path_to_string(const py::object& path);-std::shared_ptr<ov::Model> convert_to_model(const py::object& obj);void deprecation_warning(const std::string& function_name, const std::string& version = std::string(), const std::string& message = std::string(), int stacklevel=2);diff --git a/src/bindings/python/tests/test_runtime/test_core.py b/src/bindings/python/tests/test_runtime/test_core.pyindex eb0c88f247e..c492b112492 100644--- a/src/bindings/python/tests/test_runtime/test_core.py+++ b/src/bindings/python/tests/test_runtime/test_core.py@@ -446,6 +446,14 @@ def test_add_extension():assert isinstance(model, Model)+def test_add_extension_from_path():+ core = Core()++ with pytest.raises(RuntimeError) as e:+ core.add_extension(Path("non_existing_extension"))+ assert "Cannot load library" in str(e.value)++def test_read_model_from_buffer_no_weights():bytes_model = bytes(b"""<net name="add_model" version="10">diff --git a/src/frontends/common/include/openvino/frontend/frontend.hpp b/src/frontends/common/include/openvino/frontend/frontend.hppindex 25421fe5e10..572881aaa82 100644--- a/src/frontends/common/include/openvino/frontend/frontend.hpp+++ b/src/frontends/common/include/openvino/frontend/frontend.hpp@@ -131,7 +131,7 @@ public:void add_extension(const std::string& library_path);void add_extension(const std::filesystem::path& library_path) {- add_extension(library_path.string());+ add_extension(library_path.native());}/// \}diff --git a/src/frontends/onnx/tests/tests_python/test_frontendmanager.py b/src/frontends/onnx/tests/tests_python/test_frontendmanager.pyindex a8f8f2766b6..98921f68d77 100644--- a/src/frontends/onnx/tests/tests_python/test_frontendmanager.py+++ b/src/frontends/onnx/tests/tests_python/test_frontendmanager.py@@ -58,6 +58,17 @@ def test_pickle():pickle.dumps(fem)+@mock_needed+def test_register_front_end_path():+ fem2 = FrontEndManager()+ fem2.register_front_end(MOCK_PY_FRONTEND_NAME, Path(mock_py_fe_path_l[0]))+ fe = fem2.load_by_framework(framework=MOCK_PY_FRONTEND_NAME)+ assert fe is not None+ assert fe.get_name() == MOCK_PY_FRONTEND_NAME++ del fe++def test_load_by_unknown_framework():frontends = fem.get_available_front_ends()assert not ("UnknownFramework" in frontends)