在GRPC服务器中嵌入Python



我正在探索GRPC (C++).按照他们的例子,我正在尝试创建一个服务器,该服务器接受来自客户端的图像返回图像中的文本。我有一个python代码,它接受一个image和一个json文件,描述该图像中文本的边界框,并在边界框中returnstext

我正在使用python C API来使用我现有的python代码(使用OCR(来提取文本。如果我在 grpc 服务器运行之前调用 python 函数,一切都按预期工作。但是如果我在 rpc 中调用 python 函数,那么 python 函数不会返回任何内容,它在执行 python 代码的某些部分后变得无响应(我调试过(。

我用 python 片段进行了测试,它将休眠 30 秒,它正在工作。我做错了什么?我不应该从 rpc 方法调用 python/ocr 吗?请给我任何方向。

谢谢。

sample code
class ClientImpl final : public ImagToText::Service
{
public:
explicit ClientImpl()
{
}
Status GetOCRText(ServerContext* context, ServerReader<UploadImageRequest>*reader, ITTResponse *response) override
{
//...
response->set_ocrtext(PythonFun("img.jpg","data.json"));
return Status::OK;
}
string PythonFun(std::string str0,std::string str1)
{
//...
}
}
void RunServer()
{
std::string server_address("0.0.0.0:50051");
ClientImpl service;
ServerBuilder builder;
builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
builder.RegisterService(&service);
std::unique_ptr<Server> server(builder.BuildAndStart());
std::cout << "Server listening on " << server_address << std::endl;
server->Wait();
}
int main(int argc,char *argv[])
{
//Below case is working fine
//PythonFun("img.jpg","data.json");
Py_Initialize();
RunServer();
Py_Finalize();
return 0;
}

我浏览了Python C API文档,发现以下内容 [https://docs.python.org/3/c-api/init.html#thread-state-and-the-global-interpreter-lock][1]

PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
/* Perform Python actions here. */
result = CallSomeFunction();
/* evaluate result or handle exception */
/* Release the thread. No Python API allowed beyond this point. */
PyGILState_Release(gstate);

这帮助我解决了我的问题。 希望这对某人有所帮助。

最新更新