Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Multilabel Detection #891

Merged
merged 53 commits into from
Jul 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
53 commits
Select commit Hold shift + click to select a range
5fe2153
Re-added files from backup branch
hadware Jan 7, 2022
1d59d44
Re-added to init
hadware Jan 7, 2022
7ebbc74
Re-added __init__ references, re-added VoiceTypeClassification.yaml d…
hadware Jan 11, 2022
14998e6
Merge branch 'develop' into feat/vtc
hbredin Jan 12, 2022
fd1e3bc
Merge branch 'develop' into feat/vtc
hbredin Jan 27, 2022
5cc74da
Fixing Fscore metric, fixing MultilabelPipeline apply code
hadware Jan 28, 2022
98c97d2
Merge remote-tracking branch 'origin/feat/vtc' into feat/vtc
hadware Jan 28, 2022
934cf01
Fixed multilabel pipeline apply method.
hadware Jan 29, 2022
ab7112e
Merge branch 'develop' into feat/vtc
hbredin Jan 31, 2022
1f0c63e
Fixing imports
hadware Feb 3, 2022
a5947c3
Merge remote-tracking branch 'origin/feat/vtc' into feat/vtc
hadware Feb 3, 2022
b0ec1a2
Fixing imports (again)
hadware Feb 3, 2022
a28bacb
Fixing imports (again^2)
hadware Feb 3, 2022
e846109
Started re-factoring the VTC task into the speaker-tracking task.
hadware Feb 10, 2022
d569f2a
Fixed VTC preprocessor
hadware Feb 14, 2022
d4584c1
Added a VTC tutorial. The custom fscore metric should be good.
hadware Feb 15, 2022
e9df3f8
Merge remote-tracking branch 'bredin/develop' into feat-vtc-preproces…
hadware Feb 16, 2022
5f52175
Merge branch 'develop' into feat-vtc-preprocessors
hadware Feb 17, 2022
deabd36
Fixed multilabel pipeline init.
hadware Feb 28, 2022
ebd12a3
Merge branch 'develop' into feat-vtc-preprocessors
hadware Mar 8, 2022
5777043
Merge branch 'develop' into feat-vtc-preprocessors
hbredin Mar 13, 2022
796926a
Merge branch 'develop' into feat-vtc-preprocessors
hbredin Mar 14, 2022
5a26f17
Documentation for the VoiceTypeClassifierPreprocessor. A couple of do…
hadware Mar 14, 2022
fd1acd7
Removed VoiceTypeClassification.yaml .
hadware Mar 14, 2022
be54c45
Merge branch 'develop' into feat-vtc-preprocessors
hbredin Mar 15, 2022
6fa3a64
chore: rename, rewrite and reorganize things a bit
hbredin Mar 15, 2022
a53519a
Merge branch 'feat-vtc-preprocessors' of github.com:hadware/pyannote-…
hbredin Mar 15, 2022
828c1d6
Changed the database loading part of the multilabel_detection.ipynb t…
hadware Mar 15, 2022
21c8df9
Merge remote-tracking branch 'bredin/develop' into feat-vtc-preproces…
hadware Mar 15, 2022
a217e99
Merge branch 'develop' into feat-vtc-preprocessors
hbredin Mar 24, 2022
5198ac7
Removed the assertions that ensure that the classes from the unions/i…
hadware Mar 24, 2022
b515d05
Updated multilabel tutorial
hadware Apr 13, 2022
85ba6bc
Merge remote-tracking branch 'bredin/develop' into feat-vtc-preproces…
hadware Apr 13, 2022
79c9ff8
Fixing imports post-merge
hadware Apr 13, 2022
3974ded
Merge branch 'develop' into feat-vtc-preprocessors
hadware May 11, 2022
ef0421b
A bit more documentation in the tutorial (for database loading)
hadware May 12, 2022
8d225d2
Merge branch 'develop' into feat-vtc-preprocessors
hadware May 31, 2022
a51b244
Merge branch 'develop' into feat-vtc-preprocessors
hbredin Jun 8, 2022
345a262
Merge branch 'develop' into feat-vtc-preprocessors
hbredin Jun 16, 2022
5fbcb33
Merge branch 'develop' into feat-vtc-preprocessors
hadware Jun 20, 2022
4d0c36e
Removed the multilabel_detection.ipynb notebook
hadware Jun 20, 2022
5372c56
Added shared min_duration parameters to the multilabel_detection.py p…
hadware Jun 20, 2022
897d99f
Re-added the ipynb version of multilabel_detection.ipynb to the tutor…
hadware Jun 30, 2022
68e55de
Update README.md
hbredin Jul 1, 2022
39fff5a
Update and rename multilabel_detection.py to multilabel.py
hbredin Jul 1, 2022
b69cbd1
Update __init__.py
hbredin Jul 1, 2022
e49eada
Update README.md
hbredin Jul 1, 2022
2edf9aa
Update __init__.py
hbredin Jul 1, 2022
e7e18db
Update and rename multilabel_detection.py to multilabel.py
hbredin Jul 1, 2022
7dc6296
Update __init__.py
hbredin Jul 1, 2022
158e809
Update test_reproducibility.py
hbredin Jul 1, 2022
551b2c4
Update README.md
hbredin Jul 1, 2022
4b4f249
Delete multilabel_detection.ipynb
hbredin Jul 1, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 3 additions & 1 deletion pyannote/audio/pipelines/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from .segmentation import SpeakerSegmentation
from .multilabel import MultiLabelSegmentation
from .overlapped_speech_detection import OverlappedSpeechDetection
from .resegmentation import Resegmentation
from .segmentation import SpeakerSegmentation
from .speaker_diarization import SpeakerDiarization
from .voice_activity_detection import VoiceActivityDetection

