analyzeAudio 0.0.16__py3-none-any.whl → 0.0.17__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,7 @@
1
1
  """Analyzers that use the filename of an audio file to analyze its audio data."""
2
+ # ruff: noqa: D103
3
+ from analyzeAudio import cacheAudioAnalyzers, registrationAudioAspect
2
4
  from analyzeAudio.pythonator import pythonizeFFprobe
3
- from analyzeAudio import registrationAudioAspect, cacheAudioAnalyzers
4
5
  from os import PathLike
5
6
  from statistics import mean
6
7
  from typing import Any, cast
@@ -12,22 +13,31 @@ import subprocess
12
13
 
13
14
  @registrationAudioAspect('SI-SDR mean')
14
15
  def getSI_SDRmean(pathFilenameAlpha: str | PathLike[Any], pathFilenameBeta: str | PathLike[Any]) -> float | None:
15
- """
16
- Calculate the mean Scale-Invariant Signal-to-Distortion Ratio (SI-SDR) between two audio files.
17
- This function uses FFmpeg to compute the SI-SDR between two audio files specified by their paths.
18
- The SI-SDR values are extracted from the FFmpeg output and their mean is calculated.
19
- Parameters:
20
- pathFilenameAlpha: Path to the first audio file.
21
- pathFilenameBeta: Path to the second audio file.
22
- Returns:
23
- SI_SDRmean: The mean SI-SDR value in decibels (dB).
24
- Raises:
25
- subprocess.CalledProcessError: If the FFmpeg command fails.
26
- ValueError: If no SI-SDR values are found in the FFmpeg output.
16
+ """Calculate the mean Scale-Invariant Signal-to-Distortion Ratio (SI-SDR) between two audio files.
17
+
18
+ Parameters
19
+ ----------
20
+ pathFilenameAlpha : str | PathLike[Any]
21
+ Path to the first audio file.
22
+ pathFilenameBeta : str | PathLike[Any]
23
+ Path to the second audio file.
24
+
25
+ Returns
26
+ -------
27
+ SI_SDRmean : float | None
28
+ The mean SI-SDR value in decibels (dB).
29
+
30
+ Raises
31
+ ------
32
+ subprocess.CalledProcessError
33
+ If the FFmpeg command fails.
34
+ ValueError
35
+ If no SI-SDR values are found in the FFmpeg output.
36
+
27
37
  """
28
38
  commandLineFFmpeg = [
29
39
  'ffmpeg', '-hide_banner', '-loglevel', '32',
30
- '-i', f'{str(pathlib.Path(pathFilenameAlpha))}', '-i', f'{str(pathlib.Path(pathFilenameBeta))}',
40
+ '-i', f'{str(pathlib.Path(pathFilenameAlpha))}', '-i', f'{str(pathlib.Path(pathFilenameBeta))}', # noqa: RUF010
31
41
  '-filter_complex', '[0][1]asisdr', '-f', 'null', '-'
32
42
  ]
33
43
  systemProcessFFmpeg = subprocess.run(commandLineFFmpeg, check=True, stderr=subprocess.PIPE)
@@ -37,8 +47,7 @@ def getSI_SDRmean(pathFilenameAlpha: str | PathLike[Any], pathFilenameBeta: str
37
47
  regexSI_SDR = regex.compile(r"^\[Parsed_asisdr_.* (.*) dB", regex.MULTILINE)
38
48
 
39
49
  listMatchesSI_SDR = regexSI_SDR.findall(stderrFFmpeg)
40
- SI_SDRmean = mean(float(match) for match in listMatchesSI_SDR)
41
- return SI_SDRmean
50
+ return mean(float(match) for match in listMatchesSI_SDR)
42
51
 
43
52
  @cachetools.cached(cache=cacheAudioAnalyzers)
44
53
  def ffprobeShotgunAndCache(pathFilename: str | PathLike[Any]) -> dict[str, float]:
@@ -67,16 +76,16 @@ def ffprobeShotgunAndCache(pathFilename: str | PathLike[Any]) -> dict[str, float
67
76
  dictionaryAspectsAnalyzed: dict[str, float] = {}
68
77
  if 'aspectralstats' in FFprobeStructured:
69
78
  for keyName in FFprobeStructured['aspectralstats']:
70
- # No matter how many channels, each keyName is `numpy.ndarray[tuple[int, int], numpy.dtype[numpy.float64]]`
71
- # where `tuple[int, int]` is (channel, frame)
72
- # NOTE (as of this writing) `registrar` can only understand the generic class `numpy.ndarray` and not more specific typing
73
- # dictionaryAspectsAnalyzed[keyName] = FFprobeStructured['aspectralstats'][keyName]
79
+ """No matter how many channels, each keyName is `numpy.ndarray[tuple[int, int], numpy.dtype[numpy.float64]]`
80
+ where `tuple[int, int]` is (channel, frame)
81
+ NOTE (as of this writing) `registrar` can only understand the generic class `numpy.ndarray` and not more specific typing
82
+ dictionaryAspectsAnalyzed[keyName] = FFprobeStructured['aspectralstats'][keyName]"""
74
83
  dictionaryAspectsAnalyzed[keyName] = numpy.mean(FFprobeStructured['aspectralstats'][keyName]).astype(float)
75
84
  if 'r128' in FFprobeStructured:
76
85
  for keyName in FFprobeStructured['r128']:
77
86
  dictionaryAspectsAnalyzed[keyName] = FFprobeStructured['r128'][keyName][-1]
78
87
  if 'astats' in FFprobeStructured:
79
- for keyName, arrayFeatureValues in cast(dict[str, numpy.ndarray[Any, Any]], FFprobeStructured['astats']).items():
88
+ for keyName, arrayFeatureValues in cast('dict[str, numpy.ndarray[Any, Any]]', FFprobeStructured['astats']).items():
80
89
  dictionaryAspectsAnalyzed[keyName.split('.')[-1]] = numpy.mean(arrayFeatureValues[..., -1:None]).astype(float)
81
90
 
82
91
  return dictionaryAspectsAnalyzed
@@ -187,7 +196,6 @@ def analyzeRolloff(pathFilename: str | PathLike[Any]) -> float | None:
187
196
 
188
197
  @registrationAudioAspect('Abs_Peak_count')
189
198
  def analyzeAbs_Peak_count(pathFilename: str | PathLike[Any]) -> float | None:
190
- print('Abs_Peak_count', pathFilename)
191
199
  return ffprobeShotgunAndCache(pathFilename).get('Abs_Peak_count')
192
200
 
193
201
  @registrationAudioAspect('Bit_depth')
@@ -1,30 +1,31 @@
1
1
  """Analyzers that use the spectrogram to analyze audio data."""
2
- from analyzeAudio import registrationAudioAspect, audioAspects, cacheAudioAnalyzers
2
+ # ruff: noqa: D103
3
+ from analyzeAudio import audioAspects, cacheAudioAnalyzers, registrationAudioAspect
4
+ from numpy import dtype, floating
3
5
  from typing import Any
4
6
  import cachetools
5
7
  import librosa
6
8
  import numpy
7
- from numpy import dtype, floating
8
9
 
9
10
  @registrationAudioAspect('Chromagram')
10
11
  def analyzeChromagram(spectrogramPower: numpy.ndarray[Any, dtype[floating[Any]]], sampleRate: int, **keywordArguments: Any) -> numpy.ndarray: # pyright: ignore [reportMissingTypeArgument, reportUnknownParameterType]
11
- return librosa.feature.chroma_stft(S=spectrogramPower, sr=sampleRate, **keywordArguments) # type: ignore
12
+ return librosa.feature.chroma_stft(S=spectrogramPower, sr=sampleRate, **keywordArguments) # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType]
12
13
 
13
14
  @registrationAudioAspect('Spectral Contrast')
14
15
  def analyzeSpectralContrast(spectrogramMagnitude: numpy.ndarray[Any, dtype[floating[Any]]], **keywordArguments: Any) -> numpy.ndarray: # pyright: ignore [reportMissingTypeArgument, reportUnknownParameterType]
15
- return librosa.feature.spectral_contrast(S=spectrogramMagnitude, **keywordArguments) # type: ignore
16
+ return librosa.feature.spectral_contrast(S=spectrogramMagnitude, **keywordArguments) # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType]
16
17
 
17
18
  @registrationAudioAspect('Spectral Bandwidth')
18
19
  def analyzeSpectralBandwidth(spectrogramMagnitude: numpy.ndarray[Any, dtype[floating[Any]]], **keywordArguments: Any) -> numpy.ndarray: # pyright: ignore [reportMissingTypeArgument, reportUnknownParameterType]
19
20
  centroid = audioAspects['Spectral Centroid']['analyzer'](spectrogramMagnitude)
20
- return librosa.feature.spectral_bandwidth(S=spectrogramMagnitude, centroid=centroid, **keywordArguments) # type: ignore
21
+ return librosa.feature.spectral_bandwidth(S=spectrogramMagnitude, centroid=centroid, **keywordArguments) # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType]
21
22
 
22
23
  @cachetools.cached(cache=cacheAudioAnalyzers)
23
24
  @registrationAudioAspect('Spectral Centroid')
24
25
  def analyzeSpectralCentroid(spectrogramMagnitude: numpy.ndarray[Any, dtype[floating[Any]]], **keywordArguments: Any) -> numpy.ndarray: # pyright: ignore [reportMissingTypeArgument, reportUnknownParameterType]
25
- return librosa.feature.spectral_centroid(S=spectrogramMagnitude, **keywordArguments) # type: ignore
26
+ return librosa.feature.spectral_centroid(S=spectrogramMagnitude, **keywordArguments) # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType]
26
27
 
27
28
  @registrationAudioAspect('Spectral Flatness')
28
29
  def analyzeSpectralFlatness(spectrogramMagnitude: numpy.ndarray[Any, dtype[floating[Any]]], **keywordArguments: Any) -> numpy.ndarray: # pyright: ignore [reportMissingTypeArgument, reportUnknownParameterType]
29
- spectralFlatness: numpy.ndarray[tuple[int, ...], numpy.dtype[numpy.floating[Any]]] = librosa.feature.spectral_flatness(S=spectrogramMagnitude, **keywordArguments) # type: ignore
30
+ spectralFlatness: numpy.ndarray[tuple[int, ...], numpy.dtype[numpy.floating[Any]]] = librosa.feature.spectral_flatness(S=spectrogramMagnitude, **keywordArguments) # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType]
30
31
  return 20 * numpy.log10(spectralFlatness, where=(spectralFlatness != 0)) # dB
@@ -6,6 +6,6 @@ import numpy
6
6
  import torch
7
7
 
8
8
  @registrationAudioAspect('SRMR')
9
- def analyzeSRMR(tensorAudio: torch.Tensor, sampleRate: int, pytorchOnCPU: bool | None, **keywordArguments: Any) -> numpy.ndarray: # pyright: ignore [reportMissingTypeArgument, reportUnknownParameterType]
9
+ def analyzeSRMR(tensorAudio: torch.Tensor, sampleRate: int, pytorchOnCPU: bool | None, **keywordArguments: Any) -> numpy.ndarray: # pyright: ignore [reportMissingTypeArgument, reportUnknownParameterType] # noqa: D103, FBT001
10
10
  keywordArguments['fast'] = keywordArguments.get('fast') or pytorchOnCPU or None
11
- return torch.Tensor.numpy(speech_reverberation_modulation_energy_ratio(tensorAudio, sampleRate, **keywordArguments)) # type: ignore
11
+ return torch.Tensor.numpy(speech_reverberation_modulation_energy_ratio(tensorAudio, sampleRate, **keywordArguments)) # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType]
@@ -1,26 +1,27 @@
1
1
  """Analyzers that use the waveform of audio data."""
2
- from analyzeAudio import registrationAudioAspect, audioAspects, cacheAudioAnalyzers
2
+ # ruff: noqa: D103
3
+ from analyzeAudio import audioAspects, cacheAudioAnalyzers, registrationAudioAspect
3
4
  from typing import Any
5
+ import cachetools
4
6
  import librosa
5
7
  import numpy
6
- import cachetools
7
8
 
8
9
  @cachetools.cached(cache=cacheAudioAnalyzers)
9
10
  @registrationAudioAspect('Tempogram')
10
11
  def analyzeTempogram(waveform: numpy.ndarray[tuple[int, ...], numpy.dtype[numpy.floating[Any]]], sampleRate: int, **keywordArguments: Any) -> numpy.ndarray: # pyright: ignore [reportMissingTypeArgument, reportUnknownParameterType]
11
- return librosa.feature.tempogram(y=waveform, sr=sampleRate, **keywordArguments) # type: ignore
12
+ return librosa.feature.tempogram(y=waveform, sr=sampleRate, **keywordArguments) # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType]
12
13
 
13
14
  # "RMS value from audio samples is faster ... However, ... spectrogram ... more accurate ... because ... windowed"
14
15
  @registrationAudioAspect('RMS from waveform')
15
16
  def analyzeRMS(waveform: numpy.ndarray[tuple[int, ...], numpy.dtype[numpy.floating[Any]]], **keywordArguments: Any) -> numpy.ndarray: # pyright: ignore [reportMissingTypeArgument, reportUnknownParameterType]
16
- arrayRMS: numpy.ndarray[tuple[int, ...], numpy.dtype[numpy.floating[Any]]] = librosa.feature.rms(y=waveform, **keywordArguments) # type: ignore
17
+ arrayRMS: numpy.ndarray[tuple[int, ...], numpy.dtype[numpy.floating[Any]]] = librosa.feature.rms(y=waveform, **keywordArguments) # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType]
17
18
  return 20 * numpy.log10(arrayRMS, where=(arrayRMS != 0)) # dB
18
19
 
19
20
  @registrationAudioAspect('Tempo')
20
21
  def analyzeTempo(waveform: numpy.ndarray[tuple[int, ...], numpy.dtype[numpy.floating[Any]]], sampleRate: int, **keywordArguments: Any) -> numpy.ndarray: # pyright: ignore [reportMissingTypeArgument, reportUnknownParameterType]
21
22
  tempogram = audioAspects['Tempogram']['analyzer'](waveform, sampleRate)
22
- return librosa.feature.tempo(y=waveform, sr=sampleRate, tg=tempogram, **keywordArguments) # type: ignore
23
+ return librosa.feature.tempo(y=waveform, sr=sampleRate, tg=tempogram, **keywordArguments) # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType]
23
24
 
24
25
  @registrationAudioAspect('Zero-crossing rate') # This is distinct from 'Zero-crossings rate'
25
26
  def analyzeZeroCrossingRate(waveform: numpy.ndarray[tuple[int, ...], numpy.dtype[numpy.floating[Any]]], **keywordArguments: Any) -> numpy.ndarray: # pyright: ignore [reportMissingTypeArgument, reportUnknownParameterType]
26
- return librosa.feature.zero_crossing_rate(y=waveform, **keywordArguments) # type: ignore
27
+ return librosa.feature.zero_crossing_rate(y=waveform, **keywordArguments) # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType]
@@ -1,10 +1,14 @@
1
- from collections.abc import Callable, Sequence
2
- from concurrent.futures import ProcessPoolExecutor, as_completed
1
+ from collections.abc import Callable, Sequence # noqa: D100
2
+ from concurrent.futures import as_completed, ProcessPoolExecutor
3
+ from hunterMakesPy import defineConcurrencyLimit, oopsieKwargsie
4
+ from multiprocessing import set_start_method as multiprocessing_set_start_method
3
5
  from numpy.typing import NDArray
4
6
  from os import PathLike
5
- from typing import Any, cast, ParamSpec, TypeAlias, TYPE_CHECKING, TypeVar
6
- from Z0Z_tools import defineConcurrencyLimit, oopsieKwargsie, stft, Spectrogram
7
+ from typing import Any, cast, ParamSpec, TypeAlias, TypeVar
8
+ from typing_extensions import TypedDict
9
+ from Z0Z_tools import Spectrogram, stft
7
10
  import cachetools
11
+ import contextlib
8
12
  import inspect
9
13
  import numpy
10
14
  import pathlib
@@ -12,16 +16,8 @@ import soundfile
12
16
  import torch
13
17
  import warnings
14
18
 
15
- if TYPE_CHECKING:
16
- from typing import TypedDict
17
- else:
18
- TypedDict = dict
19
-
20
- from multiprocessing import set_start_method as multiprocessing_set_start_method
21
- try:
19
+ with contextlib.suppress(RuntimeError):
22
20
  multiprocessing_set_start_method('spawn')
23
- except RuntimeError:
24
- pass
25
21
 
26
22
  warnings.filterwarnings('ignore', category=UserWarning, module='torchmetrics', message='.*fast=True.*')
27
23
 
@@ -29,48 +25,57 @@ parameterSpecifications = ParamSpec('parameterSpecifications')
29
25
  typeReturned = TypeVar('typeReturned')
30
26
 
31
27
  audioAspect: TypeAlias = str
32
- class analyzersAudioAspects(TypedDict):
28
+
29
+ class analyzersAudioAspects(TypedDict): # noqa: D101
33
30
  analyzer: Callable[..., Any]
34
31
  analyzerParameters: list[str]
35
32
 
33
+
36
34
  audioAspects: dict[audioAspect, analyzersAudioAspects] = {}
37
35
  """A register of 1) measurable aspects of audio data, 2) analyzer functions to measure audio aspects, 3) and parameters of analyzer functions."""
38
36
 
39
37
  def registrationAudioAspect(aspectName: str) -> Callable[[Callable[parameterSpecifications, typeReturned]], Callable[parameterSpecifications, typeReturned]]:
40
- """
41
- A function to "decorate" a registrant-analyzer function and the aspect of audio data it can analyze.
38
+ """'Decorate' a registrant-analyzer function and the aspect of audio data it can analyze.
39
+
40
+ Parameters
41
+ ----------
42
+ aspectName : str
43
+ The audio aspect that the registrar will enter into the register, `audioAspects`.
42
44
 
43
- Parameters:
44
- aspectName: The audio aspect that the registrar will enter into the register, `audioAspects`.
45
45
  """
