nkululeko 0.81.3__py3-none-any.whl → 0.81.6__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,20 +1,30 @@
1
1
  # estimate.snr
2
- import numpy as np
2
+ """
3
+ Module for estimating SNR (signal to noise ratio) from an audio signal.
4
+
5
+ This module provides a class `SNREstimator` which calculates the SNR based on
6
+ the log energy and energy thresholds of the audio signal.
7
+
8
+ """
9
+
10
+ import argparse
11
+
3
12
  import audiofile
4
13
  import matplotlib.pyplot as plt
14
+ import numpy as np
5
15
  from scipy.signal.windows import hamming
6
- import argparse
7
16
 
8
17
 
9
18
  class SNREstimator:
10
- """Estimate SNR from audio signal using log energy and energy thresholds
19
+ """Estimate SNR from audio signal using log energy and energy thresholds.
20
+
11
21
  Args:
12
22
  input_data (ndarray): Input audio signal
13
23
  sample_rate (int): Sampling rate of input audio signal
14
24
  window_size (int): Window size in samples
15
25
  hop_size (int): Hop size in samples
16
26
 
17
- Returns:
27
+ Returns:
18
28
  object: SNREstimator object
19
29
  estimated_snr (float): Estimated SNR in dB, extracted from SNREstimator.estimate_snr()
20
30
 
@@ -34,7 +44,7 @@ class SNREstimator:
34
44
  num_frames = 1 + (len(signal) - self.frame_length) // self.hop_length
35
45
  frames = [
36
46
  signal[
37
- i * self.hop_length : (i * self.hop_length) + self.frame_length
47
+ i * self.hop_length: (i * self.hop_length) + self.frame_length
38
48
  ]
39
49
  for i in range(num_frames)
40
50
  ]
@@ -54,7 +64,8 @@ class SNREstimator:
54
64
  for frame in frames
55
65
  ]
56
66
 
57
- energy_threshold_low = np.percentile(log_energies, 25) # First quartile
67
+ energy_threshold_low = np.percentile(
68
+ log_energies, 25) # First quartile
58
69
  energy_threshold_high = np.percentile(
59
70
  log_energies, 75
60
71
  ) # Third quartile
nkululeko/constants.py CHANGED
@@ -1,2 +1,2 @@
1
- VERSION="0.81.3"
1
+ VERSION="0.81.6"
2
2
  SAMPLING_RATE = 16000
nkululeko/data/dataset.py CHANGED
@@ -76,6 +76,7 @@ class Dataset:
76
76
  if rename_cols:
77
77
  col_dict = ast.literal_eval(rename_cols)
78
78
  df = df.rename(columns=col_dict)
79
+ self.util.debug(f"renamed data columns: {col_dict}")
79
80
  return df
80
81
 
81
82
  def _report_load(self):
@@ -96,8 +97,8 @@ class Dataset:
96
97
  """Load the dataframe with files, speakers and task labels"""
97
98
  # store the dataframe
98
99
  store = self.util.get_path("store")
99
- store_file = f"{store}{self.name}"
100
100
  store_format = self.util.config_val("FEATS", "store_format", "pkl")
101
+ store_file = f"{store}{self.name}.{store_format}"
101
102
  self.root = self._load_db()
102
103
  if not self.start_fresh and os.path.isfile(store_file):
103
104
  self.util.debug(f"{self.name}: reusing previously stored file {store_file}")
@@ -241,7 +242,7 @@ class Dataset:
241
242
  # store the dataframe
242
243
  store = self.util.get_path("store")
243
244
  store_format = self.util.config_val("FEATS", "store_format", "pkl")
244
- store_file = f"{store}{self.name}"
245
+ store_file = f"{store}{self.name}.{store_format}"
245
246
  self.util.write_store(self.df, store_file, store_format)
246
247
 
247
248
  def _get_df_for_lists(self, db, df_files):
@@ -281,13 +282,19 @@ class Dataset:
281
282
  # try to get the age values
282
283
  df_local["age"] = source_df["age"].astype(int)
283
284
  got_age = True
