Package: diart
🌿 Build AI-powered real-time audio applications in a breeze 🌿💾 Installation|🎙️ Stream audio|🧠 Models📈 Tuning|🧠🔗 Pipelines|🌐 WebSockets|🔬 Research⚡ Quick introductionDiart 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 pipelinediart.SpeakerDiarizationcombines a speaker segmentation and a speaker embedding model
to power an incremental clustering algorithm that gets more accurate as the conversation progresses: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 DiarizationVoice Activity DetectionTranscription (coming soon)Speaker-Aware Transcription(coming soon)💾 Installation1) Make sure your system has the following dependencies:ffmpeg < 4.4
portaudio == 19.6.X
libsndfile >= 1.2.2Alternatively, we provide anenvironment.ymlfile for a pre-configured conda environment:condaenvcreate-fdiart/environment.yml
condaactivatediart2) Install the package:pipinstalldiartGet access to 🎹 pyannote modelsBy default, diart is based onpyannote.audiomodels from thehuggingfacehub.
In order to use them, please follow these steps:Accept user conditionsfor thepyannote/segmentationmodelAccept user conditionsfor the newestpyannote/segmentation-3.0modelAccept user conditionsfor thepyannote/embeddingmodelInstallhuggingface-cliandlog inwith your user access token (or provide it manually in diart CLI or API).🎙️ Stream audioFrom the command lineA recorded conversation:diart.stream/path/to/audio.wavA live conversation:# Use "microphone:ID" to select a non-default device# See `python -m sounddevice` for available devicesdiart.streammicrophoneBy default, diart runs a speaker diarization pipeline, equivalent to setting--pipeline SpeakerDiarization,
but you can also set it to--pipeline VoiceActivityDetection. Seediart.stream -hfor more options.From pythonUseStreamingInferenceto run a pipeline on an audio source and write the results to disk:fromdiartimportSpeakerDiarizationfromdiart.sourcesimportMicrophoneAudioSourcefromdiart.inferenceimportStreamingInferencefromdiart.sinksimportRTTMWriterpipeline=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 useBenchmark(see notes onreproducibility).🧠 ModelsYou can use other models with the--segmentationand--embeddingarguments.
Or in python:importdiart.modelsasmsegmentation=m.SegmentationModel.from_pretrained("model_name")embedding=m.EmbeddingModel.from_pretrained("model_name")Pre-trained modelsBelow is a list of all the models currently supported by diart:Model NameModel TypeCPU Time*GPU Time*🤗pyannote/segmentation(default)segmentation12ms8ms🤗pyannote/segmentation-3.0segmentation11ms8ms🤗pyannote/embedding(default)embedding26ms12ms🤗hbredin/wespeaker-voxceleb-resnet34-LM(ONNX)embedding48ms15ms🤗pyannote/wespeaker-voxceleb-resnet34-LM(PyTorch)embedding150ms29ms🤗speechbrain/spkrec-xvect-voxcelebembedding41ms15ms🤗speechbrain/spkrec-ecapa-voxcelebembedding41ms14ms🤗speechbrain/spkrec-ecapa-voxceleb-mel-specembedding42ms14ms🤗speechbrain/spkrec-resnet-voxcelebembedding41ms16ms🤗nvidia/speakerverification_en_titanet_largeembedding91ms16msThe latency of segmentation models is measured in a VAD pipeline (5s chunks).The latency of embedding models is measured in a diarization pipeline usingpyannote/segmentation(also 5s chunks).* CPU: AMD Ryzen 9 - GPU: RTX 4060 Max-QCustom modelsThird-party models can be integrated by providing a loader function:fromdiartimportSpeakerDiarization,SpeakerDiarizationConfigfromdiart.modelsimportEmbeddingModel,SegmentationModeldefsegmentation_loader():# It should take a waveform and return a segmentation tensorreturnload_pretrained_model("my_model.ckpt")defembedding_loader():# It should take (waveform, weights) and return per-speaker embeddingsreturnload_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 usefrom_onnx():fromdiart.modelsimportEmbeddingModelembedding=EmbeddingModel.from_onnx(model_path="my_model.ckpt",input_names=["x","w"],# defaults to ["waveform", "weights"]output_name="output",# defaults to "embedding")📈 Tune hyper-parametersDiart implements an optimizer based onoptunathat allows you to tune pipeline hyper-parameters to your needs.From the command linediart.tune/wav/dir--reference/rttm/dir--output/output/dirSeediart.tune -hfor more options.From pythonfromdiart.optimimportOptimizeroptimizer=Optimizer("/wav/dir","/rttm/dir","/output/dir")optimizer(num_iter=100)This will write results to an sqlite database in/output/dir.Distributed tuningFor bigger datasets, it is sometimes more convenient to run multiple optimization processes in parallel.
To do this, create a study on arecommended DBMS(e.g. MySQL or PostgreSQL) making sure that the study and database names match:mysql-uroot-e"CREATE DATABASE IF NOT EXISTS example"optunacreate-study--study-name"example"--storage"mysql://root@localhost/example"You can now run multiple identical optimizers pointing to this database:diart.tune/wav/dir--reference/rttm/dir--storagemysql://root@localhost/exampleor in python:fromdiart.optimimportOptimizerfromoptuna.samplersimportTPESamplerimportoptunadb="mysql://root@localhost/example"study=optuna.load_study("example",db,TPESampler())optimizer=Optimizer("/wav/dir","/rttm/dir",study)optimizer(num_iter=100)🧠🔗 Build pipelinesFor a more advanced usage, diart also provides building blocks that can be combined to create your own pipeline.
Streaming is powered byRxPY, but theblocksmodule is completely independent and can be used separately.ExampleObtain overlap-aware speaker embeddings from a microphone stream:importrx.operatorsasopsimportdiart.operatorsasdopsfromdiart.sourcesimportMicrophoneAudioSourcefromdiart.blocksimportSpeakerSegmentation,OverlapAwareSpeakerEmbeddingsegmentation=SpeakerSegmentation.from_pretrained("pyannote/segmentation")embedding=OverlapAwareSpeakerEmbedding.from_pretrained("pyannote/embedding")mic=MicrophoneAudioSource()stream=mic.stream.pipe(# Reformat stream to 5s duration and 500ms shiftdops.rearrange_audio_stream(sample_rate=segmentation.model.sample_rate),ops.map(lambdawav:(wav,segmentation(wav))),ops.starmap(embedding)).subscribe(on_next=lambdaemb: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])
...🌐 WebSocketsDiart is also compatible with the WebSocket protocol to serve pipelines on the web.From the command linediart.serve--host0.0.0.0--port7007diart.clientmicrophone--host<server-address>--port7007Note:make sure that the client uses the samestepandsample_ratethan the server with--stepand-sr.See-hfor more options.From pythonFor customized solutions, a server can also be created in python using theWebSocketAudioSource:fromdiartimportSpeakerDiarizationfromdiart.sourcesimportWebSocketAudioSourcefromdiart.inferenceimportStreamingInferencepipeline=SpeakerDiarization()source=WebSocketAudioSource(pipeline.config.sample_rate,"localhost",7007)inference=StreamingInference(pipeline,source)inference.attach_hooks(lambdaann_wav:source.send(ann_wav[0].to_rttm()))prediction=inference()🔬 Powered by researchDiart is the official implementation of the paperOverlap-aware low-latency online speaker diarization based on end-to-end local segmentationbyJuan Manuel Coria,Hervé Bredin,Sahar GhannayandSophie 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).CitationIf you found diart useful, please make sure to cite our paper:@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},}ReproducibilityImportant:We highly recommend installingpyannote.audio<3.1to reproduce these results.
For more information, seethis issue.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:DatasetlatencytaurhodeltaDIHARD IIIany0.5550.4221.517AMIany0.5070.0061.057VoxConverseany0.5760.9150.648DIHARD II1s0.6190.3260.997DIHARD II5s0.5550.4221.517diart.benchmarkanddiart.inference.Benchmarkcan run, evaluate and measure the real-time latency of the pipeline. For instance, for a DIHARD III configuration:diart.benchmark/wav/dir--reference/rttm/dir--tau-active=0.555--rho-update=0.422--delta-new=1.517--segmentationpyannote/segmentation@Interspeech2021or using the inference API:fromdiart.inferenceimportBenchmark,ParallelizefromdiartimportSpeakerDiarization,SpeakerDiarizationConfigfromdiart.modelsimportSegmentationModelbenchmark=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 papersegmentation=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 parallelp_benchmark=Parallelize(benchmark,num_workers=4)if__name__=="__main__":# Needed for multiprocessingp_benchmark(SpeakerDiarization,config)This pre-calculates model outputs in batches, so it runs a lot faster.
Seediart.benchmark -hfor more options.For convenience and to facilitate future comparisons, we also provide theexpected outputsof 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.📑 LicenseMIT 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.Logo generated byDesignEvo free logo designer