
      i2                        d dl Z d dlZd dlmZ d dlmZmZ d dlmZm	Z	 d dl
mZmZmZ d dlmZ d dlmZ deeeeef   ef      d	eeef   fd
Zdeeef   d	eeef   fdZddeeef   deded	eeef   fdZdeeef   d	eeef   fdZdeeef   d	eeef   fdZded	efdZdeeeeef   f   deded	eeeeef   f   fdZy)    N)	Namespace)MappingMutableMapping)asdictis_dataclass)AnyOptionalUnion)Tensor)_NUMPY_AVAILABLEparamsreturnc                 D    t        | t              rt        |       } | i } | S )zEnsure parameters are a dict or convert to dict if necessary.

    Args:
        params: Target to be converted to a dictionary

    Returns:
        params as a dictionary

    )
isinstancer   vars)r   s    v/Volumes/fast/ai/experiments/voice-extract-mac/.venv/lib/python3.12/site-packages/lightning_fabric/utilities/logger.py_convert_paramsr      s&     &)$f~M    c                     dt         dt         fd}| j                         D ci c]  \  }}| ||       c}}S c c}}w )zSanitize callable params dict, e.g. ``{'a': <function_**** at 0x****>} -> {'a': 'function_****'}``.

    Args:
        params: Dictionary containing the hyperparameters

    Returns:
        dictionary with all callables sanitized

    valr   c                     t        j                  |       r| j                  S t        |       r!	  |        }t        |      r| j                  S |S | S # t        $ r t        | dd       cY S w xY w)N__name__)inspectisclassr   callable	Exceptiongetattr)r   _vals     r   _sanitize_callablez5_sanitize_callable_params.<locals>._sanitize_callable:   sh    ??3<<C=6uD><<' 
  6sJ556s   A A A)(A))r   items)r   r   keyr   s       r   _sanitize_callable_paramsr"   /   sE        :@HXS#C#C((HHHs   ;	delimiter
parent_keyc           	         i }| j                         D ]  \  }}|r||z   t        |      z   n
t        |      }t        |      rt        |t              st        |      }nt        |t              rt        |      }t        |t              ri |t        |||      }t        |t              r=t        d |D              r+t        |      D ]  \  }}i |t        || d| |      } |||<    |S )a  Flatten hierarchical dict, e.g. ``{'a': {'b': 'c'}} -> {'a/b': 'c'}``.

    Args:
        params: Dictionary containing the hyperparameters
        delimiter: Delimiter to express the hierarchy. Defaults to ``'/'``.

    Returns:
        Flattened dict.

    Examples:
        >>> _flatten_dict({'a': {'b': 'c'}})
        {'a/b': 'c'}
        >>> _flatten_dict({'a': {'b': 123}})
        {'a/b': 123}
        >>> _flatten_dict({5: {'a': 123}})
        {'5/a': 123}
        >>> _flatten_dict({"dl": [{"a": 1, "c": 3}, {"b": 2, "d": 5}], "l": [1, 2, 3, 4]})
        {'dl/0/a': 1, 'dl/0/c': 3, 'dl/1/b': 2, 'dl/1/d': 5, 'l': [1, 2, 3, 4]}

    )r$   r#   c              3   <   K   | ]  }t        |t                y w)N)r   r   ).0items     r   	<genexpr>z _flatten_dict.<locals>.<genexpr>m   s     (XVWdD.)IVWs   /)r    strr   r   typer   r   r   r   _flatten_dictlistall	enumerate)	r   r#   r$   resultkvnew_keyir(   s	            r   r-   r-   M   s    *  F15?*y(3q61SV?:a#6q	A9%QAa(\\-gQZ"[\F4 S(XVW(X%X$Q<4lFlmDyPQRSQTEUaj&kl (  F7O  Mr   c                 *   | D ]  }t         rJddl}t        | |   |j                  |j                  |j
                  f      r| |   j                         | |<   t        | |         t        t        t        t        t        fvs}t        | |         | |<    | S )a  Returns params with non-primitvies converted to strings for logging.

    >>> import torch
    >>> params = {"float": 0.3,
    ...           "int": 1,
    ...           "string": "abc",
    ...           "bool": True,
    ...           "list": [1, 2, 3],
    ...           "namespace": Namespace(foo=3),
    ...           "layer": torch.nn.BatchNorm1d}
    >>> import pprint
    >>> pprint.pprint(_sanitize_params(params))  # doctest: +NORMALIZE_WHITESPACE
    {'bool': True,
        'float': 0.3,
        'int': 1,
        'layer': "<class 'torch.nn.modules.batchnorm.BatchNorm1d'>",
        'list': '[1, 2, 3]',
        'namespace': 'Namespace(foo=3)',
        'string': 'abc'}

    r   N)r   numpyr   bool_integerfloatingr(   r,   boolintfloatr+   r   )r   r2   nps      r   _sanitize_paramsr?   u   s|    , &)bhh

BKK%HI"1INN,q	q	?4eS&"AAF1IF1I  Mr   c                     | j                         D ci c]  \  }}|t        |      st        |      n|  c}}S c c}}w )z5Convert non-serializable objects in params to string.)r    _is_json_serializabler+   )r   r2   r3   s      r   _convert_json_serializablerB      s7    IOXAA215s1v1<XXXs   #;valuec           	          | *t        | t        t        t        t        t
        t        f      ry	 t        j                  |        y# t        t        f$ r Y yw xY w)z/Test whether a variable can be encoded as json.TF)r   r;   r<   r=   r+   r.   dictjsondumps	TypeErrorOverflowError)rC   s    r   rA   rA      sK    }
54eS$*MN

5}% s   A AAmetricsprefix	separatorc                 j    |s| S | j                         D ci c]  \  }}| | | | c}}S c c}}w )al  Insert prefix before each key in a dict, separated by the separator.

    Args:
        metrics: Dictionary with metric names as keys and measured quantities as values
        prefix: Prefix to insert before each key
        separator: Separates prefix and original key name

    Returns:
        Dictionary with prefix and separator inserted before each key

    )r    )rJ   rK   rL   r2   r3   s        r   _add_prefixrN      s@     5<]]_E_TQvhyk!%q(_EEEs   /)r*    )r   rF   argparser   collections.abcr   r   dataclassesr   r   typingr   r	   r
   torchr   "lightning_fabric.utilities.importsr   rE   r+   r   r"   r-   r?   rB   r;   rA   r=   rN    r   r   <module>rW      sc      3 , ' '  ?HU4S>9+D%EF 4PSUXPX> (Id38n Ic3h I<%.c2 %s %VY %cghkmphpcq %PT#s(^ S#X BYtCH~ Y$sCx. Y
	 	 	FS%../F9<FILFS%&&'Fr   