def decode(cls, buffer: bytes) -> Dict[str, Any]: """Deserialize a compatible dictionary""" pstruct = Struct() pstruct.ParseFromString(buffer) dictionary = dict(pstruct) cls._patch_dict_restore(dictionary) return dictionary
def decode(obj: bytes) -> Message: """ Decode bytes into a message using Protobuf. First, try to parse the input as a Protobuf 'Message'; if it fails, parse the bytes as struct. """ message_pb = ProtobufMessage() message_pb.ParseFromString(obj) message_type = message_pb.WhichOneof("message") if message_type == "body": body = dict(message_pb.body) # pylint: disable=no-member msg = TMessage(_body=body) return msg if message_type == "dialogue_message": dialogue_message_pb = ( message_pb.dialogue_message # pylint: disable=no-member ) message_id = dialogue_message_pb.message_id target = dialogue_message_pb.target dialogue_starter_reference = dialogue_message_pb.dialogue_starter_reference dialogue_responder_reference = ( dialogue_message_pb.dialogue_responder_reference ) body_json = Struct() body_json.ParseFromString(dialogue_message_pb.content) body = dict(body_json) body["message_id"] = message_id body["target"] = target body["dialogue_reference"] = ( dialogue_starter_reference, dialogue_responder_reference, ) return TMessage(_body=body) raise ValueError("Message type not recognized.") # pragma: nocover
def decode(obj: bytes) -> Message: """Decode bytes into a message using Protobuf.""" body_json = Struct() body_json.ParseFromString(obj) body = dict(body_json) msg = Message(body=body) return msg
def parse_proto_from_path(path: str) -> Dict[str, Any]: from google.protobuf.json_format import MessageToDict from google.protobuf.struct_pb2 import Struct try: s = Struct() with open(path, "rb") as data_file: try: r = data_file.read() s.ParseFromString(r) data = MessageToDict(s) return data except: print(f"Error loading proto to dict for file {path}") return dict() except FileNotFoundError: raise FileNotFoundError(f"The configuration file {path} was not found")