on_docker.py 2.2 KB

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