ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
Documentation
//! [`DocumentSegment<T>`](DocumentSegment): a four-cornered region a detector found, and how sure it
//! was.

use core::fmt;

use crate::{
  ColumnEq, ColumnKind, ColumnName, ColumnShape, CompositeFilterMarker, CompositeMarker,
  ConfidenceFilter, DefaultMarker, DefaultVecMarker, FieldName, PayloadFilter, Quad, QuadFilter,
  QuantifiedMarker, Score, shape,
};

use super::detection::CONFIDENCE;

#[cfg(test)]
mod tests;

/// **One leaf, and it is the value** — a segment means its columns in the sequence it declares them.
///
/// It is the ONE citizen of the payload trio that keeps the non-reordering word, and the reason is
/// the shape it holds rather than a decision: a [`Quad<T>`] is four positions and a position is two
/// components, so nothing beneath this type derives anything. Its two siblings hold a
/// [`BoundingBox<T>`](crate::BoundingBox), which does — see
/// [`TextDetection<T>`](super::TextDetection)'s own `ORDER`, where the obligation a holder inherits
/// is stated.
impl<T> crate::DeclaredLeaves for DocumentSegment<T> {}

/// **A FOUR-CORNERED REGION**, with the detector's confidence in it.
///
/// ```text
///   ●──────────────●        the page, photographed at an angle
///    ╲              ╲       confidence: 0.97
///     ●──────────────●
/// ```
///
/// # THE QUAD IS THE SHAPE, and a rectangle would have been a different claim
///
/// A page, a whiteboard or a receipt seen off-axis is a quadrilateral; the axis-aligned box AROUND
/// one is a coarser fact that loses the angle. So this type holds a [`Quad<T>`] and the box is a
/// READING a caller spells — [`Quad::bounds`](crate::Quad::bounds), which arrived with this cluster
/// — rather than a fifth through eighth column that an `UPDATE` could put out of step with the
/// corners.
///
/// The corners are in PERIMETER WINDING ORDER, which is the geometry house's convention and the
/// producers' own: reading them as `(TL, TR, BL, BR)` builds a bow-tie out of every real document.
/// See [`Quad<T>`], where the order is argued and pinned.
///
/// # THERE IS NO LABEL, and the absence is the subject's
///
/// A segment detector answers *there is a four-cornered thing here*. WHAT it is — a page, a
/// whiteboard, a card — is a classifier's answer with its own vocabulary and its own confidence, and
/// a caller that has one pairs this with a [`Detection`](super::Detection) rather than folding a
/// label into a shape. That is the same division [`LocatedDetection<T>`](super::LocatedDetection)
/// draws from the other side.
///
/// The name is the CONTRACT's: `avanalyze` calls this observation a document segment, and the word
/// travels with the shape rather than being renamed at the border.
///
/// # Examples
///
/// ```
/// use ingraph::{DocumentSegment, Point2, Quad, Score};
///
/// let page = DocumentSegment::new(
///   Quad::try_unit((0.10, 0.12), (0.90, 0.10), (0.92, 0.88), (0.08, 0.90)).unwrap(),
///   Score::new(0.97).unwrap(),
/// );
///
/// assert_eq!(page.confidence().get(), 0.97);
/// assert_eq!(page.quad().top_left(), Point2::try_unit(0.10, 0.12).unwrap());
/// ```
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct DocumentSegment<T> {
  pub(super) quad: Quad<T>,
  pub(super) confidence: Score,
}

impl<T> DocumentSegment<T> {
  /// A four-cornered region at a confidence.
  ///
  /// INFALLIBLE and `const`, because both halves have been through their own doors: a [`Score`]
  /// cannot exist outside `[0.0, 1.0]`, and whatever rules the quad has are its component's and its
  /// own instantiation's.
  #[inline]
  #[must_use]
  pub const fn new(quad: Quad<T>, confidence: Score) -> Self {
    Self { quad, confidence }
  }

  /// The four corners, in winding order.
  #[inline]
  #[must_use]
  pub const fn quad(&self) -> &Quad<T> {
    &self.quad
  }

  /// How sure the detector was, in `[0.0, 1.0]`.
  #[inline]
  #[must_use]
  pub const fn confidence(&self) -> Score {
    self.confidence
  }
}

impl<T: fmt::Debug> fmt::Debug for DocumentSegment<T> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("DocumentSegment")
      .field("quad", &self.quad)
      .field("confidence", &self.confidence.get())
      .finish()
  }
}

/// The four-cornered region's segment.
pub(super) const QUAD: &FieldName = FieldName::new("quad");

