Add 'packages/core/' from commit 'f8f0465a6d9f08843b8b498e2296601d1cc2fe28'

git-subtree-dir: packages/core
git-subtree-mainline: 829dc423f4
git-subtree-split: f8f0465a6d
This commit is contained in:
Hervé BREDIN committed 2026-11-02 18:06:13 +01:00
commit d72a2f2ccd
53 files changed
+13298

No files matched your search

+1
View File
@@ -0,0 +1 @@
doc/source/conf.py export-subst
Binary file not shown.

After

Width:  |  Height:  |  Size: 616 KiB

+35
View File
@@ -0,0 +1,35 @@
name: Build Wheels
on:
workflow_call:
inputs:
release-tag:
description: Release tag; empty on pull requests
required: false
type: string
default: ""
permissions:
contents: read
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
# hatch-vcs needs Git history and tags to derive the package version.
fetch-depth: 0
- uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0
- uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0
with:
python-version-file: .python-version
- name: Build wheel and source distribution
run: uv build
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: python-package-distributions
path: dist/
if-no-files-found: error
retention-days: ${{ inputs.release-tag != '' && 90 || 3 }}
+87
View File
@@ -0,0 +1,87 @@
name: CI
on:
pull_request:
release:
types: [published]
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# lint (PR only)
# build ──┬──► test ──────────┬──► publish (release only)
# └──► version-guard ─┘
# ci-complete collects all required results.
jobs:
lint:
if: github.event_name == 'pull_request'
uses: ./.github/workflows/lint.yml
build:
uses: ./.github/workflows/build-wheels.yml
with:
release-tag: ${{ github.event.release.tag_name || '' }}
test:
needs: build
uses: ./.github/workflows/test.yml
version-guard:
name: versions
if: github.event_name == 'release'
needs: build
uses: ./.github/workflows/version-guard.yml
with:
release-tag: ${{ github.event.release.tag_name }}
# PyPI trusted publishing must run in a top-level workflow.
publish:
if: github.event_name == 'release'
needs: [build, test, version-guard]
runs-on: ubuntu-latest
environment:
name: pypi
url: https://pypi.org/project/pyannote-core/
permissions:
contents: write
id-token: write
steps:
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: python-package-distributions
path: dist/
- name: Upload distributions to GitHub Release
uses: softprops/action-gh-release@3d0d9888cb7fd7b750713d6e236d1fcb99157228 # v3.0.2
with:
tag_name: ${{ github.event.release.tag_name }}
files: |
dist/*.whl
dist/*.tar.gz
fail_on_unmatched_files: true
- uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0
- name: Upload to PyPI
run: >-
uv publish --trusted-publishing always
--publish-url https://upload.pypi.org/legacy/
--check-url https://pypi.org/simple/
ci-complete:
if: always()
needs: [lint, build, test, version-guard, publish]
runs-on: ubuntu-latest
env:
RESULTS: ${{ join(needs.*.result, ' ') }}
steps:
- name: Check results
run: |
for result in $RESULTS; do
if [[ "$result" == failure || "$result" == cancelled ]]; then
echo "::error::Required job finished with result: $result"
exit 1
fi
done
+55
View File
@@ -0,0 +1,55 @@
name: Documentation
on:
pull_request:
push:
branches: [main]
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
# hatch-vcs needs Git history and tags to derive the package version.
fetch-depth: 0
- uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0
- uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0
with:
python-version-file: .python-version
- name: Install documentation dependencies
run: |
uv venv
uv pip install '.[doc]'
- name: Build documentation
run: .venv/bin/sphinx-build -b html doc/source doc/build/html
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: documentation
path: doc/build/html
include-hidden-files: true
retention-days: 3
deploy:
if: github.event_name == 'push'
needs: build
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: documentation
path: doc/build/html
- uses: peaceiris/actions-gh-pages@373f7f263a76c20808c831209c920827a82a2847 # v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: doc/build/html
+28
View File
@@ -0,0 +1,28 @@
name: Lint
on:
workflow_call:
permissions:
contents: read
jobs:
ruff:
name: python
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
# Report lint/format issues without blocking PRs.
# Remove continue-on-error once the codebase is clean.
- name: Run ruff check
uses: astral-sh/ruff-action@0ce1b0bf8b818ef400413f810f8a11cdbda0034b # v4.0.0
continue-on-error: true
with:
args: "check ."
- name: Run ruff format
uses: astral-sh/ruff-action@0ce1b0bf8b818ef400413f810f8a11cdbda0034b # v4.0.0
continue-on-error: true
with:
args: "format --check ."
+36
View File
@@ -0,0 +1,36 @@
name: Test
on:
workflow_call:
permissions:
contents: read
jobs:
test:
name: Test Python ${{ matrix.python-version }}
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: ["3.11", "3.12", "3.13", "3.14", "3.15", "3.x"]
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0
- id: python
uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0
with:
python-version: ${{ matrix.python-version }}
check-latest: ${{ matrix.python-version == '3.x' }}
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: python-package-distributions
path: dist/
- name: Install the built wheel with test dependencies
run: |
uv venv --python "${{ steps.python.outputs.python-path }}"
uv pip install "$(echo dist/*.whl)[test]"
- name: Run tests against the installed wheel
run: .venv/bin/python -m pytest tests
+70
View File
@@ -0,0 +1,70 @@
name: Version Guard
on:
workflow_call:
inputs:
release-tag:
description: Release tag expected to match the package version
required: true
type: string
permissions:
contents: read
jobs:
not-already-published:
name: pyannote-core
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0
with:
python-version-file: .python-version
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: python-package-distributions
path: dist/
- name: Compare distributions with PyPI
env:
RELEASE_TAG: ${{ inputs.release-tag }}
shell: python
run: |
import hashlib
import json
import os
from pathlib import Path
from urllib.error import HTTPError
from urllib.request import urlopen
from zipfile import ZipFile
from email.parser import BytesParser
directory = Path("dist")
tag = os.environ["RELEASE_TAG"]
wheels = list(directory.glob("*.whl"))
sources = list(directory.glob("*.tar.gz"))
if len(wheels) != 1 or len(sources) != 1:
raise ValueError("Expected exactly one wheel and one source distribution")
with ZipFile(wheels[0]) as wheel:
metadata_path, = [n for n in wheel.namelist() if n.endswith(".dist-info/METADATA")]
metadata = BytesParser().parsebytes(wheel.read(metadata_path))
version = metadata["Version"]
if metadata["Name"] != "pyannote-core" or version != tag.removeprefix("v"):
raise ValueError(f"Release tag {tag!r} does not match pyannote-core {version}")
try:
with urlopen(f"https://pypi.org/pypi/pyannote-core/{version}/json", timeout=30) as response:
published = json.load(response)["urls"]
except HTTPError as error:
if error.code != 404:
raise
published = []
hashes = {item["filename"]: item["digests"]["sha256"] for item in published}
for artifact in wheels + sources:
if artifact.name not in hashes:
print(f"{artifact.name}: not published yet")
elif hashlib.sha256(artifact.read_bytes()).hexdigest() == hashes[artifact.name]:
print(f"{artifact.name}: already published with identical contents")
else:
raise ValueError(f"{artifact.name} already exists with different contents. Use a new version.")
+64
View File
@@ -0,0 +1,64 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
# C extensions
*.so
# Distribution / packaging
MANIFEST
.Python
env/
bin/
build/
develop-eggs/
dist/
eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.cache
nosetests.xml
coverage.xml
# Translations
*.mo
# Mr Developer
.mr.developer.cfg
.project
.pydevproject
# Rope
.ropeproject
# Django stuff:
*.log
*.pot
# Sphinx documentation
docs/_build/
doc/.ipynb_checkpoints
# emacs temporary files
*~
# PyCharm
.idea/
.mypy_cache/
+1
View File
@@ -0,0 +1 @@
3.11
+412
View File
@@ -0,0 +1,412 @@
# CHANGELOG
## Version 6.1.0 (2026-10-15)
- BREAKING: require Python 3.11 or newer; Python 3.10 is no longer supported
- BREAKING: `from pyannote.core import *` now exports only public classes, constants,
and `notebook` when available; incidental module imports are no longer exported
- fix(cluster): restore pooling clustering with NumPy 2
- fix(cluster): place the larger cluster first in linkage rows, including
must-link merges; cluster membership and merge distances are unchanged
## Version 6.0.1 (2025-09-16)
- feat: add `Annotation.__iter__` (turn: Segment, speaker: str) iterator
## Version 6.0.0 (2025-09-09)
- BREAKING: drop support to `Python` < 3.10
- BREAKING: switch to native namespace package
- setup: switch to `uv`
## Version 5.0.1 (2024-06-14)
- fix: fix return type of Timeline.__iter__ (@domsmrz)
- improve: remove MatplotlibDeprecationWarning (@kimdwkimdw)
## Version 5.0.0 (2022-12-15)
- BREAKING: remove support for JSON serialization
## Version 4.5 (2022-08-24)
- feat: add Annotation.write_lab method (@FrancescoBonzi)
- feat: add Annotation.to_{rttm|lab} and Timeline.to_uem serializers (@juanmc2005)
- setup: exclude tests from package (@kimdwkimdw)
## Version 4.4 (2022-03-09)
- BREAKING: remove empty segments in Timeline.__init__
- BREAKING: Timeline.extent() returns Segment(0.0, 0.0) for empty timelines
- feat: add "duration" option to Annotation.discretize
- fix: handle various corner cases in 1D pdist and cdist
- fix: fix documentation of {Timeline | Annotation}.__bool__
- test: check robustness to Segment.set_precision
## Version 4.3 (2021-10-11)
- feat: add support for visualizing 3D SlidingWindowFeatures (#66)
- feat: add Annotation.discretize (#65)
## Version 4.2.1 (2021-09-27)
- fix: fix automatic deployment of documentation
## Version 4.2 (2021-09-24)
- feat: add Segment.set_precision to automatically round start/end timestamps (@kimdwkimdw)
- feat: add methods {Timeline|Annotation}.{extrude|get_overlap} (@hadware)
- feat: add support for `Segment` in `one_hot_encoding`
- feat: make notebook visualization support an optional installation via the [notebook] extra_requires (@hadware)
- setup: add [doc] and [testing] extra_requires (@hadware)
- fix: several type annotation fixes (@kimdwkimdw, @PaulLerner)
## Version 4.1 (2020-05-27)
- feat: add "must_link_method" option to "pool" clustering
## Version 4.0 (2020-05-15)
- feat: add support for cannot/must link constraints in "pool" clustering
- BREAKING: make one_hot_encoding return SlidingWindowFeature with labels
- feat: add "labels" optional attribute to SlidingWindowFeature
## Version 3.7.1 (2020-03-23)
- fix: fix corner case in pyannote.core.utils.numpy.one_hot_encoding
## Version 3.7 (2020-03-21)
- feat: add new method SlidingWindowFeature.align
## Version 3.6 (2020-03-03)
- feat: add collar argument to Timeline.support (@nryant)
- feat: add new method Timeline.covers (@PaulLerner)
- fix: check for spaces before writing with RTTM or UEM format (@PaulLerner)
- improve: speed up Annotation.{from_df | from_json} (@nryant)
## Version 3.5 (2020-01-23)
- feat: add align_last option to SlidingWindow.__call__
## Version 3.4 (2020-01-21)
- feat: add SlidingWindow.__call__ to slide over a specific support
- feat: add pyannote.core.utils.random
## Version 3.3 (2020-01-08)
- BREAKING: remove pyannote.core.Scores
- fix: fix legend corner case with empty Annotation instances
- fix: fix {Timeline|Annotation}.crop with overlapping segments in support
## Version 3.2.2 (2020-01-06)
- fix: fix Segment.__bool__ return type
## Version 3.2 (2019-12-13)
- feat: add type hints (@hadware)
- chore: Python3-ize code base (@hadware)
## Version 3.1.10 (2019-12-12)
- feat: add Annotation.write_rttm and Timeline.write_uem (@PaulLerner)
- feat: add numpy interface to SlidingWindowFeature (experimental)
- feat: setup continuous integration
- improve: speed up SlidingWindowFeature plotting
- doc: update notebooks to Python 3 (@PaulLerner)
- BREAKING: remove deprecated Segment.pretty()
## Version 3.0 (2019-06-24)
- BREAKING: `Annotation.__mul__` now returns `np.ndarray` instance
- BREAKING: remove `Annotation` methods (that were deprecated version 1.0)
- BREAKING: `Scores.retrack` has been renamed `rename_tracks`
- improve: remove `six` and `xarray` dependencies
- BREAKING: remove `pyannote.core.time` module
## Version 2.2.2 (2019-04-18)
- improve: speed-up several `Segment` methods
- improve: decrease `one_hot_encoding` memory usage
- feat: add support for "fixed" option in all cropping modes
- setup: switch to scipy 1.1
## Version 2.1 (2019-01-17)
- feat: add basic implementation of Chinese Whispers clustering
- feat: add "utils.hierarchy.fcluster_auto" parameter-free "fcluster"
## Version 2.0.3 (2018-11-23)
- BREAKING: move pyannote.core.util to pyannote.core.utils.generators
- BREAKING: remove support for Python 2
- feat: add one_hot_{encoding | decoding} functions
- feat: add get_class_by_name utiltiy function
- feat: add custom pdist and cdist
- feat: add custom hierachical clustering "linkage" function
- setup: add scipy dependency
## Version 1.4.1 (2018-09-13)
- feat: add unit tests for feature cropping
- fix: fix out-of-bounds feature cropping
## Version 1.4 (2018-07-09)
- feat: expose `SlidingWindow.closest_frame`
## Version 1.3.2 (2018-06-12)
- feat: add support for multi-dimensional SlidingWindowFeatures
- setup: switch to sortedcontainers 2.x
- fix: update SWF.crop docstring
- chore: remove support for "segment" option in Annotation.argmax
## Version 1.3.1 (2017-12-14)
- feat: add "return_ranges" option to SlidingWindow.crop
- improve: faster SlidingWindowFeature.crop
- fix: fix documentation
## Version 1.2 (2017-10-05)
- BREAKING: remove all things "Transcription"
- feat: add return_data parameter to SlidingWindowFeature.crop (SWF)
- feat: add support for len(SWF)
- feat: add ylim parameter to plot_feature
- fix: fix corner case where notebook.crop is larger than SWF extent
## Version 1.1 (2017-09-19)
- feat: make iterators out of SlidingWindowFeature instances
- improve: make Annotation.__mul__ (much) faster
## Version 1.0.5 (2017-09-13)
- fix: make iterators out of SlidingWindow instances
## Version 1.0.4 (2017-07-18)
- fix: add missing import
- fix: fix corner case in Timeline.crop_iter
## Version 1.0.2 (2017-07-15)
- fix: use Timeline.support() instead of .coverage()
## Version 1.0.1 (2017-07-04)
- improve: switch from banyan to sortedcontainers
- feat: add Timeline.{remove|discard|overlapping_iter} methods
- BREAKING: Timeline.__init__ now raises ValueError in case of empty segment
- BREAKING: Timeline.crop now raises ValueError for bad mode
- BREAKING: rename "mapping" arguments to "returns_mapping" in Timeline.crop
- test: add more tests
## Version 0.13.3 (2017-06-29)
- fix: fix SlidingWindowFeature.iterfeatures()
## Version 0.13.2 (2017-03-29)
- setup: add dependencies for notebook visualization
## Version 0.13.1 (2017-02-20)
- fix: fix Annotation.rename_labels
## Version 0.13 (2017-02-05)
- improve: faster Annotation.subset and Annotation.rename_labels
## Version 0.12.1 (2017-30-01)
- fix: fix Annotation.uri setter
## Version 0.12 (2017-29-01)
- feat: add Timeline.to_annotation()
## Version 0.11.1 (2017-25-01)
- fix: fix (deprecated) "smooth" method
## Version 0.11 (2017-24-01)
- feat: add (Sphinx-based) documentation
- chore: move sample notebooks to /notebook
- feat: add unit tests
- BREAKING: rename some Timeline and Annotation methods
## Version 0.10 (2017-18-01)
- feat: add 'copy' parameter to Annotation.{label|get}_timeline()
- improve: speed-up Timeline.extent()
- chore: move tests at root directory
- chore: remove support for Unknown labels
## Version 0.9 (2017-01-17)
- improve: speed up Timeline and Annotation
## Version 0.8 (2016-11-05)
- feat: add "copy" option to Annotation.update
## Version 0.7.3 (2016-11-01)
- feat: SlidingWindowFeature notebook display
## Version 0.7.2 (2016-07-12)
- feat: new SlidingWindow.{samples|crop} methods
- feat: new 'mode' parameter to SlidingWindowFeature.crop method
- doc: updated notebooks for SlidingWindow and SlidingWindowFeature
## Version 0.6.6 (2016-06-23)
- fix: force internal timeline update after copy
## Version 0.6.5 (2016-06-13)
- BREAKING: make segmentToRange deterministic wrt. segment duration
## Version 0.6.4 (2016-06-06)
- fix: Python 3 support in pyannote.core.features
## Version 0.6.3 (2016-03-29)
- setup: versioneer 0.15
## Version 0.6.1 (2016-03-20)
- fix: prevent adding empty segments in Annotation and Scores
## Version 0.6 (2016-02-25)
- BREAKING: pyannote.core.json.{load|dump} expects file handles
- feat: load_from, dump_to
## Version 0.5.2 (2016-02-19)
- feat: Annotation * Annotation returns cooccurrence matrix
- fix: Annotation.itertracks would raise a UnicodeDecodeError in some
cases
## Version 0.5.1 (2016-02-17)
- improve: notebook display
- improve: Annotation.anonymize_{tracks|labels} no longer use Unknown
instances
- improve: empty segments are now printed as "[]"
## Version 0.4.7 (2016-02-04)
- feat: deterministic order in Annotation.co_iter
- fix: LabelMatrix.argmax corner case
- setup: update dependencies
## Version 0.4.4 (2015-11-02)
- feat: Travis continuous integration
## Version 0.4.3 (2015-10-28)
- fix: Python 2/3 notebook representations
- fix: bug in Scores with integer-values segments
## Version 0.4.1 (2015-10-27)
- fix: update Scores.from_df to pandas 0.17
## Version 0.4 (2015-10-26)
- feat: Python 3 support
- feat: pytest test suite
- fix: Annotation comparison
- fix: deterministic order in Annotation.itertracks
## Version 0.3.6 (2015-05-06)
- feat: LabelMatrix save/load methods
## Version 0.3.4 (2015-03-04)
- fix: MAJOR bug in Annotation lazy-update
## Version 0.3.3 (2015-02-27)
- fix: Scores IPython display
## Version 0.3.1 (2015-01-26)
- feat: new Annotation.update method
- improve: Annotation.subset support for any label iterable
## Version 0.3 (2014-12-04)
- refactor: rewrote Scores internals
- setup: use pandas 0.15.1+
## Version 0.2.5 (2014-11-21)
- setup: use pyannote-banyan 0.1.6
## Version 0.2.4 (2014-11-18)
- fix: extent of empty Timeline
## Version 0.2.3 (2014-11-14)
- fix: force revert to pandas 0.13.1 for Scores to work again...
## Version 0.2.2 (2014-11-12)
- setup: use banyan 0.1.5.1 from GitHub
## Version 0.2.1 (2014-10-30)
- feat: pyannote/core Docker image
- feat(Timeline): add from_df constructor
## Version 0.2 (2014-10-24)
- breaking change: new PyAnnote JSON format
## Version 0.1 (2014-08-05)
- fix(Transcription): fix potential edge/key conflict during alignment
## Version 0.0.5 (2014-07-23)
- feat(SlidingWindow): add durationToSamples (and vice-versa)
- fix(Transcription): fix loading from JSON
- fix(Transcription): fix cropping corner cases
- docs: add installation instruction for IPython display support
- docs(Scores): add IPython documentation for Scores
## Version 0.0.3 (2014-06-02)
- feat(Annotation): add 'collar' param to .smooth()
- refactor(Annotation): remove support for >> operator
- maintain(Mapping): remove label mapping data structure
- feat(LabelMatrix): add IPython display
- improve(LabelMatrix): 10x faster cooccurrence matrix
- feat(Scores): add IPython display
- feat(Transcription): add edge timerange prediction
- feat(Transcription): add node temporal sort
- fix(Transcription): make label_timeline return a copy
- fix(Transcription): fix IPython display
- docs(Transcription): add IPython documentation for Transcription
## Version 0.0.2 (2014-05-06)
- feat: Transcription data structure (annotation graph)
## Version 0.0.1 (2014-05-02)
- first public version
+24
View File
@@ -0,0 +1,24 @@
The MIT License (MIT)
Copyright (c) 2014 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
Hervé BREDIN - http://herve.niderb.fr
+37
View File
@@ -0,0 +1,37 @@
![pyannote.core](https://raw.githubusercontent.com/pyannote/pyannote-core/main/.github/social-preview.png)
> advanced data structures for handling and visualizing temporal segments with attached labels.
## Installation
```bash
$ pip install pyannote.core
```
Support for graphical visualization in Jupyter notebooks can be added with:
```bash
$ pip install pyannote.core[notebook]
```
## Documentation
The documentation is available at [http://pyannote.github.io/pyannote-core](http://pyannote.github.io/pyannote-core).
Sample notebooks are available [here](https://nbviewer.jupyter.org/github/pyannote/pyannote-core/blob/develop/notebook/index.ipynb).
## Citation
If you use `pyannote.core` in your research, please use the following citation:
```bibtex
@inproceedings{pyannote.metrics,
author = {Herv\'e Bredin},
title = {{pyannote.metrics: a toolkit for reproducible evaluation, diagnostic, and error analysis of speaker diarization systems}},
booktitle = {{Interspeech 2017, 18th Annual Conference of the International Speech Communication Association}},
year = {2017},
month = {August},
address = {Stockholm, Sweden},
url = {http://pyannote.github.io/pyannote-metrics},
}
```
+20
View File
@@ -0,0 +1,20 @@
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
SPHINXPROJ = pyannotecore
SOURCEDIR = source
BUILDDIR = build
# Put it first so that "make" without argument is like "make help".
help:
uv run --extra doc $(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
uv run --extra doc $(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
+201
View File
@@ -0,0 +1,201 @@
#
# pyannote.core documentation build configuration file, created by
# sphinx-quickstart on Tue Jan 24 15:45:55 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# allow pyannote.core import
import os
import sys
sys.path.insert(0, os.path.abspath("../.."))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.napoleon",
"sphinx.ext.intersphinx",
"sphinx.ext.todo",
"sphinx.ext.coverage",
"sphinx.ext.mathjax",
"sphinx.ext.viewcode",
"sphinx.ext.githubpages",
"matplotlib.sphinxext.plot_directive",
"IPython.sphinxext.ipython_directive",
]
# Napoleon settings
napoleon_google_docstring = True
napoleon_numpy_docstring = True
napoleon_include_init_with_doc = False
napoleon_include_private_with_doc = False
napoleon_include_special_with_doc = False
napoleon_use_admonition_for_examples = False
napoleon_use_admonition_for_notes = False
napoleon_use_admonition_for_references = False
napoleon_use_ivar = False
napoleon_use_param = True
napoleon_use_rtype = True
napoleon_use_keyword = True
# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = {".rst": "restructuredtext"}
# The master toctree document.
master_doc = "index"
# General information about the project.
project = "pyannote.core"
copyright = "2017, CNRS"
author = "Hervé Bredin"
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
import pyannote.core
# The short X.Y version.
version = pyannote.core.__version__.split("+")[0]
# The full version, including alpha/beta/rc tags.
release = pyannote.core.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = "en"
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = []
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "sphinx"
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = "sphinx_rtd_theme"
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = "pyannotecoredoc"
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(
master_doc,
"pyannotecore.tex",
"pyannote.core Documentation",
"Hervé Bredin",
"manual",
),
]
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [(master_doc, "pyannotecore", "pyannote.core Documentation", [author], 1)]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(
master_doc,
"pyannotecore",
"pyannote.core Documentation",
author,
"pyannotecore",
"One line description of project.",
"Miscellaneous",
),
]
# Example configuration for intersphinx: refer to the Python standard library.
plot_pre_code = """import matplotlib.pyplot as plt
from pyannote.core import notebook
from pyannote.core import Segment
from pyannote.core import Timeline
from pyannote.core import Annotation
from pyannote.core import SlidingWindow
from pyannote.core import SlidingWindowFeature"""
ipython_savefig_dir = "../../build/html/_static"
+54
View File
@@ -0,0 +1,54 @@
.. pyannote.core documentation master file, created by
sphinx-quickstart on Thu Jan 19 13:25:34 2017.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
#############
pyannote.core
#############
`pyannote.core` is an open-source Python library providing advanced data structures for handling temporal segments with attached labels.
.. plot:: pyplots/introduction.py
It is the foundation of the `pyannote` ecosystem, made of a (growing) number of libraries ( `pyannote.parser`, `pyannote.metrics`, `pyannote.database`, `pyannote.audio`, `pyannote.video`).
It also provides a convenient way to visualize this temporal data in IPython notebooks.
Installation
============
::
$ conda create -n pyannote python=3.5 anaconda
$ source activate pyannote
$ pip install pyannote.core
User guide
==========
.. toctree::
:maxdepth: 2
structure
visualization
API documentation
=================
.. toctree::
:maxdepth: 2
reference
Changelog <https://github.com/pyannote/pyannote-core/blob/main/CHANGELOG.md>
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
@@ -0,0 +1,19 @@
import matplotlib.pyplot as plt
from pyannote.core import Annotation, Segment, notebook
notebook.width = 10
plt.rcParams["figure.figsize"] = (notebook.width, 2)
# only display [0, 20] timerange
notebook.crop = Segment(0, 20)
# plot annotation
annotation = Annotation()
annotation[Segment(1, 5)] = "Carol"
annotation[Segment(6, 8)] = "Bob"
annotation[Segment(12, 18)] = "Carol"
annotation[Segment(7, 20)] = "Alice"
notebook.plot_annotation(annotation, legend=True, time=True)
plt.show()
@@ -0,0 +1,29 @@
import matplotlib.pyplot as plt
from pyannote.core import Annotation, Segment, Timeline, notebook
notebook.width = 10
plt.rcParams["figure.figsize"] = (notebook.width, 3)
# only display [0, 20] timerange
notebook.crop = Segment(0, 20)
# plot annotation
plt.subplot(211)
annotation = Annotation()
annotation[Segment(1, 5)] = "Carol"
annotation[Segment(6, 8)] = "Bob"
annotation[Segment(12, 18)] = "Carol"
annotation[Segment(7, 20)] = "Alice"
notebook.plot_annotation(annotation, legend=True, time=False)
# plot timeline
plt.subplot(212)
timeline = Timeline()
timeline.add(Segment(1, 5))
timeline.add(Segment(6, 8))
timeline.add(Segment(12, 18))
timeline.add(Segment(7, 20))
notebook.plot_timeline(timeline, time=True)
plt.show()
@@ -0,0 +1,15 @@
import matplotlib.pyplot as plt
from pyannote.core import Segment, notebook
notebook.width = 10
plt.rcParams["figure.figsize"] = (notebook.width, 2)
# only display [0, 20] timerange
notebook.crop = Segment(0, 20)
# plot segment
segment = Segment(5, 15)
notebook.plot_segment(segment, time=True)
plt.show()
@@ -0,0 +1,19 @@
import matplotlib.pyplot as plt
from pyannote.core import Segment, Timeline, notebook
notebook.width = 10
plt.rcParams["figure.figsize"] = (notebook.width, 2)
# only display [0, 20] timerange
notebook.crop = Segment(0, 20)
# plot timeline
timeline = Timeline()
timeline.add(Segment(1, 5))
timeline.add(Segment(6, 8))
timeline.add(Segment(12, 18))
timeline.add(Segment(7, 20))
notebook.plot_timeline(timeline, time=True)
plt.show()
+60
View File
@@ -0,0 +1,60 @@
#########
Reference
#########
***************
Data structures
***************
.. toctree::
:maxdepth: 2
Segment
=======
.. autoclass:: pyannote.core.Segment
:members:
:special-members:
Timeline
========
.. autoclass:: pyannote.core.Timeline
:members:
:special-members:
Annotation
==========
.. autoclass:: pyannote.core.Annotation
:members:
:special-members:
.. Scores
.. ======
..
.. .. autoclass:: pyannote.core.Scores
.. :members:
.. :special-members:
SlidingWindow
=============
.. autoclass:: pyannote.core.SlidingWindow
:members:
:special-members:
SlidingWindowFeature
====================
.. autoclass:: pyannote.core.SlidingWindowFeature
:members:
:special-members:
*************
Visualization
*************
.. automodule:: pyannote.core.notebook
:members:
:no-index:
+12
View File
@@ -0,0 +1,12 @@
#########################
Available data structures
#########################
.. automodule:: pyannote.core.segment
.. automodule:: pyannote.core.timeline
.. automodule:: pyannote.core.annotation
.. automodule:: pyannote.core.feature
@@ -0,0 +1 @@
.. automodule:: pyannote.core.notebook
+310
View File
@@ -0,0 +1,310 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Populating the interactive namespace from numpy and matplotlib\n"
]
}
],
"source": [
"%pylab inline\n",
"import random\n",
"\n",
"random.seed(1337)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Documentation for `pyannote.core`"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Install"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`pyannote.core` package can be installed the easy way:\n",
"```bash\n",
"$ pip install pyannote.core\n",
"```\n",
"\n",
"Adding support for Jupyter/IPython Notebook graphical representations is as easy as:\n",
"```bash\n",
"$ pip install pyannote.core[notebook]\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Available data structures"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"from pyannote.core import *"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Segment ([pyannote.core.segment](pyannote.core.segment.ipynb))"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAABHQAAABnCAYAAABhARWQAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAB6JJREFUeJzt3V+IZmUdB/Dvz52i1P6v2K4KI2HWEphhYgph6YVRZBBI\nUSLRTVBqEYR1U5deSOVFBGKWkBihghJRhkXdmbsa+S/JLHXdMZWotCgzf13MKy6C7PuOzpyeeT8f\nGN5zzp7zzncuHvad75znOdXdAQAAAGAch00dAAAAAIDFKHQAAAAABqPQAQAAABiMQgcAAABgMAod\nAAAAgMEodAAAAAAGo9ABAAAA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Lh7JzLk3yju9+d5KOzfwMAGIo1dACA7eS27l5Lkqr6Q5KbZ8fvTPK+2fbZSfZU1XPXvLaqjuzu\np7Y0KQDAS6DQAQC2k38ftP3sQfvP5vnPPYclOa27/7WVwQAAXk6mXAEAy+bmPD/9KlX1zgmzAABs\niEIHAFg2FyU5pap+W1X3ZH3NHQCAoXhsOQAAAMBg3KEDAAAAMBiFDgAAAMBgFDoAAAAAg1HoAAAA\nAAxGoQMAAAAwGIUOAAAAwGAUOgAAAACDUegAAAAADOZ/4N5bcno/AecAAAAASUVORK5CYII=\n",
"text/plain": [
"<Segment(0, 10)>"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"segment = Segment(start=0, end=10)\n",
"segment"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Timeline ([pyannote.core.timeline](pyannote.core.timeline.ipynb))"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAABHQAAABnCAYAAABhARWQAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAB/5JREFUeJzt3V+oZWUZBvDnzVOU2v8RKxWOhFlDYMYkphCWXhhFBkEU\nJRLdBKUWQVg3M955IZUXEYhZQmKECkpEGRZ1Z57RyH9JZqljYypRaVFmvl2cLQ6Czd7HOWf1nf37\nwbDXWrPWnmfYfLPXPGetb1V3BwAAAIBxvGTqAAAAAAAsRqEDAAAAMBiFDgAAAMBgFDoAAAAAg1Ho\nAAAAAAxGoQMAAAAwGIUOAAAAwGAUOgAAAACDUegAAAAADGZlkZ137NjRq6urmxQFAAAAYPns3bv3\n8e4+apFjFip0VldXs7a2tlgqAAAAAF5QVT2w6DFuuQIAAAAYjEIHAAAAYDAKHQAAAIDBKHQAAAAA\nBqPQAQAAABiMQgcAAABgMAodAAAAgMEodAAAAAAGo9ABAAAAGIxCBwAAAGAwCh0AAACAwSh0AAAA\n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wHLzxyw/kye\nO+95SZJTu/ufWxkMAOBQcssVALBsbspzt1+lqt4xYRYAgA1R6AAAy+aCJLuq6tdVdXfW59wBABiK\nx5YDAAAADMYVOgAAAACDUegAAAAADEahAwAAADAYhQ4AAADAYBQ6AAAAAINR6AAAAAAMRqEDAAAA\nMBiFDgAAAMBg/gtDeo9owLlLVgAAAABJRU5ErkJggg==\n",
"text/plain": [
"<Timeline(uri=None, segments=[<Segment(1, 5)>, <Segment(6, 8)>, <Segment(7, 20)>, <Segment(12, 18)>])>"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"timeline = Timeline([Segment(1, 5), Segment(6, 8), Segment(12, 18), Segment(7, 20)])\n",
"timeline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Annotation ([pyannote.core.annotation](pyannote.core.annotation.ipynb))"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAABHQAAACsCAYAAAAaLvvnAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAADYZJREFUeJzt3XusZWV5BvDnlam1CrXgENuOxDFWQVqDl9EgGINKqi1G\naLVVtFaNTWNqxWobq42GobfYaLU2NU0Ub7GIKZcqlQY0aLU1ogyggiLWCwqIItoK2HqDt3+chRyo\n0zlnOOcsvrN/v2Sy11p7fXuevZMv58wz31q7ujsAAAAAjOMucwcAAAAAYHUUOgAAAACDUegAAAAA\nDEahAwAAADAYhQ4AAADAYBQ6AAAAAINR6AAAAAAMRqEDAAAAMBiFDgAAAMBgFDoAAAAAgxmy0Kmq\n46qqq+qQaX97VV06be+oqr+dN+F8qurGvRjztqp66nrkuTP4/z6Tqjqqqt67kXkAAADgjhqy0Ely\nfJJ/nx5vo7t3dfcJGx8JAAAAYGMMV+hU1b5JHp3keUme/mOe/9GKi6rat6reWlWXVNWnquop0/Ff\nrqqPVtVFVXXa9JqbxvS+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at 0x11e832320>"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"annotation = Annotation()\n",
"annotation[Segment(1, 5)] = \"John\"\n",
"annotation[Segment(6, 8)] = \"Jack\"\n",
"annotation[Segment(12, 18)] = \"John\"\n",
"annotation[Segment(7, 20)] = \"Alice\"\n",
"annotation"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Feature ([pyannote.core.feature](pyannote.core.feature.ipynb))"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"# one 4-dimensional feature vector extracted every 100ms from a 200ms window\n",
"frame = SlidingWindow(start=0.0, step=0.100, duration=0.200)\n",
"data = np.random.randn(100, 4)\n",
"features = SlidingWindowFeature(data, frame)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAABHQAAACdCAYAAADVCC/vAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzs3WdAFFfXwPH/7sLSiwiodHvvsTewxdiiMTGWqDGmqInG\n9MT050neFI1J1CTG2BV719gVFGwIIiIgTem9s7Rt837YWIiogCDqc39fkNnZ2bu4Zebcc86VSZKE\nIAiCIAiCIAiCIAiC8PiQ1/UABEEQBEEQBEEQBEEQhKoRAR1BEARBEARBEARBEITHjAjoCIIgCIIg\nCIIgCIIgPGZEQEcQBEEQBEEQBEEQBOExIwI6giAIgiAIgiAIgiAIjxkR0BEEQRAEQRAEQRAEQXjM\niICOIAiCIAiCIAiCIAjCY0YEdARBEARBEARBEARBEB4zIqAjCIIgCIIgCIIgCILwmDGqys729vaS\nh4dHLQ1FEARBEARBEARBEAThf09QUFCWJEkOVblPlQI6Hh4eBAYGVm1UgiAIgiAIgiAIgiAIwl3J\nZLL4qt5HlFwJgiAIgiAIgiAIgiA8ZkRARxAEQRAEQRAEQRAE4TEjAjqCIAiCIAiCIAiCI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9RLPP2W4\nGBnV0QmZDPZeqpksnY0B17HyWEH9ZmtYfOIq+cWP9gVlbfKJzKSrez3GdHZib0jKQLine truncated
"text/plain": [
"<pyannote.core.feature.SlidingWindowFeature at 0x11e8344e0>"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"features"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[ 0.4421429 , -1.44502143, -0.43282043, -0.01994535],\n",
" [ 0.95060543, -0.74292602, 1.22086979, 1.95070816],\n",
" [ 1.19066555, 1.29371768, 0.11550674, -3.74567368],\n",
" [ 1.17795762, -0.39977873, -1.27290048, 1.13461351],\n",
" [-0.86933379, -0.69830552, -0.37775889, -0.32930616],\n",
" [-0.20408787, -0.24439993, -0.07213635, -1.17373151],\n",
" [-0.25488363, 0.13070289, 0.56219605, 0.36592598],\n",
" [ 0.82328558, 0.80167407, -1.61040618, -0.18284535],\n",
" [ 1.02423512, 0.78117785, -0.57796508, -0.24171816],\n",
" [ 0.41506776, -1.05395226, -1.32510005, 0.0041201 ],\n",
" [ 0.39898321, -0.4456852 , 0.50380856, -0.64459603],\n",
" [ 1.08797586, 0.48974714, 0.50622516, -0.05644439],\n",
" [-0.30759844, 0.05496161, -0.79779151, -1.32959826]])"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"features.crop(Segment(2, 3))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Scores ([pyannote.core.scores](pyannote.core.scores.ipynb))"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAABIcAAACsCAYAAADhVcx9AAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAFL1JREFUeJzt3X2wZ3V9H/D3x904EXyMbIzhocukRLKNonJFfGjUaiK0\nNqvVacCHqM2IdERjH6Zi0qnr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nd1+7u30uLCz04uLivtYNAAAAwDJVtbm7F/Zmmz2OHKqqNUnOSXJqkg1JTq+qDcu63ZLkOd39xCS/\nleS8vSkCAAAAgHGsZFrZSUm2dPfN3X1PkouTbFzaobu/0N3fGRavSnLUfMsEAAAAYDWsJBw6Mslt\nS5a3Dm278mtJ/tf+FAUAAADAgTHXR9lX1fMyC4eevYv1ZyQ5I0mOOeaYeR4aAAAAgH2wkpFDtyc5\nesnyUUPb31FVT0pyfpKN3f0XO9tRd5/X3QvdvbBu3bp9qRcAAACAOVpJOHR1kuOq6tiqemiS05Jc\ntrRDVR2T5NIkr+rub8y/TAAAAABWwx6nlXX39qo6K8kVmT3K/oLuvr6qzhzWn5vkPyR5bJJ3V1WS\nbN/bx6YBAAAAcOBVd49y4IWFhV5cXBzl2AAAAACHoqravLcDduZ6Q2oAVtfiRddm8Line truncated
"text/plain": [
"<pyannote.core.scores.Scores at 0x11e9a2a90>"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"scores = Scores()\n",
"scores[Segment(3, 5), \"_\", \"Penny\"] = 0.8\n",
"scores[Segment(3, 5), \"_\", \"Leonard\"] = 0.15\n",
"scores[Segment(3, 5), \"_\", \"Sheldon\"] = 0.05\n",
"scores[Segment(5.5, 7), \"_\", \"Penny\"] = 0.4\n",
"scores[Segment(5.5, 7), \"_\", \"Leonard\"] = 0.5\n",
"scores[Segment(5.5, 7), \"_\", \"Sheldon\"] = 0.1\n",
"scores[Segment(8, 10), \"_\", \"Penny\"] = 0.4\n",
"scores[Segment(8, 10), \"_\", \"Leonard\"] = 0.25\n",
"scores[Segment(8, 10), \"_\", \"Sheldon\"] = 0.35\n",
"scores"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Contribute"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`pyannote.core` is on [Github](https://github.com/pyannote/pyannote-core). \n",
" \n",
" \n",
" Fork and pull requests are very welcome!"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.3"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,287 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Populating the interactive namespace from numpy and matplotlib\n"
]
}
],
"source": [
"%pylab inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# SlidingWindowFeature (`pyannote.core.feature.SlidingWindowFeature`)"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"from pyannote.core import SlidingWindow, SlidingWindowFeature"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**SlidingWindowFeature** are used to manage feature vectors extracted on a sliding window (e.g. MFCC in audio processing)."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"# one 4-dimensional feature vector extracted every 100ms from a 200ms window\n",
"frame = SlidingWindow(start=0.0, step=0.100, duration=0.200)\n",
"\n",
"# random for illustration purposes\n",
"data = np.random.randn(100, 4)\n",
"\n",
"features = SlidingWindowFeature(data, frame)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Cropping"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You may use `crop` to extract a temporal subset:"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Help on method crop in module pyannote.core.feature:\n",
"\n",
"crop(self, focus, mode=u'loose', fixed=None) method of pyannote.core.feature.SlidingWindowFeature instance\n",
" Extract frames as numpy array\n",
" \n",
" Parameters\n",
" ----------\n",
" focus : Segment or Timeline\n",
" mode : {'loose', 'strict', 'center', 'fixed'}, optional\n",
" In 'strict' mode, only frames fully included in focus coverage are\n",
" returned. In 'loose' mode, any intersecting frames are returned. In\n",
" 'center' mode, first and last frames are chosen to be the positions\n",
" whose centers are the closest to the focus start and end times.\n",
" Defaults to 'loose'.\n",
" fixed : float, optional\n",
" When provided and mode is 'center', override focus duration to make\n",
" sure two `focus` with the same duration always result in the same\n",
" (fixed) number of frames being selected.\n",
" \n",
" Returns\n",
" -------\n",
" data : numpy array\n",
" (nSamples, nFeatures) numpy array\n",
" \n",
" See also\n",
" --------\n",
" SlidingWindow.crop\n",
"\n"
]
}
],
"source": [
"help(features.crop)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"array([[-0.170939 , 0.7268368 , -1.11357192, 0.9102115 ],\n",
" [ 0.75526988, 0.13631738, -1.12959046, 0.57945519],\n",
" [-1.63332126, -1.05239927, -2.80404685, -3.19025518],\n",
" [-1.2622323 , 0.80263563, 0.8912935 , 0.85251067],\n",
" [-0.58865284, -1.05005899, 0.5468816 , 1.03976293],\n",
" [ 2.99740924, 1.544513 , -2.18700361, -0.19051365],\n",
" [-1.16020413, 2.75010658, -1.63448261, 0.96354481],\n",
" [-1.09404058, -0.56915077, -0.73265453, -0.5412315 ],\n",
" [-3.83225883, 2.48916336, -0.475149 , -0.56418448],\n",
" [ 0.01583975, -1.41733235, -0.47454703, -1.18346613],\n",
" [ 0.4350982 , -0.61821957, 0.0458578 , -0.66109202],\n",
" [ 1.39603516, 1.00657646, 1.67931705, 0.01362444],\n",
" [ 0.95027176, -0.02961472, -0.71587331, -0.04884979]])"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from pyannote.core import Segment\n",
"\n",
"features.crop(Segment(2, 3))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Need help?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can always try the following... \n",
"Who knows? It might give you the information you are looking for!"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Help on class SlidingWindowFeature in module pyannote.core.feature:\n",
"\n",
"class SlidingWindowFeature(__builtin__.object)\n",
" | Periodic feature vectors\n",
" | \n",
" | Parameters\n",
" | ----------\n",
" | data : (nSamples, nFeatures) numpy array\n",
" | \n",
" | sliding_window : SlidingWindow\n",
" | \n",
" | Methods defined here:\n",
" | \n",
" | __getitem__(self, i)\n",
" | Get ith feature vector\n",
" | \n",
" | __init__(self, data, sliding_window)\n",
" | \n",
" | crop(self, focus, mode=u'loose', fixed=None)\n",
" | Extract frames as numpy array\n",
" | \n",
" | Parameters\n",
" | ----------\n",
" | focus : Segment or Timeline\n",
" | mode : {'loose', 'strict', 'center', 'fixed'}, optional\n",
" | In 'strict' mode, only frames fully included in focus coverage are\n",
" | returned. In 'loose' mode, any intersecting frames are returned. In\n",
" | 'center' mode, first and last frames are chosen to be the positions\n",
" | whose centers are the closest to the focus start and end times.\n",
" | Defaults to 'loose'.\n",
" | fixed : float, optional\n",
" | When provided and mode is 'center', override focus duration to make\n",
" | sure two `focus` with the same duration always result in the same\n",
" | (fixed) number of frames being selected.\n",
" | \n",
" | Returns\n",
" | -------\n",
" | data : numpy array\n",
" | (nSamples, nFeatures) numpy array\n",
" | \n",
" | See also\n",
" | --------\n",
" | SlidingWindow.crop\n",
" | \n",
" | getDimension(self)\n",
" | Dimension of feature vectors\n",
" | \n",
" | getExtent(self)\n",
" | \n",
" | getNumber(self)\n",
" | Number of feature vectors\n",
" | \n",
" | iterfeatures(self, window=False)\n",
" | Feature vector iterator\n",
" | \n",
" | Parameters\n",
" | ----------\n",
" | window : bool, optional\n",
" | When True, yield both feature vector and corresponding window.\n",
" | Default is to only yield feature vector\n",
" | \n",
" | ----------------------------------------------------------------------\n",
" | Data descriptors defined here:\n",
" | \n",
" | __dict__\n",
" | dictionary for instance variables (if defined)\n",
" | \n",
" | __weakref__\n",
" | list of weak references to the object (if defined)\n",
"\n"
]
}
],
"source": [
"help(SlidingWindowFeature)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.10"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -0,0 +1,175 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false,
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Populating the interactive namespace from numpy and matplotlib\n"
]
}
],
"source": [
"%pylab inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Scores (`pyannote.core.scores.Scores`)"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from pyannote.core import Scores"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**`Scores`** instances are used to describe classification scores.\n",
"For instance, one can use a **`Scores`** to store the result of speaker identification approach applied on an episode of *The Big Bang Theory* TV series."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"scores = Scores(uri=\"TheBigBangTheory.Season01.Episode01\", modality=\"speaker\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For instance, to represent a dialogue between Penny and Leonard, we could do the following:"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAABIkAAACxCAYAAABA1O2LAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAFNZJREFUeJzt3XuwpGV9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95fWlrK0tLSWsoCAAAAWCjLy8tZXl5e\n0zGqu2dTzfYaqTooyRnd/eCtrOv1qAEAAABgUVRVuntF0wDN89vN7jX18FeSXDSvtgAAAABYm3l+\nu9l/q6qHJrklyRVJXjHHtgAAAABYg3UZbrbdAgw3AwAAAJipXWq4GQAAAAC7DyERAAAAAEIiAAAA\nAIREAAAAAERIBAAAAECERAAAAABESAQAAABAhEQAAAAAREgEAAAAQIREAAAAAERIBAAAAECERAAA\nAABESAQAAABAhEQAAAAAZI0hUVU9u6ouqqqbq+rhW6w7uqq+WFWXVNWT1lYmAAAAAPO0YY37fyHJ\ns5L85fTCqjokyXOSHJLkgCQfraoHdHevsT0AAAAA5mBNPYm6+7Lu/mKS2mLVkUne090/7O4rknwx\nyWFraQsAAACA+ZnXnET7J9k09fjqYRkAAAAAu6AdDjerqo8k2W96UZJO8vvdfcYsiLine truncated
"text/plain": [
"<pyannote.core.scores.Scores at 0x7f4d64aec510>"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from pyannote.core import Segment\n",
"\n",
"scores[Segment(3, 5), \"_\", \"Penny\"] = 8\n",
"scores[Segment(3, 5), \"_\", \"Leonard\"] = 0.15\n",
"scores[Segment(3, 5), \"_\", \"Sheldon\"] = 0.05\n",
"scores[Segment(5.5, 7), \"_\", \"Penny\"] = 0.4\n",
"scores[Segment(5.5, 7), \"_\", \"Leonard\"] = 0.5\n",
"scores[Segment(5.5, 7), \"_\", \"Sheldon\"] = 0.1\n",
"scores[Segment(8, 10), \"_\", \"Penny\"] = 0.4\n",
"scores[Segment(8, 10), \"_\", \"Leonard\"] = 0.25\n",
"scores[Segment(8, 10), \"_\", \"Sheldon\"] = -12\n",
"scores"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAABHMAAACxCAYAAABHuvHbAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nA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++PT8jVmEO7CR\nfjXJOdP5DzbCYUk+1N2XTUNd/jnJfWauiSXR3du6+7Du3prk8iTnz1wSy+eSqrpNklTVbZNcurM3\nrOZqVre6diblqZv3Q5J8chcLhZ3q7ud29x26+5AsJsB7X3c/ce66WA5VtU9V7Tc93jfJQ7Pohgu7\n1dTFdntV3XF66VdiEng23uNiiBUb6/NJjqiqm1RVZXHuM/k7G6Kqfma6v0OSX0/yunkrYgnsOPLk\n9CS/Oz0+Nslbd7aBLav4kP2TnDSdVG+U5JTufu/a6gQYzm2SvLmqOotz5andfebMNbE8npHk1Gmo\ny5eS/N7M9bBEpjkjHpzkKXPXwvLo7vOmHtjnZDHE5dwkr563KpbIm6rqFkmuTvKHLjzA7lRVr0uy\nNcktq+qCJMcneVGS06rqSUm+muS3d7qdbvPKAgAAAIzCJXcBAAAABiLMAQAAABiIMAcAAABgIMIc\nAAAAgIEIcwAAAAAGIswBAAAAGMiWuQsAANiZqrpFkvcm6ST7J/lBkkuTVJJvd/f9ZLine truncated
"text/plain": [
"<pyannote.core.annotation.Annotation at 0x7f4d64863b90>"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"scores.to_annotation()"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAXwAAAEhCAYAAAB89xvjAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAFFpJREFUeJzt3X20JHV95/H3B0dQwEdQkGFgdVcMrotiEDhB5fqAKEHR\n3axRj0LUYBI1etw1m2CyDribrFmPJp64OUkWguhiXNBlUTThITon0QRkFRWWhyEoMA5PGhCNZAnC\nd/+oGmxm5s693ff2rdvze7/O6XO7u6qrvl3V/blVv6quX6oKSdLOb5ehC5AkrQwDX5IaYeBLUiMM\nfElqhIEvSY0w8CWpEQa+JDXCwJekRhj4ktQIA1+SGmHgS1IjDPydTJKjk2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aGLmFJrH9Ys1z/LNcOs1//JDJpW9CyFZDU0DVI0qxJQs3iQVtJ0vQZ+JLUCANfkhph4EtSIwx8\nSWqEgS9JjTDwJakRBr4kNcLAl6RGGPiS1AgDX5IaYeBLUiMMfElqhIEvSY0w8CWpEQa+JDXCwJek\nRhj4ktQIA1+SGmHgS1IjDHxJaoSBL0mNMPAlqREGviQ1wsCXpEYY+JLUCANfkhph4EtSIwx8SWqE\ngS9JjTDwJakRBr4kNcLAl6RGGPiS1AgDX5IaYeBLUiMMfElqhIEvSY0w8CWpEQa+JLine truncated
"text/plain": [
"<matplotlib.figure.Figure at 0x7f4d6468e490>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import matplotlib.pyplot as plt\n",
"\n",
"from pyannote.core import notebook\n",
"\n",
"plt.subplot(211)\n",
"notebook(scores, time=False)\n",
"plt.subplot(212)\n",
"notebook(scores.to_annotation(), legend=False)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -0,0 +1,957 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Populating the interactive namespace from numpy and matplotlib\n"
]
}
],
"source": [
"%pylab inline\n",
"from pyannote.core import notebook"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Segment (`pyannote.core.segment.Segment`)"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [],
"source": [
"from pyannote.core import Segment"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**`Segment`** instances are used to describe temporal fragments (e.g. of an audio file)."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAABHEAAABjCAYAAAAcuZzCAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjEsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy8QZhcZAAAIoUlEQVR4nO3dW4huZRkH8P9juzDtiNtqm8WOIDGErMwOllRmdKKiboryopsKorQuorqp7gqkw1UQ2olKMTWCiNhR0eEia2+zNM3ooGXuUulgu6Pp08WsyFBnf586rvXO/v3gY75vZq3hP/AwfPOf9b6rujsAAAAALNthcwcAAAAA4OCUOAAAAAADUOIAAAAADECJAwAAADAAJQ4AAADAAHasc/DOnTt79+7dWxQFAAAA4NCzb9++m7r76IMdt1aJs3v37uzdu/fupwIAAADg/1TVtascZzkVAAAAwACUOAAAAAADUOIAAAAADECJAwAAADAAJQ4AAADAAJQ4AAAAAANQ4gAAAAAMQIkDAAAAMAAlDgAAAMAAlDgAAAAAA1DiAAAAAAxAiQMAAAAwACUOAAAAwACUOAAAAAADUOIAAAAADECJAwAAADAAJQ4AAADAAJQ4AAAAAANQ4gAAAAAMQIkDAAAAMAAlDgAAAMAAlDgAAAAAA1DiAAAAAAxgrRLn+uuv36ocAAAAAGxirRJn//79W5UDAAAAgE1YTgUAAAAwgB3rnlBVW5EDAAAAgE2sXeJ091bkAAAAADgkrXrBzFrLqXbt2nW3wgAAAABwz6xV4hxzzDFblQMAAACATdjYGAAAAGAAShwAAACAAShxAAAAAAagxAEAAAAYgBIHAAAAYABKHAAAAIABKHEAAAAABqDEAQAAABiAEgcAAABgAEocAAAAgAEocQAAAAAGoMQBAAAAGIASBwAAAGAAShwAAACAAShxAAAAAAagxAEAAAAYgBIH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": [
"<Segment(1, 9)>"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# start time in seconds\n",
"s = 1.0\n",
"# end time in seconds\n",
"e = 9.0\n",
"segment = Segment(start=s, end=e)\n",
"segment"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**`Segment`** instances are nothing more than 2-tuples augmented with several useful methods and properties."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"from 1.0 to 9.0\n"
]
}
],
"source": [
"start, end = segment\n",
"print(f\"from {start} to {end}\")"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Segment [ 00:00:01.000 --> 00:00:09.000] ends at 9 seconds.\n",
"Its duration is 8 seconds.\n",
"Its middle stands as 5 seconds.\n"
]
}
],
"source": [
"print(f\"Segment {segment} ends at {segment.end:g} seconds.\")\n",
"print(f\"Its duration is {segment.duration:g} seconds.\")\n",
"print(f\"Its middle stands as {segment.middle:g} seconds.\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Intersection"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Segment [ 00:00:01.000 --> 00:00:09.000] intersects other segment [ 00:00:04.000 --> 00:00:13.000].\n",
"Their intersection is [ 00:00:04.000 --> 00:00:09.000].\n"
]
}
],
"source": [
"other_segment = Segment(4, 13)\n",
"if segment.intersects(other_segment):\n",
" print(f\"Segment {segment} intersects other segment {other_segment}.\")\n",
" intersection = segment & other_segment\n",
" print(f\"Their intersection is {intersection!s}.\")"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAABG0AAABjCAYAAAAhK/2kAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjEsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy8QZhcZAAAImUlEQVR4nO3da6hldRkG8OfNKUqtrMa0HOlE2EWii0xiCdEdu5BBX4qKor4EZReC6ALppxCSSiiKsDJIirCiCCrFor50ccZKSzPt6pilEV1Muvr2YW9xGB08M+4z67/2/H5w2Guts2d4Zng5e51nr/Xf1d0BAAAAYCz3mToAAAAAAHeltAEAAAAYkNIGAAAAYEBKGwAAAIABKW0AAAAABrTtQJ68ffv23tjY2KIoAAAAAIef3bt3/6m7j933+AGVNhsbG9m1a9fqUgEAAAAc5qrqt3d33O1RAAAAAANS2gAAAAAMSGkDAAAAMCClDQAAAMCAlDYAAAAAA1LaAAAAAAxIaQMAAAAwIKUNAAAAwICUNgAAAAADUtoAAAAADEhpAwAAADAgpQ0AAADAgJQ2AAAAAANS2gAAAAAMSGkDAAAAMCClDQAAAMCAlDYAAAAAA1LaAAAAAAxIaQMAAAAwIKUNAAAAwICUNgAAAAADUtoAAAAADEhpAwAAADAgpc0WOOecc6aOAAAwW86lAGChunvTT965c2fv2rVrC+Osh6rKgfy/AgBwJ+dSABxuqmp3d+/c97grbQAAAAAGtG3qAOuqqqaOAAAAAMyY0maLuKQXAODgePMLABbcHrUFzj777KkjAADMlnMpAFiwEDEAAADAhCxEDAAAADAjShsAAACAASltAAAAAAaktAEAAAAYkNIGAAAAYEBKGwAAAIABKW0AAAAABqS0AQAAABiQ0gYAAABgQEobAAAAgAEpbQAAAAAGpLQBAAAAGJDSBgAAAGBAShsAAACAASltAAAAAAaktAEAAAAYkNIGAAAAYEBKGwAAAIABKW0AAAAABqS0AQAAABiQ0gYAAABgQEobAAA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hsLuruL02dh9k7PclLq+o3WdzC+Zyq+uy0kZi5PUn2dPcdVwFenEWJAwfjeUl+3d23dPd/knwpyTMmzsT6+GNVPSJJlo83T5yHmauq1yV5SZJXLYtAOFiPyeINi58sz9N3JLmiqo6fNNXMbKa0uTzJSVX16Kq6XxYL5311a2Oxzqqqslgn4pru/uDUeZi/7n53d+/o7o0sfkZ9q7u9i81B6+4/JLmhqh63PPTcJFdPGIl5+12S06rqyOVr4HNjYWtW56tJXrvcfm2Sr0yYhZmrqjOyuN38pd1929R5mLfuvqq7H97dG8vz9D1JTlmeZ7FJ91jaLBeienOSb2ZxgvGF7v7ZVgdjrZ2e5DVZXA3x4+XXi6YOBbCPs5JcVFVXJnlKkvdPnIeZWl6xdXGSK5JclcX51ycmDcUsVdXnknwvyeOqak9VvSHJuUmeX1XXZXFV17lTZmQ+9jNPH0nywCSXLs/RPz5pSGZlPzPFvVSueAMAAAAYj4WIAQAAAAaktAEAAAAYkNIGAAAAYEBKGwAAAIABKW0AAAAABrRt6gAAAPekqh6W5LLl7vFJ/pfkluX+bd39jEmCAQBsIR/5DQDMSlWdk+TW7j5v6iwAAFvJ7VEAwKxV1a3Lx2dV1Xeq6itV9auqOreqXlVVP6yqq6rqMcvnHVtVX6yqy5dfp0/7LwAAuHtKGwBgnTw5yRuTPCHJa5I8trtPTXJBkrOWzzk/yYe6+2lJXr78HgDAcKxpAwCsk8u7+6YkqapfJrlkefyqJM9ebj8vyclVdcefeVBVHd3dtx7SpAAA90BpAwCsk3/ttX37Xvu3587znvskOa27/3kogwEAHCi3RwEAh5tLcuetUqmqp0yYBQBgv5Q2AMDh5i1JdlbVlVV1dRZr4AAADMdHfgMAAAAMyJU2AAAAAANS2gAAAAAMSGkDAAAAMCClDQAAAMCAlDYAAAAAA1LaAAAAAAxIaQMAAAAwoP8D+i7aL22nSOwAAAAASUVORK5CYII=\n",
"text/plain": [
"<Segment(1, 9)>"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"notebook.crop = Segment(0, 15)\n",
"segment"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAABG0AAABjCAYAAAAhK/2kAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjEsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy8QZhcZAAAImklEQVR4nO3da6hldRkG8OfNKUq7N2blSEeim0Q3JrGE6GJhFzLoS1FR1JegO0F0gfRTCEUXKIqwMkiMsEIJKsWivnRxxkpLs/tlzNKILhZdzLcPe0fD6OCZ4z5n/dee3w8Oe6119hmegZez13n2Wv9d3R0AAAAAxnKXqQMAAAAAcFtKGwAAAIABKW0AAAAABqS0AQAAABiQ0gYAAABgQLuO5Mm7d+/ujY2NbYoCAAAAcPTZv3//H7r7+EOPH1Fps7GxkX379q0uFQAAAMBRrqp+dXvH3R4FAAAAMCClDQAAAMCAlDYAAAAAA1LaAAAAAAxIaQMAAAAwIKUNAAAAwICUNgAAAAADUtoAAAAADEhpAwAAADAgpQ0AAADAgJQ2AAAAAANS2gAAAAAMSGkDAAAAMCClDQAAAMCAlDYAAAAAA1LaAAAAAAxIaQMAAAAwIKUNAAAAwICUNgAAAAADUtoAAAAADEhpAwAAADAgpQ0AAADAgJQ2AAAAAANS2gBr45xzzpk6AgAARwHnneyU6u5NP3nv3r29b9++bYwDsHVVlSP5nQYAAFvhvJNVq6r93b330OOutAEAAAAY0K6pAwCsUlVNHQEAAGAllDbAWnGZKgAA280bhewUt0cBa+Pss8+eOgIAAEcB553sFAsRAwAAAEzIQsQAAAAAM6K0AQAAABiQ0gYAAABgQEobAAAAgAEpbQAAAAAGpLQBAAAAGJDSBgAAAGBAShsAAACAASltAAAAAAaktAEAAAAYkNIGAAAAYEBKG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uQmCC\n",
"text/plain": [
"<Segment(4, 13)>"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"other_segment"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAABG0AAABjCAYAAAAhK/2kAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjEsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy8QZhcZAAAImElEQVR4nO3da6hldRkG8OfNKUq7N2blSEeim0Q3JjGFqKywC03Ql6KiqC9BaUUQWZB+CqHIgqIIK4OkCCuKoFIs6ksXZ6y0NLtnY5ZGdDHpYr592FscRgfPjPvM+q89vx8czlrr7DM8Ay97r/Pstf67ujsAAAAAjOVeUwcAAAAA4M6UNgAAAAADUtoAAAAADEhpAwAAADAgpQ0AAADAgLYdzIO3b9/eGxsbWxQFAAAA4MizZ8+eP3f3sfsfP6jSZmNjI7t3715dKgAAAIAjXFX97q6Ouz0KAAAAYEBKGwAAAIABKW0AAAAABqS0AQAAABiQ0gYAAABgQEobAAAAgAEpbQAAAAAGpLQBAAAAGJDSBgAAAGBAShsAAACAASltAAAAAAaktAEAAAAYkNIGAAAAYEBKGwAAAIABKW0AAAAABqS0AQAAABiQ0gYAAABgQEobAAAAgAEpbQAAAAAGpLQBAAAAGJDSBgAAAGBAShsAAACAASltAAAAAAaktAHWxrnnnjt1BABWwPM5ACxUd2/6wTt37uzdu3dvYRyAQ1dVOZjnNADG5PkcgCNNVe3p7p37H3elDQAAAMCAtk0dAGCVqmrqCAAAACuhtAHWisvpAeZPAQ8AC26PAtbGOeecM3UEAFbA8zkALFiIGAAAAGBCFiIGAAAAmBGlDQAAAMCAlDYAAAAAA1LaAAAAAAxIaQMAAAAwIKUNAAAAw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GAAAAYEBKGwAAAIABKW0AAAAABqS0AQAAABjQ/wGm0dovkW7s6QAAAABJRU5ErkJggg==\n",
"text/plain": [
"<Segment(4, 9)>"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"segment & other_segment"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Those two segments do not intersect.\n"
]
}
],
"source": [
"other_segment = Segment(13, 20)\n",
"if not (segment & other_segment):\n",
" print(\"Those two segments do not intersect.\")"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAABHQAAABjCAYAAAD6kFeGAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjEsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy8QZhcZAAAIIElEQVR4nO3dXahlZRkH8P/TjFKooTZiosaU9EmUxSR9SFhUlDcWhSQVdlVBH0Y3RTczBYGEfV0ZfQgGlUlaeqmE9HGjM2PqmGKpKCmTk4jkEBk5TxdniYM4Z86eOTN73r1/PzjstdZea59nw3Ne9vmz3ndXdwcAAACAcbxo3gUAAAAAMBuBDgAAAMBgBDoAAAAAgxHoAAAAAAxGoAMAAAAwmI2znLxp06bevHnzESoFAAAAYPns3Lnz8e4+bZZrZgp0Nm/enB07dsxWFQAAAAAHVFUPz3qNKVcAAAAAgxHoAAAAAAxGoAMAAAAwGIEOAAAAwGAEOgAAAACDEegAAAAADEagAwAAADAYgQ4AAADAYAQ6AAAAAIMR6AAAAAAMRqADAAAAMBiBDgAAAMBgBDoAAAAAgxHoAAAAAAxGoAMAAAAwGIEOAAAAwGAEOgAAAACDEegAAAA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ALBInt5ve99++/vy3OeeFyV5e3f/52gWBgCwnky5AgCWzU15bvpVqurcOdYCAHBIBDoAwLL5UpItVXVXVd2TlTV3AACG4mvLAQAAAAbjDh0AAACAwQh0AAAAAAYj0AEAAAAYjEAHAAAAYDACHQAAAIDBCHQAAAAABiPQAQAAABjM/wGaYB4rN0IT+AAAAABJRU5ErkJggg==\n",
"text/plain": [
"<Segment(1, 9)>"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"notebook.crop = Segment(0, 30)\n",
"segment"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAABHIAAABjCAYAAAD3jifBAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAACBtJREFUeJzt3V2IredZBuD7TnaKVgWtlUZqJDnQA6XSEhH/3QWVFiH+\nUulR8UA8EPVE8OfAPSdSrFoKCp4YJbaiiGKtSNUWGqoHtkb2Nmlaq0IDpsZU8YeECgbzeDBr0yHp\n3rPGPTtr3rWuC4b55lvvHp6BZz+zuOd7v68zEwAAAAAuvjt2XQAAAAAA2xHkAAAAACxCkAMAAACw\nCEEOAAAAwCIEOQAAAACLEOQAAAAALOLStgvbek45AAAAwDmbmW67dusgZ/ONz14NLOTo6ChHR0e7\nLgNuK33OIdDnHAJ9ziHQ5xyCdusMJ4mtVQAAAADLEOQAAAAALEKQAydcvnx51yXAbafPOQT6nEOg\nzzkE+hxerNve96btuEcOAAAAwPlpe6abHbsiBwAAAGARghwAAACARQhyAAAAABYhyAEAAABYhCAH\nAAAAYBGCHAAAAIBFCHIAAAAAFiHIAQAAAFiEIAcAAABgEYIcAAAAgEUIcgAAAAAWIcgBAAAAWIQg\nBwAAAGARghwAAACARQhyAAAAABYhyAEAAABYhCAHAAAAYBGCHAAAAIBFCHIAAAAAFiHIAYBFHB0d\n7bo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AMAiBDkAAAAA\nixDkAAAAACxCkAMAAACwCEEOAAAAwCIEOQAAAACLEOQAAAAALOL/AOD6Op7eng0gAAAAAElFTkSu\nQmCC\n",
"text/plain": [
"<Segment(13, 20)>"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"other_segment"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Inclusion"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[ 00:00:05.000 --> 00:00:06.000] in included in [ 00:00:01.000 --> 00:00:09.000]\n"
]
}
],
"source": [
"other_segment = Segment(5, 6)\n",
"if other_segment in segment:\n",
" print(f\"{other_segment} in included in {segment}\")"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[ 00:00:01.000 --> 00:00:09.000] does not contain time 23.000000\n"
]
}
],
"source": [
"t = 23.0\n",
"if not segment.overlaps(t):\n",
" print(f\"{segment} does not contain time {t:f}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Other operations"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Union of [ 00:00:01.000 --> 00:00:09.000] and [ 00:00:10.000 --> 00:00:30.000] is [ 00:00:01.000 --> 00:00:30.000]\n"
]
}
],
"source": [
"other_segment = Segment(10, 30)\n",
"print(f\"Union of {segment} and {other_segment} is {segment | other_segment}\")"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gap between [ 00:00:01.000 --> 00:00:09.000] and [ 00:00:14.000 --> 00:00:15.000] is [ 00:00:09.000 --> 00:00:14.000]\n"
]
}
],
"source": [
"other_segment = Segment(14, 15)\n",
"print(f\"Gap between {segment} and {other_segment} is {segment ^ other_segment}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# SlidingWindow (`pyannote.core.segment.SlidingWindow`)"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"from pyannote.core import SlidingWindow, Timeline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Iteration"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAABHQAAABjCAYAAAD6kFeGAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjEsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy8QZhcZAAAIeUlEQVR4nO3dXYhtZRkH8P+Tpyi17yNmGpwIsyQwYxJTCCsvjCKDIIoSiW6CUosgrJtzLr2QyosIxCwhMUIDJaIMi7or52jkV5JZfpdKVFqUmU8Xs8WD1pnZnrNnnXfv3w+GWWudtdY8B+aZd89/1vvu6u4AAAAAMI4XTF0AAAAAAPMR6AAAAAAMRqADAAAAMBiBDgAAAMBgBDoAAAAAg9kxz8k7d+7sXbt2LagUAAAAgNWzd+/eR7v7qHmumSvQ2bVrV9bX1+erCgAAAID/q6rumfcaU64AAAAABiPQAQAAABiMQAcAAABgMAIdAAAAgMEIdAAAAAAGI9ABAAAAGIxABwAAAGAwAh0AAACAwQh0AAAAAAYj0AEAAAAYjEAHAAAAYDACHQAAAIDBCHQAAAAABiPQAQAAABjMXIHOgw8+uKg6gP3Ys2fPUPcF9m+RvaevYRrGalguxmpGUN299ZOrep7zgYOjqrKI3lvUfYH9W2Tv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ebNzLknyle5+e5IPzf4NAGAo1tABAJbJjd39UJJU1e+SXD87fkuSd822z0xyYlU9fc3LqurI7n58WysFADgAAh0AYJn8a5/tp/bZfyrPvO55QZJTu/uf21kYAMDBZMoVALBqrs8z069SVW+dsBYAgOdFoAMArJrzk6xV1a+r6vZsrLkDADAUb1sOAAAAMBhP6AAAAAAMRqADAAAAMBiBDgAAAMBgBDoAAAAAgxHoAAAAAAxGoAMAAAAwGIEOAAAAwGD+C34GBVKcVMJvAAAAAElFTkSuQmCC\n",
"text/plain": [
"<Timeline(uri=None, segments=[<Segment(0, 2)>, <Segment(1.1, 3.1)>, <Segment(2.2, 4.2)>, <Segment(3.3, 5.3)>, <Segment(4.4, 6.4)>, <Segment(5.5, 7.5)>, <Segment(6.6, 8.6)>, <Segment(7.7, 9.7)>, <Segment(8.8, 10.8)>, <Segment(9.9, 11.9)>])>"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"notebook.crop = Segment(0, 10)\n",
"window = SlidingWindow(start=0.0, step=1.1, duration=2.0, end=10.0)\n",
"Timeline(window)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Cropping"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Given an interval, `.crop` can be used to return every position of the sliding window within this interval. "
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAABHQAAABjCAYAAAD6kFeGAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjEsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy8QZhcZAAAHnklEQVR4nO3dX6hlZRkG8OfVU5Ta/xErFY6EWUNgxklMISy9MIoMAilKJLoJSi2CsG5mLr2QyosIxCwhMUIFJaIMi7ozz2jkn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PVhVl1fVJ6rql1V1d1W9ZXbesVV1Y1XdMfs5a9rfAABgfgodAGA7OTXJZ5K8PcmFSd7a3acnuTrJxbNzrkzyte5+d5KPzv4MAGAo1tABALaTO7p7f5JU1e+S3Do7fneS9822z02ys6qeG/Pqqjqmu5/e0qQAAIdAoQMAbCf/Omj7wEH7B/L8+54jkpzR3f/cymAAAC8lt1wBAIvm1jx/+1Wq6p0TZgEA+L8odACARXNJkpWq+nVV3Ze1NXcAAIbia8sBAAAABuMKHQAAAIDBKHQAAAAABqPQAQAAABiMQgcAAABgMAodAAAAgMEodAAAAAAGo9ABAAAAGMx/AYgYd1xUnjgzAAAAAElFTkSuQmCC\n",
"text/plain": [
"<Segment(3, 7.5)>"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"interval = Segment(3.0, 7.5)\n",
"interval"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`strict` mode only returns fully contained positions."
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAABHQAAABjCAYAAAD6kFeGAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjEsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy8QZhcZAAAH9klEQVR4nO3dX6hlZRkG8OfNU5Ta/xErFUbCrCEw4ySmEJZeGEUGQRQlEt0EpRZBWDczl15I5UUEYpaQGKGCElGGRd2ZZzTyX5JZ6tiYSlRalJlvF2eLg2Dn7Gb2WfOd/fvBcNZas9aeZy7eOXues9a3q7sDAAAAwDheMnUAAAAAAOaj0AEAAAAYjEIHAAAAYDAKHQAAAIDBKHQAAAAABrMyz8k7duzonTt3LigKAAAAwPLZu3fvE919zDzXzFXo7Ny5M2tra/OlAgAAAOBFVdWD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/ylu4+LcmVSS6cnXN5kq9197uSfGT2ewAAQ7GGDgCwndzW3fuTpKp+l+Tm2fE7k7x3tn1Okl1V9dw1r6qqo7v7qS1NCgBwEBQ6AMB28q8Dtp89YP/ZPP++5yVJTu/uf25lMACAQ8kjVwDAsrk5zz9+lap6x4RZAAD+LwodAGDZXJRktap+XVX3ZH3NHQCAofjYcgAAAIDBuEMHAAAAYDAKHQAAAIDBKHQAAAAABqPQAQAAABiMQgcAAABgMAodAAAAgMEodAAAAAAG818wsqtSW5wuEQAAAABJRU5ErkJggg==\n",
"text/plain": [
"<Timeline(uri=None, segments=[<Segment(3.3, 5.3)>, <Segment(4.4, 6.4)>, <Segment(5.5, 7.5)>])>"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"indices = window.crop(interval, mode=\"strict\")\n",
"Timeline(window[i] for i in indices)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`loose` mode returns any intersecting position."
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAABHQAAABjCAYAAAD6kFeGAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjEsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy8QZhcZAAAIQklEQVR4nO3dW6ilZRkH8P+TU5R2bsRKg4kwS4IO7MQUooMXRpFBEEWFRDdBqUUQ1c3MpRdSeRGB2AmKIixIIsqwqLtyT0WaJpWdNEslOliUmU8Xe4mDh/Zezaz9zrvX7wfD/tY337fmGZj/nrX++/veVd0dAAAAAObxqNEDAAAAALAchQ4AAADAZBQ6AAAAAJNR6AAAAABMRqEDAAAAMJl9yxy8f//+PnDgwIpGAQAAAFg/hw8fvqu7T17mnKUKnQMHDmRzc3O5qQAAAA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YCpVdSjJ3d192ehZAABGccsVADC1qrp78fUVVfXdqvpqVd1SVZdW1Vur6gdVdX1VPWdx3MlV9eWqum7x69yxfwMAgOUpdACAveSFSd6V5PlJ3p7kud19VpIrk1y0OObyJB/t7pcmeePi9wAApmINHQBgL7muu29Pkqr6ZZJrFvuvT/LKxfZ5Sc6sqvvPeWJVPb67797VSQEAjoJCBwDYS/51xPZ9Rzy+Lw+87nlUkrO7+5+7ORgAwLHklisAYN1ckwduv0pVvWjgLAAA/xeFDgCwbi5OslFVP6mqG7O15g4AwFR8bDkAAADAZFyhAwAAADAZhQ4AAADAZBQ6AAAAAJNR6AAAAABMRqEDAAAAMBmFDgAAAMBkFDoAAAAAk/kv13jYSQaAcdMAAAAASUVORK5CYII=\n",
"text/plain": [
"<Timeline(uri=None, segments=[<Segment(1.1, 3.1)>, <Segment(2.2, 4.2)>, <Segment(3.3, 5.3)>, <Segment(4.4, 6.4)>, <Segment(5.5, 7.5)>, <Segment(6.6, 8.6)>])>"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"indices = window.crop(interval, mode=\"loose\")\n",
"Timeline(window[i] for i in indices)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`center` mode centers first and last position on interval boundaries."
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAABHQAAABjCAYAAAD6kFeGAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjEsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy8QZhcZAAAIJ0lEQVR4nO3dW6hldR0H8O9Pp6js3kQXDSaimwRlnMISoosPRpFBEEVFRC9B2YUgqpeZxx6ky0MEYTcoijBBiSjDot7MMxZZmlR20yyNqLTo6q+Hs8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LqXV9n59YsAAAAAGZhUWQAAACAySh0AAAAACaj0AEAAACYjEIHAAAAYDIKHQAAAIDJ7Pqx5QAAo1XVo5JctXr62CT/SnL76vlfuvv5Q4IBAAziY8sBgKlU1bEkd3b3xaOzAACM4pYrAGBqVXXn6vGFVfWtqrq8qm6qqg9U1euq6jtVdV1VPWl13KOr6ktVdc3qz3lj/wcAAOtT6AAAB8kzk7wlydOTvCHJU7r7uUkuSXLR6piPJPlQdz8nyatWfwcAMBVr6AAAB8k13X1rklTVT5Ncudp/XZIXrbbPT3J2Vf3nnIdW1YO7+859TQoAcBIUOgDAQfK3E7bvOuH5Xbn7fc9pSc7t7r/uZzAAgFPJLVcAwNJcmbtvv0pVPWtgFgCA/4tCBwBYmrcn2aqq71fV9dlZcwcAYCo+thwAAABgMq7QAQAAAJiMQgcAAABgMgodAAAAgMkodAAAAAAmo9ABAAAAmIxCBwAAAGAyCh0AAACAyfwbEJnJTLHYR8IAAAAASUVORK5CYII=\n",
"text/plain": [
"<Timeline(uri=None, segments=[<Segment(2.2, 4.2)>, <Segment(3.3, 5.3)>, <Segment(4.4, 6.4)>, <Segment(5.5, 7.5)>, <Segment(6.6, 8.6)>])>"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"indices = window.crop(interval, mode=\"center\")\n",
"Timeline(window[i] for i in indices)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Need help?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can always try the following... \n",
"Who knows? It might give you the information you are looking for!"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Help on class Segment in module pyannote.core.segment:\n",
"\n",
"class Segment(Segment)\n",
" | Temporal interval defined by its `start` and `end` times.\n",
" | \n",
" | Multiple segment operators are available -- including intersection (&),\n",
" | inclusion (in), emptiness test, start/end time shifting (+, -, >>, <<).\n",
" | They are illustrated in **Examples** section.\n",
" | \n",
" | Comparison of two segments is also available (==, !=, <, <=, >, >=).\n",
" | Two segments are equal iff they have identical start and end times.\n",
" | Segment S is smaller than segment T iff S.start < T.start or if they have\n",
" | the same start time and S.end < T.start.\n",
" | \n",
" | Parameters\n",
" | ----------\n",
" | start, end : float\n",
" | `start` and `end` times, in seconds.\n",
" | \n",
" | Returns\n",
" | -------\n",
" | segment : Segment\n",
" | New segment with `start` and `end` times.\n",
" | \n",
" | Examples\n",
" | --------\n",
" | Create a new temporal interval between 00:13.000 and 00:37.000.\n",
" | \n",
" | >>> segment = Segment(start=13., end=37)\n",
" | >>> print segment\n",
" | [13.000 --> 37.000]\n",
" | \n",
" | Inclusion, intersection, union & gap\n",
" | \n",
" | >>> s1 = Segment(1, 2)\n",
" | >>> s2 = Segment(0, 3)\n",
" | >>> if s1 in s2:\n",
" | ... print \"Segment %s is included in segment %s.\" % (s1, s2)\n",
" | Segment [1.000 --> 2.000] is included in segment [0.000 --> 3.000].\n",
" | >>> s3 = Segment(2, 5)\n",
" | >>> print s1 & s3\n",
" | ∅\n",
" | >>> print s2 & s3\n",
" | [2.000 --> 3.000]\n",
" | >>> print s2 | s3\n",
" | [0.000 --> 5.000]\n",
" | >>> print s1 ^ Segment(5, 7)\n",
" | [2.000 --> 5.000]\n",
" | \n",
" | Test whether segment is empty or not.\n",
" | \n",
" | >>> if not Segment(10, 10):\n",
" | ... print \"Segment is empty.\"\n",
" | Segment is empty.\n",
" | \n",
" | Comparison\n",
" | \n",
" | >>> s1 = Segment(1, 3)\n",
" | >>> s2 = Segment(1, 3)\n",
" | >>> s3 = Segment(2, 6)\n",
" | >>> s4 = Segment(1, 2)\n",
" | >>> for s in sorted([s1, s2, s3, s4]):\n",
" | ... print s\n",
" | [1.000 --> 2.000]\n",
" | [1.000 --> 3.000]\n",
" | [1.000 --> 3.000]\n",
" | [2.000 --> 6.000]\n",
" | \n",
" | Method resolution order:\n",
" | Segment\n",
" | Segment\n",
" | __builtin__.tuple\n",
" | __builtin__.object\n",
" | \n",
" | Methods defined here:\n",
" | \n",
" | __and__(self, other)\n",
" | Use the expression 'segment & other'\n",
" | \n",
" | Returns\n",
" | -------\n",
" | segment : Segment\n",
" | Intersection of the two segments\n",
" | \n",
" | __bool__(self)\n",
" | Use the expression 'if segment'\n",
" | \n",
" | Returns\n",
" | -------\n",
" | valid : bool\n",
" | False is segment is empty, True otherwise.\n",
" | \n",
" | __contains__(self, other)\n",
" | Use the expression 'other in segment'\n",
" | \n",
" | Returns\n",
" | -------\n",
" | contains : bool\n",
" | True if other segment is fully included, False otherwise\n",
" | \n",
" | __iter__(self)\n",
" | Makes sure tuple(segment) is a tuple of float\n",
" | \n",
" | __nonzero__(self)\n",
" | \n",
" | __or__(self, other)\n",
" | Use the expression 'segment | other'\n",
" | \n",
" | Returns\n",
" | -------\n",
" | segment : Segment\n",
" | Shortest segment that contains both segments\n",
" | \n",
" | __repr__(self)\n",
" | \n",
" | __str__(self)\n",
" | Use the expression str(segment)\n",
" | \n",
" | __xor__(self, other)\n",
" | Use the expression 'segment ^ other'\n",
" | \n",
" | Returns\n",
" | -------\n",
" | segment : Segment\n",
" | Gap between the two segments\n",
" | \n",
" | _get_duration(self)\n",
" | \n",
" | _get_middle(self)\n",
" | \n",
" | _pretty(self, seconds)\n",
" | \n",
" | _repr_png_(self)\n",
" | \n",
" | copy(self)\n",
" | Duplicate segment.\n",
" | \n",
" | for_json(self)\n",
" | \n",
" | intersects(self, other)\n",
" | Check whether two segments intersect each other\n",
" | \n",
" | Parameters\n",
" | ----------\n",
" | other : Segment\n",
" | Other segment\n",
" | \n",
" | Returns\n",
" | -------\n",
" | intersects : bool\n",
" | True if segments intersect, False otherwise\n",
" | \n",
" | overlaps(self, t)\n",
" | \n",
" | pretty(self)\n",
" | Human-readable representation of segments\n",
" | \n",
" | ----------------------------------------------------------------------\n",
" | Class methods defined here:\n",
" | \n",
" | from_json(cls, data) from __builtin__.type\n",
" | \n",
" | ----------------------------------------------------------------------\n",
" | Static methods defined here:\n",
" | \n",
" | __new__(cls, start=0.0, end=0.0)\n",
" | \n",
" | ----------------------------------------------------------------------\n",
" | Data descriptors defined here:\n",
" | \n",
" | __dict__\n",
" | dictionary for instance variables (if defined)\n",
" | \n",
" | duration\n",
" | \n",
" | middle\n",
" | \n",
" | ----------------------------------------------------------------------\n",
" | Methods inherited from Segment:\n",
" | \n",
" | __getnewargs__(self)\n",
" | Return self as a plain tuple. Used by copy and pickle.\n",
" | \n",
" | __getstate__(self)\n",
" | Exclude the OrderedDict from pickling\n",
" | \n",
" | _asdict(self)\n",
" | Return a new OrderedDict which maps field names to their values\n",
" | \n",
" | _replace(_self, **kwds)\n",
" | Return a new Segment object replacing specified fields with new values\n",
" | \n",
" | ----------------------------------------------------------------------\n",
" | Class methods inherited from Segment:\n",
" | \n",
" | _make(cls, iterable, new=<built-in method __new__ of type object>, len=<built-in function len>) from __builtin__.type\n",
" | Make a new Segment object from a sequence or iterable\n",
" | \n",
" | ----------------------------------------------------------------------\n",
" | Data descriptors inherited from Segment:\n",
" | \n",
" | end\n",
" | Alias for field number 1\n",
" | \n",
" | start\n",
" | Alias for field number 0\n",
" | \n",
" | ----------------------------------------------------------------------\n",
" | Data and other attributes inherited from Segment:\n",
" | \n",
" | _fields = ('start', 'end')\n",
" | \n",
" | ----------------------------------------------------------------------\n",
" | Methods inherited from __builtin__.tuple:\n",
" | \n",
" | __add__(...)\n",
" | x.__add__(y) <==> x+y\n",
" | \n",
" | __eq__(...)\n",
" | x.__eq__(y) <==> x==y\n",
" | \n",
" | __ge__(...)\n",
" | x.__ge__(y) <==> x>=y\n",
" | \n",
" | __getattribute__(...)\n",
" | x.__getattribute__('name') <==> x.name\n",
" | \n",
" | __getitem__(...)\n",
" | x.__getitem__(y) <==> x[y]\n",
" | \n",
" | __getslice__(...)\n",
" | x.__getslice__(i, j) <==> x[i:j]\n",
" | \n",
" | Use of negative indices is not supported.\n",
" | \n",
" | __gt__(...)\n",
" | x.__gt__(y) <==> x>y\n",
" | \n",
" | __hash__(...)\n",
" | x.__hash__() <==> hash(x)\n",
" | \n",
" | __le__(...)\n",
" | x.__le__(y) <==> x<=y\n",
" | \n",
" | __len__(...)\n",
" | x.__len__() <==> len(x)\n",
" | \n",
" | __lt__(...)\n",
" | x.__lt__(y) <==> x<y\n",
" | \n",
" | __mul__(...)\n",
" | x.__mul__(n) <==> x*n\n",
" | \n",
" | __ne__(...)\n",
" | x.__ne__(y) <==> x!=y\n",
" | \n",
" | __rmul__(...)\n",
" | x.__rmul__(n) <==> n*x\n",
" | \n",
" | count(...)\n",
" | T.count(value) -> integer -- return number of occurrences of value\n",
" | \n",
" | index(...)\n",
" | T.index(value, [start, [stop]]) -> integer -- return first index of value.\n",
" | Raises ValueError if the value is not present.\n",
"\n"
]
}
],
"source": [
"help(Segment)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.4"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
File diff suppressed because it is too large. Load diff
+50
View File
@@ -0,0 +1,50 @@
[project]
name = "pyannote-core"
description = "Advanced data structures for handling temporal segments with attached labels"
readme = "README.md"
authors = [
{ name = "Hervé BREDIN", email = "herve@pyannote.ai" }
]
requires-python = ">=3.11"
dynamic = [
"version",
]
dependencies = [
"numpy>=2.0",
"pandas>=2.2.3",
"sortedcontainers>=2.4.0",
]
[project.optional-dependencies]
notebook = [
"ipython>=8.31.0",
"matplotlib>=3.10.0",
]
test = [
"matplotlib>=3.10.0",
"pytest>=8.3.4",
"scipy>=1.15.1",
]
doc = [
"sphinx-rtd-theme>=3.0.2",
"sphinx>=8.1.3",
"matplotlib>=3.10.0",
"ipython>=8.32.0",
]
[build-system]
requires = ["hatchling==1.32.0", "hatch-vcs"]
build-backend = "hatchling.build"
[tool.hatch.version]
source = "vcs"
[tool.hatch.build.targets.wheel]
packages = ["src/pyannote"]
[dependency-groups]
dev = [
"ipykernel>=6.29.5",
]
@@ -0,0 +1,66 @@
# The MIT License (MIT)
# Copyright (c) 2014-2019 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
# Hervé BREDIN - http://herve.niderb.fr
import importlib.metadata
PYANNOTE_URI = "uri"
PYANNOTE_MODALITY = "modality"
PYANNOTE_SEGMENT = "segment"
PYANNOTE_TRACK = "track"
PYANNOTE_LABEL = "label"
PYANNOTE_SCORE = "score"
PYANNOTE_IDENTITY = "identity"
from .annotation import Annotation
from .feature import SlidingWindowFeature
from .segment import Segment, SlidingWindow
from .timeline import Timeline
__all__ = [
"PYANNOTE_IDENTITY",
"PYANNOTE_LABEL",
"PYANNOTE_MODALITY",
"PYANNOTE_SCORE",
"PYANNOTE_SEGMENT",
"PYANNOTE_TRACK",
"PYANNOTE_URI",
"Annotation",
"Segment",
"SlidingWindow",
"SlidingWindowFeature",
"Timeline",
]
try:
from .notebook import notebook
except ImportError:
pass
else:
__all__ += ["notebook"]
Segment.set_precision()
__version__ = importlib.metadata.version("pyannote-core")
File diff suppressed because it is too large. Load diff
+331
View File
@@ -0,0 +1,331 @@
# The MIT License (MIT)
# Copyright (c) 2014-2019 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
# Hervé BREDIN - http://herve.niderb.fr
"""
########
Features
########
See :class:`pyannote.core.SlidingWindowFeature` for the complete reference.
"""
import numbers
import warnings
from collections.abc import Iterator
from typing import Union
import numpy as np
from pyannote.core.utils.types import Alignment
from .segment import Segment, SlidingWindow
from .timeline import Timeline
class SlidingWindowFeature(np.lib.mixins.NDArrayOperatorsMixin):
"""Periodic feature vectors
Parameters
----------
data : (n_frames, n_features) numpy array
sliding_window : SlidingWindow
labels : list, optional
Textual description of each dimension.
"""
def __init__(
self,
data: np.ndarray,
sliding_window: SlidingWindow,
labels: list[str] | None = None,
):
self.sliding_window: SlidingWindow = sliding_window
self.data = data
self.labels = labels
self.__i: int = -1
def __len__(self):
"""Number of feature vectors"""
return self.data.shape[0]
@property
def extent(self):
return self.sliding_window.range_to_segment(0, len(self))
@property
def dimension(self):
"""Dimension of feature vectors"""
return self.data.shape[1]
def getNumber(self):
warnings.warn("This is deprecated in favor of `__len__`", DeprecationWarning)
return self.data.shape[0]
def getDimension(self):
warnings.warn(
"This is deprecated in favor of `dimension` property", DeprecationWarning
)
return self.dimension
def getExtent(self):
warnings.warn(
"This is deprecated in favor of `extent` property", DeprecationWarning
)
return self.extent
def __getitem__(self, i: int) -> np.ndarray:
"""Get ith feature vector"""
return self.data[i]
def __iter__(self):
self.__i = -1
return self
def __next__(self) -> tuple[Segment, np.ndarray]:
self.__i += 1
try:
return self.sliding_window[self.__i], self.data[self.__i]
except IndexError:
raise StopIteration()
def next(self):
return self.__next__()
def iterfeatures(
self, window: bool | None = False
) -> Iterator[tuple[np.ndarray, Segment] | np.ndarray]:
"""Feature vector iterator
Parameters
----------
window : bool, optional
When True, yield both feature vector and corresponding window.
Default is to only yield feature vector
"""
n_samples = self.data.shape[0]
for i in range(n_samples):
if window:
yield self.data[i], self.sliding_window[i]
else:
yield self.data[i]
def crop(
self,
focus: Segment | Timeline,
mode: Alignment = "loose",
fixed: float | None = None,
return_data: bool = True,
) -> Union[np.ndarray, "SlidingWindowFeature"]:
"""Extract frames
Parameters
----------
focus : Segment or Timeline
mode : {'loose', 'strict', 'center'}, optional
In 'strict' mode, only frames fully included in 'focus' support are
returned. In 'loose' mode, any intersecting frames are returned. In
'center' mode, first and last frames are chosen to be the ones
whose centers are the closest to 'focus' start and end times.
Defaults to 'loose'.
fixed : float, optional
Overrides `Segment` 'focus' duration and ensures that the number of
returned frames is fixed (which might otherwise not be the case
because of rounding errors).
return_data : bool, optional
Return a numpy array (default). For `Segment` 'focus', setting it
to False will return a `SlidingWindowFeature` instance.
Returns
-------
data : `numpy.ndarray` or `SlidingWindowFeature`
Frame features.
See also
--------
SlidingWindow.crop
"""
if (not return_data) and (not isinstance(focus, Segment)):
msg = (
'"focus" must be a "Segment" instance when "return_data"'
"is set to False."
)
raise ValueError(msg)
if (not return_data) and (fixed is not None):
msg = '"fixed" cannot be set when "return_data" is set to False.'
raise ValueError(msg)
ranges = self.sliding_window.crop(
focus, mode=mode, fixed=fixed, return_ranges=True
)
# total number of samples in features
n_samples = self.data.shape[0]
# 1 for vector features (e.g. MFCC in pyannote.audio)
# 2 for matrix features (e.g. grey-level frames in pyannote.video)
# 3 for 3rd order tensor (e.g. RBG frames in pyannote.video)
n_dimensions = len(self.data.shape) - 1
# clip ranges
clipped_ranges, repeat_first, repeat_last = [], 0, 0
for start, end in ranges:
# count number of requested samples before first sample
repeat_first += min(end, 0) - min(start, 0)
# count number of requested samples after last sample
repeat_last += max(end, n_samples) - max(start, n_samples)
# if all requested samples are out of bounds, skip
if end < 0 or start >= n_samples:
continue
else:
# keep track of non-empty clipped ranges
clipped_ranges += [[max(start, 0), min(end, n_samples)]]
if clipped_ranges:
data = np.vstack([self.data[start:end, :] for start, end in clipped_ranges])
else:
# if all ranges are out of bounds, just return empty data
shape = (0,) + self.data.shape[1:]
data = np.empty(shape)
# corner case when "fixed" duration cropping is requested:
# correct number of samples even with out-of-bounds indices
if fixed is not None:
data = np.vstack(
[
# repeat first sample as many times as needed
np.tile(self.data[0], (repeat_first,) + (1,) * n_dimensions),
data,
# repeat last sample as many times as needed
np.tile(
self.data[n_samples - 1], (repeat_last,) + (1,) * n_dimensions
),
]
)
# return data
if return_data:
return data
# wrap data in a SlidingWindowFeature and return
sliding_window = SlidingWindow(
start=self.sliding_window[clipped_ranges[0][0]].start,
duration=self.sliding_window.duration,
step=self.sliding_window.step,
)
return SlidingWindowFeature(data, sliding_window, labels=self.labels)
def _repr_png_(self):
from .notebook import MATPLOTLIB_IS_AVAILABLE, MATPLOTLIB_WARNING
if not MATPLOTLIB_IS_AVAILABLE:
warnings.warn(MATPLOTLIB_WARNING.format(klass=self.__class__.__name__))
return None
from .notebook import repr_feature
return repr_feature(self)
_HANDLED_TYPES = (np.ndarray, numbers.Number)
def __array__(self) -> np.ndarray:
return self.data
def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
out = kwargs.get("out", ())
for x in inputs + out:
# Only support operations with instances of _HANDLED_TYPES.
# Use SlidingWindowFeature instead of type(self) for isinstance to
# allow subclasses that don't override __array_ufunc__ to
# handle SlidingWindowFeature objects.
if not isinstance(x, self._HANDLED_TYPES + (SlidingWindowFeature,)):
return NotImplemented
# Defer to the implementation of the ufunc on unwrapped values.
inputs = tuple(
x.data if isinstance(x, SlidingWindowFeature) else x for x in inputs
)
if out:
kwargs["out"] = tuple(
x.data if isinstance(x, SlidingWindowFeature) else x for x in out
)
data = getattr(ufunc, method)(*inputs, **kwargs)
if type(data) is tuple:
# multiple return values
return tuple(
type(self)(x, self.sliding_window, labels=self.labels) for x in data
)
elif method == "at":
# no return value
return None
else:
# one return value
return type(self)(data, self.sliding_window, labels=self.labels)
def align(self, to: "SlidingWindowFeature") -> "SlidingWindowFeature":
"""Align features by linear temporal interpolation
Parameters
----------
to : SlidingWindowFeature
Features to align with.
Returns
-------
aligned : SlidingWindowFeature
Aligned features
"""
old_start = self.sliding_window.start
old_step = self.sliding_window.step
old_duration = self.sliding_window.duration
old_samples = len(self)
old_t = old_start + 0.5 * old_duration + np.arange(old_samples) * old_step
new_start = to.sliding_window.start
new_step = to.sliding_window.step
new_duration = to.sliding_window.duration
new_samples = len(to)
new_t = new_start + 0.5 * new_duration + np.arange(new_samples) * new_step
new_data = np.hstack(
[
np.interp(new_t, old_t, old_data)[:, np.newaxis]
for old_data in self.data.T
]
)
return SlidingWindowFeature(new_data, to.sliding_window, labels=self.labels)
if __name__ == "__main__":
import doctest
doctest.testmod()
+460
View File
@@ -0,0 +1,460 @@
# The MIT License (MIT)
# Copyright (c) 2014-2019 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
# Hervé BREDIN - http://herve.niderb.fr
"""
#############
Visualization
#############
:class:`pyannote.core.Segment`, :class:`pyannote.core.Timeline`,
:class:`pyannote.core.Annotation` and :class:`pyannote.core.SlidingWindowFeature`
instances can be directly visualized in notebooks.
You will however need to install ``pyannote.core``'s additional dependencies
for notebook representations (namely, matplotlib):
.. code-block:: bash
pip install pyannote.core[notebook]
Segments
--------
.. code-block:: ipython
In [1]: from pyannote.core import Segment
In [2]: segment = Segment(start=5, end=15)
....: segment
.. plot:: pyplots/segment.py
Timelines
---------
.. code-block:: ipython
In [25]: from pyannote.core import Timeline, Segment
In [26]: timeline = Timeline()
....: timeline.add(Segment(1, 5))
....: timeline.add(Segment(6, 8))
....: timeline.add(Segment(12, 18))
....: timeline.add(Segment(7, 20))
....: timeline
.. plot:: pyplots/timeline.py
Annotations
-----------
.. code-block:: ipython
In [1]: from pyannote.core import Annotation, Segment
In [6]: annotation = Annotation()
...: annotation[Segment(1, 5)] = 'Carol'
...: annotation[Segment(6, 8)] = 'Bob'
...: annotation[Segment(12, 18)] = 'Carol'
...: annotation[Segment(7, 20)] = 'Alice'
...: annotation
.. plot:: pyplots/annotation.py
"""
from collections.abc import Iterable
from itertools import cycle, groupby, product
import numpy as np
from .annotation import Annotation
from .feature import SlidingWindowFeature
from .segment import Segment, SlidingWindow
from .timeline import Timeline
from .utils.types import Label, LabelStyle, Resource
try:
import matplotlib # noqa: F401 -- probe whether the optional dependency imports
except ImportError:
MATPLOTLIB_IS_AVAILABLE = False
else:
MATPLOTLIB_IS_AVAILABLE = True
MATPLOTLIB_WARNING = (
"Couldn't import matplotlib to render the vizualization "
"for object {klass}. To enable, install the required dependencies "
"with 'pip install pyannore.core[notebook]'"
)
class Notebook:
def __init__(self):
self.reset()
def reset(self):
from matplotlib.pyplot import get_cmap
linewidth = [3, 1]
linestyle = ["solid", "dashed", "dotted"]
cm = get_cmap("Set1")
colors = [cm(1.0 * i / 8) for i in range(9)]
self._style_generator = cycle(product(linestyle, linewidth, colors))
self._style: dict[Label | None, LabelStyle] = {
None: ("solid", 1, (0.0, 0.0, 0.0))
}
del self.crop
del self.width
@property
def crop(self):
"""The crop property."""
return self._crop
@crop.setter
def crop(self, segment: Segment):
self._crop = segment
@crop.deleter
def crop(self):
self._crop = None
@property
def width(self):
"""The width property"""
return self._width
@width.setter
def width(self, value: int):
self._width = value
@width.deleter
def width(self):
self._width = 20
def __getitem__(self, label: Label) -> LabelStyle:
"""Get line style for a given label"""
if label not in self._style:
self._style[label] = next(self._style_generator)
return self._style[label]
def setup(self, ax=None, ylim=(0, 1), yaxis=False, time=True):
import matplotlib.pyplot as plt
if ax is None:
ax = plt.gca()
ax.set_xlim(self.crop)
if time:
ax.set_xlabel("Time")
else:
ax.set_xticklabels([])
ax.set_ylim(ylim)
ax.axes.get_yaxis().set_visible(yaxis)
return ax
def draw_segment(self, ax, segment: Segment, y, label=None, boundaries=True):
# do nothing if segment is empty
if not segment:
return
linestyle, linewidth, color = self[label]
# draw segment
ax.hlines(
y,
segment.start,
segment.end,
color,
linewidth=linewidth,
linestyle=linestyle,
label=label,
)
if boundaries:
ax.vlines(
segment.start, y + 0.05, y - 0.05, color, linewidth=1, linestyle="solid"
)
ax.vlines(
segment.end, y + 0.05, y - 0.05, color, linewidth=1, linestyle="solid"
)
if label is None:
return
def get_y(self, segments: Iterable[Segment]) -> np.ndarray:
"""
Parameters
----------
segments : Iterable
`Segment` iterable (sorted)
Returns
-------
y : np.array
y coordinates of each segment
"""
# up_to stores the largest end time
# displayed in each line (at the current iteration)
# (at the beginning, there is only one empty line)
up_to = [-np.inf]
# y[k] indicates on which line to display kth segment
y = []
for segment in segments:
# so far, we do not know which line to use
found = False
# try each line until we find one that is ok
for i, u in enumerate(up_to):
# if segment starts after the previous one
# on the same line, then we add it to the line
if segment.start >= u:
found = True
y.append(i)
up_to[i] = segment.end
break
# in case we went out of lines, create a new one
if not found:
y.append(len(up_to))
up_to.append(segment.end)
# from line numbers to actual y coordinates
y = 1.0 - 1.0 / (len(up_to) + 1) * (1 + np.array(y))
return y
def __call__(self, resource: Resource, time: bool = True, legend: bool = True):
if isinstance(resource, Segment):
self.plot_segment(resource, time=time)
elif isinstance(resource, Timeline):
self.plot_timeline(resource, time=time)
elif isinstance(resource, Annotation):
self.plot_annotation(resource, time=time, legend=legend)
elif isinstance(resource, SlidingWindowFeature):
self.plot_feature(resource, time=time)
def plot_segment(self, segment, ax=None, time=True):
if not self.crop:
self.crop = segment
ax = self.setup(ax=ax, time=time)
self.draw_segment(ax, segment, 0.5)
def plot_timeline(self, timeline: Timeline, ax=None, time=True):
if not self.crop and timeline:
self.crop = timeline.extent()
cropped = timeline.crop(self.crop, mode="loose")
ax = self.setup(ax=ax, time=time)
for segment, y in zip(cropped, self.get_y(cropped)):
self.draw_segment(ax, segment, y)
# ax.set_aspect(3. / self.crop.duration)
def plot_annotation(self, annotation: Annotation, ax=None, time=True, legend=True):
if not self.crop:
self.crop = annotation.get_timeline(copy=False).extent()
cropped = annotation.crop(self.crop, mode="intersection")
segments = [s for s, _ in cropped.itertracks()]
ax = self.setup(ax=ax, time=time)
for (segment, track, label), y in zip(
cropped.itertracks(yield_label=True), self.get_y(segments)
):
self.draw_segment(ax, segment, y, label=label)
if legend:
H, L = ax.get_legend_handles_labels()
# corner case when no segment is visible
if not H:
return
# this gets exactly one legend handle and one legend label per label
# (avoids repeated legends for repeated tracks with same label)
HL = groupby(
sorted(zip(H, L), key=lambda h_l: h_l[1]), key=lambda h_l: h_l[1]
)
H, L = zip(*[(next(h_l)[0], l) for l, h_l in HL])
ax.legend(
H,
L,
bbox_to_anchor=(0, 1),
loc=3,
ncol=5,
borderaxespad=0.0,
frameon=False,
)
def plot_feature(
self, feature: SlidingWindowFeature, ax=None, time=True, ylim=None
):
if not self.crop:
self.crop = feature.extent
window = feature.sliding_window
n, _dimension = feature.data.shape
((start, stop),) = window.crop(self.crop, mode="loose", return_ranges=True)
xlim = (window[start].middle, window[stop].middle)
start = max(0, start)
stop = min(stop, n)
t = window[0].middle + window.step * np.arange(start, stop)
data = feature[start:stop]
if ylim is None:
m = np.nanmin(data)
M = np.nanmax(data)
ylim = (m - 0.1 * (M - m), M + 0.1 * (M - m))
ax = self.setup(ax=ax, yaxis=False, ylim=ylim, time=time)
ax.plot(t, data)
ax.set_xlim(xlim)
notebook = Notebook()
def repr_segment(segment: Segment):
"""Get `png` data for `segment`"""
import matplotlib.pyplot as plt
from IPython.core.pylabtools import print_figure
figsize = plt.rcParams["figure.figsize"]
plt.rcParams["figure.figsize"] = (notebook.width, 1)
fig, ax = plt.subplots()
notebook.plot_segment(segment, ax=ax)
data = print_figure(fig, "png")
plt.close(fig)
plt.rcParams["figure.figsize"] = figsize
return data
def repr_timeline(timeline: Timeline):
"""Get `png` data for `timeline`"""
import matplotlib.pyplot as plt
from IPython.core.pylabtools import print_figure
figsize = plt.rcParams["figure.figsize"]
plt.rcParams["figure.figsize"] = (notebook.width, 1)
fig, ax = plt.subplots()
notebook.plot_timeline(timeline, ax=ax)
data = print_figure(fig, "png")
plt.close(fig)
plt.rcParams["figure.figsize"] = figsize
return data
def repr_annotation(annotation: Annotation):
"""Get `png` data for `annotation`"""
import matplotlib.pyplot as plt
from IPython.core.pylabtools import print_figure
figsize = plt.rcParams["figure.figsize"]
plt.rcParams["figure.figsize"] = (notebook.width, 2)
fig, ax = plt.subplots()
notebook.plot_annotation(annotation, ax=ax)
data = print_figure(fig, "png")
plt.close(fig)
plt.rcParams["figure.figsize"] = figsize
return data
def repr_feature(feature: SlidingWindowFeature):
"""Get `png` data for `feature`"""
import matplotlib.pyplot as plt
from IPython.core.pylabtools import print_figure
figsize = plt.rcParams["figure.figsize"]
if feature.data.ndim == 2:
plt.rcParams["figure.figsize"] = (notebook.width, 2)
fig, ax = plt.subplots()
notebook.plot_feature(feature, ax=ax)
data = print_figure(fig, "png")
plt.close(fig)
elif feature.data.ndim == 3:
num_chunks = len(feature)
if notebook.crop is None:
notebook.crop = Segment(
start=feature.sliding_window.start,
end=feature.sliding_window[num_chunks - 1].end,
)
else:
feature = feature.crop(notebook.crop, mode="loose", return_data=False)
num_overlap = (
round(feature.sliding_window.duration // feature.sliding_window.step) + 1
)
num_overlap = min(num_chunks, num_overlap)
plt.rcParams["figure.figsize"] = (notebook.width, 1.5 * num_overlap)
fig, axes = plt.subplots(nrows=num_overlap, ncols=1, squeeze=False)
axes = axes.flatten()
mini, maxi = np.nanmin(feature.data), np.nanmax(feature.data)
ylim = (mini - 0.2 * (maxi - mini), maxi + 0.2 * (maxi - mini))
for c, (window, data) in enumerate(feature):
ax = axes[c % num_overlap]
step = duration = window.duration / len(data)
frames = SlidingWindow(start=window.start, step=step, duration=duration)
window_feature = SlidingWindowFeature(data, frames, labels=feature.labels)
notebook.plot_feature(
window_feature,
ax=ax,
time=c % num_overlap == (num_overlap - 1),
ylim=ylim,
)
ax.set_prop_cycle(None)
data = print_figure(fig, "png")
plt.close(fig)
plt.rcParams["figure.figsize"] = figsize
return data
+922
View File
@@ -0,0 +1,922 @@
# The MIT License (MIT)
# Copyright (c) 2014-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.
# AUTHORS
# Hervé BREDIN - http://herve.niderb.fr
"""
#######
Segment
#######
.. plot:: pyplots/segment.py
:class:`pyannote.core.Segment` instances describe temporal fragments (*e.g.* of an audio file). The segment depicted above can be defined like that:
.. code-block:: ipython
In [1]: from pyannote.core import Segment
In [2]: segment = Segment(start=5, end=15)
In [3]: print(segment)
It is nothing more than 2-tuples augmented with several useful methods and properties:
.. code-block:: ipython
In [4]: start, end = segment
In [5]: start
In [6]: segment.end
In [7]: segment.duration # duration (read-only)
In [8]: segment.middle # middle (read-only)
In [9]: segment & Segment(3, 12) # intersection
In [10]: segment | Segment(3, 12) # union
In [11]: segment.overlaps(3) # does segment overlap time t=3?
Use `Segment.set_precision(ndigits)` to automatically round start and end timestamps to `ndigits` precision after the decimal point.
To ensure consistency between `Segment` instances, it is recommended to call this method only once, right after importing `pyannote.core.Segment`.
.. code-block:: ipython
In [12]: Segment(1/1000, 330/1000) == Segment(1/1000, 90/1000+240/1000)
Out[12]: False
In [13]: Segment.set_precision(ndigits=4)
In [14]: Segment(1/1000, 330/1000) == Segment(1/1000, 90/1000+240/1000)
Out[14]: True
See :class:`pyannote.core.Segment` for the complete reference.
"""
import warnings
from collections.abc import Iterable, Iterator
from dataclasses import dataclass
from typing import TYPE_CHECKING, Union
if TYPE_CHECKING:
from .timeline import Timeline
import numpy as np
from .utils.types import Alignment
# setting 'frozen' to True makes it hashable and immutable
@dataclass(frozen=True, order=True)
class Segment:
"""
Time interval
Parameters
----------
start : float
interval start time, in seconds.
end : float
interval end time, in seconds.
Segments can be compared and sorted using the standard operators:
>>> Segment(0, 1) == Segment(0, 1.)
True
>>> Segment(0, 1) != Segment(3, 4)
True
>>> Segment(0, 1) < Segment(2, 3)
True
>>> Segment(0, 1) < Segment(0, 2)
True
>>> Segment(1, 2) < Segment(0, 3)
False
Note
----
A segment is smaller than another segment if one of these two conditions is verified:
- `segment.start < other_segment.start`
- `segment.start == other_segment.start` and `segment.end < other_segment.end`
"""
start: float = 0.0
end: float = 0.0
@staticmethod
def set_precision(ndigits: int | None = None):
"""Automatically round start and end timestamps to `ndigits` precision after the decimal point
To ensure consistency between `Segment` instances, it is recommended to call this method only
once, right after importing `pyannote.core.Segment`.
Usage
-----
>>> from pyannote.core import Segment
>>> Segment.set_precision(2)
>>> Segment(1/3, 2/3)
<Segment(0.33, 0.67)>
"""
global AUTO_ROUND_TIME
global SEGMENT_PRECISION
if ndigits is None:
# backward compatibility
AUTO_ROUND_TIME = False
# 1 μs (one microsecond)
SEGMENT_PRECISION = 1e-6
else:
AUTO_ROUND_TIME = True
SEGMENT_PRECISION = 10 ** (-ndigits)
def __bool__(self):
"""Emptiness
>>> if segment:
... # segment is not empty.
... else:
... # segment is empty.
Note
----
A segment is considered empty if its end time is smaller than its
start time, or its duration is smaller than 1μs.
"""
return bool((self.end - self.start) > SEGMENT_PRECISION)
def __post_init__(self):
"""Round start and end up to SEGMENT_PRECISION precision (when required)"""
if AUTO_ROUND_TIME:
object.__setattr__(
self,
"start",
int(self.start / SEGMENT_PRECISION + 0.5) * SEGMENT_PRECISION,
)
object.__setattr__(
self, "end", int(self.end / SEGMENT_PRECISION + 0.5) * SEGMENT_PRECISION
)
@property
def duration(self) -> float:
"""Segment duration (read-only)"""
return self.end - self.start if self else 0.0
@property
def middle(self) -> float:
"""Segment mid-time (read-only)"""
return 0.5 * (self.start + self.end)
def __iter__(self) -> Iterator[float]:
"""Unpack segment boundaries
>>> segment = Segment(start, end)
>>> start, end = segment
"""
yield self.start
yield self.end
def copy(self) -> "Segment":
"""Get a copy of the segment
Returns
-------
copy : Segment
Copy of the segment.
"""
return Segment(start=self.start, end=self.end)
# ------------------------------------------------------- #
# Inclusion (in), intersection (&), union (|) and gap (^) #
# ------------------------------------------------------- #
def __contains__(self, other: "Segment"):
"""Inclusion
>>> segment = Segment(start=0, end=10)
>>> Segment(start=3, end=10) in segment:
True
>>> Segment(start=5, end=15) in segment:
False
"""
return (self.start <= other.start) and (self.end >= other.end)
def __and__(self, other):
"""Intersection
>>> segment = Segment(0, 10)
>>> other_segment = Segment(5, 15)
>>> segment & other_segment
<Segment(5, 10)>
Note
----
When the intersection is empty, an empty segment is returned:
>>> segment = Segment(0, 10)
>>> other_segment = Segment(15, 20)
>>> intersection = segment & other_segment
>>> if not intersection:
... # intersection is empty.
"""
start = max(self.start, other.start)
end = min(self.end, other.end)
return Segment(start=start, end=end)
def intersects(self, other: "Segment") -> bool:
"""Check whether two segments intersect each other
Parameters
----------
other : Segment
Other segment
Returns
-------
intersect : bool
True if segments intersect, False otherwise
"""
return (
(self.start < other.start and other.start < self.end - SEGMENT_PRECISION)
or (self.start > other.start and self.start < other.end - SEGMENT_PRECISION)
or (self.start == other.start)
)
def overlaps(self, t: float) -> bool:
"""Check if segment overlaps a given time
Parameters
----------
t : float
Time, in seconds.
Returns
-------
overlap: bool
True if segment overlaps time t, False otherwise.
"""
return self.start <= t and self.end >= t
def __or__(self, other: "Segment") -> "Segment":
"""Union
>>> segment = Segment(0, 10)
>>> other_segment = Segment(5, 15)
>>> segment | other_segment
<Segment(0, 15)>
Note
----
When a gap exists between the segment, their union covers the gap as well:
>>> segment = Segment(0, 10)
>>> other_segment = Segment(15, 20)
>>> segment | other_segment
<Segment(0, 20)
"""
# if segment is empty, union is the other one
if not self:
return other
# if other one is empty, union is self
if not other:
return self
# otherwise, do what's meant to be...
start = min(self.start, other.start)
end = max(self.end, other.end)
return Segment(start=start, end=end)
def __xor__(self, other: "Segment") -> "Segment":
"""Gap
>>> segment = Segment(0, 10)
>>> other_segment = Segment(15, 20)
>>> segment ^ other_segment
<Segment(10, 15)
Note
----
The gap between a segment and an empty segment is not defined.
>>> segment = Segment(0, 10)
>>> empty_segment = Segment(11, 11)
>>> segment ^ empty_segment
ValueError: The gap between a segment and an empty segment is not defined.
"""
# if segment is empty, xor is not defined
if (not self) or (not other):
raise ValueError(
"The gap between a segment and an empty segment is not defined."
)
start = min(self.end, other.end)
end = max(self.start, other.start)
return Segment(start=start, end=end)
def _str_helper(self, seconds: float) -> str:
from datetime import timedelta
negative = seconds < 0
seconds = abs(seconds)
td = timedelta(seconds=seconds)
seconds = td.seconds + 86400 * td.days
microseconds = td.microseconds
hours, remainder = divmod(seconds, 3600)
minutes, seconds = divmod(remainder, 60)
sign = "-" if negative else " "
return (
f"{sign}{hours:02d}:{minutes:02d}:{seconds:02d}.{microseconds // 1000:03d}"
)
def __str__(self):
"""Human-readable representation
>>> print(Segment(1337, 1337 + 0.42))
[ 00:22:17.000 --> 00:22:17.420]
Note
----
Empty segments are printed as "[]"
"""
if self:
return f"[{self._str_helper(self.start)} --> {self._str_helper(self.end)}]"
return "[]"
def __repr__(self):
"""Computer-readable representation
>>> Segment(1337, 1337 + 0.42)
<Segment(1337, 1337.42)>
"""
return f"<Segment({self.start:g}, {self.end:g})>"
def _repr_png_(self):
"""IPython notebook support
See also
--------
:mod:`pyannote.core.notebook`
"""
from .notebook import MATPLOTLIB_IS_AVAILABLE, MATPLOTLIB_WARNING
if not MATPLOTLIB_IS_AVAILABLE:
warnings.warn(MATPLOTLIB_WARNING.format(klass=self.__class__.__name__))
return None
from .notebook import repr_segment
try:
return repr_segment(self)
except ImportError:
warnings.warn(
f"Couldn't import matplotlib to render the vizualization for object {self}. To enable, install the required dependencies with 'pip install pyannore.core[notebook]'"
)
return None
class SlidingWindow:
"""Sliding window
Parameters
----------
duration : float > 0, optional
Window duration, in seconds. Default is 30 ms.
step : float > 0, optional
Step between two consecutive position, in seconds. Default is 10 ms.
start : float, optional
First start position of window, in seconds. Default is 0.
end : float > `start`, optional
Default is infinity (ie. window keeps sliding forever)
Examples
--------
>>> sw = SlidingWindow(duration, step, start)
>>> frame_range = (a, b)
>>> frame_range == sw.toFrameRange(sw.toSegment(*frame_range))
... True
>>> segment = Segment(A, B)
>>> new_segment = sw.toSegment(*sw.toFrameRange(segment))
>>> abs(segment) - abs(segment & new_segment) < .5 * sw.step
>>> sw = SlidingWindow(end=0.1)
>>> print(next(sw))
[ 00:00:00.000 --> 00:00:00.030]
>>> print(next(sw))
[ 00:00:00.010 --> 00:00:00.040]
"""
def __init__(self, duration=0.030, step=0.010, start=0.000, end=None):
# duration must be a float > 0
if duration <= 0:
raise ValueError("'duration' must be a float > 0.")
self.__duration = duration
# step must be a float > 0
if step <= 0:
raise ValueError("'step' must be a float > 0.")
self.__step: float = step
# start must be a float.
self.__start: float = start
# if end is not provided, set it to infinity
if end is None:
self.__end: float = np.inf
else:
# end must be greater than start
if end <= start:
raise ValueError("'end' must be greater than 'start'.")
self.__end: float = end
# current index of iterator
self.__i: int = -1
@property
def start(self) -> float:
"""Sliding window start time in seconds."""
return self.__start
@property
def end(self) -> float:
"""Sliding window end time in seconds."""
return self.__end
@property
def step(self) -> float:
"""Sliding window step in seconds."""
return self.__step
@property
def duration(self) -> float:
"""Sliding window duration in seconds."""
return self.__duration
def closest_frame(self, t: float) -> int:
"""Closest frame to timestamp.
Parameters
----------
t : float
Timestamp, in seconds.
Returns
-------
index : int
Index of frame whose middle is the closest to `timestamp`
"""
return int(np.rint((t - self.__start - 0.5 * self.__duration) / self.__step))
def samples(self, from_duration: float, mode: Alignment = "strict") -> int:
"""Number of frames
Parameters
----------
from_duration : float
Duration in seconds.
mode : {'strict', 'loose', 'center'}
In 'strict' mode, computes the maximum number of consecutive frames
that can be fitted into a segment with duration `from_duration`.
In 'loose' mode, computes the maximum number of consecutive frames
intersecting a segment with duration `from_duration`.
In 'center' mode, computes the average number of consecutive frames
where the first one is centered on the start time and the last one
is centered on the end time of a segment with duration
`from_duration`.
"""
if mode == "strict":
return int(np.floor((from_duration - self.duration) / self.step)) + 1
elif mode == "loose":
return int(np.floor((from_duration + self.duration) / self.step))
elif mode == "center":
return int(np.rint(from_duration / self.step))
def crop(
self,
focus: Union[Segment, "Timeline"],
mode: Alignment = "loose",
fixed: float | None = None,
return_ranges: bool | None = False,
) -> np.ndarray | list[list[int]]:
"""Crop sliding window
Parameters
----------
focus : `Segment` or `Timeline`
mode : {'strict', 'loose', 'center'}, optional
In 'strict' mode, only indices of segments fully included in
'focus' support are returned. In 'loose' mode, indices of any
intersecting segments are returned. In 'center' mode, first and
last positions are chosen to be the positions whose centers are the
closest to 'focus' start and end times. Defaults to 'loose'.
fixed : float, optional
Overrides `Segment` 'focus' duration and ensures that the number of
returned frames is fixed (which might otherwise not be the case
because of rounding erros).
return_ranges : bool, optional
Return as list of ranges. Defaults to indices numpy array.
Returns
-------
indices : np.array (or list of ranges)
Array of unique indices of matching segments
"""
from .timeline import Timeline
if not isinstance(focus, (Segment, Timeline)):
msg = '"focus" must be a `Segment` or `Timeline` instance.'
raise TypeError(msg)
if isinstance(focus, Timeline):
if fixed is not None:
msg = "'fixed' is not supported with `Timeline` 'focus'."
raise ValueError(msg)
if return_ranges:
ranges = []
for i, s in enumerate(focus.support()):
rng = self.crop(s, mode=mode, fixed=fixed, return_ranges=True)
# if first or disjoint segment, add it
if i == 0 or rng[0][0] > ranges[-1][1]:
ranges += rng
# if overlapping segment, update last range
else:
ranges[-1][1] = rng[0][1]
return ranges
# concatenate all indices
indices = np.hstack(
[
self.crop(s, mode=mode, fixed=fixed, return_ranges=False)
for s in focus.support()
]
)
# remove duplicate indices
return np.unique(indices)
# 'focus' is a `Segment` instance
if mode == "loose":
# find smallest integer i such that
# self.start + i x self.step + self.duration >= focus.start
i_ = (focus.start - self.duration - self.start) / self.step
i = int(np.ceil(i_))
if fixed is None:
# find largest integer j such that
# self.start + j x self.step <= focus.end
j_ = (focus.end - self.start) / self.step
j = int(np.floor(j_))
rng = (i, j + 1)
else:
n = self.samples(fixed, mode="loose")
rng = (i, i + n)
elif mode == "strict":
# find smallest integer i such that
# self.start + i x self.step >= focus.start
i_ = (focus.start - self.start) / self.step
i = int(np.ceil(i_))
if fixed is None:
# find largest integer j such that
# self.start + j x self.step + self.duration <= focus.end
j_ = (focus.end - self.duration - self.start) / self.step
j = int(np.floor(j_))
rng = (i, j + 1)
else:
n = self.samples(fixed, mode="strict")
rng = (i, i + n)
elif mode == "center":
# find window position whose center is the closest to focus.start
i = self.closest_frame(focus.start)
if fixed is None:
# find window position whose center is the closest to focus.end
j = self.closest_frame(focus.end)
rng = (i, j + 1)
else:
n = self.samples(fixed, mode="center")
rng = (i, i + n)
else:
msg = "'mode' must be one of {'loose', 'strict', 'center'}."
raise ValueError(msg)
if return_ranges:
return [list(rng)]
return np.array(range(*rng), dtype=np.int64)
def segmentToRange(self, segment: Segment) -> tuple[int, int]:
warnings.warn("Deprecated in favor of `segment_to_range`", DeprecationWarning)
return self.segment_to_range(segment)
def segment_to_range(self, segment: Segment) -> tuple[int, int]:
"""Convert segment to 0-indexed frame range
Parameters
----------
segment : Segment
Returns
-------
i0 : int
Index of first frame
n : int
Number of frames
Examples
--------
>>> window = SlidingWindow()
>>> print window.segment_to_range(Segment(10, 15))
i0, n
"""
# find closest frame to segment start
i0 = self.closest_frame(segment.start)
# number of steps to cover segment duration
n = int(segment.duration / self.step) + 1
return i0, n
def rangeToSegment(self, i0: int, n: int) -> Segment:
warnings.warn(
"This is deprecated in favor of `range_to_segment`", DeprecationWarning
)
return self.range_to_segment(i0, n)
def range_to_segment(self, i0: int, n: int) -> Segment:
"""Convert 0-indexed frame range to segment
Each frame represents a unique segment of duration 'step', centered on
the middle of the frame.
The very first frame (i0 = 0) is the exception. It is extended to the
sliding window start time.
Parameters
----------
i0 : int
Index of first frame
n : int
Number of frames
Returns
-------
segment : Segment
Examples
--------
>>> window = SlidingWindow()
>>> print window.range_to_segment(3, 2)
[ --> ]
"""
# frame start time
# start = self.start + i0 * self.step
# frame middle time
# start += .5 * self.duration
# subframe start time
# start -= .5 * self.step
start = self.__start + (i0 - 0.5) * self.__step + 0.5 * self.__duration
duration = n * self.__step
end = start + duration
# extend segment to the beginning of the timeline
if i0 == 0:
start = self.start
return Segment(start, end)
def samplesToDuration(self, nSamples: int) -> float:
warnings.warn(
"This is deprecated in favor of `samples_to_duration`", DeprecationWarning
)
return self.samples_to_duration(nSamples)
def samples_to_duration(self, n_samples: int) -> float:
"""Returns duration of samples"""
return self.range_to_segment(0, n_samples).duration
def durationToSamples(self, duration: float) -> int:
warnings.warn(
"This is deprecated in favor of `duration_to_samples`", DeprecationWarning
)
return self.duration_to_samples(duration)
def duration_to_samples(self, duration: float) -> int:
"""Returns samples in duration"""
return self.segment_to_range(Segment(0, duration))[1]
def __getitem__(self, i: int) -> Segment:
"""
Parameters
----------
i : int
Index of sliding window position
Returns
-------
segment : :class:`Segment`
Sliding window at ith position
"""
# window start time at ith position
start = self.__start + i * self.__step
# in case segment starts after the end,
# return an empty segment
if start >= self.__end:
return None
return Segment(start=start, end=start + self.__duration)
def next(self) -> Segment:
return self.__next__()
def __next__(self) -> Segment:
self.__i += 1
window = self[self.__i]
if window:
return window
else:
raise StopIteration()
def __iter__(self) -> "SlidingWindow":
"""Sliding window iterator
Use expression 'for segment in sliding_window'
Examples
--------
>>> window = SlidingWindow(end=0.1)
>>> for segment in window:
... print(segment)
[ 00:00:00.000 --> 00:00:00.030]
[ 00:00:00.010 --> 00:00:00.040]
[ 00:00:00.020 --> 00:00:00.050]
[ 00:00:00.030 --> 00:00:00.060]
[ 00:00:00.040 --> 00:00:00.070]
[ 00:00:00.050 --> 00:00:00.080]
[ 00:00:00.060 --> 00:00:00.090]
[ 00:00:00.070 --> 00:00:00.100]
[ 00:00:00.080 --> 00:00:00.110]
[ 00:00:00.090 --> 00:00:00.120]
"""
# reset iterator index
self.__i = -1
return self
def __len__(self) -> int:
"""Number of positions
Equivalent to len([segment for segment in window])
Returns
-------
length : int
Number of positions taken by the sliding window
(from start times to end times)
"""
if np.isinf(self.__end):
raise ValueError("infinite sliding window.")
# start looking for last position
# based on frame closest to the end
i = self.closest_frame(self.__end)
while self[i]:
i += 1
length = i
return length
def copy(self) -> "SlidingWindow":
"""Duplicate sliding window"""
duration = self.duration
step = self.step
start = self.start
end = self.end
sliding_window = self.__class__(
duration=duration, step=step, start=start, end=end
)
return sliding_window
def __call__(
self, support: Union[Segment, "Timeline"], align_last: bool = False
) -> Iterable[Segment]:
"""Slide window over support
Parameter
---------
support : Segment or Timeline
Support on which to slide the window.
align_last : bool, optional
Yield a final segment so that it aligns exactly with end of support.
Yields
------
chunk : Segment
Example
-------
>>> window = SlidingWindow(duration=2., step=1.)
>>> for chunk in window(Segment(3, 7.5)):
... print(tuple(chunk))
(3.0, 5.0)
(4.0, 6.0)
(5.0, 7.0)
>>> for chunk in window(Segment(3, 7.5), align_last=True):
... print(tuple(chunk))
(3.0, 5.0)
(4.0, 6.0)
(5.0, 7.0)
(5.5, 7.5)
"""
from pyannote.core import Timeline
if isinstance(support, Timeline):
segments = support
elif isinstance(support, Segment):
segments = Timeline(segments=[support])
else:
msg = (
f'"support" must be either a Segment or a Timeline '
f"instance (is {type(support)})"
)
raise TypeError(msg)
for segment in segments:
if segment.duration < self.duration:
continue
window = SlidingWindow(
duration=self.duration,
step=self.step,
start=segment.start,
end=segment.end,
)
for s in window:
# ugly hack to account for floating point imprecision
if s in segment:
yield s
last = s
if align_last and last.end < segment.end:
yield Segment(start=segment.end - self.duration, end=segment.end)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,24 @@
# The MIT License (MIT)
# Copyright (c) 2018 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
# Hervé BREDIN - http://herve.niderb.fr
@@ -0,0 +1,120 @@
# The MIT License (MIT)
# Copyright (c) 2018 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
# Hervé BREDIN - http://herve.niderb.fr
from collections import Counter
import numpy as np
from scipy.spatial.distance import squareform
from .distance import pdist
def chinese_whispers_clustering(
X, t, method="distance", metric="euclidean", max_iter=1000, init=None
):
"""Chinese whispers clustering
Parameters
----------
X : `np.ndarray`
(n_samples, n_dimensions) feature vectors.
t :
method : `str`
Method use to build neighboring graph. Defaults to 'distance'.
No other method is available yet.
metric : `str`
The distance metric to use. See `pdist` function for a list of valid
distance metrics. Defaults to 'euclidean'.
max_iter : `int`
Maximum number of iterations. Defaults to 1000.
init : `np.ndarray`
(n_samples, ) array. Initial cluster number.
Defauts to each item in its own cluster.
Returns
-------
T : `np.ndarray`
(n_samples, ) array. T[i] is the cluster number to which
original observation i belongs.
Reference
---------
Chris Biemann. "Chinese Whispers - an Efficient Graph Clustering Algorithm
and its Application to Natural Language Processing Problems". Workshop on
TextGraphs, at HLT-NAACL 2006.
"""
# TODO. add support for 'precomputed' metric
if method == "distance":
distance = pdist(X, metric=metric)
neighbors = squareform(distance < t)
# mark item with no neighbor as their own neighbor
has_no_neighbor = np.sum(neighbors, axis=1) == 0
for i in range(len(X)):
neighbors[i, i] = has_no_neighbor[i]
elif method == "knn":
msg = "only 'distance' method is supported for now."
raise NotImplementedError(msg)
# neighbors = np.argpartition(squareform(distance), t, axis=1)[:,:t]
else:
msg = "only 'distance' method is supported for now."
raise NotImplementedError(msg)
if init is None:
# initialize one cluster per item
clusters = np.arange(len(X))
else:
# or use provided initialization
clusters = np.array(init).reshape(-1)
# list of indices used to iterate over all items
indices = np.arange(len(X))
for _ in range(max_iter):
# keep track of current state
prev_clusters = np.copy(clusters)
# loop on all items in randomized order
# TODO: option to set random seed for reproducibility
np.random.shuffle(indices)
for i in indices:
# count number of neighbors in each cluster
counts = Counter(clusters[neighbors[i]])
# assign item to most common neighbor cluster
clusters[i] = counts.most_common(n=1)[0][0]
# ratio of items that have changed clusters
changed = np.mean(clusters != prev_clusters)
# stop early if not much has changed since last iteration
if changed > 1e-4:
break
# relabel clusters between 1 and K
_, clusters = np.unique(clusters, return_inverse=True)
return clusters + 1
@@ -0,0 +1,237 @@
# The MIT License (MIT)
# Copyright (c) 2018 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
# Hervé BREDIN - http://herve.niderb.fr
import numpy as np
import scipy.cluster.hierarchy
import scipy.spatial.distance
def l2_normalize(X: np.ndarray):
"""L2 normalize vectors
Parameters
----------
X : `np.ndarray`
(n_samples, n_dimensions) vectors.
Returns
-------
normalized : `np.ndarray`
(n_samples, n_dimensions) L2-normalized vectors
"""
norm = np.sqrt(np.sum(X**2, axis=1))
norm[norm == 0] = 1.0
return (X.T / norm).T
def dist_range(metric="euclidean", normalize=False):
"""Return range of possible distance between two vectors
Parameters
----------
metric : `str`, optional
Metric. Defaults to 'euclidean'
normalize : `bool`, optional
Set to True if vectors are L2-normalized. Defaults to False.
Returns
-------
min_dist, max_dist : `float`
Range of possible distance.
"""
if metric == "euclidean":
if normalize:
return (0.0, 2.0)
return (0.0, np.inf)
if metric == "sqeuclidean":
if normalize:
return (0.0, 4.0)
return (0.0, np.inf)
if metric == "cosine":
return (0.0, 2.0)
if metric == "angular":
return (0.0, np.pi)
msg = f"dist_range does not support {metric} metric."
raise NotImplementedError(msg)
def _pdist_func_1D(X, func):
"""Helper function for pdist"""
(n_items,) = X.shape
if n_items < 2:
return np.array([])
distances = []
for i in range(n_items - 1):
distance = func(X[i], X[i + 1 :])
distances.append(distance)
return np.hstack(distances)
def pdist(fX, metric="euclidean", **kwargs):
"""Same as scipy.spatial.distance with support for additional metrics
* 'angular': pairwise angular distance
* 'equal': pairwise equality check (only for 1-dimensional fX)
* 'minimum': pairwise minimum (only for 1-dimensional fX)
* 'maximum': pairwise maximum (only for 1-dimensional fX)
* 'average': pairwise average (only for 1-dimensional fX)
"""
if metric == "angular":
cosine = scipy.spatial.distance.pdist(fX, metric="cosine", **kwargs)
return np.arccos(np.clip(1.0 - cosine, -1.0, 1.0))
elif metric == "equal":
assert fX.ndim == 1, f"'{metric}' metric only supports 1-dimensional fX."
return _pdist_func_1D(fX, lambda x, X: x == X)
elif metric == "minimum":
assert fX.ndim == 1, f"'{metric}' metric only supports 1-dimensional fX."
return _pdist_func_1D(fX, np.minimum)
elif metric == "maximum":
assert fX.ndim == 1, f"'{metric}' metric only supports 1-dimensional fX."
return _pdist_func_1D(fX, np.maximum)
elif metric == "average":
assert fX.ndim == 1, f"'{metric}' metric only supports 1-dimensional fX."
return _pdist_func_1D(fX, lambda x, X: 0.5 * (x + X))
else:
return scipy.spatial.distance.pdist(fX, metric=metric, **kwargs)
def _cdist_func_1D(X_trn, X_tst, func):
"""Helper function for cdist"""
return np.vstack(func(x_trn, X_tst) for x_trn in iter(X_trn))
def cdist(fX_trn, fX_tst, metric="euclidean", **kwargs):
"""Same as scipy.spatial.distance.cdist with support for additional metrics
* 'angular': pairwise angular distance
* 'equal': pairwise equality check (only for 1-dimensional fX)
* 'minimum': pairwise minimum (only for 1-dimensional fX)
* 'maximum': pairwise maximum (only for 1-dimensional fX)
* 'average': pairwise average (only for 1-dimensional fX)
"""
if metric == "angular":
cosine = scipy.spatial.distance.cdist(fX_trn, fX_tst, metric="cosine", **kwargs)
return np.arccos(np.clip(1.0 - cosine, -1.0, 1.0))
elif metric == "equal":
assert fX_trn.ndim == 1 and fX_tst.ndim == 1, (
f"'{metric}' metric only supports 1-dimensional fX_trn and fX_tst."
)
return _cdist_func_1D(fX_trn, fX_tst, lambda x_trn, X_tst: x_trn == X_tst)
elif metric == "minimum":
assert fX_trn.ndim == 1 and fX_tst.ndim == 1, (
f"'{metric}' metric only supports 1-dimensional fX_trn and fX_tst."
)
return _cdist_func_1D(fX_trn, fX_tst, np.minimum)
elif metric == "maximum":
assert fX_trn.ndim == 1 and fX_tst.ndim == 1, (
f"'{metric}' metric only supports 1-dimensional fX_trn and fX_tst."
)
return _cdist_func_1D(fX_trn, fX_tst, np.maximum)
elif metric == "average":
assert fX_trn.ndim == 1 and fX_tst.ndim == 1, (
f"'{metric}' metric only supports 1-dimensional fX_trn and fX_tst."
)
return _cdist_func_1D(
fX_trn, fX_tst, lambda x_trn, X_tst: 0.5 * (x_trn + X_tst)
)
else:
return scipy.spatial.distance.cdist(fX_trn, fX_tst, metric=metric, **kwargs)
def to_condensed(n, i, j):
"""Compute index in condensed pdist matrix
V
0 | . 0 1 2 3
-> 1 | . . 4 5 6 <- ==> 0 1 2 3 4 5 6 7 8 9
2 | . . . 7 8 ^
3 | . . . . 9
4 | . . . . .
----------
0 1 2 3 4
Parameters
----------
n : int
Number of inputs in squared pdist matrix
i, j : `int` or `numpy.ndarray`
Indices in squared pdist matrix
Returns
-------
k : `int` or `numpy.ndarray`
Index in condensed pdist matrix
"""
i, j = np.array(i), np.array(j)
if np.any(i == j):
raise ValueError("i and j should be different.")
i, j = np.minimum(i, j), np.maximum(i, j)
return np.int64(i * n - i * i / 2 - 3 * i / 2 + j - 1)
def to_squared(n, k):
"""Compute indices in squared matrix
Parameters
----------
n : int
Number of inputs in squared pdist matrix
k : `int` or `numpy.ndarray`
Index in condensed pdist matrix
Returns
-------
i, j : `int` or `numpy.ndarray`
Indices in squared pdist matrix
"""
k = np.array(k)
i = np.int64(n - np.sqrt(-8 * k + 4 * n**2 - 4 * n + 1) / 2 - 1 / 2)
j = np.int64(i**2 / 2 - i * n + 3 * i / 2 + k + 1)
return i, j
@@ -0,0 +1,84 @@
# The MIT License (MIT)
# Copyright (c) 2014-2018 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
# Hervé BREDIN - http://herve.niderb.fr
import itertools
from collections.abc import Iterable, Iterator
from string import ascii_uppercase
def pairwise(iterable: Iterable):
"""s -> (s0,s1), (s1,s2), (s2, s3), ..."""
a, b = itertools.tee(iterable)
next(b, None)
return zip(a, b)
def string_generator(skip: list | set | None = None) -> Iterator[str]:
"""Label generator
Parameters
----------
skip : list or set
List of labels that must be skipped.
This option is useful in case you want to make sure generated labels
are different from a pre-existing set of labels.
Usage
-----
t = string_generator()
next(t) -> 'A' # start with 1-letter labels
... # from A to Z
next(t) -> 'Z'
next(t) -> 'AA' # then 2-letters labels
next(t) -> 'AB' # from AA to ZZ
...
next(t) -> 'ZY'
next(t) -> 'ZZ'
next(t) -> 'AAA' # then 3-letters labels
... # (you get the idea)
"""
if skip is None:
skip = []
# label length
r = 1
# infinite loop
while True:
# generate labels with current length
for c in itertools.product(ascii_uppercase, repeat=r):
if c in skip:
continue
yield "".join(c)
# increment label length when all possibilities are exhausted
r = r + 1
def int_generator() -> Iterator[int]:
i = 0
while True:
yield i
i = i + 1
@@ -0,0 +1,64 @@
# The MIT License (MIT)
# Copyright (c) 2018 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
# Hervé BREDIN - http://herve.niderb.fr
from importlib import import_module
def get_class_by_name(class_name: str, default_module_name: str | None = None) -> type:
"""Load class by its name
Parameters
----------
class_name : `str`
default_module_name : `str`, optional
When provided and `class_name` does not contain the absolute path
Returns
-------
Klass : `type`
Class.
Example
-------
>>> ClopiNet = get_class_by_name(
... 'pyannote.audio.embedding.models.ClopiNet')
>>> ClopiNet = get_class_by_name(
... 'ClopiNet', default_module_name='pyannote.audio.embedding.models')
"""
tokens = class_name.split(".")
if len(tokens) == 1:
if default_module_name is None:
msg = (
f'Could not infer module name from class name "{class_name}".'
f"Please provide default module name."
)
raise ValueError(msg)
module_name = default_module_name
else:
module_name = ".".join(tokens[:-1])
class_name = tokens[-1]
return getattr(import_module(module_name), class_name)
@@ -0,0 +1,455 @@
# The MIT License (MIT)
# Copyright (c) 2018 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
# Hervé BREDIN - http://herve.niderb.fr
"""
==============================================================
Hierarchical clustering (:mod:`pyannote.core.utils.hierarchy`)
==============================================================
"""
from collections import Counter
from collections.abc import Callable
from inspect import signature
import numpy as np
import scipy.cluster.hierarchy
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import connected_components
from scipy.spatial.distance import squareform
from .distance import cdist, l2_normalize, pdist, to_condensed, to_squared
def linkage(X, method="single", metric="euclidean", **kwargs):
"""Same as scipy.cluster.hierarchy.linkage with more metrics and methods"""
if method == "pool":
return pool(X, metric=metric, **kwargs)
# corner case when using non-euclidean distances with methods
# designed for the euclidean distance
if metric != "euclidean" and method in ["centroid", "median", "ward"]:
# Those 3 methods only work with 'euclidean' distance.
# Therefore, one has to unit-normalized embeddings before
# comparison in case they were optimized for 'cosine' (or 'angular')
# distance.
X = l2_normalize(X)
metric = "euclidean"
distance = pdist(X, metric=metric)
return scipy.cluster.hierarchy.linkage(
distance, method=method, metric=metric, **kwargs
)
def _average_pooling_func(
u: int,
v: int,
S: np.ndarray = None,
C: np.ndarray = None,
**kwargs,
) -> np.ndarray:
"""Compute average of newly merged cluster
Parameters
----------
u : int
Cluster index.
v : int
Cluster index.
C : (2 x n_observations - 1, dimension) np.ndarray
Cluster average.
S : (2 x n_observations - 1, ) np.ndarray
Cluster size.
Returns
-------
Cuv : (dimension, ) np.ndarray
Average of newly formed cluster.
"""
return (C[u] * S[u] + C[v] * S[v]) / (S[u] + S[v])
def _centroid_pooling_func(
u: int,
v: int,
X: np.ndarray = None,
d: np.ndarray = None,
K: np.ndarray = None,
**kwargs,
) -> np.ndarray:
"""Compute centroid of newly merged cluster
Parameters
----------
u : int
Cluster index.
v : int
Cluster index.
X : (n_observations, dimension) np.ndarray
Observations.
d : (n_observations, n_obversations) np.ndarray
Distance between observations.
K : (n_observations, ) np.ndarray, optional
Cluster assignment.
Returns
-------
Cuv : (dimension, ) np.ndarray
Centroid of newly formed cluster.
"""
u_or_v = np.where(np.isin(K, [u, v]))[0]
i = np.argmin(np.mean(d[u_or_v][:, u_or_v], axis=0))
return X[u_or_v[i]]
def propagate_constraints(
cannot_link: list[tuple[int, int]], must_link: list[tuple[int, int]]
):
# expand list of "cannot link" constraints thanks to the following rule
# (u != v) & (v == w) ==> u != w
cannot_link = {tuple(sorted(uv)) for uv in cannot_link}
while True:
new_cannot_link = []
for x, y in must_link:
for u, v in cannot_link:
ij = tuple(sorted({u, v}.symmetric_difference({x, y})))
if not ij:
msg = (
f"Found a conflict between 'must_link' and "
f"'cannot_link' constraints for pair ({u}, {v})."
)
raise ValueError(msg)
if len(ij) == 2 and ij not in cannot_link:
new_cannot_link.append(ij)
if new_cannot_link:
cannot_link.update(new_cannot_link)
else:
break
return list(cannot_link)
def pool(
X: np.ndarray,
metric: str = "euclidean",
pooling_func: str | Callable = "average",
cannot_link: list[tuple[int, int]] | None = None,
must_link: list[tuple[int, int]] | None = None,
must_link_method: str = "both",
):
"""'pool' linkage
Parameters
----------
X : np.ndarray
(n_samples, dimension) obversations.
metric : {"euclidean", "cosine", "angular"}, optional
Distance metric. Defaults to "euclidean"
pooling_func: callable, optional
Defaults to "average".
cannot_link : list of pairs, optional
Pairs of indices of observations that cannot be linked. For instance,
[(1, 2), (5, 6)] means that first and second observations cannot end up
in the same cluster, as well as 5th and 6th obversations.
must_link : list of pairs, optional
Pairs of indices of observations that must be linked. For instance,
[(1, 2), (5, 6)] means that first and second observations must end up
in the same cluster, as well as 5th and 6th obversations.
must_link_method : {"merge", "propagate", "both"}, optional
Method used for taking "must link" constraints into account.
* use "merge" to initialize clusters by merging "must link" observations
before any other regular clustering iterations.
* use "propagate" to infer additional "cannot link" constraints by
applying the following propagation rule:
if u and v cannot be linked and v and w must be linked,
then u and w cannot be linked.
* use "both" to apply both methods.
Defaults to "both".
"""
if pooling_func == "average":
pooling_func = _average_pooling_func
elif pooling_func == "centroid":
pooling_func = _centroid_pooling_func
elif isinstance(pooling_func, str):
msg = (
f"{pooling_func} pooling is not supported. Choose between "
f"'average' and 'centroid', or provide your own function."
)
raise ValueError(msg)
if cannot_link is None:
cannot_link = []
if must_link is None:
must_link = []
# obtain number of original observations
n, dimension = X.shape
# compute similarity matrix
d = pdist(X, metric=metric)
# K[j] contains the index of the cluster to which
# the jth observation is currently assigned
K = np.arange(n)
# S[k] contains the current size of kth cluster
S = np.zeros(2 * n - 1, dtype=np.int16)
S[:n] = 1
# C[k] contains the centroid of kth cluster
C = np.zeros((2 * n - 1, dimension))
# at the beginning, each observation is assigned to its own cluster
C[:n, :] = X
# clustering tree (aka dendrogram)
# Z[i, 0] and Z[i, 1] are merged at ith iteration
# Z[i, 2] is the distance between Z[i, 0] and Z[i, 1]
# Z[i, 3] is the total number of original observation in the newly formed cluster
Z = np.zeros((n - 1, 4))
# convert condensed pdist matrix for the `n` original observation to a
# condensed pdist matrix for the `2n-1` clusters (including the `n`
# original observations) that will exist at some point during the process.
D = np.inf * np.ones((2 * n - 1) * (2 * n - 2) // 2)
D[to_condensed(2 * n - 1, *to_squared(n, np.arange(n * (n - 1) // 2)))] = d
if "d" in signature(pooling_func).parameters:
d = squareform(d)
def merge(u, v, iteration, constraint=False):
"""Merge two clusters
Parameters
----------
u, v : int
Indices of clusters to merge.
iteration : int
Current clustering iteration.
constraint : bool
Set to True to indicate that this merge is coming from a 'must_link'
constraint. This will artificially set Z[iteration, 2] to 0.0.
Returns
-------
uv : int
Indices of resulting cluster.
Raises
------
"ValueError" in case of conflict between "must_link" and "cannot_link"
constraints.
"""
k = to_condensed(2 * n - 1, u, v)
if constraint and D[k] == np.inf:
w = u if u < n else v
msg = f"Found a conflict between 'must_link' and 'cannot_link' constraints for observation {w}."
raise ValueError(msg)
# keep track of ...
# ... which clusters are merged at this iteration
# Place the larger child first; preserve input order for equal sizes.
Z[iteration, 0] = v if S[v] > S[u] else u
Z[iteration, 1] = u if Z[iteration, 0] == v else v
# ... their distance
Z[iteration, 2] = 0.0 if constraint else D[k]
# ... the size of the newly formed cluster
Z[iteration, 3] = S[u] + S[v]
S[n + iteration] = S[u] + S[v]
# compute "representation" of newly formed cluster
C[n + iteration] = pooling_func(u, v, X=X, d=d, K=K, S=S, C=C)
# merged clusters are now empty...
S[u] = 0
S[v] = 0
# move observations of merged clusters into the newly formed cluster
K[K == u] = n + iteration
K[K == v] = n + iteration
# compute distance to newly formed cluster
# (only for clusters that still exists, i.e. those that are not empty)
empty = S[: n + iteration] == 0
k = to_condensed(2 * n - 1, n + iteration, np.arange(n + iteration)[~empty])
D[k] = cdist(
C[np.newaxis, n + iteration, :],
C[: n + iteration, :][~empty, :],
metric=metric,
)
# condensed indices of all (u, _) and (v, _) pairs
_u = to_condensed(2 * n - 1, u, np.arange(u))
u_ = to_condensed(2 * n - 1, u, np.arange(u + 1, n + iteration))
_v = to_condensed(2 * n - 1, v, np.arange(v))
v_ = to_condensed(2 * n - 1, v, np.arange(v + 1, n + iteration))
# propagate "cannot link" constraints to newly formed cluster
if cannot_link:
x, _ = to_squared(2 * n - 1, _u[D[_u] == np.inf])
D[to_condensed(2 * n - 1, n + iteration, x)] = np.inf
_, x = to_squared(2 * n - 1, u_[D[u_] == np.inf])
D[to_condensed(2 * n - 1, n + iteration, x)] = np.inf
x, _ = to_squared(2 * n - 1, _v[D[_v] == np.inf])
D[to_condensed(2 * n - 1, n + iteration, x)] = np.inf
_, x = to_squared(2 * n - 1, v_[D[v_] == np.inf])
D[to_condensed(2 * n - 1, n + iteration, x)] = np.inf
# distance to merged clusters u and v no longer exist
D[_u] = np.inf
D[u_] = np.inf
D[_v] = np.inf
D[v_] = np.inf
k = to_condensed(2 * n - 1, n + iteration, np.arange(n + iteration)[empty])
D[k] = np.inf
return n + iteration
iteration = 0
if cannot_link:
if must_link_method in ["propagate", "both"]:
cannot_link = propagate_constraints(cannot_link, must_link)
# take "cannot link" constraints into account by artifically setting the
# distance between corresponding observations to infinity.
u, v = zip(*cannot_link)
D[to_condensed(2 * n - 1, u, v)] = np.inf
# take "must link" constraints into account by merging corresponding
# observations regardless of their actual similarity. this might lead to
# weird clustering results when merged observations are very dissimilar.
if must_link_method in ["merge", "both"] and must_link:
# find connected components in "must link" graph
graph = np.zeros((n, n), dtype=np.int8)
for u, v in must_link:
graph[u, v] = 1
_, K_init = connected_components(
csr_matrix(graph), directed=False, return_labels=True
)
# merge observations within each connected components
for k, count in Counter(K_init).items():
if count < 2:
continue
u, *others = np.where(K_init == k)[0]
for v in others:
u = merge(u, v, iteration, constraint=True)
iteration += 1
# iterate until one cluster remains
start_iteration = iteration
for iteration in range(start_iteration, n - 1):
# find two most similar clusters
k = np.argmin(D)
# when cannot_link constraints prevents any further merging,
# choose an arbitrary (u, v) pair among remaining clusters
if D[k] == np.inf:
u, v, *_ = np.where(S > 0)[0]
else:
u, v = to_squared(2 * n - 1, k)
_ = merge(u, v, iteration)
# return dendrogram
return Z
def fcluster_auto(X, Z, metric="euclidean"):
"""Forms flat clusters using within-class sum of square elbow criterion
Parameters
----------
X : `np.ndarray`
(n_samples, n_dimensions) feature vectors.
Z : `np.ndarray`
The hierarchical clustering encoded with the matrix returned by the
`linkage` function.
metric : `str`
The distance metric to use. See `pdist` function for a list of valid
distance metrics.
Returns
-------
T : ndarray
An array of length n. T[i] is the flat cluster number to which
original observation i belongs.
Reference
---------
H. Delgado, X. Anguerra, C. Fredouille, J. Serrano. "Fast Single- and
Cross-Show Speaker Diarization Using Binary Key Speaker Modeling".
IEEE Transactions on Audio Speech and Language Processing
"""
# within-class sum of squares
wcss = []
for threshold in Z[:, 2]:
y_t = scipy.cluster.hierarchy.fcluster(Z, threshold, criterion="distance")
D = []
for k in np.unique(y_t):
Xk = X[y_t == k]
Ck = np.mean(Xk, axis=0, keepdims=True)
D.append(
cdist(Ck, Xk, metric=metric).reshape(
-1,
)
)
wcss.append(np.mean(np.hstack(D) ** 2))
wcss = np.array(wcss)
# elbow criterion
n = len(X)
# after first step, there n-1 clusters (x1)
x1, y1 = n - 1, wcss[0]
# after last step, there is 1 cluster (x2)
x2, y2 = 1, wcss[-1]
# equation of line passing at both points
# ax + by + c = 0
a = (y2 - y1) / (x2 - x1)
b = 1
c = (x2 * y1 - x1 * y2) / (x1 - x2)
# elbow is at maximum distance to this line
distance = np.abs(a * np.arange(1, n) + b * wcss + c) / np.sqrt(a**2 + b**2)
threshold = Z[np.argmax(distance), 2]
return scipy.cluster.hierarchy.fcluster(Z, threshold, criterion="distance")
@@ -0,0 +1,192 @@
# The MIT License (MIT)
# Copyright (c) 2018 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
# Hervé BREDIN - http://herve.niderb.fr
import numpy as np
from ..annotation import Annotation
from ..feature import SlidingWindowFeature
from ..segment import Segment, SlidingWindow
from ..timeline import Timeline
from .generators import string_generator
def one_hot_encoding(
annotation: Annotation,
support: Segment | Timeline,
window: SlidingWindow | SlidingWindowFeature,
labels: list[str] | None = None,
mode: str = "center",
) -> SlidingWindowFeature:
"""Convert annotation to one-hot-encoded numpy array
Parameters
----------
annotation : `pyannote.core.Annotation`
support : `pyannote.core.Timeline` or `pyannote.core.Segment`
window : `SlidingWindow`
Use this `window`.
labels : list, optional
Predefined list of labels. Defaults to using labels in `annotation`.
Returns
-------
y : SlidingWindowFeature
(N, K) array where y[t, k] > 0 when labels[k] is active at timestep t.
y[t, k] = -1 means we have no idea.
See also
--------
See `one_hot_decoding` to convert `y` back to a `pyannote.core.Annotation`
instance
"""
if not isinstance(window, SlidingWindow):
if hasattr(window, "sliding_window"):
window = window.sliding_window
else:
msg = (
"`window` must be an instance of `SlidingWindow` "
"or have an attribute called 'sliding_window'."
)
raise TypeError(msg)
if isinstance(support, Segment):
extent = support
support = Timeline([support])
else:
extent = support.extent()
window = SlidingWindow(
start=extent.start, step=window.step, duration=window.duration
)
n_samples = window.samples(extent.duration, mode=mode)
# defaults to `labels` contained by `annotation`
labels = annotation.labels() if labels is None else labels
indices = {label: i for i, label in enumerate(labels)}
# one-hot encoding
# -1 = unknown / +1 = active / 0 = inactive
y = -np.ones((n_samples, len(labels)), dtype=np.int8)
for i, j in window.crop(support, mode=mode, return_ranges=True):
i = max(0, min(n_samples, i))
j = max(0, min(n_samples, j))
y[i:j, :] = 0
for label in annotation.labels():
try:
k = indices[label]
except KeyError:
msg = f'List of `labels` does not contain label "{label}".'
print(indices.keys())
raise ValueError(msg)
for i, j in window.crop(
annotation.label_timeline(label), mode=mode, return_ranges=True
):
i = max(0, min(n_samples, i))
j = max(0, min(n_samples, j))
y[i:j, k] += 1
y = np.minimum(y, 1, out=y)
return SlidingWindowFeature(y, window, labels=labels)
def one_hot_decoding(y, window, labels=None):
"""Convert one-hot-encoded numpy array to annotation
Parameters
----------
y : (N, K) or (N, ) `numpy.ndarray`
When y has shape (N, K), y[t, k] > 0 means kth label is active at
timestep t. When y has shape (N, ), y[t] = 0 means no label is active
at timestep t, y[t] = k means (k-1)th label is active.
window : `SlidingWindow`
Use this `window`.
labels : list, optional
Predefined list of labels. Defaults to labels generated by
`pyannote.core.utils.generators.string_generator`.
Returns
-------
annotation : `pyannote.core.Annotation`
See also
--------
`one_hot_encoding`
"""
if not isinstance(window, SlidingWindow):
if hasattr(window, "sliding_window"):
window = window.sliding_window
else:
msg = (
"`window` must be an instance of `SlidingWindow` "
"or have an attribute called 'sliding_window'."
)
raise TypeError(msg)
# if y has shape (N, ), convert it to (N, K) shape
if len(y.shape) < 2:
(N,) = y.shape
# estimate the number of classes
if labels is not None:
K = len(labels)
else:
K = np.max(y)
# convert to (N, K) shape
# y[t, k] = 1 means kth class is active
y_ = np.zeros((N, K), dtype=np.int64)
for t, k in enumerate(y):
if k > 0:
y_[t, k - 1] = 1
y = y_
N, K = y.shape
# generate label names when not provided
if labels is None:
labels = string_generator()
labels = [next(labels) for _ in range(K)]
annotation = Annotation()
y_off = np.zeros((1, K), dtype=np.int64)
y = np.vstack((y_off, y, y_off))
diff = np.diff(y, axis=0)
for k, label in enumerate(labels):
for t in np.where(diff[:, k] != 0)[0]:
if diff[t, k] > 0:
onset_t = window[t].middle
else:
segment = Segment(onset_t, window[t].middle)
annotation[segment, k] = label
return annotation
@@ -0,0 +1,115 @@
# The MIT License (MIT)
# Copyright (c) 2020 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
# Hervé BREDIN - http://herve.niderb.fr
from collections.abc import Iterable, Iterator
import numpy as np
from pyannote.core import Segment
def random_segment(
segments: Iterable[Segment], weighted: bool = False
) -> Iterator[Segment]:
"""Generate segment with probability proportional to its duration
Parameters
----------
segments : Segment iterable
Segments.
weighted : bool, optional
When True, yield segments with probability proportional to their
duration. Defaults to yield segments with uniform probability.
Yields
------
segment : `Segment`
"""
p = None
if weighted:
total = float(sum(s.duration for s in segments))
p = [s.duration / total for s in segments]
n_segments = len(segments)
while True:
i = np.random.choice(n_segments, p=p)
yield segments[i]
def random_subsegment(
segment: Segment, duration: float, min_duration: float | None = None
) -> Iterator[Segment]:
"""Pick a subsegment at random
Parameters
----------
segment : Segment
duration : float
Duration of random subsegment
min_duration : float, optional
When provided, choose segment duration at random between `min_duration`
and `duration` (instead of fixed `duration`).
Yields
------
segment : `Segment`
Usage
-----
>>> for subsegment in random_subsegment(segment, duration):
>>> ... # do something with subsegment
>>> ... pass
>>> generator = random_subsegment(segment, duration)
>>> subsegment = next(generator)
"""
if min_duration is None:
if duration > segment.duration:
msg = (
f"`duration` (= {duration:g}) should be smaller "
f"than `segment` duration (= {segment.duration:g})."
)
raise ValueError(msg)
while True:
# draw start time from [segment.start, segment.end - duration]
t = segment.start + np.random.random() * (segment.duration - duration)
yield Segment(t, t + duration)
else:
# make sure max duration is smaller than actual segment duration
max_duration = min(segment.duration, duration)
while True:
# draw duration from [min_duration, max_duration] interval
rnd_duration = min_duration + np.random.random() * (
max_duration - min_duration
)
# draw start from [segment.start, segment.end - rnd_duration] interval
t = segment.start + np.random.random() * (segment.duration - rnd_duration)
yield Segment(t, t + rnd_duration)
@@ -0,0 +1,19 @@
from collections.abc import Hashable, Iterator
from typing import TYPE_CHECKING, Literal, Union
if TYPE_CHECKING:
from ..annotation import Annotation
from ..feature import SlidingWindowFeature
from ..segment import Segment
from ..timeline import Timeline
Label = Hashable
Support = Union["Segment", "Timeline"]
LabelGeneratorMode = Literal["int", "string"]
LabelGenerator = LabelGeneratorMode | Iterator[Label]
TrackName = str | int
Key = Union["Segment", tuple["Segment", TrackName]]
Resource = Union["Segment", "Timeline", "SlidingWindowFeature", "Annotation"]
CropMode = Literal["intersection", "loose", "strict"]
Alignment = Literal["center", "loose", "strict"]
LabelStyle = tuple[str, int, tuple[float, float, float]]
View File
Whitespace-only changes.
+242
View File
@@ -0,0 +1,242 @@
import pandas as pd
import pytest
from pyannote.core import (
PYANNOTE_LABEL,
PYANNOTE_SEGMENT,
PYANNOTE_TRACK,
Annotation,
Segment,
Timeline,
)
@pytest.fixture
def annotation():
annotation = Annotation(
uri="TheBigBangTheory.Season01.Episode01", modality="speaker"
)
annotation[Segment(3, 5), "_"] = "Penny"
annotation[Segment(5.5, 7), "_"] = "Leonard"
annotation[Segment(8, 10), "_"] = "Penny"
annotation[Segment(8, 10), "anything"] = "Sheldon"
return annotation
def test_crop(annotation):
expected = Annotation(uri="TheBigBangTheory.Season01.Episode01", modality="speaker")
expected[Segment(5.5, 7), "_"] = "Leonard"
expected[Segment(8, 9), "_"] = "Penny"
expected[Segment(8, 9), "anything"] = "Sheldon"
actual = annotation.crop(Segment(5, 9))
assert actual == expected, str(actual)
def test_crop_loose(annotation):
expected = Annotation(uri="TheBigBangTheory.Season01.Episode01", modality="speaker")
expected[Segment(5.5, 7), "_"] = "Leonard"
expected[Segment(8, 10), "_"] = "Penny"
expected[Segment(8, 10), "anything"] = "Sheldon"
actual = annotation.crop(Segment(5, 9), mode="loose")
assert actual == expected, str(actual)
def test_crop_strict(annotation):
expected = Annotation(uri="TheBigBangTheory.Season01.Episode01", modality="speaker")
expected[Segment(5.5, 7), "_"] = "Leonard"
actual = annotation.crop(Segment(5, 9), mode="strict")
assert actual == expected, str(actual)
def test_copy(annotation):
copy = annotation.copy()
assert copy == annotation
def test_creation(annotation):
assert list(annotation.itersegments()) == [
Segment(3, 5),
Segment(5.5, 7),
Segment(8, 10),
]
assert list(annotation.itertracks()) == [
(Segment(3, 5), "_"),
(Segment(5.5, 7), "_"),
(Segment(8, 10), "_"),
(Segment(8, 10), "anything"),
]
assert list(annotation.itertracks(yield_label=True)) == [
(Segment(3, 5), "_", "Penny"),
(Segment(5.5, 7), "_", "Leonard"),
(Segment(8, 10), "_", "Penny"),
(Segment(8, 10), "anything", "Sheldon"),
]
def test_segments(annotation):
assert annotation.get_timeline(copy=False) == Timeline(
[Segment(3, 5), Segment(5.5, 7), Segment(8, 10)],
uri="TheBigBangTheory.Season01.Episode01",
)
def test_segments_copy(annotation):
assert annotation.get_timeline(copy=True) == Timeline(
[Segment(3, 5), Segment(5.5, 7), Segment(8, 10)],
uri="TheBigBangTheory.Season01.Episode01",
)
def test_tracks(annotation):
assert not annotation.has_track(Segment(8, 10), "---")
assert annotation.get_tracks(Segment(8, 10)) == {"_", "anything"}
assert list(annotation.rename_tracks().itertracks()) == [
(Segment(3, 5), "A"),
(Segment(5.5, 7), "B"),
(Segment(8, 10), "C"),
(Segment(8, 10), "D"),
]
def test_labels(annotation):
assert annotation.labels() == ["Leonard", "Penny", "Sheldon"]
assert annotation.get_labels(Segment(8, 10)) == {"Penny", "Sheldon"}
expected_res = Annotation(
uri="TheBigBangTheory.Season01.Episode01", modality="speaker"
)
expected_res[Segment(3, 5), "_"] = "Kaley Cuoco"
expected_res[
Segment(5.5, 7),
"_",
] = "Johnny Galecki"
expected_res[Segment(8, 10), "_"] = "Kaley Cuoco"
expected_res[Segment(8, 10), "anything"] = "Jim Parsons"
mapping = {
"Penny": "Kaley Cuoco",
"Sheldon": "Jim Parsons",
"Leonard": "Johnny Galecki",
}
assert annotation.rename_labels(mapping) == expected_res
def test_analyze(annotation):
assert annotation.label_duration("Penny") == 4
assert annotation.chart() == [("Penny", 4), ("Sheldon", 2), ("Leonard", 1.5)]
assert annotation.argmax() == "Penny"
def test_rename_labels(annotation):
actual = annotation.rename_labels()
expected = Annotation(uri="TheBigBangTheory.Season01.Episode01", modality="speaker")
expected[Segment(3, 5), "_"] = "B"
expected[
Segment(5.5, 7),
"_",
] = "A"
expected[Segment(8, 10), "_"] = "B"
expected[Segment(8, 10), "anything"] = "C"
assert actual == expected
def test_relabel_tracks(annotation):
actual = annotation.relabel_tracks()
expected = Annotation(uri="TheBigBangTheory.Season01.Episode01", modality="speaker")
expected[Segment(3, 5), "_"] = "A"
expected[
Segment(5.5, 7),
"_",
] = "B"
expected[Segment(8, 10), "_"] = "C"
expected[Segment(8, 10), "anything"] = "D"
assert actual == expected
def test_support(annotation):
actual = annotation.support(collar=3.5)
expected = Annotation(uri="TheBigBangTheory.Season01.Episode01", modality="speaker")
expected[Segment(3, 10), "B"] = "Penny"
expected[Segment(5.5, 7), "A"] = "Leonard"
expected[Segment(8, 10), "C"] = "Sheldon"
assert actual == expected
def test_from_records(annotation):
# Check that we can reconstruct an annotation from the
# output of itertracks.
records = annotation.itertracks(yield_label=True)
actual = Annotation.from_records(records)
expected = annotation
assert actual == expected
def test_from_df(annotation):
# Check that we can reconstruct an annotation from a Pandas
# dataframe containing its tracks.
column_names = [PYANNOTE_SEGMENT, PYANNOTE_TRACK, PYANNOTE_LABEL]
df = pd.DataFrame.from_records(annotation.itertracks(True), columns=column_names)
actual = Annotation.from_df(df)
expected = annotation
assert actual == expected
def test_extrude():
annotation = Annotation()
annotation[Segment(0, 10)] = "A"
annotation[Segment(15, 20)] = "A"
annotation[Segment(20, 35)] = "B"
annotation[Segment(15, 25)] = "C"
annotation[Segment(30, 35)] = "C"
extrusion_tl = Timeline([Segment(5, 12), Segment(14, 25)])
intersection_expected = Annotation()
intersection_expected[Segment(0, 5)] = "A"
intersection_expected[Segment(25, 35)] = "B"
intersection_expected[Segment(30, 35)] = "C"
assert (
annotation.extrude(extrusion_tl, mode="intersection") == intersection_expected
)
loose_expected = Annotation()
loose_expected[Segment(30, 35)] = "C"
assert annotation.extrude(extrusion_tl, mode="loose") == loose_expected
strict_expected = Annotation()
strict_expected[Segment(0, 10)] = "A"
strict_expected[Segment(20, 35)] = "B"
strict_expected[Segment(30, 35)] = "C"
assert annotation.extrude(extrusion_tl, mode="strict") == strict_expected
def test_get_overlap():
annotation = Annotation()
annotation[Segment(0, 5)] = "A"
annotation[Segment(10, 15)] = "A"
annotation[Segment(20, 25)] = "A"
annotation[Segment(0, 10)] = "B"
annotation[Segment(15, 25)] = "B"
annotation[Segment(5, 10)] = "C"
annotation[Segment(20, 30)] = "C"
assert annotation.get_overlap() == Timeline([Segment(0, 10), Segment(20, 25)])
assert annotation.get_overlap(["A", "B"]) == Timeline(
[Segment(0, 5), Segment(20, 25)]
)
assert annotation.get_overlap(["A", "C"]) == Timeline([Segment(20, 25)])
assert annotation.get_overlap(["B", "C"]) == Timeline(
[Segment(5, 10), Segment(20, 25)]
)
+86
View File
@@ -0,0 +1,86 @@
import numpy as np
import pytest
from pyannote.core import Segment, SlidingWindow, SlidingWindowFeature
@pytest.fixture
def features():
data = np.arange(20).reshape(2, 10).T
window = SlidingWindow(start=0.0, step=1.0, duration=2.0)
return SlidingWindowFeature(data, window)
@pytest.fixture
def one_feature():
return SlidingWindowFeature(np.array([[[0, 0, 0]], [[1, 1, 1]]]), SlidingWindow())
@pytest.fixture
def segment():
return Segment(3.3, 6.7)
def test_crop_loose(features, segment):
actual = features.crop(segment, mode="loose")
expected = np.array([[2, 3, 4, 5, 6], [12, 13, 14, 15, 16]]).T
np.testing.assert_array_equal(expected, actual)
def test_crop_strict(features, segment):
actual = features.crop(segment, mode="strict")
expected = np.array(
[
[
4,
],
[
14,
],
]
).T
np.testing.assert_array_equal(expected, actual)
def test_crop_center(features, segment):
actual = features.crop(segment, mode="center")
expected = np.array([[2, 3, 4, 5, 6], [12, 13, 14, 15, 16]]).T
np.testing.assert_array_equal(expected, actual)
def test_crop_fixed(features, segment):
actual = features.crop(segment, mode="center", fixed=4.0)
expected = np.array([[2, 3, 4, 5], [12, 13, 14, 15]]).T
np.testing.assert_array_equal(expected, actual)
def test_crop_out_of_bounds(features):
segment = Segment(-6, -1)
actual = features.crop(segment, mode="strict")
expected = np.empty((0, 2))
np.testing.assert_array_equal(expected, actual)
def test_crop_fixed_out_of_bounds(features):
segment = Segment(-2, 6.7)
actual = features.crop(segment, mode="center", fixed=8.7)
expected = np.array(
[[0, 0, 0, 0, 1, 2, 3, 4, 5], [10, 10, 10, 10, 11, 12, 13, 14, 15]]
).T
np.testing.assert_array_equal(expected, actual)
def test_repr_png(features):
pytest.importorskip("IPython")
pytest.importorskip("matplotlib")
expected = b"\x89PNG"
actual = features._repr_png_()[:4]
assert expected == actual
def test_repr_png_one_feature(one_feature):
pytest.importorskip("IPython")
pytest.importorskip("matplotlib")
expected = b"\x89PNG"
actual = one_feature._repr_png_()[:4]
assert expected == actual
+41
View File
@@ -0,0 +1,41 @@
import numpy as np
import pytest
from scipy.cluster.hierarchy import is_valid_linkage
from pyannote.core.utils.hierarchy import pool
@pytest.mark.parametrize("pooling_func", ["average", "centroid"])
def test_pool_unconstrained(pooling_func):
tree = pool(np.array([[0.0], [1.0], [10.0]]), pooling_func=pooling_func)
assert is_valid_linkage(tree)
np.testing.assert_array_equal(tree[:, 3], [2, 3])
assert set(tree[0, :2]) == {0, 1}
assert set(tree[1, :2]) == {2, 3}
np.testing.assert_allclose(
tree[:, 2], [1, 9.5 if pooling_func == "average" else 10]
)
def test_pool_orders_larger_child_first_during_must_link_merges():
tree = pool(
np.array([[0.0], [1.0], [2.0], [20.0]]),
must_link=[(0, 1), (1, 2)],
)
assert is_valid_linkage(tree)
# The second merge combines cluster 4 (two points) with point 2.
# The final merge combines cluster 5 (three points) with point 3.
np.testing.assert_array_equal(tree[1:, :2], [[4, 2], [5, 3]])
np.testing.assert_allclose(tree[:, 2:], [[0, 2], [0, 3], [19, 4]])
def test_pool_cannot_link_remains_separate_until_infinite_distance():
tree = pool(np.array([[0.0], [1.0], [10.0]]), cannot_link=[(0, 1)])
assert set(tree[0, :2]) == {1, 2}
assert np.isinf(tree[-1, 2])
assert tree[-1, 3] == 3
def test_pool_conflicting_constraints():
with pytest.raises(ValueError, match="conflict"):
pool(np.array([[0.0], [1.0]]), must_link=[(0, 1)], cannot_link=[(0, 1)])
+55
View File
@@ -0,0 +1,55 @@
from pyannote.core import Segment
from tests.utils import preserve_segment_state
def test_creation():
s = 1.0
e = 9.0
segment = Segment(start=s, end=e)
assert str(segment) == "[ 00:00:01.000 --> 00:00:09.000]"
assert segment.end == 9
assert segment.duration == 8
assert segment.middle == 5
def test_intersection():
segment = Segment(start=1, end=9)
other_segment = Segment(4, 13)
assert segment.intersects(other_segment)
assert segment & other_segment == Segment(4, 9)
other_segment = Segment(13, 20)
assert not segment.intersects(other_segment)
def test_inclusion():
segment = Segment(start=1, end=9)
other_segment = Segment(5, 9)
print(other_segment in segment)
assert other_segment in segment
assert not segment.overlaps(23)
def test_other_operation():
segment = Segment(start=1, end=9)
other_segment = Segment(10, 30)
assert segment | other_segment == Segment(1, 30)
other_segment = Segment(14, 15)
assert segment ^ other_segment == Segment(9, 14)
@preserve_segment_state
def test_segment_precision_mode():
Segment.set_precision(None)
assert Segment(90 / 1000, 90 / 1000 + 240 / 1000) != Segment(90 / 1000, 330 / 1000)
Segment.set_precision(4)
assert Segment(90 / 1000, 90 / 1000 + 240 / 1000) == Segment(90 / 1000, 330 / 1000)
+271
View File
@@ -0,0 +1,271 @@
# The MIT License (MIT)
# Copyright (c) 2016-2017 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
# Hervé BREDIN - http://herve.niderb.fr
import pytest
from pyannote.core import Annotation, Segment, Timeline
from tests.utils import preserve_segment_state
@pytest.fixture
def timeline():
t = Timeline(uri="MyAudioFile")
t.add(Segment(6, 8))
t.add(Segment(0.5, 3))
t.add(Segment(8.5, 10))
t.add(Segment(1, 4))
t.add(Segment(5, 7))
t.add(Segment(7, 8))
return t
def test_to_annotation(timeline):
expected = Annotation(uri="MyAudioFile", modality="MyModality")
expected[Segment(6, 8)] = "D"
expected[Segment(0.5, 3)] = "A"
expected[Segment(8.5, 10)] = "F"
expected[Segment(1, 4)] = "B"
expected[Segment(5, 7)] = "C"
expected[Segment(7, 8)] = "E"
assert expected == timeline.to_annotation(modality="MyModality")
def test_iteration(timeline):
assert list(timeline) == [
Segment(0.5, 3),
Segment(1, 4),
Segment(5, 7),
Segment(6, 8),
Segment(7, 8),
Segment(8.5, 10),
]
def test_remove(timeline):
timeline.remove(Segment(1, 4))
timeline.remove(Segment(5, 7))
assert list(timeline) == [
Segment(0.5, 3),
Segment(6, 8),
Segment(7, 8),
Segment(8.5, 10),
]
def test_getter(timeline):
assert len(timeline) == 6
assert str(timeline[1]) == "[ 00:00:01.000 --> 00:00:04.000]"
def test_getter_negative(timeline):
assert timeline[-2] == Segment(7, 8)
def test_remove_and_extent():
t = Timeline(uri="MyAudioFile")
t.add(Segment(6, 8))
t.add(Segment(7, 9))
t.add(Segment(6, 9))
t.remove(Segment(6, 9))
assert t.extent() == Segment(6, 9)
def test_extent(timeline):
assert timeline.extent() == Segment(0.5, 10)
def test_support(timeline):
# No collar (default).
assert list(timeline.support()) == [
Segment(0.5, 4),
Segment(5, 8),
Segment(8.5, 10),
]
# Collar of 600 ms.
assert list(timeline.support(0.600)) == [Segment(0.5, 4), Segment(5, 10)]
def test_gaps(timeline):
assert list(timeline.gaps()) == [Segment(4, 5), Segment(8, 8.5)]
@preserve_segment_state
def test_empty_gaps():
empty_timeline = Timeline(uri="MyEmptyGaps")
assert list(empty_timeline.gaps()) == []
Segment.set_precision(3)
assert list(empty_timeline.gaps()) == []
def test_crop(timeline):
selection = Segment(3, 7)
expected_answer = Timeline(uri="MyAudioFile")
expected_answer.add(Segment(3, 4))
expected_answer.add(Segment(5, 7))
expected_answer.add(Segment(6, 7))
assert timeline.crop(selection, mode="intersection") == expected_answer
expected_answer = Timeline(uri="MyAudioFile")
expected_answer.add(Segment(5, 7))
assert timeline.crop(selection, mode="strict") == expected_answer
expected_answer = Timeline(uri="pouet")
expected_answer.add(Segment(1, 4))
expected_answer.add(Segment(5, 7))
expected_answer.add(Segment(6, 8))
assert timeline.crop(selection, mode="loose") == expected_answer
def test_crop_mapping():
timeline = Timeline([Segment(0, 2), Segment(1, 2), Segment(3, 4)])
cropped, mapping = timeline.crop(Segment(1, 2), returns_mapping=True)
expected_cropped = Timeline([Segment(1, 2)])
assert cropped == expected_cropped
expected_mapping = {Segment(1, 2): [Segment(0, 2), Segment(1, 2)]}
assert mapping == expected_mapping
def test_union():
first_timeline = Timeline([Segment(0, 1), Segment(2, 3), Segment(4, 5)])
second_timeline = Timeline([Segment(1.5, 4.5)])
assert first_timeline.union(second_timeline) == Timeline(
[Segment(0, 1), Segment(1.5, 4.5), Segment(2, 3), Segment(4, 5)]
)
assert second_timeline.crop(first_timeline) == Timeline(
[Segment(2, 3), Segment(4, 4.5)]
)
assert list(first_timeline.co_iter(second_timeline)) == [
(Segment(2, 3), Segment(1.5, 4.5)),
(Segment(4, 5), Segment(1.5, 4.5)),
]
def test_union_extent():
first_timeline = Timeline([Segment(0, 1), Segment(2, 3), Segment(4, 5)])
second_timeline = Timeline([Segment(1.5, 6)])
union_timeline = first_timeline.union(second_timeline)
assert union_timeline.extent() == Segment(0, 6)
def test_update_extent():
timeline = Timeline([Segment(0, 1), Segment(2, 3), Segment(4, 5)])
other_timeline = Timeline([Segment(1.5, 6)])
timeline.update(other_timeline)
assert timeline.extent() == Segment(0, 6)
def test_timeline_overlaps():
overlapped_tl = Timeline(uri="La menuiserie mec")
overlapped_tl.add(Segment(0, 10))
overlapped_tl.add(Segment(5, 10))
overlapped_tl.add(Segment(15, 20))
overlapped_tl.add(Segment(18, 23))
expected_overlap = Timeline()
expected_overlap.add(Segment(5, 10))
expected_overlap.add(Segment(18, 20))
assert expected_overlap == overlapped_tl.get_overlap()
def test_extrude():
removed = Segment(2, 5)
timeline = Timeline(uri="KINGJU")
timeline.add(Segment(0, 3))
timeline.add(Segment(2, 5))
timeline.add(Segment(6, 7))
expected_answer = Timeline()
expected_answer.add(Segment(0, 2))
expected_answer.add(Segment(6, 7))
assert timeline.extrude(removed, mode="intersection") == expected_answer
expected_answer = Timeline(uri="MCSALO")
expected_answer.add(Segment(0, 3))
expected_answer.add(Segment(6, 7))
assert timeline.extrude(removed, mode="strict") == expected_answer
expected_answer = Timeline(uri="CADILLAC")
expected_answer.add(Segment(6, 7))
assert timeline.extrude(removed, mode="loose") == expected_answer
def test_initialized_with_empty_segments():
# The first timeline includes empty segments.
first_timeline = Timeline(
[Segment(1, 5), Segment(6, 6), Segment(7, 7), Segment(8, 10)]
)
# The second has no empty segments.
second_timeline = Timeline([Segment(1, 5), Segment(8, 10)])
assert first_timeline == second_timeline
def test_added_empty_segments():
# The first timeline includes empty segments.
first_timeline = Timeline()
first_timeline.add(Segment(1, 5))
first_timeline.add(Segment(6, 6))
first_timeline.add(Segment(7, 7))
first_timeline.add(Segment(8, 10))
# The second has no empty segments.
second_timeline = Timeline()
second_timeline.add(Segment(1, 5))
second_timeline.add(Segment(8, 10))
assert first_timeline == second_timeline
def test_consistent_timelines_with_empty_segments():
# The first timeline is initialized with Segments, some empty.
first_timeline = Timeline(
[Segment(1, 5), Segment(6, 6), Segment(7, 7), Segment(8, 10)]
)
# The second timeline adds one Segment at a time, including empty ones.
second_timeline = Timeline()
second_timeline.add(Segment(1, 5))
second_timeline.add(Segment(6, 6))
second_timeline.add(Segment(7, 7))
second_timeline.add(Segment(8, 10))
assert first_timeline == second_timeline
+16
View File
@@ -0,0 +1,16 @@
from functools import wraps
from pyannote.core import segment
def preserve_segment_state(f):
@wraps(f)
def wrapper(*args, **kwargs):
prev_round_time = segment.AUTO_ROUND_TIME
try:
ret = f(*args, **kwargs)
finally:
segment.AUTO_ROUND_TIME = prev_round_time
return ret
return wrapper
+1403
View File
File diff suppressed because it is too large. Load diff