
    ^j/                         d dl ZddlmZmZ ddlmZ ddlmZm	Z	m
Z
 ddlmZ ddlmZmZmZ  e       rd dlZ ej$                  e      Z G d d	ed
      Ze G d de	             ZdgZy)    N   )
AudioInput make_list_of_audio_chat_template)BatchFeature)ProcessingKwargsProcessorMixinUnpack)	TextInput)auto_docstringis_torch_availableloggingc                   *    e Zd Zddidddddddd	Zy
)AudioFlamingo3ProcessorKwargspaddingTi>  
max_length)sampling_ratereturn_attention_maskr   ptleft)return_tensorspadding_side)text_kwargsaudio_kwargscommon_kwargsN)__name__
__module____qualname__	_defaults     /var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/audioflamingo3/processing_audioflamingo3.pyr   r   !   s2     t
 #%)#
 #"
Ir    r   F)totalc                       e Zd ZeZ	 	 	 	 d fd	Ze	 	 ddeee   z  de	dz  de
dz  dee   def
 fd	       Z	 	 dde	dz  deee   z  dz  dee   f fd
Zd Zde	fdZdededefdZedee   f fd       Zedee   fd       Z	 ddeee   z  e	z  deee   z  dz  dee   defdZdddZd ZdedefdZ xZS )AudioFlamingo3ProcessorNc                     || _         |j                  |      | _        || _        || _        t
        |   |||       y)a  
        audio_token (`Optional[str]`, *optional*, defaults to `"<sound>"`):
            Special token used to represent audio inputs in the chat template.
        default_transcription_prompt (`str`, *optional*, defaults to `"Transcribe the input speech."`):
            Default prompt to use for transcription tasks when applying transcription requests.
        max_audio_len (`int`, *optional*, defaults to 600):
            Maximum length of audio sequences in seconds. Audio longer than this will be truncated.
        )chat_templateN)audio_tokenconvert_tokens_to_idsaudio_token_iddefault_transcription_promptmax_audio_lensuper__init__)selffeature_extractor	tokenizerr&   r'   r*   r+   	__class__s          r!   r-   z AudioFlamingo3Processor.__init__6   sE    " ''==kJ,H)**I]Sr    Ftextaudiooutput_labelskwargsreturnc                 J   d|v r*|d   dk7  r"t        | j                  j                   d      |rd|d<   t        |   d||d|}|rM|j                  d      }|d   j                         }d	||d
k7  <   d	||| j                  j                  k(  <   ||d<   t        |d      S )a0  
        output_labels (bool, *optional*, default=False):
            Whether to return labels for training.

        Returns:
            [`BatchFeature`]: A dictionary with tokenized text (`input_ids`, `attention_mask`) and
            audio features (`input_features`, `input_features_mask`).
        r   r   z% only supports `return_tensors='pt'`.Treturn_mm_token_type_idsr3   r2   mm_token_type_ids	input_idsir   labels)datatensor_typer   )

ValueErrorr1   r   r,   __call__popcloner0   pad_token_idr   )	r.   r2   r3   r4   r5   model_inputsr:   r<   r1   s	           r!   r@   z AudioFlamingo3Processor.__call__M   s    " v%&1A*Bd*J 7 788]^__15F-.w'Ie$I&I , 0 01D E!+.446F-1F$)*<@F6T^^8889%+L"4@@r    c                     t        |   d||d| |?|<t        |      t        |      k7  r$t        dt        |       dt        |       d      y y y )Nr9   zGot z
 text but z audios; they must match 1:1.r   )r,   validate_inputslenr?   )r.   r3   r2   r5   r1   s       r!   rF   z'AudioFlamingo3Processor.validate_inputsm   se     	Ae$A&A 1c$i3u:6MtCI;jUDabcc 7N 1r    c                 2    |dz
  dz  dz   }|dz
  dz  dz   }|S )N      r   )r.   audio_lengthsconv_output_lengthsaudio_tokens_lengthss       r!   _get_audio_token_lengthz/AudioFlamingo3Processor._get_audio_token_lengthx   s2    ,q0Q6: 3a 7A=A##r    c           
      6   t        |d   | j                  j                  z        }t        | j                  | j                  j                  z        }g }g }|D ]  }t        |j                  d         }t        d||z   dz
  |z        }	|	|kD  r<t        j                  d||d   z  dd| j                   d| j                   d       |}	|j                  |	       t        ||	|z        }
