fauna-api 1.0.783

The Fauna SDK for Rust: accounts, Drive, groups, calendar, chats, payments, Parrot and live rooms.
Documentation
use std::collections::HashMap;
use std::ops::{Deref, DerefMut};

use serde_json::{Map, Value};

use super::graph::Stimuli;
use crate::error::Result;
use crate::parrot::format::{CategoricalFormat, Format};

// Phoenix discrete heads from home-mixer/params/param.rs (product words).
// Field names in comments. Skip post_unexplored and continuous dwell seconds.

const X_INSTRUCTION: &str = "You are a viewer on X For You. Phoenix predicts the probability of each action below. Pick the one action you would take. Favorite is Like. Copy link, reply, quote, and share via DM are the strong positive heads. Report, mute, block, and not interested are the negative heads. Did not dwell means you skip the card.";

pub const X_ACTIONS: [&str; 22] = [
    "Did not dwell",
    "Dwell",
    "Like",
    "Reply",
    "Repost",
    "Quote",
    "Photo expand",
    "Video open",
    "Video quality view",
    "Click",
    "Open link",
    "Quoted click",
    "Quoted video view",
    "Profile",
    "Follow",
    "Share",
    "Share via DM",
    "Copy link",
    "Not interested",
    "Mute",
    "Block",
    "Report",
];

/// Phoenix default weights (param.rs). Copy link is the tile max.
pub const X_WEIGHTS: [(&str, f64); 22] = [
    ("Did not dwell", -0.02),
    ("Dwell", 0.05),
    ("Like", 0.5),
    ("Reply", 5.0),
    ("Repost", 1.0),
    ("Quote", 5.0),
    ("Photo expand", 0.05),
    ("Video open", 0.07),
    ("Video quality view", 0.0),
    ("Click", 0.4),
    ("Open link", 0.2),
    ("Quoted click", 0.05),
    ("Quoted video view", 0.0),
    ("Profile", 0.0),
    ("Follow", 4.0),
    ("Share", 2.0),
    ("Share via DM", 5.0),
    ("Copy link", 20.0),
    ("Not interested", -43.2),
    ("Mute", -58.8),
    ("Block", -31.2),
    ("Report", -234.0),
];

const LINKEDIN_INSTRUCTION: &str = "You are a member in the LinkedIn feed. Feed SR predicts skip, click, and long dwell on one tower and like, comment, and share on the other. Those scores are blended to rank the post. Pick the one action you would take. Long dwell means you stay past the type threshold. Skip means you scroll past. Weights below are ours, not LinkedIn production numbers.";

pub const LINKEDIN_ACTIONS: [&str; 6] = ["Skip", "Click", "Long dwell", "Like", "Comment", "Share"];

/// Not official. Feed SR does not publish numbers. Share is the tile max.
pub const LINKEDIN_WEIGHTS: [(&str, f64); 6] = [
    ("Skip", 0.0),
    ("Click", 1.0),
    ("Like", 1.0),
    ("Long dwell", 2.0),
    ("Comment", 2.0),
    ("Share", 3.0),
];

fn max_weight(weights: &[(&str, f64)]) -> f64 {
    weights
        .iter()
        .map(|(_, weight)| *weight)
        .fold(0.0, f64::max)
}

/// Phoenix style: Σ w_a * (count_a / n). Signed. Empty bucket is NaN.
fn score(weights: &[(&str, f64)], counts: &HashMap<String, f64>) -> f64 {
    let mut n = 0.0;
    let mut sum = 0.0;
    for (label, weight) in weights {
        let count = counts.get(*label).copied().unwrap_or(0.0);
        n += count;
        sum += weight * count;
    }
    if n == 0.0 { f64::NAN } else { sum / n }
}

fn with_type(json: Value, kind: &str, weights: &[(&str, f64)]) -> Value {
    let Value::Object(mut fields) = json else {
        return json;
    };
    fields.insert("type".to_string(), Value::from(kind));
    fields.insert(
        "weights".to_string(),
        Value::Object(
            weights
                .iter()
                .map(|(label, weight)| (label.to_string(), Value::from(*weight)))
                .collect::<Map<String, Value>>(),
        ),
    );
    Value::Object(fields)
}

/// A feed format: a categorical question over a platform's actions, each action weighted.
pub enum AntFormat {
    X(XFormat),
    LinkedIn(LinkedInFormat),
}

/// `Format<any>` in the TypeScript SDK as `AntFormat.fromJSON` returns it: a feed
/// format, or any Parrot format. Cloning copies the question and its answer.
pub enum AntFormatOrFormat {
    Ant(AntFormat),
    Format(Format),
}

