# Copyright (c) 2021 PaddlePaddle Authors. 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.
import os
from typing import Optional

import onnxruntime as ort


def get_sess(model_path: Optional[os.PathLike]=None, sess_conf: dict=None):
    sess_options = ort.SessionOptions()
    sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
    sess_options.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL

    if "gpu" in sess_conf["device"]:
        # fastspeech2/mb_melgan can't use trt now!
        if sess_conf["use_trt"]:
            providers = ['TensorrtExecutionProvider']
        else:
            providers = ['CUDAExecutionProvider']
    elif sess_conf["device"] == "cpu":
        providers = ['CPUExecutionProvider']
    sess_options.intra_op_num_threads = sess_conf["cpu_threads"]
    sess = ort.InferenceSession(
        model_path, providers=providers, sess_options=sess_options)
    return sess