t        |	      D ]-  }||z  }t        |dz   |z  |
      }|j                  |||        /  | j                  j                  |      } | j                  |fi |}|j                  d	      |d
<   t        j                  t        j                  |d
   j!                  d      |      D cg c]  }|j!                          c}      }| j#                  |      |d<   g }t        t%        |            D ]&  }| j'                  ||      }|j                  |       ( ||fS c c}w )Nr   r   rI   zAudio duration (z.1fzs) exceeds zs; truncating to first zs.attention_maskinput_features_masknum_audio_tokens)	audio_idx)intr/   chunk_lengthr+   shapemaxloggerwarningappendminrangefetch_audiorA   torchstacksplitsumrN   rG   replace_audio_token)r.   r3   r5   window_sizemax_windowsper_sample_windowsflat_chunksaudio_el	n_samplesn_wintime_capistartendaudio_inputssrK   audio_replacementsidxreplacement_texts                       r!   _process_audioz&AudioFlamingo3Processor._process_audio}   sU   &1D4J4J4W4WWX$,,0F0F0S0SST(*(* 	8HHNN1-.II3a7KGHE{"&y6/3J'J3&O{[_[m[mZn  oF  GK  GY  GY  FZ  Z\  ] $%%e,9ek&9:H5\ 8K1q5K/:""8E##678	8  &&2259-t--kDVD.:.>.>?O.P*+
 #kk,7L*M*Q*QRT*UWijkQUUWk
 ,0+G+G+V'(U$ 	8C#77PS7T%%&67	8 /// ls   !Hro   rT   c                 0    |d   |   }| j                   |z  S )NrS   )r'   )r.   ro   rT   rS   s       r!   rc   z+AudioFlamingo3Processor.replace_audio_token   s%    '(:;IF"222r    c                      t         |   dgz   S )NrQ   )r,   model_input_names)r.   r1   s    r!   rw   z)AudioFlamingo3Processor.model_input_names   s    w(,A+BBBr    c                     dgS )zNInput names returned always by subprocessors but not used in model's `forward`rS   r   )r.   s    r!   unused_input_namesz*AudioFlamingo3Processor.unused_input_names   s     ###r    promptc           
      p   t        t        |            }t               rU|D cg c]J  }t        |t        j
                        r,|j                         j                         j                         n|L }}t        |      }|dk(  rt        d      || j                  g|z  }nt        |t              r|g|z  }nt        |t         t        f      r}t        |      |k7  rt        dt        |       d| d      g }|D ]L  }||j                  | j                         !t        |t              r|j                  |       Ct        d       nt        d      t!        ||      D 	
cg c](  \  }	}
dd	|	d
t        |
t              rd|
dnd|
dgdg* }}	}
 | j"                  |fdddd|S c c}w c c}
}	w )a  
        Prepare inputs for automatic speech recognition without manually writing the default transcription prompt.

        Args:
            audio (`str`, `list[str]`, `np.ndarray`, `torch.Tensor`, `list[np.ndarray]`, `list[torch.Tensor]`):
                Audio to transcribe. Strings are interpreted as local paths or URLs and will be loaded automatically by
                the chat template loader; NumPy arrays and PyTorch tensors are forwarded directly.
            prompt (`str` or `list[str]`, *optional*):
                Custom prompt(s) to include in the user turn. A list must be the same length as the batch. When `None`,
                each sample uses `"Transcribe the input speech."`.
            **kwargs:
                Additional keyword arguments forwarded to [`~AudioFlamingo3Processor.apply_chat_template`] (for example
                `text_kwargs`, `audio_kwargs`, ...).

        Returns:
            [`BatchFeature`]: Processor outputs ready to be passed to [`AudioFlamingo3ForConditionalGeneration.generate`].

        r   z)`audio` must contain at least one sample.z	Received z prompt(s) for z$ audio sample(s); counts must match.z'Each prompt must be a string or `None`.z<`prompt` must be a string, a sequence of strings, or `None`.userr2   )typer2   r3   )r}   path)r}   r3   )rolecontentT)tokenizeadd_generation_promptreturn_dict)listr   r   
