code: def _tree_map(
      func: Callable,
      x: Union[Any, collections.Sequence, collections.Mapping],
      key: Optional[Union[int, str]] = None,
  ) -> Union[Any, collections.Sequence, collections.Mapping]:
      if isinstance(x, collections.Mapping):
          return cast(Callable, type(x))(
              {
                  k: _tree_map(func, sample, key=k)
                  for k, sample in x.items()
              }
          )
      if isinstance(x, tuple) and hasattr(x, "_fields"):  # namedtuple
          return cast(Callable, type(x))(
              *(_tree_map(func, sample) for sample in x)
          )
      if isinstance(x, collections.Sequence):
          return cast(Callable, type(x))(
              [
                  _tree_map(func, sample, key=i)
                  for i, sample in enumerate(x)
              ]
          )
      return func(x, key=key)
  
imports: import collections.abc
  import functools
  import hashlib
  import logging
  import random
  import shutil
  import warnings
  from pathlib import Path
  from typing import Any, Callable, cast, Dict, List, Optional, TextIO, Tuple, Type, TypeVar, Union
  import torch
label_desc: Use image node_id 4 for calling a global function with example usage: _tree_map(func, x, key) and returns: func, cast, cast, cast