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.

imagenet_server.py 5.5 kB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  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 web
  22. import os
  23. import string
  24. import _thread
  25. import logging
  26. import urllib
  27. from queue import Queue
  28. import time
  29. import random
  30. import json
  31. import argparse
  32. import sys
  33. import codecs
  34. import of_cnn_resnet
  35. import numpy as np
  36. from log_config import setup_log
  37. from upload_config import Upload_cfg, MyApplication
  38. urls = ('/auto_annotate', 'Upload')
  39. sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
  40. label_url = "api/data/datasets/files/annotations/auto/"
  41. parser = argparse.ArgumentParser(description="config for imagenet label server")
  42. parser.add_argument("-p", "--port", type=int, required=True)
  43. parser.add_argument("-m", "--mode", type=str, default="test", required=False)
  44. args = parser.parse_args()
  45. url_json = './config/url.json'
  46. with open(url_json) as f:
  47. url_dict = json.loads(f.read())
  48. label_url = url_dict[args.mode] + label_url
  49. port = args.port
  50. taskQueue = Queue()
  51. taskInImages = {}
  52. base_path = "/nfs/"
  53. des_folder = os.path.join('./log', args.mode)
  54. if not os.path.exists(des_folder):
  55. os.makedirs(des_folder)
  56. logging = setup_log(args.mode, 'imagenet-' + args.mode + '.log')
  57. #############################label_server#####################################
  58. def get_code():
  59. return ''.join(random.sample(string.ascii_letters + string.digits, 8))
  60. def get_32code():
  61. return ''.join(random.sample(string.ascii_letters + string.digits, 32))
  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. if_imagenet = x['labelType']
  71. task_id = get_code()
  72. task_images = {}
  73. task_images[task_id] = {
  74. "input": {
  75. 'type': type_, 'data': x}, "output": {
  76. "annotations": []}, 'if_imagenet': if_imagenet}
  77. logging.info(task_id)
  78. web.t_queue.put(task_images)
  79. return {"code": 200, "msg": "", "data": task_id}
  80. except Exception as e:
  81. logging.error("Error post")
  82. logging.error(e)
  83. return 'post error'
  84. def imagenetProcess():
  85. """The implementation of imageNet auto labeling thread"""
  86. global taskQueue
  87. global label_url
  88. logging.info('ImageNet auto labeling server start'.center(66,'-'))
  89. logging.info(label_url)
  90. while True:
  91. try:
  92. task_dict = taskQueue.get()
  93. for task_id in task_dict:
  94. id_list = []
  95. image_path_list = []
  96. type_ = task_dict[task_id]["input"]['type']
  97. if_imagenet = task_dict[task_id]['if_imagenet']
  98. for file in task_dict[task_id]["input"]['data']["files"]:
  99. id_list.append(file["id"])
  100. image_path_list.append(base_path + file["url"])
  101. label_list = task_dict[task_id]["input"]['data']["labels"]
  102. image_num = len(image_path_list)
  103. logging.info(image_num)
  104. logging.info(image_path_list)
  105. annotations = []
  106. if if_imagenet == 2:
  107. for inds in range(len(image_path_list)):
  108. temp = {}
  109. temp['id'] = id_list[inds]
  110. score, ca_id = of_cnn_resnet.resnet_inf(
  111. image_path_list[inds])
  112. temp['annotation'] = [
  113. {'category_id': int(ca_id), 'score': np.float(score)}]
  114. temp['annotation'] = json.dumps(temp['annotation'])
  115. annotations.append(temp)
  116. result = {"annotations": annotations}
  117. logging.info(result)
  118. send_data = json.dumps(result).encode()
  119. task_url = label_url + task_id
  120. headers = {'Content-Type': 'application/json'}
  121. req = urllib.request.Request(task_url, headers=headers)
  122. response = urllib.request.urlopen(
  123. req, data=send_data, timeout=5)
  124. logging.info(task_url)
  125. logging.info(response.read())
  126. logging.info("End imagenet")
  127. except Exception as e:
  128. logging.error("Error imagenet_Process")
  129. logging.error(e)
  130. logging.info(label_url)
  131. time.sleep(0.01)
  132. def imagenet_thread(no, interval):
  133. """Running the imageNet auto labeling thread"""
  134. imagenetProcess()
  135. if __name__ == "__main__":
  136. of_cnn_resnet.init_resnet()
  137. _thread.start_new_thread(imagenet_thread, (5, 5))
  138. app = MyApplication(urls, globals())
  139. web.t_queue = taskQueue
  140. web.taskInImages = taskInImages
  141. app.run(port=port)

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

Contributors (1)