<p align="center">
<img width="100%" src="https://github.com/juanmc2005/diart/blob/main/logo.jpg?raw=true" title="diart logo" />
</p>
<p align="center">
<i>πΏ Build AI-powered real-time audio applications in a breeze πΏ</i>
</p>
<p align="center">
<img alt="PyPI Version" src="https://img.shields.io/pypi/v/diart?color=g">
<img alt="PyPI Downloads" src="https://static.pepy.tech/personalized-badge/diart?period=total&units=international_system&left_color=grey&right_color=brightgreen&left_text=downloads">
<img alt="Python Versions" src="https://img.shields.io/badge/python-3.8%20%7C%203.9%20%7C%203.10-dark_green">
<img alt="Code size in bytes" src="https://img.shields.io/github/languages/code-size/juanmc2005/StreamingSpeakerDiarization?color=g">
<img alt="License" src="https://img.shields.io/github/license/juanmc2005/StreamingSpeakerDiarization?color=g">
<a href="https://joss.theoj.org/papers/cc9807c6de75ea4c29025c7bd0d31996"><img src="https://joss.theoj.org/papers/cc9807c6de75ea4c29025c7bd0d31996/status.svg"></a>
</p>
<div align="center">
<h4>
<a href="#-installation">
πΎ Installation
</a>
<span> | </span>
<a href="#%EF%B8%8F-stream-audio">
ποΈ Stream audio
</a>
<span> | </span>
<a href="#-models">
π§ Models
</a>
<br />
<a href="#-tune-hyper-parameters">
π Tuning
</a>
<span> | </span>
<a href="#-build-pipelines">
π§ π Pipelines
</a>
<span> | </span>
<a href="#-websockets">
π WebSockets
</a>
<span> | </span>
<a href="#-powered-by-research">
π¬ Research
</a>
</h4>
</div>
<br/>
<p align="center">
<img width="100%" src="https://github.com/juanmc2005/diart/blob/main/demo.gif?raw=true" title="Real-time diarization example" />
</p>
## β‘ Quick introduction
Diart is a python framework to build AI-powered real-time audio applications.
Its key feature is the ability to recognize different speakers in real time with state-of-the-art performance,
a task commonly known as "speaker diarization".
The pipeline `diart.SpeakerDiarization` combines a speaker segmentation and a speaker embedding model
to power an incremental clustering algorithm that gets more accurate as the conversation progresses:
<p align="center">
<img width="100%" src="https://github.com/juanmc2005/diart/blob/main/pipeline.gif?raw=true" title="Real-time speaker diarization pipeline" />
</p>
With diart you can also create your own custom AI pipeline, benchmark it,
tune its hyper-parameters, and even serve it on the web using websockets.
**We provide pre-trained pipelines for:**
- Speaker Diarization
- Voice Activity Detection
- Transcription ([coming soon](https://github.com/juanmc2005/diart/pull/144))
- [Speaker-Aware Transcription](https://betterprogramming.pub/color-your-captions-streamlining-live-transcriptions-with-diart-and-openais-whisper-6203350234ef) ([coming soon](https://github.com/juanmc2005/diart/pull/147))
## πΎ Installation
**1) Make sure your system has the following dependencies:**
```
ffmpeg < 4.4
portaudio == 19.6.X
libsndfile >= 1.2.2
```
Alternatively, we provide an `environment.yml` file for a pre-configured conda environment:
```shell
conda env create -f diart/environment.yml
conda activate diart
```
**2) Install the package:**
```shell
pip install diart
```
### Get access to πΉ pyannote models
By default, diart is based on [pyannote.audio](https://github.com/pyannote/pyannote-audio) models from the [huggingface](https://huggingface.co/) hub.
In order to use them, please follow these steps:
1) [Accept user conditions](https://huggingface.co/pyannote/segmentation) for the `pyannote/segmentation` model
2) [Accept user conditions](https://huggingface.co/pyannote/segmentation-3.0) for the newest `pyannote/segmentation-3.0` model
3) [Accept user conditions](https://huggingface.co/pyannote/embedding) for the `pyannote/embedding` model
4) Install [huggingface-cli](https://huggingface.co/docs/huggingface_hub/quick-start#install-the-hub-library) and [log in](https://huggingface.co/docs/huggingface_hub/quick-start#login) with your user access token (or provide it manually in diart CLI or API).
## ποΈ Stream audio
### From the command line
A recorded conversation:
```shell
diart.stream /path/to/audio.wav
```
A live conversation:
```shell
# Use "microphone:ID" to select a non-default device
# See `python -m sounddevice` for available devices
diart.stream microphone
```
By default, diart runs a speaker diarization pipeline, equivalent to setting `--pipeline SpeakerDiarization`,
but you can also set it to `--pipeline VoiceActivityDetection`. See `diart.stream -h` for more options.
### From python
Use `StreamingInference` to run a pipeline on an audio source and write the results to disk:
```python
from diart import SpeakerDiarization
from diart.sources import MicrophoneAudioSource
from diart.inference import StreamingInference
from diart.sinks import RTTMWriter
pipeline = SpeakerDiarization()
mic = MicrophoneAudioSource()
inference = StreamingInference(pipeline, mic, do_plot=True)
inference.attach_observers(RTTMWriter(mic.uri, "/output/file.rttm"))
prediction = inference()
```
For inference and evaluation on a dataset we recommend to use `Benchmark` (see notes on [reproducibility](#reproducibility)).
## π§ Models
You can use other models with the `--segmentation` and `--embedding` arguments.
Or in python:
```python
import diart.models as m
segmentation = m.SegmentationModel.from_pretrained("model_name")
embedding = m.EmbeddingModel.from_pretrained("model_name")
```
### Pre-trained models
Below is a list of all the models currently supported by diart:
| Model Name | Model Type | CPU Time* | GPU Time* |
|---------------------------------------------------------------------------------------------------------------------------|--------------|-----------|-----------|
| [π€](https://huggingface.co/pyannote/segmentation) `pyannote/segmentation` (default) | segmentation | 12ms | 8ms |
| [π€](https://huggingface.co/pyannote/segmentation-3.0) `pyannote/segmentation-3.0` | segmentation | 11ms | 8ms |
| [π€](https://huggingface.co/pyannote/embedding) `pyannote/embedding` (default) | embedding | 26ms | 12ms |
| [π€](https://huggingface.co/hbredin/wespeaker-voxceleb-resnet34-LM) `hbredin/wespeaker-voxceleb-resnet34-LM` (ONNX) | embedding | 48ms | 15ms |
| [π€](https://huggingface.co/pyannote/wespeaker-voxceleb-resnet34-LM) `pyannote/wespeaker-voxceleb-resnet34-LM` (PyTorch) | embedding | 150ms | 29ms |
| [π€](https://huggingface.co/speechbrain/spkrec-xvect-voxceleb) `speechbrain/spkrec-xvect-voxceleb` | embedding | 41ms | 15ms |
| [π€](https://huggingface.co/speechbrain/spkrec-ecapa-voxceleb) `speechbrain/spkrec-ecapa-voxceleb` | embedding | 41ms | 14ms |
| [π€](https://huggingface.co/speechbrain/spkrec-ecapa-voxceleb-mel-spec) `speechbrain/spkrec-ecapa-voxceleb-mel-spec` | embedding | 42ms | 14ms |
| [π€](https://huggingface.co/speechbrain/spkrec-resnet-voxceleb) `speechbrain/spkrec-resnet-voxceleb` | embedding | 41ms | 16ms |
| [π€](https://huggingface.co/nvidia/speakerverification_en_titanet_large) `nvidia/speakerverification_en_titanet_large` | embedding | 91ms | 16ms |
The latency of segmentation models is measured in a VAD pipeline (5s chunks).
The latency of embedding models is measured in a diarization pipeline using `pyannote/segmentation` (also 5s chunks).
\* CPU: AMD Ryzen 9 - GPU: RTX 4060 Max-Q
### Custom models
Third-party models can be integrated by providing a loader function:
```python
from diart import SpeakerDiarization, SpeakerDiarizationConfig
from diart.models import EmbeddingModel, SegmentationModel
def segmentation_loader():
# It should take a waveform and return a segmentation tensor
return load_pretrained_model("my_model.ckpt")
def embedding_loader():
# It should take (waveform, weights) and return per-speaker embeddings
return load_pretrained_model("my_other_model.ckpt")
segmentation = SegmentationModel(segmentation_loader)
embedding = EmbeddingModel(embedding_loader)
config = SpeakerDiarizationConfig(
segmentation=segmentation,
embedding=embedding,
)
pipeline = SpeakerDiarization(config)
```
If you have an ONNX model, you can use `from_onnx()`:
```python
from diart.models import EmbeddingModel
embedding = EmbeddingModel.from_onnx(
model_path="my_model.ckpt",
input_names=["x", "w"], # defaults to ["waveform", "weights"]
output_name="output", # defaults to "embedding"
)
```
## π Tune hyper-parameters
Diart implements an optimizer based on [optuna](https://optuna.readthedocs.io/en/stable/index.html) that allows you to tune pipeline hyper-parameters to your needs.
### From the command line
```shell
diart.tune /wav/dir --reference /rttm/dir --output /output/dir
```
See `diart.tune -h` for more options.
### From python
```python
from diart.optim import Optimizer
optimizer = Optimizer("/wav/dir", "/rttm/dir", "/output/dir")
optimizer(num_iter=100)
```
This will write results to an sqlite database in `/output/dir`.
### Distributed tuning
For bigger datasets, it is sometimes more convenient to run multiple optimization processes in parallel.
To do this, create a study on a [recommended DBMS](https://optuna.readthedocs.io/en/stable/tutorial/10_key_features/004_distributed.html#sphx-glr-tutorial-10-key-features-004-distributed-py) (e.g. MySQL or PostgreSQL) making sure that the study and database names match:
```shell
mysql -u root -e "CREATE DATABASE IF NOT EXISTS example"
optuna create-study --study-name "example" --storage "mysql://root@localhost/example"
```
You can now run multiple identical optimizers pointing to this database:
```shell
diart.tune /wav/dir --reference /rttm/dir --storage mysql://root@localhost/example
```
or in python:
```python
from diart.optim import Optimizer
from optuna.samplers import TPESampler
import optuna
db = "mysql://root@localhost/example"
study = optuna.load_study("example", db, TPESampler())
optimizer = Optimizer("/wav/dir", "/rttm/dir", study)
optimizer(num_iter=100)
```
## π§ π Build pipelines
For a more advanced usage, diart also provides building blocks that can be combined to create your own pipeline.
Streaming is powered by [RxPY](https://github.com/ReactiveX/RxPY), but the `blocks` module is completely independent and can be used separately.
### Example
Obtain overlap-aware speaker embeddings from a microphone stream:
```python
import rx.operators as ops
import diart.operators as dops
from diart.sources import MicrophoneAudioSource
from diart.blocks import SpeakerSegmentation, OverlapAwareSpeakerEmbedding
segmentation = SpeakerSegmentation.from_pretrained("pyannote/segmentation")
embedding = OverlapAwareSpeakerEmbedding.from_pretrained("pyannote/embedding")
mic = MicrophoneAudioSource()
stream = mic.stream.pipe(
# Reformat stream to 5s duration and 500ms shift
dops.rearrange_audio_stream(sample_rate=segmentation.model.sample_rate),
ops.map(lambda wav: (wav, segmentation(wav))),
ops.starmap(embedding)
).subscribe(on_next=lambda emb: print(emb.shape))
mic.read()
```
Output:
```
# Shape is (batch_size, num_speakers, embedding_dim)
torch.Size([1, 3, 512])
torch.Size([1, 3, 512])
torch.Size([1, 3, 512])
...
```
## π WebSockets
Diart is also compatible with the WebSocket protocol to serve pipelines on the web.
### From the command line
```shell
diart.serve --host 0.0.0.0 --port 7007
diart.client microphone --host <server-address> --port 7007
```
**Note:** make sure that the client uses the same `step` and `sample_rate` than the server with `--step` and `-sr`.
See `-h` for more options.
### From python
For customized solutions, a server can also be created in python using the `WebSocketAudioSource`:
```python
from diart import SpeakerDiarization
from diart.sources import WebSocketAudioSource
from diart.inference import StreamingInference
pipeline = SpeakerDiarization()
source = WebSocketAudioSource(pipeline.config.sample_rate, "localhost", 7007)
inference = StreamingInference(pipeline, source)
inference.attach_hooks(lambda ann_wav: source.send(ann_wav[0].to_rttm()))
prediction = inference()
```
## π¬ Powered by research
Diart is the official implementation of the paper
[Overlap-aware low-latency online speaker diarization based on end-to-end local segmentation](https://github.com/juanmc2005/diart/blob/main/paper.pdf)
by [Juan Manuel Coria](https://juanmc2005.github.io/),
[HervΓ© Bredin](https://herve.niderb.fr),
[Sahar Ghannay](https://saharghannay.github.io/)
and [Sophie Rosset](https://perso.limsi.fr/rosset/).
> We propose to address online speaker diarization as a combination of incremental clustering and local diarization applied to a rolling buffer updated every 500ms. Every single step of the proposed pipeline is designed to take full advantage of the strong ability of a recently proposed end-to-end overlap-aware segmentation to detect and separate overlapping speakers. In particular, we propose a modified version of the statistics pooling layer (initially introduced in the x-vector architecture) to give less weight to frames where the segmentation model predicts simultaneous speakers. Furthermore, we derive cannot-link constraints from the initial segmentation step to prevent two local speakers from being wrongfully merged during the incremental clustering step. Finally, we show how the latency of the proposed approach can be adjusted between 500ms and 5s to match the requirements of a particular use case, and we provide a systematic analysis of the influence of latency on the overall performance (on AMI, DIHARD and VoxConverse).
<p align="center">
<img height="400" src="https://github.com/juanmc2005/diart/blob/main/figure1.png?raw=true" title="Visual explanation of the system" width="325" />
</p>
### Citation
If you found diart useful, please make sure to cite our paper:
```bibtex
@inproceedings{diart,
author={Coria, Juan M. and Bredin, HervΓ© and Ghannay, Sahar and Rosset, Sophie},
booktitle={2021 IEEE Automatic Speech Recognition and Understanding Workshop (ASRU)},
title={Overlap-Aware Low-Latency Online Speaker Diarization Based on End-to-End Local Segmentation},
year={2021},
pages={1139-1146},
doi={10.1109/ASRU51503.2021.9688044},
}
```
### Reproducibility
![Results table](https://github.com/juanmc2005/diart/blob/main/table1.png?raw=true)
**Important:** We highly recommend installing `pyannote.audio<3.1` to reproduce these results.
For more information, see [this issue](https://github.com/juanmc2005/diart/issues/214).
Diart aims to be lightweight and capable of real-time streaming in practical scenarios.
Its performance is very close to what is reported in the paper (and sometimes even a bit better).
To obtain the best results, make sure to use the following hyper-parameters:
| Dataset | latency | tau | rho | delta |
|-------------|---------|--------|--------|-------|
| DIHARD III | any | 0.555 | 0.422 | 1.517 |
| AMI | any | 0.507 | 0.006 | 1.057 |
| VoxConverse | any | 0.576 | 0.915 | 0.648 |
| DIHARD II | 1s | 0.619 | 0.326 | 0.997 |
| DIHARD II | 5s | 0.555 | 0.422 | 1.517 |
`diart.benchmark` and `diart.inference.Benchmark` can run, evaluate and measure the real-time latency of the pipeline. For instance, for a DIHARD III configuration:
```shell
diart.benchmark /wav/dir --reference /rttm/dir --tau-active=0.555 --rho-update=0.422 --delta-new=1.517 --segmentation pyannote/segmentation@Interspeech2021
```
or using the inference API:
```python
from diart.inference import Benchmark, Parallelize
from diart import SpeakerDiarization, SpeakerDiarizationConfig
from diart.models import SegmentationModel
benchmark = Benchmark("/wav/dir", "/rttm/dir")
model_name = "pyannote/segmentation@Interspeech2021"
model = SegmentationModel.from_pretrained(model_name)
config = SpeakerDiarizationConfig(
# Set the segmentation model used in the paper
segmentation=model,
step=0.5,
latency=0.5,
tau_active=0.555,
rho_update=0.422,
delta_new=1.517
)
benchmark(SpeakerDiarization, config)
# Run the same benchmark in parallel
p_benchmark = Parallelize(benchmark, num_workers=4)
if __name__ == "__main__": # Needed for multiprocessing
p_benchmark(SpeakerDiarization, config)
```
This pre-calculates model outputs in batches, so it runs a lot faster.
See `diart.benchmark -h` for more options.
For convenience and to facilitate future comparisons, we also provide the
<a href="https://github.com/juanmc2005/diart/tree/main/expected_outputs">expected outputs</a>
of the paper implementation in RTTM format for every entry of Table 1 and Figure 5.
This includes the VBx offline topline as well as our proposed online approach with
latencies 500ms, 1s, 2s, 3s, 4s, and 5s.
![Figure 5](https://github.com/juanmc2005/diart/blob/main/figure5.png?raw=true)
## π License
```
MIT License
Copyright (c) 2021 UniversitΓ© Paris-Saclay
Copyright (c) 2021 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.
```
<p style="color:grey;font-size:14px;">Logo generated by <a href="https://www.designevo.com/" title="Free Online Logo Maker">DesignEvo free logo designer</a></p>
Raw data
{
"_id": null,
"home_page": "https://github.com/juanmc2005/diart",
"name": "diart",
"maintainer": null,
"docs_url": null,
"requires_python": null,
"maintainer_email": null,
"keywords": "speaker diarization, streaming, online, real time, rxpy",
"author": "Juan Manuel Coria",
"author_email": null,
"download_url": "https://files.pythonhosted.org/packages/2e/04/28838c037571592dba593dd8036ab90998f353b15536201a29dbe624dbcb/diart-0.9.1.tar.gz",
"platform": null,
"description": "<p align=\"center\">\n<img width=\"100%\" src=\"https://github.com/juanmc2005/diart/blob/main/logo.jpg?raw=true\" title=\"diart logo\" />\n</p>\n\n<p align=\"center\">\n<i>\ud83c\udf3f Build AI-powered real-time audio applications in a breeze \ud83c\udf3f</i>\n</p>\n\n<p align=\"center\">\n<img alt=\"PyPI Version\" src=\"https://img.shields.io/pypi/v/diart?color=g\">\n<img alt=\"PyPI Downloads\" src=\"https://static.pepy.tech/personalized-badge/diart?period=total&units=international_system&left_color=grey&right_color=brightgreen&left_text=downloads\">\n<img alt=\"Python Versions\" src=\"https://img.shields.io/badge/python-3.8%20%7C%203.9%20%7C%203.10-dark_green\">\n<img alt=\"Code size in bytes\" src=\"https://img.shields.io/github/languages/code-size/juanmc2005/StreamingSpeakerDiarization?color=g\">\n<img alt=\"License\" src=\"https://img.shields.io/github/license/juanmc2005/StreamingSpeakerDiarization?color=g\">\n<a href=\"https://joss.theoj.org/papers/cc9807c6de75ea4c29025c7bd0d31996\"><img src=\"https://joss.theoj.org/papers/cc9807c6de75ea4c29025c7bd0d31996/status.svg\"></a>\n</p>\n\n<div align=\"center\">\n <h4>\n <a href=\"#-installation\">\n \ud83d\udcbe Installation\n </a>\n <span> | </span>\n <a href=\"#%EF%B8%8F-stream-audio\">\n \ud83c\udf99\ufe0f Stream audio\n </a>\n <span> | </span>\n <a href=\"#-models\">\n \ud83e\udde0 Models\n </a>\n <br />\n <a href=\"#-tune-hyper-parameters\">\n \ud83d\udcc8 Tuning\n </a>\n <span> | </span>\n <a href=\"#-build-pipelines\">\n \ud83e\udde0\ud83d\udd17 Pipelines\n </a>\n <span> | </span>\n <a href=\"#-websockets\">\n \ud83c\udf10 WebSockets\n </a>\n <span> | </span>\n <a href=\"#-powered-by-research\">\n \ud83d\udd2c Research\n </a>\n </h4>\n</div>\n\n<br/>\n\n<p align=\"center\">\n<img width=\"100%\" src=\"https://github.com/juanmc2005/diart/blob/main/demo.gif?raw=true\" title=\"Real-time diarization example\" />\n</p>\n\n## \u26a1 Quick introduction\n\nDiart is a python framework to build AI-powered real-time audio applications.\nIts key feature is the ability to recognize different speakers in real time with state-of-the-art performance,\na task commonly known as \"speaker diarization\".\n\nThe pipeline `diart.SpeakerDiarization` combines a speaker segmentation and a speaker embedding model\nto power an incremental clustering algorithm that gets more accurate as the conversation progresses:\n\n<p align=\"center\">\n<img width=\"100%\" src=\"https://github.com/juanmc2005/diart/blob/main/pipeline.gif?raw=true\" title=\"Real-time speaker diarization pipeline\" />\n</p>\n\nWith diart you can also create your own custom AI pipeline, benchmark it,\ntune its hyper-parameters, and even serve it on the web using websockets.\n\n**We provide pre-trained pipelines for:**\n\n- Speaker Diarization\n- Voice Activity Detection\n- Transcription ([coming soon](https://github.com/juanmc2005/diart/pull/144))\n- [Speaker-Aware Transcription](https://betterprogramming.pub/color-your-captions-streamlining-live-transcriptions-with-diart-and-openais-whisper-6203350234ef) ([coming soon](https://github.com/juanmc2005/diart/pull/147))\n\n## \ud83d\udcbe Installation\n\n**1) Make sure your system has the following dependencies:**\n\n```\nffmpeg < 4.4\nportaudio == 19.6.X\nlibsndfile >= 1.2.2\n```\n\nAlternatively, we provide an `environment.yml` file for a pre-configured conda environment:\n\n```shell\nconda env create -f diart/environment.yml\nconda activate diart\n```\n\n**2) Install the package:**\n```shell\npip install diart\n```\n\n### Get access to \ud83c\udfb9 pyannote models\n\nBy default, diart is based on [pyannote.audio](https://github.com/pyannote/pyannote-audio) models from the [huggingface](https://huggingface.co/) hub.\nIn order to use them, please follow these steps:\n\n1) [Accept user conditions](https://huggingface.co/pyannote/segmentation) for the `pyannote/segmentation` model\n2) [Accept user conditions](https://huggingface.co/pyannote/segmentation-3.0) for the newest `pyannote/segmentation-3.0` model\n3) [Accept user conditions](https://huggingface.co/pyannote/embedding) for the `pyannote/embedding` model\n4) Install [huggingface-cli](https://huggingface.co/docs/huggingface_hub/quick-start#install-the-hub-library) and [log in](https://huggingface.co/docs/huggingface_hub/quick-start#login) with your user access token (or provide it manually in diart CLI or API).\n\n## \ud83c\udf99\ufe0f Stream audio\n\n### From the command line\n\nA recorded conversation:\n\n```shell\ndiart.stream /path/to/audio.wav\n```\n\nA live conversation:\n\n```shell\n# Use \"microphone:ID\" to select a non-default device\n# See `python -m sounddevice` for available devices\ndiart.stream microphone\n```\n\nBy default, diart runs a speaker diarization pipeline, equivalent to setting `--pipeline SpeakerDiarization`,\nbut you can also set it to `--pipeline VoiceActivityDetection`. See `diart.stream -h` for more options.\n\n### From python\n\nUse `StreamingInference` to run a pipeline on an audio source and write the results to disk:\n\n```python\nfrom diart import SpeakerDiarization\nfrom diart.sources import MicrophoneAudioSource\nfrom diart.inference import StreamingInference\nfrom diart.sinks import RTTMWriter\n\npipeline = SpeakerDiarization()\nmic = MicrophoneAudioSource()\ninference = StreamingInference(pipeline, mic, do_plot=True)\ninference.attach_observers(RTTMWriter(mic.uri, \"/output/file.rttm\"))\nprediction = inference()\n```\n\nFor inference and evaluation on a dataset we recommend to use `Benchmark` (see notes on [reproducibility](#reproducibility)).\n\n## \ud83e\udde0 Models\n\nYou can use other models with the `--segmentation` and `--embedding` arguments.\nOr in python:\n\n```python\nimport diart.models as m\n\nsegmentation = m.SegmentationModel.from_pretrained(\"model_name\")\nembedding = m.EmbeddingModel.from_pretrained(\"model_name\")\n```\n\n### Pre-trained models\n\nBelow is a list of all the models currently supported by diart:\n\n| Model Name | Model Type | CPU Time* | GPU Time* |\n|---------------------------------------------------------------------------------------------------------------------------|--------------|-----------|-----------|\n| [\ud83e\udd17](https://huggingface.co/pyannote/segmentation) `pyannote/segmentation` (default) | segmentation | 12ms | 8ms |\n| [\ud83e\udd17](https://huggingface.co/pyannote/segmentation-3.0) `pyannote/segmentation-3.0` | segmentation | 11ms | 8ms |\n| [\ud83e\udd17](https://huggingface.co/pyannote/embedding) `pyannote/embedding` (default) | embedding | 26ms | 12ms |\n| [\ud83e\udd17](https://huggingface.co/hbredin/wespeaker-voxceleb-resnet34-LM) `hbredin/wespeaker-voxceleb-resnet34-LM` (ONNX) | embedding | 48ms | 15ms |\n| [\ud83e\udd17](https://huggingface.co/pyannote/wespeaker-voxceleb-resnet34-LM) `pyannote/wespeaker-voxceleb-resnet34-LM` (PyTorch) | embedding | 150ms | 29ms |\n| [\ud83e\udd17](https://huggingface.co/speechbrain/spkrec-xvect-voxceleb) `speechbrain/spkrec-xvect-voxceleb` | embedding | 41ms | 15ms |\n| [\ud83e\udd17](https://huggingface.co/speechbrain/spkrec-ecapa-voxceleb) `speechbrain/spkrec-ecapa-voxceleb` | embedding | 41ms | 14ms |\n| [\ud83e\udd17](https://huggingface.co/speechbrain/spkrec-ecapa-voxceleb-mel-spec) `speechbrain/spkrec-ecapa-voxceleb-mel-spec` | embedding | 42ms | 14ms |\n| [\ud83e\udd17](https://huggingface.co/speechbrain/spkrec-resnet-voxceleb) `speechbrain/spkrec-resnet-voxceleb` | embedding | 41ms | 16ms |\n| [\ud83e\udd17](https://huggingface.co/nvidia/speakerverification_en_titanet_large) `nvidia/speakerverification_en_titanet_large` | embedding | 91ms | 16ms |\n\nThe latency of segmentation models is measured in a VAD pipeline (5s chunks).\n\nThe latency of embedding models is measured in a diarization pipeline using `pyannote/segmentation` (also 5s chunks).\n\n\\* CPU: AMD Ryzen 9 - GPU: RTX 4060 Max-Q\n\n### Custom models\n\nThird-party models can be integrated by providing a loader function:\n\n```python\nfrom diart import SpeakerDiarization, SpeakerDiarizationConfig\nfrom diart.models import EmbeddingModel, SegmentationModel\n\ndef segmentation_loader():\n # It should take a waveform and return a segmentation tensor\n return load_pretrained_model(\"my_model.ckpt\")\n\ndef embedding_loader():\n # It should take (waveform, weights) and return per-speaker embeddings\n return load_pretrained_model(\"my_other_model.ckpt\")\n\nsegmentation = SegmentationModel(segmentation_loader)\nembedding = EmbeddingModel(embedding_loader)\nconfig = SpeakerDiarizationConfig(\n segmentation=segmentation,\n embedding=embedding,\n)\npipeline = SpeakerDiarization(config)\n```\n\nIf you have an ONNX model, you can use `from_onnx()`:\n\n```python\nfrom diart.models import EmbeddingModel\n\nembedding = EmbeddingModel.from_onnx(\n model_path=\"my_model.ckpt\",\n input_names=[\"x\", \"w\"], # defaults to [\"waveform\", \"weights\"]\n output_name=\"output\", # defaults to \"embedding\"\n)\n```\n\n## \ud83d\udcc8 Tune hyper-parameters\n\nDiart implements an optimizer based on [optuna](https://optuna.readthedocs.io/en/stable/index.html) that allows you to tune pipeline hyper-parameters to your needs.\n\n### From the command line\n\n```shell\ndiart.tune /wav/dir --reference /rttm/dir --output /output/dir\n```\n\nSee `diart.tune -h` for more options.\n\n### From python\n\n```python\nfrom diart.optim import Optimizer\n\noptimizer = Optimizer(\"/wav/dir\", \"/rttm/dir\", \"/output/dir\")\noptimizer(num_iter=100)\n```\n\nThis will write results to an sqlite database in `/output/dir`.\n\n### Distributed tuning\n\nFor bigger datasets, it is sometimes more convenient to run multiple optimization processes in parallel.\nTo do this, create a study on a [recommended DBMS](https://optuna.readthedocs.io/en/stable/tutorial/10_key_features/004_distributed.html#sphx-glr-tutorial-10-key-features-004-distributed-py) (e.g. MySQL or PostgreSQL) making sure that the study and database names match:\n\n```shell\nmysql -u root -e \"CREATE DATABASE IF NOT EXISTS example\"\noptuna create-study --study-name \"example\" --storage \"mysql://root@localhost/example\"\n```\n\nYou can now run multiple identical optimizers pointing to this database:\n\n```shell\ndiart.tune /wav/dir --reference /rttm/dir --storage mysql://root@localhost/example\n```\n\nor in python:\n\n```python\nfrom diart.optim import Optimizer\nfrom optuna.samplers import TPESampler\nimport optuna\n\ndb = \"mysql://root@localhost/example\"\nstudy = optuna.load_study(\"example\", db, TPESampler())\noptimizer = Optimizer(\"/wav/dir\", \"/rttm/dir\", study)\noptimizer(num_iter=100)\n```\n\n## \ud83e\udde0\ud83d\udd17 Build pipelines\n\nFor a more advanced usage, diart also provides building blocks that can be combined to create your own pipeline.\nStreaming is powered by [RxPY](https://github.com/ReactiveX/RxPY), but the `blocks` module is completely independent and can be used separately.\n\n### Example\n\nObtain overlap-aware speaker embeddings from a microphone stream:\n\n```python\nimport rx.operators as ops\nimport diart.operators as dops\nfrom diart.sources import MicrophoneAudioSource\nfrom diart.blocks import SpeakerSegmentation, OverlapAwareSpeakerEmbedding\n\nsegmentation = SpeakerSegmentation.from_pretrained(\"pyannote/segmentation\")\nembedding = OverlapAwareSpeakerEmbedding.from_pretrained(\"pyannote/embedding\")\nmic = MicrophoneAudioSource()\n\nstream = mic.stream.pipe(\n # Reformat stream to 5s duration and 500ms shift\n dops.rearrange_audio_stream(sample_rate=segmentation.model.sample_rate),\n ops.map(lambda wav: (wav, segmentation(wav))),\n ops.starmap(embedding)\n).subscribe(on_next=lambda emb: print(emb.shape))\n\nmic.read()\n```\n\nOutput:\n\n```\n# Shape is (batch_size, num_speakers, embedding_dim)\ntorch.Size([1, 3, 512])\ntorch.Size([1, 3, 512])\ntorch.Size([1, 3, 512])\n...\n```\n\n## \ud83c\udf10 WebSockets\n\nDiart is also compatible with the WebSocket protocol to serve pipelines on the web.\n\n### From the command line\n\n```shell\ndiart.serve --host 0.0.0.0 --port 7007\ndiart.client microphone --host <server-address> --port 7007\n```\n\n**Note:** make sure that the client uses the same `step` and `sample_rate` than the server with `--step` and `-sr`.\n\nSee `-h` for more options.\n\n### From python\n\nFor customized solutions, a server can also be created in python using the `WebSocketAudioSource`:\n\n```python\nfrom diart import SpeakerDiarization\nfrom diart.sources import WebSocketAudioSource\nfrom diart.inference import StreamingInference\n\npipeline = SpeakerDiarization()\nsource = WebSocketAudioSource(pipeline.config.sample_rate, \"localhost\", 7007)\ninference = StreamingInference(pipeline, source)\ninference.attach_hooks(lambda ann_wav: source.send(ann_wav[0].to_rttm()))\nprediction = inference()\n```\n\n## \ud83d\udd2c Powered by research\n\nDiart is the official implementation of the paper\n[Overlap-aware low-latency online speaker diarization based on end-to-end local segmentation](https://github.com/juanmc2005/diart/blob/main/paper.pdf)\nby [Juan Manuel Coria](https://juanmc2005.github.io/),\n[Herv\u00e9 Bredin](https://herve.niderb.fr),\n[Sahar Ghannay](https://saharghannay.github.io/)\nand [Sophie Rosset](https://perso.limsi.fr/rosset/).\n\n\n> We propose to address online speaker diarization as a combination of incremental clustering and local diarization applied to a rolling buffer updated every 500ms. Every single step of the proposed pipeline is designed to take full advantage of the strong ability of a recently proposed end-to-end overlap-aware segmentation to detect and separate overlapping speakers. In particular, we propose a modified version of the statistics pooling layer (initially introduced in the x-vector architecture) to give less weight to frames where the segmentation model predicts simultaneous speakers. Furthermore, we derive cannot-link constraints from the initial segmentation step to prevent two local speakers from being wrongfully merged during the incremental clustering step. Finally, we show how the latency of the proposed approach can be adjusted between 500ms and 5s to match the requirements of a particular use case, and we provide a systematic analysis of the influence of latency on the overall performance (on AMI, DIHARD and VoxConverse).\n\n<p align=\"center\">\n<img height=\"400\" src=\"https://github.com/juanmc2005/diart/blob/main/figure1.png?raw=true\" title=\"Visual explanation of the system\" width=\"325\" />\n</p>\n\n### Citation\n\nIf you found diart useful, please make sure to cite our paper:\n\n```bibtex\n@inproceedings{diart, \n author={Coria, Juan M. and Bredin, Herv\u00e9 and Ghannay, Sahar and Rosset, Sophie}, \n booktitle={2021 IEEE Automatic Speech Recognition and Understanding Workshop (ASRU)}, \n title={Overlap-Aware Low-Latency Online Speaker Diarization Based on End-to-End Local Segmentation}, \n year={2021},\n pages={1139-1146},\n doi={10.1109/ASRU51503.2021.9688044},\n}\n```\n\n### Reproducibility\n\n![Results table](https://github.com/juanmc2005/diart/blob/main/table1.png?raw=true)\n\n**Important:** We highly recommend installing `pyannote.audio<3.1` to reproduce these results.\nFor more information, see [this issue](https://github.com/juanmc2005/diart/issues/214).\n\nDiart aims to be lightweight and capable of real-time streaming in practical scenarios.\nIts performance is very close to what is reported in the paper (and sometimes even a bit better).\n\nTo obtain the best results, make sure to use the following hyper-parameters:\n\n| Dataset | latency | tau | rho | delta |\n|-------------|---------|--------|--------|-------|\n| DIHARD III | any | 0.555 | 0.422 | 1.517 |\n| AMI | any | 0.507 | 0.006 | 1.057 |\n| VoxConverse | any | 0.576 | 0.915 | 0.648 |\n| DIHARD II | 1s | 0.619 | 0.326 | 0.997 |\n| DIHARD II | 5s | 0.555 | 0.422 | 1.517 |\n\n`diart.benchmark` and `diart.inference.Benchmark` can run, evaluate and measure the real-time latency of the pipeline. For instance, for a DIHARD III configuration:\n\n```shell\ndiart.benchmark /wav/dir --reference /rttm/dir --tau-active=0.555 --rho-update=0.422 --delta-new=1.517 --segmentation pyannote/segmentation@Interspeech2021\n```\n\nor using the inference API:\n\n```python\nfrom diart.inference import Benchmark, Parallelize\nfrom diart import SpeakerDiarization, SpeakerDiarizationConfig\nfrom diart.models import SegmentationModel\n\nbenchmark = Benchmark(\"/wav/dir\", \"/rttm/dir\")\n\nmodel_name = \"pyannote/segmentation@Interspeech2021\"\nmodel = SegmentationModel.from_pretrained(model_name)\nconfig = SpeakerDiarizationConfig(\n # Set the segmentation model used in the paper\n segmentation=model,\n step=0.5,\n latency=0.5,\n tau_active=0.555,\n rho_update=0.422,\n delta_new=1.517\n)\nbenchmark(SpeakerDiarization, config)\n\n# Run the same benchmark in parallel\np_benchmark = Parallelize(benchmark, num_workers=4)\nif __name__ == \"__main__\": # Needed for multiprocessing\n p_benchmark(SpeakerDiarization, config)\n```\n\nThis pre-calculates model outputs in batches, so it runs a lot faster.\nSee `diart.benchmark -h` for more options.\n\nFor convenience and to facilitate future comparisons, we also provide the\n<a href=\"https://github.com/juanmc2005/diart/tree/main/expected_outputs\">expected outputs</a>\nof the paper implementation in RTTM format for every entry of Table 1 and Figure 5.\nThis includes the VBx offline topline as well as our proposed online approach with\nlatencies 500ms, 1s, 2s, 3s, 4s, and 5s.\n\n![Figure 5](https://github.com/juanmc2005/diart/blob/main/figure5.png?raw=true)\n\n## \ud83d\udcd1 License\n\n```\nMIT License\n\nCopyright (c) 2021 Universit\u00e9 Paris-Saclay\nCopyright (c) 2021 CNRS\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n```\n\n<p style=\"color:grey;font-size:14px;\">Logo generated by <a href=\"https://www.designevo.com/\" title=\"Free Online Logo Maker\">DesignEvo free logo designer</a></p>\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "A python framework to build AI for real-time speech",
"version": "0.9.1",
"project_urls": {
"Homepage": "https://github.com/juanmc2005/diart"
},
"split_keywords": [
"speaker diarization",
" streaming",
" online",
" real time",
" rxpy"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "992fb5dc61859499051a2eb24a7172e48d4e7cf7ddcd809db8430932c556d382",
"md5": "2a6187ff488df03d3323dfb7cee934c9",
"sha256": "8fbcc3f9e391fe0c494c9d9c3a4358c322459c43f11697931e7a9616ae19f78d"
},
"downloads": -1,
"filename": "diart-0.9.1-py3-none-any.whl",
"has_sig": false,
"md5_digest": "2a6187ff488df03d3323dfb7cee934c9",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": null,
"size": 58806,
"upload_time": "2024-05-25T18:51:28",
"upload_time_iso_8601": "2024-05-25T18:51:28.434161Z",
"url": "https://files.pythonhosted.org/packages/99/2f/b5dc61859499051a2eb24a7172e48d4e7cf7ddcd809db8430932c556d382/diart-0.9.1-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "2e0428838c037571592dba593dd8036ab90998f353b15536201a29dbe624dbcb",
"md5": "4a5c981596622ed2f500a38cea2912dd",
"sha256": "e8aa0633699dba03c3520b0ca5be337f6b9a09a8a83adcd8235fc47317942678"
},
"downloads": -1,
"filename": "diart-0.9.1.tar.gz",
"has_sig": false,
"md5_digest": "4a5c981596622ed2f500a38cea2912dd",
"packagetype": "sdist",
"python_version": "source",
"requires_python": null,
"size": 53994,
"upload_time": "2024-05-25T18:51:30",
"upload_time_iso_8601": "2024-05-25T18:51:30.097079Z",
"url": "https://files.pythonhosted.org/packages/2e/04/28838c037571592dba593dd8036ab90998f353b15536201a29dbe624dbcb/diart-0.9.1.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-05-25 18:51:30",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "juanmc2005",
"github_project": "diart",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"requirements": [],
"lcname": "diart"
}