You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

run_label_server.py 5.5 kB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. """
  2. /**
  3. * Copyright 2020 Zhejiang Lab. All Rights Reserved.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. * =============================================================
  17. */
  18. """
  19. # !/usr/bin/env python3
  20. # -*- coding: utf-8 -*-
  21. import _thread
  22. import argparse
  23. import codecs
  24. import json
  25. import os
  26. import random
  27. import string
  28. import sys
  29. import time
  30. import urllib
  31. from queue import Queue
  32. import predict_with_print_box as yolo_demo
  33. import web
  34. from upload_config import Upload_cfg, MyApplication
  35. from log_config import setup_log
  36. '''Config urls and chinese coding'''
  37. urls = ('/auto_annotate', 'Upload')
  38. sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
  39. '''Set port and mode'''
  40. parser = argparse.ArgumentParser(description="config for label server")
  41. parser.add_argument("-p", "--port", type=int, required=True)
  42. parser.add_argument("-m", "--mode", type=str, default="test", required=False)
  43. args = parser.parse_args()
  44. '''Set path'''
  45. base_path = "/nfs/"
  46. label_url = "api/data/datasets/files/annotations/auto/"
  47. url_json = './config/url.json'
  48. '''Init task queue and log'''
  49. with open(url_json) as f:
  50. url_dict = json.loads(f.read())
  51. label_url = url_dict[args.mode] + label_url
  52. port = args.port
  53. taskQueue = Queue()
  54. taskInImages = {}
  55. des_folder = os.path.join('./log', args.mode)
  56. if not os.path.exists(des_folder):
  57. os.makedirs(des_folder)
  58. label_log = setup_log(args.mode, 'label-' + args.mode + '.log')
  59. def get_code():
  60. """Generate task_id"""
  61. return ''.join(random.sample(string.ascii_letters + string.digits, 8))
  62. class Upload(Upload_cfg):
  63. """Recieve and analyze the post request"""
  64. def POST(self):
  65. try:
  66. super().POST()
  67. x = web.data()
  68. x = json.loads(x.decode())
  69. type_ = x['annotateType']
  70. task_id = get_code()
  71. task_images = {}
  72. task_images[task_id] = {"input": {'type': type_, 'data': x}, "output": {"annotations": []}}
  73. print("Random_code:", task_id)
  74. label_log.info(task_id)
  75. label_log.info('web.t_queue length:%s' % web.t_queue.qsize())
  76. label_log.info('Recv task_images:%s' % task_images)
  77. web.t_queue.put(task_images)
  78. return {"code": 200, "msg": "", "data": task_id}
  79. except Exception as e:
  80. label_log.error("Error post")
  81. label_log.error(e)
  82. return 'post error'
  83. def bgProcess():
  84. """The implementation of automatic_label generating thread"""
  85. global taskQueue
  86. global label_url
  87. label_log.info('auto label server start'.center(66, '-'))
  88. label_log.info(label_url)
  89. while True:
  90. try:
  91. task_dict = taskQueue.get()
  92. for task_id in task_dict:
  93. id_list = []
  94. image_path_list = []
  95. type_ = task_dict[task_id]["input"]['type']
  96. for file in task_dict[task_id]["input"]['data']["files"]:
  97. id_list.append(file["id"])
  98. image_path_list.append(base_path + file["url"])
  99. label_list = task_dict[task_id]["input"]['data']["labels"]
  100. coco_flag = 0
  101. if "labelType" in task_dict[task_id]["input"]['data']:
  102. label_type = task_dict[task_id]["input"]['data']["labelType"]
  103. if label_type == 3:
  104. coco_flag = 80
  105. label_log.info(coco_flag)
  106. image_num = len(image_path_list)
  107. if image_num < 16:
  108. for i in range(16 - image_num):
  109. image_path_list.append(image_path_list[0])
  110. id_list.append(id_list[0])
  111. label_log.info(image_num)
  112. label_log.info(image_path_list)
  113. annotations = yolo_obj.yolo_inference(type_, id_list, image_path_list, label_list, coco_flag)
  114. annotations = annotations[0:image_num]
  115. result = {"annotations": annotations}
  116. label_log.info('Inference complete %s' % task_id)
  117. send_data = json.dumps(result).encode()
  118. task_url = label_url + task_id
  119. headers = {'Content-Type': 'application/json'}
  120. req = urllib.request.Request(task_url, headers=headers)
  121. response = urllib.request.urlopen(req, data=send_data, timeout=2)
  122. label_log.info(task_url)
  123. label_log.info(response.read())
  124. label_log.info("End automatic label")
  125. except Exception as e:
  126. label_log.error("Error bgProcess")
  127. label_log.error(e)
  128. label_log.info(label_url)
  129. time.sleep(0.01)
  130. def bg_thread(no, interval):
  131. """Running the automatic_label generating thread"""
  132. bgProcess()
  133. if __name__ == "__main__":
  134. yolo_obj = yolo_demo.YoloInference(label_log)
  135. _thread.start_new_thread(bg_thread, (5, 5))
  136. app = MyApplication(urls, globals())
  137. web.t_queue = taskQueue
  138. web.taskInImages = taskInImages
  139. app.run(port=port)

一站式算法开发平台、高性能分布式深度学习框架、先进算法模型库、视觉模型炼知平台、数据可视化分析平台等一系列平台及工具,在模型高效分布式训练、数据处理和可视分析、模型炼知和轻量化等技术上形成独特优势,目前已在产学研等各领域近千家单位及个人提供AI应用赋能

Contributors (1)