PageRenderTime 40ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/ants/visualizer/visualize_locally.py

http://github.com/aichallenge/aichallenge
Python | 63 lines | 58 code | 4 blank | 1 comment | 1 complexity | b35c9cf069e084fa55e8f4699c5f7e2a MD5 | raw file
Possible License(s): Apache-2.0, BSD-3-Clause
  1. #!/usr/bin/env python
  2. import re
  3. import sys
  4. import os
  5. import webbrowser
  6. import json
  7. def generate(data, generated_path):
  8. path = os.path.dirname(__file__)
  9. template_path = os.path.join(path, 'replay.html.template')
  10. template = open(template_path, 'r')
  11. content = template.read()
  12. template.close()
  13. path1 = os.path.realpath(__file__)
  14. path2 = os.path.realpath(generated_path)
  15. common = os.path.commonprefix((path1, path2))
  16. path1 = path1[len(common):]
  17. path2 = path2[len(common):]
  18. mod_path = '/'.join(['..'] * (path2.count(os.sep)) + [os.path.split(path1)[0].replace('\\', '/')])
  19. if len(mod_path) > 0 and mod_path[-1] != '/':
  20. mod_path += '/'
  21. quote_re = re.compile("'")
  22. newline_re = re.compile("\s", re.MULTILINE)
  23. insert_re = re.compile(r"## REPLAY PLACEHOLDER ##")
  24. path_re = re.compile(r"## PATH PLACEHOLDER ##")
  25. try:
  26. json.loads(data)
  27. data = quote_re.sub(r"\\\\'", data)
  28. data = newline_re.sub("", data)
  29. except ValueError:
  30. data = data.replace('\n', '\\\\n')
  31. content = path_re.sub(mod_path, content)
  32. content = insert_re.sub(data, content)
  33. output = open(generated_path, 'w')
  34. output.write(content)
  35. output.close()
  36. def launch(filename=None, nolaunch=False, generated_path=None):
  37. if generated_path == None:
  38. generated_path = 'replay.html'
  39. if filename == None:
  40. data = sys.stdin.read()
  41. generated_path = os.path.realpath(os.path.join(os.path.dirname(__file__)
  42. , generated_path))
  43. else:
  44. with open(filename, 'r') as f:
  45. data = f.read()
  46. generated_path = os.path.join(os.path.split(filename)[0], generated_path)
  47. generate(data, generated_path)
  48. # open the page in the browser
  49. if not nolaunch:
  50. webbrowser.open('file://'+os.path.realpath(generated_path))
  51. if __name__ == "__main__":
  52. launch(nolaunch=len(sys.argv) > 1 and sys.argv[1] == '--nolaunch')