lingualabpy 0.0.2__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.2"
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
  )
@@ -2,7 +2,7 @@ import click
2
2
  import json
3
3
 
4
4
  from lingualabpy import default_config, read_json
5
- from lingualabpy.tools import merge_participants_to_df
5
+ from lingualabpy.tools.data import merge_participants_to_df
6
6
 
7
7
 
8
8
  @click.command()
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
@@ -1,11 +1,35 @@
1
+ import re
1
2
  from textgrids import TextGrid, Interval
3
+ import warnings
2
4
 
3
5
 
4
- def extract_intervals(grid: TextGrid, speakers: list[str]) -> tuple[list[Interval]]:
6
+ def extract_intervals(textgrid: TextGrid, speakers: list[str]) -> list[list[Interval]]:
5
7
  """"""
8
+ # Check if speakers are in the textgrid tiers
9
+ tiers = set(textgrid.keys())
10
+ if not set(speakers).issubset(tiers):
11
+ raise ValueError(
12
+ f"Some speaker(s) '{speakers}' are not a tier in the TextGrid '{tiers}'"
13
+ )
14
+
15
+ # Check if there is other speaker in the textgrid
16
+ if not set(speakers) == tiers:
17
+ warnings.warn(
18
+ f"TextGrid '{tiers}' have more speakers than specify '{speakers}'"
19
+ )
20
+
21
+ # Extraction of intervals with text value
6
22
  speakers_intervals = []
7
23
  for speaker in speakers:
8
- speakers_intervals.append([_ for _ in grid[speaker] if _.text])
24
+ speaker_intervals = []
25
+ for interval in textgrid[speaker]:
26
+ # Cleaning of the interval text
27
+ interval.text = (
28
+ interval.text.encode().decode("unicode_escape").strip(" \n\r\t")
29
+ )
30
+ if interval.text:
31
+ speaker_intervals.append(interval)
32
+ speakers_intervals.append(speaker_intervals)
9
33
 
10
34
  # Checking if all intervals are correctly labeled
11
35
  def interval_qc(intervals, label):
lingualabpy/tools/data.py CHANGED
@@ -1,12 +1,24 @@
1
- import pandas as pd
1
+ from collections import UserDict
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,
9
- ) -> pd.DataFrame:
21
+ ) -> DataFrame:
10
22
  # Check if all data have a `participant_col` key
11
23
  participant_col_checks = [_.get(participant_col) for _ in data_participants]
12
24
  if not all(participant_col_checks):
@@ -15,7 +27,7 @@ def merge_participants_to_df(
15
27
  )
16
28
 
17
29
  # Check if there are no duplicates in the data
18
- df_raw = pd.DataFrame.from_dict(data_participants)
30
+ df_raw = DataFrame.from_dict(data_participants)
19
31
  df_melt = df_raw.melt(id_vars=[participant_col]).dropna()
20
32
  df_for_test = df_melt.drop(columns="value")
21
33
  duplicates = df_for_test[df_for_test.duplicated()]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: lingualabpy
3
- Version: 0.0.2
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
@@ -24,18 +24,18 @@ Requires-Dist: praat-parselmouth
24
24
  Requires-Dist: praat-textgrids
25
25
  Requires-Dist: pydub
26
26
  Requires-Dist: python-docx
27
- Requires-Dist: lingualabpy[tests, docs, lint, feature] ; extra == "dev"
27
+ Requires-Dist: lingualabpy[test, doc, lint, feature] ; extra == "dev"
28
28
  Requires-Dist: black ; extra == "lint"
29
- Requires-Dist: pytest ; extra == "tests"
30
- Requires-Dist: pytest-cov ; extra == "tests"
29
+ Requires-Dist: pytest ; extra == "test"
30
+ Requires-Dist: pytest-cov ; extra == "test"
31
31
  Project-URL: Documentation, https://github.com/lingualab/lingualabpy
32
32
  Project-URL: Source, https://github.com/lingualab/lingualabpy
33
33
  Project-URL: Tracker, https://github.com/lingualab/lingualabpy/issues
34
34
  Provides-Extra: dev
35
- Provides-Extra: docs
35
+ Provides-Extra: doc
36
36
  Provides-Extra: feature
37
37
  Provides-Extra: lint
38
- Provides-Extra: tests
38
+ Provides-Extra: test
39
39
 
40
40
  # lingualabpy
41
41
 
