Skip to main content

rightkit_ocr/
lib.rs

1//! Product-neutral two-stage ONNX OCR pipeline.
2//!
3//! Two-model pipeline:
4//!   1. Det model (`det.onnx`) — DB detector; finds text
5//!      bounding boxes in the image.
6//!   2. Rec model (`rec.onnx`) — multilingual recognizer
7//!      (50 languages + symbols + emoji, 18,708-char dict); reads text from each
8//!      cropped box. The vocab length is read from the model output at runtime,
9//!      so the dict is model-driven, not hardcoded.
10//!
11//! The caller configures the dynamic runtime through `rightkit-onnx`, supplies
12//! an absolute model directory, and supplies resolved artifact provenance.
13
14mod native;
15mod router;
16#[cfg(feature = "onnx")]
17mod support;
18mod types;
19pub mod worker;
20
21#[cfg(all(target_os = "macos", feature = "native"))]
22pub use native::vision;
23#[cfg(all(windows, feature = "native"))]
24pub use native::win_native;
25pub use native::{canary_png, native_backend};
26pub use router::{
27    BackendPreference, Isolation, ModelLeaseHook, NativeHealthHook, Ocr, OcrOptions, OcrOutcome,
28    OcrResult, OnnxConfig,
29};
30pub use types::{
31    decode_encoded, is_backend_unavailable, OcrBackend, OcrErrorKind, OcrLine, OcrRect,
32    MACOS_VISION_UNAVAILABLE, MAX_PIXELS, OCR_UNSUPPORTED_PLATFORM, WINDOWS_OCR_UNAVAILABLE,
33};
34pub use worker::{RunRecord, WorkerCommand, WorkerEvent, WorkerEvents, WorkerFailure, WorkerRun};
35
36#[cfg(feature = "onnx")]
37use image::{imageops, RgbImage};
38#[cfg(feature = "onnx")]
39use rightkit_onnx::ort;
40#[cfg(feature = "onnx")]
41use rightkit_onnx::ort::{session::Session, value::Tensor};
42#[cfg(feature = "onnx")]
43use rightkit_onnx::ProviderDiagnostic;
44#[cfg(feature = "onnx")]
45use sha2::{Digest, Sha256};
46use std::fmt;
47#[cfg(feature = "onnx")]
48use std::path::Path;
49use std::path::PathBuf;
50#[cfg(feature = "onnx")]
51use support::{
52    build_session, crop_box, ctc_greedy_decode_scored, dedup_boxes, det_chw_data, det_net_size,
53    extract_boxes, group_into_lines, load_image, load_vocab, rec_chw_data, BBox, DET_BAND_OVERLAP,
54    DET_MAX_W, DET_TILE_H,
55};
56
57// ---------------------------------------------------------------------------
58// Public artifact and error contract
59// ---------------------------------------------------------------------------
60
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub enum OcrProvenance {
63    Resolved {
64        label: String,
65        source: String,
66        license: String,
67    },
68    Conflicting {
69        labels: Vec<String>,
70    },
71}
72
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct OcrArtifactManifest {
75    pub provenance: OcrProvenance,
76    pub detector_sha256: String,
77    pub recognizer_sha256: String,
78    pub dictionary_sha256: String,
79    pub fixture_sha256: String,
80    pub expected_fixture_output: String,
81}
82
83impl OcrArtifactManifest {
84    pub fn characterized_windows_contract() -> Self {
85        Self {
86            provenance: OcrProvenance::Conflicting {
87                labels: vec!["PP-OCRv5".to_string(), "PP-OCRv6".to_string()],
88            },
89            detector_sha256: "eb13b44b25bb36f89528b68720af8a61d9cf381176107f465db1757b65d086e1"
90                .to_string(),
91            recognizer_sha256: "5435fd747c9e0efe15a96d0b378d5bd157e9492ed8fd80edf08f30d02fa24634"
92                .to_string(),
93            dictionary_sha256: "b5f2bfe2bdd9448429e3e82b51c789775d9b42f2403d082b00662eb77e401c5d"
94                .to_string(),
95            fixture_sha256: "803e102100c91a077607cd2d4750d9d748d86ced48fabc0f77062f26dcba0a4b"
96                .to_string(),
97            expected_fixture_output: "RIGHTKIT OCR 2026\nShared parity fixture".to_string(),
98        }
99    }
100
101    /// The PP-OCRv6 model set ScrapeRight and CodeRight ship, with its resolved provenance.
102    ///
103    /// The three digests are the ones in `PROVENANCE.toml`. Provenance is tied to bytes, not
104    /// asserted: ScrapeRight's `scripts/fetch-ocr-assets.mjs` downloads `det.onnx` from
105    /// `PaddlePaddle/PP-OCRv6_medium_det_onnx` and `rec.onnx` from
106    /// `PaddlePaddle/PP-OCRv6_small_rec_onnx` (`inference.onnx` in each), and the Hugging Face
107    /// LFS SHA-256 of each upstream file equals the digest here (checked 2026-10-09). Both model
108    /// cards declare Apache-2.0. `en_dict.txt` is the inline `character_dict` of the recognizer's
109    /// `inference.yml` (18,708 entries). The earlier PP-OCRv5 label belonged to different
110    /// CodeRight weights that were migrated off; it does not describe these bytes.
111    pub fn pp_ocr_v6() -> Self {
112        let mut manifest = Self::characterized_windows_contract();
113        manifest.provenance = OcrProvenance::Resolved {
114            label: "PP-OCRv6".to_string(),
115            source: "https://huggingface.co/PaddlePaddle/PP-OCRv6_medium_det_onnx (det) + \
116                     https://huggingface.co/PaddlePaddle/PP-OCRv6_small_rec_onnx (rec + dict)"
117                .to_string(),
118            license: "Apache-2.0".to_string(),
119        };
120        manifest
121    }
122
123    /// Replace the characterized conflict only with an explicit authoritative
124    /// label and provenance source supplied by the signed artifact catalog.
125    pub fn with_resolved_provenance(
126        mut self,
127        label: impl Into<String>,
128        source: impl Into<String>,
129        license: impl Into<String>,
130    ) -> Result<Self, OcrError> {
131        self.provenance = OcrProvenance::Resolved {
132            label: label.into(),
133            source: source.into(),
134            license: license.into(),
135        };
136        self.validate_metadata()?;
137        Ok(self)
138    }
139
140    pub fn validate_metadata(&self) -> Result<(), OcrError> {
141        match &self.provenance {
142            OcrProvenance::Conflicting { labels } => Err(OcrError::UnresolvedProvenance {
143                labels: labels.clone(),
144            }),
145            OcrProvenance::Resolved {
146                label,
147                source,
148                license,
149            } if label.trim().is_empty()
150                || source.trim().is_empty()
151                || license.trim().is_empty() =>
152            {
153                Err(OcrError::InvalidProvenance)
154            }
155            OcrProvenance::Resolved { .. } => Ok(()),
156        }
157    }
158
159    #[cfg(feature = "onnx")]
160    pub fn validate_model_dir(&self, model_dir: &Path) -> Result<VerifiedOcrArtifacts, OcrError> {
161        self.validate_metadata()?;
162        if !model_dir.is_absolute() {
163            return Err(OcrError::UnsafeArtifactPath {
164                path: model_dir.to_path_buf(),
165            });
166        }
167        let root = model_dir
168            .canonicalize()
169            .map_err(|_| OcrError::MissingArtifact {
170                path: model_dir.to_path_buf(),
171            })?;
172        if !root.is_dir() {
173            return Err(OcrError::MissingArtifact { path: root });
174        }
175        Ok(VerifiedOcrArtifacts {
176            detector: verify_artifact(&root, "det.onnx", &self.detector_sha256)?,
177            recognizer: verify_artifact(&root, "rec.onnx", &self.recognizer_sha256)?,
178            dictionary: verify_artifact(&root, "en_dict.txt", &self.dictionary_sha256)?,
179        })
180    }
181}
182
183#[derive(Debug, Clone, PartialEq, Eq)]
184pub struct VerifiedOcrArtifacts {
185    pub detector: PathBuf,
186    pub recognizer: PathBuf,
187    pub dictionary: PathBuf,
188}
189
190#[derive(Debug, Clone, PartialEq, Eq)]
191pub enum OcrError {
192    UnresolvedProvenance {
193        labels: Vec<String>,
194    },
195    InvalidProvenance,
196    UnsafeArtifactPath {
197        path: PathBuf,
198    },
199    MissingArtifact {
200        path: PathBuf,
201    },
202    DigestMismatch {
203        path: PathBuf,
204        expected: String,
205        actual: String,
206    },
207    Runtime(String),
208    /// The requested backend cannot run on this machine (capability verdict).
209    BackendUnavailable(String),
210    /// A fallback ONNX engine was needed but no [`OnnxConfig`] was supplied.
211    NoFallbackConfigured(String),
212}
213
214impl fmt::Display for OcrError {
215    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216        match self {
217            Self::UnresolvedProvenance { labels } => write!(
218                f,
219                "OCR provenance conflict is unresolved: {}",
220                labels.join(" vs ")
221            ),
222            Self::InvalidProvenance => {
223                write!(
224                    f,
225                    "OCR provenance label, source, and license must be non-empty"
226                )
227            }
228            Self::UnsafeArtifactPath { path } => {
229                write!(f, "OCR artifact path must be absolute: {}", path.display())
230            }
231            Self::MissingArtifact { path } => {
232                write!(f, "OCR artifact is missing: {}", path.display())
233            }
234            Self::DigestMismatch {
235                path,
236                expected,
237                actual,
238            } => write!(
239                f,
240                "OCR artifact digest mismatch for {}: expected {expected}, got {actual}",
241                path.display()
242            ),
243            Self::Runtime(message) => write!(f, "OCR runtime error: {message}"),
244            Self::BackendUnavailable(message) => write!(f, "OCR backend unavailable: {message}"),
245            Self::NoFallbackConfigured(message) => {
246                write!(
247                    f,
248                    "OCR native backend unavailable and no ONNX fallback configured: {message}"
249                )
250            }
251        }
252    }
253}
254
255impl OcrError {
256    /// The typed kind to key on. Each variant maps to one kind; `BackendUnavailable` is refined
257    /// by its backend prefix when it has one, so a Vision verdict reports
258    /// [`OcrErrorKind::MacosVisionUnavailable`]. `NoFallbackConfigured` stays its own kind even
259    /// when its message carries the native cause. Worker-level kinds such as `WorkerTimeout`
260    /// reach callers through [`WorkerFailure::kind`] and surface here as `Runtime`.
261    pub fn kind(&self) -> OcrErrorKind {
262        match self {
263            Self::UnresolvedProvenance { .. } | Self::InvalidProvenance => OcrErrorKind::Provenance,
264            Self::UnsafeArtifactPath { .. }
265            | Self::MissingArtifact { .. }
266            | Self::DigestMismatch { .. } => OcrErrorKind::Artifact,
267            Self::Runtime(_) => OcrErrorKind::Runtime,
268            Self::BackendUnavailable(message) => {
269                OcrErrorKind::from_message(message).unwrap_or(OcrErrorKind::BackendUnavailable)
270            }
271            Self::NoFallbackConfigured(_) => OcrErrorKind::NoFallbackConfigured,
272        }
273    }
274}
275
276impl std::error::Error for OcrError {}
277impl From<String> for OcrError {
278    fn from(value: String) -> Self {
279        Self::Runtime(value)
280    }
281}
282
283/// The three model files `model_dir` is expected to hold (unverified; for lease registration).
284#[cfg(feature = "onnx")]
285fn artifact_paths(model_dir: &Path) -> Vec<PathBuf> {
286    ["det.onnx", "rec.onnx", "en_dict.txt"]
287        .iter()
288        .map(|name| model_dir.join(name))
289        .collect()
290}
291
292#[cfg(feature = "onnx")]
293fn verify_artifact(root: &Path, name: &str, expected: &str) -> Result<PathBuf, OcrError> {
294    let path = root.join(name);
295    let canonical = path
296        .canonicalize()
297        .map_err(|_| OcrError::MissingArtifact { path: path.clone() })?;
298    if !canonical.starts_with(root) || !canonical.is_file() {
299        return Err(OcrError::UnsafeArtifactPath { path: canonical });
300    }
301    let bytes = std::fs::read(&canonical).map_err(|_| OcrError::MissingArtifact {
302        path: canonical.clone(),
303    })?;
304    let actual: String = Sha256::digest(bytes)
305        .iter()
306        .map(|b| format!("{b:02x}"))
307        .collect();
308    if actual != expected {
309        return Err(OcrError::DigestMismatch {
310            path: canonical,
311            expected: expected.to_string(),
312            actual,
313        });
314    }
315    Ok(canonical)
316}
317
318#[cfg(feature = "onnx")]
319pub fn ocr_image_with_manifest(
320    path: &Path,
321    model_dir: &Path,
322    manifest: &OcrArtifactManifest,
323) -> Result<String, OcrError> {
324    let mut engine = OcrEngine::load_with_manifest(model_dir, manifest)?;
325    let img = load_image(path)?;
326    engine.run(&img)
327}
328
329// ---------------------------------------------------------------------------
330
331// OcrEngine — load once, reuse across slides
332// ---------------------------------------------------------------------------
333
334/// A loaded, warm OCR engine.
335///
336/// Build once on a dedicated worker thread; reuse across slides.
337/// DirectML sessions are GPU-state-bound — keep on the same thread.
338#[cfg(feature = "onnx")]
339pub struct OcrEngine {
340    det: Session,
341    rec: Session,
342    /// CTC vocabulary: index 0 = blank '\0'; 1..=N = dict chars (N = en_dict.txt
343    /// line count for the characterized model); final index = ' '. The decoder indexes
344    /// by the model's own output `vocab_size`, so an extra trailing entry is
345    /// never reached if the model omits the space class.
346    vocab: Vec<char>,
347    provider_diagnostics: Vec<ProviderDiagnostic>,
348    /// Caller's model-store lease; declared last so the sessions drop before it releases.
349    _lease: Option<Box<dyn std::any::Any + Send>>,
350}
351
352#[cfg(feature = "onnx")]
353impl OcrEngine {
354    /// Load using [`OcrArtifactManifest::pp_ocr_v6`], the digest-pinned model set with
355    /// resolved provenance.
356    pub fn load(model_dir: &Path) -> Result<Self, OcrError> {
357        Self::load_with_manifest(model_dir, &OcrArtifactManifest::pp_ocr_v6())
358    }
359
360    /// Load det + rec sessions from an explicit, verified model directory.
361    ///
362    /// Probes DirectML first on Windows and records any CPU fallback.
363    ///
364    /// Expected files:
365    /// - `<model_dir>/det.onnx`      detector ONNX
366    /// - `<model_dir>/rec.onnx`      recognizer ONNX
367    /// - `<model_dir>/en_dict.txt`   character dictionary (UTF-8, one char/line)
368    pub fn load_with_manifest(
369        model_dir: &Path,
370        manifest: &OcrArtifactManifest,
371    ) -> Result<Self, OcrError> {
372        Self::load_with_lease(model_dir, manifest, None)
373    }
374
375    /// Like [`OcrEngine::load_with_manifest`], taking a model-store lease first.
376    ///
377    /// The hook is called before any artifact is verified, so an app's model GC cannot replace
378    /// the payload between verification and session construction. The returned guard is held
379    /// until the engine is dropped (after its sessions).
380    pub fn load_with_lease(
381        model_dir: &Path,
382        manifest: &OcrArtifactManifest,
383        lease_hook: Option<&dyn ModelLeaseHook>,
384    ) -> Result<Self, OcrError> {
385        let lease = match lease_hook {
386            Some(hook) => Some(hook.acquire_model_lease(&artifact_paths(model_dir))?),
387            None => None,
388        };
389        let artifacts = manifest.validate_model_dir(model_dir)?;
390        let vocab = load_vocab(&artifacts.dictionary)?;
391        let (det, mut provider_diagnostics) = build_session(&artifacts.detector)?;
392        let (rec, rec_diagnostics) = build_session(&artifacts.recognizer)?;
393        provider_diagnostics.extend(rec_diagnostics);
394        Ok(OcrEngine {
395            det,
396            rec,
397            vocab,
398            provider_diagnostics,
399            _lease: lease,
400        })
401    }
402
403    /// Verify `model_dir` against `manifest`, then build and drop real det + rec sessions.
404    ///
405    /// For migration and doctor checks that already hold the app's model lease, so none is
406    /// taken here. Native-only OCR callers never need this.
407    pub fn validate_sessions(
408        model_dir: &Path,
409        manifest: &OcrArtifactManifest,
410    ) -> Result<(), OcrError> {
411        let artifacts = manifest.validate_model_dir(model_dir)?;
412        load_vocab(&artifacts.dictionary)?;
413        build_session(&artifacts.detector)?;
414        build_session(&artifacts.recognizer)?;
415        Ok(())
416    }
417
418    pub fn provider_diagnostics(&self) -> &[ProviderDiagnostic] {
419        &self.provider_diagnostics
420    }
421
422    /// OCR a pre-loaded RGB image; returns newline-joined text.
423    pub fn run(&mut self, img: &RgbImage) -> Result<String, OcrError> {
424        let lines = self.run_lines(img)?;
425        Ok(lines
426            .into_iter()
427            .map(|l| l.text)
428            .collect::<Vec<_>>()
429            .join("\n"))
430    }
431
432    /// OCR with per-line geometry: one [`OcrLine`] per visual line, rect =
433    /// union of the line's detected boxes normalized to the image (top-left
434    /// origin), confidence = mean CTC character score when the recognizer
435    /// emits probabilities.
436    pub fn run_lines(&mut self, img: &RgbImage) -> Result<Vec<OcrLine>, OcrError> {
437        let boxes = self.detect(img)?;
438        if boxes.is_empty() {
439            return Ok(Vec::new());
440        }
441        let (iw, ih) = (img.width().max(1) as f32, img.height().max(1) as f32);
442        // Group boxes into visual lines (baseline-overlap), then read each line
443        // left-to-right. Without this, higher-resolution detection fragments big
444        // display text into per-word boxes that a naive top-down sort scrambles.
445        let rows = group_into_lines(boxes);
446        let mut out = Vec::new();
447        for row in rows {
448            let mut words = Vec::new();
449            let (mut x0, mut y0, mut x1, mut y1) = (u32::MAX, u32::MAX, 0u32, 0u32);
450            let (mut conf_sum, mut conf_n, mut conf_ok) = (0.0f32, 0u32, true);
451            for bbox in &row {
452                let crop = crop_box(img, bbox);
453                if crop.width() == 0 || crop.height() == 0 {
454                    continue;
455                }
456                let (text, conf) = self.recognize(&crop)?;
457                let t = text.trim().to_string();
458                if t.is_empty() {
459                    continue;
460                }
461                words.push(t);
462                x0 = x0.min(bbox.x0);
463                y0 = y0.min(bbox.y0);
464                x1 = x1.max(bbox.x1);
465                y1 = y1.max(bbox.y1);
466                match conf {
467                    Some(c) => {
468                        conf_sum += c;
469                        conf_n += 1;
470                    }
471                    None => conf_ok = false,
472                }
473            }
474            if words.is_empty() {
475                continue;
476            }
477            let (x0, y0) = (x0 as f32 / iw, y0 as f32 / ih);
478            let (x1, y1) = ((x1 as f32 / iw).min(1.0), (y1 as f32 / ih).min(1.0));
479            out.push(OcrLine {
480                text: words.join(" "),
481                rect: OcrRect {
482                    x: x0,
483                    y: y0,
484                    width: (x1 - x0).max(0.0),
485                    height: (y1 - y0).max(0.0),
486                },
487                confidence: (conf_ok && conf_n > 0).then(|| conf_sum / conf_n as f32),
488            });
489        }
490        Ok(out)
491    }
492
493    // -----------------------------------------------------------------------
494    // Detection
495    // -----------------------------------------------------------------------
496
497    /// Detect text boxes across the whole image.
498    ///
499    /// Caps working width at [`DET_MAX_W`] (downscale only — never upscale) so
500    /// horizontal text keeps near-native resolution, then splits tall images
501    /// into overlapping vertical bands each ≤ [`DET_TILE_H`] and detects per
502    /// band. Boxes are translated to original-image coordinates and
503    /// de-duplicated across band seams. Recognition always crops from the
504    /// full-resolution original, so higher detection resolution directly
505    /// improves read accuracy.
506    fn detect(&mut self, img: &RgbImage) -> Result<Vec<BBox>, String> {
507        let (orig_w, orig_h) = (img.width(), img.height());
508
509        // Width cap: downscale only. Most screenshots are ≤ DET_MAX_W → native.
510        let ws = if orig_w > DET_MAX_W {
511            DET_MAX_W as f32 / orig_w as f32
512        } else {
513            1.0
514        };
515        let work = if ws < 1.0 {
516            let nh = ((orig_h as f32 * ws).round() as u32).max(1);
517            imageops::resize(img, DET_MAX_W, nh, imageops::FilterType::Lanczos3)
518        } else {
519            img.clone()
520        };
521        let (work_w, work_h) = (work.width(), work.height());
522
523        // Overlapping vertical bands so tall pages keep native resolution
524        // instead of being crushed to a 960px long side.
525        let mut bands: Vec<(u32, u32)> = Vec::new();
526        if work_h <= DET_TILE_H {
527            bands.push((0, work_h));
528        } else {
529            let step = DET_TILE_H - DET_BAND_OVERLAP;
530            let mut y = 0u32;
531            loop {
532                let end = (y + DET_TILE_H).min(work_h);
533                bands.push((y, end));
534                if end >= work_h {
535                    break;
536                }
537                y += step;
538            }
539        }
540
541        let mut all: Vec<BBox> = Vec::new();
542        for (ys, ye) in bands {
543            let band = imageops::crop_imm(&work, 0, ys, work_w, ye - ys).to_image();
544            for mut b in self.detect_one(&band)? {
545                b.y0 += ys;
546                b.y1 += ys;
547                all.push(b);
548            }
549        }
550
551        // Map working → original coordinates.
552        if ws < 1.0 {
553            let inv = 1.0 / ws;
554            for b in all.iter_mut() {
555                b.x0 = (b.x0 as f32 * inv) as u32;
556                b.y0 = (b.y0 as f32 * inv) as u32;
557                b.x1 = ((b.x1 as f32 * inv) as u32).min(orig_w);
558                b.y1 = ((b.y1 as f32 * inv) as u32).min(orig_h);
559            }
560        }
561
562        let mut boxes = dedup_boxes(all);
563        boxes.sort_by(|a, b| a.y0.cmp(&b.y0).then(a.x0.cmp(&b.x0)));
564        Ok(boxes)
565    }
566
567    /// Run the detector on a single band; returns boxes in band-local pixels.
568    fn detect_one(&mut self, band: &RgbImage) -> Result<Vec<BBox>, String> {
569        let (bw, bh) = (band.width(), band.height());
570        let (net_w, net_h) = det_net_size(bw, bh);
571        let resized = imageops::resize(band, net_w, net_h, imageops::FilterType::Lanczos3);
572
573        let data = det_chw_data(&resized, net_w, net_h);
574        let shape = [1i64, 3, net_h as i64, net_w as i64];
575        let tensor =
576            Tensor::<f32>::from_array((shape, data)).map_err(|e| format!("det tensor: {e}"))?;
577
578        let outputs = self
579            .det
580            .run(ort::inputs![tensor])
581            .map_err(|e| format!("det run: {e}"))?;
582
583        // Output: [1, 1, H, W].  Extract as flat &[f32] + shape.
584        let (out_shape, prob_flat) = outputs[0]
585            .try_extract_tensor::<f32>()
586            .map_err(|e| format!("det extract: {e}"))?;
587        // Shape derefs to &[i64]; dims are [batch, channel, H, W].
588        let dims: &[i64] = out_shape;
589        let (oh, ow) = match dims {
590            [_, _, h, w] => (*h as usize, *w as usize),
591            s => return Err(format!("unexpected det output shape: {s:?}")),
592        };
593        let prob_2d: &[f32] = &prob_flat[0..oh * ow];
594
595        // Map prob-map → band pixels (handles any det output downsampling).
596        let scale_x = bw as f32 / ow as f32;
597        let scale_y = bh as f32 / oh as f32;
598        Ok(extract_boxes(
599            prob_2d, ow, oh, scale_x, scale_y, 0.3, bw, bh,
600        ))
601    }
602
603    // -----------------------------------------------------------------------
604    // Recognition
605    // -----------------------------------------------------------------------
606
607    fn recognize(&mut self, crop: &RgbImage) -> Result<(String, Option<f32>), String> {
608        let (h, w) = (crop.height(), crop.width());
609        let new_w = ((48.0 / h as f32) * w as f32).max(4.0) as u32;
610        let strip = imageops::resize(crop, new_w, 48, imageops::FilterType::Lanczos3);
611
612        let data = rec_chw_data(&strip, new_w);
613        let shape = [1i64, 3, 48, new_w as i64];
614        let tensor =
615            Tensor::<f32>::from_array((shape, data)).map_err(|e| format!("rec tensor: {e}"))?;
616
617        let outputs = self
618            .rec
619            .run(ort::inputs![tensor])
620            .map_err(|e| format!("rec run: {e}"))?;
621
622        // Output: [1, T, vocab_size].
623        let (out_shape, logits_flat) = outputs[0]
624            .try_extract_tensor::<f32>()
625            .map_err(|e| format!("rec extract: {e}"))?;
626        // Shape derefs to &[i64]; dims are [batch, T, vocab_size].
627        let dims: &[i64] = out_shape;
628        let (t_len, vocab_size) = match dims {
629            [_, t, v] => (*t as usize, *v as usize),
630            s => return Err(format!("unexpected rec output shape: {s:?}")),
631        };
632        // logits_flat: [1, T, V]; skip batch dim.
633        let logits = &logits_flat[0..t_len * vocab_size];
634
635        Ok(ctc_greedy_decode_scored(
636            logits,
637            t_len,
638            vocab_size,
639            &self.vocab,
640        ))
641    }
642}
643
644// ---------------------------------------------------------------------------