284
- except (KeyError, ValueError, audformat.errors.BadKeyError) as e:
285
+ except (KeyError, ValueError, audformat.errors.BadKeyError):
285
286
  pass
286
287
  try:
287
288
  # also it might be possible that the sex is part of the speaker description
288
289
  df_local["gender"] = db[table]["speaker"].get(map="gender")
289
290
  got_gender = True
290
- except (ValueError, audformat.errors.BadKeyError) as e:
291
+ except (ValueError, audformat.errors.BadKeyError):
292
+ pass
293
+ try:
294
+ # also it might be possible that the sex is part of the speaker description
295
+ df_local["gender"] = db[table]["speaker"].get(map="sex")
296
+ got_gender = True
297
+ except (ValueError, audformat.errors.BadKeyError):
291
298
  pass
292
299
  try:
293
300
  # also it might be possible that the age is part of the speaker description
nkululeko/demo.py CHANGED
@@ -2,20 +2,35 @@
2
2
  # Demonstration code to use the ML-experiment framework
3
3
  # Test the loading of a previously trained model and demo mode
4
4
  # needs the project config file to run before
5
+ """
6
+ This script is used to test the loading of a previously trained model and run it in demo mode.
7
+ It requires the project config file to be run before.
5
8
 
6
- import os
9
+ Usage:
10
+ python -m nkululeko.demo [--config CONFIG] [--file FILE] [--list LIST] [--folder FOLDER] [--outfile OUTFILE]
11
+
12
+ Options: \n
13
+ --config CONFIG The base configuration file (default: exp.ini) \n
14
+ --file FILE A file that should be processed (16kHz mono wav) \n
15
+ --list LIST A file with a list of files, one per line, that should be processed (16kHz mono wav) \n
16
+ --folder FOLDER A name of a folder where the files within the list are in (default: ./) \n
17
+ --outfile OUTFILE A filename to store the results in CSV (default: None)
18
+ """
7
19
  import argparse
8
20
  import configparser
21
+ import os
9
22
 
23
+ import nkululeko.glob_conf as glob_conf
24
+ from nkululeko.constants import VERSION
10
25
  from nkululeko.experiment import Experiment
11
26
  from nkululeko.utils.util import Util
12
- from nkululeko.constants import VERSION
13
- import nkululeko.glob_conf as glob_conf
14
27
 
15
28
 
16
29
  def main(src_dir):
17
- parser = argparse.ArgumentParser(description="Call the nkululeko framework.")
18
- parser.add_argument("--config", default="exp.ini", help="The base configuration")
30
+ parser = argparse.ArgumentParser(
31
+ description="Call the nkululeko DEMO framework.")
32
+ parser.add_argument("--config", default="exp.ini",
33
+ help="The base configuration")
19
34
  parser.add_argument(
20
35
  "--file", help="A file that should be processed (16kHz mono wav)"
21
36
  )
@@ -1,8 +1,11 @@
1
+ # demo_predictor.py
1
2
  import os
2
- import pandas as pd
3
- import numpy as np
4
- import audiofile
3
+
5
4
  import audformat
5
+ import audiofile
6
+ import numpy as np
7
+ import pandas as pd
8
+
6
9
  import nkululeko.glob_conf as glob_conf
7
10
  from nkululeko.utils.util import Util
8
11
 
nkululeko/experiment.py CHANGED
@@ -685,7 +685,7 @@ class Experiment:
685
685
  glob_conf.set_labels(self.labels)
686
686
 
687
687
  def save(self, filename):
688
- if self.runmgr.modelrunner.model.is_ANN():
688
+ if self.runmgr.modelrunner.model.is_ann():
689
689
  self.runmgr.modelrunner.model = None
