o
    oi                     @   s  d dl Z d dlZd dlZd dlZd dlZd dlmZ d dlmZm	Z	m
Z
mZmZ d dlZd dlZd dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d d	lmZ d
d ZdefddZdefddZG dd deZG dd deZd<de
e  fddZ!deeej"ef dej"fddZ#d=de$de%fddZ&de'd e'd!e%fd"d#Z(d>d$e	e' fd%d&Z)d'd( Z*d)d* Z+de fd+d,Z,d-d. Z-d/d0 Z.d1edefd2d3Z/d?d5e d6e d7e$fd8d9Z0d:d; Z1dS )@    Ngethostname)AnyOptionalSetTupleUnion)logger)Tensor)Function)Number)config)ModelParamsc                  C   sJ   t dddd} | dkrtj rtd}|S td}|S t| }|S )NDEVICE train)defaultsectionzcuda:0cpu)r   torchcudais_availabledevice)sr    r   F/home/ubuntu/SoloSpeech/.venv/lib/python3.10/site-packages/df/utils.py
get_device   s   



r   xc                 C   sL   t | r| S | jd dkrtd| j | ddkr!|  } t | S )N   z9Last dimension need to be of length 2 (re + im), but got    )r   
is_complexshape
ValueErrorstride
contiguousview_as_complexr   r   r   r   
as_complex    s   

r(   c                 C   s   t | r
t | S | S N)r   r!   view_as_realr'   r   r   r   as_real*   s   

r+   c                   @   sD   e Zd ZdZededefddZededeeef fdd	Zd
S )angle_re_imESimilar to torch.angle but robustify the gradient for zero magnitude.reimc                 C   s   |  || t||S r)   )save_for_backwardr   atan2)ctxr.   r/   r   r   r   forward3   s   zangle_re_im.forwardgradreturnc                 C   s6   | j \}}|| |  d }| | || fS )N绽|=)saved_tensorssquare
clamp_min_)r2   r4   r.   r/   grad_invr   r   r   backward8   s   
zangle_re_im.backwardN)	__name__
__module____qualname____doc__staticmethodr
   r3   r   r;   r   r   r   r   r,   0   s     r,   c                   @   s4   e Zd ZdZedefddZedefddZdS )	angler-   r   c                 C   s   |  | t|j|jS r)   )r0   r   r1   imagreal)r2   r   r   r   r   r3   B   s   
zangle.forwardr4   c                 C   sL   | j \}||j |j  d }ttj|j | |j| fddS )Nr6   r   )dim)r7   rC   r8   rB   r9   r   r&   stack)r2   r4   r   r:   r   r   r   r;   G   s   &zangle.backwardN)r<   r=   r>   r?   r@   r
   r3   r;   r   r   r   r   rA   ?   s    rA   ModuleTr5   c                 C   s   t  }t| tjjr:|  D ]\}}|t||B }q|  D ]\}}|t||B }q|  D ]\}}|t||B }q.|rKt	|dkrKt
| d| |S )Nr   z1 not finite during checkpoint writing including: )set
isinstancer   nnrF   named_childrencheck_finite_modulenamed_parametersnamed_bufferslenr#   )objname_raiseoutchildparambufr   r   r   rK   N   s   rK   c                 C   sR   t | tjr| S t| rt| gS t | tr |    S t	d
t| )zTransforms Tensor to numpy.
    Args:
      x: An instance of torch tensor or caffe blob name

    Returns:
        numpy.array: Numpy array
    z>Got {}, but numpy array, scalar, or torch tensor are expected.)rH   npndarrayisscalararrayr
   detachr   numpyNotImplementedErrorformattyper'   r   r   r   make_np\   s   

