
    Vhg                         d Z ddlZddlm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lmZ ddlmZmZ ddlmZmZmZmZmZ  G d dej                  ZdS )zB
This code contains the spectrogram and Hybrid version of Demucs.
    N)wiener)nn)
functional)Fraction)	rearrange   )CrossTransformerEncoder)rescale_module)capture_init)spectroispectro)pad1dScaledEmbedding	HEncLayer	MultiWrap	HDecLayerc            ?            e Zd ZdZedddddddddd	ddd
dddddd	ddd	d	dddddddddddddddddddddddddg ddddddddddddddf> fd	            Zd  Zd(d!Zd" Zd# Z	d$ Z
d%efd&Zd' Z xZS ))HTDemucsaV  
    Spectrogram and hybrid Demucs model.
    The spectrogram model has the same structure as Demucs, except the first few layers are over the
    frequency axis, until there is only 1 frequency, and then it moves to time convolutions.
    Frequency layers can still access information across time steps thanks to the DConv residual.

    Hybrid model have a parallel time branch. At some layer, the time branch has the same stride
    as the frequency branch and then the two are combined. The opposite happens in the decoder.

    Models can either use naive iSTFT from masking, Wiener filtering ([Ulhih et al. 2017]),
    or complex as channels (CaC) [Choi et al. 2020]. Wiener filtering is based on
    Open Unmix implementation [Stoter et al. 2019].

    The loss is always on the temporal domain, by backpropagating through the above
    output methods and iSTFT. This allows to define hybrid models nicely. However, this breaks
    a bit Wiener filtering, as doing more iteration at test time will change the spectrogram
    contribution, without changing the one from the waveform, which will lead to worse performance.
    I tried using the residual option in OpenUnmix Wiener implementation, but it didn't improve.
    CaC on the other hand provides similar performance for hybrid, and works naturally with
    hybrid models.

    This model also uses frequency embeddings are used to improve efficiency on convolutions
    over the freq. axis, following [Isik et al. 2020] (https://arxiv.org/pdf/2008.04470.pdf).

    Unlike classic Demucs, there is no resampling here, and normalization is always applied.
       0   Ni   r   FT      g?
      r   gMbP?   sing      @g        i'  g     @      ?)g     @r   gffffff?diag*   i  d   gffffff?g?iD  c@                    t                                                       |
| _        |	| _        || _        || _        || _        || _        || _        || _	        || _
        || _        |=| _        |>| _        |?| _        || _        |dz  | _        || _        || _        d| _        ||k    sJ t)          j                    | _        t)          j                    | _        t)          j                    | _        t)          j                    | _        |}@|@}A| j        r|Adz  }A|p|}B|}C|dz  }Dt5          |          D ]}E|E|k    }F|Ddk    }G|}H|}I|Gs|Ddk    sJ |dz  }I|}Hd}Jd}K|Gr|D|k    r|D}Id}Jd}K|I|H|G|J|F|||||ddd}Lt7          |L          }Md	|Md
