Refactor singleton to manage cleanup
This commit is contained in:
185
src/PyWrap.cc
185
src/PyWrap.cc
@@ -10,6 +10,7 @@ namespace pywrap {
|
||||
namespace np = boost::python::numpy;
|
||||
PyWrap* PyWrap::wrapper = nullptr;
|
||||
std::mutex PyWrap::mutex;
|
||||
CPyInstance* PyWrap::pyInstance = nullptr;
|
||||
|
||||
PyWrap* PyWrap::GetInstance()
|
||||
{
|
||||
@@ -17,27 +18,23 @@ namespace pywrap {
|
||||
if (wrapper == nullptr) {
|
||||
std::cout << "Creando instancia" << std::endl;
|
||||
wrapper = new PyWrap();
|
||||
pyInstance = new CPyInstance();
|
||||
std::cout << "Instancia creada" << std::endl;
|
||||
}
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
PyWrap::PyWrap()
|
||||
void PyWrap::RemoveInstance()
|
||||
{
|
||||
PyStatus status = initPython();
|
||||
if (PyStatus_Exception(status)) {
|
||||
throw std::runtime_error("Error initializing Python");
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
if (wrapper != nullptr) {
|
||||
std::cout << "Liberando instancia" << std::endl;
|
||||
delete pyInstance;
|
||||
pyInstance = nullptr;
|
||||
delete wrapper;
|
||||
wrapper = nullptr;
|
||||
std::cout << "Instancia liberada" << std::endl;
|
||||
}
|
||||
np::initialize();
|
||||
}
|
||||
|
||||
PyWrap::~PyWrap()
|
||||
{
|
||||
std::cout << "Destruyendo PyWrap" << std::endl;
|
||||
Py_Finalize();
|
||||
std::cout << "PyWrap destruido" << std::endl;
|
||||
}
|
||||
|
||||
void PyWrap::importClass(const std::string& moduleName, const std::string& className)
|
||||
{
|
||||
std::cout << "Importando clase" << std::endl;
|
||||
@@ -61,7 +58,6 @@ namespace pywrap {
|
||||
moduleClassMap[{moduleName, className}] = { module, classObject, instance };
|
||||
std::cout << "Clase importada" << std::endl;
|
||||
}
|
||||
|
||||
void PyWrap::clean(const std::string& moduleName, const std::string& className)
|
||||
{
|
||||
std::cout << "Limpiando" << std::endl;
|
||||
@@ -71,14 +67,20 @@ namespace pywrap {
|
||||
}
|
||||
std::cout << "--> Limpiando" << std::endl;
|
||||
moduleClassMap.erase(result);
|
||||
if (PyErr_Occurred()) {
|
||||
PyErr_Print();
|
||||
errorAbort("Error cleaning module " + moduleName + " and class " + className);
|
||||
}
|
||||
if (moduleClassMap.empty()) {
|
||||
RemoveInstance();
|
||||
}
|
||||
std::cout << "Limpieza terminada" << std::endl;
|
||||
}
|
||||
|
||||
|
||||
void PyWrap::errorAbort(const std::string& message)
|
||||
{
|
||||
std::cout << message << std::endl;
|
||||
PyErr_Print();
|
||||
RemoveInstance();
|
||||
exit(1);
|
||||
}
|
||||
PyObject* PyWrap::getClass(const std::string& moduleName, const std::string& className)
|
||||
@@ -93,28 +95,45 @@ namespace pywrap {
|
||||
std::string PyWrap::callMethodString(const std::string& moduleName, const std::string& className, const std::string& method)
|
||||
{
|
||||
std::cout << "Llamando método " << method << std::endl;
|
||||
CPyObject instance = getClass(moduleName, className);
|
||||
CPyObject result;
|
||||
if (!(result = PyObject_CallMethod(instance, method.c_str(), NULL)))
|
||||
errorAbort("Couldn't call method " + method);
|
||||
|
||||
PyObject* instance = getClass(moduleName, className);
|
||||
PyObject* result;
|
||||
try {
|
||||
if (!(result = PyObject_CallMethod(instance, method.c_str(), NULL)))
|
||||
errorAbort("Couldn't call method " + method);
|
||||
}
|
||||
catch (const std::exception& e) {
|
||||
std::cerr << e.what() << '\n';
|
||||
RemoveInstance();
|
||||
exit(1);
|
||||
}
|
||||
std::string value = PyUnicode_AsUTF8(result);
|
||||
std::cout << "Result: " << value << std::endl;
|
||||
Py_DECREF(result);
|
||||
return value;
|
||||
}
|
||||
std::string PyWrap::version(const std::string& moduleName, const std::string& className)
|
||||
{
|
||||
return callMethodString(moduleName, className, "version");
|
||||
}
|
||||
|
||||
std::string PyWrap::graph(const std::string& moduleName, const std::string& className)
|
||||
{
|
||||
return callMethodString(moduleName, className, "graph");
|
||||
}
|
||||
void PyWrap::fit(const std::string& moduleName, const std::string& className, CPyObject& X, CPyObject& y)
|
||||
{
|
||||
std::cout << "Llamando método fit" << std::endl;
|
||||
CPyObject instance = getClass(moduleName, className);
|
||||
CPyObject result;
|
||||
std::string method = "fit";
|
||||
if (!(result = PyObject_CallMethodObjArgs(instance, PyUnicode_FromString(method.c_str()), X, y, NULL)))
|
||||
errorAbort("Couldn't call method fit");
|
||||
try {
|
||||
if (!(result = PyObject_CallMethodObjArgs(instance, PyUnicode_FromString(method.c_str()), X, y, NULL)))
|
||||
errorAbort("Couldn't call method fit");
|
||||
}
|
||||
catch (const std::exception& e) {
|
||||
std::cerr << e.what() << '\n';
|
||||
RemoveInstance();
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
CPyObject PyWrap::predict(const std::string& moduleName, const std::string& className, CPyObject& X)
|
||||
{
|
||||
@@ -122,9 +141,16 @@ namespace pywrap {
|
||||
CPyObject instance = getClass(moduleName, className);
|
||||
CPyObject result;
|
||||
std::string method = "predict";
|
||||
if (!(result = PyObject_CallMethodObjArgs(instance, PyUnicode_FromString(method.c_str()), X, NULL)))
|
||||
errorAbort("Couldn't call method predict");
|
||||
return result; // The caller has to decref the result
|
||||
try {
|
||||
if (!(result = PyObject_CallMethodObjArgs(instance, PyUnicode_FromString(method.c_str()), X, NULL)))
|
||||
errorAbort("Couldn't call method predict");
|
||||
}
|
||||
catch (const std::exception& e) {
|
||||
std::cerr << e.what() << '\n';
|
||||
RemoveInstance();
|
||||
exit(1);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
double PyWrap::score(const std::string& moduleName, const std::string& className, CPyObject& X, CPyObject& y)
|
||||
{
|
||||
@@ -132,100 +158,15 @@ namespace pywrap {
|
||||
CPyObject instance = getClass(moduleName, className);
|
||||
CPyObject result;
|
||||
std::string method = "score";
|
||||
if (!(result = PyObject_CallMethodObjArgs(instance, PyUnicode_FromString(method.c_str()), X, y, NULL)))
|
||||
errorAbort("Couldn't call method score");
|
||||
try {
|
||||
if (!(result = PyObject_CallMethodObjArgs(instance, PyUnicode_FromString(method.c_str()), X, y, NULL)))
|
||||
errorAbort("Couldn't call method score");
|
||||
}
|
||||
catch (const std::exception& e) {
|
||||
std::cerr << e.what() << '\n';
|
||||
RemoveInstance();
|
||||
exit(1);
|
||||
}
|
||||
return PyFloat_AsDouble(result);
|
||||
}
|
||||
// void PyWrap::doCommand2()
|
||||
// {
|
||||
// PyObject* list = Py_BuildValue("[s]", "Stree");
|
||||
// // PyObject* module = PyImport_ImportModuleEx("stree", NULL, NULL, list);
|
||||
// PyObject* module = PyImport_ImportModule("stree");
|
||||
// if (PyErr_Occurred()) {
|
||||
// PyErr_Print();
|
||||
// cout << "Fails to obtain the module.\n";
|
||||
// return;
|
||||
// }
|
||||
// cout << "Antes de empezar" << endl;
|
||||
// if (module != nullptr) {
|
||||
// cout << "Lo consiguió!!!" << endl;
|
||||
// // dict is a borrowed reference.
|
||||
// auto pdict = PyModule_GetDict(module);
|
||||
// if (pdict == nullptr) {
|
||||
// cout << "Fails to get the dictionary.\n";
|
||||
// return;
|
||||
// }
|
||||
// Py_DECREF(module);
|
||||
// PyObject* pKeys = PyDict_Keys(pdict);
|
||||
// PyObject* pValues = PyDict_Values(pdict);
|
||||
// map<string, string> my_map;
|
||||
// cout << "size: " << PyDict_Size(pdict) << endl;
|
||||
// char* cstr_key = new char[100];
|
||||
// char* cstr_value = new char[500];
|
||||
// for (Py_ssize_t i = 0; i < PyDict_Size(pdict); ++i) {
|
||||
// PyArg_Parse(PyList_GetItem(pKeys, i), "s", &cstr_key);
|
||||
// PyArg_Parse(PyList_GetItem(pValues, i), "s", &cstr_value);
|
||||
// //cout << cstr<< " "<< cstr2 <<endl;
|
||||
// my_map.emplace(cstr_key, cstr_value);
|
||||
// }
|
||||
// for (auto x : my_map) {
|
||||
// cout << x.first << " : " << x.second << endl;
|
||||
// }
|
||||
// // Builds the name of a callable class
|
||||
// const char* class_name = "Stree";
|
||||
// auto python_class = PyDict_GetItemString(pdict, class_name);
|
||||
// // if (PyErr_Occurred()) {
|
||||
// // PyErr_Print();
|
||||
// // cout << "Fails to obtain the class.\n";
|
||||
// // return;
|
||||
// // }
|
||||
// if (python_class == nullptr) {
|
||||
// cout << "Fails to get the Python class.\n";
|
||||
// return;
|
||||
// }
|
||||
// Py_DECREF(pdict);
|
||||
// cout << "Clase: " << python_class << endl;
|
||||
// PyObject* object;
|
||||
// // Creates an instance of the class
|
||||
// if (PyCallable_Check(python_class)) {
|
||||
// cout << "Es callable" << endl;
|
||||
// object = PyObject_CallObject(python_class, NULL);
|
||||
// Py_DECREF(python_class);
|
||||
// } else {
|
||||
// std::cout << "Cannot instantiate the Python class" << endl;
|
||||
// Py_DECREF(python_class);
|
||||
// return;
|
||||
// }
|
||||
// if (PyErr_Occurred()) {
|
||||
// PyErr_Print();
|
||||
// cout << "Fails to create the Python object.\n";
|
||||
// return;
|
||||
// }
|
||||
// auto val = PyObject_CallMethod(object, "version", NULL);
|
||||
// if (val != nullptr) {
|
||||
// cout << "Valor: " << val << endl;
|
||||
// } else {
|
||||
// cout << "No se pudo ejecutar" << endl;
|
||||
// }
|
||||
|
||||
// } else {
|
||||
// cout << "No lo consiguió :(" << endl;
|
||||
// }
|
||||
// Py_RunMain();
|
||||
// }
|
||||
|
||||
PyStatus PyWrap::initPython()
|
||||
{
|
||||
PyStatus status;
|
||||
PyConfig config;
|
||||
PyConfig_InitPythonConfig(&config);
|
||||
config.isolated = 0;
|
||||
status = PyConfig_Read(&config);
|
||||
if (PyStatus_Exception(status)) {
|
||||
errorAbort("Error reading config");
|
||||
}
|
||||
status = Py_InitializeFromConfig(&config);
|
||||
PyConfig_Clear(&config);
|
||||
return status;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user