Skip to main content

adk_vision/runtime/
calls.rs

1//! The runtime's task methods and escalation.
2
3use super::{
4    Backend, CallOptions, CallRecord, Escalation, Inputs, Prepared, Route, Trigger, VisionOutput,
5    VisionRuntime, mismatch, planned_size,
6};
7use crate::backend::{BackendDescriptor, BackendId};
8use crate::cx::VisionCx;
9use crate::digest::Digest;
10use crate::edit::EditOp;
11use crate::error::{Result, VisionError};
12use crate::geometry::{
13    BBox, EscalatedFrom, EscalationReason, RawRegion, Region, RegionNormalizer, Shape, resample,
14};
15use crate::manifest::VisionTask;
16use crate::media::{ImageRef, Provenance, SourceImage};
17use crate::sent::SentImage;
18use crate::traits::{
19    Block, DescribeRequest, DescribeSpec, Description, DetectQuery, DocumentPage, ReadOptions,
20    SegmentPrompt, TableCell, Word,
21};
22
23/// An edited image, stored with `Provenance::Derived`.
24#[derive(Clone, Debug)]
25pub struct Edited {
26    /// The stored image.
27    pub image: ImageRef,
28    /// Its pixels and digest.
29    pub source: SourceImage,
30}
31
32enum RegionTask<'a> {
33    Detect(&'a DetectQuery),
34    Segment(&'a [SegmentPrompt]),
35}
36
37impl RegionTask<'_> {
38    fn task(&self) -> VisionTask {
39        match self {
40            Self::Detect(_) => VisionTask::Detect,
41            Self::Segment(_) => VisionTask::Segment,
42        }
43    }
44}
45
46impl VisionRuntime {
47    /// Detects objects in a source image on the detection route.
48    ///
49    /// # Errors
50    ///
51    /// The route's, the gate's or the backend's error; see [`detect_with`](Self::detect_with).
52    pub async fn detect(
53        &self,
54        cx: &VisionCx,
55        image: &SourceImage,
56        query: &DetectQuery,
57    ) -> Result<VisionOutput<Vec<Region>>> {
58        self.detect_with(cx, image, query, &CallOptions::default()).await
59    }
60
61    /// Detects objects with per-call options. Regions come back in source pixels; a route
62    /// with an escalation crops each uncertain region, plus margin, and sends only that.
63    ///
64    /// # Errors
65    ///
66    /// [`VisionError::BackendNotFound`], the egress gate's refusals for a remote backend,
67    /// a budget or kill-switch refusal before the request, [`VisionError::Cancelled`], or
68    /// the backend's error.
69    pub async fn detect_with(
70        &self,
71        cx: &VisionCx,
72        image: &SourceImage,
73        query: &DetectQuery,
74        options: &CallOptions,
75    ) -> Result<VisionOutput<Vec<Region>>> {
76        let route = self.route_for(VisionTask::Detect, options, self.detectors.default_id())?;
77        self.regions_routed(cx, &RegionTask::Detect(query), &route, image, options).await
78    }
79
80    /// Segments a source image on the segmentation route. Prompts are in source pixels.
81    ///
82    /// # Errors
83    ///
84    /// As [`detect_with`](Self::detect_with).
85    pub async fn segment(
86        &self,
87        cx: &VisionCx,
88        image: &SourceImage,
89        prompts: &[SegmentPrompt],
90    ) -> Result<VisionOutput<Vec<Region>>> {
91        self.segment_with(cx, image, prompts, &CallOptions::default()).await
92    }
93
94    /// Segments with per-call options.
95    ///
96    /// # Errors
97    ///
98    /// As [`detect_with`](Self::detect_with), and [`VisionError::Unsupported`] for a mask
99    /// prompt to a backend whose frame has no raster.
100    pub async fn segment_with(
101        &self,
102        cx: &VisionCx,
103        image: &SourceImage,
104        prompts: &[SegmentPrompt],
105        options: &CallOptions,
106    ) -> Result<VisionOutput<Vec<Region>>> {
107        let route = self.route_for(VisionTask::Segment, options, self.segmenters.default_id())?;
108        self.regions_routed(cx, &RegionTask::Segment(prompts), &route, image, options).await
109    }
110
111    async fn regions_routed(
112        &self,
113        cx: &VisionCx,
114        task: &RegionTask<'_>,
115        route: &Route,
116        image: &SourceImage,
117        options: &CallOptions,
118    ) -> Result<VisionOutput<Vec<Region>>> {
119        let mut calls = Vec::new();
120        let regions = self
121            .regions_once(cx, task, &route.primary, image, options.region, options, &mut calls)
122            .await?;
123        let regions = match &route.escalation {
124            Some(escalation) => {
125                self.escalate_regions(
126                    cx,
127                    task,
128                    &route.primary,
129                    escalation,
130                    image,
131                    regions,
132                    options,
133                    &mut calls,
134                )
135                .await?
136            }
137            None => regions,
138        };
139        Ok(VisionOutput { value: regions, calls })
140    }
141
142    #[allow(clippy::too_many_arguments)] // One call's full context; a struct would only rename it.
143    async fn regions_once(
144        &self,
145        cx: &VisionCx,
146        task: &RegionTask<'_>,
147        id: &BackendId,
148        image: &SourceImage,
149        crop: Option<BBox>,
150        options: &CallOptions,
151        calls: &mut Vec<CallRecord>,
152    ) -> Result<Vec<Region>> {
153        let (descriptor, raw, prepared, mut record) = match task {
154            RegionTask::Detect(query) => {
155                let (descriptor, backend) = self.detectors.get(id)?;
156                let sent = planned_size(image.size(), crop, &descriptor.limits);
157                let concepts = match query {
158                    DetectQuery::Classes(c) | DetectQuery::Concepts(c) => c.len(),
159                };
160                // The image is processed once per request the backend makes for the query.
161                let requests = descriptor.requests_for(concepts, false) as usize;
162                let hold = self
163                    .preflight(
164                        cx,
165                        task.task(),
166                        descriptor,
167                        &vec![sent; requests],
168                        0,
169                        None,
170                        options.image_unit(),
171                    )
172                    .await?;
173                let prepared =
174                    self.prepare(cx, descriptor, backend.is_remote(), image, crop, options).await?;
175                let work = match (backend, &prepared) {
176                    (Backend::Local(b), Prepared::Local(s)) => b.detect(cx, s, query),
177                    (Backend::Remote(b), Prepared::Remote(r)) => b.detect(cx, r, query),
178                    _ => return Err(mismatch(descriptor)),
179                };
180                let inputs = Inputs::of(std::slice::from_ref(&prepared));
181                let (raw, record) =
182                    self.metered(cx, task.task(), descriptor, inputs, hold, work).await?;
183                (descriptor, raw, prepared, record)
184            }
185            RegionTask::Segment(prompts) => {
186                let (descriptor, backend) = self.segmenters.get(id)?;
187                let sent = planned_size(image.size(), crop, &descriptor.limits);
188                let concepts =
189                    prompts.iter().filter(|p| matches!(p, SegmentPrompt::Concept { .. })).count();
190                // The image is processed once per request the backend makes for the prompts.
191                let requests = descriptor.requests_for(concepts, concepts < prompts.len()) as usize;
192                let hold = self
193                    .preflight(
194                        cx,
195                        task.task(),
196                        descriptor,
197                        &vec![sent; requests],
198                        0,
199                        None,
200                        options.image_unit(),
201                    )
202                    .await?;
203                let prepared =
204                    self.prepare(cx, descriptor, backend.is_remote(), image, crop, options).await?;
205                let prompts = prompts_for(descriptor, prepared.image(), prompts)?;
206                let work = match (backend, &prepared) {
207                    (Backend::Local(b), Prepared::Local(s)) => b.segment(cx, s, &prompts),
208                    (Backend::Remote(b), Prepared::Remote(r)) => b.segment(cx, r, &prompts),
209                    _ => return Err(mismatch(descriptor)),
210                };
211                let inputs = Inputs::of(std::slice::from_ref(&prepared));
212                let (raw, record) =
213                    self.metered(cx, task.task(), descriptor, inputs, hold, work).await?;
214                (descriptor, raw, prepared, record)
215            }
216        };
217        let regions = Self::normalizer(descriptor, &prepared).regions(raw)?;
218        record.regions = regions.len();
219        calls.push(record);
220        Ok(regions)
221    }
222
223    #[allow(clippy::too_many_arguments)] // One escalation's full context.
224    async fn escalate_regions(
225        &self,
226        cx: &VisionCx,
227        task: &RegionTask<'_>,
228        primary: &BackendId,
229        escalation: &Escalation,
230        image: &SourceImage,
231        regions: Vec<Region>,
232        options: &CallOptions,
233        calls: &mut Vec<CallRecord>,
234    ) -> Result<Vec<Region>> {
235        let (w, h) = image.size();
236        // (index of the primary region it replaces, reason, the box to crop)
237        let mut items: Vec<(Option<usize>, EscalationReason, Option<BBox>)> = Vec::new();
238        let listed = |items: &[(Option<usize>, EscalationReason, Option<BBox>)], i: usize| {
239            items.iter().any(|(j, _, _)| *j == Some(i))
240        };
241        for trigger in &escalation.triggers {
242            match trigger {
243                Trigger::LowConfidence { threshold } => {
244                    for (i, region) in regions.iter().enumerate() {
245                        if region.score.is_some_and(|s| s < *threshold)
246                            && !listed(&items, i)
247                            && let Some(bbox) = region.shape.bbox()
248                        {
249                            let reason = EscalationReason::LowConfidence { threshold: *threshold };
250                            items.push((Some(i), reason, Some(bbox)));
251                        }
252                    }
253                }
254                Trigger::NoResult => {
255                    if regions.is_empty()
256                        && !items.iter().any(|(_, r, _)| *r == EscalationReason::NoResult)
257                    {
258                        items.push((None, EscalationReason::NoResult, None));
259                    }
260                }
261                Trigger::Disagreement { with, min_iou } => {
262                    let other = self
263                        .regions_once(cx, task, with, image, options.region, options, calls)
264                        .await?;
265                    let agrees = |a: &Region, b: &Region| match (a.shape.bbox(), b.shape.bbox()) {
266                        (Some(x), Some(y)) => x.iou(&y) >= *min_iou,
267                        _ => false,
268                    };
269                    let reason = EscalationReason::Disagreement { with: with.clone() };
270                    for (i, region) in regions.iter().enumerate() {
271                        if !other.iter().any(|o| agrees(region, o)) && !listed(&items, i) {
272                            items.push((Some(i), reason.clone(), region.shape.bbox()));
273                        }
274                    }
275                    for o in &other {
276                        if !regions.iter().any(|r| agrees(r, o)) {
277                            items.push((None, reason.clone(), o.shape.bbox()));
278                        }
279                    }
280                }
281            }
282        }
283        if items.is_empty() {
284            return Ok(regions);
285        }
286        let esc_options = escalation_options(escalation, options);
287        let mut replacements: Vec<(usize, Vec<Region>)> = Vec::new();
288        let mut additions = Vec::new();
289        for (index, reason, bbox) in items {
290            let crop = bbox.map(|b| b.expanded(escalation.margin).clamped(w, h));
291            let found = match self
292                .regions_once(cx, task, &escalation.backend, image, crop, &esc_options, calls)
293                .await
294            {
295                Ok(found) => found,
296                Err(err @ VisionError::EgressRefused { .. }) => {
297                    escalation_refused(escalation, &err);
298                    continue;
299                }
300                Err(err) => return Err(err),
301            };
302            if let Some(last) = calls.last_mut() {
303                last.escalation = Some(reason.clone());
304            }
305            let replaced = index.map(|i| &regions[i]);
306            let from = EscalatedFrom {
307                backend: primary.clone(),
308                reason,
309                label: replaced.and_then(|r| r.label.clone()),
310                score: replaced.and_then(|r| r.score),
311                text: None,
312            };
313            let found: Vec<Region> = found
314                .into_iter()
315                .map(|mut r| {
316                    r.origin.escalated_from = Some(from.clone());
317                    r
318                })
319                .collect();
320            match index {
321                Some(i) if !found.is_empty() => replacements.push((i, found)),
322                Some(_) => {}
323                None => additions.extend(found),
324            }
325        }
326        let mut out = Vec::with_capacity(regions.len() + additions.len());
327        for (i, region) in regions.into_iter().enumerate() {
328            match replacements.iter_mut().find(|(j, _)| *j == i) {
329                Some((_, found)) => out.append(found),
330                None => out.push(region),
331            }
332        }
333        out.extend(additions);
334        Ok(out)
335    }
336
337    /// Reads a document page on the reading route.
338    ///
339    /// # Errors
340    ///
341    /// As [`detect_with`](Self::detect_with).
342    pub async fn read(
343        &self,
344        cx: &VisionCx,
345        page: &SourceImage,
346        read: &ReadOptions,
347    ) -> Result<VisionOutput<DocumentPage>> {
348        self.read_with(cx, page, read, &CallOptions::default()).await
349    }
350
351    /// Reads with per-call options. A block below a low-confidence trigger is re-read from
352    /// its crop by the escalation backend, which replaces its text with `escalatedFrom`
353    /// provenance on its region.
354    ///
355    /// # Errors
356    ///
357    /// As [`detect_with`](Self::detect_with).
358    pub async fn read_with(
359        &self,
360        cx: &VisionCx,
361        page: &SourceImage,
362        read: &ReadOptions,
363        options: &CallOptions,
364    ) -> Result<VisionOutput<DocumentPage>> {
365        let route = self.route_for(VisionTask::Read, options, self.readers.default_id())?;
366        let mut calls = Vec::new();
367        let mut result = self
368            .read_once(cx, &route.primary, page, options.region, read, options, &mut calls)
369            .await?;
370        let Some(escalation) = &route.escalation else {
371            return Ok(VisionOutput { value: result, calls });
372        };
373        let esc_options = escalation_options(escalation, options);
374        let (w, h) = page.size();
375        for trigger in &escalation.triggers {
376            match trigger {
377                Trigger::NoResult if result.blocks.is_empty() => {
378                    let mut whole = self
379                        .read_once(
380                            cx,
381                            &escalation.backend,
382                            page,
383                            options.region,
384                            read,
385                            &esc_options,
386                            &mut calls,
387                        )
388                        .await?;
389                    if let Some(last) = calls.last_mut() {
390                        last.escalation = Some(EscalationReason::NoResult);
391                    }
392                    let from = EscalatedFrom {
393                        backend: route.primary.clone(),
394                        reason: EscalationReason::NoResult,
395                        label: None,
396                        score: None,
397                        text: None,
398                    };
399                    for block in &mut whole.blocks {
400                        block.region.origin.escalated_from = Some(from.clone());
401                    }
402                    result = whole;
403                }
404                Trigger::LowConfidence { threshold } => {
405                    for i in 0..result.blocks.len() {
406                        let block = &result.blocks[i];
407                        let low = block.confidence.is_some_and(|c| c < *threshold);
408                        let escalated = block.region.origin.escalated_from.is_some();
409                        let Some(bbox) = block.region.shape.bbox().filter(|_| low && !escalated)
410                        else {
411                            continue;
412                        };
413                        let crop = bbox.expanded(escalation.margin).clamped(w, h);
414                        let sub = match self
415                            .read_once(
416                                cx,
417                                &escalation.backend,
418                                page,
419                                Some(crop),
420                                read,
421                                &esc_options,
422                                &mut calls,
423                            )
424                            .await
425                        {
426                            Ok(sub) => sub,
427                            Err(err @ VisionError::EgressRefused { .. }) => {
428                                escalation_refused(escalation, &err);
429                                continue;
430                            }
431                            Err(err) => return Err(err),
432                        };
433                        let reason = EscalationReason::LowConfidence { threshold: *threshold };
434                        if let Some(last) = calls.last_mut() {
435                            last.escalation = Some(reason.clone());
436                        }
437                        if sub.blocks.is_empty() {
438                            continue;
439                        }
440                        let block = &mut result.blocks[i];
441                        let from = EscalatedFrom {
442                            backend: route.primary.clone(),
443                            reason,
444                            label: None,
445                            score: block.confidence,
446                            text: Some(block.text.clone()),
447                        };
448                        let order: Vec<usize> = if sub.reading_order.is_empty() {
449                            (0..sub.blocks.len()).collect()
450                        } else {
451                            sub.reading_order.clone()
452                        };
453                        block.text = order
454                            .iter()
455                            .filter_map(|&j| sub.blocks.get(j).map(|b| b.text.as_str()))
456                            .collect::<Vec<_>>()
457                            .join("\n");
458                        block.confidence =
459                            sub.blocks.iter().filter_map(|b| b.confidence).reduce(f32::max);
460                        block.words = sub.blocks.iter().flat_map(|b| b.words.clone()).collect();
461                        let mut origin = sub.blocks[0].region.origin.clone();
462                        origin.escalated_from = Some(from);
463                        block.region.origin = origin;
464                    }
465                }
466                Trigger::NoResult | Trigger::Disagreement { .. } => {}
467            }
468        }
469        Ok(VisionOutput { value: result, calls })
470    }
471
472    #[allow(clippy::too_many_arguments)] // One call's full context; a struct would only rename it.
473    async fn read_once(
474        &self,
475        cx: &VisionCx,
476        id: &BackendId,
477        page: &SourceImage,
478        crop: Option<BBox>,
479        read: &ReadOptions,
480        options: &CallOptions,
481        calls: &mut Vec<CallRecord>,
482    ) -> Result<DocumentPage> {
483        let (descriptor, backend) = self.readers.get(id)?;
484        let sent = planned_size(page.size(), crop, &descriptor.limits);
485        let hold = self
486            .preflight(cx, VisionTask::Read, descriptor, &[sent], 0, None, options.image_unit())
487            .await?;
488        let prepared =
489            self.prepare(cx, descriptor, backend.is_remote(), page, crop, options).await?;
490        let work = match (backend, &prepared) {
491            (Backend::Local(b), Prepared::Local(s)) => b.read(cx, s, read),
492            (Backend::Remote(b), Prepared::Remote(r)) => b.read(cx, r, read),
493            _ => return Err(mismatch(descriptor)),
494        };
495        let inputs = Inputs::of(std::slice::from_ref(&prepared));
496        let (raw, mut record) =
497            self.metered(cx, VisionTask::Read, descriptor, inputs, hold, work).await?;
498        let page = normalize_page(&Self::normalizer(descriptor, &prepared), raw)?;
499        record.regions = page.blocks.len();
500        calls.push(record);
501        Ok(page)
502    }
503
504    /// Describes source images on the describing route.
505    ///
506    /// # Errors
507    ///
508    /// As [`detect_with`](Self::detect_with).
509    pub async fn describe(
510        &self,
511        cx: &VisionCx,
512        images: &[&SourceImage],
513        spec: &DescribeSpec,
514    ) -> Result<VisionOutput<Description>> {
515        self.describe_with(cx, images, spec, &CallOptions::default()).await
516    }
517
518    /// Describes with per-call options. On a trigger the escalation backend answers the
519    /// same request, and its answer replaces the primary's with `escalatedFrom` provenance.
520    ///
521    /// # Errors
522    ///
523    /// As [`detect_with`](Self::detect_with), and [`VisionError::InvalidInput`] for no
524    /// image.
525    pub async fn describe_with(
526        &self,
527        cx: &VisionCx,
528        images: &[&SourceImage],
529        spec: &DescribeSpec,
530        options: &CallOptions,
531    ) -> Result<VisionOutput<Description>> {
532        if images.is_empty() {
533            return Err(VisionError::InvalidInput("describe needs at least one image".into()));
534        }
535        let route = self.route_for(VisionTask::Describe, options, self.describers.default_id())?;
536        let mut calls = Vec::new();
537        let mut answer =
538            self.describe_once(cx, &route.primary, images, spec, options, &mut calls).await?;
539        if let Some(escalation) = &route.escalation {
540            let reason = escalation.triggers.iter().find_map(|trigger| match trigger {
541                Trigger::LowConfidence { threshold }
542                    if answer.confidence.is_some_and(|c| c < *threshold) =>
543                {
544                    Some(EscalationReason::LowConfidence { threshold: *threshold })
545                }
546                Trigger::NoResult
547                    if answer.text.is_none()
548                        && answer.value.is_none()
549                        && answer.regions.is_empty() =>
550                {
551                    Some(EscalationReason::NoResult)
552                }
553                _ => None,
554            });
555            let esc_options = escalation_options(escalation, options);
556            let escalated = match reason {
557                Some(reason) => match self
558                    .describe_once(cx, &escalation.backend, images, spec, &esc_options, &mut calls)
559                    .await
560                {
561                    Ok(escalated) => Some((reason, escalated)),
562                    Err(err @ VisionError::EgressRefused { .. }) => {
563                        escalation_refused(escalation, &err);
564                        None
565                    }
566                    Err(err) => return Err(err),
567                },
568                None => None,
569            };
570            if let Some((reason, mut escalated)) = escalated {
571                if let Some(last) = calls.last_mut() {
572                    last.escalation = Some(reason.clone());
573                }
574                let from = EscalatedFrom {
575                    backend: route.primary.clone(),
576                    reason,
577                    label: None,
578                    score: answer.confidence,
579                    text: answer.text.clone(),
580                };
581                for region in &mut escalated.regions {
582                    region.origin.escalated_from = Some(from.clone());
583                }
584                escalated.escalated_from = Some(from);
585                answer = escalated;
586            }
587        }
588        Ok(VisionOutput { value: answer, calls })
589    }
590
591    async fn describe_once(
592        &self,
593        cx: &VisionCx,
594        id: &BackendId,
595        images: &[&SourceImage],
596        spec: &DescribeSpec,
597        options: &CallOptions,
598        calls: &mut Vec<CallRecord>,
599    ) -> Result<Description> {
600        let (descriptor, backend) = self.describers.get(id)?;
601        let sizes: Vec<(u32, u32)> = images
602            .iter()
603            .map(|i| planned_size(i.size(), options.region, &descriptor.limits))
604            .collect();
605        let hold = self
606            .preflight(
607                cx,
608                VisionTask::Describe,
609                descriptor,
610                &sizes,
611                spec.prompt.len(),
612                spec.max_output_tokens,
613                options.image_unit(),
614            )
615            .await?;
616        let prepared =
617            self.prepare_all(cx, descriptor, backend.is_remote(), images, options).await?;
618        let normalizers: Vec<RegionNormalizer> =
619            prepared.iter().map(|p| Self::normalizer(descriptor, p)).collect();
620        let inputs = Inputs::of(&prepared);
621        let task = VisionTask::Describe;
622        let (raw, mut record) = match backend {
623            Backend::Local(b) => {
624                let request = DescribeRequest::new(local_images(descriptor, prepared)?, spec);
625                self.metered(cx, task, descriptor, inputs, hold, b.describe(cx, &request)).await?
626            }
627            Backend::Remote(b) => {
628                let request = DescribeRequest::new(released_images(descriptor, prepared)?, spec);
629                self.metered(cx, task, descriptor, inputs, hold, b.describe(cx, &request)).await?
630            }
631        };
632        let mut regions = Vec::with_capacity(raw.regions.len());
633        for found in raw.regions {
634            let normalizer = normalizers.get(found.image).ok_or_else(|| VisionError::Parse {
635                backend: descriptor.id.to_string(),
636                message: format!(
637                    "a region names image {}, but the request had {}",
638                    found.image,
639                    normalizers.len()
640                ),
641            })?;
642            if let Some(region) = normalizer.region(found.region)? {
643                regions.push(region);
644            }
645        }
646        record.regions = regions.len();
647        calls.push(record);
648        Ok(Description {
649            text: raw.text,
650            value: raw.value,
651            regions,
652            confidence: raw.confidence,
653            escalated_from: None,
654        })
655    }
656
657    async fn prepare_all(
658        &self,
659        cx: &VisionCx,
660        descriptor: &BackendDescriptor,
661        remote: bool,
662        images: &[&SourceImage],
663        options: &CallOptions,
664    ) -> Result<Vec<Prepared>> {
665        let mut prepared = Vec::with_capacity(images.len());
666        for image in images {
667            prepared
668                .push(self.prepare(cx, descriptor, remote, image, options.region, options).await?);
669        }
670        Ok(prepared)
671    }
672
673    /// Embeds source images with the embedding route's backend.
674    ///
675    /// # Errors
676    ///
677    /// As [`detect_with`](Self::detect_with), and [`VisionError::Parse`] when the backend
678    /// returns the wrong number of vectors or vectors outside its space's dimensions.
679    pub async fn embed_images(
680        &self,
681        cx: &VisionCx,
682        images: &[&SourceImage],
683        options: &CallOptions,
684    ) -> Result<VisionOutput<Vec<Vec<f32>>>> {
685        let route = self.route_for(VisionTask::Embed, options, self.embedders.default_id())?;
686        let (descriptor, backend) = self.embedders.get(&route.primary)?;
687        let sizes: Vec<(u32, u32)> = images
688            .iter()
689            .map(|i| planned_size(i.size(), options.region, &descriptor.limits))
690            .collect();
691        let hold = self
692            .preflight(cx, VisionTask::Embed, descriptor, &sizes, 0, Some(0), options.image_unit())
693            .await?;
694        let prepared =
695            self.prepare_all(cx, descriptor, backend.is_remote(), images, options).await?;
696        let inputs = Inputs::of(&prepared);
697        let task = VisionTask::Embed;
698        let (vectors, dims, record) = match backend {
699            Backend::Local(b) => {
700                let images = local_images(descriptor, prepared)?;
701                let (v, r) = self
702                    .metered(cx, task, descriptor, inputs, hold, b.embed_images(cx, &images))
703                    .await?;
704                (v, b.space().dimensions, r)
705            }
706            Backend::Remote(b) => {
707                let images = released_images(descriptor, prepared)?;
708                let (v, r) = self
709                    .metered(cx, task, descriptor, inputs, hold, b.embed_images(cx, &images))
710                    .await?;
711                (v, b.space().dimensions, r)
712            }
713        };
714        check_vectors(descriptor, &vectors, images.len(), dims)?;
715        Ok(VisionOutput { value: vectors, calls: vec![record] })
716    }
717
718    /// Embeds texts with the embedding route's backend, into the same space as its images.
719    ///
720    /// # Errors
721    ///
722    /// As [`embed_images`](Self::embed_images).
723    pub async fn embed_texts(
724        &self,
725        cx: &VisionCx,
726        texts: &[&str],
727        options: &CallOptions,
728    ) -> Result<VisionOutput<Vec<Vec<f32>>>> {
729        let route = self.route_for(VisionTask::Embed, options, self.embedders.default_id())?;
730        let (descriptor, backend) = self.embedders.get(&route.primary)?;
731        let chars = texts.iter().map(|t| t.len()).sum();
732        let hold = self
733            .preflight(cx, VisionTask::Embed, descriptor, &[], chars, Some(0), options.image_unit())
734            .await?;
735        let inputs = Inputs::default();
736        let task = VisionTask::Embed;
737        let (vectors, dims, record) = match backend {
738            Backend::Local(b) => {
739                let (v, r) = self
740                    .metered(cx, task, descriptor, inputs, hold, b.embed_texts(cx, texts))
741                    .await?;
742                (v, b.space().dimensions, r)
743            }
744            Backend::Remote(b) => {
745                let (v, r) = self
746                    .metered(cx, task, descriptor, inputs, hold, b.embed_texts(cx, texts))
747                    .await?;
748                (v, b.space().dimensions, r)
749            }
750        };
751        check_vectors(descriptor, &vectors, texts.len(), dims)?;
752        Ok(VisionOutput { value: vectors, calls: vec![record] })
753    }
754
755    /// Edits a source image with the edit route's backend and stores the result with
756    /// `Provenance::Derived`, under the context's media scope.
757    ///
758    /// # Errors
759    ///
760    /// [`VisionError::InvalidInput`] without a media store or a media scope, as
761    /// [`detect_with`](Self::detect_with) otherwise.
762    pub async fn edit(
763        &self,
764        cx: &VisionCx,
765        image: &SourceImage,
766        operation: &EditOp,
767        options: &CallOptions,
768    ) -> Result<VisionOutput<Edited>> {
769        let store = self.store.as_ref().ok_or_else(|| {
770            VisionError::InvalidInput("edits are stored; give the runtime a media store".into())
771        })?;
772        let scope = cx.media_scope().ok_or_else(|| {
773            VisionError::InvalidInput("edits are stored; give the context a media scope".into())
774        })?;
775        let route = self.route_for(VisionTask::Edit, options, self.editors.default_id())?;
776        let (descriptor, backend) = self.editors.get(&route.primary)?;
777        let sent = planned_size(image.size(), None, &descriptor.limits);
778        let hold = self
779            .preflight(cx, VisionTask::Edit, descriptor, &[sent], 0, None, options.image_unit())
780            .await?;
781        let prepared =
782            self.prepare(cx, descriptor, backend.is_remote(), image, None, options).await?;
783        let work = match (backend, &prepared) {
784            (Backend::Local(b), Prepared::Local(s)) => b.edit(cx, s, operation),
785            (Backend::Remote(b), Prepared::Remote(r)) => b.edit(cx, r, operation),
786            _ => return Err(mismatch(descriptor)),
787        };
788        let inputs = Inputs::of(std::slice::from_ref(&prepared));
789        let (pixels, record) =
790            self.metered(cx, VisionTask::Edit, descriptor, inputs, hold, work).await?;
791        let operation_digest = Digest::of_json(&serde_json::json!({
792            "op": operation,
793            "chain": prepared.image().chain(),
794        }));
795        let provenance = Provenance::Derived { from: image.digest(), operation: operation_digest };
796        let (stored, source) = store.put_pixels(scope, pixels, provenance).await?;
797        tracing::info!(
798            edit.input = %image.digest(),
799            edit.operation = %operation_digest,
800            edit.output = %stored.digest,
801            "image edited"
802        );
803        Ok(VisionOutput { value: Edited { image: stored, source }, calls: vec![record] })
804    }
805}
806
807fn escalation_options(escalation: &Escalation, options: &CallOptions) -> CallOptions {
808    let mut esc = options.clone();
809    esc.route = None;
810    if let Some(class) = &escalation.data_class {
811        esc.data_class = Some(class.clone());
812    }
813    esc
814}
815
816fn local_images(descriptor: &BackendDescriptor, prepared: Vec<Prepared>) -> Result<Vec<SentImage>> {
817    prepared
818        .into_iter()
819        .map(|p| match p {
820            Prepared::Local(image) => Ok(image),
821            Prepared::Remote(_) => Err(mismatch(descriptor)),
822        })
823        .collect()
824}
825
826fn released_images(
827    descriptor: &BackendDescriptor,
828    prepared: Vec<Prepared>,
829) -> Result<Vec<crate::egress::ReleasedImage>> {
830    prepared
831        .into_iter()
832        .map(|p| match p {
833            Prepared::Remote(released) => Ok(*released),
834            Prepared::Local(_) => Err(mismatch(descriptor)),
835        })
836        .collect()
837}
838
839fn check_vectors(
840    descriptor: &BackendDescriptor,
841    vectors: &[Vec<f32>],
842    expected: usize,
843    dims: usize,
844) -> Result<()> {
845    let parse =
846        |message: String| VisionError::Parse { backend: descriptor.id.to_string(), message };
847    if vectors.len() != expected {
848        return Err(parse(format!("{} vectors for {expected} inputs", vectors.len())));
849    }
850    if let Some(v) = vectors.iter().find(|v| v.len() != dims) {
851        return Err(parse(format!(
852            "a {}-dimensional vector in a {dims}-dimensional space",
853            v.len()
854        )));
855    }
856    Ok(())
857}
858
859/// Maps segmentation prompts from source pixels into the backend's frame.
860fn prompts_for(
861    descriptor: &BackendDescriptor,
862    image: &SentImage,
863    prompts: &[SegmentPrompt],
864) -> Result<Vec<SegmentPrompt>> {
865    let chain = image.chain();
866    let sent = image.size();
867    let frame = descriptor.frame;
868    let to_frame = |p: [f32; 2]| {
869        let s = chain.to_target([f64::from(p[0]), f64::from(p[1])]);
870        let f = frame.point_from_sent(s, sent);
871        [f[0] as f32, f[1] as f32]
872    };
873    prompts
874        .iter()
875        .map(|prompt| {
876            Ok(match prompt {
877                SegmentPrompt::Concept { text } => SegmentPrompt::Concept { text: text.clone() },
878                SegmentPrompt::Point { at, positive } => {
879                    SegmentPrompt::Point { at: to_frame(*at), positive: *positive }
880                }
881                SegmentPrompt::Box { bbox } => {
882                    let s = chain.bbox_to_target(bbox);
883                    let a = frame.point_from_sent([f64::from(s.x0), f64::from(s.y0)], sent);
884                    let b = frame.point_from_sent([f64::from(s.x1), f64::from(s.y1)], sent);
885                    SegmentPrompt::Box { bbox: BBox::new(a[0] as f32, a[1] as f32, b[0] as f32, b[1] as f32) }
886                }
887                SegmentPrompt::Mask { mask } => {
888                    let Shape::Mask(in_sent) = chain.shape_to_target(&Shape::Mask(mask.clone()))? else {
889                        return Err(VisionError::InvalidInput("a mask prompt did not map to a mask".into()));
890                    };
891                    let mask = match frame.mask_raster(sent) {
892                        Some(raster) if raster == sent => in_sent,
893                        Some(raster) => resample(
894                            &in_sent,
895                            raster,
896                            |p| frame.point_to_sent(p, sent),
897                            |p| frame.point_from_sent(p, sent),
898                        ),
899                        None => {
900                            return Err(VisionError::Unsupported(format!(
901                                "backend `{}` answers in a frame with no raster, so it takes no mask prompt",
902                                descriptor.id
903                            )));
904                        }
905                    };
906                    SegmentPrompt::Mask { mask }
907                }
908            })
909        })
910        .collect()
911}
912
913/// Maps a page's blocks, words and cells to source pixels, dropping those outside the image
914/// and renumbering the reading order.
915fn normalize_page(
916    normalizer: &RegionNormalizer,
917    raw: DocumentPage<RawRegion>,
918) -> Result<DocumentPage> {
919    let mut index_map = Vec::with_capacity(raw.blocks.len());
920    let mut blocks = Vec::with_capacity(raw.blocks.len());
921    for block in raw.blocks {
922        let Some(region) = normalizer.region(block.region)? else {
923            index_map.push(None);
924            continue;
925        };
926        let mut words = Vec::with_capacity(block.words.len());
927        for word in block.words {
928            if let Some(region) = normalizer.region(word.region)? {
929                words.push(Word { region, text: word.text, confidence: word.confidence });
930            }
931        }
932        let mut cells = Vec::with_capacity(block.cells.len());
933        for cell in block.cells {
934            if let Some(region) = normalizer.region(cell.region)? {
935                cells.push(TableCell {
936                    region,
937                    row: cell.row,
938                    col: cell.col,
939                    row_span: cell.row_span,
940                    col_span: cell.col_span,
941                    text: cell.text,
942                });
943            }
944        }
945        index_map.push(Some(blocks.len()));
946        blocks.push(Block {
947            kind: block.kind,
948            region,
949            text: block.text,
950            confidence: block.confidence,
951            words,
952            cells,
953        });
954    }
955    let reading_order =
956        raw.reading_order.iter().filter_map(|&i| index_map.get(i).copied().flatten()).collect();
957    Ok(DocumentPage { blocks, reading_order, markdown: raw.markdown })
958}
959
960/// An escalation the egress gate refused — a deny rule, an unlisted host, the on-device
961/// profile — leaves the primary's answer standing; the gate has recorded the refusal and its
962/// reason. A hold is not a refusal: it stops the call until a person decides.
963fn escalation_refused(escalation: &Escalation, err: &VisionError) {
964    tracing::warn!(
965        vision.backend = %escalation.backend,
966        error = %err,
967        "escalation refused at the egress gate, the on-device answer stands"
968    );
969}