pyannote-core icon indicating copy to clipboard operation
pyannote-core copied to clipboard

Typing of core classes

Open simonottenhauskenbun opened this issue 1 year ago • 1 comments

This PR should make working with Annotation easier for those using type checkers.

In my own project I neede to wrap Annotation with another class and add ugly type-checked code like this:

class Diarization:
... 
    @classmethod
    def labeled_tracks(cls, diarization: Annotation) -> List[Tuple[Segment, TrackName, Label]]:
       return list(diarization.itertracks(yield_label=True))  # type: ignore

Now typed versions of yield_label=True and yield_label=False exist. Type checkers do not allow to "set the type" by parameter value.

Details

  • fix type erros in pyannote.core.feature.py
  • fix type erros in pyannote.core.utils.types.py
  • Add named tuples SegmentTrack and SegmentTrackLabel as return types for itertracks in annotation.py

Notes on NamedTuples

SegmentTrack(NamedTuple) and SegmentTrackLabel(NamedTuple) are fully compatible with Tuple[Segment, TrackName]andTuple[Segment, TrackName, Label], i.e. they can be deconstructed via a,b,c = ...and accessed withtup[0], tup[1]In addition the fields can be accessed via dot-notation. This also works type-checked for the union type ofSegmentTrackandSegmentTrackLabel` for the common fields.

class SegmentTrack(NamedTuple):
    segment: Segment
    track: TrackName

class SegmentTrackLabel(NamedTuple):
    segment: Segment
    track: TrackName
    label: Label

s1 = SegmentTrack(...)
s2 = SegmentTrackLabel(...)

segment, track = s1 # OK!
segment, track, label = s2 # OK!

some_s: Union[SegmentTrack, SegmentTrackLabel] = s1 # or s2
print(some_s.segment) # OK!
print(some_s.track) # OK!

simonottenhauskenbun avatar Apr 05 '24 14:04 simonottenhauskenbun

FYI -- a bit busy right now but I did notice this PR.

I think pyannote.core API needs some love anyway and should probably be simplified...

hbredin avatar Apr 18 '24 07:04 hbredin