finish tracker
[trackerpp.git] / src / PredictorWrapper.cpp
1 #include "PredictorWrapper.h"
2 #include <string>
3 #include "Logger.h"
4 #include <iostream>
5 #include <thread>
6
7 namespace py = boost::python;
8
9 using namespace std;
10 using namespace suanzi;
11
12
13 PredictorWrapperWPtr PredictorWrapper::instance;
14
15 const static std::string TAG = "PredictorWrapper";
16
17 static std::string parse_python_exception();
18
19 template <class T>
20 boost::python::list toPythonList(const std::vector<T>& v) {
21     typename std::vector<T>::iterator iter;
22     boost::python::list list;
23     for(const auto& vv : v){
24         list.append(vv);
25     }
26     return list;
27 }
28
29 PredictorWrapperPtr PredictorWrapper::create(const std::string& python_dir, const std::string& model_path)
30 {
31     if (instance.lock()){
32         return PredictorWrapperPtr();
33     }
34     PredictorWrapperPtr ins (new PredictorWrapper(python_dir, model_path));
35     instance = ins;
36     return ins;
37 }
38
39 void PredictorWrapper::dump()
40 {
41     LOG_DEBUG(TAG, "dump");
42     std::string ss = "";
43     try{
44         py::object ret = this->dump_func();
45         ss = py::extract<std::string>(ret);
46     } catch (boost::python::error_already_set const &){
47         std::string perror_str = parse_python_exception();
48         LOG_ERROR(TAG, "Error in Python: " + perror_str)
49     }
50     LOG_DEBUG(TAG, ss);
51 }
52
53 double PredictorWrapper::predict(int index, const std::vector<double>& ff)
54 {
55     LOG_DEBUG(TAG, "predict");
56     py::object ret;
57     try{
58         ret = this->predict_func(index, toPythonList(ff));
59     } catch (boost::python::error_already_set const &){
60         std::string perror_str = parse_python_exception();
61         LOG_ERROR(TAG, "Error in Python: " + perror_str)
62     }
63     double rr = py::extract<double>(ret);
64     LOG_DEBUG(TAG, "return: " + std::to_string(rr));
65     return rr; 
66 }
67
68 PredictorWrapper::PredictorWrapper(const std::string& py_dir, const std::string& model_path)
69 {
70     Py_Initialize();
71     try{
72         py::object main_module = py::import("__main__");
73         py::object main_namespace = main_module.attr("__dict__");
74         py::exec("import sys", main_namespace);
75         std::string cmd = "sys.path.insert(0, '" + py_dir + "')";
76         py::exec(cmd.c_str(), main_namespace);
77         py::exec("import signal", main_namespace);
78         py::exec("signal.signal(signal.SIGINT, signal.SIG_DFL)", main_namespace);
79         py::object predictor_mod = py::import("predictor");
80         py::object predictor_init = predictor_mod.attr("init");
81         dump_func = predictor_mod.attr("dump");
82         predict_func = predictor_mod.attr("predict");
83         predictor_init(model_path.c_str());
84     } catch (boost::python::error_already_set const &){
85         std::string perror_str = parse_python_exception();
86         LOG_ERROR(TAG, "Error in Python: " + perror_str)
87     }
88 }
89
90 static std::string parse_python_exception(){  
91     PyObject *type_ptr = NULL, *value_ptr = NULL, *traceback_ptr = NULL;  
92     // Fetch the exception info from the Python C API  
93     PyErr_Fetch(&type_ptr, &value_ptr, &traceback_ptr);  
94   
95     // Fallback error  
96     std::string ret("Unfetchable Python error");  
97     // If the fetch got a type pointer, parse the type into the exception string  
98     if(type_ptr != NULL){  
99         py::handle<> h_type(type_ptr);  
100         py::str type_pstr(h_type);  
101         // Extract the string from the boost::python object  
102         py::extract<std::string> e_type_pstr(type_pstr);  
103         // If a valid string extraction is available, use it   
104         //  otherwise use fallback  
105         if(e_type_pstr.check())  
106             ret = e_type_pstr();  
107         else  
108             ret = "Unknown exception type";  
109     }  
110     // Do the same for the exception value (the stringification of the exception)  
111     if(value_ptr != NULL){  
112         py::handle<> h_val(value_ptr);  
113         py::str a(h_val);  
114         py::extract<std::string> returned(a);  
115         if(returned.check())  
116             ret +=  ": " + returned();  
117         else  
118             ret += std::string(": Unparseable Python error: ");  
119     }  
120     // Parse lines from the traceback using the Python traceback module  
121     if(traceback_ptr != NULL){  
122         py::handle<> h_tb(traceback_ptr);  
123         // Load the traceback module and the format_tb function  
124         py::object tb(py::import("traceback"));  
125         py::object fmt_tb(tb.attr("format_tb"));  
126         // Call format_tb to get a list of traceback strings  
127         py::object tb_list(fmt_tb(h_tb));  
128         // Join the traceback strings into a single string  
129         py::object tb_str(py::str("\n").join(tb_list));  
130         // Extract the string, check the extraction, and fallback in necessary  
131         py::extract<std::string> returned(tb_str);  
132         if(returned.check())  
133             ret += ": " + returned();  
134         else  
135             ret += std::string(": Unparseable Python traceback");  
136     }  
137     return ret;  
138 }  
139