# Buggy code
def notebook_metadata():
    """Attempts to query jupyter for the path and name of the notebook file"""
    error_message = "Failed to query for notebook name, you can set it manually with the WANDB_NOTEBOOK_NAME environment variable"
    try:
        import ipykernel
        from notebook.notebookapp import list_running_servers

        kernel_id = re.search(
            "kernel-(.*).json", ipykernel.connect.get_connection_file()
        ).group(1)
        servers = list(
            list_running_servers()
        )  # TODO: sometimes there are invalid JSON files and this blows up
    except Exception:
        logger.error(error_message)
        return {}
    for s in servers:
        try:
            if s["password"]:
                raise ValueError("Can't query password protected kernel")
            res = requests.get(
                urljoin(s["url"], "api/sessions"), params={"token": s.get("token", "")}
            ).json()
        except (requests.RequestException, ValueError):
            logger.error(error_message)
            return {}
        for nn in res:
            # TODO: wandb/client#400 found a case where res returned an array of strings...
            if isinstance(nn, dict) and nn.get("kernel"):
                if nn["kernel"]["id"] == kernel_id:
                    return {
                        "root": s["notebook_dir"],
                        "path": nn["notebook"]["path"],
                        "name": nn["notebook"]["name"],
                    }
    return {}


# Traceback (AttributeError)
AttributeError                            Traceback (most recent call last)
C:\Python37\lib\site-packages\wandb\meta.py in setup(self)
46             import __main__
---> 47             self.data["program"] = __main__.__file__
48         except (ImportError, AttributeError):

AttributeError: module '__main__' has no attribute '__file__'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
in
1 import wandb
2 from wandb.keras import WandbCallback
----> 3 wandb.init(project="my_project_name")

C:\Python37\lib\site-packages\wandb\__init__.py in init(job_type, dir, config, project, entity, reinit, tags, group, allow_val_change, resume, force, tensorboard, sync_tensorboard, monitor_gym, name, notes, id, magic, anonymous)
1068         allow_val_change = True
1069     if config or telemetry_updated:
-> 1070         run.config._update(config, allow_val_change=allow_val_change, as_defaults=not allow_val_change)
1071
1072     # Access history to ensure resumed is set when resuming

C:\Python37\lib\site-packages\wandb\wandb_config.py in _update(self, params, allow_val_change, as_defaults)
276                 continue
277             self._items[key] = val
--> 278         self.persist()
279
280     def update(self, params, allow_val_change=False):

C:\Python37\lib\site-packages\wandb\wandb_config.py in persist(self)
194             conf_file.write(str(self))
195         if wandb.run and wandb.run._jupyter_agent:
--> 196             wandb.run._jupyter_agent.start()
197
198     def get(self, *args):

C:\Python37\lib\site-packages\wandb\jupyter.py in start(self)
120     def start(self):
121         if self.paused:
--> 122             self.rm = RunManager(wandb.run, output=False, cloud=wandb.run.mode != "dryrun")
123             wandb.run.api._file_stream_api = None
124             self.rm.mirror_stdout_stderr()

C:\Python37\lib\site-packages\wandb\run_manager.py in __init__(self, run, project, tags, cloud, output, port)
504         # Calling .start() on _meta and _system_stats will spin a thread that reports system stats every 30 seconds
505         self._system_stats = stats.SystemStats(run, self._api)
--> 506         self._meta = meta.Meta(self._api, self._run.dir)
507         self._meta.data["jobType"] = self._run.job_type
508         self._meta.data["mode"] = self._run.mode

C:\Python37\lib\site-packages\wandb\meta.py in __init__(self, api, out_dir)
34             self.data = {}
35         self.lock = threading.Lock()
---> 36         self.setup()
37         self._thread = threading.Thread(target=self._thread_body)
38         self._thread.daemon = True

C:\Python37\lib\site-packages\wandb\meta.py in setup(self)
52                     self.data["program"] = os.getenv(env.NOTEBOOK_NAME)
53                 else:
---> 54                     meta = wandb.jupyter.notebook_metadata()
55                     if meta.get("path"):
56                         if "fileId=" in meta["path"]:

C:\Python37\lib\site-packages\wandb\jupyter.py in notebook_metadata()
108             if isinstance(nn, dict) and nn.get("kernel"):
109                 if nn['kernel']['id'] == kernel_id:
--> 110                     return {"root": s['notebook_dir'], "path": nn['notebook']['path'], "name": nn['notebook']['name']}
111     return {}
112

KeyError: 'notebook'

# Fixed code
def notebook_metadata():
    """Attempts to query jupyter for the path and name of the notebook file"""
    error_message = "Failed to query for notebook name, you can set it manually with the WANDB_NOTEBOOK_NAME environment variable"
    try:
        import ipykernel
        from notebook.notebookapp import list_running_servers

        kernel_id = re.search(
            "kernel-(.*).json", ipykernel.connect.get_connection_file()
        ).group(1)
        servers = list(
            list_running_servers()
        )  # TODO: sometimes there are invalid JSON files and this blows up
    except Exception:
        logger.error(error_message)
        return {}
    for s in servers:
        try:
            if s["password"]:
                raise ValueError("Can't query password protected kernel")
            res = requests.get(
                urljoin(s["url"], "api/sessions"), params={"token": s.get("token", "")}
            ).json()
        except (requests.RequestException, ValueError):
            logger.error(error_message)
            return {}
        for nn in res:
            # TODO: wandb/client#400 found a case where res returned an array of strings...
            if isinstance(nn, dict) and nn.get("kernel") and "notebook" in nn:
                if nn["kernel"]["id"] == kernel_id:
                    return {
                        "root": s["notebook_dir"],
                        "path": nn["notebook"]["path"],
                        "name": nn["notebook"]["name"],
                    }
    return {}