docstr: Complete setup for `wandb.init()`.
  
  This includes parsing all arguments, applying them with settings and enabling logging.
docstr_tok: ["Complete","setup","for","`","wandb.init","(",")","`",".","This","includes","parsing","all","arguments",",","applying","them","with","settings","and","enabling","logging","."]
code: def setup(self, kwargs: Any) -> None:  # noqa: C901
      """Complete setup for `wandb.init()`.
  
      This includes parsing all arguments, applying them with settings and enabling logging.
      """
      self.kwargs = kwargs
  
      # if the user ran, for example, `wandb.login(`) before `wandb.init()`,
      # the singleton will already be set up and so if e.g. env vars are set
      # in between, they will be ignored, which we need to inform the user about.
      singleton = wandb_setup._WandbSetup._instance
      if singleton is not None:
          self._setup_printer(settings=singleton._settings)
          assert self.printer
          exclude_env_vars = {"WANDB_SERVICE", "WANDB_KUBEFLOW_URL"}
          # check if environment variables have changed
          singleton_env = {
              k: v
              for k, v in singleton._environ.items()
              if k.startswith("WANDB_") and k not in exclude_env_vars
          }
          os_env = {
              k: v
              for k, v in os.environ.items()
              if k.startswith("WANDB_") and k not in exclude_env_vars
          }
          if set(singleton_env.keys()) != set(os_env.keys()) or set(
              singleton_env.values()
          ) != set(os_env.values()):
              line = (
                  "Changes to your `wandb` environment variables will be ignored "
                  "because your `wandb` session has already started. "
                  "For more information on how to modify your settings with "
                  "`wandb.init()` arguments, please refer to "
                  f"{self.printer.link(wburls.get('wandb_init'), 'the W&B docs')}."
              )
              self.printer.display(line, level="warn")
  
      # we add this logic to be backward compatible with the old behavior of disable
      # where it would disable the service if the mode was set to disabled
      mode = kwargs.get("mode")
      settings_mode = (kwargs.get("settings") or {}).get("mode")
      _disable_service = (
          mode == "disabled" or settings_mode == "disabled"
      )
      setup_settings = {"_disable_service": _disable_service}
  
      self._wl = wandb_setup.setup(settings=setup_settings)
      # Make sure we have a logger setup (might be an early logger)
      assert self._wl is not None
      _set_logger(self._wl._get_logger())
  
      # Start with settings from wandb library singleton
      settings: Settings = self._wl.settings.copy()
  
      # when using launch, we don't want to reuse the same run id from the singleton
      # since users might launch multiple runs in the same process
      # TODO(kdg): allow users to control this via launch settings
      if settings.launch and singleton is not None:
          settings.update({"run_id": None}, source=Source.INIT)
  
      settings_param = kwargs.pop("settings", None)
      if settings_param is not None and isinstance(
          settings_param, (Settings, dict)
      ):
          settings.update(settings_param, source=Source.INIT)
  
      self._setup_printer(settings)
      self._reporter = reporting.setup_reporter(settings=settings)
  
      sagemaker_config: Dict = (
          dict()
          if settings.sagemaker_disable
          else sagemaker.parse_sm_config()
      )
      if sagemaker_config:
          sagemaker_api_key = sagemaker_config.get(
              "wandb_api_key", None
          )
          sagemaker_run, sagemaker_env = sagemaker.parse_sm_resources()
          if sagemaker_env:
              if sagemaker_api_key:
                  sagemaker_env["WANDB_API_KEY"] = sagemaker_api_key
              settings._apply_env_vars(sagemaker_env)
              wandb.setup(settings=settings)
          settings.update(sagemaker_run, source=Source.SETUP)
          with telemetry.context(obj=self._init_telemetry_obj) as tel:
              tel.feature.sagemaker = True
  
      with telemetry.context(obj=self._init_telemetry_obj) as tel:
          if kwargs.get("config"):
              tel.feature.set_init_config = True
          if kwargs.get("name"):
              tel.feature.set_init_name = True
          if kwargs.get("id"):
              tel.feature.set_init_id = True
          if kwargs.get("tags"):
              tel.feature.set_init_tags = True
  
      # Remove parameters that are not part of settings
      init_config = kwargs.pop("config", None) or dict()
  
      # todo: remove this once officially deprecated
      deprecated_kwargs = {
          "config_include_keys": (
              "Use `config=wandb.helper.parse_config(config_object, include=('key',))` instead."
          ),
          "config_exclude_keys": (
              "Use `config=wandb.helper.parse_config(config_object, exclude=('key',))` instead."
          ),
      }
      for deprecated_kwarg, msg in deprecated_kwargs.items():
          if kwargs.get(deprecated_kwarg):
              self.deprecated_features_used[deprecated_kwarg] = msg
  
      init_config = parse_config(
          init_config,
          include=kwargs.pop("config_include_keys", None),
          exclude=kwargs.pop("config_exclude_keys", None),
      )
  
      # merge config with sweep or sagemaker (or config file)
      self.sweep_config = dict()
      sweep_config = self._wl._sweep_config or dict()
      self.config = dict()
      self.init_artifact_config: Dict[str, Any] = dict()
      for config_data in (
          sagemaker_config,
          self._wl._config,
          init_config,
      ):
          if not config_data:
              continue
          # split out artifacts, since when inserted into
          # config they will trigger use_artifact
          # but the run is not yet upserted
          self._split_artifacts_from_config(config_data, self.config)
  
      if sweep_config:
          self._split_artifacts_from_config(
              sweep_config, self.sweep_config
          )
  
      monitor_gym = kwargs.pop("monitor_gym", None)
      if monitor_gym and len(wandb.patched["gym"]) == 0:
          wandb.gym.monitor()
  
      if wandb.patched["tensorboard"]:
          with telemetry.context(obj=self._init_telemetry_obj) as tel:
              tel.feature.tensorboard_patch = True
  
      tensorboard = kwargs.pop("tensorboard", None)
      sync_tensorboard = kwargs.pop("sync_tensorboard", None)
      if (
          tensorboard
          or sync_tensorboard
          and len(wandb.patched["tensorboard"]) == 0
      ):
          wandb.tensorboard.patch()
          with telemetry.context(obj=self._init_telemetry_obj) as tel:
              tel.feature.tensorboard_sync = True
  
      magic = kwargs.get("magic")
      if magic not in (None, False):
          magic_install(kwargs)
  
      # handle login related parameters as these are applied to global state
      init_settings = {
          key: kwargs[key]
          for key in ["anonymous", "force", "mode", "resume"]
          if kwargs.get(key) is not None
      }
      if init_settings:
          settings.update(init_settings, source=Source.INIT)
  
      if not settings._offline and not settings._noop:
          wandb_login._login(
              anonymous=kwargs.pop("anonymous", None),
              force=kwargs.pop("force", None),
              _disable_warning=True,
              _silent=settings.quiet or settings.silent,
              _entity=kwargs.get("entity") or settings.entity,
          )
  
      # apply updated global state after login was handled
      wl = wandb.setup()
      assert wl is not None
      settings._apply_settings(wl.settings)
  
      # get status of code saving before applying user settings
      save_code_pre_user_settings = settings.save_code
  
      settings._apply_init(kwargs)
      if not settings._offline and not settings._noop:
          user_settings = self._wl._load_user_settings()
          settings._apply_user(user_settings)
  
      # ensure that user settings don't set saving to true
      # if user explicitly set these to false in UI
      if save_code_pre_user_settings is False:
          settings.update({"save_code": False}, source=Source.INIT)
  
      # TODO(jhr): should this be moved? probably.
      settings._set_run_start_time(source=Source.INIT)
  
      if not settings._noop:
          self._log_setup(settings)
  
          if settings._jupyter:
              self._jupyter_setup(settings)
      launch_config = _handle_launch_config(settings)
      if launch_config:
          self._split_artifacts_from_config(
              launch_config, self.launch_config
          )
  
      self.settings = settings
  
imports: import copy
  import json
  import logging
  import os
  import platform
  import sys
  import tempfile
  import traceback
  from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Union
  import wandb
  import wandb.env
  from wandb import trigger
  from wandb.errors import CommError, Error, UsageError
  from wandb.errors.util import ProtobufErrorHandler
  from wandb.integration import sagemaker
  from wandb.integration.magic import magic_install
  from wandb.sdk.lib import runid
  from wandb.sdk.lib.paths import StrPath
  from wandb.util import _is_artifact_representation
  from .None import wandb_login, wandb_setup
  from .backend.backend import Backend
  from .lib import RunDisabled, SummaryDisabled, filesystem, ipython, module, reporting, telemetry
  from .lib.deprecate import Deprecated, deprecate
  from .lib.mailbox import Mailbox, MailboxProgress
  from .lib.printer import Printer, get_printer
  from .lib.wburls import wburls
  from .wandb_helper import parse_config
  from .wandb_run import Run, TeardownHook, TeardownStage
  from .wandb_settings import Settings, Source
label_desc: Use image node_id 3 for calling the _WandbInit obj's underlying member method code with example usage: obj.setup(kwargs) without return types