Skip to main content

adk_vision/
guardrail.rs

1//! [`ImagePrivacyGuardrail`] and [`PersonalTextRedactor`] (spec 3.7 §7.8, feature
2//! `guardrail`).
3//!
4//! The egress gate guards what the vision tools send. The guardrail runs the same gate on
5//! every other path an image could take to a remote model the framework controls:
6//!
7//! | Path | Hook | What happens to an image |
8//! |------|------|--------------------------|
9//! | Model calls | [`ImagePrivacyGuardrail::before_model_callback`] | Every image part in the request — user uploads, tool-result images — is released through the gate, or replaced by a text placeholder that says why |
10//! | Tool results | [`ToolGuardrail::validate_result`] | A base64 image in a tool's JSON result, such as a screenshot, is replaced by its released copy or a placeholder |
11//! | User input | [`Guardrail::validate`] | As for model calls, returned as `Transform` |
12//!
13//! An image the gate already released passes through: its part carries the release
14//! annotation and its bytes hash to a digest the gate released. A model that runs on the
15//! device (`Llm::data_locality()` is not `Remote`) is not guarded, since nothing leaves.
16//! User code that calls an `Llm` directly, without the guardrail, is outside this guarantee.
17//!
18//! [`PersonalTextRedactor`] finds the personal text the gate covers: words a local
19//! [`DocumentReader`] reads that `adk_guardrail::PiiRedactor`'s patterns match (email,
20//! phone, SSN, card number), and the values of labelled fields such as `Name:`.
21
22use std::sync::Arc;
23
24use adk_core::{
25    BeforeModelCallback, BeforeModelResult, CallbackContext, Content, DataLocality, Llm, Part,
26};
27use adk_guardrail::{
28    Guardrail, GuardrailResult, PiiRedactor, ToolGuardrail, ToolGuardrailResult,
29    ToolResultGuardrailResult,
30};
31use async_trait::async_trait;
32use base64::Engine as _;
33use base64::engine::general_purpose::STANDARD;
34use serde_json::Value;
35
36use crate::backend::{BackendDescriptor, Locality};
37use crate::cx::VisionCx;
38use crate::digest::Digest;
39use crate::egress::{DataClass, EgressGate, RedactionClass, Redactor, ReleaseRequest};
40use crate::error::Result;
41use crate::geometry::{BBox, CoordFrame, RawRegion};
42use crate::media::{DecodeLimits, MediaScope, SourceImage};
43use crate::redact::{OnDevice, fit_on_device, to_image_boxes};
44use crate::sent::SentImage;
45use crate::traits::{Block, DocumentReader, ReadOptions};
46
47/// The data class images bound for a remote model's context are released as.
48pub const MODEL_CONTEXT_CLASS: &str = "model_context";
49
50/// Runs the egress gate on every image the framework sends to a remote model.
51///
52/// # Example
53///
54/// ```
55/// use std::sync::Arc;
56/// use adk_core::egress::EgressPolicy;
57/// use adk_vision::{
58///     EgressConfig, EgressGate, ImagePrivacyGuardrail, InMemoryEgressRecorder,
59/// };
60///
61/// let gate = Arc::new(EgressGate::new(
62///     EgressPolicy::allow_private_networks(),
63///     EgressConfig::default(),
64///     Arc::new(InMemoryEgressRecorder::new()),
65/// ));
66/// let guardrail = ImagePrivacyGuardrail::new(gate, "claude", ["api.anthropic.com"]);
67/// assert!(guardrail.guards());
68/// ```
69pub struct ImagePrivacyGuardrail {
70    gate: Arc<EgressGate>,
71    destination: BackendDescriptor,
72    data_class: DataClass,
73    locality: DataLocality,
74    limits: DecodeLimits,
75    audit: Option<adk_core::audit_log::AuditTrail>,
76}
77
78impl std::fmt::Debug for ImagePrivacyGuardrail {
79    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80        f.debug_struct("ImagePrivacyGuardrail")
81            .field("destination", &self.destination.locality)
82            .field("data_class", &self.data_class)
83            .field("locality", &self.locality)
84            .finish_non_exhaustive()
85    }
86}
87
88/// What gating one content changed.
89#[derive(Clone, Debug, Default, PartialEq, Eq)]
90#[non_exhaustive]
91pub struct GateOutcome {
92    /// Egress digests of the images released.
93    pub released: Vec<Digest>,
94    /// Source digests of the images withheld, with why.
95    pub withheld: Vec<(Option<Digest>, String)>,
96}
97
98impl GateOutcome {
99    /// Whether any image was released or withheld.
100    pub fn changed(&self) -> bool {
101        !self.released.is_empty() || !self.withheld.is_empty()
102    }
103}
104
105impl ImagePrivacyGuardrail {
106    /// A guardrail releasing images through `gate` to a remote model named `model` at
107    /// `hosts`, as data class `model_context`.
108    pub fn new(
109        gate: Arc<EgressGate>,
110        model: impl Into<String>,
111        hosts: impl IntoIterator<Item = impl Into<String>>,
112    ) -> Self {
113        let hosts = hosts.into_iter().map(Into::into).collect();
114        Self {
115            gate,
116            destination: BackendDescriptor::new(
117                model,
118                Locality::Remote { hosts },
119                CoordFrame::SentPixels,
120            ),
121            data_class: DataClass::new(MODEL_CONTEXT_CLASS),
122            locality: DataLocality::Remote,
123            limits: DecodeLimits::default(),
124            audit: None,
125        }
126    }
127
128    /// A guardrail for `model`, guarding only when its `data_locality()` is `Remote`.
129    ///
130    /// Images are released to `hosts`, or with none to the hosts the model names
131    /// ([`Llm::data_destinations`]); `provider` egress rules match the providers it names.
132    pub fn for_model(
133        gate: Arc<EgressGate>,
134        model: &dyn Llm,
135        hosts: impl IntoIterator<Item = impl Into<String>>,
136    ) -> Self {
137        let destinations = model.data_destinations();
138        let mut hosts: Vec<String> = hosts.into_iter().map(Into::into).collect();
139        if hosts.is_empty() {
140            hosts = adk_core::DataDestination::all_hosts(&destinations);
141        }
142        let mut guardrail = Self::new(gate, model.name(), hosts);
143        guardrail.locality = model.data_locality();
144        for destination in destinations {
145            guardrail.destination = guardrail.destination.with_provider(destination.provider);
146        }
147        guardrail
148    }
149
150    /// Releases images as `class` instead of `model_context`.
151    pub fn with_data_class(mut self, class: &str) -> Self {
152        self.data_class = DataClass::new(class);
153        self
154    }
155
156    /// Writes the `vision.egress.*` records of model-context releases to `trail` too.
157    pub fn with_audit(mut self, trail: adk_core::audit_log::AuditTrail) -> Self {
158        self.audit = Some(trail);
159        self
160    }
161
162    /// Whether the guarded model's requests leave the machine.
163    pub fn guards(&self) -> bool {
164        self.locality.leaves_machine()
165    }
166
167    /// Releases or withholds every image part of `content`, in place.
168    pub async fn gate_content(&self, cx: &VisionCx, content: &mut Content) -> GateOutcome {
169        let mut outcome = GateOutcome::default();
170        if !self.guards() {
171            return outcome;
172        }
173        for part in &mut content.parts {
174            match part {
175                Part::InlineData { mime_type, data, annotations, .. }
176                    if mime_type.starts_with("image/") =>
177                {
178                    if self.already_released(data, annotations.as_ref()) {
179                        continue;
180                    }
181                    *part = match self.release_bytes(cx, data).await {
182                        Ok(released) => {
183                            outcome.released.push(released.receipt().egress);
184                            released.to_part()
185                        }
186                        Err((source, reason)) => {
187                            outcome.withheld.push((source, reason.clone()));
188                            Part::Text { text: placeholder(source, &reason) }
189                        }
190                    };
191                }
192                Part::FunctionResponse { function_response, .. } => {
193                    let mut kept = Vec::with_capacity(function_response.inline_data.len());
194                    for inline in std::mem::take(&mut function_response.inline_data) {
195                        if !inline.mime_type.starts_with("image/")
196                            || self.already_released(&inline.data, inline.annotations.as_ref())
197                        {
198                            kept.push(inline);
199                            continue;
200                        }
201                        match self.release_bytes(cx, &inline.data).await {
202                            Ok(released) => {
203                                outcome.released.push(released.receipt().egress);
204                                let mut inline = inline;
205                                inline.data = released.bytes().to_vec();
206                                inline.mime_type = released.mime_type().to_string();
207                                kept.push(inline);
208                            }
209                            Err((source, reason)) => {
210                                note_withheld(&mut function_response.response, source, &reason);
211                                outcome.withheld.push((source, reason));
212                            }
213                        }
214                    }
215                    function_response.inline_data = kept;
216                }
217                _ => {}
218            }
219        }
220        outcome
221    }
222
223    /// The `BeforeModelCallback` that gates every image in a request to the guarded model.
224    pub fn before_model_callback(self: &Arc<Self>) -> BeforeModelCallback {
225        let guardrail = Arc::clone(self);
226        Box::new(move |ctx: Arc<dyn CallbackContext>, mut request: adk_core::LlmRequest| {
227            let guardrail = Arc::clone(&guardrail);
228            Box::pin(async move {
229                if !guardrail.guards() {
230                    return Ok(BeforeModelResult::Continue(request));
231                }
232                let acting = ctx.acting_context();
233                let mut cx = VisionCx::current()
234                    .with_media_scope(MediaScope::new(
235                        ctx.app_name(),
236                        ctx.user_id(),
237                        ctx.session_id(),
238                    ))
239                    .with_acting(acting.clone());
240                if let Some(trail) = &guardrail.audit {
241                    let actor = adk_core::audit_log::AuditActor::new(&acting, ctx.invocation_id());
242                    cx = cx.with_audit(trail.clone(), actor);
243                }
244                for content in &mut request.contents {
245                    guardrail.gate_content(&cx, content).await;
246                }
247                Ok(BeforeModelResult::Continue(request))
248            })
249        })
250    }
251
252    fn already_released(&self, data: &[u8], annotations: Option<&Value>) -> bool {
253        let released = annotations
254            .and_then(|a| a.get("adkVision"))
255            .and_then(|v| v.get("release"))
256            .is_some_and(|release| !release.is_null());
257        released && self.gate.has_released(&Digest::of(data))
258    }
259
260    async fn release_bytes(
261        &self,
262        cx: &VisionCx,
263        data: &[u8],
264    ) -> std::result::Result<crate::egress::ReleasedImage, (Option<Digest>, String)> {
265        let source = SourceImage::decode(data, &self.limits)
266            .map_err(|err| (None, format!("it could not be read on this computer: {err}")))?;
267        let request = ReleaseRequest::new(&source, &self.destination, self.data_class.clone());
268        self.gate.release(cx, request).await.map_err(|err| (Some(source.digest()), err.to_string()))
269    }
270
271    /// Releases or withholds the images inside a JSON tool result.
272    async fn gate_value(&self, cx: &VisionCx, value: &mut Value, outcome: &mut GateOutcome) {
273        match value {
274            Value::String(text) => {
275                let Some((prefix, bytes)) = embedded_image(text) else {
276                    return;
277                };
278                *text = match self.release_bytes(cx, &bytes).await {
279                    Ok(released) => {
280                        outcome.released.push(released.receipt().egress);
281                        let encoded = STANDARD.encode(released.bytes());
282                        match prefix {
283                            Some(_) => format!("data:image/png;base64,{encoded}"),
284                            None => encoded,
285                        }
286                    }
287                    Err((source, reason)) => {
288                        outcome.withheld.push((source, reason.clone()));
289                        placeholder(source, &reason)
290                    }
291                };
292            }
293            Value::Array(items) => {
294                for item in items {
295                    Box::pin(self.gate_value(cx, item, outcome)).await;
296                }
297            }
298            Value::Object(map) => {
299                for (_, item) in map.iter_mut() {
300                    Box::pin(self.gate_value(cx, item, outcome)).await;
301                }
302            }
303            _ => {}
304        }
305    }
306}
307
308/// The text a withheld image is replaced by.
309fn placeholder(source: Option<Digest>, reason: &str) -> String {
310    match source {
311        Some(digest) => format!(
312            "[image {digest} withheld from this model: {reason}. The vision tools can read it on this computer.]"
313        ),
314        None => format!("[image withheld from this model: {reason}]"),
315    }
316}
317
318fn note_withheld(response: &mut Value, source: Option<Digest>, reason: &str) {
319    let note = Value::String(placeholder(source, reason));
320    match response {
321        Value::Object(map) => {
322            let withheld = map.entry("withheldImages").or_insert_with(|| Value::Array(Vec::new()));
323            if let Value::Array(items) = withheld {
324                items.push(note);
325            }
326        }
327        other => {
328            *other = serde_json::json!({ "result": other.take(), "withheldImages": [note] });
329        }
330    }
331}
332
333/// A base64 image inside a string: a `data:image/...;base64,` URL or bare base64 that
334/// starts with a PNG, JPEG, WebP or GIF signature. Returns the data-URL prefix, if any, and
335/// the decoded bytes.
336fn embedded_image(text: &str) -> Option<(Option<&str>, Vec<u8>)> {
337    let (prefix, payload) = match text.strip_prefix("data:image/") {
338        Some(rest) => {
339            let (_, payload) = rest.split_once(";base64,")?;
340            (Some(&text[..text.len() - payload.len()]), payload)
341        }
342        None => {
343            // A bare payload: PNG, JPEG, WebP (RIFF) and GIF signatures in base64.
344            let signature = ["iVBORw0KGgo", "/9j/", "UklGR", "R0lGOD"];
345            if text.len() < 64 || !signature.iter().any(|s| text.starts_with(s)) {
346                return None;
347            }
348            (None, text)
349        }
350    };
351    let bytes = STANDARD.decode(payload.trim()).ok()?;
352    Some((prefix, bytes))
353}
354
355#[async_trait]
356impl Guardrail for ImagePrivacyGuardrail {
357    fn name(&self) -> &str {
358        "image_privacy"
359    }
360
361    async fn validate(&self, content: &Content) -> GuardrailResult {
362        let mut gated = content.clone();
363        let outcome = self.gate_content(&VisionCx::new(), &mut gated).await;
364        if !outcome.changed() {
365            return GuardrailResult::Pass;
366        }
367        GuardrailResult::Transform {
368            new_content: gated,
369            reason: format!(
370                "{} image(s) released after redaction, {} withheld",
371                outcome.released.len(),
372                outcome.withheld.len()
373            ),
374        }
375    }
376
377    fn run_parallel(&self) -> bool {
378        false
379    }
380}
381
382#[async_trait]
383impl ToolGuardrail for ImagePrivacyGuardrail {
384    fn name(&self) -> &str {
385        "image_privacy"
386    }
387
388    async fn validate_call(&self, _tool: &str, _args: &Value) -> ToolGuardrailResult {
389        ToolGuardrailResult::Allow
390    }
391
392    async fn validate_result(
393        &self,
394        _tool: &str,
395        _args: &Value,
396        result: &Value,
397    ) -> ToolResultGuardrailResult {
398        if !self.guards() {
399            return ToolResultGuardrailResult::Allow;
400        }
401        let mut gated = result.clone();
402        let mut outcome = GateOutcome::default();
403        self.gate_value(&VisionCx::new(), &mut gated, &mut outcome).await;
404        if !outcome.changed() {
405            return ToolResultGuardrailResult::Allow;
406        }
407        ToolResultGuardrailResult::revise(
408            gated,
409            format!(
410                "{} image(s) released after redaction, {} withheld",
411                outcome.released.len(),
412                outcome.withheld.len()
413            ),
414        )
415    }
416}
417
418/// The field labels whose values identify a person on identity documents and forms:
419/// `PersonalTextRedactor::with_labelled_fields` takes them as the harness vision pack's
420/// default.
421///
422/// # Example
423///
424/// ```
425/// assert!(adk_vision::PERSONAL_FIELD_LABELS.contains(&"Date of birth"));
426/// ```
427pub const PERSONAL_FIELD_LABELS: &[&str] = &[
428    "Name",
429    "Full name",
430    "Surname",
431    "Given names",
432    "Date of birth",
433    "Place of birth",
434    "Address",
435    "Email",
436    "Phone",
437];
438
439/// Finds personal text: words an on-device [`DocumentReader`] reads that
440/// `adk_guardrail::PiiRedactor`'s patterns match, and the values of labelled fields.
441///
442/// The reader's words are joined per block with single spaces, `PiiRedactor::find` returns
443/// byte ranges in that text (spec 3.7 X18), and every word a match touches is covered. A
444/// labelled field — a block whose words start with one of the labels, such as `Name` or
445/// `Date of birth`, with or without a colon — has every word after the label covered; when
446/// the reader returns the label as a block of its own, the nearest block to its right on
447/// the same line is the value and is covered whole. A block with no words is covered whole
448/// when its text matches.
449///
450/// `PersonalTextRedactor::pp_ocr` (feature `ocr`) is the default reader: PP-OCRv6 from the
451/// built-in manifest, loaded on first use.
452///
453/// # Example
454///
455/// ```
456/// use std::sync::Arc;
457/// use adk_vision::{PersonalTextRedactor, RedactionClass, Redactor};
458/// # use adk_vision::{BackendDescriptor, CoordFrame, DocumentPage, DocumentReader, Locality, RawRegion, ReadOptions, SentImage, VisionCx};
459/// # struct Blank(BackendDescriptor);
460/// # #[async_trait::async_trait]
461/// # impl DocumentReader for Blank {
462/// #     fn descriptor(&self) -> &BackendDescriptor { &self.0 }
463/// #     async fn read(&self, _: &VisionCx, _: &SentImage, _: &ReadOptions) -> adk_vision::Result<DocumentPage<RawRegion>> { Ok(DocumentPage::default()) }
464/// # }
465/// # let reader = Arc::new(Blank(BackendDescriptor::new("ocr", Locality::InProcess, CoordFrame::SentPixels)));
466///
467/// let redactor = PersonalTextRedactor::new(reader).with_labelled_fields(["Name", "Date of birth"]);
468/// assert_eq!(redactor.class(), RedactionClass::personal_text());
469/// ```
470pub struct PersonalTextRedactor {
471    reader: OnDevice<dyn DocumentReader>,
472    pii: PiiRedactor,
473    labels: Vec<Vec<String>>,
474}
475
476impl std::fmt::Debug for PersonalTextRedactor {
477    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
478        f.debug_struct("PersonalTextRedactor")
479            .field("reader", &self.reader.name())
480            .field("labels", &self.labels)
481            .finish_non_exhaustive()
482    }
483}
484
485impl PersonalTextRedactor {
486    /// Covers the words `reader` reads that `PiiRedactor::new()`'s patterns match.
487    pub fn new(reader: Arc<dyn DocumentReader>) -> Self {
488        let name = reader.descriptor().id.to_string();
489        Self { reader: OnDevice::ready(name, reader), pii: PiiRedactor::new(), labels: Vec::new() }
490    }
491
492    /// Covers the words PP-OCRv6 of `size` reads that `PiiRedactor::new()`'s patterns match:
493    /// the built-in `pp-ocrv6-{size}-det` and `-rec` manifests, fetched through `fetcher`
494    /// and verified against their SHA-256 on the redactor's first use (feature `ocr`).
495    ///
496    /// Nothing loads here. When the weights cannot be had — `HF_HUB_OFFLINE` with an empty
497    /// cache, a digest mismatch — `find` fails, and the egress gate refuses the release.
498    ///
499    /// # Example
500    ///
501    /// ```
502    /// use std::sync::Arc;
503    /// use adk_vision::{
504    ///     FetchConfig, InMemoryAcceptanceStore, ModelFetcher, PERSONAL_FIELD_LABELS,
505    ///     PersonalTextRedactor, PpOcrV6Size, RedactionClass, Redactor,
506    /// };
507    ///
508    /// let fetcher =
509    ///     ModelFetcher::new(FetchConfig::from_env(), Arc::new(InMemoryAcceptanceStore::new()));
510    /// let redactor = PersonalTextRedactor::pp_ocr(fetcher, PpOcrV6Size::Small)
511    ///     .with_labelled_fields(PERSONAL_FIELD_LABELS.iter().copied());
512    /// assert_eq!(redactor.class(), RedactionClass::personal_text());
513    /// ```
514    #[cfg(feature = "ocr")]
515    pub fn pp_ocr(fetcher: crate::ModelFetcher, size: crate::PpOcrV6Size) -> Self {
516        use crate::error::VisionError;
517        use crate::redact::{Load, Loading};
518
519        let name = size.recognition_manifest().trim_end_matches("-rec").to_string();
520        let load: Load<dyn DocumentReader> = Box::new(move || {
521            let fetcher = fetcher.clone();
522            Box::pin(async move {
523                let manifests = crate::ManifestSet::builtin()?;
524                let lookup = |id: String| {
525                    manifests.get(&id).cloned().ok_or_else(|| VisionError::Manifest {
526                        id,
527                        reason: "not in the built-in manifest".into(),
528                    })
529                };
530                let det = fetcher.fetch(&lookup(size.detection_manifest())?).await?;
531                let rec = fetcher.fetch(&lookup(size.recognition_manifest())?).await?;
532                let reader = tokio::task::spawn_blocking(move || {
533                    crate::PpOcrReader::from_models(size, &det, &rec)
534                })
535                .await
536                .map_err(|e| VisionError::Backend {
537                    backend: "pp-ocrv6".into(),
538                    message: format!("the load task failed: {e}"),
539                })??;
540                tracing::info!(vision.backend = %reader.descriptor().id, "personal text redactor loaded");
541                Ok(Arc::new(reader) as Arc<dyn DocumentReader>)
542            }) as Loading<dyn DocumentReader>
543        });
544        Self { reader: OnDevice::lazy(name, load), pii: PiiRedactor::new(), labels: Vec::new() }
545    }
546
547    /// Matches with `pii`'s patterns instead.
548    pub fn with_pii(mut self, pii: PiiRedactor) -> Self {
549        self.pii = pii;
550        self
551    }
552
553    /// Also covers the value of every field labelled with one of `labels`, such as `Name`.
554    pub fn with_labelled_fields(
555        mut self,
556        labels: impl IntoIterator<Item = impl Into<String>>,
557    ) -> Self {
558        self.labels = labels
559            .into_iter()
560            .map(|label| label.into().split_whitespace().map(normalize_word).collect())
561            .filter(|words: &Vec<String>| !words.is_empty())
562            .collect();
563        self
564    }
565
566    /// The indices of the words of one block that are personal.
567    fn personal_words(&self, words: &[String]) -> Vec<usize> {
568        let mut text = String::new();
569        let mut spans = Vec::with_capacity(words.len());
570        for word in words {
571            if !text.is_empty() {
572                text.push(' ');
573            }
574            let start = text.len();
575            text.push_str(word);
576            spans.push(start..text.len());
577        }
578        let mut personal: Vec<usize> = Vec::new();
579        for found in self.pii.find(&text) {
580            for (index, span) in spans.iter().enumerate() {
581                if span.start < found.range.end && found.range.start < span.end {
582                    personal.push(index);
583                }
584            }
585        }
586        let normalized: Vec<String> = words.iter().map(normalize_word).collect();
587        for label in &self.labels {
588            if normalized.len() > label.len() && normalized[..label.len()] == label[..] {
589                personal.extend(label.len()..words.len());
590            }
591        }
592        personal.sort_unstable();
593        personal.dedup();
594        personal
595    }
596
597    /// Whether `words` are one of the labels and nothing else.
598    fn bare_label(&self, words: &[String]) -> bool {
599        let normalized: Vec<String> = words.iter().map(normalize_word).collect();
600        self.labels.contains(&normalized)
601    }
602}
603
604/// The block holding a bare label's value: the nearest block that starts right of the label
605/// and whose vertical centre lies within the label's line.
606fn value_beside(blocks: &[Block<RawRegion>], label: usize) -> Option<usize> {
607    let line = blocks[label].region.shape.bbox()?;
608    blocks
609        .iter()
610        .enumerate()
611        .filter(|(index, _)| *index != label)
612        .filter_map(|(index, block)| Some((index, block.region.shape.bbox()?)))
613        .filter(|(_, bbox)| {
614            let centre = (bbox.y0 + bbox.y1) / 2.0;
615            centre >= line.y0 && centre <= line.y1 && bbox.x0 >= line.x1 - line.height() / 2.0
616        })
617        .min_by(|(_, a), (_, b)| a.x0.total_cmp(&b.x0))
618        .map(|(index, _)| index)
619}
620
621/// A word lowercased, without the punctuation that ends a label.
622fn normalize_word(word: impl AsRef<str>) -> String {
623    word.as_ref().trim_end_matches([':', '.', ';']).to_lowercase()
624}
625
626#[async_trait]
627impl Redactor for PersonalTextRedactor {
628    fn class(&self) -> RedactionClass {
629        RedactionClass::personal_text()
630    }
631
632    async fn find(&self, cx: &VisionCx, image: &SentImage) -> Result<Vec<BBox>> {
633        let reader = self.reader.get().await?;
634        let descriptor = reader.descriptor();
635        let fitted = fit_on_device(descriptor, image)?;
636        let page = reader.read(cx, &fitted, &ReadOptions::default()).await?;
637        let mut raw: Vec<RawRegion> = Vec::new();
638        for (index, block) in page.blocks.iter().enumerate() {
639            let texts: Vec<String> = if block.words.is_empty() {
640                block.text.split_whitespace().map(str::to_string).collect()
641            } else {
642                block.words.iter().map(|w| w.text.clone()).collect()
643            };
644            if self.bare_label(&texts) {
645                if let Some(value) = value_beside(&page.blocks, index) {
646                    raw.push(page.blocks[value].region.clone());
647                }
648                continue;
649            }
650            let personal = self.personal_words(&texts);
651            if block.words.is_empty() {
652                if !personal.is_empty() {
653                    raw.push(block.region.clone());
654                }
655                continue;
656            }
657            raw.extend(personal.into_iter().map(|i| block.words[i].region.clone()));
658        }
659        to_image_boxes(descriptor, &fitted, image, raw)
660    }
661}