Expand All @@ -32,4 +33,5 @@
"SpeakerSegmentation",
"SpeakerDiarization",
"Resegmentation",
"MultiLabelSegmentation",
]
213 changes: 213 additions & 0 deletions pyannote/audio/pipelines/multilabel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
# The MIT License (MIT)
#
# Copyright (c) 2022- CNRS
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

# AUTHORS
# Hadrien TITEUX - https://github.com/hadware
# Hervé BREDIN - http://herve.niderb.fr


from typing import Callable, Optional, Union

from pyannote.core import Annotation, SlidingWindowFeature
from pyannote.metrics.identification import IdentificationErrorRate
from pyannote.pipeline.parameter import ParamDict, Uniform

from pyannote.audio import Inference
from pyannote.audio.core.io import AudioFile
from pyannote.audio.core.pipeline import Pipeline
from pyannote.audio.utils.metric import MacroAverageFMeasure

from ..utils.signal import Binarize
from .utils import PipelineModel, get_devices, get_model


class MultiLabelSegmentation(Pipeline):
"""Generic multi-label segmentation

Parameters
----------
segmentation : Model, str, or dict
Pretrained multi-label segmentation model.
See pyannote.audio.pipelines.utils.get_model for supported format.
fscore : bool, optional
Optimize for average (precision/recall) fscore, over all classes.
Defaults to optimizing identification error rate.
share_min_duration : bool, optional
If True, `min_duration_on` and `min_duration_off` are shared among labels.
inference_kwargs : dict, optional
Keywords arguments passed to Inference.

Hyper-parameters
----------------
Each {label} of the segmentation model is assigned four hyper-parameters:
onset, offset : float
Onset/offset detection thresholds
min_duration_on : float
Remove {label} regions shorter than that many seconds.
Shared between labels if `share_min_duration` is `True`.
min_duration_off : float
Fill non-{label} regions shorter than that many seconds.
Shared between labels if `share_min_duration` is `True`.
"""

def __init__(
self,
segmentation: PipelineModel = None,
fscore: bool = False,
share_min_duration: bool = False,
**inference_kwargs,
):

