
    -cJj                         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
mZmZmZmZ d dlmZ d dlmZmZmZmZmZmZmZmZmZ defdZ G d d	e      Zy
)    )Path)ListOptional)	
CudaConfigEndpointConfigFeatureExtractorConfigHomophoneReplacerConfigOnlineCtcFstDecoderConfigOnlineLMConfigOnlineModelConfigOnlineNeMoCtcModelConfigOnlineParaformerModelConfig)OnlineRecognizer)	OnlineRecognizerConfigOnlineRecognizerResultOnlineStreamOnlineToneCtcModelConfigOnlineTransducerModelConfigOnlineWenetCtcModelConfigOnlineZipformer2CtcModelConfigProviderConfigTensorrtConfigfc                 J    t        |       j                         s
J |  d       y )Nz does not exist)r   is_file)r   s    g/Users/ahmed/devFolder/claude-voice/.venv/lib/python3.12/site-packages/sherpa_onnx/online_recognizer.py_assert_file_existsr      s"    7??3?33    c            f          e Zd ZdZe	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dSdededededededed	ed
edededededededededededededededededededededed ed!ed"ed#ed$ed%ed&ed'ed(ed)ed*ed+ed,ed-ed.ed/ed0ed1ed2ed3efdd4       Z	e	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dTdededededededededededed"eded ed!ed#ed/ed0ed1ef&d5       Z
e	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dUded6ededededededededed7ed8ed"eded ed!ed#ed/ed0ed1ef(d9       Ze	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dVded6ededededededededed"eded ed!ed#ed/ed0ed1ef$d:       Ze	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dTded6ededededededededed"eded ed!ed#ed/ed0ed1ef$d;       Ze	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dWded6ed<ed=ededededededededed"eded ed!ed#ed/ed0ed1ef(d>       ZdXd@ee   fdAZdBefdCZdDee   fdEZdBedFefdGZdBedFefdHZdBedFefdIZdBedFefdJZdBedFee   fdKZdBedFee   fdLZdBedFefdMZdBedFee   fdNZdBedFee   fdOZdBedFee   fdPZdBedFefdQZ dBedFefdRZ!y?)Yr   a  A class for streaming (online) speech recognition.

    It supports multiple model families via factory methods:

    - :meth:`from_transducer` -- Zipformer, Nemotron, etc.
    - :meth:`from_paraformer` -- Streaming Paraformer
    - :meth:`from_zipformer2_ctc` -- Zipformer2 CTC
    - :meth:`from_wenet_ctc` -- WeNet CTC

    Example using streaming Zipformer transducer::

        import numpy as np
        import sherpa_onnx

        recognizer = sherpa_onnx.OnlineRecognizer.from_transducer(
            tokens="./model/tokens.txt",
            encoder="./model/encoder-epoch-99-avg-1.int8.onnx",
            decoder="./model/decoder-epoch-99-avg-1.onnx",
            joiner="./model/joiner-epoch-99-avg-1.int8.onnx",
            num_threads=2,
            decoding_method="greedy_search",
            enable_endpoint_detection=True,
        )

        # Read audio (float32, normalized to [-1, 1])
        samples = read_audio("test.wav")  # your own function
        sample_rate = 16000

        stream = recognizer.create_stream()
        stream.accept_waveform(sample_rate, samples)

        # Add tail padding and signal end of input
        tail = np.zeros(int(0.5 * sample_rate), dtype=np.float32)
        stream.accept_waveform(sample_rate, tail)
        stream.input_finished()

        # Streaming decode loop
        while recognizer.is_ready(stream):
            recognizer.decode_stream(stream)

        result = recognizer.get_result_all(stream)
        print(result.text)

    Example with endpoint detection::

        stream = recognizer.create_stream()
        stream.accept_waveform(sample_rate, samples)

        while recognizer.is_ready(stream):
            recognizer.decode_stream(stream)

        if recognizer.is_endpoint(stream):
            result = recognizer.get_result_all(stream)
            print("Endpoint detected:", result.text)
            recognizer.reset(stream)  # reset for next utterance

    Please refer to the following files for more usages:

    - `<https://github.com/k2-fsa/sherpa-onnx/blob/master/python-api-examples/online-decode-files.py>`_
    - `<https://github.com/k2-fsa/sherpa-onnx/blob/master/python-api-examples/streaming-zipformer-rtf.py>`_
    tokensencoderdecoderjoinernum_threadssample_ratefeature_dimlow_freq	high_freqdithernormalize_samples
