on_docker.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #!/usr/bin/env python
  2. import argparse
  3. import distutils.spawn
  4. import json
  5. import os
  6. import os.path as osp
  7. import platform
  8. import shlex
  9. import subprocess
  10. import sys
  11. from labelme.logger import logger
  12. def get_ip():
  13. dist = platform.platform().split('-')[0]
  14. if dist == 'Linux':
  15. return ''
  16. elif dist == 'Darwin':
  17. cmd = 'ifconfig en0'
  18. output = subprocess.check_output(shlex.split(cmd))
  19. if str != bytes: # Python3
  20. output = output.decode('utf-8')
  21. for row in output.splitlines():
  22. cols = row.strip().split(' ')
  23. if cols[0] == 'inet':
  24. ip = cols[1]
  25. return ip
  26. else:
  27. raise RuntimeError('No ip is found.')
  28. else:
  29. raise RuntimeError('Unsupported platform.')
  30. def labelme_on_docker(in_file, out_file):
  31. ip = get_ip()
  32. cmd = 'xhost + %s' % ip
  33. subprocess.check_output(shlex.split(cmd))
  34. if out_file:
  35. out_file = osp.abspath(out_file)
  36. if osp.exists(out_file):
  37. raise RuntimeError('File exists: %s' % out_file)
  38. else:
  39. open(osp.abspath(out_file), 'w')
  40. cmd = 'docker run -it --rm' \
  41. ' -e DISPLAY={0}:0' \
  42. ' -e QT_X11_NO_MITSHM=1' \
  43. ' -v /tmp/.X11-unix:/tmp/.X11-unix' \
  44. ' -v {1}:{2}' \
  45. ' -w /home/developer'
  46. in_file_a = osp.abspath(in_file)
  47. in_file_b = osp.join('/home/developer', osp.basename(in_file))
  48. cmd = cmd.format(
  49. ip,
  50. in_file_a,
  51. in_file_b,
  52. )
  53. if out_file:
  54. out_file_a = osp.abspath(out_file)
  55. out_file_b = osp.join('/home/developer', osp.basename(out_file))
  56. cmd += ' -v {0}:{1}'.format(out_file_a, out_file_b)
  57. cmd += ' wkentaro/labelme labelme {0}'.format(in_file_b)
  58. if out_file:
  59. cmd += ' -O {0}'.format(out_file_b)
  60. subprocess.call(shlex.split(cmd))
  61. if out_file:
  62. try:
  63. json.load(open(out_file))
  64. return out_file
  65. except Exception:
  66. if open(out_file).read() == '':
  67. os.remove(out_file)
  68. raise RuntimeError('Annotation is cancelled.')
  69. def main():
  70. parser = argparse.ArgumentParser()
  71. parser.add_argument('in_file', help='Input file or directory.')
  72. parser.add_argument('-O', '--output')
  73. args = parser.parse_args()
  74. if not distutils.spawn.find_executable('docker'):
  75. logger.error('Please install docker.')
  76. sys.exit(1)
  77. try:
  78. out_file = labelme_on_docker(args.in_file, args.output)
  79. if out_file:
  80. print('Saved to: %s' % out_file)
  81. except RuntimeError as e:
  82. sys.stderr.write(e.__str__() + '\n')
  83. sys.exit(1)
  84. if __name__ == '__main__':
  85. main()