super().__init__()

if segmentation is None:
raise ValueError(
"MultiLabelSegmentation pipeline must be provided with a `segmentation` model."
)

self.segmentation = segmentation
self.fscore = fscore
self.share_min_duration = share_min_duration

# load model and send it to GPU (when available and not already on GPU)
model = get_model(segmentation)
if model.device.type == "cpu":
(segmentation_device,) = get_devices(needs=1)
model.to(segmentation_device)

self._classes = model.specifications.classes
self._segmentation = Inference(model, **inference_kwargs)

# hyper-parameters used for hysteresis thresholding and postprocessing
if self.share_min_duration:
self.min_duration_on = Uniform(0.0, 2.0)
self.min_duration_off = Uniform(0.0, 2.0)

self.thresholds = ParamDict(
**{
label: ParamDict(
onset=Uniform(0.0, 1.0),
offset=Uniform(0.0, 1.0),
)
for label in self._classes
}
)
else:
self.thresholds = ParamDict(
**{
label: ParamDict(
onset=Uniform(0.0, 1.0),
offset=Uniform(0.0, 1.0),
min_duration_on=Uniform(0.0, 2.0),
min_duration_off=Uniform(0.0, 2.0),
)
for label in self._classes
}
)

# needed by pyannote.audio Prodigy recipes
def classes(self):
return self._classes

def initialize(self):
"""Initialize pipeline with current set of parameters"""
self._binarize = {
label: Binarize(
onset=self.thresholds[label]["onset"],
offset=self.thresholds[label]["offset"],
min_duration_on=(self.thresholds[label]["min_duration_on"]
if not self.share_min_duration
else self.min_duration_on), # noqa
min_duration_off=(self.thresholds[label]["min_duration_off"]
if not self.share_min_duration
else self.min_duration_off) , # noqa
)
for label in self._classes
}

CACHED_SEGMENTATION = "cache/segmentation"

def apply(self, file: AudioFile, hook: Optional[Callable] = None) -> Annotation:
"""Apply multi-label detection

Parameters
----------
file : AudioFile
Processed file.
hook : callable, optional
Hook called after each major step of the pipeline with the following
signature: hook("step_name", step_artefact, file=file)

Returns
-------
detection : Annotation
Detected regions.
"""

# setup hook (e.g. for debugging purposes)
hook = self.setup_hook(file, hook=hook)

# apply segmentation model (only if needed)
# output shape is (num_chunks, num_frames, num_classes)
if self.training:
if self.CACHED_SEGMENTATION in file:
segmentations = file[self.CACHED_SEGMENTATION]
else:
segmentations = self._segmentation(file)
file[self.CACHED_SEGMENTATION] = segmentations
else:
segmentations: SlidingWindowFeature = self._segmentation(file)

hook("segmentation", segmentations)

# apply hysteresis thresholding on each class separately
detection = Annotation(uri=file["uri"])

for i, label in enumerate(self._classes):
# extract raw segmentation of current label
label_segmentation = SlidingWindowFeature(
segmentations.data[:, i: i + 1], segmentations.sliding_window
)
# obtain hard segments
label_annotation: Annotation = self._binarize[label](label_segmentation)

# add them to the pool of labels
detection.update(
label_annotation.rename_labels(
dict.fromkeys(label_annotation.labels(), label), copy=False
)
)

return detection

def get_metric(self) -> Union[MacroAverageFMeasure, IdentificationErrorRate]:
"""Return new instance of identification metric"""

if self.fscore:
return MacroAverageFMeasure(classes=self._classes)

return IdentificationErrorRate()

def get_direction(self):
if self.fscore:
return "maximize"
return "minimize"
7 changes: 2 additions & 5 deletions pyannote/audio/tasks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,15 @@
OverlappedSpeechDetection,
)

from .segmentation.speaker_tracking import SpeakerTracking # isort:skip

