use super::classification::{CATEGORIES, QUALIFIERS};
use crate::error::ErrorCode;
use crate::models::{
Asset, DetectedFace, DetectedLink, DetectedPerson, DetectedQrCode, TextRegion,
};
use crate::{Error, Result};
use serde_json::{json, Map, Value};
use std::{fmt, str::FromStr};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum MockOutcome {
Pending,
Failed,
Allowed,
Limited,
AgeRestricted,
Blocked,
Purged,
}
const OUTCOMES: [MockOutcome; 7] = [
MockOutcome::Pending,
MockOutcome::Failed,
MockOutcome::Allowed,
MockOutcome::Limited,
MockOutcome::AgeRestricted,
MockOutcome::Blocked,
MockOutcome::Purged,
];
impl MockOutcome {
pub fn as_str(self) -> &'static str {
match self {
Self::Pending => "pending",
Self::Failed => "failed",
Self::Allowed => "allowed",
Self::Limited => "limited",
Self::AgeRestricted => "age-restricted",
Self::Blocked => "blocked",
Self::Purged => "purged",
}
}
pub fn is_decided(self) -> bool {
!matches!(self, Self::Pending | Self::Failed)
}
fn action(self) -> &'static str {
match self {
Self::Limited => "limit",
Self::AgeRestricted => "age-restrict",
Self::Blocked => "block",
Self::Purged => "purge",
_ => "allow",
}
}
}
impl fmt::Display for MockOutcome {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for MockOutcome {
type Err = Error;
fn from_str(value: &str) -> Result<Self> {
OUTCOMES
.into_iter()
.find(|outcome| outcome.as_str() == value)
.ok_or_else(|| {
let known: Vec<&str> = OUTCOMES.iter().map(|outcome| outcome.as_str()).collect();
invalid_argument(format!("status must be one of {}", known.join(", ")))
})
}
}
fn invalid_argument(message: impl Into<String>) -> Error {
Error::new(ErrorCode::InvalidArgument, message)
}
fn likelihood(score: f64) -> &'static str {
if score >= 0.8 {
"very-likely"
} else if score >= 0.6 {
"likely"
} else if score >= 0.4 {
"possible"
} else if score >= 0.2 {
"unlikely"
} else {
"very-unlikely"
}
}
fn known_category(category: &str) -> Result<&'static str> {
CATEGORIES
.iter()
.find(|known| **known == category)
.copied()
.ok_or_else(|| invalid_argument(format!("{category} is not a CalmLens category")))
}
fn is_score(score: f64) -> bool {
score.is_finite() && (0.0..=1.0).contains(&score)
}
#[derive(Clone, Debug, PartialEq)]
struct PendingReview {
reason: &'static str,
uncertain_categories: Vec<&'static str>,
}
#[derive(Clone, Debug, PartialEq)]
struct Flag {
category: &'static str,
score: f64,
qualifiers: Vec<(&'static str, f64)>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct MockDecision {
status: MockOutcome,
flags: Vec<Flag>,
not_evaluated: Vec<&'static str>,
pending_review: Option<PendingReview>,
ocr: Option<(Option<String>, Value)>,
link_detection: Option<Value>,
people: Option<Value>,
faces: Option<Value>,
}
impl From<MockOutcome> for MockDecision {
fn from(status: MockOutcome) -> Self {
Self::new(status)
}
}
impl MockDecision {
pub fn new(status: MockOutcome) -> Self {
Self {
status,
flags: Vec::new(),
not_evaluated: Vec::new(),
pending_review: None,
ocr: None,
link_detection: None,
people: None,
faces: None,
}
}
pub fn status(&self) -> MockOutcome {
self.status
}
pub fn flag(mut self, category: &str, score: f64, qualifiers: &[(&str, f64)]) -> Result<Self> {
let category = self.check_new(category)?;
if !is_score(score) {
return Err(invalid_argument(format!(
"{category}'s score must be from 0 to 1"
)));
}
let known = QUALIFIERS
.iter()
.find(|(name, _)| *name == category)
.map_or(&[][..], |(_, qualifiers)| qualifiers);
let mut checked: Vec<(&'static str, f64)> = Vec::with_capacity(qualifiers.len());
for &(qualifier, qualifier_score) in qualifiers {
let Some(&qualifier) = known.iter().find(|known| **known == qualifier) else {
return Err(invalid_argument(format!(
"{qualifier} is not a qualifier of {category}"
)));
};
if !is_score(qualifier_score) {
return Err(invalid_argument(format!(
"{qualifier}'s score must be from 0 to 1"
)));
}
if checked.iter().any(|(seen, _)| *seen == qualifier) {
return Err(invalid_argument(format!("{qualifier} is listed twice")));
}
checked.push((qualifier, qualifier_score));
}
self.flags.push(Flag {
category,
score,
qualifiers: checked,
});
Ok(self)
}
pub fn not_evaluated(mut self, category: &str) -> Result<Self> {
let category = self.check_new(category)?;
self.not_evaluated.push(category);
Ok(self)
}
pub fn pending_review(mut self, reason: &str, uncertain_categories: &[&str]) -> Result<Self> {
if !self.status.is_decided() {
return Err(invalid_argument(format!(
"a {} decision can't wait for review",
self.status
)));
}
let reason = match reason {
"sampled" if !uncertain_categories.is_empty() => {
return Err(invalid_argument(
"a sampled review has no uncertain categories",
));
}
"sampled" => "sampled",
"uncertain" => "uncertain",
_ => return Err(invalid_argument("reason must be sampled or uncertain")),
};
let uncertain_categories = uncertain_categories
.iter()
.map(|category| known_category(category))
.collect::<Result<_>>()?;
self.pending_review = Some(PendingReview {
reason,
uncertain_categories,
});
Ok(self)
}
pub fn with_ocr(mut self, text: Option<&str>, text_regions: &[TextRegion]) -> Self {
let regions = serde_json::to_value(text_regions).unwrap_or_else(|_| json!([]));
self.ocr = Some((text.map(str::to_owned), regions));
self
}
pub fn with_link_detection(
mut self,
qr_codes: &[DetectedQrCode],
links: &[DetectedLink],
) -> Self {
self.link_detection = Some(json!({
"qrCodes": serde_json::to_value(qr_codes).unwrap_or_else(|_| json!([])),
"links": serde_json::to_value(links).unwrap_or_else(|_| json!([])),
}));
self
}
pub fn with_person_detection(mut self, people: &[DetectedPerson]) -> Self {
self.people = Some(serde_json::to_value(people).unwrap_or_else(|_| json!([])));
self
}
pub fn with_face_detection(mut self, faces: &[DetectedFace]) -> Self {
self.faces = Some(serde_json::to_value(faces).unwrap_or_else(|_| json!([])));
self
}
pub(crate) fn person_findings(&self) -> Option<&Value> {
self.people.as_ref()
}
pub(crate) fn face_findings(&self) -> Option<&Value> {
self.faces.as_ref()
}
pub(crate) fn ocr_findings(&self) -> Option<&(Option<String>, Value)> {
self.ocr.as_ref()
}
pub(crate) fn link_findings(&self) -> Option<&Value> {
self.link_detection.as_ref()
}
fn check_new(&self, category: &str) -> Result<&'static str> {
let known = known_category(category)?;
if !self.status.is_decided() {
return Err(invalid_argument(format!(
"a {} decision has no findings",
self.status
)));
}
if self.not_evaluated.contains(&known) || self.flags.iter().any(|f| f.category == known) {
return Err(invalid_argument(format!(
"{known} is already in this decision"
)));
}
Ok(known)
}
fn score_of(&self, category: &str) -> f64 {
self.flags
.iter()
.find(|flag| flag.category == category)
.map_or(0.0, |flag| flag.score)
}
pub(super) fn flagged_categories(&self) -> Vec<&'static str> {
CATEGORIES
.iter()
.copied()
.filter(|category| !self.not_evaluated.contains(category))
.filter(|category| self.action(self.score_of(category)) != "allow")
.collect()
}
fn action(&self, score: f64) -> &'static str {
if self.status != MockOutcome::Allowed && score >= 0.5 {
self.status.action()
} else {
"allow"
}
}
pub(super) fn report(&self, requested_at: u64) -> Option<Map<String, Value>> {
if !self.status.is_decided() {
return None;
}
let evaluated: Vec<(&str, f64)> = CATEGORIES
.iter()
.filter(|category| !self.not_evaluated.contains(category))
.map(|category| (*category, self.score_of(category)))
.collect();
let mut categories = Map::new();
for category in CATEGORIES {
let result = if self.not_evaluated.contains(category) {
json!({"status": "not-evaluated", "reason": "not-supported"})
} else {
let score = self.score_of(category);
let flag = self.flags.iter().find(|flag| flag.category == *category);
let mut result = json!({
"status": "evaluated", "likelihood": likelihood(score), "score": score,
});
if let Some(flag) = flag.filter(|flag| !flag.qualifiers.is_empty()) {
result["qualifiers"] = flag
.qualifiers
.iter()
.map(|(qualifier, some_score)| {
let result = json!({
"status": "evaluated", "someScore": some_score,
"likelihood": likelihood(*some_score),
});
((*qualifier).to_owned(), result)
})
.collect::<Map<String, Value>>()
.into();
}
result
};
categories.insert((*category).to_owned(), result);
}
let policy_categories: Map<String, Value> = evaluated
.iter()
.map(|(category, score)| {
let action = self.action(*score);
let source = if *score >= 0.5 {
"default"
} else {
"below-threshold"
};
(
(*category).to_owned(),
json!({
"score": score, "action": action, "source": {"kind": source},
"settings": {
"action": self.status.action(), "allowances": [], "restrictions": [],
},
}),
)
})
.collect();
let mut report = Map::new();
report.insert(
"raw".into(),
json!({"categories": categories, "hashMatches": []}),
);
report.insert("categories".into(), policy_categories.into());
report.insert("explanationComplete".into(), true.into());
report.insert("policy".into(), Value::Null);
report.insert(
"pendingReview".into(),
self.pending_review.as_ref().map_or(Value::Null, |review| {
json!({
"requestedAt": requested_at, "reason": review.reason,
"uncertainCategories": review.uncertain_categories,
})
}),
);
report.insert("source".into(), "policy".into());
report.insert("rule".into(), Value::Null);
report.insert("automatedStatus".into(), self.status.as_str().into());
report.insert("regions".into(), json!([]));
report.insert("linkSafety".into(), Value::Null);
report.insert("timeline".into(), Value::Null);
report.insert("flaggedCategories".into(), json!(self.flagged_categories()));
Some(report)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum MockModerationTrigger {
Upload,
Retry,
Complete,
}
impl MockModerationTrigger {
pub fn as_str(self) -> &'static str {
match self {
Self::Upload => "upload",
Self::Retry => "retry",
Self::Complete => "complete",
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct MockModerationContent {
pub bytes: Option<Vec<u8>>,
pub text: Option<String>,
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct MockModerationInput {
pub asset: Asset,
pub content: MockModerationContent,
pub trigger: MockModerationTrigger,
pub queued: bool,
}
impl MockModerationInput {
pub fn default_decision(&self) -> MockDecision {
if self.queued && self.trigger != MockModerationTrigger::Complete {
MockOutcome::Pending.into()
} else {
MockOutcome::Allowed.into()
}
}
}
pub trait IntoMockDecision {
fn into_mock_decision(self) -> Result<MockDecision>;
}
impl IntoMockDecision for MockDecision {
fn into_mock_decision(self) -> Result<MockDecision> {
Ok(self)
}
}
impl IntoMockDecision for MockOutcome {
fn into_mock_decision(self) -> Result<MockDecision> {
Ok(self.into())
}
}
impl<T: IntoMockDecision> IntoMockDecision for Result<T> {
fn into_mock_decision(self) -> Result<MockDecision> {
self?.into_mock_decision()
}
}