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
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
//! [`TextDetection<T>`](TextDetection): words that were READ out of a region of the frame.

use core::fmt;

use smol_bytes::Utf8Bytes;

use crate::{
  BoundingBox, BoundingBoxFilter, BoundingBoxLeaf, ColumnEq, ColumnKind, ColumnName, ColumnShape,
  CompositeFilterMarker, CompositeMarker, ConfidenceFilter, DefaultMarker, DefaultVecMarker,
  FieldName, OrderLevel, PayloadFilter, QuantifiedMarker, Score, TextFilter, shape,
};

use super::{detection::CONFIDENCE, located::BBOX};

#[cfg(test)]
mod tests;

/// **WORDS THAT WERE READ**, and the region they were read from.
///
/// ```text
///   ┌─ bbox ───────────────┐
///   │  "Gate B14 · 19:40"  │   confidence: 0.91
///   └──────────────────────┘
/// ```
///
/// # THE TEXT IS A PAYLOAD AND NOT A LABEL, which is why there is no [`Detection`] here
///
/// A classification's label names a CLASS a model chose from its own vocabulary. A recognised string
/// names nothing — it is the picture's own content, read back — so putting it in a `label` field
/// would call one thing by the other's name in every schema that published it. The two types have
/// the same SHAPE and different subjects, and a shape is not a reason to share a type.
///
/// The consequence is visible at the door: a [`Label`](super::Label) refuses the empty word because
/// a classification of nothing is not a classification, and **this type refuses nothing at all**. A
/// recogniser that read a region and found no characters in it has made an observation, and the
/// honest carrier for it is the empty string rather than a refusal that loses the region.
///
/// [`Detection`]: super::Detection
///
/// # THE BOX IS REQUIRED, on [`LocatedDetection<T>`](super::LocatedDetection)'s terms
///
/// Text that was read has a place it was read from. There is no `Option` here and there will be
/// none: a recognised string with no region is not a text detection, and one shape with an optional
/// box would make *a page's transcript* and *a line whose geometry was lost* the same value.
///
/// # GENERIC over the GEOMETRY component, and over nothing else
///
/// `T` is what the box is measured in, exactly as it is for [`BoundingBox<T>`] — a normalized page
/// writes `TextDetection<NormCoord>`, a raster scan `TextDetection<u32>`. The confidence names
/// [`Score`] rather than taking a width, which is [`Detection`](super::Detection)'s own ruling and
/// its reason: a confidence width is a REPRESENTATION of an invariant this crate already wrote four
/// carriers for, where a geometry component is a UNIT the caller owns.
///
/// # Examples
///
/// ```
/// use ingraph::{BoundingBox, Score, TextDetection};
///
/// let line = TextDetection::new(
///   "Gate B14",
///   Score::new(0.91).unwrap(),
///   BoundingBox::try_unit(0.10, 0.42, 0.30, 0.06).unwrap(),
/// );
///
/// assert_eq!(line.text(), "Gate B14");
/// assert_eq!(line.confidence().get(), 0.91);
/// ```
// NOT `Copy`, where the geometry half is: a reading carries text, and text is not a register move.
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct TextDetection<T> {
  pub(super) text: Utf8Bytes,
  pub(super) confidence: Score,
  pub(super) bbox: BoundingBox<T>,
}

impl<T> TextDetection<T> {
  /// A recognised string, in the region it was read from.
  ///
  /// INFALLIBLE, and every half is why: a [`Score`] cannot exist outside `[0.0, 1.0]`, whatever
  /// rules the box has are its own component's and its own instantiation's, and the text has no rule
  /// at all — see the type's note, where the absent refusal is the ruling.
  #[inline]
  #[must_use]
  pub fn new(text: impl Into<Utf8Bytes>, confidence: Score, bbox: BoundingBox<T>) -> Self {
    Self {
      text: text.into(),
      confidence,
      bbox,
    }
  }

  /// The words that were read, exactly as the recogniser gave them.
  #[inline]
  #[must_use]
  pub fn text(&self) -> &str {
    self.text.as_str()
  }

  /// The words as the crate's own text carrier — what a column binds.
  #[inline]
  #[must_use]
  pub const fn text_bytes(&self) -> &Utf8Bytes {
    &self.text
  }

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

  /// The region the words were read from.
  #[inline]
  #[must_use]
  pub const fn bbox(&self) -> &BoundingBox<T> {
    &self.bbox
  }
}

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

/// The recognised string's segment.
pub(super) const TEXT: &FieldName = FieldName::new("text");