isinstancer_   TensordetachcpunumpyrG   r?   r*   strtupler[   	TypeErrorzipapply_chat_template)r.   r3   rz   r5   audio_itemsel
batch_sizepromptsitemprompt_text
audio_itemconversationss               r!   apply_transcription_requestz3AudioFlamingo3Processor.apply_transcription_request   s   2 /33STY3Z.[grsac
2u||8T299;??,224Z\\sKs%
?HII>889JFG$h+Gu.6{j( F}OJ<Gkl  G O<NN4#D#DEc*NN4(#$MNNO Z[[ ,/w+D
 (Z #!'=%j#6 ")*=&-
C	 

 
 (t''
"&	

 
 	
S t4
s   AF-&-F2)strip_prefixc                     | j                   j                  |i |}|r|D cg c]  }| j                  |       }}|S c c}w )aj  
        Forward arguments to [`~PreTrainedTokenizer.decode`] and optionally remove the assistant framing the model
        was trained to produce.

        AF3 transcription requests respond with sentences such as `"The spoken content of the audio is "..."."`.
        Setting `strip_prefix=True` trims the fixed prefix for just the transcription text.
        )r0   decode"_strip_assistant_prefix_and_quotes)r.   r   argsr5   decodedr2   s         r!   r   zAudioFlamingo3Processor.decode   sK     ($..''88QXYt>>tDYGY Zs   ?c                 &     | j                   |i |S )z)BC as previous examples used batch_decode)r   )r.   r   r5   s      r!   batch_decodez$AudioFlamingo3Processor.batch_decode  s    t{{D+F++r    c                 @   |j                         }dD ]1  }|j                  |      s|t        |      d j                         } n |j                  d      r|dd j                         }t        |      dk\  r%|d   |d   k(  r|d   dv r|dd j                         }|S )	zi
        Remove the assistant prefix and surrounding quotes from a decoded transcription string.
        )z"The spoken content of the audio isz!The transcription of the audio isz!The content of the input audio isN.rR   rJ   r   >   "'rI   )strip
startswithrG   endswith)r.   r2   strippedprefixs       r!   r   z:AudioFlamingo3Processor._strip_assistant_prefix_and_quotes  s    
 ::<
 	F
 ""6*#CKM288:	 S!}**,Hx=A(1+""=(1+Q[B["~++-Hr    )Nz<sound>zTranscribe the input speech.iX  )NF)NN)N)r   r   r   r   valid_processor_kwargsr-   r   r
   r   r   boolr	   r   r@   r   rF   rN   rt   dictrU   r   rc   propertyrw   ry   r   r   r   r   __classcell__)r1   s   @r!   r$   r$   2   s   : %CT.  $(%*	A$y/)A D A d{	A
 67A 
A AB $(37	dD 	d $y/)D0	d )*		d$
(0J (0T3 3 3 3 C49 C C $DI $ $ *.J
T#Y+J
 d3i$&J
 67	J

 
J
X */ ,s s r    r$   )r   npaudio_utilsr   r   feature_extraction_utilsr   processing_utilsr   r   r	   tokenization_utils_baser
   utilsr   r   r   r_   
get_loggerr   rY   r   r$   __all__r   r    r!   <module>r      sv   "  G 4 H H 0 @ @  
		H	%$4E " tn t tn %
%r    