gen_gifs.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. from __future__ import annotations
  2. import os
  3. import re
  4. import gymnasium
  5. from PIL import Image
  6. from tqdm import tqdm
  7. # snake to camel case: https://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-snake-case # noqa: E501
  8. pattern = re.compile(r"(?<!^)(?=[A-Z])")
  9. # how many steps to record an env for
  10. LENGTH = 300
  11. output_dir = os.path.join(os.path.dirname(__file__), "..", "_static", "videos")
  12. os.makedirs(output_dir, exist_ok=True)
  13. # Some environments have multiple versions
  14. # For example, KeyCorridorEnv -> KeyCorridorS3R1, KeyCorridorS3R2, KeyCorridorS3R3, etc
  15. # We only want one as an example
  16. envs_completed = []
  17. # iterate through all envspecs
  18. for env_spec in tqdm(gymnasium.envs.registry.values()):
  19. # minigrid.envs:Env or minigrid.envs.babyai:Env
  20. if not isinstance(env_spec.entry_point, str):
  21. continue
  22. split = env_spec.entry_point.split(".")
  23. # ignore minigrid.envs.env_type:Env
  24. env_module = split[0]
  25. env_name = split[-1].split(":")[-1]
  26. env_type = env_module if len(split) == 2 else split[-1].split(":")[0]
  27. # Override env_name for WFC to include the preset name
  28. if env_name == "WFCEnv":
  29. env_name = env_spec.kwargs["wfc_config"]
  30. if env_module == "minigrid" and env_name not in envs_completed:
  31. os.makedirs(os.path.join(output_dir, env_type), exist_ok=True)
  32. path = os.path.join(output_dir, env_type, env_name + ".gif")
  33. envs_completed.append(env_name)
  34. # try catch in case missing some installs
  35. try:
  36. env = gymnasium.make(env_spec.id, render_mode="rgb_array")
  37. # the gymnasium needs to be rgb renderable
  38. if not ("rgb_array" in env.metadata["render_modes"]):
  39. continue
  40. # obtain and save LENGTH frames worth of steps
  41. frames = []
  42. t = 0
  43. while True:
  44. state, info = env.reset()
  45. terminated, truncated = False, False
  46. while not (terminated or truncated) and len(frames) <= LENGTH:
  47. frame = env.render()
  48. frames.append(Image.fromarray(frame))
  49. action = env.action_space.sample()
  50. # Avoid to much movement
  51. if t % 10 == 0:
  52. state_next, reward, terminated, truncated, info = env.step(
  53. action
  54. )
  55. t += 1
  56. if len(frames) > LENGTH:
  57. break
  58. env.close()
  59. frames[0].save(
  60. path,
  61. save_all=True,
  62. append_images=frames[1:],
  63. duration=50,
  64. loop=0,
  65. )
  66. print("Saved: " + env_name)
  67. except BaseException as e:
  68. print("ERROR", e)
  69. continue