#!/usr/bin/env python3
#
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

"""
This script uses the Polygraphy Runner API to validate the outputs
of an identity model using a trivial dataset.
"""
import sys
import numpy as np
from polygraphy.backend.trt import EngineFromNetwork, NetworkFromOnnxPath, TrtRunner

# Pretend that this is a very large dataset.
EXAMPLE_DATASET = [
    np.random.normal(size=(1, 512, 512, 3)).astype(np.float32),
    np.random.normal(size=(1, 512, 512, 3)).astype(np.float32),
    np.random.normal(size=(1, 512, 512, 3)).astype(np.float32),
    np.random.normal(size=(1, 512, 512, 3)).astype(np.float32),
    np.random.normal(size=(1, 512, 512, 3)).astype(np.float32),
]  # Definitely real data

# For an identity network, the golden output values are the same as the input values.
# Though such a network appears useless at first glance, it can be very useful in some cases (like here!).
EXPECTED_OUTPUTS = EXAMPLE_DATASET


def main(onnx_model):
    build_engine = EngineFromNetwork(NetworkFromOnnxPath(onnx_model))

    with TrtRunner(build_engine) as runner:
        for data in EXAMPLE_DATASET:
            # NOTE: The runner owns the output buffers and is free to reuse them between `infer()` calls.
            #   Thus, if you want to store results from multiple inferences, you should use `copy.deepcopy()`.
            outputs = runner.infer(feed_dict={"input_image": data})

            assert not np.any(np.isnan(outputs["mrcnn_detection"]))
            assert not np.any(np.isnan(outputs["mrcnn_mask"]))

        print("Validation succeeded!")


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print('Pass ONNX model as an argument')
        sys.exit(1)
    else:
        main(sys.argv[1])
        sys.exit(0)