/// **The SEVEN columns a reading spans**: the text, the confidence, and the box's five under its own
/// name.
///
/// The two leaves this level owns are PLAIN and the box KEEPS its name, which is
/// [`LocatedDetection<T>`](super::LocatedDetection)'s arrangement and carries its argument: a splice
/// would put `x`, `y`, `width`, `height` and `area` into a namespace beside `text` and
/// `confidence`, and the `bbox` segment is what makes a collision UNREPRESENTABLE rather than merely
/// absent.
///
/// Nothing flattens here where a located detection flattens its classification, and the reason is
/// that there is nothing to flatten: this type holds two leaves of its own rather than a composite
/// that would lend a redundant name.
impl<T: ColumnKind> ColumnKind for TextDetection<T> {
  const SEGMENTS: &'static [ColumnShape] = &[
    ColumnShape::Plain(ColumnName::of(TEXT)),
    ColumnShape::Plain(ColumnName::of(CONFIDENCE)),
    shape::<BoundingBox<T>>(ColumnName::of(BBOX)),
  ];

  const ORDER: &'static [OrderLevel] = ORDER;
}

/// A reading is one column value when its words, its confidence and its region all are — the
/// region through its own row, so the box's derived area plays no part in what the box itself
/// compares equal.
impl<T: ColumnEq> ColumnEq for TextDetection<T> {
  #[inline]
  fn column_eq(&self, other: &Self) -> bool {
    self.text_bytes().column_eq(other.text_bytes())
      && self.confidence().column_eq(&other.confidence())
      && self.bbox().column_eq(other.bbox())
  }
}

/// **The order those seven columns MEAN, and the box's derived leaf is in NO level of it.**
///
/// Six levels over seven leaves: the text, the confidence, and the rectangle's four value leaves.
/// The seventh is the box's `area` — see [`BoundingBox`]'s own `ORDER` — and this citizen inherits
/// the obligation to say so rather than the leaf itself.
///
/// The sequence is the DECLARATION's, so nothing here claims that readings sort by their words. What
/// stating it BUYS is the expansion: a term over this type becomes six one-column levels, so the
/// derived leaf cannot reach a keyset row value. That is
/// [`LocatedDetection<T>`](super::LocatedDetection)'s own sentence at a second holder, and the rule
/// it is the first case of — *a holder of a citizen with a derived leaf owes a sequence of its own*.
pub(super) const ORDER: &[OrderLevel] = &[
  OrderLevel::new(0),
  OrderLevel::new(1),
  OrderLevel::new(2),
  OrderLevel::new(3),
  OrderLevel::new(4),
  OrderLevel::new(5),
];

/// **The VALUE one of a reading's six levels compares.**
///
/// The geometry's members carry the box's own leaf vocabulary rather than restating it, so a change
/// in that house moves this face too and there is no second list to drift from. Leaf `6` is the
/// box's derived area, and there is no member for it.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TextDetectionLeaf<T> {
  /// Leaf `0` — the words that were read.
  Text(Utf8Bytes),
  /// Leaf `1` — how sure the recogniser was.
  Confidence(Score),
  /// Leaves `2`–`5` — the rectangle's own, under the box's numbering shifted by the two above.
  Bbox(BoundingBoxLeaf<T>),
}

/// One leaf is the same as another leaf when it is the SAME leaf holding the same value — never
/// across kinds, so the words are never equal to a confidence even where both compare true
/// against another value of their own kind.
impl<T: ColumnEq> ColumnEq for TextDetectionLeaf<T> {
  fn column_eq(&self, other: &Self) -> bool {
    match (self, other) {
      (Self::Text(this), Self::Text(that)) => this.column_eq(that),
      (Self::Confidence(this), Self::Confidence(that)) => this.column_eq(that),
      (Self::Bbox(this), Self::Bbox(that)) => this.column_eq(that),
      _ => false,
    }
  }
}

/// **The six VALUE leaves, the geometry's four delegated, and [`None`] for the derived seventh.**
impl<T: ColumnKind + Copy> crate::OrderLeaves for TextDetection<T> {
  type Leaf = TextDetectionLeaf<T>;

  fn leaf(&self, at: usize) -> Option<TextDetectionLeaf<T>> {
    match at {
      0 => Some(TextDetectionLeaf::Text(self.text.clone())),
      1 => Some(TextDetectionLeaf::Confidence(self.confidence)),
      2..=6 => crate::OrderLeaves::leaf(&self.bbox, at - 2).map(TextDetectionLeaf::Bbox),
      _ => None,
    }
  }
}

