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