gen_gifs.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. split = env_spec.entry_point.split(".")
  21. # ignore minigrid.envs.env_type:Env
  22. env_module = split[0]
  23. env_name = split[-1].split(":")[-1]
  24. env_type = env_module if len(split) == 2 else split[-1].split(":")[0]
  25. if env_module == "minigrid" and env_name not in envs_completed:
  26. os.makedirs(os.path.join(output_dir, env_type), exist_ok=True)
  27. path = os.path.join(output_dir, env_type, env_name + ".gif")
  28. envs_completed.append(env_name)
  29. # try catch in case missing some installs
  30. try:
  31. env = gymnasium.make(env_spec.id, render_mode="rgb_array")
  32. # the gymnasium needs to be rgb renderable
  33. if not ("rgb_array" in env.metadata["render_modes"]):
  34. continue
  35. # obtain and save LENGTH frames worth of steps
  36. frames = []
  37. t = 0
  38. while True:
  39. state, info = env.reset()
  40. terminated, truncated = False, False
  41. while not (terminated or truncated) and len(frames) <= LENGTH:
  42. frame = env.render()
  43. frames.append(Image.fromarray(frame))
  44. action = env.action_space.sample()
  45. # Avoid to much movement
  46. if t % 10 == 0:
  47. state_next, reward, terminated, truncated, info = env.step(
  48. action
  49. )
  50. t += 1
  51. if len(frames) > LENGTH:
  52. break
  53. env.close()
  54. frames[0].save(
  55. path,
  56. save_all=True,
  57. append_images=frames[1:],
  58. duration=50,
  59. loop=0,
  60. )
  61. print("Saved: " + env_name)
  62. except BaseException as e:
  63. print("ERROR", e)
  64. continue