snip_edgesenable_endpoint_detectionrule1_min_trailing_silencerule2_min_trailing_silencerule3_min_utterance_lengthdecoding_methodmax_active_pathshotwords_scoreblank_penaltyhotwords_file
model_typemodeling_unit	bpe_vocablmlm_scalelm_shallow_fusiontemperature_scalereset_encoderdebug	rule_fsts	rule_farsproviderdevicecudnn_conv_algo_searchtrt_max_workspace_sizetrt_max_partition_iterationstrt_min_subgraph_sizetrt_fp16_enabletrt_detailed_build_logtrt_engine_cache_enabletrt_timing_cache_enabletrt_engine_cache_pathtrt_timing_cache_pathtrt_dump_subgraphshr_dict_dirhr_rule_fsts
hr_lexiconlodr_fst
lodr_scalec3                 h   | j                  |       }3t        |       t        |       t        |       t        |       t        |||      }4t        |#      }5t	        |$|%|&|'|(|)|*|+|,|-
      }6t        |6|5|!|"      }7t        |4|||7||||      }8t        ||||||	|
      }9t        |||      }:t        |      dkD  r|d	k7  rt        d
|       |r|d	k7  rt        d|       t        ||||1|2      };t        |9|8|;|:||||||||| |t        |.|0|/            }<t        |<      |3_        |<|3_        |3S )a  
        Please refer to
        `<https://k2-fsa.github.io/sherpa/onnx/pretrained_models/index.html>`_
        to download pre-trained models for different languages, e.g., Chinese,
        English, etc.

        Args:
          tokens:
            Path to ``tokens.txt``. Each line in ``tokens.txt`` contains two
            columns::

                symbol integer_id

          encoder:
            Path to ``encoder.onnx``.
          decoder:
            Path to ``decoder.onnx``.
          joiner:
            Path to ``joiner.onnx``.
          num_threads:
            Number of threads for neural network computation.
          sample_rate:
            Sample rate of the training data used to train the model.
          feature_dim:
            Dimension of the feature used to train the model.
          low_freq:
            Low cutoff frequency for mel bins in feature extraction.
          high_freq:
            High cutoff frequency for mel bins in feature extraction
            (if <= 0, offset from Nyquist)
          dither:
            Dithering constant (0.0 means no dither).
            By default the audio samples are in range [-1,+1],
            so dithering constant 0.00003 is a good value,
            equivalent to the default 1.0 from kaldi
          normalize_samples:
            True for +/- 1.0 range of audio samples (default, zipformer feats),
            False for +/- 32k samples (ebranchformer features).
          snip_edges:
            handling of end of audio signal in kaldi feature extraction.
            If true, end effects will be handled by outputting only frames that
            completely fit in the file, and the number of frames depends on the
            frame-length.  If false, the number of frames depends only on the
            frame-shift, and we reflect the data at the ends.
          enable_endpoint_detection:
            True to enable endpoint detection. False to disable endpoint
            detection.
          rule1_min_trailing_silence:
            Used only when enable_endpoint_detection is True. If the duration
            of trailing silence in seconds is larger than this value, we assume
            an endpoint is detected.
          rule2_min_trailing_silence:
            Used only when enable_endpoint_detection is True. If we have decoded
            something that is nonsilence and if the duration of trailing silence
            in seconds is larger than this value, we assume an endpoint is
            detected.
          rule3_min_utterance_length:
            Used only when enable_endpoint_detection is True. If the utterance
            length in seconds is larger than this value, we assume an endpoint
            is detected.
          decoding_method:
            Valid values are greedy_search, modified_beam_search.
          max_active_paths:
            Use only when decoding_method is modified_beam_search. It specifies
            the maximum number of active paths during beam search.
          blank_penalty:
            The penalty applied on blank symbol during decoding.
          hotwords_file:
            The file containing hotwords, one words/phrases per line, and for each
            phrase the bpe/cjkchar are separated by a space.
          hotwords_score:
            The hotword score of each token for biasing word/phrase. Used only if
            hotwords_file is given with modified_beam_search as decoding method.
          temperature_scale:
            Temperature scaling for output symbol confidence estimation.
            It affects only confidence values, the decoding uses the original
            logits without temperature.
          reset_encoder:
            True to reset `encoder_state` on an endpoint after empty segment.
            Done in `Reset()` method, after an endpoint was detected,
            currently only in `OnlineRecognizerTransducerImpl`.
          model_type:
            Online transducer model type. Valid values are: conformer, lstm,
            zipformer, zipformer2. All other values lead to loading the model twice.
          modeling_unit:
            The modeling unit of the model, commonly used units are bpe, cjkchar,
            cjkchar+bpe, etc. Currently, it is needed only when hotwords are
            provided, we need it to encode the hotwords into token sequence.
          bpe_vocab:
            The vocabulary generated by google's sentencepiece program.
            It is a file has two columns, one is the token, the other is
            the log probability, you can get it from the directory where
            your bpe model is generated. Only used when hotwords provided
            and the modeling unit is bpe or cjkchar+bpe.
          rule_fsts:
            If not empty, it specifies fsts for inverse text normalization.
            If there are multiple fsts, they are separated by a comma.
          rule_fars:
            If not empty, it specifies fst archives for inverse text normalization.
            If there are multiple archives, they are separated by a comma.
          provider:
            onnxruntime execution providers. Valid values are: cpu, cuda, coreml.
          device:
            onnxruntime cuda device index.
          cudnn_conv_algo_search:
            onxrt CuDNN convolution search algorithm selection. CUDA EP
          trt_max_workspace_size:
            Set TensorRT EP GPU memory usage limit. TensorRT EP
          trt_max_partition_iterations:
            Limit partitioning iterations for model conversion. TensorRT EP
          trt_min_subgraph_size:
            Set minimum size for subgraphs in partitioning. TensorRT EP
          trt_fp16_enable: bool = True,
            Enable FP16 precision for faster performance. TensorRT EP
          trt_detailed_build_log: bool = False,
            Enable detailed logging of build steps. TensorRT EP
          trt_engine_cache_enable: bool = True,
            Enable caching of TensorRT engines. TensorRT EP
          trt_timing_cache_enable: bool = True,
            "Enable use of timing cache to speed up builds." TensorRT EP
          trt_engine_cache_path: str ="",
            "Set path to store cached TensorRT engines." TensorRT EP
          trt_timing_cache_path: str ="",
            "Set path for storing timing cache." TensorRT EP
          trt_dump_subgraphs: bool = False,
            "Dump optimized subgraphs for debugging." TensorRT EP
          lodr_fst:
            Path to the LODR FST file in binary format. If empty, LODR is disabled.
          lodr_scale:
            Scale factor for LODR rescoring. Only used when lodr_fst is provided.
        )r!   r"   r#   )rB   )
rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   )
trt_configcuda_configr@   rA   )
transducerr    r$   provider_configr5   r6   r7   r=   )sampling_rater*   r+   r&   r'   r(   r)   r-   r.   r/   r   modified_beam_searchz_Please use --decoding-method=modified_beam_search when using --hotwords-file. Currently given: zTPlease use --decoding-method=modified_beam_search when using --lm. Currently given: )modelscaleshallow_fusionrP   rQ   dict_dirlexiconr>   )feat_configmodel_config	lm_configendpoint_configenable_endpointr0   r1   r2   r4   r3   r;   r>   r?   r<   hr)__new__r   r   r   r   r   r   r   r   len
ValueErrorr   r   r	   _Recognizer
recognizerconfig)=clsr    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   selftransducer_configrT   rS   rV   ra   r`   rc   rb   recognizer_configs=                                                                r   from_transducerz OnlineRecognizer.from_transducera   s   r {{3F#G$G$F#7
 !#9
 $#9)E"7+#9$;$;"7"71

 )!#	
 )(#+!'	
 -%/!#
 )'A'A'A
 }!o9O&O55D4EG 
 /%;;**9):< 
 #,!
	 3#%+5+-)''/'&$"&
, &&78'r   c                 b   | j                  |       }t        |       t        |       t        |       t        ||      }t        ||      }t	        ||||d|      }t        ||      }t        ||	|
      }t        |||||||t        |||            }t        |      |_
        ||_        |S )	a  
        Please refer to
        `<https://k2-fsa.github.io/sherpa/onnx/pretrained_models/index.html>`_
        to download pre-trained models for different languages, e.g., Chinese,
        English, etc.

        Args:
          tokens:
            Path to ``tokens.txt``. Each line in ``tokens.txt`` contains two
            columns::

                symbol integer_id

          encoder:
            Path to ``encoder.onnx``.
          decoder:
            Path to ``decoder.onnx``.
          num_threads:
            Number of threads for neural network computation.
          sample_rate:
            Sample rate of the training data used to train the model.
          feature_dim:
            Dimension of the feature used to train the model.
          enable_endpoint_detection:
            True to enable endpoint detection. False to disable endpoint
            detection.
          rule1_min_trailing_silence:
            Used only when enable_endpoint_detection is True. If the duration
            of trailing silence in seconds is larger than this value, we assume
            an endpoint is detected.
          rule2_min_trailing_silence:
            Used only when enable_endpoint_detection is True. If we have decoded
            something that is nonsilence and if the duration of trailing silence
            in seconds is larger than this value, we assume an endpoint is
            detected.
          rule3_min_utterance_length:
            Used only when enable_endpoint_detection is True. If the utterance
            length in seconds is larger than this value, we assume an endpoint
            is detected.
          decoding_method:
            The only valid value is greedy_search.
          provider:
            onnxruntime execution providers. Valid values are: cpu, cuda, coreml.
          rule_fsts:
            If not empty, it specifies fsts for inverse text normalization.
            If there are multiple fsts, they are separated by a comma.
          rule_fars:
            If not empty, it specifies fst archives for inverse text normalization.
            If there are multiple archives, they are separated by a comma.
          device:
            onnxruntime cuda device index.
        )r!   r"   r@   rA   
