# Copyright (c) Hangzhou Hikvision Digital Technology Co., Ltd. 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
#
# https://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 detectron2.utils.file_io import PathManager
from detectron2.config import get_cfg
from detectron2.engine import launch
# to register
import coin.data.datasets.builtin

from coin import add_config
from coin.evaluation.gdino_pascal_voc_evaluation import GDINO_PascalVOCDetectionEvaluator
from coin.evaluation.testing import print_csv_format
from coin.utils.util import default_setup, default_argument_parser

os.environ["TOKENIZERS_PARALLELISM"] = "false"

def setup(args):
    """
    Create configs and perform basic setups.
    """
    # detectron2的配置文件
    cfg = get_cfg()
    add_config(cfg)
    cfg.merge_from_file(args.config_file)
    cfg.merge_from_list(args.opts)
    cfg.merge_from_list(['RESUME',args.resume])
    args.eval_only=True
    cfg.freeze()
    # 设置logger之类的，输出环境信息等
    default_setup(cfg, args)
    return cfg


def main(args):
    cfg = setup(args)

    if args.eval_only:
        dataset_name = cfg.DATASETS.TEST[0]
        evaluator = GDINO_PascalVOCDetectionEvaluator(cfg, dataset_name)
        results = evaluator.evaluate()
        print_csv_format(cfg, results)

        return results


if __name__ == "__main__":
    
    args = default_argument_parser().parse_args()

    # launch文件启动，主要进行分布式训练
    launch(
        main,
        args.num_gpus,
        num_machines=args.num_machines,
        machine_rank=args.machine_rank,
        dist_url='auto',
        args=(args,),
    )
