code: #     Copyright [yyyy] [name of copyright owner]
  #     Copyright 2021 Huawei Technologies Co., Ltd
  #
  #     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.
  #
  
  """RAdam Optimizer.
  Implementation lifted from: https://github.com/LiyuanLucasLiu/RAdam
  Paper: `On the Variance of the Adaptive Learning Rate and Beyond` - https://arxiv.org/abs/1908.03265
  """
  import math
  import torch
  from torch.optim.optimizer import Optimizer, required
  
  
  class RAdam(Optimizer):
  
      def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0):
          defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay)
          self.buffer = [[None, None, None] for ind in range(10)]
          super(RAdam, self).__init__(params, defaults)
  
      def __setstate__(self, state):
          super(RAdam, self).__setstate__(state)
  
      def step(self, closure=None):
  
          loss = None
          if closure is not None:
              loss = closure()
  
          for group in self.param_groups:
  
              for p in group['params']:
                  if p.grad is None:
                      continue
                  grad = p.grad.data.float()
                  if grad.is_sparse:
                      raise RuntimeError('RAdam does not support sparse gradients')
  
                  p_data_fp32 = p.data.float()
  
                  state = self.state[p]
  
                  if len(state) == 0:
                      state['step'] = 0
                      state['exp_avg'] = torch.zeros_like(p_data_fp32)
                      state['exp_avg_sq'] = torch.zeros_like(p_data_fp32)
                  else:
                      state['exp_avg'] = state['exp_avg'].type_as(p_data_fp32)
                      state['exp_avg_sq'] = state['exp_avg_sq'].type_as(p_data_fp32)
  
                  exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']
                  beta1, beta2 = group['betas']
  
                  exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)
                  exp_avg.mul_(beta1).add_(1 - beta1, grad)
  
                  state['step'] += 1
                  buffered = self.buffer[int(state['step'] % 10)]
                  if state['step'] == buffered[0]:
                      N_sma, step_size = buffered[1], buffered[2]
                  else:
                      buffered[0] = state['step']
                      beta2_t = beta2 ** state['step']
                      N_sma_max = 2 / (1 - beta2) - 1
                      N_sma = N_sma_max - 2 * state['step'] * beta2_t / (1 - beta2_t)
                      buffered[1] = N_sma
  
                      # more conservative since it's an approximated value
                      if N_sma >= 5:
                          step_size = group['lr'] * math.sqrt(
                              (1 - beta2_t) * (N_sma - 4) / (N_sma_max - 4) * (N_sma - 2) / N_sma * N_sma_max / (
                                          N_sma_max - 2)) / (1 - beta1 ** state['step'])
                      else:
                          step_size = group['lr'] / (1 - beta1 ** state['step'])
                      buffered[2] = step_size
  
                  if group['weight_decay'] != 0:
                      p_data_fp32.add_(-group['weight_decay'] * group['lr'], p_data_fp32)
  
                  # more conservative since it's an approximated value
                  if N_sma >= 5:
                      denom = exp_avg_sq.sqrt().add_(group['eps'])
                      p_data_fp32.addcdiv_(-step_size, exp_avg, denom)
                  else:
                      p_data_fp32.add_(-step_size, exp_avg)
  
                  p.data.copy_(p_data_fp32)
  
          return loss
  
  
  class PlainRAdam(Optimizer):
  
      def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0):
          defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay)
  
          super(PlainRAdam, self).__init__(params, defaults)
  
      def __setstate__(self, state):
          super(PlainRAdam, self).__setstate__(state)
  
      def step(self, closure=None):
  
          loss = None
          if closure is not None:
              loss = closure()
  
          for group in self.param_groups:
  
              for p in group['params']:
                  if p.grad is None:
                      continue
                  grad = p.grad.data.float()
                  if grad.is_sparse:
                      raise RuntimeError('RAdam does not support sparse gradients')
  
                  p_data_fp32 = p.data.float()
  
                  state = self.state[p]
  
                  if len(state) == 0:
                      state['step'] = 0
                      state['exp_avg'] = torch.zeros_like(p_data_fp32)
                      state['exp_avg_sq'] = torch.zeros_like(p_data_fp32)
                  else:
                      state['exp_avg'] = state['exp_avg'].type_as(p_data_fp32)
                      state['exp_avg_sq'] = state['exp_avg_sq'].type_as(p_data_fp32)
  
                  exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']
                  beta1, beta2 = group['betas']
  
                  exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)
                  exp_avg.mul_(beta1).add_(1 - beta1, grad)
  
                  state['step'] += 1
                  beta2_t = beta2 ** state['step']
                  N_sma_max = 2 / (1 - beta2) - 1
                  N_sma = N_sma_max - 2 * state['step'] * beta2_t / (1 - beta2_t)
  
                  if group['weight_decay'] != 0:
                      p_data_fp32.add_(-group['weight_decay'] * group['lr'], p_data_fp32)
  
                  # more conservative since it's an approximated value
                  if N_sma >= 5:
                      step_size = group['lr'] * math.sqrt(
                          (1 - beta2_t) * (N_sma - 4) / (N_sma_max - 4) * (N_sma - 2) / N_sma * N_sma_max / (
                                      N_sma_max - 2)) / (1 - beta1 ** state['step'])
                      denom = exp_avg_sq.sqrt().add_(group['eps'])
                      p_data_fp32.addcdiv_(-step_size, exp_avg, denom)
                  else:
                      step_size = group['lr'] / (1 - beta1 ** state['step'])
                      p_data_fp32.add_(-step_size, exp_avg)
  
                  p.data.copy_(p_data_fp32)
  
          return loss
   # Copyright 2017 The TensorFlow 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.
  # ============================================================================
  # Copyright 2021 Huawei Technologies Co., Ltd
  #
  # 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 sklearn.metrics import  average_precision_score, roc_auc_score
  import numpy as np
  import sys
  
  def aucPerformance(mse, labels):
      """
      :param mse:
      :param labels:
      :return:
      """
      roc_auc = roc_auc_score(labels, mse)
      ap = average_precision_score(labels, mse)
      print("AUC-ROC: %.4f, AUC-PR: %.4f" % (roc_auc, ap))
      return roc_auc, ap
  
  
  def eval_om(label_dir, om_output_dir):
      """
      :param label_dir:
      :param om_output_dir:
      :return:
      """
      label, score = read_directory(label_dir, om_output_dir)
      aucPerformance(score, label)
  
  
  def read_directory(label_dir, om_output_dir):
      """
      :param label_dir:
      :param om_output_dir:
      :return:
      """
      # get label bin files
      labels = os.listdir(label_dir)
      labels.sort()
      labels_data = list()
  
      # get om output files
      outputs = os.listdir(om_output_dir)
      outputs.sort()
      outputs_data = list()
  
      for i in range(len(outputs)):
          label_data = np.fromfile(os.path.join(label_dir, labels[i]), dtype=np.int32)
          labels_data.extend(label_data)
          output_data = np.fromfile(os.path.join(om_output_dir, outputs[i]), dtype=np.float32)
          outputs_data.extend(output_data)
      return labels_data, outputs_data
  
  gt_dir = sys.argv[1]
  predict_dir = sys.argv[2]
  eval_om(gt_dir, predict_dir)
   # Copyright 2017 The TensorFlow 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.
  # ============================================================================
  # Copyright 2021 Huawei Technologies Co., Ltd
  #
  # 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
  import numpy as np
  import multiprocessing
  import sys
  sys.path.append('./')
  from utility.batch_test import cores, Ks, BATCH_SIZE, ITEM_NUM, data_generator, test_one_user
  from utility.parser import parse_args
  
  
  def xaclPath(output_path, inference_path, model_path):
      """
      使用文件夹推理
      """
      if os.path.isdir(inference_path):
          os.system("rm -rf " + inference_path)
      os.makedirs(inference_path)
      output_path = output_path if output_path[-1] == "/" else output_path + "/"
      output_path_lst = [output_path + "input1", output_path + "input2", output_path + "input3"]
      output_paths = ','.join(output_path_lst)
      print("xacl_fmk -m " + model_path + " -i " + output_paths +
            " -o " + inference_path + '/kgat_output_bin')
      os.system("xacl_fmk -m " + model_path + " -i " +
                output_paths + " -o " + inference_path + '/kgat_output_bin')
      print(inference_path)
      print("[INFO]    推理结果生成结束")
  
  
  def inference_files(inference_path):
      result = {'precision': np.zeros(len(Ks)), 'recall': np.zeros(len(Ks)), 'ndcg': np.zeros(len(Ks)),
                'hit_ratio': np.zeros(len(Ks)), 'auc': 0.}
  
      pool = multiprocessing.Pool(cores)
  
      u_batch_size = BATCH_SIZE * 2
  
      users_to_test = list(data_generator.test_user_dict.keys())
      test_users = users_to_test
      n_test_users = len(test_users)
  
      files = sorted(os.listdir(inference_path))
      files = [inference_path + '/' + i for i in files]
  
      for u_batch_id, f in enumerate(files):
          if f.endswith(".bin"):
              rate_batch = np.fromfile(f, dtype='float32')
              rate_batch = rate_batch.reshape((-1, ITEM_NUM))
  
              start = u_batch_id * u_batch_size
              end = (u_batch_id + 1) * u_batch_size
  
              user_batch = test_users[start: end]
  
              user_batch_rating_uid = zip(rate_batch, user_batch)
              batch_result = pool.map(test_one_user, user_batch_rating_uid)
  
              for re in batch_result:
                  result['precision'] += re['precision'] / n_test_users
                  result['recall'] += re['recall'] / n_test_users
                  result['ndcg'] += re['ndcg'] / n_test_users
                  result['hit_ratio'] += re['hit_ratio'] / n_test_users
                  result['auc'] += re['auc'] / n_test_users
      pool.close()
      print(result)
  
  
  if __name__ == '__main__':
      args = parse_args()
  
      output_path = args.output_path
      inference_path = args.inference_path
      model_path = args.model_path
  
      xaclPath(output_path, inference_path, model_path)
      inference_files(inference_path)
   # Copyright 2021 Huawei Technologies Co., Ltd
  #
  # 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 argparse
  import subprocess
  
  import torch
  
  
  def parse_args():
      parser = argparse.ArgumentParser(
          description='Process a checkpoint to be published')
      parser.add_argument('in_file', help='input checkpoint filename')
      parser.add_argument('out_file', help='output checkpoint filename')
      args = parser.parse_args()
      return args
  
  
  def process_checkpoint(in_file, out_file):
      checkpoint = torch.load(in_file, map_location='cpu')
      # remove optimizer for smaller file size
      if 'optimizer' in checkpoint:
          del checkpoint['optimizer']
      # if it is necessary to remove some sensitive data in checkpoint['meta'],
      # add the code here.
      torch.save(checkpoint, out_file)
      sha = subprocess.check_output(['sha256sum', out_file]).decode()
      if out_file.endswith('.pth'):
          out_file_name = out_file[:-4]
      else:
          out_file_name = out_file
      final_file = out_file_name + f'-{sha[:8]}.pth'
      subprocess.Popen(['mv', out_file, final_file])
  
  
  def main():
      args = parse_args()
      process_checkpoint(args.in_file, args.out_file)
  
  
  if __name__ == '__main__':
      main()
   # Copyright 2021 Huawei Technologies Co., Ltd
  #
  # 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 torch
  from torch.nn.parallel.distributed import (DistributedDataParallel,
                                             _find_tensors)
  
  from mmcv import print_log
  from mmcv.utils import TORCH_VERSION
  from .scatter_gather import scatter_kwargs
  
  
  class MMDistributedDataParallel(DistributedDataParallel):
      """The DDP module that supports DataContainer.
  
      MMDDP has two main differences with PyTorch DDP:
  
      - It supports a custom type :class:`DataContainer` which allows more
        flexible control of input data.
      - It implement two APIs ``train_step()`` and ``val_step()``.
      """
  
      def scatter(self, inputs, kwargs, device_ids):
          return scatter_kwargs(inputs, kwargs, device_ids, dim=self.dim)
  
      def train_step(self, *inputs, **kwargs):
          """train_step() API for module wrapped by DistributedDataParallel.
  
          This method is basically the same as
          ``DistributedDataParallel.forward()``, while replacing
          ``self.module.forward()`` with ``self.module.train_step()``.
          It is compatible with PyTorch 1.1 - 1.5.
          """
  
          # In PyTorch >= 1.7, ``reducer._rebuild_buckets()`` is moved from the
          # end of backward to the beginning of forward.
          if (TORCH_VERSION >= '1.7' and 'parrots'
                  not in TORCH_VERSION) and self.reducer._rebuild_buckets():
              print_log(
                  'Reducer buckets have been rebuilt in this iteration.',
                  logger='mmcv')
  
          if getattr(self, 'require_forward_param_sync', True):
              self._sync_params()
          if self.device_ids and False:
              inputs, kwargs = self.scatter(inputs, kwargs, self.device_ids)
              if len(self.device_ids) == 1:
                  output = self.module.train_step(*inputs[0], **kwargs[0])
              else:
                  outputs = self.parallel_apply(
                      self._module_copies[:len(inputs)], inputs, kwargs)
                  output = self.gather(outputs, self.output_device)
          else:
              inputs, kwargs = self.scatter(inputs, kwargs, [-1])
              output = self.module.train_step(*inputs[0], **kwargs[0])
  
          if torch.is_grad_enabled() and getattr(
                  self, 'require_backward_grad_sync', True):
              if self.find_unused_parameters:
                  self.reducer.prepare_for_backward(list(_find_tensors(output)))
              else:
                  self.reducer.prepare_for_backward([])
          else:
              if TORCH_VERSION > '1.2':
                  self.require_forward_param_sync = False
          return output
  
      def val_step(self, *inputs, **kwargs):
          """val_step() API for module wrapped by DistributedDataParallel.
  
          This method is basically the same as
          ``DistributedDataParallel.forward()``, while replacing
          ``self.module.forward()`` with ``self.module.val_step()``.
          It is compatible with PyTorch 1.1 - 1.5.
          """
          # In PyTorch >= 1.7, ``reducer._rebuild_buckets()`` is moved from the
          # end of backward to the beginning of forward.
          if (TORCH_VERSION >= '1.7' and 'parrots'
                  not in TORCH_VERSION) and self.reducer._rebuild_buckets():
              print_log(
                  'Reducer buckets have been rebuilt in this iteration.',
                  logger='mmcv')
  
          if getattr(self, 'require_forward_param_sync', True):
              self._sync_params()
          if self.device_ids:
              inputs, kwargs = self.scatter(inputs, kwargs, self.device_ids)
              if len(self.device_ids) == 1:
                  output = self.module.val_step(*inputs[0], **kwargs[0])
              else:
                  outputs = self.parallel_apply(
                      self._module_copies[:len(inputs)], inputs, kwargs)
                  output = self.gather(outputs, self.output_device)
          else:
              output = self.module.val_step(*inputs, **kwargs)
  
          if torch.is_grad_enabled() and getattr(
                  self, 'require_backward_grad_sync', True):
              if self.find_unused_parameters:
                  self.reducer.prepare_for_backward(list(_find_tensors(output)))
              else:
                  self.reducer.prepare_for_backward([])
          else:
              if TORCH_VERSION > '1.2':
                  self.require_forward_param_sync = False
          return output
   #     Copyright [yyyy] [name of copyright owner]
  #     Copyright 2020 Huawei Technologies Co., Ltd
  #
  #     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 argparse
  import collections
  import os
  import sys
  import time
  
  import cv2
  import numpy as np
  import torch
  from torch.utils import data
  
  import models
  import util
  from dataset import IC15TestLoader
  # c++ version pse based on opencv 3+
  # from pse import pse
  # python pse
  from pypse import pse as pypse
  
  
  def extend_3c(img):
      img = img.reshape(img.shape[0], img.shape[1], 1)
      img = np.concatenate((img, img, img), axis=2)
      return img
  
  
  def debug(idx, img_paths, imgs, output_root):
      if not os.path.exists(output_root):
          os.makedirs(output_root)
  
      col = []
      for i in range(len(imgs)):
          row = []
          for j in range(len(imgs[i])):
              # img = cv2.copyMakeBorder(imgs[i][j], 3, 3, 3, 3, cv2.BORDER_CONSTANT, value=[255, 0, 0])
              row.append(imgs[i][j])
          res = np.concatenate(row, axis=1)
          col.append(res)
      res = np.concatenate(col, axis=0)
      img_name = img_paths[idx].split('/')[-1]
      print(idx, '/', len(img_paths), img_name)
      cv2.imwrite(output_root + img_name, res)
  
  
  def write_result_as_txt(image_name, bboxes, path):
      if not os.path.exists(path):
          os.mkdir(path)
      filename = util.io.join_path(path, 'res_%s.txt' % (image_name))
      lines = []
      for b_idx, bbox in enumerate(bboxes):
          values = [int(v) for v in bbox]
          line = "%d, %d, %d, %d, %d, %d, %d, %d\n" % tuple(values)
          lines.append(line)
      util.io.write_lines(filename, lines)
  
  
  def polygon_from_points(points):
      """
      Returns a Polygon object to use with the Polygon2 class from a list of 8 points: x1,y1,x2,y2,x3,y3,x4,y4
      """
      resBoxes = np.empty([1, 8], dtype='int32')
      resBoxes[0, 0] = int(points[0])
      resBoxes[0, 4] = int(points[1])
      resBoxes[0, 1] = int(points[2])
      resBoxes[0, 5] = int(points[3])
      resBoxes[0, 2] = int(points[4])
      resBoxes[0, 6] = int(points[5])
      resBoxes[0, 3] = int(points[6])
      resBoxes[0, 7] = int(points[7])
      pointMat = resBoxes[0].reshape([2, 4]).T
      return plg.Polygon(pointMat)
  
  
  @torch.no_grad()
  def test(args):
      data_loader = IC15TestLoader(long_size=args.long_size, datadir=args.data_dir)
      test_loader = torch.utils.data.DataLoader(
          data_loader,
          batch_size=1,
          shuffle=False,
          num_workers=1,
          drop_last=True)
  
      # Setup Model
      if args.arch == "resnet50":
          model = models.resnet50(pretrained=True, num_classes=7, scale=args.scale)
      elif args.arch == "resnet101":
          model = models.resnet101(pretrained=True, num_classes=7, scale=args.scale)
      elif args.arch == "resnet152":
          model = models.resnet152(pretrained=True, num_classes=7, scale=args.scale)
  
      for param in model.parameters():
          param.requires_grad = False
  
      model = model.to(CALCULATE_DEVICE)
  
      if args.resume is not None:
          if os.path.isfile(args.resume):
              print("Loading model and optimizer from checkpoint '{}'".format(args.resume))
              checkpoint = torch.load(args.resume, map_location=CALCULATE_DEVICE)
  
              # model.load_state_dict(checkpoint['state_dict'])
              d = collections.OrderedDict()
              for key, value in checkpoint['state_dict'].items():
                  if key.startswith('module.'):
                      tmp = key[7:]
                  else:
                      tmp = key
                  d[tmp] = value
              model.load_state_dict(d)
  
              print("Loaded checkpoint '{}' (epoch {})"
                    .format(args.resume, checkpoint['epoch']))
              sys.stdout.flush()
          else:
              print("No checkpoint found at '{}'".format(args.resume))
              sys.stdout.flush()
  
      model.eval()
      total_frame = 0.0
      total_time = 0.0
      for idx, (org_img, img) in enumerate(test_loader):
          print('progress: %d / %d' % (idx, len(test_loader)))
          sys.stdout.flush()
  
          img = img.to(CALCULATE_DEVICE)
          org_img = org_img.numpy().astype('uint8')[0]
          text_box = org_img.copy()
  
          torch.npu.synchronize()
          start = time.time()
          outputs = model(img)
  
          score = torch.sigmoid(outputs[:, 0, :, :])
          outputs = (torch.sign(outputs - args.binary_th) + 1) / 2
  
          text = outputs[:, 0, :, :]
          kernels = outputs[:, 0:args.kernel_num, :, :] * text
  
          score = score.data.cpu().numpy()[0].astype(np.float32)
          text = text.data.cpu().numpy()[0].astype(np.uint8)
          kernels = kernels.data.cpu().numpy()[0].astype(np.uint8)
  
          # c++ version pse
          # pred = pse(kernels, args.min_kernel_area / (args.scale * args.scale))
          # python version pse
          pred = pypse(kernels, args.min_kernel_area / (args.scale * args.scale))
          print(pred.shape)
  
          # scale = (org_img.shape[0] * 1.0 / pred.shape[0], org_img.shape[1] * 1.0 / pred.shape[1])
          scale = (org_img.shape[1] * 1.0 / pred.shape[1], org_img.shape[0] * 1.0 / pred.shape[0])
          label = pred
          label_num = np.max(label) + 1
          bboxes = []
          for i in range(1, label_num):
              points = np.array(np.where(label == i)).transpose((1, 0))[:, ::-1]
  
              if points.shape[0] < args.min_area / (args.scale * args.scale):
                  continue
  
              score_i = np.mean(score[label == i])
              if score_i < args.min_score:
                  continue
  
              rect = cv2.minAreaRect(points)
              bbox = cv2.boxPoints(rect) * scale
              bbox = bbox.astype('int32')
              bboxes.append(bbox.reshape(-1))
  
          torch.npu.synchronize()
          end = time.time()
          total_frame += 1
          total_time += (end - start)
          print('fps: %.2f' % (total_frame / total_time))
          sys.stdout.flush()
  
          for bbox in bboxes:
              cv2.drawContours(text_box, [bbox.reshape(4, 2)], -1, (0, 255, 0), 2)
  
          image_name = data_loader.img_paths[idx].split('/')[-1].split('.')[0]
          write_result_as_txt(image_name, bboxes, 'outputs/' + args.output_file)
  
          # text_box = cv2.resize(text_box, (text.shape[1], text.shape[0]))
          # debug(idx, data_loader.img_paths, [[text_box]], 'outputs/vis_ic15/')
  
      cmd = 'cd %s;zip -j %s %s/*' % ('./outputs/', args.output_file + '.zip', args.output_file)
      print(cmd)
      sys.stdout.flush()
      util.cmd.cmd(cmd)
  
  
  if __name__ == '__main__':
      parser = argparse.ArgumentParser(description='Hyperparams')
      parser.add_argument('--arch', nargs='?', type=str, default='resnet50')
      parser.add_argument('--resume', nargs='?', type=str, default=None,
                          help='Path to previous saved model to restart from')
      parser.add_argument('--binary_th', nargs='?', type=float, default=1.0,
                          help='Path to previous saved model to restart from')
      parser.add_argument('--kernel_num', nargs='?', type=int, default=7,
                          help='Path to previous saved model to restart from')
      parser.add_argument('--scale', nargs='?', type=int, default=1,
                          help='Path to previous saved model to restart from')
      parser.add_argument('--long_size', nargs='?', type=int, default=2240,
                          help='Path to previous saved model to restart from')
      parser.add_argument('--min_kernel_area', nargs='?', type=float, default=5.0,
                          help='min kernel area')
      parser.add_argument('--min_area', nargs='?', type=float, default=800.0,
                          help='min area')
      parser.add_argument('--min_score', nargs='?', type=float, default=0.93,
                          help='min score')
      parser.add_argument('--npu', default=None, type=int,
                          help='NPU id to use.')
      parser.add_argument('--data_dir', default='./data/ICDAR/Challenge/', type=str)
      parser.add_argument('--output_file', default='submit_ic15', type=str)
      args = parser.parse_args()
      CALCULATE_DEVICE = f"npu:{args.npu}"
      PRINT_DEVICE = "cpu"
      torch.npu.set_device(CALCULATE_DEVICE)
      test(args)
   # Copyright 2020 Huawei Technologies Co., Ltd
  #
  # 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.
  # ============================================================================
  """ Test Time Pooling (Average-Max Pool)
  
  Hacked together by / Copyright 2020 Ross Wightman
  """
  
  import logging
  from torch import nn
  import torch.nn.functional as F
  
  from .adaptive_avgmax_pool import adaptive_avgmax_pool2d
  
  
  _logger = logging.getLogger(__name__)
  
  
  class TestTimePoolHead(nn.Module):
      def __init__(self, base, original_pool=7):
          super(TestTimePoolHead, self).__init__()
          self.base = base
          self.original_pool = original_pool
          base_fc = self.base.get_classifier()
          if isinstance(base_fc, nn.Conv2d):
              self.fc = base_fc
          else:
              self.fc = nn.Conv2d(
                  self.base.num_features, self.base.num_classes, kernel_size=1, bias=True)
              self.fc.weight.data.copy_(base_fc.weight.data.view(self.fc.weight.size()))
              self.fc.bias.data.copy_(base_fc.bias.data.view(self.fc.bias.size()))
          self.base.reset_classifier(0)  # delete original fc layer
  
      def forward(self, x):
          x = self.base.forward_features(x)
          x = F.avg_pool2d(x, kernel_size=self.original_pool, stride=1)
          x = self.fc(x)
          x = adaptive_avgmax_pool2d(x, 1)
          return x.view(x.size(0), -1)
  
  
  def apply_test_time_pool(model, config, use_test_size=True):
      test_time_pool = False
      if not hasattr(model, 'default_cfg') or not model.default_cfg:
          return model, False
      if use_test_size and 'test_input_size' in model.default_cfg:
          df_input_size = model.default_cfg['test_input_size']
      else:
          df_input_size = model.default_cfg['input_size']
      if config['input_size'][-1] > df_input_size[-1] and config['input_size'][-2] > df_input_size[-2]:
          _logger.info('Target input size %s > pretrained default %s, using test time pooling' %
                       (str(config['input_size'][-2:]), str(df_input_size[-2:])))
          model = TestTimePoolHead(model, original_pool=model.default_cfg['pool_size'])
          test_time_pool = True
      return model, test_time_pool
  
apis: torch.zeros_like
apis: sklearn.metrics.roc_auc_score sklearn.metrics.average_precision_score
apis: numpy.fromfile
apis: torch.save torch.load
apis: torch.is_grad_enabled torch.nn.parallel.distributed._find_tensors
apis: torch.utils.data.DataLoader numpy.empty torch.load numpy.concatenate torch.no_grad numpy.where torch.sign numpy.max torch.npu.synchronize torch.sigmoid torch.npu.set_device numpy.mean
apis: torch.nn.functional.avg_pool2d torch.nn.Conv2d