Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(integrations): update gym integration to match last version #4571

Merged
merged 7 commits into from
Dec 5, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
42 changes: 35 additions & 7 deletions wandb/integration/gym/__init__.py
@@ -1,25 +1,53 @@
import re
from typing import Optional

import wandb

_gym_version_lt_0_26: Optional[bool] = None


def monitor():
vcr = wandb.util.get_module(
"gym.wrappers.monitoring.video_recorder",
required="Couldn't import the gym python package, install with pip install gym",
required="Couldn't import the gym python package, install with `pip install gym`",
)
vcr.ImageEncoder.orig_close = vcr.ImageEncoder.close

global _gym_version_lt_0_26

if _gym_version_lt_0_26 is None:
import gym # type: ignore
from pkg_resources import parse_version

if parse_version(gym.__version__) < parse_version("0.26.0"):
_gym_version_lt_0_26 = True
else:
_gym_version_lt_0_26 = False

# breaking change in gym 0.26.0
vcr_recorder_attribute = "ImageEncoder" if _gym_version_lt_0_26 else "VideoRecorder"
recorder = getattr(vcr, vcr_recorder_attribute)
path = "output_path" if _gym_version_lt_0_26 else "path"

recorder.orig_close = recorder.close

def close(self):
vcr.ImageEncoder.orig_close(self)
m = re.match(r".+(video\.\d+).+", self.output_path)
recorder.orig_close(self)
m = re.match(r".+(video\.\d+).+", getattr(self, path))
if m:
key = m.group(1)
else:
key = "videos"
wandb.log({key: wandb.Video(self.output_path)})
wandb.log({key: wandb.Video(getattr(self, path))})

def del_(self):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's verify this del_ behavior. other than that looks great!

self.orig_close()

vcr.ImageEncoder.close = close
if not _gym_version_lt_0_26:
recorder.__del__ = del_
recorder.close = close
wandb.patched["gym"].append(
["gym.wrappers.monitoring.video_recorder.ImageEncoder", "close"]
[
f"gym.wrappers.monitoring.video_recorder.{vcr_recorder_attribute}",
"close",
]
)