r_   logc                 C   s^   t  }t|j|j|jd}d}d}|dkr"t||}|d7 }|dks| r-td| d |S )N)srhop_sizetau   g      ?r    z+Running with normalization window alpha = '')r   _calculate_norm_alphara   rb   norm_tauroundr	   info)r`   pa_	precisionar   r   r   get_norm_alphao   s   
rn   ra   rb   rc   c                 C   s   ||  }t | | S )zGExponential decay factor alpha for a given tau (decay window size [s]).)mathexp)ra   rb   rc   dtr   r   r   rf   |   s   rf   seedc                 C   s4   | pt dd} tj |  t |  t|  | S )zTIf manual seed is not specified, choose a random one and communicate it to the user.r    i'  )randomrandintrV   rr   r   manual_seed)rr   r   r   r   check_manual_seed   s
   

rv   c                  C   sN   zt jt jt} dd| ddg}t|  W S  tj	y&   Y dS w )zTReturns the top level git directory or None if not called within the git repository.git-C	rev-parsez--show-toplevelN
ospathdirnameabspath__file__
subprocesscheck_outputstripdecodeCalledProcessError)git_local_dirargsr   r   r   get_git_root   s   r   c                  C   sR   zt  } | du rW dS dd| ddddg}t|  W S  tjy(   Y dS w )zReturns the current git commit.Nrw   rx   ry   z--shortz--verifyHEAD)r   r   r   r   r   r   )git_dirr   r   r   r   get_commit_hash   s   r   c                   C   s   t  S r)   r   r   r   r   r   get_host   s   r   c                  C   sX   zt jt jt} dd| dddg}t|  }W |S  tj	y+   d }Y |S w )Nrw   rx   ry   z--abbrev-refr   rz   )r   r   branchr   r   r   get_branch_name   s   r   c                    s   t | tjjr fdd|  D S t | tjjr | jS t | tr' | S t | tt	fr0| S t | t
jrA fdd|  D S t | t
jrP fdd| D S | du rV| S | S )z@Apply a function on a tensor or mapping, or sequence of tensors.c                       g | ]}t | qS r   apply_to_tensor).0cfuncr   r   
<listcomp>       z#apply_to_tensor.<locals>.<listcomp>c                    s   i | ]
\}}|t | qS r   r   )r   ksampler   r   r   
<dictcomp>   s    z#apply_to_tensor.<locals>.<dictcomp>c                    r   r   r   )r   r   r   r   r   r      r   N)rH   r   rI   rF   children	Parameterdatar
   strbytescollectionsMappingitemsIterable)input_r   r   r   r   r      s   

r   hiddenc                 C   s   t | tjS )z{Cut backpropagation graph.
    Auxillary function to cut the backpropagation graph by detaching the hidden
    vector.
    )r   r
   rZ   )r   r   r   r   detach_hidden   s   r   Furldownload_dirextractc           
   	   C   s8  dd l }dd l}dd l}| dd }tj||}|j| dd=}|jdkr;t	
d|  d|j d	|j  td
 t|d}||j| W d    n1 sRw   Y  W d    n1 saw   Y  |rtj|d
 dkr{t	
d td
 ||}	|	| W d    n1 sw   Y  t| |S )Nr   /r   T)streami  zError downloading file z (z): r    wbz.zipz#File not supported. Cannot extract.)shutilzipfilerequestssplitr{   r|   joingetstatus_coder	   errorreasonexitopencopyfileobjrawsplitextZipFile
extractallremove)
r   r   r   r   r   r   local_filenamerfzfr   r   r   download_file   s.   
 

r   c                  C   sP   zddl m}  | dW S  ty'   dd l}|jdkr#tjd Y S tdw )Nr   )user_cache_dirDeepFilterNetlinuxz~/.cache/DeepFilterNet/zKCould not get cache dir. Please install `appdirs` via `pip install appdirs`)	appdirsr   ImportErrorsysplatformr{   r|   
expanduserr#   )r   r   r   r   r   get_cache_dir   s   

r   )rF   T)Tr)   )F)2r   ro   r{   rs   r   socketr   typingr   r   r   r   r   r[   rV   r   logurur	   r
   torch.autogradr   torch.typesr   	df.configr   df.modelr   r   r(   r+   r,   rA   r   rK   rW   r_   boolfloatrn   intrf   rv   r   r   r   r   r   r   r   r   r   r   r   r   <module>   sB    
 	