impl AntFormatOrFormat {
    pub fn to_json(&self) -> Value {
        match self {
            AntFormatOrFormat::Ant(AntFormat::X(format)) => format.to_json(),
            AntFormatOrFormat::Ant(AntFormat::LinkedIn(format)) => format.to_json(),
            AntFormatOrFormat::Format(format) => format.to_json(),
        }
    }
}

impl Clone for AntFormatOrFormat {
    fn clone(&self) -> Self {
        AntFormat::from_json(&self.to_json()).expect("a format reads its own JSON")
    }
}

impl AntFormat {
    pub fn weights(&self) -> &'static [(&'static str, f64)] {
        match self {
            AntFormat::X(_) => &X_WEIGHTS,
            AntFormat::LinkedIn(_) => &LINKEDIN_WEIGHTS,
        }
    }

    pub fn max_weight(&self) -> f64 {
        max_weight(self.weights())
    }

    /// Phoenix style: Σ w_a * (count_a / n). Signed. Empty bucket is NaN.
    pub fn score(&self, counts: &HashMap<String, f64>) -> f64 {
        score(self.weights(), counts)
    }

    pub fn from_json(json: &Value) -> Result<AntFormatOrFormat> {
        let answer = json["answer"].as_str().map(str::to_string);
        match json["type"].as_str() {
            Some("x") => {
                let mut format = XFormat::new();
                if let Some(answer) = answer {
                    format.answer(answer);
                }
                Ok(AntFormatOrFormat::Ant(AntFormat::X(format)))
            }
            Some("linkedin") => {
                let mut format = LinkedInFormat::new();
                if let Some(answer) = answer {
                    format.answer(answer);
                }
                Ok(AntFormatOrFormat::Ant(AntFormat::LinkedIn(format)))
            }
            _ => Ok(AntFormatOrFormat::Format(Format::from_json(json)?)),
        }
    }

    pub fn for_kind(kind: Stimuli) -> Vec<AntFormat> {
        match kind {
            Stimuli::X => vec![AntFormat::X(XFormat::new())],
            Stimuli::Linkedin => vec![AntFormat::LinkedIn(LinkedInFormat::new())],
            _ => Vec::new(),
        }
    }
}

pub struct XFormat(CategoricalFormat);

impl Deref for XFormat {
    type Target = CategoricalFormat;
    fn deref(&self) -> &CategoricalFormat {
        &self.0
    }
}

impl DerefMut for XFormat {
    fn deref_mut(&mut self) -> &mut CategoricalFormat {
        &mut self.0
    }
}

impl Default for XFormat {
    fn default() -> Self {
        XFormat::new()
    }
}

impl XFormat {
    pub fn new() -> XFormat {
        XFormat(CategoricalFormat::new(
            X_INSTRUCTION,
            X_ACTIONS.iter().map(|action| action.to_string()).collect(),
        ))
    }

    pub fn weights(&self) -> &'static [(&'static str, f64)] {
        &X_WEIGHTS
    }

    pub fn max_weight(&self) -> f64 {
        max_weight(&X_WEIGHTS)
    }

    pub fn score(&self, counts: &HashMap<String, f64>) -> f64 {
        score(&X_WEIGHTS, counts)
    }

    #[allow(clippy::should_implement_trait)]
    pub fn clone(&self) -> XFormat {
        XFormat::new()
    }

    pub fn to_json(&self) -> Value {
        with_type(self.0.to_json(), "x", &X_WEIGHTS)
    }
}

pub struct LinkedInFormat(CategoricalFormat);

impl Deref for LinkedInFormat {
    type Target = CategoricalFormat;
    fn deref(&self) -> &CategoricalFormat {
        &self.0
    }
}

impl DerefMut for LinkedInFormat {
    fn deref_mut(&mut self) -> &mut CategoricalFormat {
        &mut self.0
    }
}

impl Default for LinkedInFormat {
    fn default() -> Self {
        LinkedInFormat::new()
    }
}

impl LinkedInFormat {
    pub fn new() -> LinkedInFormat {
        LinkedInFormat(CategoricalFormat::new(
            LINKEDIN_INSTRUCTION,
            LINKEDIN_ACTIONS
                .iter()
                .map(|action| action.to_string())
                .collect(),
        ))
    }

    pub fn weights(&self) -> &'static [(&'static str, f64)] {
        &LINKEDIN_WEIGHTS
    }

    pub fn max_weight(&self) -> f64 {
        max_weight(&LINKEDIN_WEIGHTS)
    }

    pub fn score(&self, counts: &HashMap<String, f64>) -> f64 {
        score(&LINKEDIN_WEIGHTS, counts)
    }

    #[allow(clippy::should_implement_trait)]
    pub fn clone(&self) -> LinkedInFormat {
        LinkedInFormat::new()
    }

    pub fn to_json(&self) -> Value {
        with_type(self.0.to_json(), "linkedin", &LINKEDIN_WEIGHTS)
    }
}