o
    pi2                     @  s  d Z ddlmZ ddlZddlZddlm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 ddlmZ ddlZeejd ZeeZeeZW d   n1 scw   Y  ed Ze di Z!e"e
 Z#ed Z$eee!dZ%ee%ddZ&ee&gdZ'e(e' e)e*Z+e+j,ddddZ-dCddZ.e+j,ddddZ/dDd"d#Z0e+j1d$g d%d&d'd(Z2			dEdFd1d2Z3d3ej4vre"ed4 5 ej4d3< dGd6d7Z6dHd9d:Z7dIdJd=d>Z8dKdAdBZ9e9e$ dS )Lat  OpenTelemetry metrics for tracking function usage.

Metrics can be enabled/disabled for the current python kernel:

>>> from pyannote.audio.telemetry.metrics import set_telemetry_metrics
>>> set_telemetry_metrics(True)   # enable
>>> set_telemetry_metrics(False)  # disable

To activate / deactivate globally:

>>> set_telemetry_metrics(True, save_choice_as_default=True)
    )annotationsN)Path)Any)uuid4)metrics)OTLPMetricExporter)MeterProvider)PeriodicExportingMetricReader)__version__zconfig.yamlotlp_endpointotlp_headerstelemetry_log_level)endpointheadersi`  )export_interval_millis)metric_readerszoss-model-initzNumber of model initializations1)namedescriptionunitmodel'Model'returnNonec                 C  s*   t  rtdt| ddttd dS dS )z
    Increment the model initialization counter.

    Parameters
    ----------
    model : Model
        Instantiated model
       _otel_originunknown)originversion
session_idN)is_metrics_enabledmodel_init_counteraddgetattrr
   
SESSION_ID)r    r%   T/home/ubuntu/.local/lib/python3.10/site-packages/pyannote/audio/telemetry/metrics.pytrack_model_init;   s   	
r'   zoss-pipeline-initz"Number of pipeline initializationspipeline
'Pipeline'c                 C  s4   t  rtdt| ddt| ddttd dS dS )z|
    Track pipeline initialization

    Parameters
    ----------
    pipeline : Pipeline
        Instantiated pipeline
    r   r   r   
_otel_name)r   r   r   r   N)r    pipeline_init_counterr"   r#   r
   r$   )r(   r%   r%   r&   track_pipeline_initW   s   	

r,   zoss-pipeline-apply)
         <   x   i,  iX  i  i  i   i@8  ip  iQ zDuration of file in secondss)r   #explicit_bucket_boundaries_advisoryr   r   file'AudioFile'num_speakers
int | Nonemin_speakersmax_speakerskwargsr   c           	      K  s   t  r>ddlm} | |}ddlm} ||||d\}}}t|t| ddt| ddt	t
||t|r7|ndd	 d
S d
S )ad  
    Track duration of files processed by pipelines

    Parameters
    ----------
    pipeline : Pipeline
        The pipeline being applied.
    file : AudioFile
        The audio file being processed by the pipeline.
    num_speakers, min_speakers, max_speakers : int, optional
        Requested number of speakers in the audio file, if applicable.
    r   )Audio)set_num_speakers)r6   r8   r9   r   r   r*   inf)r   r   r   r   r6   r8   r9   N)r    pyannote.audio.core.ior;   get_duration*pyannote.audio.pipelines.utils.diarizationr<   file_duration_bucketrecordr#   r
   r$   npisfinite)	r(   r4   r6   r8   r9   r:   r;   durationr<   r%   r%   r&   track_pipeline_apply   s*   

rF   PYANNOTE_METRICS_ENABLEDmetrics_enabledboolc                   C  s$   dt jvr	tdt jd  dkS )z
    Check if metrics are enabled.

    Returns
    -------
    bool
        True if metrics are enabled, False otherwise.
    rG   z9PYANNOTE_METRICS_ENABLED environment variable is not set.true)osenviron
ValueErrorlowerr%   r%   r%   r&   r       s   

r    enabledc                 C  sv   t t}t|}W d   n1 sw   Y  | |d< t td}t|| W d   dS 1 s4w   Y  dS )z
    Save metrics state to the configuration file.

    Parameters
    ----------
    enabled : bool
        Whether metrics should be enabled or disabled.
    NrH   w)openCONFIG_FILEyaml	safe_load	safe_dump)rO   fconfigr%   r%   r&   _save_metrics_config   s   
	"rX   Fsave_choice_as_defaultc                 C  s.   t | } t|  tjd< |rt|  dS dS )a  
    Enable or disable metrics globally.

    Parameters
    ----------
    enabled : bool
        Whether to enable or disable the metrics.
    save_choice_as_default : bool, optional
        If True, saves the state to the configuration file as the default value.
    rG   N)rI   strrN   rK   rL   rX   )rO   rY   r%   r%   r&   set_telemetry_metrics   s
   r[   levelrZ   c                 C  s`   d}|   } | |vrtdd| tt| }tjjjD ]}|dr-t	|
| qdS )ac  
    Set the log level for OpenTelemetry loggers to control error visibility.

    This can be used to suppress error messages when telemetry fails.

    Parameters
    ----------
    level : str
        The log level to set. Must be one of: 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'.

        - 'DEBUG': Show all messages including detailed debugging information
        - 'INFO': Show informational messages, warnings and errors
        - 'WARNING': Show only warnings and errors (default)
        - 'ERROR': Show only errors
        - 'CRITICAL': Show only critical errors

    Raises
    ------
    ValueError
        If the provided level is not a valid logging level.

    Examples
    --------
    To suppress most error messages:

    >>> set_opentelemetry_log_level('ERROR')

    To show all messages:

    >>> set_opentelemetry_log_level('DEBUG')
    )DEBUGINFOWARNINGERRORCRITICALzLog level must be one of: z, opentelemetryN)upperrM   joinr#   loggingrootmanager
loggerDict
startswith	getLoggersetLevel)r\   valid_levelslogging_levellogger_namer%   r%   r&   set_opentelemetry_log_level   s    

ro   )r   r   r   r   )r(   r)   r   r   )NNN)r(   r)   r4   r5   r6   r7   r8   r7   r9   r7   r:   r   r   r   )r   rI   )rO   rI   r   r   )F)rO   rI   rY   rI   r   r   )r\   rZ   r   r   ):__doc__
__future__r   re   rK   pathlibr   typingr   uuidr   rS   rb   r   6opentelemetry.exporter.otlp.proto.http.metric_exporterr   opentelemetry.sdk.metricsr    opentelemetry.sdk.metrics.exportr	   pyannote.audior
   numpyrC   __file__parentrR   rQ   config_file_streamrT   CONFIGOTLP_ENDPOINTgetOTLP_HEADERSrZ   r$   DEFAULT_LOG_LEVELexporterreaderproviderset_meter_provider	get_meter__name__metercreate_counterr!   r'   r+   r,   create_histogramrA   rF   rL   rN   r    rX   r[   ro   r%   r%   r%   r&   <module>   sp   






.


/