
    VhH*                        d Z ddlmZ ddlZddlZddlZddlm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mZ ej        eeef         Z G d dej                  Z G d d          Zd Z	 	 	 	 	 ddej        eef         dej        ej        ef         dededededededej         e         dej        fdZ!dS ) 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                        e Zd Z	 	 d	dej        e         dej        ej        ej        e                           dej        e         f fdZe	defd            Z
d Z xZS )
BagOfModelsNmodelsweightssegmentc                 R   t                                                       t          |          dk    sJ |d         |D ]A}|j        j        k    sJ |j        j        k    sJ |j        j        k    sJ |||_        Bj        | _        j        | _        j        | _        t          j        |          | _	        |fd|D             }nNt          |          t          |          k    sJ |D ])}t          |          t          j                  k    sJ *|| _
        dS )a  
        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   Nc                 2    g | ]}d  j         D             S )c                     g | ]}d S )      ? ).0_s     R/var/www/html/movieo_spanner_bot/venv/lib/python3.11/site-packages/demucs/apply.py
<listcomp>z3BagOfModels.__init__.<locals>.<listcomp>.<listcomp><   s    222q222    )sources)r   r   firsts     r   r   z(BagOfModels.__init__.<locals>.<listcomp><   s*    CCCq22EM222CCCr   )super__init__lenr   
samplerateaudio_channelsr   r   
ModuleListr   r   )selfr   r   r   otherweightr   	__class__s         @r   r   zBagOfModels.__init__   sB     	6{{Qq	 	( 	(E=EM1111#u'77777'5+?????" '#2*}mF++?CCCCFCCCGGw<<3v;;....! 9 96{{c%-&8&888888r   returnc                     t          d          }| j        D ]9}t          |t                    r"t	          |t          |j                            }:|S )Ninf)floatr   
isinstancer	   minr   )r#   max_allowed_segmentmodels      r   r-   zBagOfModels.max_allowed_segmentC   sV    #Ell[ 	U 	UE%** U&)*=uU]?S?S&T&T#""r   c                      t          d          )NzCall `apply_model` on this.)NotImplementedError)r#   xs     r   forwardzBagOfModels.forwardK   s    !"?@@@r   )NN)__name__
__module____qualname__tpListModelOptionalr*   r   propertyr-   r2   __classcell__)r&   s   @r   r   r      s        AE/3% %rwu~ %+bgbgen&=>%+e,% % % % % %N #U # # # X#A A A A A A Ar   r   c                   2    e Zd ZddZed             Zd ZdS )TensorChunkr   Nc                    |j         d         }|dk    sJ ||k     sJ |||z
  }nt          ||z
  |          }t          |t                    r|j        | _        ||j        z   | _        n|| _        || _        || _        |j        | _        d S )Nr   )shaper,   r+   r=   tensoroffsetlengthdevice)r#   rA   rB   rC   total_lengths        r   r   zTensorChunk.__init__P   s    |B'{{{{$$$$>!F*FF.77Ffk** 	! -DK 6=0DKK DK DKmr   c                 L    t          | j        j                  }| j        |d<   |S )Nr?   )listrA   r@   rC   )r#   r@   s     r   r@   zTensorChunk.shapec   s$    T[&''Kb	r   c                 8   || j         z
  }| j        j        d         }|dk    sJ | j        |dz  z
  }||z   }t	          d|          }t          ||          }||z
  }||z
  }	t          j        | j        d||f         ||	f          }
|
j        d         |k    sJ |
S )Nr?   r      .)rC   rA   r@   rB   maxr,   Fpad)r#   target_lengthdeltarE   startendcorrect_startcorrect_endpad_left	pad_rightouts              r   paddedzTensorChunk.paddedi   s    +{(,zzzzeqj(m#Au,,, 5(+%	eDK];%> >?(IAVWWy}----
r   )r   N)r3   r4   r5   r   r:   r@   rV   r   r   r   r=   r=   O   sR        $ $ $ $&   X
    r   r=   c                     t          | t                    r| S t          | t          j                  sJ t          |           S )N)r+   r=   thTensor)tensor_or_chunks    r   tensor_chunkr[   |   s@    /;// ,/2955555?+++r   T      ?r   Fr.   mixshiftssplitoverlaptransition_powerprogressnum_workersr   r'   c           	         ||j         }nt          j         |          }|
/|dk    r|j        dk    rt          |          }
nt	                      }
|||||||
|	d}t          | t                    rEd}dgt          | j                  z  }t          | j
        | j                  D ]\  }}t          t          |                                                    j         }|                    |           t!          ||fi |}|                    |           t#          |          D ]/\  }}|dd|ddddfxx         |z  cc<   ||xx         |z  cc<   0||z  }~t          |t          j                  sJ t'          |j        d                   D ]"}|dd|ddddfxx         ||         z  cc<   #|S |                     |           |                                  |dk    s