46
46
 
47
47
  def registrar(registrant: Callable[parameterSpecifications, typeReturned]) -> Callable[parameterSpecifications, typeReturned]:
48
48
  """
49
49
  `registrar` updates the registry, `audioAspects`, with 1) the analyzer function, `registrant`, 2) the analyzer function's parameters, and 3) the aspect of audio data that the analyzer function measures.
50
50
 
51
- Parameters:
52
- registrant: The function that analyzes an aspect of audio data.
51
+ Parameters
52
+ ----------
53
+ registrant : Callable
54
+ The function that analyzes an aspect of audio data.
55
+
56
+ Note
57
+ ----
58
+ `registrar` does not change the behavior of `registrant`, the analyzer function.
53
59
 
54
- Note:
55
- `registrar` does not change the behavior of `registrant`, the analyzer function.
56
60
  """
57
61
  audioAspects[aspectName] = {
58
62
  'analyzer': registrant,
59
63
  'analyzerParameters': inspect.getfullargspec(registrant).args
60
64
  }
61
65
 
62
- # if registrant.__annotations__.get('return') is not None and issubclass(registrant.__annotations__['return'], subclassTarget): # maybe someday I will understand why this doesn't work
63
- # if registrant.__annotations__.get('return') is not None and issubclass(registrant.__annotations__.get('return', type(None)), subclassTarget): # maybe someday I will understand why this doesn't work
64
66
  if isinstance(registrant.__annotations__.get('return', type(None)), type) and issubclass(registrant.__annotations__.get('return', type(None)), numpy.ndarray): # maybe someday I will understand what all of this statement means