/// **The NINE columns a segment spans**: the quad's eight under its own name, then the confidence.
///
/// The quad KEEPS its name for [`LocatedDetection<T>`](super::LocatedDetection)'s reason at a deeper
/// fan: its own segments are four CORNERS of two components each, so a splice would put eight
/// coordinate names into this holder's namespace beside a `confidence`. A segment at `page` reaches
/// `page_quad_top_left_x` and its seven siblings, and `page_confidence`.
///
/// **Every one of the nine holds the value**, which is what makes this citizen the trio's simple one
/// — see the [`DeclaredLeaves`](crate::DeclaredLeaves) row at the top of this file.
impl<T: ColumnKind> ColumnKind for DocumentSegment<T> {
  const SEGMENTS: &'static [ColumnShape] = &[
    shape::<Quad<T>>(ColumnName::of(QUAD)),
    ColumnShape::Plain(ColumnName::of(CONFIDENCE)),
  ];
}

/// A segment is one column value when its four corners and its confidence all are — every one of
/// the nine holds the value, so the fold is the whole of the row.
impl<T: ColumnEq> ColumnEq for DocumentSegment<T> {
  #[inline]
  fn column_eq(&self, other: &Self) -> bool {
    self.quad().column_eq(other.quad()) && self.confidence().column_eq(&other.confidence())
  }
}

/// **The DECLARED half — NINE words**, the quad's eight read off its own row and the confidence's
/// beside them.
impl<Db, T> crate::StoredAs<Db> for DocumentSegment<T>
where
  Quad<T>: crate::StoredAs<Db>,
  Score: crate::StoredAs<Db>,
{
  const WORDS: &'static [&'static str] = &[
    <Quad<T> as crate::StoredAs<Db>>::WORDS[0],
    <Quad<T> as crate::StoredAs<Db>>::WORDS[1],
    <Quad<T> as crate::StoredAs<Db>>::WORDS[2],
    <Quad<T> as crate::StoredAs<Db>>::WORDS[3],
    <Quad<T> as crate::StoredAs<Db>>::WORDS[4],
    <Quad<T> as crate::StoredAs<Db>>::WORDS[5],
    <Quad<T> as crate::StoredAs<Db>>::WORDS[6],
    <Quad<T> as crate::StoredAs<Db>>::WORDS[7],
    <Score as crate::StoredAs<Db>>::WORDS[0],
  ];
}

/// **THE ADMISSION**, DELEGATED to the geometry half: a scan with several pages on it is
/// `Vec<DocumentSegment<NormCoord>>`.
impl<T: crate::CollectionElement> crate::CollectionElement for DocumentSegment<T> {}

/// **NINE BINDS OUT** — the quad's eight, then the confidence, with the one comma this level owns
/// between them.
///
/// [`push_value_bind`](crate::Carrier::push_value_bind) takes its DEFAULT, and that is the whole of
/// what having no derived leaf buys: the two faces are the same nine placeholders, so there is
/// nothing here for the pairing to get wrong.
#[cfg(feature = "sqlx")]
impl<Db, T> crate::Carrier<Db> for DocumentSegment<T>
where
  Db: sqlx::Database,
  Quad<T>: crate::Carrier<Db>,
  Score: crate::Carrier<Db>,
{
  fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
    <Quad<T> as crate::Carrier<Db>>::push_bind(&self.quad, qb);
    qb.push(", ");
    <Score as crate::Carrier<Db>>::push_bind(&self.confidence, qb);
  }
}

/// **AND THE NINE BACK IN**, by name.
#[cfg(feature = "sqlx")]
impl<'a, R, T> crate::Assemble<'a, R> for DocumentSegment<T>
where
  R: sqlx::Row,
  Quad<T>: crate::Assemble<'a, R>,
  Score: crate::Assemble<'a, R>,
{
  fn assemble(row: &'a R, under: Option<&crate::Path<'_>>) -> sqlx::Result<Self> {
    let quad: Quad<T> = crate::assembled(row, QUAD, under)?;
    let confidence: Score = crate::assembled(row, CONFIDENCE, under)?;

    Ok(Self::new(quad, confidence))
  }
}

/// **THE KEYSET POSITION** — the quad, then the confidence, each behind its own four-byte length.
///
/// The framing is the framework's [`write_member`](crate::cursor::write_member) pair rather than a
/// division by constants, and here the reason is the GENERIC half rather than a variable-width one:
/// a quad's own row divides its payload by eight, so the split point this level would need is the
/// component's width times eight — a number no constant here can name. Four bytes a member buys a
/// read that refuses a frame this type did not write.
impl<T: crate::CursorValue> crate::CursorValue for DocumentSegment<T> {
  fn write_cursor(&self, out: &mut Vec<u8>) {
    crate::cursor::write_member(&self.quad, out);
    crate::cursor::write_member(&self.confidence, out);
  }

  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    let mut rest = bytes;
    let quad = crate::cursor::read_member::<Quad<T>>(&mut rest)?;
    let confidence = crate::cursor::read_member::<Score>(&mut rest)?;

