
    ]iH*                        S r SSKJr  SSKrSSKrSSKrSSKJr  SSK	J
r  SSKrSSKJr  SSKJr  SS	KJr  SS
KJrJr  \R,                  \\\4   r " S S\R0                  5      r " S S5      rS r     SS\R,                  \\4   S\R,                  \R8                  \4   S\S\S\S\S\S\S\R@                  \   S\R8                  4S jjr!g)z
Code to apply a model to a mix. It will handle chunking with overlaps and
inteprolation between chunks, as well as the "shift trick".
    )ThreadPoolExecutorN)nn)
functional   )Demucs)HDemucs)HTDemucs)center_trimDummyPoolExecutorc                      ^  \ rS rSr  S
S\R
                  \   S\R                  \R
                  \R
                  \         S\R                  \   4U 4S jjjr	\
S\4S j5       rS rS	rU =r$ )BagOfModels   modelsweightssegmentc                   > [         TU ]  5         [        U5      S:  d   eUS   nU Hb  nUR                  UR                  :X  d   eUR                  UR                  :X  d   eUR
                  UR
                  :X  d   eUc  M\  X5l        Md     UR
                  U l        UR                  U l        UR                  U l        [        R                  " U5      U l	        Uc-  U Vs/ s H  odR                   Vs/ s H  nSPM     snPM!     nnOG[        U5      [        U5      :X  d   eU H'  n[        U5      [        UR                  5      :X  a  M'   e   X l
        gs  snf s  snf )aJ  
Represents a bag of models with specific weights.
You should call `apply_model` rather than calling directly the forward here for
optimal performance.

Args:
    models (list[nn.Module]): list of Demucs/HDemucs models.
    weights (list[list[float]]): list of weights. If None, assumed to
        be all ones, otherwise it should be a list of N list (N number of models),
        each containing S floats (S number of sources).
    segment (None or float): overrides the `segment` attribute of each model
        (this is performed inplace, be careful is you reuse the models passed).
r   N      ?)super__init__lensources
samplerateaudio_channelsr   r   
ModuleListr   r   )	selfr   r   r   firstother_weight	__class__s	           I/mnt/rpi/tmp/demucs-venv-sys/lib/python3.13/site-packages/demucs/apply.pyr   BagOfModels.__init__   s4     	6{Qq	E==EMM111##u'7'7777''5+?+????" '  $22**}}mmF+?<BCFqMM2MqM2FGCGw<3v;...!6{c%--&8888 " 3Cs   #E6E
EEreturnc                     [        S5      nU R                   H9  n[        U[        5      (       d  M  [	        U[        UR
                  5      5      nM;     U$ )Ninf)floatr   
isinstancer	   minr   )r   max_allowed_segmentmodels      r!   r)   BagOfModels.max_allowed_segmentC   sF    #El[[E%**&)*=uU]]?S&T# ! #"    c                     [        S5      e)NzCall `apply_model` on this.)NotImplementedError)r   xs     r!   forwardBagOfModels.forwardK   s    !"?@@r,   )r   r   r   r   r   )NN)__name__
__module____qualname____firstlineno__tpListModelOptionalr&   r   propertyr)   r0   __static_attributes____classcell__)r    s   @r!   r   r      s}    AE/3%rwwu~ %++bggbggen&=>%++e,% %N #U # #A Ar,   r   c                   4    \ rS rSrSS jr\S 5       rS rSrg)TensorChunkO   Nc                 &   UR                   S   nUS:  d   eX$:  d   eUc  XB-
  nO[        XB-
  U5      n[        U[        5      (       a%  UR                  U l        X!R
                  -   U l        OXl        X l        X0l        UR                  U l        g )Nr   )shaper(   r'   r>   tensoroffsetlengthdevice)r   rC   rD   rE   total_lengths        r!   r   TensorChunk.__init__P   s    ||B'{{$$$>!*F.7Ffk** --DK ==0DK K Kmmr,   c                 b    [        U R                  R                  5      nU R                  US'   U$ )NrA   )listrC   rB   rE   )r   rB   s     r!   rB   TensorChunk.shapec   s(    T[[&&'KKb	r,   c                 H   XR                   -
  nU R                  R                  S   nUS:  d   eU R                  US-  -
  nXA-   n[	        SU5      n[        X55      nXd-
  nXW-
  n	[        R                  " U R                  SXg24   X45      n
U
R                  S   U:X  d   eU
$ )NrA   r      .)rE   rC   rB   rD   maxr(   Fpad)r   target_lengthdeltarG   startendcorrect_startcorrect_endpad_left	pad_rightouts              r!   paddedTensorChunk.paddedi   s    +{{((,zzeqj(#Au,, (%	eeDKK]%> >?(AVWyy}---
r,   )rF   rE   rD   rC   )r   N)	r2   r3   r4   r5   r   r:   rB   rZ   r;    r,   r!   r>   r>   O   s     $&  
r,   r>   c                     [        U [        5      (       a  U $ [        U [        R                  5      (       d   e[        U 5      $ )N)r'   r>   thTensor)tensor_or_chunks    r!   tensor_chunkra   |   s7    /;///2995555?++r,   r*   mixshiftssplitoverlaptransition_powerprogressnum_workersr   r#   c           
      ~   Uc  UR                   nO[        R                   " U5      nU
c,  US:  a  UR                  S:X  a  [        U5      n
O
[	        5       n
UUUUUUU
U	S.n[        U [        5      (       Ga9  SnS/[        U R                  5      -  n[        U R                  U R                  5       H  u  p[        [        UR                  5       5      5      R                   nUR                  U5        [!        X40 UD6nUR                  U5        [#        U5       H*  u  nnUSS2USS2SS24==   U-  ss'   UU==   U-  ss'   M,     UU-  nAM     [        U[        R$                  5      (       d   e['        UR(                  S   5       H  nUSS2USS2SS24==   UU   -  ss'   M     U$ U R                  U5        U R+                  5         US:  d   S5       eUR(                  u  nnnU(       a  SUS'   [-        S	U R.                  -  5      n[1        U5      n[        U[2        5      (       d   eUR5                  US
U-  -   5      nSn['        U5       HI  n[6        R8                  " SU5      n[3        UUUU-   U-
  5      n[!        U U40 UD6nUUSUU-
  S24   -  nMK     UU-  n[        U[        R$                  5      (       d   eU$ U(       Gao  SUS'   [        R:                  " U[        U R                  5      UUUR                   S9n[        R:                  " UUR                   S9nU	c  U R<                  n	U	b  U	S:  d   e[-        U R.                  U	-  5      n[-        SU-
  U-  5      n['        SUU5      n [?        [A        UU R.                  -  S5      5      n![        RB                  " [        RD                  " SUS
-  S-   US9[        RD                  " UUS
-  -
  SSUS9/5      n"[        U"5      U:X  d   eU"U"RG                  5       -  U-  n"/ n#U  HA  n[3        UUU5      n$U
RH                  " [         U U$40 UD6n%U#RK                  U%U45        UU-  nMC     U(       a  [L        RL                  " U#U!SSS9n#U# H  u  n%nU%RO                  5       n&U&R(                  S   n'USUUU-   24==   U"SU' U&-  R                  UR                   5      -  ss'   UUUU-   === U"SU' R                  UR                   5      -  sss& M     URQ                  5       S:  d   eUU-  n[        U[        R$                  5      (       d   eU$ [        U [R        5      (       a  U	b  [-        XR.                  -  5      n(O%[U        U S5      (       a  U RW                  U5      n(OUn([1        U5      n[        U[2        5      (       d   eUR5                  U(5      R                  U5      n[        RX                  " 5          U " U5      nSSS5        [        W[        R$                  5      (       d   e[[        UU5      $ ! , (       d  f       N;= f)aa  
Apply model to a given mixture.

Args:
    shifts (int): if > 0, will shift in time `mix` by a random amount between 0 and 0.5 sec
        and apply the oppositve shift to the output. This is repeated `shifts` time and
        all predictions are averaged. This effectively makes the model time equivariant
        and improves SDR by up to 0.2 points.
    split (bool): if True, the input will be broken down in 8 seconds extracts
        and predictions will be performed individually on each and concatenated.
        Useful for model with large memory footprint like Tasnet.
    progress (bool): if True, show a progress bar (requires split=True)
    device (torch.device, str, or None): if provided, device on which to
        execute the computation, otherwise `mix.device` is assumed.
        When `device` is different from `mix.device`, only local computations will
        be on `device`, while the entire tracks will be stored on `mix.device`.
    num_workers (int): if non zero, device is 'cpu', how many threads to
        use in parallel.
    segment (float or None): override the model segment parameter.
Nr   cpu)rc   rd   re   rf   rg   rF   poolr   g        r   z-transition_power < 1 leads to weird behavior.rc   g      ?rM   .Frd   )rF   z.2frA   x   seconds)
unit_scalencolsunitvalid_length).rF   r^   typer   r   r'   r   r   r   zipr   r   nextiter
parameterstoapply_model	enumerater_   rangerB   evalintr   ra   r>   rZ   randomrandintzerosr   r&   formatcatarangerN   submitappendtqdmresultr(   r	   hasattrrq   no_gradr
   ))r*   rb   rc   rd   re   rf   rg   rF   rh   r   rk   kwargs	estimatestotals	sub_modelmodel_weightsoriginal_model_devicerY   kinst_weightbatchchannelsrE   	max_shift
padded_mixr   rD   shiftedshifted_out
sum_weightsegment_lengthstrideoffsetsscaler   futureschunkfuture	chunk_outchunk_lengthrq   s)                                            r!   rx   rx      s   6 ~6"|?v{{e3%k2D$&D,	$F %%% 13	EMM**(+ELL%--(H$I$(i.B.B.D)E$F$M$M!LL i77CLL./"+M":;Aq!QJ;.q	[(	 #; I )I )RYY////yq)*AaAqj!VAY.! +	HHV	JJLq Q"QQ !iiE8Vxe.../	3#{++++ZZY 67
vA^^Ay1F!*ffy6H66QRG%eW??K;sI$6$7788C	 
 	v#ryy))))
	whhuc%--0(F3::VXXfSZZ8
?mmG"w|33!%"2"2W"<=a'k^3466*fVe&6&66>? 1n&9A&=fM>Na4G#GBW]^` a6{n,,, 6::<'*::FV^<E[[eUEfEFNNFF+,n$F	 
 iiE9UG%NFFI$??2.LVF^3334}%	122cjj>B4vf~56&,:O:R:RSVS]S]:^^6 & ~~!###z#ryy))))
 eX&&7+>w)9)99:LUN++ --f5L!L3#{++++ZZ-008
ZZ\
#C #ryy))))3'' \s   0	X..
X<)	r   Tg      ?r   FNr   NN)"__doc__concurrent.futuresr   r}   typingr6   torchr^   r   torch.nnr   rO   r   demucsr   hdemucsr   htdemucsr	   utilsr
   r   Unionr8   Moduler   r>   ra   r_   r|   boolr&   r9   rx   r\   r,   r!   <module>r      s   2     $     1
(*+1A")) 1Ah* *Z, 04AC/3DHM(rxxU 23 M(XXbii45M(M((,M( M( :?M( 	M(
 !M(
 02{{5/AM( !iiM(r,   