65
67
  def registrationAudioAspectMean(*arguments: parameterSpecifications.args, **keywordArguments: parameterSpecifications.kwargs) -> numpy.floating[Any]:
66
68
  """
67
69
  `registrar` updates the registry with a new analyzer function that calculates the mean of the analyzer's numpy.ndarray result.
68
70
 
69
- Returns:
70
- mean: Mean value of the analyzer's numpy.ndarray result.
71
+ Returns
72
+ -------
73
+ mean : float
74
+ Mean value of the analyzer's numpy.ndarray result.
75
+
71
76
  """
72
77
  aspectValue = registrant(*arguments, **keywordArguments)
73
- return numpy.mean(cast(NDArray[Any], aspectValue))
78
+ return numpy.mean(cast('NDArray[Any]', aspectValue))
74
79
  # return aspectValue.mean()
75
80
  audioAspects[f"{aspectName} mean"] = {
76
81
  'analyzer': registrationAudioAspectMean,
@@ -83,15 +88,21 @@ def analyzeAudioFile(pathFilename: str | PathLike[Any], listAspectNames: list[st
83
88
  """
84
89
  Analyzes an audio file for specified aspects and returns the results.
85
90
 
86
- Parameters:
87
- pathFilename: The path to the audio file to be analyzed.
88
- listAspectNames: A list of aspect names to analyze in the audio file.
91
+ Parameters
92
+ ----------
93
+ pathFilename : str or PathLike
94
+ The path to the audio file to be analyzed.
95
+ listAspectNames : list of str
96
+ A list of aspect names to analyze in the audio file.
97
+
98
+ Returns
99
+ -------
100
+ listAspectValues : list of (str or float or NDArray)
101
+ A list of analyzed values in the same order as `listAspectNames`.
89
102
 
90
- Returns:
91
- listAspectValues: A list of analyzed values in the same order as `listAspectNames`.
92
103
  """
93
104
  pathlib.Path(pathFilename).stat() # raises FileNotFoundError if the file does not exist
94
- dictionaryAspectsAnalyzed: dict[str, str | float | NDArray[Any]] = {aspectName: 'not found' for aspectName in listAspectNames}
105
+ dictionaryAspectsAnalyzed: dict[str, str | float | NDArray[Any]] = dict.fromkeys(listAspectNames, 'not found')
95
106
  """Despite returning a list, use a dictionary to preserve the order of the listAspectNames.
96
107
  Similarly, 'not found' ensures the returned list length == len(listAspectNames)"""
97
108
 
@@ -104,20 +115,20 @@ def analyzeAudioFile(pathFilename: str | PathLike[Any], listAspectNames: list[st
104
115
  tryAgain = True
105
116
  while tryAgain:
106
117
  try:
107
- tensorAudio = torch.from_numpy(waveform) # memory-sharing
118
+ tensorAudio = torch.from_numpy(waveform) # pyright: ignore[reportUnknownMemberType] # memory-sharing # noqa: F841
108
119
  tryAgain = False
109
- except RuntimeError as ERRORmessage:
120
+ except RuntimeError as ERRORmessage: # noqa: PERF203
110
121
  if 'negative stride' in str(ERRORmessage):
111
122
  waveform = waveform.copy() # not memory-sharing
112
123
  tryAgain = True
113
124
  else:
114
- raise ERRORmessage
125
+ raise ERRORmessage # noqa: TRY201
115
126
 
116
127
  spectrogram = stft(waveform, sampleRate=sampleRate)
117
128
  spectrogramMagnitude = numpy.absolute(spectrogram)
118
- spectrogramPower = spectrogramMagnitude ** 2
129
+ spectrogramPower = spectrogramMagnitude ** 2 # noqa: F841
119
130
 
120
- pytorchOnCPU = not torch.cuda.is_available() # False if GPU available, True if not
131
+ pytorchOnCPU = not torch.cuda.is_available() # False if GPU available, True if not # noqa: F841
121
132
 
122
133
  for aspectName in listAspectNames:
123
134
  if aspectName in audioAspects:
@@ -127,18 +138,23 @@ def analyzeAudioFile(pathFilename: str | PathLike[Any], listAspectNames: list[st
127
138
 
128
139
  return [dictionaryAspectsAnalyzed[aspectName] for aspectName in listAspectNames]
129
140
 
130
- def analyzeAudioListPathFilenames(listPathFilenames: Sequence[str] | Sequence[PathLike[Any]], listAspectNames: list[str], CPUlimit: int | float | bool | None = None) -> list[list[str | float | NDArray[Any]]]:
141
+ def analyzeAudioListPathFilenames(listPathFilenames: Sequence[str] | Sequence[PathLike[Any]], listAspectNames: list[str], CPUlimit: int | float | bool | None = None) -> list[list[str | float | NDArray[Any]]]: # noqa: FBT001, PYI041
131
142
  """
132
143
  Analyzes a list of audio files for specified aspects of the individual files and returns the results.
133
144
 
134
- Parameters:
135
- listPathFilenames: A list of paths to the audio files to be analyzed.
136
- listAspectNames: A list of aspect names to analyze in each audio file.
137
- CPUlimit (gluttonous resource usage): whether and how to limit the CPU usage. See notes for details.
145
+ Parameters
146
+ ----------
147
+ listPathFilenames : Sequence of str or PathLike
148
+ A list of paths to the audio files to be analyzed.
149
+ listAspectNames : list of str
150
+ A list of aspect names to analyze in each audio file.
151
+ CPUlimit : int, float, bool, or None, default=None
152
+ Whether and how to limit the CPU usage. See notes for details.
138
153
 
139
- Returns:
140
- rowsListFilenameAspectValues: A list of lists, where each inner list contains the filename and
141
- analyzed values corresponding to the specified aspects, which are in the same order as `listAspectNames`.
154
+ Returns
155
+ -------
156
+ rowsListFilenameAspectValues : list of list of (str or float or NDArray)
157
+ A list of lists, where each inner list contains the filename and analyzed values corresponding to the specified aspects, which are in the same order as `listAspectNames`.
142
158
 
143
159
  You can save the data with `Z0Z_tools.dataTabularTOpathFilenameDelimited()`.
144
160
  For example,
@@ -166,7 +182,7 @@ def analyzeAudioListPathFilenames(listPathFilenames: Sequence[str] | Sequence[Pa
166
182
 
167
183
  if not (CPUlimit is None or isinstance(CPUlimit, (bool, int, float))):
168
184
  CPUlimit = oopsieKwargsie(CPUlimit)
169
- max_workers = defineConcurrencyLimit(CPUlimit)
185
+ max_workers = defineConcurrencyLimit(limit=CPUlimit)
170
186
 
171
187
  with ProcessPoolExecutor(max_workers=max_workers) as concurrencyManager:
172
188
  dictionaryConcurrency = {concurrencyManager.submit(analyzeAudioFile, pathFilename, listAspectNames)
@@ -177,18 +193,20 @@ def analyzeAudioListPathFilenames(listPathFilenames: Sequence[str] | Sequence[Pa
177
193
  cacheAudioAnalyzers.pop(dictionaryConcurrency[claimTicket], None)
178
194
  listAspectValues = claimTicket.result()
179
195
  rowsListFilenameAspectValues.append(
180
- [str(pathlib.PurePath(dictionaryConcurrency[claimTicket]).as_posix())]
196
+ [str(pathlib.PurePath(dictionaryConcurrency[claimTicket]).as_posix())] # noqa: RUF005
181
197
  + listAspectValues)
182
198
 
183
199
  return rowsListFilenameAspectValues
184
200
 
185
201
  def getListAvailableAudioAspects() -> list[str]:
186
202
  """
187
- Returns a sorted list of audio aspect names. All valid values for the parameter `listAspectNames`, for example,
188
- are returned by this function.
203
+ Return a sorted list of audio aspect names. All valid values for the parameter `listAspectNames`, for example, are returned by this function.
204
+
205
+ Returns
206
+ -------
207
+ listAvailableAudioAspects : list of str
208
+ The list of aspect names registered in `audioAspects`.
189
209
 
190
- Returns:
191
- listAvailableAudioAspects: The list of aspect names registered in `audioAspects`.
192
210
  """
193
211
  return sorted(audioAspects.keys())
194
212
 
@@ -1,4 +1,5 @@
1
1
  """Convert FFprobe output to a standardized Python object."""
2
+ # ruff: noqa: D103
2
3
  from collections import defaultdict
3
4
  from typing import Any, cast, NamedTuple
4
5
  import json
@@ -12,11 +13,11 @@ import numpy
12
13
  # NOTE You changed the code because a static type checker was mad at you. Ask yourself,
13
14
  # "Are you the tool or is the type checker the tool?"
14
15
 
15
- class Blackdetect(NamedTuple):
16
+ class Blackdetect(NamedTuple): # noqa: D101
16
17
  black_start: float | None = None
17
18
  black_end: float | None = None
18
19
 
19
- def pythonizeFFprobe(FFprobeJSON_utf8: str):
20
+ def pythonizeFFprobe(FFprobeJSON_utf8: str) -> tuple[defaultdict[str, Any] | dict[str, Any], dict[str, numpy.ndarray[Any, Any] | dict[str, numpy.ndarray[Any, Any]]]]: # noqa: C901, PLR0912, PLR0915
20
21
  FFroot: dict[str, Any] = json.loads(FFprobeJSON_utf8)
21
22
  Z0Z_dictionaries: dict[str, numpy.ndarray[Any, Any] | dict[str, numpy.ndarray[Any, Any]]] = {}
22
23
  if 'packets_and_frames' in FFroot: # Divide into 'packets' and 'frames'
@@ -26,7 +27,8 @@ def pythonizeFFprobe(FFprobeJSON_utf8: str):
26
27
  FFroot[section := packetOrFrame['type'] + 's'].append(packetOrFrame)
27
28
  del FFroot[section][-1]['type']
28
29
  else:
29
- raise ValueError("'packets_and_frames' for the win!")
30
+ msg = "'packets_and_frames' for the win!"
31
+ raise ValueError(msg)
30
32
  del FFroot['packets_and_frames']
31
33
 
32
34
  Z0Z_register = [
@@ -38,16 +40,16 @@ def pythonizeFFprobe(FFprobeJSON_utf8: str):
38
40
  leftCrumbs = False
39
41
  if 'frames' in FFroot:
40
42
  leftCrumbs = False
41
- # listTuplesBlackdetect = [] # uncommentToFixBlackdetect
43
+ # listTuplesBlackdetect = [] # uncommentToFixBlackdetect # noqa: ERA001
42
44
  listTuplesBlackdetect: list[Blackdetect] = []
43
45
  for indexFrame, FFframe in enumerate(FFroot['frames']):
44
46
  if 'tags' in FFframe:
45
47
  if 'lavfi.black_start' in FFframe['tags']:
46
- # listTuplesBlackdetect.append(float(FFframe['tags']['lavfi.black_start'])) # uncommentToFixBlackdetect
48
+ # listTuplesBlackdetect.append(float(FFframe['tags']['lavfi.black_start'])) # uncommentToFixBlackdetect # noqa: ERA001
47
49
  listTuplesBlackdetect.append(Blackdetect(black_start=float(FFframe['tags']['lavfi.black_start'])))
48
50
  del FFframe['tags']['lavfi.black_start']
49
51
  if 'lavfi.black_end' in FFframe['tags']:
50
- # listTuplesBlackdetect[-1] = (listTuplesBlackdetect[-1], float(FFframe['tags']['lavfi.black_end'])) # uncommentToFixBlackdetect
52
+ # listTuplesBlackdetect[-1] = (listTuplesBlackdetect[-1], float(FFframe['tags']['lavfi.black_end'])) # uncommentToFixBlackdetect # noqa: ERA001
51
53
  tupleBlackdetectLast = listTuplesBlackdetect.pop() if listTuplesBlackdetect else Blackdetect()
52
54
  match tupleBlackdetectLast.black_end:
53
55
  case None:
@@ -89,15 +91,15 @@ def pythonizeFFprobe(FFprobeJSON_utf8: str):
89
91
  if registrant not in Z0Z_dictionaries:
90
92
  Z0Z_dictionaries[registrant] = {}
91
93
  elif statistic not in Z0Z_dictionaries[registrant]:
92
- # NOTE (as of this writing) `registrar` can only understand the generic class `numpy.ndarray` and not more specific typing
93
- valueSherpa = cast(numpy.ndarray, numpy.zeros((channel, len(FFroot['frames'])))) # type: ignore
94
+ # NOTE (as of this writing) `registrar` can only understand the generic class `numpy.ndarray` and not more specific typing # noqa: ERA001
95
+ valueSherpa = cast('numpy.ndarray', numpy.zeros((channel, len(FFroot['frames'])))) # pyright: ignore[reportMissingTypeArgument, reportUnknownVariableType]
94
96
  Z0Z_dictionaries[registrant][statistic] = valueSherpa
95
97
  else:
96
98
  raise # Re-raise the exception
97
99
  except IndexError:
98
100
  if channel > Z0Z_dictionaries[registrant][statistic].shape[0]:
99
101
  Z0Z_dictionaries[registrant][statistic] = numpy.resize(Z0Z_dictionaries[registrant][statistic], (channel, len(FFroot['frames'])))
100
- # Z0Z_dictionaries[registrant][statistic].resize((channel, len(FFroot['frames'])))
102
+ # Z0Z_dictionaries[registrant][statistic].resize((channel, len(FFroot['frames']))) # noqa: ERA001
101
103
  else:
102
104
  raise # Re-raise the exception
103
105
 
@@ -106,7 +108,7 @@ def pythonizeFFprobe(FFprobeJSON_utf8: str):
106
108
  if FFframe:
107
109
  leftCrumbs = True
108
110
  if listTuplesBlackdetect:
109
- # 2025-03-06: I am _shocked_ that I was able to create a numpy structured array whenever it was that I originally wrote this code.
111
+ # 2025-03-06 I am _shocked_ that I was able to create a numpy structured array whenever it was when I originally wrote this code.
110
112
  arrayBlackdetect = numpy.array(
111
113
  [(
112
114
  -1.0 if detect.black_start is None else detect.black_start,
@@ -116,7 +118,7 @@ def pythonizeFFprobe(FFprobeJSON_utf8: str):
116
118
  copy=False
117
119
  )
118
120
  Z0Z_dictionaries['blackdetect'] = arrayBlackdetect
119
- # Z0Z_dictionaries['blackdetect'] = numpy.array(listTuplesBlackdetect, dtype=[('black_start', numpy.float32), ('black_end', numpy.float32)], copy=False) # uncommentToFixBlackdetect
121
+ # Z0Z_dictionaries['blackdetect'] = numpy.array(listTuplesBlackdetect, dtype=[('black_start', numpy.float32), ('black_end', numpy.float32)], copy=False) # uncommentToFixBlackdetect # noqa: ERA001
120
122
  if not leftCrumbs:
121
123
  del FFroot['frames']
122
124
  return FFroot, Z0Z_dictionaries
@@ -1,20 +1,21 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: analyzeAudio
3
- Version: 0.0.16
3
+ Version: 0.0.17
4
4
  Summary: Measure one or more aspects of one or more audio files.
5
5
  Author-email: Hunter Hogan <HunterHogan@pm.me>
6
6
  License: CC-BY-NC-4.0
7
7
  Project-URL: Donate, https://www.patreon.com/integrated
8
8
  Project-URL: Homepage, https://github.com/hunterhogan/analyzeAudio
9
+ Project-URL: Issues, https://github.com/hunterhogan/
9
10
  Project-URL: Repository, https://github.com/hunterhogan/analyzeAudio.git
10
- Keywords: audio,analysis,measurement,metrics,torch,spectrum,spectral,waveform,loudness,LUFS,RMS,FFmpeg,FFprobe,SRMR,audio-analysis,signal-processing
11
+ Keywords: FFmpeg,FFprobe,LUFS,RMS,SRMR,analysis,audio,audio-analysis,loudness,measurement,metrics,signal-processing,spectral,spectrum,torch,waveform
11
12
  Classifier: Development Status :: 3 - Alpha
12
13
  Classifier: Environment :: Console
13
14
  Classifier: Intended Audience :: Developers
14
15
  Classifier: Intended Audience :: End Users/Desktop
15
- Classifier: Intended Audience :: Science/Research
16
16
  Classifier: Intended Audience :: Information Technology
17
17
  Classifier: Intended Audience :: Other Audience
18
+ Classifier: Intended Audience :: Science/Research
18
19
  Classifier: Natural Language :: English
19
20
  Classifier: Operating System :: OS Independent
20
21
  Classifier: Programming Language :: Python
@@ -32,7 +33,9 @@ Classifier: Typing :: Typed
32
33
  Requires-Python: >=3.10
33
34
  Description-Content-Type: text/markdown
34
35
  License-File: LICENSE
36
+ Requires-Dist: Z0Z_tools
35
37
  Requires-Dist: cachetools
38
+ Requires-Dist: hunterMakesPy
36
39
  Requires-Dist: librosa
37
40
  Requires-Dist: numpy
38
41
  Requires-Dist: standard-aifc; python_version >= "3.13"
@@ -40,7 +43,7 @@ Requires-Dist: standard-sunau; python_version >= "3.13"
40
43
  Requires-Dist: torch
41
44
  Requires-Dist: torchmetrics[audio]
42
45
  Requires-Dist: tqdm
43
- Requires-Dist: Z0Z_tools
46
+ Requires-Dist: typing_extensions
44
47
  Provides-Extra: testing
45
48
  Requires-Dist: pytest; extra == "testing"
46
49
  Requires-Dist: pytest-cov; extra == "testing"
@@ -0,0 +1,17 @@
1
+ analyzeAudio/__init__.py,sha256=2D5JMeZfLGnwyQvt4Q2-HCsShHulcNXBM_Wu9vZPCiI,437
2
+ analyzeAudio/analyzersUseFilename.py,sha256=NShXm8XMHI1QsgitgrLq0hHjyWKzaOdxvRKlBc2XZec,10894
3
+ analyzeAudio/analyzersUseSpectrogram.py,sha256=k1mNzpzXykBIhE3NeizvSwVdfuKQtE_eIpHAR-Bya-I,2640
4
+ analyzeAudio/analyzersUseTensor.py,sha256=Uqf8haZDCQYjHFb_7Ybpm40_QNlKYyh-N1QifiLOeb4,779
5
+ analyzeAudio/analyzersUseWaveform.py,sha256=wfTkASR_2Uj3KpMI8UYQXWuKG4CqDIbhe9B6UgPrpyU,2282
6
+ analyzeAudio/audioAspectsRegistry.py,sha256=hvAAqS4FvJuNnLqBL0Hd813iF87HQ-TfZUdyWLqSA_A,8642
7
+ analyzeAudio/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ analyzeAudio/pythonator.py,sha256=fy8uduDQexYJMUQX0uNZHwPEX5sDH_3600W9hvPjZuo,6036
9
+ analyzeaudio-0.0.17.dist-info/licenses/LICENSE,sha256=NxH5Y8BdC-gNU-WSMwim3uMbID2iNDXJz7fHtuTdXhk,19346
10
+ tests/conftest.py,sha256=BhZswOjkl_u-qiS4Zy38d2fETdWAtZiigeuXYBK8l0k,397
11
+ tests/test_audioAspectsRegistry.py,sha256=-TWTLMdAn6IFv7ZdFWrBm1KxpLBa3Mz1sCygAwxV6gE,27
12
+ tests/test_other.py,sha256=ozabc_DFX5mAeSw3r01hQ8OEMNvbYdToKivSHoDxmG0,535
13
+ analyzeaudio-0.0.17.dist-info/METADATA,sha256=DAMobI3GMlYhlHefL2IpN1gu1CNVnx9TT_8xKNwT_Q0,9293
14
+ analyzeaudio-0.0.17.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
15
+ analyzeaudio-0.0.17.dist-info/entry_points.txt,sha256=FHgSx7fndtZ6SnQ-nWVXf0NB59exaHQ2DtatTK9KrLg,100
16
+ analyzeaudio-0.0.17.dist-info/top_level.txt,sha256=QV8LQ0r_1LIQuewxDcEzODpykv5qRYG3I70piOUSVRg,19
17
+ analyzeaudio-0.0.17.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (80.8.0)
2
+ Generator: setuptools (80.9.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
tests/test_other.py CHANGED
@@ -1,10 +1,11 @@
1
+ from collections.abc import Callable
2
+ from hunterMakesPy.pytestForYourUse import PytestFor_defineConcurrencyLimit, PytestFor_oopsieKwargsie
1
3
  import pytest
2
- from Z0Z_tools.pytestForYourUse import PytestFor_defineConcurrencyLimit, PytestFor_oopsieKwargsie
3
4
 
4
5
  @pytest.mark.parametrize("nameOfTest,callablePytest", PytestFor_defineConcurrencyLimit())
5
- def testConcurrencyLimit(nameOfTest, callablePytest):
6
+ def testConcurrencyLimit(nameOfTest: str, callablePytest: Callable[[], None]) -> None:
6
7
  callablePytest()
7
8
 
8
9
  @pytest.mark.parametrize("nameOfTest,callablePytest", PytestFor_oopsieKwargsie())
9
- def testOopsieKwargsie(nameOfTest, callablePytest):
10
+ def testOopsieKwargsie(nameOfTest: str, callablePytest: Callable[[], None]) -> None:
10
11
  callablePytest()
@@ -1,17 +0,0 @@
1
- analyzeAudio/__init__.py,sha256=2D5JMeZfLGnwyQvt4Q2-HCsShHulcNXBM_Wu9vZPCiI,437
2
- analyzeAudio/analyzersUseFilename.py,sha256=AOA_Ab6-QU4q4i7AOy9Z68yPiGBi-Zjpo4zYmqvOwuM,11021
3
- analyzeAudio/analyzersUseSpectrogram.py,sha256=RjKW9it_9EDgKwkx9sB99z7qbLrVq5xM7ALTcwo4xE8,2346
4
- analyzeAudio/analyzersUseTensor.py,sha256=oRxKw42Q4bdBhuSlwdyVo2MNgI0AbnjEjpnRLQVaqco,701
5
- analyzeAudio/analyzersUseWaveform.py,sha256=2nGhwdpDpamAAgeZ4XAbtX1aGAn5R-VIwHO1qnyxz0U,2042
6
- analyzeAudio/audioAspectsRegistry.py,sha256=NoRUflTxls4palGtc7iQsfMLc9nMGITCVRPhDehNFJ4,8564
7
- analyzeAudio/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
- analyzeAudio/pythonator.py,sha256=hL2KzeO7cgboSCL9uOl1uyuWMrnR0xhDt9o78GkM2_0,5680
9
- analyzeaudio-0.0.16.dist-info/licenses/LICENSE,sha256=NxH5Y8BdC-gNU-WSMwim3uMbID2iNDXJz7fHtuTdXhk,19346
10
- tests/conftest.py,sha256=BhZswOjkl_u-qiS4Zy38d2fETdWAtZiigeuXYBK8l0k,397
11
- tests/test_audioAspectsRegistry.py,sha256=-TWTLMdAn6IFv7ZdFWrBm1KxpLBa3Mz1sCygAwxV6gE,27
12
- tests/test_other.py,sha256=sd20ms4StQ13_3-gmwZwtAuoIAwfxWC5IXM_Cp5GQXM,428
13
- analyzeaudio-0.0.16.dist-info/METADATA,sha256=Nn-a1bKLTdVvwmayCHEA8SdelzcSDhmbCJyMrdIv5XU,9178
14
- analyzeaudio-0.0.16.dist-info/WHEEL,sha256=zaaOINJESkSfm_4HQVc5ssNzHCPXhJm0kEUakpsEHaU,91
15
- analyzeaudio-0.0.16.dist-info/entry_points.txt,sha256=FHgSx7fndtZ6SnQ-nWVXf0NB59exaHQ2DtatTK9KrLg,100
16
- analyzeaudio-0.0.16.dist-info/top_level.txt,sha256=QV8LQ0r_1LIQuewxDcEzODpykv5qRYG3I70piOUSVRg,19
17
- analyzeaudio-0.0.16.dist-info/RECORD,,