J d            |j        \  }}}|rd|d<   t-          d	| j        z            }t1          |          }t          |t2                    sJ |                    |d
|z  z             }d}t'          |          D ]N}t7          j        d|          }t3          ||||z   |z
            }t!          | |fi |}||d||z
  df         z  }O||z  }t          |t          j                  sJ |S |ryd|d<   t          j        |t          | j                  |||j                   }t          j        ||j                   }|	| j        }	|	|	dk    sJ t-          | j        |	z            }t-          d|z
  |z            }t'          d||          } t?          tA          || j        z  d                    }!t          j!        t          j"        d|d
z  dz   |          t          j"        ||d
z  z
  dd|          g          }"t          |"          |k    sJ |"|"#                                z  |z  }"g }#| D ]D}t3          |||          }$ |
j$        t           | |$fi |}%|#%                    |%|f           ||z  }E|rtM          j&        |#|!dd          }#|#D ]\  }%}|%'                                }&|&j        d         }'|d|||z   fxx         |"d|'         |&z                      |j                   z  cc<   ||||z   xx         |"d|'                             |j                   z  cc<   |(                                dk    sJ ||z  }t          |t          j                  sJ |S t          | tR                    r|	t-          |	| j        z            }(n(tU          | d          r| +                    |          }(n|}(t1          |          }t          |t2                    sJ |                    |(                              |          }t          j,                    5   | |          }ddd           n# 1 swxY w Y   t          |t          j                  sJ t[          ||          S )a  
    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)r^   r_   r`   ra   rb   rD   poolr   g        r   z-transition_power < 1 leads to weird behavior.r^   g      ?rI   .Fr_   )rD   z.2fr?   x   seconds)
unit_scalencolsunitvalid_length).rD   rX   typer   r   r+   r   r   r   zipr   r   nextiter
parameterstoapply_model	enumeraterY   ranger@   evalintr    r[   r=   rV   randomrandintzerosr   r*   formatcatarangerJ   submitappendtqdmresultr,   r	   hasattrrl   no_gradr
   ))r.   r]   r^   r_   r`   ra   rb   rD   rc   r   rf   kwargs	estimatestotals	sub_modelmodel_weightsoriginal_model_devicerU   kinst_weightbatchchannelsrC   	max_shift
padded_mixr   rB   shiftedshifted_out
sum_weightsegment_lengthstrideoffsetsscaler%   futureschunkfuture	chunk_outchunk_lengthrl   s)                                            r   rs   rs      sf   6 ~6""|??v{e33%k22DD$&&D,	$ 	$F %%%  13	EM***(+EL%-(H(H 
	 
	$I}$(i.B.B.D.D)E)E$F$F$M!LL   i7777CLL.///"+M":": ) );AAAq!!!QQQJ;.q			[(				I)RY/////yq)** 	/ 	/AaaaAAAqqqj!!!VAY.!!!!	HHV	JJLLLq   "Q   !iE8V C(xe..//	3#{+++++ZZY 677
v 	9 	9A^Ay11F!*ffy6H66QRRG%eW????K;sI$6$7$7788CCv#ry)))))
	 4(whuc%-00(F3:VVVXfSZ888
?mG"w|||3!%"2W"<==a'k^34466**fVe&66>>?? 1n&9A&=fMMM>Na4G#GBW]^^^` a a6{{n,,,, 6::<<'*:: 	% 	%FV^<<E T[eUEEfEEFNNFF+,,,n$FF 	ViE9UUUG% 	_ 	_NFFI$?2.LVF^333444}}%	122cj>>B444vf~55666&,:O:R:RSVS]:^:^^6666~~!####z#ry)))))
 eX&& 	"7+>w)99::LLUN++ 	" --f55LL!L3#{+++++ZZ--0088
Z\\ 	$ 	$%
##C	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$#ry)))))3'''s   X((X,/X,)	r   Tr\   r   FNr   NN)"__doc__concurrent.futuresr   rx   typingr6   torchrX   r   torch.nnr   rK   r   demucsr   hdemucsr   htdemucsr	   utilsr
   r   Unionr8   Moduler   r=   r[   rY   rw   boolr*   r9   rs   r   r   r   <module>r      s    2 1 1 1 1 1                $ $ $ $ $ $                    1 1 1 1 1 1 1 1
(*+1A 1A 1A 1A 1A") 1A 1A 1Ah* * * * * * * *Z, , , 04AC/3DHM( M(rxU 23 M(Xbi45M(M((,M( M( :?M( 	M(
 !M(
 02{5/AM( !iM( M( M( M( M( M(r   