paraformer)rs   r    r$   rV   r5   r=   rW   r&   rX   r]   r`   ra   rc   rd   r0   r>   r?   re   )rf   r   r   r   r   r   r   r   r	   ri   rj   rk   )rl   r    r!   r"   r$   r%   r&   r,   r-   r.   r/   r0   r@   r=   r>   r?   rA   rM   rN   rO   rm   paraformer_configrV   ra   r`   rc   ro   s                              r   from_paraformerz OnlineRecognizer.from_paraformer  s    V {{3F#G$G$7

 )

 )(#+#
 -%#

 )'A'A'A
 3#%+5+&$"&
 &&78'r   rZ   	ctc_graphctc_max_activec                 d   | j                  |       }t        |       t        |       t        |      }t        ||      }t	        |||||      }t        ||      }t        |||	      }t        ||      }t        ||||||
||t        |||      	      }t        |      |_        ||_        |S )	a	  
        Please refer to
        `<https://k2-fsa.github.io/sherpa/onnx/pretrained_models/online-ctc/index.html>`_
        to download pre-trained models for different languages, e.g., Chinese,
        English, etc.

        Args:
          tokens:
            Path to ``tokens.txt``. Each line in ``tokens.txt`` contains two
            columns::

                symbol integer_id

          model:
            Path to ``model.onnx``.
          num_threads:
            Number of threads for neural network computation.
          sample_rate:
            Sample rate of the training data used to train the model.
          feature_dim:
            Dimension of the feature used to train the model.
          enable_endpoint_detection:
            True to enable endpoint detection. False to disable endpoint
            detection.
          rule1_min_trailing_silence:
            Used only when enable_endpoint_detection is True. If the duration
            of trailing silence in seconds is larger than this value, we assume
            an endpoint is detected.
          rule2_min_trailing_silence:
            Used only when enable_endpoint_detection is True. If we have decoded
            something that is nonsilence and if the duration of trailing silence
            in seconds is larger than this value, we assume an endpoint is
            detected.
          rule3_min_utterance_length:
            Used only when enable_endpoint_detection is True. If the utterance
            length in seconds is larger than this value, we assume an endpoint
            is detected.
          decoding_method:
            The only valid value is greedy_search.
          ctc_graph:
            If not empty, decoding_method is ignored. It contains the path to
            H.fst, HL.fst, or HLG.fst
          ctc_max_active:
            Used only when ctc_graph is not empty. It specifies the maximum
            active paths at a time.
          provider:
            onnxruntime execution providers. Valid values are: cpu, cuda, coreml.
          rule_fsts:
            If not empty, it specifies fsts for inverse text normalization.
            If there are multiple fsts, they are separated by a comma.
          rule_fars:
            If not empty, it specifies fst archives for inverse text normalization.
            If there are multiple archives, they are separated by a comma.
          device:
            onnxruntime cuda device index.
        rZ   rr   )zipformer2_ctcr    r$   rV   r=   rt   rX   )graph
