def callout_info_for_entities()

in web-app-pix2info-python/src/backend/render.py [0:0]


def callout_info_for_entities(demo: Demo) -> Iterator[CalloutInfoBase]:
    def flatten(
        entities: Iterable[Entity],
        parent_page_ref: Document.PageAnchor.PageRef | None = None,
    ) -> Iterator[Entity]:
        page_index = demo.options.page - 1
        for entity in entities:
            render, page_ref = will_render_entity(entity, parent_page_ref, page_index)
            if render:
                yield entity
            if entity.properties:
                yield from flatten(entity.properties, page_ref)

    def reading_order_key_for_entity(entity: Entity) -> TextAnchorKey:
        return reading_order_key_for_text_anchor(entity.text_anchor, default_text_index)

    def entity_vertices_gen() -> Iterator[tuple[Entity, Vertices | None]]:
        page_index = demo.options.page - 1
        for entity in entities:
            if not entity.page_anchor.page_refs:
                yield entity, None
                continue
            for page_ref in entity.page_anchor.page_refs:
                if page_ref.page != page_index:
                    continue
                if page_ref.bounding_poly.normalized_vertices:
                    vertices = vertices_from_bounding_poly(demo, page_ref.bounding_poly)
                else:
                    vertices = None
                yield entity, vertices

    default_text_index = len(demo.document.text)  # Place entities with no anchor last
    entities = sorted(flatten(demo.document.entities), key=reading_order_key_for_entity)

    for entity, vertices in entity_vertices_gen():
        entity_text, normalized = text_for_entity(demo, entity)
        caption = entity.type_
        if normalized:
            caption += "(n)"
        confidence = entity.confidence if "confidence" in entity else None
        if confidence is not None and not confident_enough(confidence):
            caption += f"[{confidence:.0%}]"
        text = f"{caption}: {entity_text}"

        yield vertices, text, confidence