lingualabpy 0.0.6__py3-none-any.whl → 0.1.1__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
@@ -1,20 +1,25 @@
1
- # -------------------------------------------------------------
2
- # Licensed under the MIT License. See LICENSE in project root for information.
3
- # -------------------------------------------------------------
4
- """lingualabpy"""
5
- from __future__ import annotations
6
-
7
- __version__ = "0.0.6"
8
-
9
- default_config = {
10
- "participant_col": "participant_id",
11
- "participant_label": "IE",
12
- "clinician_label": "IV",
13
- "f0_bounds": {
14
- "female": [100.0, 600.0],
15
- "male": [75.0, 300.0],
16
- },
17
- "unit_frequency": "Hertz",
18
- }
19
-
20
- from lingualabpy.io import read_audio, read_docx, read_json, write_json, read_textgrid
1
+ # -------------------------------------------------------------
2
+ # Licensed under the MIT License. See LICENSE in project root for information.
3
+ # -------------------------------------------------------------
4
+ """lingualabpy"""
5
+
6
+ from __future__ import annotations
7
+
8
+ try:
9
+ from lingualabpy._version import __version__
10
+ except ImportError:
11
+ pass
12
+
13
+
14
+ default_config = {
15
+ "participant_col": "participant_id",
16
+ "participant_label": "IE",
17
+ "clinician_label": "IV",
18
+ "f0_bounds": {
19
+ "female": [100.0, 600.0],
20
+ "male": [75.0, 300.0],
21
+ },
22
+ "unit_frequency": "Hertz",
23
+ }
24
+
25
+ from lingualabpy.io import read_audio, read_docx, read_json, write_json, read_textgrid
@@ -0,0 +1,34 @@
1
+ # file generated by setuptools-scm
2
+ # don't change, don't track in version control
3
+
4
+ __all__ = [
5
+ "__version__",
6
+ "__version_tuple__",
7
+ "version",
8
+ "version_tuple",
9
+ "__commit_id__",
10
+ "commit_id",
11
+ ]
12
+
13
+ TYPE_CHECKING = False
14
+ if TYPE_CHECKING:
15
+ from typing import Tuple
16
+ from typing import Union
17
+
18
+ VERSION_TUPLE = Tuple[Union[int, str], ...]
19
+ COMMIT_ID = Union[str, None]
20
+ else:
21
+ VERSION_TUPLE = object
22
+ COMMIT_ID = object
23
+
24
+ version: str
25
+ __version__: str
26
+ __version_tuple__: VERSION_TUPLE
27
+ version_tuple: VERSION_TUPLE
28
+ commit_id: COMMIT_ID
29
+ __commit_id__: COMMIT_ID
30
+
31
+ __version__ = version = '0.1.1'
32
+ __version_tuple__ = version_tuple = (0, 1, 1)
33
+
34
+ __commit_id__ = commit_id = None
@@ -1,85 +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
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
@@ -1,11 +1,11 @@
1
- from pydub import AudioSegment
2
-
3
-
4
- def extract_audio(audio: AudioSegment, intervals: list[list[float]]) -> AudioSegment:
5
- """"""
6
- new_audio = AudioSegment.empty()
7
-
8
- for start, end in intervals:
9
- new_audio += audio[start * 1000 : end * 1000]
10
-
11
- return new_audio
1
+ from pydub import AudioSegment
2
+
3
+
4
+ def extract_audio(audio: AudioSegment, intervals: list[list[float]]) -> AudioSegment:
5
+ """"""
6
+ new_audio = AudioSegment.empty()
7
+
8
+ for start, end in intervals:
9
+ new_audio += audio[start * 1000 : end * 1000]
10
+
11
+ return new_audio
@@ -1,59 +1,59 @@
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
-
52
- audiofile = Path(audiofile)
53
-
54
- metrics["filename"] = audiofile.name
55
-
56
- if not output_json:
57
- output_json = audiofile.stem + "_metric-audio.json"
58
-
59
- write_json(dict(metrics), output_json)
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
+
52
+ audiofile = Path(audiofile)
53
+
54
+ metrics["filename"] = audiofile.name
55
+
56
+ if not output_json:
57
+ output_json = audiofile.stem + "_metric-audio.json"
58
+
59
+ write_json(dict(metrics), output_json)
@@ -1,48 +1,48 @@
1
- import click
2
-
3
- from lingualabpy import default_config, read_audio, read_textgrid
4
- from lingualabpy.audio.triming import extract_audio
5
- from lingualabpy.text.textgrid import extract_intervals
6
- from lingualabpy.tools.interval import intervals_masking, interval_to_list
7
-
8
-
9
- @click.command()
10
- @click.option(
11
- "--participant_label",
12
- default=default_config["participant_label"],
13
- show_default=True,
14
- )
15
- @click.option(
16
- "--clinician_label",
17
- default=default_config["clinician_label"],
18
- show_default=True,
19
- )
20
- @click.option("--remove_overlap", is_flag=True, show_default=True)
21
- @click.argument("textgrid", nargs=1, type=click.Path(exists=True))
22
- @click.argument("audiofile", nargs=1, type=click.Path(exists=True))
23
- @click.argument("output", nargs=1)
24
- def main(
25
- participant_label, clinician_label, remove_overlap, textgrid, audiofile, output
26
- ):
27
- """Doc"""
28
- grid = read_textgrid(textgrid)
29
-
30
- try:
31
- participant_intervals, clinician_intervals = extract_intervals(
32
- grid, [participant_label, clinician_label]
33
- )
34
- except Exception as e:
35
- raise Exception(f"Failed to extract intervals for {textgrid}", repr(e))
36
-
37
- if remove_overlap:
38
- participant_intervals = intervals_masking(
39
- participant_intervals, clinician_intervals
40
- )
41
- else:
42
- participant_intervals = map(interval_to_list, participant_intervals)
43
-
44
- audio = read_audio(audiofile)
45
-
46
- audio_clean = extract_audio(audio, participant_intervals)
47
-
48
- audio_clean.export(output, format="wav")
1
+ import click
2
+
3
+ from lingualabpy import default_config, read_audio, read_textgrid
4
+ from lingualabpy.audio.triming import extract_audio
5
+ from lingualabpy.text.textgrid import extract_intervals
6
+ from lingualabpy.tools.interval import intervals_masking, interval_to_list
7
+
8
+
9
+ @click.command()
10
+ @click.option(
11
+ "--participant_label",
12
+ default=default_config["participant_label"],
13
+ show_default=True,
14
+ )
15
+ @click.option(
16
+ "--clinician_label",
17
+ default=default_config["clinician_label"],
18
+ show_default=True,
19
+ )
20
+ @click.option("--remove_overlap", is_flag=True, show_default=True)
21
+ @click.argument("textgrid", nargs=1, type=click.Path(exists=True))
22
+ @click.argument("audiofile", nargs=1, type=click.Path(exists=True))
23
+ @click.argument("output", nargs=1)
24
+ def main(
25
+ participant_label, clinician_label, remove_overlap, textgrid, audiofile, output
26
+ ):
27
+ """Doc"""
28
+ grid = read_textgrid(textgrid)
29
+
30
+ try:
31
+ participant_intervals, clinician_intervals = extract_intervals(
32
+ grid, [participant_label, clinician_label]
33
+ )
34
+ except Exception as e:
35
+ raise Exception(f"Failed to extract intervals for {textgrid}", repr(e))
36
+
37
+ if remove_overlap:
38
+ participant_intervals = intervals_masking(
39
+ participant_intervals, clinician_intervals
40
+ )
41
+ else:
42
+ participant_intervals = map(interval_to_list, participant_intervals)
43
+
44
+ audio = read_audio(audiofile)
45
+
46
+ audio_clean = extract_audio(audio, participant_intervals)
47
+
48
+ audio_clean.export(output, format="wav")
@@ -1,21 +1,21 @@
1
- import click
2
-
3
- from lingualabpy import read_docx, write_json
4
- from lingualabpy.text.parser import parse_waywithwords
5
-
6
-
7
- @click.command()
8
- @click.option("--origin", default="waywithwords", show_default=True)
9
- @click.argument("docx_path", nargs=1, type=click.Path(exists=True))
10
- @click.argument("output", nargs=1)
11
- def main(docx_path, output, origin):
12
- """Doc"""
13
- document = read_docx(docx_path)
14
-
15
- if origin == "waywithwords":
16
- data = parse_waywithwords(document)
17
-
18
- else:
19
- raise ValueError(f"{origin} is not implemented")
20
-
21
- write_json(data, output)
1
+ import click
2
+
3
+ from lingualabpy import read_docx, write_json
4
+ from lingualabpy.text.parser import parse_waywithwords
5
+
6
+
7
+ @click.command()
8
+ @click.option("--origin", default="waywithwords", show_default=True)
9
+ @click.argument("docx_path", nargs=1, type=click.Path(exists=True))
10
+ @click.argument("output", nargs=1)
11
+ def main(docx_path, output, origin):
12
+ """Doc"""
13
+ document = read_docx(docx_path)
14
+
15
+ if origin == "waywithwords":
16
+ data = parse_waywithwords(document)
17
+
18
+ else:
19
+ raise ValueError(f"{origin} is not implemented")
20
+
21
+ write_json(data, output)
@@ -1,23 +1,23 @@
1
- import click
2
- import json
3
-
4
- from lingualabpy import default_config, read_json
5
- from lingualabpy.tools.data import merge_participants_to_df
6
-
7
-
8
- @click.command()
9
- @click.option(
10
- "-c",
11
- "--column",
12
- default=default_config["participant_col"],
13
- show_default=True,
14
- )
15
- @click.argument("jsons", nargs=-1, type=click.Path(exists=True))
16
- @click.argument("output", nargs=1)
17
- def main(column, jsons, output):
18
- """ """
19
- data = []
20
- for path in jsons:
21
- data.append(read_json(path))
22
- df = merge_participants_to_df(data, participant_col=column)
23
- df.to_csv(output)
1
+ import click
2
+ import json
3
+
4
+ from lingualabpy import default_config, read_json
5
+ from lingualabpy.tools.data import merge_participants_to_df
6
+
7
+
8
+ @click.command()
9
+ @click.option(
10
+ "-c",
11
+ "--column",
12
+ default=default_config["participant_col"],
13
+ show_default=True,
14
+ )
15
+ @click.argument("jsons", nargs=-1, type=click.Path(exists=True))
16
+ @click.argument("output", nargs=1)
17
+ def main(column, jsons, output):
18
+ """ """
19
+ data = []
20
+ for path in jsons:
21
+ data.append(read_json(path))
22
+ df = merge_participants_to_df(data, participant_col=column)
23
+ df.to_csv(output)