<   ||Md<   ||Md<   d|Md<   t7          |L          }Nd}O|r|E|k     rd}Od|Nd<   |Krt9          |B|C          }C|C}Bt;          |A|Cf|dz  |d|L}P|Gr/t;          |@|Bf|dz  ||Kd|M}Q| j                            |Q           |Ort?          |P|          }P| j                            |P           |Ed	k    r*| j        tA          | j                  z  }@|@}A| j        r|Adz  }AtC          |C|Af|dz  |Ed	k    |d|N}R|Ort?          |R|          }R|Gr5tC          |B|@f|dz  |K|Ed	k    |d|M}S| j        "                    d	|S           | j        "                    d	|R           |B}@|C}AtG          ||Bz            }BtG          ||Cz            }C|Gr|D|k    rd}Dn|D|z  }D|Ed	k    r!|rtI          |D|A||          | _        || _%        |<rtM          | |<           |||dz
  z  z  }T|rnt)          j'        |T|d          | _(        t)          j'        ||Td          | _)        t)          j'        |T|d          | _*        t)          j'        ||Td          | _+        |}T|d	k    rntY          d4i d|Td|d| d|!d|d|;d|"d|#d|$d|%d|&d |'d!|(d"|)d#|*d$|+d%|,d&|-d'|/d(|.d)|0d*|1d+|2d,|3d-|4d.|5d/|6d0|7d1|8d2|9d3|:| _-        dS d| _-        dS )5a  
        Args:
            sources (list[str]): list of source names.
            audio_channels (int): input/output audio channels.
            channels (int): initial number of hidden channels.
            channels_time: if not None, use a different `channels` value for the time branch.
            growth: increase the number of hidden channels by this factor at each layer.
            nfft: number of fft bins. Note that changing this require careful computation of
                various shape parameters and will not work out of the box for hybrid models.
            wiener_iters: when using Wiener filtering, number of iterations at test time.
            end_iters: same but at train time. For a hybrid model, must be equal to `wiener_iters`.
            wiener_residual: add residual source before wiener filtering.
            cac: uses complex as channels, i.e. complex numbers are 2 channels each
                in input and output. no further processing is done before ISTFT.
            depth (int): number of layers in the encoder and in the decoder.
            rewrite (bool): add 1x1 convolution to each layer.
            multi_freqs: list of frequency ratios for splitting frequency bands with `MultiWrap`.
            multi_freqs_depth: how many layers to wrap with `MultiWrap`. Only the outermost
                layers will be wrapped.
            freq_emb: add frequency embedding after the first frequency layer if > 0,
                the actual value controls the weight of the embedding.
            emb_scale: equivalent to scaling the embedding learning rate
            emb_smooth: initialize the embedding with a smooth one (with respect to frequencies).
            kernel_size: kernel_size for encoder and decoder layers.
            stride: stride for encoder and decoder layers.
            time_stride: stride for the final time layer, after the merge.
            context: context for 1x1 conv in the decoder.
            context_enc: context for 1x1 conv in the encoder.
            norm_starts: layer at which group norm starts being used.
                decoder layers are numbered in reverse order.
            norm_groups: number of groups for group norm.
            dconv_mode: if 1: dconv in encoder only, 2: decoder only, 3: both.
            dconv_depth: depth of residual DConv branch.
            dconv_comp: compression of DConv branch.
            dconv_attn: adds attention layers in DConv branch starting at this layer.
            dconv_lstm: adds a LSTM layer in DConv branch starting at this layer.
            dconv_init: initial scale for the DConv branch LayerScale.
            bottom_channels: if >0 it adds a linear layer (1x1 Conv) before and after the
                transformer in order to change the number of channels
            t_layers: number of layers in each branch (waveform and spec) of the transformer
            t_emb: "sin", "cape" or "scaled"
            t_hidden_scale: the hidden scale of the Feedforward parts of the transformer
                for instance if C = 384 (the number of channels in the transformer) and
                t_hidden_scale = 4.0 then the intermediate layer of the FFN has dimension
                384 * 4 = 1536
            t_heads: number of heads for the transformer
            t_dropout: dropout in the transformer
            t_max_positions: max_positions for the "scaled" positional embedding, only
                useful if t_emb="scaled"
            t_norm_in: (bool) norm before addinf positional embedding and getting into the
                transformer layers
            t_norm_in_group: (bool) if True while t_norm_in=True, the norm is on all the
                timesteps (GroupNorm with group=1)
            t_group_norm: (bool) if True, the norms of the Encoder Layers are on all the
                timesteps (GroupNorm with group=1)
            t_norm_first: (bool) if True the norm is before the attention and before the FFN
            t_norm_out: (bool) if True, there is a GroupNorm (group=1) at the end of each layer
            t_max_period: (float) denominator in the sinusoidal embedding expression
            t_weight_decay: (float) weight decay for the transformer
            t_lr: (float) specific learning rate for the transformer
            t_layer_scale: (bool) Layer Scale for the transformer
            t_gelu: (bool) activations of the transformer are GeLU if True, ReLU else
            t_weight_pos_embed: (float) weighting of the positional embedding
            t_cape_mean_normalize: (bool) if t_emb="cape", normalisation of positional embeddings
                see: https://arxiv.org/abs/2106.03143
            t_cape_augment: (bool) if t_emb="cape", must be True during training and False
                during the inference, see: https://arxiv.org/abs/2106.03143
            t_cape_glob_loc_scale: (list of 3 floats) if t_emb="cape", CAPE parameters
                see: https://arxiv.org/abs/2106.03143
            t_sparse_self_attn: (bool) if True, the self attentions are sparse
            t_sparse_cross_attn: (bool) if True, the cross-attentions are sparse (don't use it
                unless you designed really specific masks)
            t_mask_type: (str) can be "diag", "jmask", "random", "global" or any combination
                with '_' between: i.e. "diag_jmask_random" (note that this is permutation
                invariant i.e. "diag_jmask_random" is equivalent to "jmask_random_diag")
            t_mask_random_seed: (int) if "random" is in t_mask_type, controls the seed
                that generated the random part of the mask
            t_sparse_attn_window: (int) if "diag" is in t_mask_type, for a query (i), and
                a key (j), the mask is True id |i-j|<=t_sparse_attn_window
            t_global_window: (int) if "global" is in t_mask_type, mask[:t_global_window, :]
                and mask[:, :t_global_window] will be True
            t_sparsity: (float) if "random" is in t_mask_type, t_sparsity is the sparsity
                level of the random part of the mask.
            t_cross_first: (bool) if True cross attention is the first layer of the
                transformer (False seems to be better)
            rescale: weight rescaling trick
            use_train_segment: (bool) if True, the actual size that is used during the
                training is used during inference.
        r   Nr   r   TF)depthcompressinitgelu)kernel_sizestridefreqpadnormrewritenorm_groupsdconv_kwr   r(   r&   r'   r)   context_freq)dconvcontext)r/   r0   empty)r/   lastr0   )r/   r1   r2   r0   )smoothscale)	referencedimembhidden_scale	num_heads
num_layerscross_firstdropoutmax_positionsnorm_innorm_in_group
group_norm
norm_firstnorm_out
max_periodweight_decaylrlayer_scaler%   sin_random_shiftweight_pos_embedcape_mean_normalizecape_augmentcape_glob_loc_scalesparse_self_attnsparse_cross_attn	mask_typemask_random_seedsparse_attn_windowglobal_windowsparsityauto_sparsity ).super__init__cacwiener_residualaudio_channelssourcesr&   r0   r'   r"   bottom_channelschannels
sampleratesegmentuse_train_segmentnfft
hop_lengthwiener_iters	end_itersfreq_embr   
ModuleListencoderdecodertencodertdecoderrangedictmaxr   appendr   lenr   insertintr   freq_emb_scaler
   Conv1dchannel_upsamplerchannel_downsamplerchannel_upsampler_tchannel_downsampler_tr	   crosstransformer)VselfrZ   rY   r\   channels_timegrowthr`   rb   rc   rX   rW   r"   r+   multi_freqsmulti_freqs_depthrd   	emb_scale
emb_smoothr&   time_strider'   r0   context_encnorm_startsr,   
dconv_modedconv_depth
dconv_comp
dconv_initr[   t_layerst_embt_hidden_scalet_heads	t_dropoutt_max_positions	t_norm_int_norm_in_groupt_group_normt_norm_first
t_norm_outt_max_periodt_weight_decayt_lrt_layer_scalet_gelut_weight_pos_embedt_sin_random_shiftt_cape_mean_normalizet_cape_augmentt_cape_glob_loc_scalet_sparse_self_attnt_sparse_cross_attnt_mask_typet_mask_random_seedt_sparse_attn_windowt_global_window
t_sparsityt_auto_sparsityt_cross_firstrescaler]   r^   r_   chinchin_zchoutchout_zfreqsindexr*   r(   strikerr)   	last_freqkwkwtkw_decmultienctencdectdectransformer_channels	__class__sV                                                                                        U/var/www/html/movieo_spanner_bot/venv/lib/python3.11/site-packages/demucs/htdemucs.pyrV   zHTDemucs.__init__7   s   P 	.,&
. $!2	!)("y((((}}8 	aKF)	5\\ i	/ i	/EK'D19DDC #zzzz!Ao"CI !,, 	  #"*( *& 	  B r((CCK!,C"CMCJ"XXFE /u'888).~&  eW--'1A~{ NP C  	+  %q.'#    $$T*** 2[11L$$$zz*S->->>8  aKF !1naZ   C  2[11 
.  %q.#!#    $$Q---L3'''DF''E&7*++G %K''EEf$Ezzhz /6*I! ! ! '/# 	4473333'&UQY*?? 	3%'Y/C_VW%X%XD"')y!5q( (D$ (*y$oq( (D$ *,!5q* *D& $3 a<<$;  %  %  %(( %E % ,^ % "'	 %
 $8 % *M % "	 % .o % "	 % .o % (< % (< % $ % (< % ,^ %  4! %" *M# %$ V% %& "4!3' %( "4!3) %* %:$9+ %, ,^- %. %:$9/ %0 "4!31 %2 #6"53 %4 &+5 %6 "4!37 %8 $8#79 %: .o; %< $= %> .o? %D!!!D %)D!!!    c                    | j         }| j        }|}||dz  k    sJ t          t          j        |j        d         |z                      }|dz  dz  }t          |||||z  z   |j        d         z
  fd          }t          |||          dd dd d f         }|j        d         |dz   k    sJ |j        |j        |f            |ddd|z   f         }|S )Nr   r   r   reflect)mode.)ra   r`   rp   mathceilshaper   r   )rx   xhlr`   x0ler)   zs           r   _speczHTDemucs._spec  s    _y TQY172;+,,--Agk!c3b=172;67iHHHAtR  crc111-wr{b1f$$$qw&<$$$c1a"f9nr   c                     | j         d|z  z  }t          j        |d          }t          j        |d          }|dz  dz  }|t          t	          j        ||z                      z  d|z  z   }t          |||          }|d|||z   f         }|S )Nr   )r   r   r   r   )r   r   r   r   )length.)ra   Fr)   rp   r   r   r   )rx   r   r   r4   r   r)   r   r   s           r   _ispeczHTDemucs._ispec  s    _E*E!\""E!VAgk#di,,---C7Q2&&&c3f$$%r   c                     | j         rS|j        \  }}}}t          j        |                              ddddd          }|                    ||dz  ||          }n|                                }|S )Nr   r   r   r   r   )rW   r   torchview_as_realpermutereshapeabs)rx   r   BCFrTms          r   
_magnitudezHTDemucs._magnitude  sr     8 	'KAq"a"1%%--aAq!<<A		!QUB**AAAr   c                    | j         }| j        rg|j        \  }}}}}|                    ||dd||                              dddddd          }	t          j        |	                                          }	|	S | j        r| j	        }|dk     r)|d d d f         }|d|
                                z   z  |z  S |                     |||          S )	Nr   r   r   r   r   r   r   g:0yE>)rb   rW   r   viewr   r   view_as_complex
contiguoustrainingrc   r   _wiener)
rx   r   r   nitersr   Sr   r   r   outs
             r   _maskzHTDemucs._mask  s     "8 	WNAq!R&&Ar1b!,,44Q1aAFFC'(8(899CJ= 	$^FA::!!!T'
Aquuww'!++<<1f---r   c                 V   |j         }d}| j        }|j        \  }}}	}
}|                    ddddd          }t	          j        |                    dddd                    }g }t          |          D ]}d}g }t          d||          D ]a}t          |||z             }t          |||f         |||f         ||          }|	                    |
                    dd	                     b|	                    t	          j        |d
                     t	          j        t	          j        |d                    }|                    ddddd                                          }|r|d d d df         }t          |j                  |||	|
|gk    sJ |                    |          S )Ni,  r   r   r   r   r   )residualr   )r6   )dtyperX   r   r   r   r   rj   slicer   rm   	transposecatr   stackr   listto)rx   mag_outmix_stftr   r$   wiener_win_lenr   r   r   r   Fqr   outssampleposr   framez_outs                     r   r   zHTDemucs._wiener  s   ~' 1aQ//!Q1a00%h&6&6q!Q&B&BCCAhh 	/ 	/FCCQ>22 4 4c3#788FEM*VU]+%	   

5??2r223333KK	#1---....#EKa$8$899kk!Q1a((3355 	aaa"f+CCI1aB"22222vvd||r   r   c                     | j         s|S t          | j        | j        z            }||k     rt	          d| d|           |S )z
        Return a length that is appropriate for evaluation.
        In our case, always return the training length, unless
        it is smaller than the given length, in which case this
        raises an error.
        zGiven length z  is longer than training length )r_   rp   r^   r]   
ValueError)rx   r   training_lengths      r   valid_lengthzHTDemucs.valid_length  sm     % 	MdlT_<==V##9F 9 9'69 9: : : r   c                    |j         d         }d }| j        r| j        r&t          |j         d         | j                  | _        nTt          | j        | j        z            }|j         d         |k     r'|j         d         }t          j        |d||z
  f          }| 	                    |          }| 
                    |                              |j                  }|}|j         \  }}	}
}|                    dd          }|                    dd          }||z
  d|z   z  }|}|                    dd          }|                    dd          }||z
  d|z   z  }g }g }g }g }t          | j                  D ]@\  }}|                    |j         d                    d }|t%          | j                  k     rW|                    |j         d                    | j        |         } ||          }|j        s|                    |           n|} |||          }|dk    r| j        {t-          j        |j         d         |j        	          }|                     |                                          d d d d d d f                             |          }|| j        |z  z   }|                    |           B| j        r| j        rX|j         \  }}}}t;          |d
          }|                     |          }t;          |d|          }|                     |          }|                     ||          \  }}| j        rLt;          |d
          }|                      |          }t;          |d|          }| !                    |          }t          | j"                  D ]\  }}|#                    d          }  ||| |#                    d                    \  }}!| j$        t%          | j%                  z
  }"||"k    r| j%        ||"z
           }#|#                    d          }$|#j        r@|!j         d         dk    sJ |!j                     |!d d d d df         }! |#|!d |$          \  }}%|#                    d          }  |#|| |$          \  }}%t%          |          dk    sJ t%          |          dk    sJ t%          |          dk    sJ t%          | j&                  }&|'                    ||&d|
|          }||d d d f         z  |d d d f         z   }|j        j(        dk    }'|'r|)                                }| *                    ||          }(| j        r5| j        r| +                    |(|          }n-| +                    |(|          }n| +                    |(|          }|'r|                    d          }| j        r9| j        r|'                    ||&d|          }n1|'                    ||&d|          }n|'                    ||&d|          }||d d d f         z  |d d d f         z   }||z   }|r|dd |f         }|S )Nr   r   )r   r   r   T)r6   keepdimgh㈵>)r   r   r   )devicezb c f t-> b c (f t)zb c (f t)-> b c f t)fr   r   mps.),r   r_   r   r   r]   r^   rp   r   r)   r   r   r   r   meanstd	enumeraterf   rm   rn   rh   r1   rd   r   aranget	expand_asrq   rw   r[   r   rs   ru   rt   rv   rg   popr"   ri   rZ   r   typecpur   r   ))rx   mixr   length_pre_padr   r   magr   r   r   r   r   r   r   xtmeantstdtsavedsaved_tlengths	lengths_tidxencodeinjectr   frsr7   bcr   r  decodeskippreoffsetr   length_t_r   x_is_mpszouts)                                            r   forwardzHTDemucs.forward  s   2! 	L} L'	"tGG"%dlT_&D"E"E9R=?22%(Yr]N%a>)I%JKKCJJsOOooa  ##CJ//g1b! vv)Tv22ee	4e00X$*% FD11vv&$v//5jTD[) 	$T\22 	 	KCNN172;'''FS''''  "...}S)T"XXz  NN2&&&&  Fq&!!AaxxDM5 l172;qx@@@mmC((**,,T111aaa-=>HHKK+c11LLOOOO  	4# 2W
1aa!677**1--a!6!<<<--b11))!R00EAr# 4a!677,,Q//a!6!<<<//33$T\22 	5 	5KC99R==DVAtW[[__55FAs Z#dm"4"44Ff}}}S6\2$==,,: 59Q<1,,,ci,,,aaaAg,C DdH55EB";;r??D DT844EB 5zzQ9~~""""7||q    FF1aR##AAAtGtAAAtG}, 8=E) 	Azz!Q! 	*} 7KKf--KKo66D&))A  	UA! 	+} 8WWQ2v..WWQ277Ar6**B$qqq$w-%4.0F 	(#&'Ar   )Nr   )__name__
__module____qualname____doc__r   rV   r   r   r   r   r   rp   r   r  __classcell__)r   s   @r   r   r      s        6 
 "000 ! Yj) j) j) j) j) \j)X  ,   	 	 	. . ."  >3     E E E E E E Er   r   )r"  r   openunmix.filteringr   r   r   torch.nnr   r   	fractionsr   einopsr   transformerr	   demucsr
   statesr   specr   r   hdemucsr   r   r   r   r   Moduler   rT   r   r   <module>r.     s5     & & & & & &        $ $ $ $ $ $             0 0 0 0 0 0 " " " " " "             # # # # # # # # L L L L L L L L L L L L L Ly	 y	 y	 y	 y	ry y	 y	 y	 y	 y	r   