@@ -0,0 +1,21 @@
1
+ lingualabpy/__init__.py,sha256=9r7VH5hUUG5UFPACgN3-Y_v0ZeJC3vTnQ7eyc5B4IVY,642
2
+ lingualabpy/io.py,sha256=RY8gsfKmkIpBC9I3XOX-VcLuPvlElxGR7P8iyY1wOUc,888
3
+ lingualabpy/audio/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ lingualabpy/audio/metrics.py,sha256=u5FlADmqeYQOSpqhY2l1l8CSC4tfBV6cWp3g6Hri6bE,3502
5
+ lingualabpy/audio/triming.py,sha256=6CY9pH43KFGAPj8Nw34y1YnlOb8gxGLU1btcuRy-Hgc,288
6
+ lingualabpy/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ lingualabpy/cli/audio_metrics.py,sha256=scuJoncBPauMvgOVaSCyrOgbnWC3tGpqDyxVP0RNfs0,1801
8
+ lingualabpy/cli/audio_triming.py,sha256=rG0gk-epVWb_jvPHAmk2Lhm4LvGkFzSUW20wi2DZBP0,1329
9
+ lingualabpy/cli/docx2json.py,sha256=Bj5f89B76NtA7Xx71xXGnSucrDEyaH9mUFifQo0wfn4,590
10
+ lingualabpy/cli/jsons2csv.py,sha256=_AcIXiQUCF5SsKqMg6WjTr8fhbuflaJNFrCP91ccSYs,596
11
+ lingualabpy/text/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
+ lingualabpy/text/parser.py,sha256=qZqhzi-6UHdbsXEWi5IMxsDK5Tsosb3pdSo67hcA6To,913
13
+ lingualabpy/text/textgrid.py,sha256=LXdDAY4aEl3Q998Uq28fz0gryFj3KWq1j0RsuWOlEC0,1632
14
+ lingualabpy/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
15
+ lingualabpy/tools/data.py,sha256=FU0_3TaeAZNCu1WpNIOkVBV3bYiEhI1rPw_l8q8z0gk,1523
16
+ lingualabpy/tools/interval.py,sha256=50lzbMTNHF26mPRG50mykCUQE3pdyRjPWMwsskwy0tg,2060
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
@@ -1,19 +0,0 @@
1
- lingualabpy/__init__.py,sha256=8Opixd2cbELk9IqSFfGxZCTgz93fX92jXQQk78MkYNU,515
2
- lingualabpy/io.py,sha256=TF8eSuX_xfGWWbQ1C0TLnia7HS1Vexn0RqKMvCzHGnE,878
3
- lingualabpy/audio/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
- lingualabpy/audio/triming.py,sha256=6CY9pH43KFGAPj8Nw34y1YnlOb8gxGLU1btcuRy-Hgc,288
5
- lingualabpy/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
- lingualabpy/cli/audio_triming.py,sha256=pAsLv2IuAKLoj8jBHB-SR5mZ7Jb0w26m41-Cya4VvoU,1194
7
- lingualabpy/cli/docx2json.py,sha256=Bj5f89B76NtA7Xx71xXGnSucrDEyaH9mUFifQo0wfn4,590
8
- lingualabpy/cli/jsons2csv.py,sha256=mwe2KO6oI0TkZML41-ezA5fo8UjPRlT_37vcv6eqiCE,591
9
- lingualabpy/text/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
- lingualabpy/text/parser.py,sha256=qZqhzi-6UHdbsXEWi5IMxsDK5Tsosb3pdSo67hcA6To,913
11
- lingualabpy/text/textgrid.py,sha256=8mkFHCLpFmlzUQpZoysXRyeES6VjwLMEqY2-IZEfQkU,779
12
- lingualabpy/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
- lingualabpy/tools/data.py,sha256=hsGxu6KQ-ltK5AstwVVpvJpBYaAIc_XT5SP0BVAQlss,1103
14
- lingualabpy/tools/interval.py,sha256=50lzbMTNHF26mPRG50mykCUQE3pdyRjPWMwsskwy0tg,2060
15
- lingualabpy-0.0.2.dist-info/entry_points.txt,sha256=QvnRy1hJXRGGbVQgS-u--5Rgs7rPBmgWC9K1iaxS5gQ,186
16
- lingualabpy-0.0.2.dist-info/LICENSE,sha256=s3hbMsmwGq2XFcxpMD3oHc8GSUeXAmPVXJbn7SYXdos,1095
17
- lingualabpy-0.0.2.dist-info/WHEEL,sha256=EZbGkh7Ie4PoZfRQ8I0ZuP9VklN_TvcZ6DSE5Uar4z4,81
18
- lingualabpy-0.0.2.dist-info/METADATA,sha256=nJgDfrbvhZYyU4wQXLD_dzdcwkA1wKze5bYjraTdAyc,1709
19
- lingualabpy-0.0.2.dist-info/RECORD,,