通过 CLI 序列化和反序列化 protobufs?

Serialize and deserialize protobufs through CLI?

我正在尝试通过 CLI 反序列化保存为 protobuf 的文件(似乎是最简单的事情)。我宁愿不使用 protoc 编译,将其导入编程语言,然后读取结果。

我的用例:TensorFlow lite 工具以 protobuf 格式输出了一些数据。我也在 TensorFlow 存储库中找到了 protobuf message 定义。我只想快速阅读输出。具体来说,我从 inference_diff tool.

收到一条 tflite::evaluation::EvaluationStageMetrics 消息

我假设该工具以二进制格式输出 protobuf 消息。

protoc 可以解码消息并以文本格式输出。看到这个选项:

  --decode=MESSAGE_TYPE       Read a binary message of the given type from
                              standard input and write it in text format
                              to standard output.  The message type must
                              be defined in PROTO_FILES or their imports.

虽然 Timo Stamms 的回答很有帮助,但我仍然在努力寻找让 protoc 在复杂的 repo(例如 TensorFlow)中工作的途径。

最后,这对我有用:

cat inference_diff.txt | \
    protoc --proto_path="/Users/ben/butter/repos/tensorflow/" \
    --decode tflite.evaluation.EvaluationStageMetrics \ 
    $(pwd)/evaluation_config.proto

在这里,我通过管道传输包含 protobuf 的文件的二进制内容(inference_diff.txt 在我的例子中,通过遵循此 guide 生成),并指定完全限定的 protobuf 消息(我通过组合获得package tflite.evaluation; 和消息名称 EvaluationStageMetrics),proto_path 项目的绝对路径(即项目根目录/TensorFlow 存储库),以及文件的绝对路径它实际上包含消息。 proto_path 仅用于解析导入,而 PROTO_FILE(在本例中为 evaluation_config.proto)用于解码文件。

示例输出

num_runs: 50
process_metrics {
  inference_profiler_metrics {
    reference_latency {
      last_us: 455818
      max_us: 577312
      min_us: 453121
      sum_us: 72573828
      avg_us: 483825.52
      std_deviation_us: 37940
    }
    test_latency {
      last_us: 59503
      max_us: 66746
      min_us: 57828
      sum_us: 8992747
      avg_us: 59951.646666666667
      std_deviation_us: 1284
    }
    output_errors {
      max_value: 122.371696
      min_value: 83.0335922
      avg_value: 100.17548828125
      std_deviation: 8.16124535
    }
  }
}

如果你只是想快速获取数字而懒得修改路径,你可以这样做

cat inference_diff.txt | protoc --decode_raw

示例输出

1: 50
2 {
  5 {
    1 {
      1: 455818
      2: 577312
      3: 453121
      4: 72573828
      5: 0x411d87c6147ae148
      6: 37940
    }
    2 {
      1: 59503
      2: 66746
      3: 57828
      4: 8992747
      5: 0x40ed45f4b17e4b18
      6: 1284
    }
    3 {
      1: 0x42f4be4f
      2: 0x42a61133
      3: 0x40590b3b33333333
      4: 0x41029476
    }
  }
}