/// **The KEYSET position of ONE leaf**: which leaf, then that leaf's own bytes.
impl<T: crate::CursorValue> crate::CursorValue for TextDetectionLeaf<T> {
  fn write_cursor(&self, out: &mut Vec<u8>) {
    match self {
      Self::Text(text) => {
        out.push(0);
        crate::CursorValue::write_cursor(text, out);
      }
      Self::Confidence(confidence) => {
        out.push(1);
        crate::CursorValue::write_cursor(confidence, out);
      }
      Self::Bbox(leaf) => {
        out.push(2);
        crate::CursorValue::write_cursor(leaf, out);
      }
    }
  }

  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    let (tag, value) = bytes.split_first()?;
    match tag {
      0 => <Utf8Bytes as crate::CursorValue>::read_cursor(value).map(Self::Text),
      1 => <Score as crate::CursorValue>::read_cursor(value).map(Self::Confidence),
      2 => <BoundingBoxLeaf<T> as crate::CursorValue>::read_cursor(value).map(Self::Bbox),
      _ => None,
    }
  }
}

/// **ONE BIND OUT**, through the row the leaf's own type already had.
#[cfg(feature = "sqlx")]
impl<Db, T> crate::Carrier<Db> for TextDetectionLeaf<T>
where
  Db: sqlx::Database,
  Utf8Bytes: crate::Carrier<Db>,
  Score: crate::Carrier<Db>,
  BoundingBoxLeaf<T>: crate::Carrier<Db>,
{
  fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
    match self {
      Self::Text(text) => <Utf8Bytes as crate::Carrier<Db>>::push_bind(text, qb),
      Self::Confidence(confidence) => <Score as crate::Carrier<Db>>::push_bind(confidence, qb),
      Self::Bbox(leaf) => <BoundingBoxLeaf<T> as crate::Carrier<Db>>::push_bind(leaf, qb),
    }
  }
}

/// **The DECLARED half — SEVEN words**: text, the confidence's, and the box's five read off its own
/// row.
impl<Db, T> crate::StoredAs<Db> for TextDetection<T>
where
  Utf8Bytes: crate::StoredAs<Db>,
  Score: crate::StoredAs<Db>,
  BoundingBox<T>: crate::StoredAs<Db>,
{
  const WORDS: &'static [&'static str] = &[
    <Utf8Bytes as crate::StoredAs<Db>>::WORDS[0],
    <Score as crate::StoredAs<Db>>::WORDS[0],
    <BoundingBox<T> as crate::StoredAs<Db>>::WORDS[0],
    <BoundingBox<T> as crate::StoredAs<Db>>::WORDS[1],
    <BoundingBox<T> as crate::StoredAs<Db>>::WORDS[2],
    <BoundingBox<T> as crate::StoredAs<Db>>::WORDS[3],
    <BoundingBox<T> as crate::StoredAs<Db>>::WORDS[4],
  ];
}

/// **THE ADMISSION**, DELEGATED to the geometry half: a page's transcript is
/// `Vec<TextDetection<NormCoord>>`, one element per line, which is the row an edge table of readings
/// needs.
impl<T: crate::CollectionElement> crate::CollectionElement for TextDetection<T> {}

/// **SEVEN BINDS OUT** — the text, the confidence, then the box's five.
///
/// **AND SIX FOR A STRUCTURAL JUDGMENT**, the box leaving its index leaf out where it always does.
#[cfg(feature = "sqlx")]
impl<Db, T> crate::Carrier<Db> for TextDetection<T>
where
  Db: sqlx::Database,
  Utf8Bytes: crate::Carrier<Db>,
  Score: crate::Carrier<Db>,
  BoundingBox<T>: crate::Carrier<Db>,
{
  fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
    <Utf8Bytes as crate::Carrier<Db>>::push_bind(&self.text, qb);
    qb.push(", ");
    <Score as crate::Carrier<Db>>::push_bind(&self.confidence, qb);
    qb.push(", ");
    <BoundingBox<T> as crate::Carrier<Db>>::push_bind(&self.bbox, qb);
  }

  fn push_value_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
    <Utf8Bytes as crate::Carrier<Db>>::push_bind(&self.text, qb);
    qb.push(", ");
    <Score as crate::Carrier<Db>>::push_bind(&self.confidence, qb);
    qb.push(", ");
    <BoundingBox<T> as crate::Carrier<Db>>::push_value_bind(&self.bbox, qb);
  }
}

/// **AND THE VALUE COLUMNS BACK IN**, by name.
///
/// It states no invariant of its own: the text has none, the confidence's is [`Score`]'s at its own
/// column, and the geometry's are the component's. This level adds no rule ACROSS them, there being
/// none to add — a string says nothing about where a rectangle may sit.
#[cfg(feature = "sqlx")]
impl<'a, R, T> crate::Assemble<'a, R> for TextDetection<T>
where
  R: sqlx::Row,
  Utf8Bytes: crate::Assemble<'a, R>,
  Score: crate::Assemble<'a, R>,
  BoundingBox<T>: crate::Assemble<'a, R>,
{
  fn assemble(row: &'a R, under: Option<&crate::Path<'_>>) -> sqlx::Result<Self> {
    let text: Utf8Bytes = crate::assembled(row, TEXT, under)?;
    let confidence: Score = crate::assembled(row, CONFIDENCE, under)?;
    let bbox: BoundingBox<T> = crate::assembled(row, BBOX, under)?;

    Ok(Self::new(text, confidence, bbox))
  }
}

