lingualabpy 0.0.3__py3-none-any.whl → 0.0.4__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.
lingualabpy/__init__.py CHANGED
@@ -4,12 +4,17 @@
4
4
  """lingualabpy"""
5
5
  from __future__ import annotations
6
6
 
7
- __version__ = "0.0.3"
7
+ __version__ = "0.0.4"
8
8
 
9
9
  default_config = {
10
10
  "participant_col": "participant_id",
11
11
  "participant_label": "IE",
12
12
  "clinician_label": "IV",
13
+ "f0_bounds": {
14
+ "female": [100.0, 600.0],
15
+ "male": [75.0, 300.0],
16
+ },
17
+ "unit_frequency": "Hertz",
13
18
  }
14
19
 
15
20
  from lingualabpy.io import read_audio, read_docx, read_json, write_json, read_textgrid
@@ -0,0 +1,85 @@
1
+ from collections import defaultdict
2
+ import numpy as np
3
+ from parselmouth import Sound
4
+ from parselmouth.praat import call
5
+
6
+ from lingualabpy.tools.data import UnchangeableDict
7
+
8
+
9
+ def measure_pitch(sound: Sound, f0min: str, f0max: str, unit: str) -> UnchangeableDict:
10
+ """
11
+ This function measures duration, pitch, HNR, jitter, and shimmer
12
+ This is the function to measure source acoustics using default male parameters.
13
+ """
14
+ # compute usefull praat object
15
+ pitch = call(sound, "To Pitch", 0.0, f0min, f0max)
16
+ harmonicity = call(sound, "To Harmonicity (cc)", 0.01, f0min, 0.1, 1.0)
17
+ point_process = call(sound, "To PointProcess (periodic, cc)", f0min, f0max)
18
+
19
+ # metrics container
20
+ metrics = UnchangeableDict()
21
+
22
+ # Metrics computation
23
+ metrics["duration"] = call(sound, "Get total duration")
24
+ metrics["f0_mean"] = call(pitch, "Get mean", 0, 0, unit)
25
+ metrics["F0_std"] = call(pitch, "Get standard deviation", 0, 0, unit)
26
+ metrics["hnr"] = call(harmonicity, "Get mean", 0, 0)
27
+
28
+ # jitter
29
+ jitter_types = ["local", ["local", "absolute"], "rap", "ppq5", "ddp"]
30
+ for jitter_type in jitter_types:
31
+ if isinstance(jitter_type, list):
32
+ metric_name = f"jitter_{'_'.join(jitter_type)}"
33
+ praat_function = f"Get jitter ({', '.join(jitter_type)})"
34
+ else:
35
+ metric_name = f"jitter_{jitter_type}"
36
+ praat_function = f"Get jitter ({jitter_type})"
37
+ metrics[metric_name] = call(
38
+ point_process, praat_function, 0, 0, 0.0001, 0.02, 1.3
39
+ )
40
+
41
+ # shimmer
42
+ shimmer_types = ["local", "local_dB", "apq3", "apq5", "apq11", "dda"]
43
+ for shimmer_type in shimmer_types:
44
+ metric_name = f"shimmer_{shimmer_type}"
45
+ praat_function = f"Get shimmer ({shimmer_type})"
46
+ metrics[metric_name] = call(
47
+ [sound, point_process], praat_function, 0, 0, 0.0001, 0.02, 1.3, 1.6
48
+ )
49
+
50
+ return metrics
51
+
52
+
53
+ def measure_formants(
54
+ sound: Sound, f0min: str, f0max: str, unit: str
55
+ ) -> UnchangeableDict:
56
+ """
57
+ This function measures formants at each glottal pulse
58
+
59
+ Puts, D. A., Apicella, C. L., & Cárdenas, R. A. (2012). Masculine voices signal men's threat potential in forager and industrial societies. Proceedings of the Royal Society of London B: Biological Sciences, 279(1728), 601-609.
60
+
61
+ Adapted from: DOI 10.17605/OSF.IO/K2BHS
62
+ """
63
+ # compute usefull praat object
64
+ point_process = call(sound, "To PointProcess (periodic, cc)", f0min, f0max)
65
+ formants = call(sound, "To Formant (burg)", 0.0025, 5, 5000, 0.025, 50)
66
+ number_of_points = call(point_process, "Get number of points")
67
+
68
+ # metrics container
69
+ metrics = UnchangeableDict()
70
+
71
+ # Measure formants only at glottal pulses
72
+ formants_list = defaultdict(list)
73
+ for index in range(1, number_of_points + 1):
74
+ time = call(point_process, "Get time from index", index)
75
+ for pulse in [1, 2, 3, 4]:
76
+ value = call(formants, "Get value at time", pulse, time, unit, "Linear")
77
+ if str(value) != "nan":
78
+ formants_list[pulse].append(value)
79
+
80
+ # calculate mean and median formants across pulses, median is what is used in all subsequent calculations
81
+ for pulse in [1, 2, 3, 4]:
82
+ metrics[f"formants_{pulse}_mean"] = np.mean(formants_list[pulse])
83
+ metrics[f"formants_{pulse}_median"] = np.median(formants_list[pulse])
84
+
85
+ return metrics
@@ -0,0 +1,57 @@
1
+ import click
2
+ from parselmouth import Sound
3
+ from pathlib import Path
4
+
5
+ from lingualabpy import default_config, write_json
6
+ from lingualabpy.audio.metrics import measure_pitch, measure_formants
7
+
8
+
9
+ @click.command()
10
+ @click.option(
11
+ "--sex",
12
+ type=click.Choice(["female", "male"]),
13
+ help=f"Set f0min and f0max for praat analysis. {default_config['f0_bounds']}",
14
+ )
15
+ @click.option(
16
+ "--f0min",
17
+ type=float,
18
+ help="Define f0min for praat analysis. Not required if sex is specify",
19
+ )
20
+ @click.option(
21
+ "--f0max",
22
+ type=float,
23
+ help="Define f0max for praat analysis. Not required if sex is specify",
24
+ )
25
+ @click.option(
26
+ "--unit_frequency",
27
+ default=default_config["unit_frequency"],
28
+ show_default=True,
29
+ )
30
+ @click.option("--participant_id", "-p", default=None, help="")
31
+ @click.option("--output_json", default=None, help="")
32
+ @click.argument("audiofile", nargs=1, type=click.Path(exists=True))
33
+ def main(sex, f0min, f0max, unit_frequency, participant_id, output_json, audiofile):
34
+ """Doc"""
35
+ if sex:
36
+ f0min, f0max = default_config["f0_bounds"][sex]
37
+ else:
38
+ if not f0min or not f0max:
39
+ raise click.UsageError(
40
+ "'--f0min' and '--f0max' are required if '--sex' is not specified"
41
+ )
42
+
43
+ sound = Sound(audiofile)
44
+ metrics = measure_pitch(sound, f0min, f0max, unit_frequency)
45
+ metrics.update(measure_formants(sound, f0min, f0max, unit_frequency))
46
+
47
+ audiofile_stem = Path(audiofile).stem
48
+
49
+ if participant_id:
50
+ metrics["participant_id"] = participant_id
51
+ else:
52
+ metrics["participant_id"] = audiofile_stem.split("_")[0]
53
+
54
+ if not output_json:
55
+ output_json = audiofile_stem + "_metric-audio.json"
56
+
57
+ write_json(dict(metrics), output_json)
@@ -23,9 +23,14 @@ from lingualabpy.tools.interval import intervals_masking
23
23
  def main(participant_label, clinician_label, textgrid, audiofile, output):