    rest.is_empty().then(|| Self::new(quad, confidence))
  }
}

/// What guards a [`DocumentSegment<T>`] column — its own filter at both seats.
impl<T> CompositeFilterMarker for DocumentSegment<T>
where
  T: DefaultMarker,
{
  type Filter = DocumentSegmentFilter<PayloadFilter<T>>;
  type ColumnFilter = DocumentSegmentFilter<PayloadFilter<T>>;
}

/// The interpretation a [`DocumentSegment<T>`] field is read under — the COMPOSITE reading.
impl<T: DefaultMarker> DefaultMarker for DocumentSegment<T> {
  type Marker = CompositeMarker<DocumentSegment<T>>;
}

/// **A COLLECTION of segments is asked through the QUANTIFIERS alone** — the house's ruling,
/// inherited along with the float that makes it.
impl<T: DefaultMarker> DefaultVecMarker for DocumentSegment<T> {
  type Marker = QuantifiedMarker<Vec<DocumentSegment<T>>>;
}

/// The filter that guards a [`DocumentSegment<T>`] column: the four corners, and the confidence.
///
/// ```text
/// input DocumentSegmentF32Filter {
///   quad: QuadF32Filter  confidence: ConfidenceFilter
/// }
/// ```
///
/// # The quad does NOT flatten, and the corner facets are the geometry house's own
///
/// Its eight component names live two descents down — `quad: { topLeft: { x: { gte: … } } }` — which
/// is the same nesting the columns take and the same recursion
/// [`QuadFilter`](crate::QuadFilter) already publishes. A splice would put four corner names beside
/// a `confidence` and buy nothing.
///
/// # NO WHOLE-SEGMENT OPERATOR, and NO `area` FACET EITHER
///
/// The first is the house's shared refusal: the leaf tuple IS the conjunction of the facets, a
/// whole-value `ne` over a composite is a disjunction, and a per-column `in` is the cartesian
/// product. The second is a RECORDED GAP rather than a refusal, and it is the one place this citizen
/// is poorer than its two siblings: they hold a [`BoundingBox<T>`](crate::BoundingBox), which stores
/// its own derived area, and a quad stores none. *How much of the page is this segment* would need
/// either the shoelace area as a ninth column or the tight box's as a tenth, and neither is invented
/// ahead of a caller — the reading exists today as [`Quad::bounds`](crate::Quad::bounds) applied by
/// whoever wants it.
pub struct DocumentSegmentFilter<CF> {
  pub(super) quad: Option<QuadFilter<CF>>,
  pub(super) confidence: Option<ConfidenceFilter>,
}

impl<CF> DocumentSegmentFilter<CF> {
  /// The empty filter — no facet set, so a column guarded by it is unconstrained.
  #[inline]
  #[must_use]
  pub const fn new() -> Self {
    Self {
      quad: None,
      confidence: None,
    }
  }

  crate::graphql::filter::opt_accessor!(
    quad: QuadFilter<CF> => with_quad, set_quad, maybe_quad, update_quad
  );
  crate::graphql::filter::opt_accessor!(
    confidence: ConfidenceFilter => with_confidence, set_confidence, maybe_confidence, update_confidence
  );
}

impl<CF: crate::GraphqlFilter> DocumentSegmentFilter<CF> {
  /// True while NO operator slot is set on EITHER facet.
  pub fn is_empty(&self) -> bool {
    self
      .quad
      .as_ref()
      .is_none_or(crate::GraphqlFilter::is_empty)
      && self
        .confidence
        .as_ref()
        .is_none_or(ConfidenceFilter::is_empty)
  }
}

impl<CF: crate::GraphqlFilter> crate::GraphqlFilter for DocumentSegmentFilter<CF> {
  #[inline]
  fn is_empty(&self) -> bool {
    Self::is_empty(self)
  }
}

impl<CF> Default for DocumentSegmentFilter<CF> {
  #[inline]
  fn default() -> Self {
    Self::new()
  }
}

impl<CF: fmt::Debug> fmt::Debug for DocumentSegmentFilter<CF> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("DocumentSegmentFilter")
      .field("quad", &self.quad)
      .field("confidence", &self.confidence)
      .finish()
  }
}

impl<CF: Clone> Clone for DocumentSegmentFilter<CF> {
  fn clone(&self) -> Self {
    Self {
      quad: self.quad.clone(),
      confidence: self.confidence.clone(),
    }
  }
}

impl<CF: PartialEq> PartialEq for DocumentSegmentFilter<CF> {
  fn eq(&self, other: &Self) -> bool {
    self.quad == other.quad && self.confidence == other.confidence
  }
}