Record a single movie and store it on hard drive

def record_take(self, model, env_instance, device, take_number):
        """ Record a single movie and store it on hard drive """
        frames = []

        observation = env_instance.reset()

        if model.is_recurrent:
            hidden_state = model.zero_state(1).to(device)

        frames.append(env_instance.render('rgb_array'))

        print("Evaluating environment...")

        while True:
            observation_array = np.expand_dims(np.array(observation), axis=0)
            observation_tensor = torch.from_numpy(observation_array).to(device)

            if model.is_recurrent:
                output = model.step(observation_tensor, hidden_state, **self.sample_args)
                hidden_state = output['state']
                actions = output['actions']
            else:
                actions = model.step(observation_tensor, **self.sample_args)['actions']

            actions = actions.detach().cpu().numpy()

            observation, reward, done, epinfo = env_instance.step(actions[0])

            frames.append(env_instance.render('rgb_array'))

            if 'episode' in epinfo:
                # End of an episode
                break

        takename = self.model_config.output_dir('videos', self.model_config.run_name, self.videoname.format(take_number))
        pathlib.Path(os.path.dirname(takename)).mkdir(parents=True, exist_ok=True)

        fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')
        video = cv2.VideoWriter(takename, fourcc, self.fps, (frames[0].shape[1], frames[0].shape[0]))

        for i in tqdm.trange(len(frames), file=sys.stdout):
            video.write(cv2.cvtColor(frames[i], cv2.COLOR_RGB2BGR))

        video.release()
        print("Written {}".format(takename))