from .segmentation.multilabel import MultiLabelSegmentation # isort:skip
from .segmentation.segmentation import Segmentation # isort:skip

from .embedding.arcface import SupervisedRepresentationLearningWithArcFace # isort:skip

SpeakerEmbedding = SupervisedRepresentationLearningWithArcFace

__all__ = [
"Segmentation",
"VoiceActivityDetection",
"OverlappedSpeechDetection",
"SpeakerTracking",
"MultiLabelSegmentation",
"SpeakerEmbedding",
]
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from typing import Dict, Optional, Sequence, Text, Tuple, Union
import warnings
from typing import Dict, Optional, Sequence, Text, Tuple, Union, List

import numpy as np
import torch
Expand All @@ -32,20 +33,21 @@
from pyannote.audio.tasks.segmentation.mixins import SegmentationTaskMixin


class SpeakerTracking(SegmentationTaskMixin, Task):
"""Speaker tracking
class MultiLabelSegmentation(SegmentationTaskMixin, Task):
"""Generic multi-label segmentation

Speaker tracking is the process of determining if and when a (previously
enrolled) person's voice can be heard in a given audio recording.
Multi-label segmentation is the process of detecting temporal intervals
when a specific audio class is active.

Here, it is addressed with the same approach as voice activity detection,
except {"non-speech", "speech"} classes are replaced by {"speaker1", ...,
"speaker_N"} where N is the number of speakers in the training set.
Example use cases include speaker tracking, gender (male/female)
classification, or audio event detection.

Parameters
----------
protocol : Protocol
pyannote.database protocol
classes : List[str], optional
List of classes. Defaults to the list of classes available in the training set.
duration : float, optional
Chunks duration. Defaults to 2s.
warm_up : float or (float, float), optional
Expand Down Expand Up @@ -78,19 +80,19 @@ class SpeakerTracking(SegmentationTaskMixin, Task):
"""

def __init__(
self,
protocol: Protocol,
duration: float = 2.0,
warm_up: Union[float, Tuple[float, float]] = 0.0,
balance: Text = None,
weight: Text = None,
batch_size: int = 32,
num_workers: int = None,
pin_memory: bool = False,
augmentation: BaseWaveformTransform = None,
metric: Union[Metric, Sequence[Metric], Dict[str, Metric]] = None,
self,
protocol: Protocol,
classes: Optional[List[str]] = None,
duration: float = 2.0,
warm_up: Union[float, Tuple[float, float]] = 0.0,
balance: Text = None,
weight: Text = None,
batch_size: int = 32,
num_workers: int = None,
pin_memory: bool = False,
augmentation: BaseWaveformTransform = None,
metric: Union[Metric, Sequence[Metric], Dict[str, Metric]] = None,
):

super().__init__(
protocol,
duration=duration,
Expand All @@ -104,20 +106,29 @@ def __init__(

self.balance = balance
self.weight = weight
self.classes = classes

# for speaker tracking, task specification depends
# on the data: we do not know in advance which
# speakers should be tracked. therefore, we postpone
# the definition of specifications.
# task specification depends on the data: we do not know in advance which
# classes should be detected. therefore, we postpone the definition of
# specifications to setup()

def setup(self, stage: Optional[str] = None):

super().setup(stage=stage)

classes_from_training_set = sorted(self._train_metadata["annotation"])
if self.classes is None:
classes = classes_from_training_set
else:
if set(classes_from_training_set) != set(self.classes):
warnings.warn(
f"Mismatch between classes passed to the task ({self.classes}) "
f"and those of the training set ({classes_from_training_set})."
)
classes = self.classes

self.specifications = Specifications(
# one class per speaker
classes=sorted(self._train_metadata["annotation"]),
# multiple speakers can be active at once
classes=classes,
problem=Problem.MULTI_LABEL_CLASSIFICATION,
resolution=Resolution.FRAME,
duration=self.duration,
Expand Down