Repository: wandb/wandb

Issue:
[CLI]: wandb gym monitor gets called when wandb.init is not
### Describe the bug

<!--- Description of the issue below  -->
 Hi, 

I am using wand in jupter notebook to track a couple of parameters and also monitor an RL agents interation with the gym env during training. To monitor the gym I set ```monitor_gym``` parameter of ```wandb.init()``` to ```True```. 

Now an Error is raised when the notebook is run in the following sequence:
1. Run the notebook in github gist with ```track``` set to ```True```
2. Re-run the notebook with ```track``` set to ```False``` leads to the following error


<!--- A minimal code snippet between the quotes below  -->
Below I have linked the GitHub Gist of the minimal ipynb and the conda env file :
* [python noteboook Gist](https://gist.github.com/jpatra72/200664c87f4ae8ed244ccea1f57241d6)
* [conda env](https://gist.github.com/jpatra72/6d21488e397ad838568d5111ccae8563)

<!--- A full traceback of the exception in the quotes below -->
```shell
---------------------------------------------------------------------------
Error                                     Traceback (most recent call last)
Cell In[5], line 20
     18 for _ in range(1000):
     19     action = np.random.randint(2, size=1)
---> 20     obs, _, _, _ = env.step(action[0])
     22 if wandb.run is not None:
     23     wandb.finish(quiet=True)

File ~/opt/anaconda3/envs/wandb_issue/lib/python3.10/site-packages/gym/wrappers/record_video.py:105, in RecordVideo.step(self, action)
    103 if not self.is_vector_env:
    104     if dones:
--> 105         self.close_video_recorder()
    106 elif dones[0]:
    107     self.close_video_recorder()

File ~/opt/anaconda3/envs/wandb_issue/lib/python3.10/site-packages/gym/wrappers/record_video.py:116, in RecordVideo.close_video_recorder(self)
    114 def close_video_recorder(self) -> None:
    115     if self.recording:
--> 116         self.video_recorder.close()
    117     self.recording = False
    118     self.recorded_frames = 1

File ~/opt/anaconda3/envs/wandb_issue/lib/python3.10/site-packages/gym/wrappers/monitoring/video_recorder.py:185, in VideoRecorder.close(self)
    183 if self.encoder:
    184     logger.debug("Closing video encoder: path=%s", self.path)
--> 185     self.encoder.close()
    186     self.encoder = None
    187 else:
    188     # No frames captured. Set metadata, and remove the empty output file.

File ~/opt/anaconda3/envs/wandb_issue/lib/python3.10/site-packages/wandb/integration/gym/__init__.py:40, in monitor.<locals>.close(self)
     38 else:
     39     key = "videos"
---> 40 wandb.log({key: wandb.Video(getattr(self, path))})

File ~/opt/anaconda3/envs/wandb_issue/lib/python3.10/site-packages/wandb/sdk/lib/preinit.py:36, in PreInitCallable.<locals>.preinit_wrapper(*args, **kwargs)
     35 def preinit_wrapper(*args: Any, **kwargs: Any) -> Any:
---> 36     raise wandb.Error(f"You must call wandb.init() before {name}()")

Error: You must call wandb.init() before wandb.log()
```


### Additional Files

_No response_

### Environment

WandB version: 0.13.7

OS: macOS v12.6.1

Python version:3.10.8

Versions of relevant libraries: [ref conda env](https://gist.github.com/jpatra72/6d21488e397ad838568d5111ccae8563)


### Additional Context

_No response_


Discussion:
Hi @jpatra72, can you see if `wandb.run` is `None` when you start the second run? I think gym still thinks the run persists so it's trying to log to it. 

Thank you,
Nate
Hi @nate-wandb, ```wand.run``` is ```None``` at the start of the second run.  

Edit: I also thought that the cause of the issue maybe because the patch applied to ```gym.wrappers.monitoring.video_recorder.close()``` by ```wandb.gym.monitor()``` still remains after the end of first run. 
WandB Internal User commented: 
jpatra72 commented: 
Hi @nate-wandb, ```wand.run``` is ```None``` at the start of the second run.

hey @nate-wandb, were you able to have a look at the issue yet?

Hi @jpatra72, sorry for the delay on this. I was able to replicate the issue in Colab and I would agree that this is not expected behavior. I'm not sure the exact issue but I can pass this onto our engineering team to investigate and let you know once they have a chance to look into this. 

Thank you,
Nate
One workaround you could use in the meantime is adding the following to disable `wandb` if you do not wish to track the run:
```
if track:
    wandb.init(
        project="wandb_monitor_gym_issue",
        name=run_name,
        monitor_gym=True,
    )
else:
    wandb.init(mode="disabled")    
```
I just tested this and it no longer causes the script to crash. 
WandB Internal User commented: 
nate-wandb commented: 
One workaround you could use in the meantime is adding the following to disable `wandb` if you do not wish to track the run:
```
if track:
    wandb.init(
        project="wandb_monitor_gym_issue",
        name=run_name,
        monitor_gym=True,
    )
else:
    wandb.init(mode="disabled")    
    
    ```
    I just tested this and it no longer causes the script to crash.


Resolving patch:
diff --git a/wandb/integration/gym/__init__.py b/wandb/integration/gym/__init__.py
--- a/wandb/integration/gym/__init__.py
+++ b/wandb/integration/gym/__init__.py
@@ -65,12 +65,10 @@ def close(self):
         recorder.orig_close(self)
         if not self.enabled:
             return
-        m = re.match(r".+(video\.\d+).+", getattr(self, path))
-        if m:
-            key = m.group(1)
-        else:
-            key = "videos"
-        wandb.log({key: wandb.Video(getattr(self, path))})
+        if wandb.run:
+            m = re.match(r".+(video\.\d+).+", getattr(self, path))
+            key = m.group(1) if m else "videos"
+            wandb.log({key: wandb.Video(getattr(self, path))})
 
     def del_(self):
         self.orig_close()


Test patch: