File size: 47,697 Bytes
8c838e7 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 |
#!/usr/bin/env python
# encoding: utf-8
# 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
# Paul LERNER
"""
##########
Annotation
##########
.. plot:: pyplots/annotation.py
:class:`pyannote.core.Annotation` instances are ordered sets of non-empty
tracks:
- ordered, because segments are sorted by start time (and end time in case of tie)
- set, because one cannot add twice the same track
- non-empty, because one cannot add empty track
A track is a (support, name) pair where `support` is a Segment instance,
and `name` is an additional identifier so that it is possible to add multiple
tracks with the same support.
To define the annotation depicted above:
.. 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'
...:
which is actually a shortcut for
.. code-block:: ipython
In [6]: annotation = Annotation()
...: annotation[Segment(1, 5), '_'] = 'Carol'
...: annotation[Segment(6, 8), '_'] = 'Bob'
...: annotation[Segment(12, 18), '_'] = 'Carol'
...: annotation[Segment(7, 20), '_'] = 'Alice'
...:
where all tracks share the same (default) name ``'_'``.
In case two tracks share the same support, use a different track name:
.. code-block:: ipython
In [6]: annotation = Annotation(uri='my_video_file', modality='speaker')
...: annotation[Segment(1, 5), 1] = 'Carol' # track name = 1
...: annotation[Segment(1, 5), 2] = 'Bob' # track name = 2
...: annotation[Segment(12, 18)] = 'Carol'
...:
The track name does not have to be unique over the whole set of tracks.
.. note::
The optional *uri* and *modality* keywords argument can be used to remember
which document and modality (e.g. speaker or face) it describes.
Several convenient methods are available. Here are a few examples:
.. code-block:: ipython
In [9]: annotation.labels() # sorted list of labels
Out[9]: ['Bob', 'Carol']
In [10]: annotation.chart() # label duration chart
Out[10]: [('Carol', 10), ('Bob', 4)]
In [11]: list(annotation.itertracks())
Out[11]: [(<Segment(1, 5)>, 1), (<Segment(1, 5)>, 2), (<Segment(12, 18)>, u'_')]
In [12]: annotation.label_timeline('Carol')
Out[12]: <Timeline(uri=my_video_file, segments=[<Segment(1, 5)>, <Segment(12, 18)>])>
See :class:`pyannote.core.Annotation` for the complete reference.
"""
import itertools
import warnings
from collections import defaultdict
from typing import (
Hashable,
Optional,
Dict,
Union,
Iterable,
List,
Set,
TextIO,
Tuple,
Iterator,
Text,
TYPE_CHECKING,
)
import numpy as np
from sortedcontainers import SortedDict
from . import (
PYANNOTE_SEGMENT,
PYANNOTE_TRACK,
PYANNOTE_LABEL,
)
from .segment import Segment, SlidingWindow
from .timeline import Timeline
from .feature import SlidingWindowFeature
from .utils.generators import string_generator, int_generator
from .utils.types import Label, Key, Support, LabelGenerator, TrackName, CropMode
if TYPE_CHECKING:
import pandas as pd
class Annotation:
"""Annotation
Parameters
----------
uri : string, optional
name of annotated resource (e.g. audio or video file)
modality : string, optional
name of annotated modality
Returns
-------
annotation : Annotation
New annotation
"""
@classmethod
def from_df(
cls,
df: "pd.DataFrame",
uri: Optional[str] = None,
modality: Optional[str] = None,
) -> "Annotation":
df = df[[PYANNOTE_SEGMENT, PYANNOTE_TRACK, PYANNOTE_LABEL]]
return Annotation.from_records(df.itertuples(index=False), uri, modality)
def __init__(self, uri: Optional[str] = None, modality: Optional[str] = None):
self._uri: Optional[str] = uri
self.modality: Optional[str] = modality
# sorted dictionary
# keys: annotated segments
# values: {track: label} dictionary
self._tracks: Dict[Segment, Dict[TrackName, Label]] = SortedDict()
# dictionary
# key: label
# value: timeline
self._labels: Dict[Label, Timeline] = {}
self._labelNeedsUpdate: Dict[Label, bool] = {}
# timeline meant to store all annotated segments
self._timeline: Timeline = None
self._timelineNeedsUpdate: bool = True
@property
def uri(self):
return self._uri
@uri.setter
def uri(self, uri: str):
# update uri for all internal timelines
for label in self.labels():
timeline = self.label_timeline(label, copy=False)
timeline.uri = uri
timeline = self.get_timeline(copy=False)
timeline.uri = uri
self._uri = uri
def _updateLabels(self):
# list of labels that needs to be updated
update = set(
label for label, update in self._labelNeedsUpdate.items() if update
)
# accumulate segments for updated labels
_segments = {label: [] for label in update}
for segment, track, label in self.itertracks(yield_label=True):
if label in update:
_segments[label].append(segment)
# create timeline with accumulated segments for updated labels
for label in update:
if _segments[label]:
self._labels[label] = Timeline(segments=_segments[label], uri=self.uri)
self._labelNeedsUpdate[label] = False
else:
self._labels.pop(label, None)
self._labelNeedsUpdate.pop(label, None)
def __len__(self):
"""Number of segments
>>> len(annotation) # annotation contains three segments
3
"""
return len(self._tracks)
def __nonzero__(self):
return self.__bool__()
def __bool__(self):
"""Emptiness
>>> if annotation:
... # annotation is not empty
... else:
... # annotation is empty
"""
return len(self._tracks) > 0
def itersegments(self):
"""Iterate over segments (in chronological order)
>>> for segment in annotation.itersegments():
... # do something with the segment
See also
--------
:class:`pyannote.core.Segment` describes how segments are sorted.
"""
return iter(self._tracks)
def itertracks(
self, yield_label: bool = False
) -> Iterator[Union[Tuple[Segment, TrackName], Tuple[Segment, TrackName, Label]]]:
"""Iterate over tracks (in chronological order)
Parameters
----------
yield_label : bool, optional
When True, yield (segment, track, label) tuples, such that
annotation[segment, track] == label. Defaults to yielding
(segment, track) tuple.
Examples
--------
>>> for segment, track in annotation.itertracks():
... # do something with the track
>>> for segment, track, label in annotation.itertracks(yield_label=True):
... # do something with the track and its label
"""
for segment, tracks in self._tracks.items():
for track, lbl in sorted(
tracks.items(), key=lambda tl: (str(tl[0]), str(tl[1]))
):
if yield_label:
yield segment, track, lbl
else:
yield segment, track
def _updateTimeline(self):
self._timeline = Timeline(segments=self._tracks, uri=self.uri)
self._timelineNeedsUpdate = False
def get_timeline(self, copy: bool = True) -> Timeline:
"""Get timeline made of all annotated segments
Parameters
----------
copy : bool, optional
Defaults (True) to returning a copy of the internal timeline.
Set to False to return the actual internal timeline (faster).
Returns
-------
timeline : Timeline
Timeline made of all annotated segments.
Note
----
In case copy is set to False, be careful **not** to modify the returned
timeline, as it may lead to weird subsequent behavior of the annotation
instance.
"""
if self._timelineNeedsUpdate:
self._updateTimeline()
if copy:
return self._timeline.copy()
return self._timeline
def __eq__(self, other: "Annotation"):
"""Equality
>>> annotation == other
Two annotations are equal if and only if their tracks and associated
labels are equal.
"""
pairOfTracks = itertools.zip_longest(
self.itertracks(yield_label=True), other.itertracks(yield_label=True)
)
return all(t1 == t2 for t1, t2 in pairOfTracks)
def __ne__(self, other: "Annotation"):
"""Inequality"""
pairOfTracks = itertools.zip_longest(
self.itertracks(yield_label=True), other.itertracks(yield_label=True)
)
return any(t1 != t2 for t1, t2 in pairOfTracks)
def __contains__(self, included: Union[Segment, Timeline]):
"""Inclusion
Check whether every segment of `included` does exist in annotation.
Parameters
----------
included : Segment or Timeline
Segment or timeline being checked for inclusion
Returns
-------
contains : bool
True if every segment in `included` exists in timeline,
False otherwise
"""
return included in self.get_timeline(copy=False)
def _iter_rttm(self) -> Iterator[Text]:
"""Generate lines for an RTTM file for this annotation
Returns
-------
iterator: Iterator[str]
An iterator over RTTM text lines
"""
uri = self.uri if self.uri else "<NA>"
if isinstance(uri, Text) and " " in uri:
msg = (
f"Space-separated RTTM file format does not allow file URIs "
f'containing spaces (got: "{uri}").'
)
raise ValueError(msg)
for segment, _, label in self.itertracks(yield_label=True):
if isinstance(label, Text) and " " in label:
msg = (
f"Space-separated RTTM file format does not allow labels "
f'containing spaces (got: "{label}").'
)
raise ValueError(msg)
yield (
f"SPEAKER {uri} 1 {segment.start:.3f} {segment.duration:.3f} "
f"<NA> <NA> {label} <NA> <NA>\n"
)
def to_rttm(self) -> Text:
"""Serialize annotation as a string using RTTM format
Returns
-------
serialized: str
RTTM string
"""
return "".join([line for line in self._iter_rttm()])
def write_rttm(self, file: TextIO):
"""Dump annotation to file using RTTM format
Parameters
----------
file : file object
Usage
-----
>>> with open('file.rttm', 'w') as file:
... annotation.write_rttm(file)
"""
for line in self._iter_rttm():
file.write(line)
def _iter_lab(self) -> Iterator[Text]:
"""Generate lines for a LAB file for this annotation
Returns
-------
iterator: Iterator[str]
An iterator over LAB text lines
"""
for segment, _, label in self.itertracks(yield_label=True):
if isinstance(label, Text) and " " in label:
msg = (
f"Space-separated LAB file format does not allow labels "
f'containing spaces (got: "{label}").'
)
raise ValueError(msg)
yield f"{segment.start:.3f} {segment.start + segment.duration:.3f} {label}\n"
def to_lab(self) -> Text:
"""Serialize annotation as a string using LAB format
Returns
-------
serialized: str
LAB string
"""
return "".join([line for line in self._iter_lab()])
def write_lab(self, file: TextIO):
"""Dump annotation to file using LAB format
Parameters
----------
file : file object
Usage
-----
>>> with open('file.lab', 'w') as file:
... annotation.write_lab(file)
"""
for line in self._iter_lab():
file.write(line)
def crop(self, support: Support, mode: CropMode = "intersection") -> "Annotation":
"""Crop annotation to new support
Parameters
----------
support : Segment or Timeline
If `support` is a `Timeline`, its support is used.
mode : {'strict', 'loose', 'intersection'}, optional
Controls how segments that are not fully included in `support` are
handled. 'strict' mode only keeps fully included segments. 'loose'
mode keeps any intersecting segment. 'intersection' mode keeps any
intersecting segment but replace them by their actual intersection.
Returns
-------
cropped : Annotation
Cropped annotation
Note
----
In 'intersection' mode, the best is done to keep the track names
unchanged. However, in some cases where two original segments are
cropped into the same resulting segments, conflicting track names are
modified to make sure no track is lost.
"""
# TODO speed things up by working directly with annotation internals
if isinstance(support, Segment):
support = Timeline(segments=[support], uri=self.uri)
return self.crop(support, mode=mode)
elif isinstance(support, Timeline):
# if 'support' is a `Timeline`, we use its support
support = support.support()
cropped = self.__class__(uri=self.uri, modality=self.modality)
if mode == "loose":
_tracks = {}
_labels = set([])
for segment, _ in self.get_timeline(copy=False).co_iter(support):
tracks = dict(self._tracks[segment])
_tracks[segment] = tracks
_labels.update(tracks.values())
cropped._tracks = SortedDict(_tracks)
cropped._labelNeedsUpdate = {label: True for label in _labels}
cropped._labels = {label: None for label in _labels}
cropped._timelineNeedsUpdate = True
cropped._timeline = None
return cropped
elif mode == "strict":
_tracks = {}
_labels = set([])
for segment, other_segment in self.get_timeline(copy=False).co_iter(
support
):
if segment not in other_segment:
continue
tracks = dict(self._tracks[segment])
_tracks[segment] = tracks
_labels.update(tracks.values())
cropped._tracks = SortedDict(_tracks)
cropped._labelNeedsUpdate = {label: True for label in _labels}
cropped._labels = {label: None for label in _labels}
cropped._timelineNeedsUpdate = True
cropped._timeline = None
return cropped
elif mode == "intersection":
for segment, other_segment in self.get_timeline(copy=False).co_iter(
support
):
intersection = segment & other_segment
for track, label in self._tracks[segment].items():
track = cropped.new_track(intersection, candidate=track)
cropped[intersection, track] = label
return cropped
else:
raise NotImplementedError("unsupported mode: '%s'" % mode)
def extrude(
self, removed: Support, mode: CropMode = "intersection"
) -> "Annotation":
"""Remove segments that overlap `removed` support.
A simple illustration:
annotation
A |------| |------|
B |----------|
C |--------------| |------|
removed `Timeline`
|-------| |-----------|
extruded Annotation with mode="intersection"
B |---|
C |--| |------|
extruded Annotation with mode="loose"
C |------|
extruded Annotation with mode="strict"
A |------|
B |----------|
C |--------------| |------|
Parameters
----------
removed : Segment or Timeline
If `support` is a `Timeline`, its support is used.
mode : {'strict', 'loose', 'intersection'}, optional
Controls how segments that are not fully included in `removed` are
handled. 'strict' mode only removes fully included segments. 'loose'
mode removes any intersecting segment. 'intersection' mode removes
the overlapping part of any intersecting segment.
Returns
-------
extruded : Annotation
Extruded annotation
Note
----
In 'intersection' mode, the best is done to keep the track names
unchanged. However, in some cases where two original segments are
cropped into the same resulting segments, conflicting track names are
modified to make sure no track is lost.
"""
if isinstance(removed, Segment):
removed = Timeline([removed])
extent_tl = Timeline([self.get_timeline().extent()], uri=self.uri)
truncating_support = removed.gaps(support=extent_tl)
# loose for truncate means strict for crop and vice-versa
if mode == "loose":
mode = "strict"
elif mode == "strict":
mode = "loose"
return self.crop(truncating_support, mode=mode)
def get_overlap(self, labels: Optional[Iterable[Label]] = None) -> "Timeline":
"""Get overlapping parts of the annotation.
A simple illustration:
annotation
A |------| |------| |----|
B |--| |-----| |----------|
C |--------------| |------|
annotation.get_overlap()
|------| |-----| |--------|
annotation.get_overlap(for_labels=["A", "B"])
|--| |--| |----|
Parameters
----------
labels : optional list of labels
Labels for which to consider the overlap
Returns
-------
overlap : `pyannote.core.Timeline`
Timeline of the overlaps.
"""
if labels:
annotation = self.subset(labels)
else:
annotation = self
overlaps_tl = Timeline(uri=annotation.uri)
for (s1, t1), (s2, t2) in annotation.co_iter(annotation):
# if labels are the same for the two segments, skipping
if self[s1, t1] == self[s2, t2]:
continue
overlaps_tl.add(s1 & s2)
return overlaps_tl.support()
def get_tracks(self, segment: Segment) -> Set[TrackName]:
"""Query tracks by segment
Parameters
----------
segment : Segment
Query
Returns
-------
tracks : set
Set of tracks
Note
----
This will return an empty set if segment does not exist.
"""
return set(self._tracks.get(segment, {}).keys())
def has_track(self, segment: Segment, track: TrackName) -> bool:
"""Check whether a given track exists
Parameters
----------
segment : Segment
Query segment
track :
Query track
Returns
-------
exists : bool
True if track exists for segment
"""
return track in self._tracks.get(segment, {})
def copy(self) -> "Annotation":
"""Get a copy of the annotation
Returns
-------
annotation : Annotation
Copy of the annotation
"""
# create new empty annotation
copied = self.__class__(uri=self.uri, modality=self.modality)
# deep copy internal track dictionary
_tracks, _labels = [], set([])
for key, value in self._tracks.items():
_labels.update(value.values())
_tracks.append((key, dict(value)))
copied._tracks = SortedDict(_tracks)
copied._labels = {label: None for label in _labels}
copied._labelNeedsUpdate = {label: True for label in _labels}
copied._timeline = None
copied._timelineNeedsUpdate = True
return copied
def new_track(
self,
segment: Segment,
candidate: Optional[TrackName] = None,
prefix: Optional[str] = None,
) -> TrackName:
"""Generate a new track name for given segment
Ensures that the returned track name does not already
exist for the given segment.
Parameters
----------
segment : Segment
Segment for which a new track name is generated.
candidate : any valid track name, optional
When provided, try this candidate name first.
prefix : str, optional
Track name prefix. Defaults to the empty string ''.
Returns
-------
name : str
New track name
"""
# obtain list of existing tracks for segment
existing_tracks = set(self._tracks.get(segment, {}))
# if candidate is provided, check whether it already exists
# in case it does not, use it
if (candidate is not None) and (candidate not in existing_tracks):
return candidate
# no candidate was provided or the provided candidate already exists
# we need to create a brand new one
# by default (if prefix is not provided), use ''
if prefix is None:
prefix = ""
# find first non-existing track name for segment
# eg. if '0' exists, try '1', then '2', ...
count = 0
while ("%s%d" % (prefix, count)) in existing_tracks:
count += 1
# return first non-existing track name
return "%s%d" % (prefix, count)
def __str__(self):
"""Human-friendly representation"""
# TODO: use pandas.DataFrame
return "\n".join(
["%s %s %s" % (s, t, l) for s, t, l in self.itertracks(yield_label=True)]
)
def __delitem__(self, key: Key):
"""Delete one track
>>> del annotation[segment, track]
Delete all tracks of a segment
>>> del annotation[segment]
"""
# del annotation[segment]
if isinstance(key, Segment):
# Pop segment out of dictionary
# and get corresponding tracks
# Raises KeyError if segment does not exist
tracks = self._tracks.pop(key)
# mark timeline as modified
self._timelineNeedsUpdate = True
# mark every label in tracks as modified
for track, label in tracks.items():
self._labelNeedsUpdate[label] = True
# del annotation[segment, track]
elif isinstance(key, tuple) and len(key) == 2:
# get segment tracks as dictionary
# if segment does not exist, get empty dictionary
# Raises KeyError if segment does not exist
tracks = self._tracks[key[0]]
# pop track out of tracks dictionary
# and get corresponding label
# Raises KeyError if track does not exist
label = tracks.pop(key[1])
# mark label as modified
self._labelNeedsUpdate[label] = True
# if tracks dictionary is now empty,
# remove segment as well
if not tracks:
self._tracks.pop(key[0])
self._timelineNeedsUpdate = True
else:
raise NotImplementedError(
"Deletion only works with Segment or (Segment, track) keys."
)
# label = annotation[segment, track]
def __getitem__(self, key: Key) -> Label:
"""Get track label
>>> label = annotation[segment, track]
Note
----
``annotation[segment]`` is equivalent to ``annotation[segment, '_']``
"""
if isinstance(key, Segment):
key = (key, "_")
return self._tracks[key[0]][key[1]]
# annotation[segment, track] = label
def __setitem__(self, key: Key, label: Label):
"""Add new or update existing track
>>> annotation[segment, track] = label
If (segment, track) does not exist, it is added.
If (segment, track) already exists, it is updated.
Note
----
``annotation[segment] = label`` is equivalent to ``annotation[segment, '_'] = label``
Note
----
If `segment` is empty, it does nothing.
"""
if isinstance(key, Segment):
key = (key, "_")
segment, track = key
# do not add empty track
if not segment:
return
# in case we create a new segment
# mark timeline as modified
if segment not in self._tracks:
self._tracks[segment] = {}
self._timelineNeedsUpdate = True
# in case we modify an existing track
# mark old label as modified
if track in self._tracks[segment]:
old_label = self._tracks[segment][track]
self._labelNeedsUpdate[old_label] = True
# mark new label as modified
self._tracks[segment][track] = label
self._labelNeedsUpdate[label] = True
def empty(self) -> "Annotation":
"""Return an empty copy
Returns
-------
empty : Annotation
Empty annotation using the same 'uri' and 'modality' attributes.
"""
return self.__class__(uri=self.uri, modality=self.modality)
def labels(self) -> List[Label]:
"""Get sorted list of labels
Returns
-------
labels : list
Sorted list of labels
"""
if any([lnu for lnu in self._labelNeedsUpdate.values()]):
self._updateLabels()
return sorted(self._labels, key=str)
def get_labels(
self, segment: Segment, unique: bool = True
) -> Union[Set[Label], List[Label]]:
"""Query labels by segment
Parameters
----------
segment : Segment
Query
unique : bool, optional
When False, return the list of (possibly repeated) labels.
Defaults to returning the set of labels.
Returns
-------
labels : set or list
Set (resp. list) of labels for `segment` if it exists, empty set (resp. list) otherwise
if unique (resp. if not unique).
Examples
--------
>>> annotation = Annotation()
>>> segment = Segment(0, 2)
>>> annotation[segment, 'speaker1'] = 'Bernard'
>>> annotation[segment, 'speaker2'] = 'John'
>>> print sorted(annotation.get_labels(segment))
set(['Bernard', 'John'])
>>> print annotation.get_labels(Segment(1, 2))
set([])
"""
labels = self._tracks.get(segment, {}).values()
if unique:
return set(labels)
return list(labels)
def subset(self, labels: Iterable[Label], invert: bool = False) -> "Annotation":
"""Filter annotation by labels
Parameters
----------
labels : iterable
List of filtered labels
invert : bool, optional
If invert is True, extract all but requested labels
Returns
-------
filtered : Annotation
Filtered annotation
"""
labels = set(labels)
if invert:
labels = set(self.labels()) - labels
else:
labels = labels & set(self.labels())
sub = self.__class__(uri=self.uri, modality=self.modality)
_tracks, _labels = {}, set([])
for segment, tracks in self._tracks.items():
sub_tracks = {
track: label for track, label in tracks.items() if label in labels
}
if sub_tracks:
_tracks[segment] = sub_tracks
_labels.update(sub_tracks.values())
sub._tracks = SortedDict(_tracks)
sub._labelNeedsUpdate = {label: True for label in _labels}
sub._labels = {label: None for label in _labels}
sub._timelineNeedsUpdate = True
sub._timeline = None
return sub
def update(self, annotation: "Annotation", copy: bool = False) -> "Annotation":
"""Add every track of an existing annotation (in place)
Parameters
----------
annotation : Annotation
Annotation whose tracks are being added
copy : bool, optional
Return a copy of the annotation. Defaults to updating the
annotation in-place.
Returns
-------
self : Annotation
Updated annotation
Note
----
Existing tracks are updated with the new label.
"""
result = self.copy() if copy else self
# TODO speed things up by working directly with annotation internals
for segment, track, label in annotation.itertracks(yield_label=True):
result[segment, track] = label
return result
def label_timeline(self, label: Label, copy: bool = True) -> Timeline:
"""Query segments by label
Parameters
----------
label : object
Query
copy : bool, optional
Defaults (True) to returning a copy of the internal timeline.
Set to False to return the actual internal timeline (faster).
Returns
-------
timeline : Timeline
Timeline made of all segments for which at least one track is
annotated as label
Note
----
If label does not exist, this will return an empty timeline.
Note
----
In case copy is set to False, be careful **not** to modify the returned
timeline, as it may lead to weird subsequent behavior of the annotation
instance.
"""
if label not in self.labels():
return Timeline(uri=self.uri)
if self._labelNeedsUpdate[label]:
self._updateLabels()
if copy:
return self._labels[label].copy()
return self._labels[label]
def label_support(self, label: Label) -> Timeline:
"""Label support
Equivalent to ``Annotation.label_timeline(label).support()``
Parameters
----------
label : object
Query
Returns
-------
support : Timeline
Label support
See also
--------
:func:`~pyannote.core.Annotation.label_timeline`
:func:`~pyannote.core.Timeline.support`
"""
return self.label_timeline(label, copy=False).support()
def label_duration(self, label: Label) -> float:
"""Label duration
Equivalent to ``Annotation.label_timeline(label).duration()``
Parameters
----------
label : object
Query
Returns
-------
duration : float
Duration, in seconds.
See also
--------
:func:`~pyannote.core.Annotation.label_timeline`
:func:`~pyannote.core.Timeline.duration`
"""
return self.label_timeline(label, copy=False).duration()
def chart(self, percent: bool = False) -> List[Tuple[Label, float]]:
"""Get labels chart (from longest to shortest duration)
Parameters
----------
percent : bool, optional
Return list of (label, percentage) tuples.
Defaults to returning list of (label, duration) tuples.
Returns
-------
chart : list
List of (label, duration), sorted by duration in decreasing order.
"""
chart = sorted(
((L, self.label_duration(L)) for L in self.labels()),
key=lambda x: x[1],
reverse=True,
)
if percent:
total = np.sum([duration for _, duration in chart])
chart = [(label, duration / total) for (label, duration) in chart]
return chart
def argmax(self, support: Optional[Support] = None) -> Optional[Label]:
"""Get label with longest duration
Parameters
----------
support : Segment or Timeline, optional
Find label with longest duration within provided support.
Defaults to whole extent.
Returns
-------
label : any existing label or None
Label with longest intersection
Examples
--------
>>> annotation = Annotation(modality='speaker')
>>> annotation[Segment(0, 10), 'speaker1'] = 'Alice'
>>> annotation[Segment(8, 20), 'speaker1'] = 'Bob'
>>> print "%s is such a talker!" % annotation.argmax()
Bob is such a talker!
>>> segment = Segment(22, 23)
>>> if not annotation.argmax(support):
... print "No label intersecting %s" % segment
No label intersection [22 --> 23]
"""
cropped = self
if support is not None:
cropped = cropped.crop(support, mode="intersection")
if not cropped:
return None
return max(
((_, cropped.label_duration(_)) for _ in cropped.labels()),
key=lambda x: x[1],
)[0]
def rename_tracks(self, generator: LabelGenerator = "string") -> "Annotation":
"""Rename all tracks
Parameters
----------
generator : 'string', 'int', or iterable, optional
If 'string' (default) rename tracks to 'A', 'B', 'C', etc.
If 'int', rename tracks to 0, 1, 2, etc.
If iterable, use it to generate track names.
Returns
-------
renamed : Annotation
Copy of the original annotation where tracks are renamed.
Example
-------
>>> annotation = Annotation()
>>> annotation[Segment(0, 1), 'a'] = 'a'
>>> annotation[Segment(0, 1), 'b'] = 'b'
>>> annotation[Segment(1, 2), 'a'] = 'a'
>>> annotation[Segment(1, 3), 'c'] = 'c'
>>> print(annotation)
[ 00:00:00.000 --> 00:00:01.000] a a
[ 00:00:00.000 --> 00:00:01.000] b b
[ 00:00:01.000 --> 00:00:02.000] a a
[ 00:00:01.000 --> 00:00:03.000] c c
>>> print(annotation.rename_tracks(generator='int'))
[ 00:00:00.000 --> 00:00:01.000] 0 a
[ 00:00:00.000 --> 00:00:01.000] 1 b
[ 00:00:01.000 --> 00:00:02.000] 2 a
[ 00:00:01.000 --> 00:00:03.000] 3 c
"""
renamed = self.__class__(uri=self.uri, modality=self.modality)
if generator == "string":
generator = string_generator()
elif generator == "int":
generator = int_generator()
# TODO speed things up by working directly with annotation internals
for s, _, label in self.itertracks(yield_label=True):
renamed[s, next(generator)] = label
return renamed
def rename_labels(
self,
mapping: Optional[Dict] = None,
generator: LabelGenerator = "string",
copy: bool = True,
) -> "Annotation":
"""Rename labels
Parameters
----------
mapping : dict, optional
{old_name: new_name} mapping dictionary.
generator : 'string', 'int' or iterable, optional
If 'string' (default) rename label to 'A', 'B', 'C', ... If 'int',
rename to 0, 1, 2, etc. If iterable, use it to generate labels.
copy : bool, optional
Set to True to return a copy of the annotation. Set to False to
update the annotation in-place. Defaults to True.
Returns
-------
renamed : Annotation
Annotation where labels have been renamed
Note
----
Unmapped labels are kept unchanged.
Note
----
Parameter `generator` has no effect when `mapping` is provided.
"""
if mapping is None:
if generator == "string":
generator = string_generator()
elif generator == "int":
generator = int_generator()
# generate mapping
mapping = {label: next(generator) for label in self.labels()}
renamed = self.copy() if copy else self
for old_label, new_label in mapping.items():
renamed._labelNeedsUpdate[old_label] = True
renamed._labelNeedsUpdate[new_label] = True
for segment, tracks in self._tracks.items():
new_tracks = {
track: mapping.get(label, label) for track, label in tracks.items()
}
renamed._tracks[segment] = new_tracks
return renamed
def relabel_tracks(self, generator: LabelGenerator = "string") -> "Annotation":
"""Relabel tracks
Create a new annotation where each track has a unique label.
Parameters
----------
generator : 'string', 'int' or iterable, optional
If 'string' (default) relabel tracks to 'A', 'B', 'C', ... If 'int'
relabel to 0, 1, 2, ... If iterable, use it to generate labels.
Returns
-------
renamed : Annotation
New annotation with relabeled tracks.
"""
if generator == "string":
generator = string_generator()
elif generator == "int":
generator = int_generator()
relabeled = self.empty()
for s, t, _ in self.itertracks(yield_label=True):
relabeled[s, t] = next(generator)
return relabeled
def support(self, collar: float = 0.0) -> "Annotation":
"""Annotation support
The support of an annotation is an annotation where contiguous tracks
with same label are merged into one unique covering track.
A picture is worth a thousand words::
collar
|---|
annotation
|--A--| |--A--| |-B-|
|-B-| |--C--| |----B-----|
annotation.support(collar)
|------A------| |------B------|
|-B-| |--C--|
Parameters
----------
collar : float, optional
Merge tracks with same label and separated by less than `collar`
seconds. This is why 'A' tracks are merged in above figure.
Defaults to 0.
Returns
-------
support : Annotation
Annotation support
Note
----
Track names are lost in the process.
"""
generator = string_generator()
# initialize an empty annotation
# with same uri and modality as original
support = self.empty()
for label in self.labels():
# get timeline for current label
timeline = self.label_timeline(label, copy=True)
# fill the gaps shorter than collar
timeline = timeline.support(collar)
# reconstruct annotation with merged tracks
for segment in timeline.support():
support[segment, next(generator)] = label
return support
def co_iter(
self, other: "Annotation"
) -> Iterator[Tuple[Tuple[Segment, TrackName], Tuple[Segment, TrackName]]]:
"""Iterate over pairs of intersecting tracks
Parameters
----------
other : Annotation
Second annotation
Returns
-------
iterable : (Segment, object), (Segment, object) iterable
Yields pairs of intersecting tracks, in chronological (then
alphabetical) order.
See also
--------
:func:`~pyannote.core.Timeline.co_iter`
"""
timeline = self.get_timeline(copy=False)
other_timeline = other.get_timeline(copy=False)
for s, S in timeline.co_iter(other_timeline):
tracks = sorted(self.get_tracks(s), key=str)
other_tracks = sorted(other.get_tracks(S), key=str)
for t, T in itertools.product(tracks, other_tracks):
yield (s, t), (S, T)
def __mul__(self, other: "Annotation") -> np.ndarray:
"""Cooccurrence (or confusion) matrix
>>> matrix = annotation * other
Parameters
----------
other : Annotation
Second annotation
Returns
-------
cooccurrence : (n_self, n_other) np.ndarray
Cooccurrence matrix where `n_self` (resp. `n_other`) is the number
of labels in `self` (resp. `other`).
"""
if not isinstance(other, Annotation):
raise TypeError(
"computing cooccurrence matrix only works with Annotation " "instances."
)
i_labels = self.labels()
j_labels = other.labels()
I = {label: i for i, label in enumerate(i_labels)}
J = {label: j for j, label in enumerate(j_labels)}
matrix = np.zeros((len(I), len(J)))
# iterate over intersecting tracks and accumulate durations
for (segment, track), (other_segment, other_track) in self.co_iter(other):
i = I[self[segment, track]]
j = J[other[other_segment, other_track]]
duration = (segment & other_segment).duration
matrix[i, j] += duration
return matrix
def discretize(
self,
support: Optional[Segment] = None,
resolution: Union[float, SlidingWindow] = 0.01,
labels: Optional[List[Hashable]] = None,
duration: Optional[float] = None,
):
"""Discretize
Parameters
----------
support : Segment, optional
Part of annotation to discretize.
Defaults to annotation full extent.
resolution : float or SlidingWindow, optional
Defaults to 10ms frames.
labels : list of labels, optional
Defaults to self.labels()
duration : float, optional
Overrides support duration and ensures that the number of
returned frames is fixed (which might otherwise not be the case
because of rounding errors).
Returns
-------
discretized : SlidingWindowFeature
(num_frames, num_labels)-shaped binary features.
"""
if support is None:
support = self.get_timeline().extent()
start_time, end_time = support
cropped = self.crop(support, mode="intersection")
if labels is None:
labels = cropped.labels()
if isinstance(resolution, SlidingWindow):
resolution = SlidingWindow(
start=start_time, step=resolution.step, duration=resolution.duration
)
else:
resolution = SlidingWindow(
start=start_time, step=resolution, duration=resolution
)
start_frame = resolution.closest_frame(start_time)
if duration is None:
end_frame = resolution.closest_frame(end_time)
num_frames = end_frame - start_frame
else:
num_frames = int(round(duration / resolution.step))
data = np.zeros((num_frames, len(labels)), dtype=np.uint8)
for k, label in enumerate(labels):
segments = cropped.label_timeline(label)
for start, stop in resolution.crop(
segments, mode="center", return_ranges=True
):
data[max(0, start) : min(stop, num_frames), k] += 1
data = np.minimum(data, 1, out=data)
return SlidingWindowFeature(data, resolution, labels=labels)
@classmethod
def from_records(
cls,
records: Iterator[Tuple[Segment, TrackName, Label]],
uri: Optional[str] = None,
modality: Optional[str] = None,
) -> "Annotation":
"""Annotation
Parameters
----------
records : iterator of tuples
(segment, track, label) tuples
uri : string, optional
name of annotated resource (e.g. audio or video file)
modality : string, optional
name of annotated modality
Returns
-------
annotation : Annotation
New annotation
"""
annotation = cls(uri=uri, modality=modality)
tracks = defaultdict(dict)
labels = set()
for segment, track, label in records:
tracks[segment][track] = label
labels.add(label)
annotation._tracks = SortedDict(tracks)
annotation._labels = {label: None for label in labels}
annotation._labelNeedsUpdate = {label: True for label in annotation._labels}
annotation._timeline = None
annotation._timelineNeedsUpdate = True
return annotation
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_annotation
return repr_annotation(self)
|