/// **THE KEYSET POSITION** — the three members in segment order, 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, for [`Detection`](super::Detection)'s reason read at this arity: the text
/// is VARIABLE-WIDTH and it is FIRST in segment order, so there is no constant split point from
/// either end. The box rides that framing unchanged and divides its own payload by four, which is
/// the contract its own row already depends on — and the derived column is absent from both, a
/// boundary being what a page is cut at.
impl<T: crate::CursorValue> crate::CursorValue for TextDetection<T> {
  fn write_cursor(&self, out: &mut Vec<u8>) {
    crate::cursor::write_member(&self.text, out);
    crate::cursor::write_member(&self.confidence, out);
    crate::cursor::write_member(&self.bbox, out);
  }

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

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

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

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

/// **A COLLECTION of readings is asked through the QUANTIFIERS alone** —
/// [`Detection`](super::Detection)'s ruling, inherited along with the float that makes it.
///
/// `any` carries the whole [`TextDetectionFilter`], so *a line containing "gate" was read
/// confidently in the top half* is ONE element question. Asked of the page separately, the text, the
/// confidence and the box would each be answered by a different line.
impl<T: DefaultMarker> DefaultVecMarker for TextDetection<T> {
  type Marker = QuantifiedMarker<Vec<TextDetection<T>>>;
}

/// The filter that guards a [`TextDetection<T>`] column: the WORDS, the confidence, and the region.
///
/// ```text
/// input TextDetectionF32Filter {
///   text: TextFilter  confidence: ConfidenceFilter
///   bbox: BoundingBoxF32Filter
/// }
/// ```
///
/// # `text` takes the TEXT family's twenty words, and here the affix half is the POINT
///
/// A recognised string is the picture's own content, so `contains: "invoice"` is the question this
/// facet exists for — where a [`Label`](super::Label)'s affix slots are a secondary reading of a
/// vocabulary word. `startsWithNocase` is where the case a recogniser preserved gets asked about
/// without being folded into the value.
///
/// # NO WHOLE-READING OPERATOR
///
/// None of `eq`, `ne`, `in` or an ordering, on the house's shared terms: 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. See [`DetectionFilter`](super::DetectionFilter) and
/// [`BoundingBoxFilter`], where each half argues its own.
///
/// The AREA facet arrives with the box and needs no line here: *a line of text covering at least
/// five percent of the page* is `{ bbox: { area: { gte: 0.05 } } }`, lowered onto the geometry
/// house's own derived column.
pub struct TextDetectionFilter<CF> {
  pub(super) text: Option<TextFilter<Utf8Bytes>>,
  pub(super) confidence: Option<ConfidenceFilter>,
  pub(super) bbox: Option<BoundingBoxFilter<CF>>,
}

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

  crate::graphql::filter::opt_accessor!(
    text: TextFilter<Utf8Bytes> => with_text, set_text, maybe_text, update_text
  );
  crate::graphql::filter::opt_accessor!(
    confidence: ConfidenceFilter => with_confidence, set_confidence, maybe_confidence, update_confidence
  );
  crate::graphql::filter::opt_accessor!(
    bbox: BoundingBoxFilter<CF> => with_bbox, set_bbox, maybe_bbox, update_bbox
  );
}

impl<CF: crate::GraphqlFilter> TextDetectionFilter<CF> {
  /// True while NO operator slot is set on ANY of the three facets.
  ///
  /// The bound is on this ONE method rather than on the type, which is the arrangement every generic
  /// filter kind here takes.
  pub fn is_empty(&self) -> bool {
    self
      .text
      .as_ref()
      .is_none_or(crate::GraphqlFilter::is_empty)
      && self
        .confidence
        .as_ref()
        .is_none_or(ConfidenceFilter::is_empty)
      && self
        .bbox
        .as_ref()
        .is_none_or(crate::GraphqlFilter::is_empty)
  }
}

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

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

// The three are written out rather than derived, for `BoundingBoxFilter`'s reason: a derive would
// bound `CF` on the whole type, where each of these needs it on itself alone.
impl<CF: fmt::Debug> fmt::Debug for TextDetectionFilter<CF> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("TextDetectionFilter")
      .field("text", &self.text)
      .field("confidence", &self.confidence)
      .field("bbox", &self.bbox)
      .finish()
  }
}

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

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