Cotton code
278 lines · 14.6 KB · RustRaw
//! Photos and videos. Most of a household's photos are METADATA ONLY, as//! most of a library is on any one device: the row names an object that is not//! there. The newest few hundred are real pictures — a generated landscape//! each ([`Scene`]), its id the sha of its own bytes — handed to the media//! sink (the original, the grid thumbnail and the display rendition) when the//! caller gave one. Around them, what a library grows: captions, a trip and//! an evening kept as albums and one still suggested, faces asking who they//! are, two pictures that are the same picture, and a few films.//!//! EVERY PICTURED ROW CARRIES A PREVIEW AND A SUMMARY. Those two columns are//! what take a row off the tiers worker's and the describe worker's lists, so//! a served household neither re-renders these nor sends them to a model.use super::{call, chunked, day, id_of, iso, object, refused, Household, SYNTHETIC_LABEL};use crate::mcp::handlers::albums::create_album;use crate::mcp::handlers::common::insert_row;use crate::synthetic::names;use crate::synthetic::picture::Scene;use base64::Engine;use chrono::{DateTime, Duration, Utc};use cotton_core::media::keys;use cotton_store::protocol::derived_id;use cotton_store::{Result, StoreError};use serde_json::{json, Map, Value};use sha2::{Digest, Sha256};/// Every table written here, for the household's recount.pub(super) const TABLES: &[&str] = &[    "cotton_photos",    "cotton_videos",    "cotton_media_albums",    "cotton_media_album_items",    "cotton_media_faces",    "cotton_media_duplicates",];/// How many of the newest photos are real pictures.const PICTURED: usize = 300;/// The moments a library groups: `(photos, days back, hours apart, city)`./// A trip over three days, an evening, and an older weekend nobody has/// decided about.const MOMENTS: [(usize, i64, i64, usize); 3] = [(10, 24, 7, 1), (6, 5, 0, 0), (5, 61, 9, 2)];const CAPTIONS: &[&str] = &[    "Before the rain", "The path back", "From the top", "Low tide", "First light", "The long way round", "Nearly there",];fn sha256_hex(bytes: &[u8]) -> String {    hex::encode(Sha256::digest(bytes))}struct Photo {    taken: DateTime<Utc>,    id: String,    patch: Map<String, Value>,}impl Household<'_> {    pub(super) fn put(&self, key: &str, bytes: &[u8]) -> Result<()> {        match self.env.media {            Some(sink) => sink(key, bytes)                .map_err(|error| StoreError::refused(format!("synthetic household: writing the bytes of {key}: {error}"))),            None => Ok(()),        }    }    /// `cotton_photos` patches: id `photo:<sha>`, key `photo_key(file, sha,    /// ext)`, content_type, size_bytes, taken_at, width, height.    pub(super) fn write_photos(&mut self) -> Result<()> {        let env = &self.env;        let rng = env.rng();        let file = env.file.id();        let mut taken: Vec<(DateTime<Utc>, Option<usize>)> = (0..env.plan.photos).map(|_| (env.moment(), None)).collect();        // The moments first: their photos are minutes or hours apart, in one place.        let mut next = 0;        for (moment, (count, back, hours, _)) in MOMENTS.iter().enumerate() {            for n in 0..*count {                if let Some(slot) = taken.get_mut(next) {                    let at = env.day_at(-back, 9, 0) + Duration::hours(hours * n as i64) + Duration::minutes(11 * n as i64);                    *slot = (at.min(env.now), Some(moment));                    next += 1;                }            }        }        taken.sort_by_key(|item| std::cmp::Reverse(item.0));        // Never the whole library: some of it is always somewhere else.        let pictured = PICTURED.min(taken.len() * 3 / 4);        let mut photos: Vec<Photo> = Vec::with_capacity(taken.len());        let mut moments: Vec<Vec<String>> = vec![Vec::new(); MOMENTS.len()];        for (n, (taken, moment)) in taken.iter().enumerate() {            let landscape = rng.chance(70);            let mut patch = Map::new();            let city = match moment {                Some(moment) => Some(names::CITIES[MOMENTS[*moment].3 % names::CITIES.len()]),                None => rng.chance(60).then(|| *rng.pick(names::CITIES)),            };            if let Some((city, lat, lng, _)) = city {                patch.insert("latitude".into(), Value::from(lat + rng.between(-200, 200) as f64 / 10_000.0));                patch.insert("longitude".into(), Value::from(lng + rng.between(-200, 200) as f64 / 10_000.0));                patch.insert("place_city".into(), Value::from(city));            }            patch.insert("taken_at".into(), Value::from(iso(*taken)));            patch.insert("favourite".into(), Value::Bool(rng.chance(5)));            let sha = if n < pictured || moment.is_some() {                let scene = Scene::draw(rng);                let (width, height) = if landscape { (320, 240) } else { (240, 320) };                let bytes = scene.png(width, height);                let sha = sha256_hex(&bytes);                let key = keys::photo_key(file, &sha, "png");                self.put(&key, &bytes)?;                self.put(&keys::photo_thumb_key(file, &sha), &scene.png(width * 4 / 5, height * 4 / 5))?;                if let Some(display) = keys::display_key_for(&key) {                    self.put(&display, &bytes)?;                }                patch.insert("key".into(), Value::from(key));                patch.insert("content_type".into(), Value::from("image/png"));                patch.insert("size_bytes".into(), Value::from(bytes.len()));                patch.insert("width".into(), Value::from(width));                patch.insert("height".into(), Value::from(height));                patch.insert("original_filename".into(), Value::from(format!("IMG_{:04}.PNG", n % 10_000)));                let preview = base64::engine::general_purpose::STANDARD.encode(scene.png(width / 20, height / 20));                patch.insert("preview".into(), Value::from(preview));                patch.insert("summary".into(), Value::from("A generated landscape: a sky, a sun and a line of hills."));                patch.insert("summary_by".into(), Value::from(SYNTHETIC_LABEL));                patch.insert("summary_at".into(), Value::from(iso(*taken)));                patch.insert("phash".into(), Value::from(env.hex(16)));                if rng.chance(35) {                    patch.insert("caption".into(), Value::from(*rng.pick(CAPTIONS)));                }                sha            } else {                // Not on this device, as most of a library is not.                let sha = env.hex(64);                let (width, height) = if landscape { (4032, 3024) } else { (3024, 4032) };                patch.insert("key".into(), Value::from(keys::photo_key(file, &sha, "jpg")));                patch.insert("content_type".into(), Value::from("image/jpeg"));                patch.insert("size_bytes".into(), Value::from(rng.between(900_000, 6_000_000)));                patch.insert("width".into(), Value::from(width));                patch.insert("height".into(), Value::from(height));                patch.insert("original_filename".into(), Value::from(format!("IMG_{:04}.JPG", n % 10_000)));                sha            };            patch.insert("sha256".into(), Value::from(sha.clone()));            let id = derived_id::photo_record_id(&sha);            if let Some(moment) = moment {                moments[*moment].push(id.clone());            }            photos.push(Photo { taken: *taken, id, patch });        }        // Newest first: the pictured ones a note or a face can show.        self.photos = photos.iter().filter(|photo| photo.patch.contains_key("preview")).take(40).map(|photo| photo.id.clone()).collect();        self.moments = moments;        photos.sort_by_key(|photo| photo.taken);        // Imported a little after it was taken.        chunked(env, &mut self.counts, &photos, |photo| (photo.taken + Duration::minutes(5)).min(env.now), |ctx, photo, counts| {            insert_row(ctx, "cotton_photos", &photo.id, photo.patch.clone()).map_err(refused("photo"))?;            ctx.commit().map_err(refused("photo"))?;            counts.add("cotton_photos", 1);            Ok(())        })    }    /// Albums (`create_album` for the two kept; the suggested one is the    /// grouping pass's own row, a patch), faces and duplicates (the analysis    /// pass's rows, patches), and films (`cotton_videos` patches; a poster    /// only where there is a sink to hold its bytes).    pub(super) fn write_media_shapes(&mut self) -> Result<()> {        let env = &self.env;        let rng = env.rng();        let file = env.file.id();        let people = &self.people;        let photos = &self.photos;        let moments = &self.moments;        if moments.iter().any(Vec::is_empty) || photos.len() < 30 {            return Ok(());        }        // The posters, before the transaction that names them.        let mut films: Vec<(DateTime<Utc>, String, Map<String, Value>)> = Vec::new();        for n in 0..7i64 {            let sha = env.hex(64);            let taken = env.day_at(-(3 + 6 * n), 15, 20);            let upright = n % 3 == 0;            let (width, height) = if upright { (720, 1280) } else { (1280, 720) };            let mut patch = object(json!({                "key": keys::video_key(file, &sha, "mp4"), "sha256": sha, "content_type": "video/mp4",                "size_bytes": rng.between(4_000_000, 90_000_000), "taken_at": iso(taken),                "duration_ms": rng.between(4_000, 190_000), "width": width, "height": height,                "original_filename": format!("MOV_{:04}.MP4", 200 + n),                "summary": "A generated film with no recording behind it.", "summary_by": SYNTHETIC_LABEL, "summary_at": iso(taken),            }));            let scene = Scene::draw(rng);            let poster = scene.png(width / 4, height / 4);            patch.insert(                "preview".into(),                Value::from(base64::engine::general_purpose::STANDARD.encode(scene.png(width / 80, height / 80))),            );            if env.media.is_some() {                let key = keys::video_poster_key(file, &sha);                self.put(&key, &poster)?;                self.put(&keys::video_thumb_key(file, &sha), &poster)?;                patch.insert("poster_key".into(), Value::from(key));            }            if n < 2 {                patch.insert("caption".into(), Value::from(*rng.pick(CAPTIONS)));            }            films.push((taken, derived_id::video_record_id(&sha), patch));        }        env.once(env.now - Duration::days(1), |ctx| {            for (taken, id, patch) in &films {                ctx.now = *taken + Duration::minutes(9);                insert_row(ctx, "cotton_videos", id, patch.clone()).map_err(refused("video"))?;            }            ctx.commit().map_err(refused("video"))?;            ctx.now = env.now - Duration::days(1);            for (moment, kind, title) in [(0usize, "trip", "Four days on the coast"), (1, "event", "Dinner at ours")] {                let args = object(json!({ "kind": kind, "title": title, "photoIds": moments[moment], "coverId": moments[moment][1] }));                id_of("album", &call("album", create_album(ctx, &args))?)?;            }            // Still a suggestion: nobody has kept or dismissed it.            let (starts, ends) = (env.day_at(-61, 9, 0), env.day_at(-59, 21, 0));            let album = format!("album:trip:{}", starts.format("%Y-%m-%d"));            let row = object(json!({                "kind": "trip", "state": "open", "title": "A weekend away", "title_by": "derived",                // An album's span is days, as the albums engine writes it.                "starts_at": day(starts), "ends_at": day(ends), "cover_id": moments[2][0],            }));            insert_row(ctx, "cotton_media_albums", &album, row).map_err(refused("suggested album"))?;            ctx.commit().map_err(refused("suggested album"))?;            for (n, photo) in moments[2].iter().enumerate() {                let row = object(json!({                    "album_id": album, "record_kind": "photo", "record_id": photo, "added_by": "derived",                    "sort_at": iso(starts + Duration::hours(9 * n as i64)),                }));                insert_row(ctx, "cotton_media_album_items", &derived_id::media_album_item_id(&album, photo), row)                    .map_err(refused("suggested album"))?;            }            ctx.commit().map_err(refused("suggested album"))?;            // Faces: some the owner has named, some that look like somebody            // (closely, and not so closely), one waved away.            for (n, photo) in photos.iter().skip(6).take(9).enumerate() {                let Some(person) = people.get(n % people.len().max(1)) else { break };                let mut row = object(json!({                    "record_kind": "photo", "record_id": photo, "source": "cotton", "source_id": "0",                    "x": 0.30 + 0.04 * n as f64, "y": 0.22, "w": 0.2, "h": 0.27, "quality": 0.9, "cluster_id": format!("synthetic-cluster-{}", n % 4),                }));                match n % 4 {                    0 => {                        row.insert("person_id".into(), Value::from(person.id.clone()));                    }                    other => {                        row.insert("suggested_person_id".into(), Value::from(person.id.clone()));                        row.insert("suggested_distance".into(), Value::from(if other == 1 { 0.18 } else { 0.52 }));                        if n == 7 {                            row.insert("suggestion_dismissed_at".into(), Value::from(iso(ctx.now)));                        }                    }                }                let id = derived_id::media_face_id("photo", photo, "cotton", "0");                insert_row(ctx, "cotton_media_faces", &id, row).map_err(refused("face"))?;            }            // The same picture twice: one pair to decide, one already decided.            for (keep, copy, state) in [(20usize, 21usize, "open"), (22, 23, "open"), (24, 25, "confirmed")] {                let mut row = object(json!({                    "record_kind": "photo", "keep_id": photos[keep], "copy_id": photos[copy],                    "distance": 3, "method": "phash", "state": state,                }));                if state != "open" {                    row.insert("decided_at".into(), Value::from(iso(ctx.now)));                }                let id = derived_id::media_duplicate_id(&photos[keep], &photos[copy]);                insert_row(ctx, "cotton_media_duplicates", &id, row).map_err(refused("duplicate"))?;            }            ctx.commit().map_err(refused("duplicate"))        })    }}