在 Python 中阅读 StanfordNLP 输出的 Protobuf 序列化
Read Protobuf Serialization of StanfordNLP Output in Python
我想在 protobuf 中输出 StanfordNLP 结果(因为它的大小要小得多)并在 python 中读回结果。我该怎么做?
我按照指令here输出了用ProtobufAnnotationSerializer
序列化的结果,像这样:
java -cp "stanford-corenlp-full-2015-12-09/*" \
edu.stanford.nlp.pipeline.StanfordCoreNLP \
-annotators tokenize,ssplit \
-file input.txt \
-outputFormat serialized \
-outputSerializer \
edu.stanford.nlp.pipeline.ProtobufAnnotationSerializer
然后使用protoc
将StanfordNLP源码自带的CoreNLP.proto
编译成python模块,如下:
protoc --python_out=. CoreNLP.proto
然后在python我读回文件是这样的:
import CoreNLP_pb2
doc = CoreNLP_pb2.Document()
doc.ParseFromString(open('input.txt.ser.gz', 'rb').read())
解析失败并显示以下错误消息
---------------------------------------------------------------------------
DecodeError Traceback (most recent call last)
<ipython-input-213-d8eaeb9c2048> in <module>()
1 doc = CoreNLP_pb2.Document()
----> 2 doc.ParseFromString(open('imed/s5_tokenized/conv-00000.ser.gz', 'rb').read())
/usr/local/lib/python2.7/dist-packages/google/protobuf/message.pyc in ParseFromString(self, serialized)
183 """
184 self.Clear()
--> 185 self.MergeFromString(serialized)
186
187 def SerializeToString(self):
/usr/local/lib/python2.7/dist-packages/google/protobuf/internal/python_message.pyc in MergeFromString(self, serialized)
1092 # The only reason _InternalParse would return early is if it
1093 # encountered an end-group tag.
-> 1094 raise message_mod.DecodeError('Unexpected end-group tag.')
1095 except (IndexError, TypeError):
1096 # Now ord(buf[p:p+1]) == ord('') gets TypeError.
DecodeError: Unexpected end-group tag.
更新:
我问了序列化程序的作者 Gabor Angeli,得到了答案。 protobuf 对象被写入 this line 中 writeDelimitedTo
的文件。将其更改为 writeTo
将使输出文件在 Python 中可读。
这个问题好像又出现了,所以我想我应该写一个合适的答案。问题的根源是原型是使用 Java 的 writeDelimitedTo
方法编写的,Google 尚未为 Python 实现。解决方法是使用以下方法读取原始文件(假设文件未压缩——您可以将 f.read()
替换为适当的代码以根据需要解压缩文件):
from google.protobuf.internal.decoder import _DecodeVarint
import CoreNLP_pb2
def readCoreNLPProtoFile(protoFile):
protos = []
with open(protoFile, 'rb') as f:
# -- Read the file --
data = f.read()
# -- Parse the file --
# In Java. there's a parseDelimitedFrom() method that makes this easier
pos = 0
while (pos < len(data)):
# (read the proto)
(size, pos) = _DecodeVarint(data, pos)
proto = CoreNLP_pb2.Document()
proto.ParseFromString(data[pos:(pos+size)])
pos += size
# (add the proto to the list; or, `yield proto`)
protos.append(proto)
return protos
文件 CoreNLP_pb2
是使用以下命令从 repo 中的 CoreNLP.proto 文件编译而来的:
protoc --python_out /path/to/output/ /path/to/CoreNLP.proto
请注意,在撰写本文时(版本 3.7.0),格式是 proto2,而不是 proto3。
Golang中有一个简单的解决方案,假设原始数据是“data”并解析为“msg”:
import (
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/encoding/protowire"
)
func CoreNLPUnmarshal(data []byte, msg
protoreflect.ProtoMessage) error {
bs, n := protowire.ConsumeBytes(data)
if n < 0 {
return protowire.ParseError(n)
}
return proto.Unmarshal(bs, msg)
}
我想在 protobuf 中输出 StanfordNLP 结果(因为它的大小要小得多)并在 python 中读回结果。我该怎么做?
我按照指令here输出了用ProtobufAnnotationSerializer
序列化的结果,像这样:
java -cp "stanford-corenlp-full-2015-12-09/*" \
edu.stanford.nlp.pipeline.StanfordCoreNLP \
-annotators tokenize,ssplit \
-file input.txt \
-outputFormat serialized \
-outputSerializer \
edu.stanford.nlp.pipeline.ProtobufAnnotationSerializer
然后使用protoc
将StanfordNLP源码自带的CoreNLP.proto
编译成python模块,如下:
protoc --python_out=. CoreNLP.proto
然后在python我读回文件是这样的:
import CoreNLP_pb2
doc = CoreNLP_pb2.Document()
doc.ParseFromString(open('input.txt.ser.gz', 'rb').read())
解析失败并显示以下错误消息
---------------------------------------------------------------------------
DecodeError Traceback (most recent call last)
<ipython-input-213-d8eaeb9c2048> in <module>()
1 doc = CoreNLP_pb2.Document()
----> 2 doc.ParseFromString(open('imed/s5_tokenized/conv-00000.ser.gz', 'rb').read())
/usr/local/lib/python2.7/dist-packages/google/protobuf/message.pyc in ParseFromString(self, serialized)
183 """
184 self.Clear()
--> 185 self.MergeFromString(serialized)
186
187 def SerializeToString(self):
/usr/local/lib/python2.7/dist-packages/google/protobuf/internal/python_message.pyc in MergeFromString(self, serialized)
1092 # The only reason _InternalParse would return early is if it
1093 # encountered an end-group tag.
-> 1094 raise message_mod.DecodeError('Unexpected end-group tag.')
1095 except (IndexError, TypeError):
1096 # Now ord(buf[p:p+1]) == ord('') gets TypeError.
DecodeError: Unexpected end-group tag.
更新:
我问了序列化程序的作者 Gabor Angeli,得到了答案。 protobuf 对象被写入 this line 中 writeDelimitedTo
的文件。将其更改为 writeTo
将使输出文件在 Python 中可读。
这个问题好像又出现了,所以我想我应该写一个合适的答案。问题的根源是原型是使用 Java 的 writeDelimitedTo
方法编写的,Google 尚未为 Python 实现。解决方法是使用以下方法读取原始文件(假设文件未压缩——您可以将 f.read()
替换为适当的代码以根据需要解压缩文件):
from google.protobuf.internal.decoder import _DecodeVarint
import CoreNLP_pb2
def readCoreNLPProtoFile(protoFile):
protos = []
with open(protoFile, 'rb') as f:
# -- Read the file --
data = f.read()
# -- Parse the file --
# In Java. there's a parseDelimitedFrom() method that makes this easier
pos = 0
while (pos < len(data)):
# (read the proto)
(size, pos) = _DecodeVarint(data, pos)
proto = CoreNLP_pb2.Document()
proto.ParseFromString(data[pos:(pos+size)])
pos += size
# (add the proto to the list; or, `yield proto`)
protos.append(proto)
return protos
文件 CoreNLP_pb2
是使用以下命令从 repo 中的 CoreNLP.proto 文件编译而来的:
protoc --python_out /path/to/output/ /path/to/CoreNLP.proto
请注意,在撰写本文时(版本 3.7.0),格式是 proto2,而不是 proto3。
Golang中有一个简单的解决方案,假设原始数据是“data”并解析为“msg”:
import (
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/encoding/protowire"
)
func CoreNLPUnmarshal(data []byte, msg
protoreflect.ProtoMessage) error {
bs, n := protowire.ConsumeBytes(data)
if n < 0 {
return protowire.ParseError(n)
}
return proto.Unmarshal(bs, msg)
}