max_activer]   )	r`   ra   rc   ctc_fst_decoder_configrd   r0   r>   r?   re   )rf   r   r   r   r   r   r   r
   r   r	   ri   rj   rk   )rl   r    rZ   r$   r%   r&   r,   r-   r.   r/   r0   rx   ry   r@   r=   r>   r?   rA   rM   rN   rO   rm   zipformer2_ctc_configrV   ra   r`   rc   r   ro   s                                r   from_zipformer2_ctcz$OnlineRecognizer.from_zipformer2_ctc  s    ` {{3F#E" >U K(

 )0#+
 -%#

 )'A'A'A
 ";%"

 3#%+#95+&$"&
  &&78'r   c                 H   | j                  |       }t        |       t        |       t        |      }t        ||      }t	        |||||      }t        ||      }t        |||	      }t        |||||
||t        |||            }t        |      |_
        ||_        |S ){  
        Please refer to
        `<https://github.com/k2-fsa/sherpa-onnx/releases/tag/asr-models>`_
        to download pre-trained models.

        Args:
          tokens:
            Path to ``tokens.txt``. Each line in ``tokens.txt`` contains two
            columns::

                symbol integer_id

          model:
            Path to ``model.onnx``.
          num_threads:
            Number of threads for neural network computation.
          sample_rate:
            Sample rate of the training data used to train the model.
          feature_dim:
            Dimension of the feature used to train the model.
          enable_endpoint_detection:
            True to enable endpoint detection. False to disable endpoint
            detection.
          rule1_min_trailing_silence:
            Used only when enable_endpoint_detection is True. If the duration
            of trailing silence in seconds is larger than this value, we assume
            an endpoint is detected.
          rule2_min_trailing_silence:
            Used only when enable_endpoint_detection is True. If we have decoded
            something that is nonsilence and if the duration of trailing silence
            in seconds is larger than this value, we assume an endpoint is
            detected.
          rule3_min_utterance_length:
            Used only when enable_endpoint_detection is True. If the utterance
            length in seconds is larger than this value, we assume an endpoint
            is detected.
          decoding_method:
            The only valid value is greedy_search.
          provider:
            onnxruntime execution providers. Valid values are: cpu, cuda, coreml.
          debug:
            True to show meta data in the model.
          rule_fsts:
            If not empty, it specifies fsts for inverse text normalization.
            If there are multiple fsts, they are separated by a comma.
          rule_fars:
            If not empty, it specifies fst archives for inverse text normalization.
            If there are multiple archives, they are separated by a comma.
          device:
            onnxruntime cuda device index.
        r{   rr   )	t_one_ctcr    r$   rV   r=   rt   rX   r]   ru   )rf   r   r   r   r   r   r   r   r	   ri   rj   rk   )rl   r    rZ   r$   r%   r&   r,   r-   r.   r/   r0   r@   r=   r>   r?   rA   rM   rN   rO   rm   t_one_ctc_configrV   ra   r`   rc   ro   s                             r   from_t_one_ctczOnlineRecognizer.from_t_one_ctc  s    R {{3F#E"3
 )

 )&#+
 -%#

 )'A'A'A
 3#%+5+&$"&
 &&78'r   c                 H   | j                  |       }t        |       t        |       t        |      }t        ||      }t	        |||||      }t        ||      }t        |||	      }t        |||||
||t        |||            }t        |      |_
        ||_        |S )r   r{   rr   )nemo_ctcr    r$   rV   r=   rt   rX   r]   ru   )rf   r   r   r   r   r   r   r   r	   ri   rj   rk   )rl   r    rZ   r$   r%   r&   r,   r-   r.   r/   r0   r@   r=   r>   r?   rA   rM   rN   rO   rm   nemo_ctc_configrV   ra   r`   rc   ro   s                             r   from_nemo_ctczOnlineRecognizer.from_nemo_ctc  s    R {{3F#E"2
 )

 )$#+
 -%#

 )'A'A'A
 3#%+5+&$"&
 &&78'r   
