How to run OpenAI Gym .render() over a server

前端 未结 15 2191
囚心锁ツ
囚心锁ツ 2020-12-12 10:07

I am running a python 2.7 script on a p2.xlarge AWS server through Jupyter (Ubuntu 14.04). I would like to be able to render my simulations.

Minimal working example<

15条回答
  •  眼角桃花
    2020-12-12 11:06

    I think we should just capture renders as video by using OpenAI Gym wrappers.Monitor and then display it within the Notebook.

    Example:

    Dependencies

    !apt install python-opengl
    !apt install ffmpeg
    !apt install xvfb
    !pip3 install pyvirtualdisplay
    
    # Virtual display
    from pyvirtualdisplay import Display
    
    virtual_display = Display(visible=0, size=(1400, 900))
    virtual_display.start()
    

    Capture as video

    import gym
    from gym import wrappers
    
    env = gym.make("SpaceInvaders-v0")
    env = wrappers.Monitor(env, "/tmp/SpaceInvaders-v0")
    
    for episode in range(2):
        observation = env.reset()
        step = 0
        total_reward = 0
    
        while True:
            step += 1
            env.render()
            action = env.action_space.sample()
            observation, reward, done, info = env.step(action)
            total_reward += reward
            if done:
                print("Episode: {0},\tSteps: {1},\tscore: {2}"
                      .format(episode, step, total_reward)
                )
                break
    env.close()
    

    Display within Notebook

    import os
    import io
    import base64
    from IPython.display import display, HTML
    
    def ipython_show_video(path):
        """Show a video at `path` within IPython Notebook
        """
        if not os.path.isfile(path):
            raise NameError("Cannot access: {}".format(path))
    
        video = io.open(path, 'r+b').read()
        encoded = base64.b64encode(video)
    
        display(HTML(
            data="""
            
            """.format(encoded.decode('ascii'))
        ))
    
    ipython_show_video("/tmp/SpaceInvaders-v0/openaigym.video.4.10822.video000000.mp4")
    

    I hope it helps. ;)

提交回复
热议问题