无Schema时将TensorFlow Serving类Protobuf日志转为Python字典
问题:无Schema解析类Protobuf格式的TensorFlow Serving gRPC日志为Python字典
用户持有一段TensorFlow Serving系统的gRPC日志,格式为类Protobuf的字符串,希望将其转换为指定结构的Python字典,此前尝试过正则表达式解析,想了解是否有更合适的工具库实现该转换。
原始gRPC日志(类Protobuf格式):
model_spec:{name:"model_name"} inputs:{key:"args_0" value:{dtype:DT_STRING tensor_shape:{dim:{size:1}} string_val:"example input"}} inputs:{key:"args_1" value:{dtype:DT_STRING tensor_shape:{dim:{size:1}} string_val:"another example input"}} inputs:{key:"args_3" value:{dtype:DT_FLOAT tensor_shape:{dim:{size:1}} float_val:374969}}
目标Python字典格式:
{ "model_spec":{"name":"model_name"}, "inputs":{ "args_0": "example input", "args_1": "another example input", "args_3": 374969 } }
可行的工具库方案
- protobuf-text:这是专门针对Protobuf文本格式的解析库,无需提前知晓Schema。它能直接把类Protobuf字符串解析为动态Python对象,之后你可以遍历对象提取需要的字段值,转换成目标字典结构。安装命令:
pip install protobuf-text,核心用法是调用parse_text方法完成解析,处理嵌套、重复字段的能力比正则表达式可靠得多。 - 官方protobuf库的动态消息API:如果不想额外安装第三方库,官方
protobuf库支持动态构建消息描述符。你可以通过google.protobuf.descriptor_pb2.FileDescriptorProto手动定义字段结构,再完成解析,这个方法无需额外依赖,但操作相对繁琐。 - pyhocon:虽然它原本用于解析HOCON配置文件,但HOCON语法和这类Protobuf文本格式高度相似,也可以用来解析日志字符串,之后再做字段映射转换到目标字典。
这些工具都比正则表达式更适配你的场景,尤其是protobuf-text,完全针对Protobuf文本格式设计,能轻松处理日志里的重复inputs字段、嵌套结构,不会出现正则容易触发的边界错误。
内容的提问来源于stack exchange,提问作者mrzo
相关产品推荐
相关产品推荐