chunk_sizenum_left_chunksc                 L   | j                  |       }t        |       t        |       t        |||      }t        ||      }t	        |||||      }t        ||      }t        |	|
|      }t        |||||||t        |||            }t        |      |_
        ||_        |S )a	  
        Please refer to
        `<https://k2-fsa.github.io/sherpa/onnx/pretrained_models/wenet/index.html>`_
        to download pre-trained models for different languages, e.g., Chinese,
        English, etc.

        Args:
          tokens:
            Path to ``tokens.txt``. Each line in ``tokens.txt`` contains two
            columns::

                symbol integer_id

          model:
            Path to ``model.onnx``.
          chunk_size:
            The --chunk-size parameter from WeNet.
          num_left_chunks:
            The --num-left-chunks parameter from WeNet.
          num_threads:
            Number of threads for neural network computation.
          sample_rate:
            Sample rate of the training data used to train the model.
          feature_dim:
            Dimension of the feature used to train the model.
          enable_endpoint_detection:
            True to enable endpoint detection. False to disable endpoint
            detection.
          rule1_min_trailing_silence:
            Used only when enable_endpoint_detection is True. If the duration
            of trailing silence in seconds is larger than this value, we assume
            an endpoint is detected.
          rule2_min_trailing_silence:
            Used only when enable_endpoint_detection is True. If we have decoded
            something that is nonsilence and if the duration of trailing silence
            in seconds is larger than this value, we assume an endpoint is
            detected.
          rule3_min_utterance_length:
            Used only when enable_endpoint_detection is True. If the utterance
            length in seconds is larger than this value, we assume an endpoint
            is detected.
          decoding_method:
            The only valid value is greedy_search.
          provider:
            onnxruntime execution providers. Valid values are: cpu, cuda, coreml.
          rule_fsts:
            If not empty, it specifies fsts for inverse text normalization.
            If there are multiple fsts, they are separated by a comma.
          rule_fars:
            If not empty, it specifies fst archives for inverse text normalization.
            If there are multiple archives, they are separated by a comma.
          device:
            onnxruntime cuda device index.
        )rZ   r   r   rr   )	wenet_ctcr    r$   rV   r=   rt   rX   r]   ru   )rf   r   r   r   r   r   r   r   r	   ri   rj   rk   )rl   r    rZ   r   r   r$   r%   r&   r,   r-   r.   r/   r0   r@   r=   r>   r?   rA   rM   rN   rO   rm   wenet_ctc_configrV   ra   r`   rc   ro   s                               r   from_wenet_ctczOnlineRecognizer.from_wenet_ctc  s    \ {{3F#E"4!+
 )

 )&#+
 -%#

 )'A'A'A
 3#%+5+&$"&
 &&78'r   Nhotwordsc                 p    || j                   j                         S | j                   j                  |      S )aS  Create a new online stream for streaming recognition.

        Args:
          hotwords:
            Optional hotwords string. Each word/phrase is separated by a
            space, and the tokens within a phrase are separated by the
            modeling unit separator.

        Returns:
          A new ``OnlineStream`` instance.
        )rj   create_stream)rm   r   s     r   r   zOnlineRecognizer.create_stream
  s2     ??0022??00::r   sc                 :    | j                   j                  |       y)zzRun one decoding step on a single stream.

        Args:
          s:
            The ``OnlineStream`` to decode.
        N)rj   decode_streamrm   r   s     r   r   zOnlineRecognizer.decode_stream  s     	%%a(r   ssc                 :    | j                   j                  |       y)zRun one decoding step on multiple streams in parallel.

        Args:
          ss:
            A list of ``OnlineStream`` instances to decode.
        N)rj   decode_streams)rm   r   s     r   r   zOnlineRecognizer.decode_streams$  s     	&&r*r   returnc                 8    | j                   j                  |      S )zCheck whether the stream has enough data for decoding.

        Args:
          s:
            The ``OnlineStream`` to check.

        Returns:
          True if there is enough data to run one decoding step.
        )rj   is_readyr   s     r   r   zOnlineRecognizer.is_ready-  s     ''**r   c                 8    | j                   j                  |      S )zGet the full recognition result object for a stream.

        Args:
          s:
            The ``OnlineStream`` to query.

        Returns:
          An ``OnlineRecognizerResult`` containing text, tokens, timestamps,
          and other fields.
        )rj   
get_resultr   s     r   get_result_allzOnlineRecognizer.get_result_all9  s     ))!,,r   c                 h    | j                   j                  |      j                  j                         S )zGet the recognition result as a plain string.

        Args:
          s:
            The ``OnlineStream`` to query.

        Returns:
          The recognized text with leading/trailing whitespace removed.
        )rj   r   textstripr   s     r   r   zOnlineRecognizer.get_resultF  s(     ))!,117799r   c                 T    | j                   j                  |      j                         S )zGet the recognition result as a JSON string.

        Args:
          s:
            The ``OnlineStream`` to query.

        Returns:
          A JSON-encoded string representing the recognition result.
        )rj   r   as_json_stringr   s     r   get_result_as_json_stringz*OnlineRecognizer.get_result_as_json_stringR  s"     ))!,;;==r   c                 L    | j                   j                  |      j                  S )zGet the list of recognized tokens for a stream.

        Args:
          s:
            The ``OnlineStream`` to query.

        Returns:
          A list of token strings from the recognition result.
        )rj   r   r    r   s     r   r    zOnlineRecognizer.tokens^  s     ))!,333r   c                 L    | j                   j                  |      j                  S )a  Get the timestamps of each recognized token.

        Args:
          s:
            The ``OnlineStream`` to query.

        Returns:
          A list of floats where each element is the time in seconds of the
          corresponding token from :meth:`tokens`.
        )rj   r   
timestampsr   s     r   r   zOnlineRecognizer.timestampsj  s     ))!,777r   c                 L    | j                   j                  |      j                  S )zGet the start time of the current segment.

        Args:
          s:
            The ``OnlineStream`` to query.

        Returns:
          The start time in seconds for the current recognition segment.
        )rj   r   
start_timer   s     r   r   zOnlineRecognizer.start_timew  s     ))!,777r   c                 L    | j                   j                  |      j                  S )zGet the output log probabilities for each recognized token.

        Args:
          s:
            The ``OnlineStream`` to query.

        Returns:
          A list of log-probability values, one per token from
          :meth:`tokens`.
        )rj   r   ys_probsr   s     r   r   zOnlineRecognizer.ys_probs       ))!,555r   c                 L    | j                   j                  |      j                  S )a  Get the language model log probabilities for each recognized token.

        Args:
          s:
            The ``OnlineStream`` to query.

        Returns:
          A list of LM log-probability values, one per token from
          :meth:`tokens`.
        )rj   r   lm_probsr   s     r   r   zOnlineRecognizer.lm_probs  r   r   c                 L    | j                   j                  |      j                  S )zGet the context biasing scores for each recognized token.

        Args:
          s:
            The ``OnlineStream`` to query.

        Returns:
          A list of context scores, one per token from :meth:`tokens`.
        )rj   r   context_scoresr   s     r   r   zOnlineRecognizer.context_scores  s     ))!,;;;r   c                 8    | j                   j                  |      S )zCheck whether an endpoint has been detected for the stream.

        Args:
          s:
            The ``OnlineStream`` to check.

        Returns:
          True if an endpoint (e.g. trailing silence) is detected.
        )rj   is_endpointr   s     r   r   zOnlineRecognizer.is_endpoint  s     **1--r   c                 8    | j                   j                  |      S )a<  Reset the stream state after an endpoint is detected.

        Call this after :meth:`is_endpoint` returns True to prepare the
        stream for the next utterance.

        Args:
          s:
            The ``OnlineStream`` to reset.

        Returns:
          True if the stream was successfully reset.
        )rj   resetr   s     r   r   zOnlineRecognizer.reset  s     $$Q''r   ).   >  P         4@g      y        TFF333333@333333?r   greedy_search   g      ?r    r   cjkcharr   r   g?Tg       @FFr   r   cpur      i
      TFTTr   r   Fr   r   r   r   r   )r   r   r   Fr   r   r   r   r   Fr   r   r   r   r   r   )r   r   r   Fr   r   r   r   r   i  r   Fr   r   r   r   r   r   )r   i@  r   Fr   r   r   r   r   Fr   r   r   r   r   r   )   r   r   r   r   Fr   r   r   r   r   Fr   r   r   r   r   r   )N)"__name__
__module____qualname____doc__classmethodstrintfloatboolrp   rw   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r   r   r   r   r   r   r    r   r   r   r   "   s	   <|  "!"& */,/,/,0. ! #"&"&#&#&'&0,.%& $',(,(,%'%'#(gcc c 	c
 c c c c c c c  c c $(c %*c  %*!c" %*#c$ %c& 'c( )c* +c, -c. /c0 1c2 3c4 5c6 7c8  9c: !;c< =c> ?c@ AcB CcD EcF GcH !$IcJ !$KcL '*McN  #OcP QcR !%ScT "&UcV "&WcX  #YcZ  #[c\ !]c^ _c` acb ccd ecf gc cJ	  "*/,/,/,0.)~~ ~ 	~
 ~ ~ ~ $(~ %*~ %*~ %*~ ~ ~ ~ ~  !~" #~$ %~& '~( )~ ~@ 
 "*/,/,/,0."+DD D 	D
 D D $(D %*D %*D %*D D D D D D  !D" #D$ %D& 'D( )D* +D DL 
 !*/,/,/,0.'yy y 	y
 y y $(y %*y %*y %*y y y y y y  !y" #y$ %y& 'y yv 
 "*/,/,/,0.'yy y 	y
 y y $(y %*y %*y %*y y y y y y  !y" #y$ %y& 'y yv 
  "*/,/,/,0.+@@ @ 	@
 @ @ @ @ $(@ %*@ %*@ %*@ @ @ @  !@" #@$ %@& '@( )@* +@ @D;hsm ;")| )+l!3 +
+, 
+4 
+- -1G -
:L 
:S 
:
>< 
>C 
>
4 
4c 
48L 8T%[ 8
8L 
8U 
86, 64; 66, 64; 6
< 
<e 
<
.\ 
.d 
.(| ( (r   r   N)pathlibr   typingr   r   sherpa_onnx.lib._sherpa_onnxr   r   r   r	   r
   r   r   r   r   r   ri   r   r   r   r   r   r   r   r   r   r   r   objectr   r   r   <module>r      sI     !
 
 
 I
 
 
43 4`(v `(r   