690
690
  self.util.warn(
691
691
  f"Save experiment: Can't pickle the learning model so saving without it."
@@ -695,7 +695,7 @@ class Experiment:
695
695
  pickle.dump(self.__dict__, f)
696
696
  f.close()
697
697
  except TypeError:
698
- self.feature_extractor.featExtractor.model = None
698
+ self.feature_extractor.feat_extractor.model = None
699
699
  f = open(filename, "wb")
700
700
  pickle.dump(self.__dict__, f)
701
701
  f.close()
@@ -708,7 +708,7 @@ class Experiment:
708
708
  def save_onnx(self, filename):
709
709
  # export the model to onnx
710
710
  model = self.runmgr.get_best_model()
711
- if model.is_ANN():
711
+ if model.is_ann():
712
712
  print("converting to onnx from torch")
713
713
  else:
714
714
  from skl2onnx import to_onnx
nkululeko/explore.py CHANGED
@@ -1,17 +1,20 @@
1
1
  # explore.py
2
2
  # explore the feature sets
3
3
 
4
- from nkululeko.experiment import Experiment
5
- import configparser
6
- from nkululeko.utils.util import Util
7
- from nkululeko.constants import VERSION
8
4
  import argparse
5
+ import configparser
9
6
  import os
10
7
 
8
+ from nkululeko.constants import VERSION
9
+ from nkululeko.experiment import Experiment
10
+ from nkululeko.utils.util import Util
11
+
11
12
 
12
13
  def main(src_dir):
13
- parser = argparse.ArgumentParser(description="Call the nkululeko framework.")
14
- parser.add_argument("--config", default="exp.ini", help="The base configuration")
14
+ parser = argparse.ArgumentParser(
15
+ description="Call the nkululeko EXPLORE framework.")
16
+ parser.add_argument("--config", default="exp.ini",
17
+ help="The base configuration")
15
18
  args = parser.parse_args()
16
19
  if args.config is not None:
17
20
  config_file = args.config
@@ -46,9 +49,11 @@ def main(src_dir):
46
49
 
47
50
  # split into train and test
48
51
  expr.fill_train_and_tests()
49
- util.debug(f"train shape : {expr.df_train.shape}, test shape:{expr.df_test.shape}")
52
+ util.debug(
53
+ f"train shape : {expr.df_train.shape}, test shape:{expr.df_test.shape}")
50
54
 
51
- plot_feats = eval(util.config_val("EXPL", "feature_distributions", "False"))
55
+ plot_feats = eval(util.config_val(
56
+ "EXPL", "feature_distributions", "False"))
52
57
  tsne = eval(util.config_val("EXPL", "tsne", "False"))
53
58
  scatter = eval(util.config_val("EXPL", "scatter", "False"))
54
59
  spotlight = eval(util.config_val("EXPL", "spotlight", "False"))
@@ -32,10 +32,7 @@ class AudModelAgenderSet(Featureset):
32
32
  audeer.extract_archive(archive_path, model_root)
33
33
  device = self.util.config_val("MODEL", "device", "cpu")
34
34
  self.model = audonnx.load(model_root, device=device)
35
- pytorch_total_params = sum(p.numel() for p in self.model.parameters())
36
- self.util.debug(
37
- f"initialized agender model with {pytorch_total_params} parameters in total"
38
- )
35
+ self.util.debug(f"initialized agender model")
39
36
  self.model_loaded = True
40
37
 
41
38
  def extract(self):
@@ -1,19 +1,24 @@
1
1
  # feats_audmodel_dim.py
2
- from nkululeko.feat_extract.featureset import Featureset
3
2
  import os
3
+
4
+ import numpy as np
4
5
  import pandas as pd
6
+ import torch
7
+
5
8
  import audeer
6
- import nkululeko.glob_conf as glob_conf
7
- import audonnx
8
- import numpy as np
9
9
  import audinterface
10
+ import audonnx
11
+
12
+ from nkululeko.feat_extract.featureset import Featureset
13
+ import nkululeko.glob_conf as glob_conf
10
14
 
11
15
 
12
- class AudModelDimSet(Featureset):
13
- """
14
- Emotional dimensions from the wav2vec2. based model finetuned on MSPPodcast emotions, described in the paper
16
+ class AuddimSet(Featureset):
17
+ """Emotional dimensions from the wav2vec2 model finetuned on MSPPodcast emotions.
18
+
19
+ Described in the paper
15
20
  "Dawn of the transformer era in speech emotion recognition: closing the valence gap"
16
- https://arxiv.org/abs/2203.07378
21
+ https://arxiv.org/abs/2203.07378.
17
22
  """
18
23
 
19
24
  def __init__(self, name, data_df):
@@ -11,11 +11,12 @@ import torch
11
11
  from nkululeko.feat_extract.featureset import Featureset
12
12
 
13
13
 
14
- class AudModelSet(Featureset):
15
- """
16
- Embeddings from the wav2vec2. based model finetuned on MSPPodcast emotions, described in the paper
14
+ class AudmodelSet(Featureset):
15
+ """Embeddings from the wav2vec2 based model finetuned on MSPPodcast emotions.
16
+
17
+ Described in the paper:
17
18
  "Dawn of the transformer era in speech emotion recognition: closing the valence gap"
18
- https://arxiv.org/abs/2203.07378
19
+ https://arxiv.org/abs/2203.07378.
19
20
  """
20
21
 
21
22
  def __init__(self, name, data_df):
@@ -8,7 +8,7 @@ from nkululeko.utils.util import Util
8
8
  from nkululeko.feat_extract.featureset import Featureset
9
9
 
10
10
 
11
- class Importset(Featureset):
11
+ class ImportSet(Featureset):
12
12
  """Class to import features that have been compiled elsewhere"""
13
13
 
14
14
  def __init__(self, name, data_df):
@@ -10,6 +10,7 @@ pip uninstall -y torch torchvision torchaudio
10
10
  pip install --pre torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/nightly/cpu
11
11
 
12
12
  """
13
+
13
14
  import os
14
15
  import pandas as pd
15
16
  from tqdm import tqdm
@@ -23,7 +24,7 @@ from nkululeko.utils.util import Util
23
24
  from nkululeko.feat_extract.featureset import Featureset
24
25
 
25
26
 
26
- class MOSSet(Featureset):
27
+ class MosSet(Featureset):
27
28
  """Class to predict MOS (mean opinion score)"""
28
29
 
29
30
  def __init__(self, name, data_df):
@@ -1,17 +1,19 @@
1
1
  # feats_praat.py
2
- from nkululeko.feat_extract.featureset import Featureset
2
+ import ast
3
3
  import os
4
- import pandas as pd
4
+
5
5
  import numpy as np
6
- import nkululeko.glob_conf as glob_conf
6
+ import pandas as pd
7
+
7
8
  from nkululeko.feat_extract import feinberg_praat
8
- import ast
9
+ from nkululeko.feat_extract.featureset import Featureset
10
+ import nkululeko.glob_conf as glob_conf
9
11
 
10
12
 
11
- class Praatset(Featureset):
12
- """
13
- a feature extractor for the Praat software, based on
14
- David R. Feinberg's Praat scripts for the parselmouth python interface.
13
+ class PraatSet(Featureset):
14
+ """A feature extractor for the Praat software.
15
+
16
+ Based on David R. Feinberg's Praat scripts for the parselmouth python interface.
15
17
  https://osf.io/6dwr3/
16
18
 
17
19
  """
@@ -1,14 +1,17 @@
1
- """ feats_snr.py
2
- Estimate snr (signal to noise ratio as acoustic features)
1
+ """ feats_snr.py is to estimate snr.
2
+
3
+ SNR (signal to noise ratio) is extracted as acoustic features.
3
4
  """
4
5
  import os
5
- from tqdm import tqdm
6
- import pandas as pd
6
+
7
7
  import audiofile
8
+ import pandas as pd
9
+ from tqdm import tqdm
10
+
8
11
  import nkululeko.glob_conf as glob_conf
9
- from nkululeko.utils.util import Util
10
- from nkululeko.feat_extract.featureset import Featureset
11
12
  from nkululeko.autopredict.estimate_snr import SNREstimator
13
+ from nkululeko.feat_extract.featureset import Featureset
14
+ from nkululeko.utils.util import Util
12
15
 
13
16
 
14
17
  class SNRSet(Featureset):
@@ -16,14 +19,17 @@ class SNRSet(Featureset):
16
19
 
17
20
  def __init__(self, name, data_df):
18
21
  """Constructor."""
22
+
19
23
  super().__init__(name, data_df)
20
24
 
21
25
  def extract(self):
22
26
  """Estimate the features or load them from disk if present."""
27
+
23
28
  store = self.util.get_path("store")
24
29
  store_format = self.util.config_val("FEATS", "store_format", "pkl")
25
30
  storage = f"{store}{self.name}.{store_format}"
26
- extract = self.util.config_val("FEATS", "needs_feature_extraction", False)
31
+ extract = self.util.config_val(
32
+ "FEATS", "needs_feature_extraction", False)
27
33
  no_reuse = eval(self.util.config_val("FEATS", "no_reuse", "False"))
28
34
  if extract or no_reuse or not os.path.isfile(storage):
29
35
  self.util.debug("estimating SNR, this might take a while...")
@@ -40,7 +46,8 @@ class SNRSet(Featureset):
40
46
  snr = self.get_snr(signal[0], sampling_rate)
41
47
  snr_series[idx] = snr
42
48
  print("")
43
- self.df = pd.DataFrame(snr_series.values.tolist(), index=self.data_df.index)
49
+ self.df = pd.DataFrame(
50
+ snr_series.values.tolist(), index=self.data_df.index)
44
51
  self.df.columns = ["snr"]
45
52
  self.util.write_store(self.df, storage, store_format)
46
53
  try:
@@ -53,10 +60,11 @@ class SNRSet(Featureset):
53
60
 
54
61
  def get_snr(self, signal, sampling_rate):
55
62
  r"""Estimate SNR from raw audio signal.
63
+
56
64
  Args:
57
65
  signal: audio signal
58
66
  sampling_rate: sample rate
59
- Returns
67
+ Returns:
60
68
  snr: estimated signal to noise ratio
61
69
  """
62
70
  snr_estimator = SNREstimator(signal, sampling_rate)
@@ -1,36 +1,33 @@
1
- """ feats_squim.py
2
- predict SQUIM ( SPEECH QUALITY AND INTELLIGIBILITY
3
- MEASURES) features
1
+ """Predict SQUIM ( SPEECH QUALITY AND INTELLIGIBILITY MEASURES) features.
4
2
 
5
-
6
- Wideband Perceptual Estimation of Speech Quality (PESQ) [2]
7
- Short-Time Objective Intelligibility (STOI) [3]
8
- Scale-Invariant Signal-to-Distortion Ratio (SI-SDR) [4]
9
-
10
-
11
- adapted from
3
+ Wideband Perceptual Estimation of Speech Quality (PESQ) [2].
4
+ Short-Time Objective Intelligibility (STOI) [3].
5
+ Scale-Invariant Signal-to-Distortion Ratio (SI-SDR) [4].
6
+ Adapted from
12
7
  from https://pytorch.org/audio/main/tutorials/squim_tutorial.html#sphx-glr-tutorials-squim-tutorial-py
13
- paper: https://arxiv.org/pdf/2304.01448.pdf
14
-
15
- needs
8
+ paper: https://arxiv.org/pdf/2304.01448.pdf.
9
+ Needs
16
10
  pip uninstall -y torch torchvision torchaudio
17
11
  pip install --pre torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/nightly/cpu
18
12
 
19
13
  """
20
14
 
21
15
  import os
22
- from tqdm import tqdm
16
+
23
17
  import pandas as pd
24
18
  import torch
25
19
  import torchaudio
26
20
  from torchaudio.pipelines import SQUIM_OBJECTIVE
21
+ from tqdm import tqdm
22
+
27
23
  import audiofile
24
+
25
+ from nkululeko.feat_extract.featureset import Featureset
28
26
  import nkululeko.glob_conf as glob_conf
29
27
  from nkululeko.utils.util import Util
30
- from nkululeko.feat_extract.featureset import Featureset
31
28
 
32
29
 
33
- class SQUIMSet(Featureset):
30
+ class SquimSet(Featureset):
34
31
  """Class to predict SQUIM features"""
35
32
 
36
33
  def __init__(self, name, data_df):