24
24
  """Doc"""
25
25
  grid = read_textgrid(textgrid)
26
- participant_intervals, clinician_intervals = extract_intervals(
27
- grid, [participant_label, clinician_label]
28
- )
26
+
27
+ try:
28
+ participant_intervals, clinician_intervals = extract_intervals(
29
+ grid, [participant_label, clinician_label]
30
+ )
31
+ except Exception as e:
32
+ raise Exception(f"Failed to extract intervals for {textgrid}", repr(e))
33
+
29
34
  participant_intervals_clean = intervals_masking(
30
35
  participant_intervals, clinician_intervals
31
36
  )
lingualabpy/io.py CHANGED
@@ -33,7 +33,7 @@ def read_json(json_path: str) -> Union[list, dict]:
33
33
  def write_json(data: Union[list, dict], json_path: str) -> None:
34
34
  """"""
35
35
  with open(json_path, "w") as file:
36
- json.dump(data, file)
36
+ json.dump(data, file, indent=4)
37
37
 
38
38
 
39
39
  # .TextGrid files
lingualabpy/tools/data.py CHANGED
@@ -1,8 +1,20 @@
1
+ from collections import UserDict
1
2
  from pandas import DataFrame
2
3
 
3
4
  from typing import Any, Dict, List
4
5
 
5
6
 
