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.

ofrecord_server.py 6.4 kB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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 shutil
  27. import sys
  28. import time
  29. import urllib
  30. from queue import Queue
  31. import web
  32. from upload_config import Upload_cfg, MyApplication
  33. import gen_ofrecord as ofrecord
  34. from log_config import setup_log
  35. urls = ('/gen_ofrecord', 'Ofrecord')
  36. sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
  37. parser = argparse.ArgumentParser(description="config for label server")
  38. parser.add_argument("-p", "--port", type=int, required=True)
  39. parser.add_argument("-m", "--mode", type=str, default="test", required=False)
  40. args = parser.parse_args()
  41. base_path = "/nfs/"
  42. record_url = 'api/data/datasets/versions/'
  43. url_json = './config/url.json'
  44. with open(url_json) as f:
  45. url_dict = json.loads(f.read())
  46. record_url = url_dict[args.mode] + record_url
  47. port = args.port
  48. of_que = Queue()
  49. of_cond = []
  50. des_folder = os.path.join('./log', args.mode)
  51. if not os.path.exists(des_folder):
  52. os.makedirs(des_folder)
  53. of_log = setup_log(args.mode, 'ofrecord-' + args.mode + '.log')
  54. class Ofrecord(Upload_cfg):
  55. """Recieve and analyze the post request"""
  56. def POST(self):
  57. try:
  58. super().POST()
  59. x = web.data()
  60. x = json.loads(x.decode())
  61. print(x)
  62. dataset_version_id = x['id']
  63. label_map = x['datasetLabels']
  64. if dataset_version_id not in web.of_cond:
  65. web.of_cond.append(dataset_version_id)
  66. src_path = base_path + x['datasetPath']
  67. save_path = base_path + x['datasetPath'] + '/ofrecord'
  68. # transform the windows path to linux path
  69. src_path = '/'.join(src_path.split('\\'))
  70. save_path = '/'.join(save_path.split('\\'))
  71. of_config = [dataset_version_id, src_path, save_path,label_map]
  72. of_log.info('Recv of_config:%s' % of_config)
  73. web.t_queue1.put(of_config)
  74. else:
  75. pass
  76. return {"code": 200, "msg": "", "data": dataset_version_id}
  77. except Exception as e:
  78. of_log.error("Error post")
  79. of_log.error(e)
  80. return 'post error'
  81. def gen_ofrecord_thread():
  82. """The implementation of ofRecord generating thread"""
  83. global record_url
  84. global of_que
  85. of_log.info('ofrecord server start'.center(66, '-'))
  86. of_log.info(record_url)
  87. while True:
  88. try:
  89. of_task = of_que.get()
  90. debug_msg = '-------- OfRecord gen start: %s --------' % of_task[0] if of_task else ''
  91. of_log.info(debug_msg)
  92. if not of_task:
  93. continue
  94. dataset_version_id = of_task[0]
  95. src_path = of_task[1]
  96. save_path = of_task[2]
  97. label_map = of_task[3]
  98. of_log.info('[%s] not in of_cond' % dataset_version_id)
  99. if os.path.exists(save_path):
  100. shutil.rmtree(save_path)
  101. os.makedirs(save_path)
  102. task_url = record_url + str(dataset_version_id) + '/convert/finish'
  103. of_log.info('key: label, type: int32')
  104. of_log.info('key: img_raw, type: bytes')
  105. desc = os.path.join(save_path, 'train')
  106. of_log.info('desc: %s' % desc)
  107. try:
  108. con, num_images, num_part = ofrecord.read_data_sets(
  109. src_path, desc,label_map)
  110. except Exception as e:
  111. error_msg = 'Error happened in ofrecord.read_data_sets'
  112. of_log.error(error_msg)
  113. if of_task[0] in web.of_cond:
  114. web.of_cond.remove(of_task[0])
  115. # send messages to DataManage
  116. url_dbg = 'Request to [%s]' % task_url
  117. of_log.info(url_dbg)
  118. headers = {'Content-Type': 'application/json'}
  119. req_body = bytes(json.dumps({'msg': str(e)}), 'utf8')
  120. req = urllib.request.Request(
  121. task_url, data=req_body, headers=headers)
  122. response = urllib.request.urlopen(req, timeout=5)
  123. debug_msg = "response.read(): %s; ret_code: %s" % (
  124. response.read(), response.getcode())
  125. of_log.info(debug_msg)
  126. raise e
  127. if not con:
  128. error_msg = 'No annotated images, No ofrecord will be created'
  129. of_log.warning(error_msg)
  130. of_log.info(
  131. 'train: {} images in {} part files.\n'.format(
  132. num_images, num_part))
  133. of_log.info('generate ofrecord file done')
  134. url_dbg = 'Request to [%s]' % task_url
  135. of_log.info(url_dbg)
  136. headers = {'Content-Type': 'application/json'}
  137. req_body = {'msg': 'ok'}
  138. req = urllib.request.Request(
  139. task_url, data=json.dumps(req_body).encode(), headers=headers)
  140. response = urllib.request.urlopen(req, timeout=5)
  141. debug_msg = "response.read(): %s; ret_code: %s" % (
  142. response.read(), response.getcode())
  143. of_log.info(debug_msg)
  144. web.of_cond.remove(of_task[0])
  145. except Exception as e:
  146. of_log.error("Error ofProcess")
  147. of_log.error(e)
  148. of_log.info(record_url)
  149. debug_msg = '-------- OfRecord gen end --------'
  150. of_log.info(debug_msg)
  151. time.sleep(0.01)
  152. def of_thread(no, interval):
  153. """Running the ofRecord generating thread"""
  154. gen_ofrecord_thread()
  155. if __name__ == "__main__":
  156. _thread.start_new_thread(of_thread, (5, 5))
  157. app = MyApplication(urls, globals())
  158. web.of_cond = of_cond
  159. web.t_queue1 = of_que
  160. app.run(port=port)

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

Contributors (1)