o
    ¤ôj‚  ã                   @   sh  d dl Z d dlmZ d dlmZmZ d dlmZmZm	Z	m
Z
mZmZ d dlZd dlmZ deeeeef ef  deeef fdd	„Zdeeef deeef fd
d„Zdde
eef dededeeef fdd„Zdeeef deeef fdd„Zdeeef deeef fdd„Zdedefdd„Zde	eeeef f dedede	eeeef f fdd„ZdS )é    N)Ú	Namespace)ÚasdictÚis_dataclass)ÚAnyÚDictÚMappingÚMutableMappingÚOptionalÚUnion)ÚTensorÚparamsÚreturnc                 C   s"   t | tƒr	t| ƒ} | du ri } | S )z²Ensure parameters are a dict or convert to dict if necessary.

    Args:
        params: Target to be converted to a dictionary

    Returns:
        params as a dictionary

    N)Ú
isinstancer   Úvars©r   © r   út/var/www/html/academy/tools/voices/clone/cosy-venv/lib/python3.10/site-packages/lightning/fabric/utilities/logger.pyÚ_convert_params   s
   
r   c                    s(   dt dt fdd„‰ ‡ fdd„|  ¡ D ƒS )zìSanitize 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                 S   sH   t | ƒr"z| ƒ }t |ƒr| jW S |W S  ty!   t| dd ƒ Y S w | S )NÚ__name__)Úcallabler   Ú	ExceptionÚgetattr)r   Ú_valr   r   r   Ú_sanitize_callable6   s   ÿz5_sanitize_callable_params.<locals>._sanitize_callablec                    s   i | ]	\}}|ˆ |ƒ“qS r   r   )Ú.0Úkeyr   ©r   r   r   Ú
<dictcomp>C   s    z-_sanitize_callable_params.<locals>.<dictcomp>)r   Úitemsr   r   r   r   Ú_sanitize_callable_params+   s   r    ú/Ú Ú	delimiterÚ
parent_keyc                 C   s„   i }|   ¡ D ]9\}}|r|| t|ƒ nt|ƒ}t|ƒr!t|ƒ}n	t|tƒr*t|ƒ}t|tƒr;i |¥t|||d�¥}q|||< q|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}

    )r$   r#   )	r   Ústrr   r   r   r   r   r   Ú_flatten_dict)r   r#   r$   ÚresultÚkÚvÚnew_keyr   r   r   r&   F   s   



r&   c                 C   sd   | D ]-}t | | tjtjtjfƒr| |  ¡ | |< qt| | ƒttt	t
tfvr/t
| | ƒ| |< q| 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   ÚnpÚbool_ÚintegerÚfloatingÚitemÚtypeÚboolÚintÚfloatr%   r   )r   r(   r   r   r   Ú_sanitize_paramsh   s   €r4   c                 C   s   dd„ |   ¡ D ƒS )z5Convert non-serializable objects in params to string.c                 S   s&   i | ]\}}|t |ƒst|ƒn|“qS r   )Ú_is_json_serializabler%   ©r   r(   r)   r   r   r   r   ‰   s   & z._convert_json_serializable.<locals>.<dictcomp>©r   r   r   r   r   Ú_convert_json_serializable‡   s   r8   Úvaluec              	   C   sL   | du st | ttttttfƒrdS zt | ¡ W dS  t	t
fy%   Y dS w )z/Test whether a variable can be encoded as json.NTF)r   r1   r2   r3   r%   ÚlistÚdictÚjsonÚdumpsÚ	TypeErrorÚOverflowError)r9   r   r   r   r5   Œ   s   
þr5   ÚmetricsÚprefixÚ	separatorc                    s    ˆ s| S ‡ ‡fdd„|   ¡ D ƒS )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

    c                    s"   i | ]\}}ˆ › ˆ› |› �|“qS r   r   r6   ©rA   rB   r   r   r   ¨   s   " z_add_prefix.<locals>.<dictcomp>r7   )r@   rA   rB   r   rC   r   Ú_add_prefix˜   s   rD   )r!   r"   )r<   Úargparser   Údataclassesr   r   Útypingr   r   r   r   r	   r
   Únumpyr+   Útorchr   r%   r   r    r&   r4   r8   r1   r5   r3   rD   r   r   r   r   Ú<module>   s*    .","""ÿÿÿþ