7
+ class UnchangeableDict(UserDict):
8
+ """A dictionary in which you can add new keys but not modify them in the future."""
9
+
10
+ def __setitem__(self, key: Any, item: Any) -> None:
11
+ try:
12
+ self.__getitem__(key)
13
+ raise ValueError("duplicate key '{}' found".format(key))
14
+ except KeyError:
15
+ return super().__setitem__(key, item)
16
+
17
+
6
18
  def merge_participants_to_df(
7
19
  data_participants: List[Dict[Any, Any]],
8
20
  participant_col: str,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: lingualabpy
3
- Version: 0.0.3
3
+ Version: 0.0.4
4
4
  Summary: Tools and utilities from the LINGUA laboratory
5
5
  Author-email: Christophe Bedetti <christophe.bedetti@umontreal.ca>
6
6
  Requires-Python: >=3.8.1
@@ -1,19 +1,21 @@
1
- lingualabpy/__init__.py,sha256=Klpz9mrtYXzZ3eSXg7ciwak9mAkgKVC5G1w0uaMn7Q8,515
2
- lingualabpy/io.py,sha256=TF8eSuX_xfGWWbQ1C0TLnia7HS1Vexn0RqKMvCzHGnE,878
1
+ lingualabpy/__init__.py,sha256=9r7VH5hUUG5UFPACgN3-Y_v0ZeJC3vTnQ7eyc5B4IVY,642
2
+ lingualabpy/io.py,sha256=RY8gsfKmkIpBC9I3XOX-VcLuPvlElxGR7P8iyY1wOUc,888
3
3
  lingualabpy/audio/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ lingualabpy/audio/metrics.py,sha256=u5FlADmqeYQOSpqhY2l1l8CSC4tfBV6cWp3g6Hri6bE,3502
4
5
  lingualabpy/audio/triming.py,sha256=6CY9pH43KFGAPj8Nw34y1YnlOb8gxGLU1btcuRy-Hgc,288
5
6
  lingualabpy/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
- lingualabpy/cli/audio_triming.py,sha256=pAsLv2IuAKLoj8jBHB-SR5mZ7Jb0w26m41-Cya4VvoU,1194
7
+ lingualabpy/cli/audio_metrics.py,sha256=scuJoncBPauMvgOVaSCyrOgbnWC3tGpqDyxVP0RNfs0,1801
8
+ lingualabpy/cli/audio_triming.py,sha256=rG0gk-epVWb_jvPHAmk2Lhm4LvGkFzSUW20wi2DZBP0,1329
7
9
  lingualabpy/cli/docx2json.py,sha256=Bj5f89B76NtA7Xx71xXGnSucrDEyaH9mUFifQo0wfn4,590
8
10
  lingualabpy/cli/jsons2csv.py,sha256=_AcIXiQUCF5SsKqMg6WjTr8fhbuflaJNFrCP91ccSYs,596
9
11
  lingualabpy/text/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
12
  lingualabpy/text/parser.py,sha256=qZqhzi-6UHdbsXEWi5IMxsDK5Tsosb3pdSo67hcA6To,913
11
13
  lingualabpy/text/textgrid.py,sha256=LXdDAY4aEl3Q998Uq28fz0gryFj3KWq1j0RsuWOlEC0,1632
12
14
  lingualabpy/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
- lingualabpy/tools/data.py,sha256=FTjxbckza65vZ_MWEO5wi4mDXpJ2u9KkiEA3-HGfOt8,1106
15
+ lingualabpy/tools/data.py,sha256=FU0_3TaeAZNCu1WpNIOkVBV3bYiEhI1rPw_l8q8z0gk,1523
14
16
  lingualabpy/tools/interval.py,sha256=50lzbMTNHF26mPRG50mykCUQE3pdyRjPWMwsskwy0tg,2060
15
- lingualabpy-0.0.3.dist-info/entry_points.txt,sha256=QvnRy1hJXRGGbVQgS-u--5Rgs7rPBmgWC9K1iaxS5gQ,186
16
- lingualabpy-0.0.3.dist-info/LICENSE,sha256=s3hbMsmwGq2XFcxpMD3oHc8GSUeXAmPVXJbn7SYXdos,1095
17
- lingualabpy-0.0.3.dist-info/WHEEL,sha256=EZbGkh7Ie4PoZfRQ8I0ZuP9VklN_TvcZ6DSE5Uar4z4,81
18
- lingualabpy-0.0.3.dist-info/METADATA,sha256=JI1jTk5UA5CeLCcLO6HCC157WmeUW0aUTm0hKZaEXm8,1703
19
- lingualabpy-0.0.3.dist-info/RECORD,,
17
+ lingualabpy-0.0.4.dist-info/entry_points.txt,sha256=IXEsa7Cgqjph5bkKSBMXZIBVP4ocrRaSh13dFPBwBmE,247
18
+ lingualabpy-0.0.4.dist-info/LICENSE,sha256=s3hbMsmwGq2XFcxpMD3oHc8GSUeXAmPVXJbn7SYXdos,1095
19
+ lingualabpy-0.0.4.dist-info/WHEEL,sha256=EZbGkh7Ie4PoZfRQ8I0ZuP9VklN_TvcZ6DSE5Uar4z4,81
20
+ lingualabpy-0.0.4.dist-info/METADATA,sha256=REDE0J8FGCnciM2CIJbJsRj7WFLZd2BqgDC1PY_C2-0,1703
21
+ lingualabpy-0.0.4.dist-info/RECORD,,
@@ -1,4 +1,5 @@
1
1
  [console_scripts]
2
+ lingualabpy_audio_metrics=lingualabpy.cli.audio_metrics:main
2
3
  lingualabpy_audio_triming=lingualabpy.cli.audio_triming:main
3
4
  lingualabpy_docx2json=lingualabpy.cli.docx2json:main
4
5
  lingualabpy_jsons2csv=lingualabpy.cli.jsons2csv:main