<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Output routines for audio and analysis"""

import csv

import numpy as np
import scipy
import scipy.io.wavfile

import librosa.core
from . import util


def annotation(path, intervals, annotations=None, delimiter=',', fmt='%0.3f'):
    r'''Save annotations in a 3-column format::

        intervals[0, 0],intervals[0, 1],annotations[0]\n
        intervals[1, 0],intervals[1, 1],annotations[1]\n
        intervals[2, 0],intervals[2, 1],annotations[2]\n
        ...

    This can be used for segment or chord annotations.

    :usage:
        >>> # Detect segment boundaries
        >>> boundaries = librosa.segment.agglomerative(data, k=10)
        >>> # Convert to time
        >>> boundary_times = librosa.frames_to_time(boundaries, sr=sr,
                                                    hop_length=hop_length)
        >>> # Make some fake annotations
        >>> labels = ['Seg #{:03d}'.format(i) for i in range(len(time_start))]
        >>> # Save the output
        >>> librosa.output.annotation('segments.csv', boundary_times,
                                      annotations=annotations)

    :parameters:
      - path : str
          path to save the output CSV file

      - intervals : np.ndarray [shape=(n, 2)]
          array of interval start and end-times.

          - ``intervals[i, 0]`` marks the start time of interval ``i``

          - ``intervals[i, 1]`` marks the endtime of interval ``i``

      - annotations : None or list-like [shape=(n,)]
          optional list of annotation strings. ``annotations[i]`` applies
          to the time range ``intervals[i, 0]`` to ``intervals[i, 1]``

      - delimiter : str
          character to separate fields

      - fmt : str
          format-string for rendering time data

    :raises:
      - ValueError
          if ``annotations`` is not ``None`` and length does
          not match ``intervals``
    '''

    if annotations is not None and len(annotations) != len(intervals):
        raise ValueError('len(annotations) != len(intervals)')

    with open(path, 'w') as output_file:
        writer = csv.writer(output_file, delimiter=delimiter)

        if annotations is None:
            for t_int in intervals:
                writer.writerow([fmt % t_int[0], fmt % t_int[1]])
        else:
            for t_int, lab in zip(intervals, annotations):
                writer.writerow([fmt % t_int[0], fmt % t_int[1], lab])


def frames_csv(path, frames, sr=22050, hop_length=512, **kwargs):
    """Convert frames to time and store tbrycehe output in CSV format.

    :usage:
        >>> y, sr = librosa.load(librosa.util.example_audio_file())
        >>> tempo, beats = librosa.beat.beat_track(y, sr=sr, hop_length=64)
        >>> librosa.output.frames_csv('beat_times.csv', frames,
                                      sr=sr, hop_length=64)

    :parameters:
      - path : string
          path to save the output CSV file

      - frames : list-like of ints
          list of frame numbers for beat events

      - sr : int > 0 [scalar]
          audio sampling rate

      - hop_length : int > 0 [scalar]
          number of samples between success frames

      - *kwargs*
          additional keyword arguments.  See :func:`librosa.output.times_csv`
    """

    times = librosa.frames_to_time(frames, sr=sr, hop_length=hop_length)

    times_csv(path, times, **kwargs)

<commit_msg>cleaned up examples in output #136<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Output routines for audio and analysis"""

import csv

import numpy as np
import scipy
import scipy.io.wavfile

import librosa.core
from . import util


def annotation(path, intervals, annotations=None, delimiter=',', fmt='%0.3f'):
    r'''Save annotations in a 3-column format::

        intervals[0, 0],intervals[0, 1],annotations[0]\n
        intervals[1, 0],intervals[1, 1],annotations[1]\n
        intervals[2, 0],intervals[2, 1],annotations[2]\n
        ...

    This can be used for segment or chord annotations.

    :usage:
        >>> y, sr = librosa.load(librosa.util.example_audio_file())
        >>> data = librosa.feature.mfcc(y=y, sr=sr, hop_length=512)
        >>> # Detect segment boundaries
        >>> boundaries = librosa.segment.agglomerative(data, k=10)
        >>> # Convert to time
        >>> boundary_times = librosa.frames_to_time(boundaries, sr=sr,
                                                    hop_length=512)
        >>> # Make some fake annotations
        >>> labels = ['Seg #{:03d}'.format(i) for i in range(len(time_start))]
        >>> # Save the output
        >>> librosa.output.annotation('segments.csv', boundary_times,
                                      annotations=annotations)

    :parameters:
      - path : str
          path to save the output CSV file

      - intervals : np.ndarray [shape=(n, 2)]
          array of interval start and end-times.

          - ``intervals[i, 0]`` marks the start time of interval ``i``

          - ``intervals[i, 1]`` marks the endtime of interval ``i``

      - annotations : None or list-like [shape=(n,)]
          optional list of annotation strings. ``annotations[i]`` applies
          to the time range ``intervals[i, 0]`` to ``intervals[i, 1]``

      - delimiter : str
          character to separate fields

      - fmt : str
          format-string for rendering time data

    :raises:
      - ValueError
          if ``annotations`` is not ``None`` and length does
          not match ``intervals``
    '''

    if annotations is not None and len(annotations) != len(intervals):
        raise ValueError('len(annotations) != len(intervals)')

    with open(path, 'w') as output_file:
        writer = csv.writer(output_file, delimiter=delimiter)

        if annotations is None:
            for t_int in intervals:
                writer.writerow([fmt % t_int[0], fmt % t_int[1]])
        else:
            for t_int, lab in zip(intervals, annotations):
                writer.writerow([fmt % t_int[0], fmt % t_int[1], lab])


def frames_csv(path, frames, sr=22050, hop_length=512, **kwargs):
    """Convert frames to time and store tbrycehe output in CSV format.

    :usage:
        >>> y, sr = librosa.load(librosa.util.example_audio_file())
        >>> tempo, beats = librosa.beat.beat_track(y, sr=sr, hop_length=64)
        >>> librosa.output.frames_csv('beat_times.csv', beats,
                                      sr=sr, hop_length=64)

    :parameters:
      - path : string
          path to save the output CSV file

      - frames : list-like of ints
          list of frame numbers for beat events

      - sr : int > 0 [scalar]
          audio sampling rate

      - hop_length : int > 0 [scalar]
          number of samples between success frames

      - *kwargs*
          additional keyword arguments.  See :func:`librosa.output.times_csv`
    """

    times = librosa.frames_to_time(frames, sr=sr, hop_length=hop_length)

    times_csv(path, times, **kwargs)


{'fraction_non_alphanumeric': 0.12152332049636286, 'fraction_numerical': 0.014405933533019541, 'mean_word_length': 2.261395348837209, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 79, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7174745', 'n_tokens_mistral': 2178, 'n_tokens_neox': 2023, 'n_words': 600}