2026-05-23 09:57:19 +00:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
|
"""Convert TensorFlow SavedModel to ONNX format."""
|
|
|
|
|
|
|
|
|
|
import argparse
|
2026-05-23 10:26:21 +00:00
|
|
|
import logging
|
2026-05-23 09:57:19 +00:00
|
|
|
import subprocess
|
|
|
|
|
import sys
|
|
|
|
|
from pathlib import Path
|
|
|
|
|
|
2026-05-23 10:26:21 +00:00
|
|
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
|
|
|
|
|
|
2026-05-23 09:57:19 +00:00
|
|
|
|
|
|
|
|
def main():
|
2026-05-23 10:26:21 +00:00
|
|
|
"""Convert a TensorFlow SavedModel to ONNX format using tf2onnx."""
|
2026-05-23 09:57:19 +00:00
|
|
|
parser = argparse.ArgumentParser(
|
|
|
|
|
description="Convert TensorFlow SavedModel to ONNX format"
|
|
|
|
|
)
|
|
|
|
|
parser.add_argument(
|
|
|
|
|
"--saved-model",
|
|
|
|
|
type=Path,
|
|
|
|
|
default=Path("model/saved_model"),
|
|
|
|
|
help="Path to the TensorFlow SavedModel directory",
|
|
|
|
|
)
|
|
|
|
|
parser.add_argument(
|
|
|
|
|
"--output",
|
|
|
|
|
type=Path,
|
|
|
|
|
default=Path("model/model.onnx"),
|
|
|
|
|
help="Path to the output ONNX model file",
|
|
|
|
|
)
|
|
|
|
|
parser.add_argument(
|
|
|
|
|
"--opset",
|
|
|
|
|
type=int,
|
|
|
|
|
default=13,
|
|
|
|
|
help="ONNX opset version to target",
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
args = parser.parse_args()
|
|
|
|
|
|
|
|
|
|
if not args.saved_model.exists():
|
|
|
|
|
raise FileNotFoundError(f"SavedModel not found at {args.saved_model}")
|
|
|
|
|
|
|
|
|
|
args.output.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
|
|
|
|
|
cmd = [
|
|
|
|
|
sys.executable,
|
|
|
|
|
"-m",
|
|
|
|
|
"tf2onnx.convert",
|
|
|
|
|
"--saved-model",
|
|
|
|
|
str(args.saved_model),
|
|
|
|
|
"--output",
|
|
|
|
|
str(args.output),
|
|
|
|
|
"--opset",
|
|
|
|
|
str(args.opset),
|
|
|
|
|
]
|
|
|
|
|
|
2026-05-23 10:26:21 +00:00
|
|
|
try:
|
|
|
|
|
subprocess.run(cmd, check=True)
|
|
|
|
|
except subprocess.CalledProcessError as e:
|
|
|
|
|
logging.error(f"tf2onnx conversion failed with exit code {e.returncode}")
|
|
|
|
|
raise
|
2026-05-23 09:57:19 +00:00
|
|
|
|
2026-05-23 10:26:21 +00:00
|
|
|
logging.info(f"ONNX model saved to {args.output}")
|
2026-05-23 09:57:19 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
main()
|