def nest_annotations(annotations: Iterator[Annotation],
text_length: int) -> List[NestableAnnotation]:
"""Converts overlapping annotations into a nested version."""
in_order = sorted(annotations, key=lambda a: (a.start, -a.end))
# Easier to operate on a single root, even if we'll remove it later.
root = last = NestableAnnotation(PlainText(start=0, end=text_length), None)
for anote in in_order:
# We're not allowing non-nested overlapping annotations, so we won't
# compare ends when determining nesting
while anote not in last:
last = last.parent
# Enforce all annotations to be nested rather than overlapping
anote.end = min(anote.end, last.end)
last = NestableAnnotation(anote, last)
root.wrap_unwrapped()
return root.children
评论列表
文章目录