1use async_trait::async_trait;
5use base64::Engine;
6
7use super::client::CvClient;
8use super::config::NimCvConfig;
9use super::wire::{self, NormBox, NormPoint, TextDetection};
10use crate::backend::{BackendDescriptor, InputLimits, Locality};
11use crate::cx::VisionCx;
12use crate::edit::ops;
13use crate::egress::ReleasedImage;
14use crate::error::{Result, VisionError};
15use crate::geometry::{AxisOrder, BBox, CoordFrame, Polygon, RawRegion, Shape};
16use crate::reading::{self, Piece};
17use crate::traits::{Block, BlockKind, DocumentPage, DocumentReader, ReadOptions, TableCell};
18
19pub const PAGE_ELEMENTS_MODEL: &str = "nvidia/nemotron-page-elements-v3";
21pub const TABLE_STRUCTURE_MODEL: &str = "nvidia/nemotron-table-structure-v1";
23pub const GRAPHIC_ELEMENTS_MODEL: &str = "nvidia/nemotron-graphic-elements-v1";
25
26#[non_exhaustive]
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub enum NimOcrModel {
30 NemotronOcrV1,
32 NemoretrieverOcr,
34 PaddleOcr,
36}
37
38impl NimOcrModel {
39 pub fn id(self) -> &'static str {
41 match self {
42 Self::NemotronOcrV1 => "nvidia/nemotron-ocr-v1",
43 Self::NemoretrieverOcr => "nvidia/nemoretriever-ocr",
44 Self::PaddleOcr => "baidu/paddleocr",
45 }
46 }
47
48 fn merge_levels(self) -> Option<&'static [&'static str]> {
49 match self {
50 Self::NemotronOcrV1 | Self::NemoretrieverOcr => Some(&["word"]),
51 Self::PaddleOcr => None,
52 }
53 }
54}
55
56#[derive(Debug, Clone)]
90pub struct NimDocumentReader {
91 descriptor: BackendDescriptor,
92 client: CvClient,
93 ocr: NimOcrModel,
94 layout: bool,
95 min_layout_confidence: f32,
96 tables: bool,
97 charts: bool,
98}
99
100pub const DEFAULT_MIN_LAYOUT_CONFIDENCE: f32 = 0.3;
104
105pub const NIM_READER_ID: &str = "nim-document-reader";
107
108impl NimDocumentReader {
109 pub fn new(config: NimCvConfig) -> Result<Self> {
116 let client = CvClient::new(config)?;
117 let mut reader = Self {
118 descriptor: BackendDescriptor::new(
119 NIM_READER_ID,
120 Locality::Remote { hosts: Vec::new() },
121 CoordFrame::Normalized { scale: 1, order: AxisOrder::Xy },
122 )
123 .with_provider("nvidia")
124 .with_limits(InputLimits::long_edge(2048)),
127 client,
128 ocr: NimOcrModel::NemotronOcrV1,
129 layout: true,
130 min_layout_confidence: DEFAULT_MIN_LAYOUT_CONFIDENCE,
131 tables: true,
132 charts: true,
133 };
134 for model in [
136 NimOcrModel::NemotronOcrV1.id(),
137 NimOcrModel::NemoretrieverOcr.id(),
138 NimOcrModel::PaddleOcr.id(),
139 PAGE_ELEMENTS_MODEL,
140 TABLE_STRUCTURE_MODEL,
141 GRAPHIC_ELEMENTS_MODEL,
142 ] {
143 let url = reader.client.config().url_for(model);
144 let parsed = reqwest::Url::parse(&url).map_err(|e| {
145 VisionError::InvalidInput(format!("NIM URL `{url}` for `{model}` is invalid: {e}"))
146 })?;
147 if parsed.host_str().is_none_or(str::is_empty) {
148 return Err(VisionError::InvalidInput(format!(
149 "NIM URL `{url}` for `{model}` names no host"
150 )));
151 }
152 }
153 reader.refresh_hosts();
154 Ok(reader)
155 }
156
157 pub fn with_id(mut self, id: impl Into<String>) -> Self {
159 self.descriptor.id = crate::backend::BackendId::new(id);
160 self
161 }
162
163 pub fn with_limits(mut self, limits: InputLimits) -> Self {
165 self.descriptor.limits = limits;
166 self
167 }
168
169 pub fn with_ocr(mut self, model: NimOcrModel) -> Self {
171 self.ocr = model;
172 self.refresh_hosts();
173 self
174 }
175
176 pub fn with_layout(mut self, on: bool) -> Self {
178 self.layout = on;
179 self.refresh_hosts();
180 self
181 }
182
183 pub fn with_min_layout_confidence(mut self, floor: f32) -> Self {
185 self.min_layout_confidence = floor;
186 self
187 }
188
189 pub fn with_tables(mut self, on: bool) -> Self {
191 self.tables = on;
192 self.refresh_hosts();
193 self
194 }
195
196 pub fn with_charts(mut self, on: bool) -> Self {
198 self.charts = on;
199 self.refresh_hosts();
200 self
201 }
202
203 fn models(&self) -> Vec<&'static str> {
204 let mut models = vec![self.ocr.id()];
205 if self.layout {
206 models.push(PAGE_ELEMENTS_MODEL);
207 if self.tables {
208 models.push(TABLE_STRUCTURE_MODEL);
209 }
210 if self.charts {
211 models.push(GRAPHIC_ELEMENTS_MODEL);
212 }
213 }
214 models
215 }
216
217 fn refresh_hosts(&mut self) {
220 let mut hosts: Vec<String> = Vec::new();
221 for model in self.models() {
222 let url = self.client.config().url_for(model);
223 let host = reqwest::Url::parse(&url)
224 .ok()
225 .and_then(|u| u.host_str().map(str::to_string))
226 .unwrap_or_default();
227 if !hosts.contains(&host) {
228 hosts.push(host);
229 }
230 }
231 self.descriptor.locality = Locality::Remote { hosts };
232 }
233
234 fn data_uri(&self, png: &[u8]) -> Result<String> {
235 let max = self.client.config().max_inline_bytes();
236 if png.len() > max {
237 return Err(VisionError::InputTooLarge {
238 backend: self.descriptor.id.to_string(),
239 limit: format!("{max} bytes inline"),
240 actual: format!("{} bytes", png.len()),
241 });
242 }
243 Ok(format!(
244 "data:image/png;base64,{}",
245 base64::engine::general_purpose::STANDARD.encode(png)
246 ))
247 }
248
249 async fn call(
250 &self,
251 model: &str,
252 data_uri: &str,
253 merge: Option<&[&str]>,
254 ) -> Result<serde_json::Value> {
255 let body = wire::body(data_uri, merge);
256 self.client.infer(self.descriptor.id.as_str(), model, &body).await
257 }
258
259 async fn on_crop(
262 &self,
263 model: &str,
264 released: &ReleasedImage,
265 crop: BBox,
266 ) -> Result<Vec<(String, NormBox)>> {
267 let (w, h) = released.image().size();
268 let (x, y, cw, ch) = crop.pixel_bounds(w, h);
269 if cw < 8 || ch < 8 {
270 return Ok(Vec::new());
271 }
272 let pixels = ops::crop(released.pixels(), x, y, cw, ch);
273 let uri = self.data_uri(&pixels.encode_png()?)?;
274 let value = self.call(model, &uri, None).await?;
275 let found = wire::elements(self.descriptor.id.as_str(), model, value)?;
276 let (fw, fh, fx, fy) = (w as f32, h as f32, x as f32, y as f32);
277 let (cw, ch) = (cw as f32, ch as f32);
278 Ok(found
279 .into_iter()
280 .map(|(class, b)| {
281 let to_page = NormBox {
282 x_min: (fx + b.x_min * cw) / fw,
283 y_min: (fy + b.y_min * ch) / fh,
284 x_max: (fx + b.x_max * cw) / fw,
285 y_max: (fy + b.y_max * ch) / fh,
286 confidence: b.confidence,
287 };
288 (class, to_page)
289 })
290 .collect())
291 }
292}
293
294struct Element {
296 class: String,
297 norm: BBox,
298 px: BBox,
299 confidence: Option<f32>,
300}
301
302fn kind_of(class: &str) -> BlockKind {
303 match class {
304 "title" => BlockKind::Title,
305 "table" => BlockKind::Table,
306 "chart" | "infographic" => BlockKind::Figure,
307 _ => BlockKind::Text,
308 }
309}
310
311fn norm_box(b: &NormBox) -> BBox {
312 BBox::new(b.x_min, b.y_min, b.x_max, b.y_max)
313}
314
315fn to_px(b: &BBox, (w, h): (u32, u32)) -> BBox {
316 BBox::new(b.x0 * w as f32, b.y0 * h as f32, b.x1 * w as f32, b.y1 * h as f32)
317}
318
319fn piece(detection: TextDetection, size: (u32, u32)) -> Piece {
320 let points: Vec<[f32; 2]> = detection.points.iter().map(|p: &NormPoint| [p.x, p.y]).collect();
321 let norm = BBox::covering(points.iter().copied()).unwrap_or(BBox::new(0.0, 0.0, 0.0, 0.0));
322 Piece {
323 raw: RawRegion {
324 shape: Shape::Polygon(Polygon { points }),
325 label: None,
326 score: detection.confidence,
327 track: None,
328 },
329 px: to_px(&norm, size),
330 text: detection.text,
331 confidence: detection.confidence,
332 }
333}
334
335fn boxed(norm: BBox, label: Option<String>, score: Option<f32>) -> RawRegion {
336 RawRegion { shape: Shape::Box(norm), label, score, track: None }
337}
338
339fn holder(elements: &[Element], point: [f32; 2]) -> Option<usize> {
341 elements
342 .iter()
343 .enumerate()
344 .filter(|(_, e)| e.px.contains(point))
345 .min_by(|(_, a), (_, b)| a.px.area().total_cmp(&b.px.area()))
346 .map(|(i, _)| i)
347}
348
349fn label_of(labels: &[Element], word: &BBox) -> Option<String> {
353 let reach = 0.5 * word.height();
354 labels
355 .iter()
356 .filter(|e| e.px.expanded(reach).contains(word.center()))
357 .min_by(|a, b| a.px.area().total_cmp(&b.px.area()))
358 .map(|e| e.class.clone())
359}
360
361fn spans(cell: &BBox, bands: &[BBox], vertical: bool) -> Option<(u32, u32)> {
364 let hits: Vec<u32> = bands
365 .iter()
366 .enumerate()
367 .filter(|(_, band)| {
368 let (a0, a1, b0, b1, len) = if vertical {
369 (cell.y0, cell.y1, band.y0, band.y1, cell.height())
370 } else {
371 (cell.x0, cell.x1, band.x0, band.x1, cell.width())
372 };
373 (a1.min(b1) - a0.max(b0)) >= 0.5 * len.max(f32::EPSILON)
374 })
375 .map(|(i, _)| i as u32)
376 .collect();
377 let first = *hits.first()?;
378 Some((first, hits.len() as u32))
379}
380
381fn cells(
384 found: Vec<(String, NormBox)>,
385 words: &[Piece],
386 size: (u32, u32),
387) -> Vec<TableCell<RawRegion>> {
388 let mut rows: Vec<BBox> = Vec::new();
389 let mut cols: Vec<BBox> = Vec::new();
390 let mut raw_cells: Vec<(BBox, Option<f32>)> = Vec::new();
391 for (class, b) in found {
392 let px = to_px(&norm_box(&b), size);
393 match class.as_str() {
394 "row" => rows.push(px),
395 "column" => cols.push(px),
396 "cell" => raw_cells.push((norm_box(&b), b.confidence)),
397 _ => {}
398 }
399 }
400 rows.sort_by(|a, b| a.center()[1].total_cmp(&b.center()[1]));
401 cols.sort_by(|a, b| a.center()[0].total_cmp(&b.center()[0]));
402 let mut out: Vec<(TableCell<RawRegion>, Option<f32>)> = Vec::new();
403 for (norm, confidence) in raw_cells {
404 let px = to_px(&norm, size);
405 let (Some((row, row_span)), Some((col, col_span))) =
406 (spans(&px, &rows, true), spans(&px, &cols, false))
407 else {
408 continue;
409 };
410 let inside: Vec<Piece> =
411 words.iter().filter(|w| px.contains(w.px.center())).cloned().collect();
412 let text = reading::lines(inside)
413 .iter()
414 .map(|line| reading::line_text(line))
415 .collect::<Vec<_>>()
416 .join(" ");
417 let cell = TableCell {
418 region: boxed(norm, Some("cell".into()), confidence),
419 row,
420 col,
421 row_span,
422 col_span,
423 text,
424 };
425 match out.iter_mut().find(|(c, _)| c.row == row && c.col == col) {
427 Some(existing) if existing.1.unwrap_or(0.0) >= confidence.unwrap_or(0.0) => {}
428 Some(existing) => *existing = (cell, confidence),
429 None => out.push((cell, confidence)),
430 }
431 }
432 let mut cells: Vec<TableCell<RawRegion>> = out.into_iter().map(|(c, _)| c).collect();
433 cells.sort_by_key(|c| (c.row, c.col));
434 cells
435}
436
437#[async_trait]
438impl DocumentReader<ReleasedImage> for NimDocumentReader {
439 fn descriptor(&self) -> &BackendDescriptor {
440 &self.descriptor
441 }
442
443 async fn read(
444 &self,
445 cx: &VisionCx,
446 page: &ReleasedImage,
447 options: &ReadOptions,
448 ) -> Result<DocumentPage<RawRegion>> {
449 cx.check()?;
450 if !page.is_for(&self.descriptor.id) {
451 return Err(VisionError::NotReleased { backend: self.descriptor.id.to_string() });
452 }
453 let size = page.image().size();
454 let backend = self.descriptor.id.as_str();
455 let uri = self.data_uri(page.bytes())?;
456 let ocr = self.call(self.ocr.id(), &uri, self.ocr.merge_levels());
457 let layout = async {
458 if self.layout {
459 self.call(PAGE_ELEMENTS_MODEL, &uri, None).await.map(Some)
460 } else {
461 Ok(None)
462 }
463 };
464 let (ocr, layout) = tokio::try_join!(ocr, layout)?;
465 let pieces: Vec<Piece> = wire::text_detections(backend, self.ocr.id(), ocr)?
466 .into_iter()
467 .filter(|d| !d.text.trim().is_empty())
468 .map(|d| piece(d, size))
469 .collect();
470 let elements: Vec<Element> = match layout {
471 Some(value) => wire::elements(backend, PAGE_ELEMENTS_MODEL, value)?
472 .into_iter()
473 .map(|(class, b)| {
474 let norm = norm_box(&b);
475 Element { px: to_px(&norm, size), norm, class, confidence: b.confidence }
476 })
477 .filter(|e| {
478 !e.px.is_empty() && e.confidence.is_none_or(|c| c >= self.min_layout_confidence)
479 })
480 .collect(),
481 None => Vec::new(),
482 };
483
484 let mut owned: Vec<Vec<Piece>> = vec![Vec::new(); elements.len()];
486 let mut free: Vec<Piece> = Vec::new();
487 for piece in pieces {
488 match holder(&elements, piece.px.center()) {
489 Some(i) => owned[i].push(piece),
490 None => free.push(piece),
491 }
492 }
493
494 let mut blocks: Vec<Block<RawRegion>> = Vec::new();
495 let mut boxes: Vec<BBox> = Vec::new();
496 for (element, words) in elements.iter().zip(owned) {
497 let kind = kind_of(&element.class);
498 let lines = reading::lines(words);
499 let text = lines.iter().map(|l| reading::line_text(l)).collect::<Vec<_>>().join("\n");
500 let flat: Vec<Piece> = lines.into_iter().flatten().collect();
501 let confidence = reading::min_confidence(&flat).or(element.confidence);
502 let mut block = reading::block(
503 kind,
504 boxed(element.norm, Some(element.class.clone()), element.confidence),
505 text,
506 confidence,
507 );
508 match kind {
509 BlockKind::Table if self.tables => {
510 let found =
511 self.on_crop(TABLE_STRUCTURE_MODEL, page, element.px.expanded(4.0)).await?;
512 block.cells = cells(found, &flat, size);
513 if !block.cells.is_empty() {
514 block.text = reading::table_text(&block.cells);
515 }
516 }
517 BlockKind::Figure if self.charts && element.class == "chart" => {
518 let found = self
519 .on_crop(GRAPHIC_ELEMENTS_MODEL, page, element.px.expanded(4.0))
520 .await?;
521 let labels: Vec<Element> = found
522 .into_iter()
523 .map(|(class, b)| {
524 let norm = norm_box(&b);
525 Element {
526 px: to_px(&norm, size),
527 norm,
528 class,
529 confidence: b.confidence,
530 }
531 })
532 .collect();
533 block.words = flat
534 .iter()
535 .map(|p| {
536 let mut word = p.word();
537 word.region.label = label_of(&labels, &p.px);
538 word
539 })
540 .collect();
541 }
542 _ => {}
543 }
544 if block.words.is_empty() {
545 block.words = flat.iter().map(Piece::word).collect();
546 }
547 boxes.push(element.px);
548 blocks.push(block);
549 }
550 for line in reading::lines(free) {
552 let norm = BBox::covering(
553 line.iter()
554 .filter_map(|p| p.raw.shape.bbox())
555 .flat_map(|b| [[b.x0, b.y0], [b.x1, b.y1]]),
556 )
557 .unwrap_or(BBox::new(0.0, 0.0, 0.0, 0.0));
558 let confidence = reading::min_confidence(&line);
559 let mut block = reading::block(
560 BlockKind::Text,
561 boxed(norm, None, confidence),
562 reading::line_text(&line),
563 confidence,
564 );
565 block.words = line.iter().map(Piece::word).collect();
566 boxes.push(reading::span(&line));
567 blocks.push(block);
568 }
569 let reading_order = reading::reading_order(&boxes);
570 let mut out = DocumentPage { blocks, reading_order, markdown: None };
571 if options.markdown {
572 out.markdown = Some(reading::markdown(&out));
573 }
574 tracing::debug!(
575 vision.backend = backend,
576 vision.blocks = out.blocks.len(),
577 "nim page read"
578 );
579 Ok(out)
580 }
581}
582
583#[cfg(test)]
584mod tests {
585 use super::*;
586
587 fn nb(x0: f32, y0: f32, x1: f32, y1: f32) -> NormBox {
588 NormBox { x_min: x0, y_min: y0, x_max: x1, y_max: y1, confidence: Some(0.9) }
589 }
590
591 #[test]
592 fn structure_boxes_become_a_cell_grid_with_text() {
593 let size = (100, 100);
594 let found = vec![
595 ("row".to_string(), nb(0.0, 0.0, 1.0, 0.5)),
596 ("row".to_string(), nb(0.0, 0.5, 1.0, 1.0)),
597 ("column".to_string(), nb(0.0, 0.0, 0.5, 1.0)),
598 ("column".to_string(), nb(0.5, 0.0, 1.0, 1.0)),
599 ("cell".to_string(), nb(0.5, 0.5, 1.0, 1.0)),
600 ("cell".to_string(), nb(0.0, 0.0, 0.5, 0.5)),
601 ("cell".to_string(), nb(0.0, 0.0, 1.0, 0.5)),
603 ];
604 let word = |text: &str, x0: f32, y0: f32| {
605 let px = BBox::new(x0, y0, x0 + 10.0, y0 + 10.0);
606 Piece {
607 raw: RawRegion::shape(Shape::Box(px)),
608 px,
609 text: text.into(),
610 confidence: Some(0.9),
611 }
612 };
613 let words = vec![word("4.2", 70.0, 70.0), word("Part", 10.0, 10.0)];
614 let cells = cells(found, &words, size);
615 let grid: Vec<(u32, u32, u32, u32, &str)> =
616 cells.iter().map(|c| (c.row, c.col, c.row_span, c.col_span, c.text.as_str())).collect();
617 assert_eq!(grid, vec![(0, 0, 1, 1, "Part"), (1, 1, 1, 1, "4.2")]);
619 }
620
621 #[test]
622 fn pieces_belong_to_the_smallest_holding_element() {
623 let element =
624 |class: &str, px: BBox| Element { class: class.into(), norm: px, px, confidence: None };
625 let elements = vec![
626 element("chart", BBox::new(0.0, 0.0, 100.0, 100.0)),
627 element("title", BBox::new(10.0, 10.0, 50.0, 20.0)),
628 ];
629 assert_eq!(holder(&elements, [20.0, 15.0]), Some(1));
630 assert_eq!(holder(&elements, [80.0, 80.0]), Some(0));
631 assert_eq!(holder(&elements, [180.0, 80.0]), None);
632 }
633}