
    ^jg3                         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
)GlmAsrProcessorKwargspaddingTi>  
max_length)sampling_ratereturn_attention_maskr   ptleft)return_tensorspadding_side)text_kwargsaudio_kwargscommon_kwargsN)__name__
__module____qualname__	_defaults     w/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/glmasr/processing_glmasr.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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 )GlmAsrProcessorNc                     || _         |j                  |      | _        || _        || _        t
        |   |||       y)a  
        audio_token (`Optional[str]`, *optional*, defaults to `"<|pad|>`"):
            Special token used to represent audio inputs in the chat template.
        default_transcription_prompt (`str`, *optional*, defaults to `"Please transcribe this audio into text"`):
            Default prompt to use for transcription tasks when applying transcription requests.
        max_audio_len (`int`, *optional*, defaults to 655):
            Maximum length of audio sequences in seconds. Audio longer than this will be truncated.
            655 gives approximately 8192 tokens, corresponding to the maximum sequence length of the text model.
        )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GlmAsrProcessor.__init__;   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GlmAsrProcessor.__call__S   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GlmAsrProcessor.validate_inputss   se     	Ae$A&A 1c$i3u:6MtCI;jUDabcc 7N 1r    c                 d    d}dD ]  \  }}}|d|z  z   |dz
  z
  dz
  |z  dz   } ||z
  |z  dz   }|S )N   ))   r   rJ   )rJ   r      rK   rJ   r   )r.   audio_lengthsmerge_factorr   kernel_sizestride
num_tokenss          r!   _get_audio_token_lengthz'GlmAsrProcessor._get_audio_token_length~   sc    ,B 	`(G[&*Q[8K!OLqPU[[^__M	` $l2|CaG
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   rJ   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sumrQ   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srL   audio_replacementsidxreplacement_texts                       r!   _process_audiozGlmAsrProcessor._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rr   rW   c                 0    |d   |   }| j                   |z  S )NrV   )r'   )r.   rr   rW   rV   s       r!   rf   z#GlmAsrProcessor.replace_audio_token   s%    '(:;IF"222r    c                      t         |   dgz   S )NrT   )r,   model_input_names)r.   r1   s    r!   rz   z!GlmAsrProcessor.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`rV   r   )r.   s    r!   unused_input_namesz"GlmAsrProcessor.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t        |
t              rd	|
d
nd	|
d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 [`~GlmAsrProcessor.apply_chat_template`] (for example
                `text_kwargs`, `audio_kwargs`, ...).

        Returns:
            [`BatchFeature`]: Processor outputs ready to be passed to [`GlmAsrForConditionalGeneration.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`.userr3   )typepath)r   r3   r2   )r   r2   )rolecontentT)tokenizeadd_generation_promptreturn_dict)listr   r   
isinstancerb   TensordetachcpunumpyrG   r?   r*   strtupler^   	TypeErrorzipapply_chat_template)r.   r3   r}   r5   audio_itemsel
batch_sizepromptsitemprompt_text
audio_itemconversationss               r!   apply_transcription_requestz+GlmAsrProcessor.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GlmAsrProcessor.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GlmAsrProcessor.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.rU   rK   r   >   "'rJ   )strip
startswithrG   endswith)r.   r2   strippedprefixs       r!   r   z2GlmAsrProcessor._strip_assistant_prefix_and_quotes  s    
 ::<
 	F
 ""6*#CKM288:	 S!}**,Hx=A(1+""=(1+Q[B["~++-Hr    )Nz<|pad|>z&Please transcribe this audio into texti  )NF)NN)rL   torch.Tensorr6   r   )N)r   r   r   r   valid_processor_kwargsr-   r   r
   r   r   boolr	   r   r@   r   rF   rQ   rw   dictrX   r   rf   propertyrz   r|   r   r   r   r   __classcell__)r1   s   @r!   r$   r$   7   s   2 %MT0  $(%*	A$y/)A D A d{	A
 ./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
 ./	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   rb   
get_loggerr   r\   r   r$   __all__r   r    r!   <module>r      sv   ,  G 4 H H 0 @ @  
		H	%,E " xn x xv 
r    