1use 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
47pub const MODEL_CONTEXT_CLASS: &str = "model_context";
49
50pub 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#[derive(Clone, Debug, Default, PartialEq, Eq)]
90#[non_exhaustive]
91pub struct GateOutcome {
92 pub released: Vec<Digest>,
94 pub withheld: Vec<(Option<Digest>, String)>,
96}
97
98impl GateOutcome {
99 pub fn changed(&self) -> bool {
101 !self.released.is_empty() || !self.withheld.is_empty()
102 }
103}
104
105impl ImagePrivacyGuardrail {
106 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 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 pub fn with_data_class(mut self, class: &str) -> Self {
152 self.data_class = DataClass::new(class);
153 self
154 }
155
156 pub fn with_audit(mut self, trail: adk_core::audit_log::AuditTrail) -> Self {
158 self.audit = Some(trail);
159 self
160 }
161
162 pub fn guards(&self) -> bool {
164 self.locality.leaves_machine()
165 }
166
167 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 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 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
308fn 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
333fn 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 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
418pub 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
439pub 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 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 #[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 pub fn with_pii(mut self, pii: PiiRedactor) -> Self {
549 self.pii = pii;
550 self
551 }
552
553 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 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 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
604fn 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
621fn 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}