Something went wrong. Try again.
Browser extension: detect and subscribe to standard.site publications on ATProto substandard.blog
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442use std::collections::{HashMap, HashSet};
use serde::Serialize;use serde_json::Value;use unicode_segmentation::UnicodeSegmentation;use url::Url;
use crate::model::PostRecord;use crate::text::strip_thread_counter;
const READABILITY_TARGET: f64 = 10.0;const ECOSYSTEM_HOSTS: &[&str] = &[ "bsky.app", "atproto.com", "docs.bsky.app", "standard.site", "leaflet.pub", "pdsls.dev", "plc.directory", "tangled.org",];
/// A local, bounded reading of the thread's prose and evidence.////// The factors mirror panoptiblog's voice and evidence categories, but a/// single thread has no cohort to percentile-rank against. Each factor is/// capped to 0..1, then the category weights are averaged.#[derive(Debug, Clone, Serialize)]pub struct Craft { pub score: f64, pub voice: f64, pub evidence: f64, pub words: usize, pub links: usize, pub ecosystem_links: usize, pub embeds: usize, pub atproto_refs: usize, pub readability: Option<f64>, pub mtld: f64, pub hapax: f64, pub depth: f64, pub lexical: f64, pub readability_factor: Option<f64>, pub source_diversity: f64,}
pub fn analyze(posts: &[PostRecord]) -> Craft { let mut text = String::new(); let mut urls: HashSet<String> = HashSet::new(); let mut atproto_refs: HashSet<String> = HashSet::new(); let mut embeds = 0usize;
for post in posts { let post_text = strip_thread_counter(&post.value.text); text.push_str(&post_text); text.push_str("\n\n");
for url in urls_in_text(&post_text) { urls.insert(url); } for token in post_text.split_whitespace() { if token.starts_with("at://") && let Some(uri) = clean_at_uri(token) { atproto_refs.insert(uri); } } for facet in &post.value.facets { for feature in &facet.features { if feature_type(feature).ends_with("#link") && let Some(uri) = feature.get("uri").and_then(Value::as_str) && let Some(url) = clean_url(uri) { urls.insert(url); } } } if let Some(embed) = &post.value.embed { collect_embed(embed, &mut urls, &mut atproto_refs, &mut embeds); } }
let analysis = analysis_text(&text); let tokens: Vec<String> = analysis .unicode_words() .map(|word| { word.to_lowercase() .trim_matches(|character: char| !character.is_alphanumeric()) .to_string() }) .filter(|word| word.chars().any(|character| character.is_alphanumeric())) .collect(); let words = analysis .split_whitespace() .filter(|token| token.chars().any(char::is_alphanumeric)) .count(); let sentence_count = sentence_count(&analysis).max(1); let latin_tokens = tokens .iter() .filter(|token| { token .chars() .any(|character| character.is_ascii_alphabetic()) }) .count(); let readability = if !tokens.is_empty() && latin_tokens * 2 >= tokens.len() { let syllables: usize = tokens.iter().map(|token| syllable_count(token)).sum(); let words = tokens.len() as f64; Some(0.39 * (words / sentence_count as f64) + 11.8 * (syllables as f64 / words) - 15.59) } else { None }; let mtld = mtld(&tokens); let hapax = hapax_ratio(&tokens);
let depth = (words as f64 / 800.0).min(1.0); let lexical = (mtld / 100.0).min(1.0); let readability_factor = readability.map(|grade| { (1.0 - ((grade - READABILITY_TARGET).abs() / READABILITY_TARGET).min(1.0)).clamp(0.0, 1.0) }); let voice = weighted(&[ (0.4, Some(depth)), (0.25, Some(lexical)), (0.15, Some(hapax)), (0.2, readability_factor), ]);
let links = urls.len(); let mut host_counts: HashMap<String, usize> = HashMap::new(); let mut ecosystem_links = 0usize; for url in &urls { let Ok(parsed) = Url::parse(url) else { continue; }; let Some(host) = parsed.host_str() else { continue; }; *host_counts.entry(host.to_string()).or_insert(0) += 1; if ECOSYSTEM_HOSTS.contains(&host) { ecosystem_links += 1; } } let source_diversity = normalized_entropy(&host_counts); let words_for_rate = words.max(1) as f64; let links_per_1000 = links as f64 / words_for_rate * 1000.0; let ecosystem_per_1000 = ecosystem_links as f64 / words_for_rate * 1000.0; let atproto_per_1000 = (atproto_refs.len() + embeds) as f64 / words_for_rate * 1000.0;
let evidence = weighted(&[ (0.2, Some((links_per_1000 / 5.0).min(1.0))), (0.15, Some(source_diversity)), (0.4, Some((ecosystem_per_1000 / 3.0).min(1.0))), (0.25, Some((atproto_per_1000 / 2.0).min(1.0))), ]); let score = weighted(&[(0.6, Some(voice)), (0.4, Some(evidence))]);
Craft { score, voice, evidence, words, links, ecosystem_links, embeds, atproto_refs: atproto_refs.len(), readability, mtld, hapax, depth, lexical, readability_factor, source_diversity, }}
fn weighted(parts: &[(f64, Option<f64>)]) -> f64 { let mut total = 0.0; let mut weight = 0.0; for (part_weight, value) in parts { if let Some(value) = value { total += part_weight * value; weight += part_weight; } } if weight == 0.0 { 0.0 } else { total / weight }}
fn analysis_text(text: &str) -> String { text.split_whitespace() .filter(|token| { let token = token.to_ascii_lowercase(); !token.starts_with('@') && !token.starts_with("http://") && !token.starts_with("https://") && !token.starts_with("www.") }) .collect::<Vec<_>>() .join(" ")}
fn urls_in_text(text: &str) -> Vec<String> { text.split_whitespace().filter_map(clean_url).collect()}
fn clean_url(value: &str) -> Option<String> { let trimmed = value.trim_end_matches([ '.', ',', ';', ':', '!', '?', '…', '\'', '"', '”', '’', ')', ']', ]); if !(trimmed.starts_with("http://") || trimmed.starts_with("https://")) { return None; } let url = Url::parse(trimmed).ok()?; if url.scheme() == "http" || url.scheme() == "https" { Some(url.to_string()) } else { None }}
fn clean_at_uri(value: &str) -> Option<String> { let trimmed = value.trim_end_matches([ '.', ',', ';', ':', '!', '?', '…', '\'', '"', '”', '’', ')', ']', ]); trimmed.starts_with("at://").then(|| trimmed.to_string())}
fn feature_type(value: &Value) -> &str { value.get("$type").and_then(Value::as_str).unwrap_or("")}
fn collect_embed( embed: &Value, urls: &mut HashSet<String>, atproto_refs: &mut HashSet<String>, embeds: &mut usize,) { let kind = feature_type(embed); if kind.starts_with("app.bsky.embed.recordWithMedia") { *embeds += 1; if let Some(uri) = embed.pointer("/record/record/uri").and_then(Value::as_str) { atproto_refs.insert(uri.to_string()); } else if let Some(uri) = embed.pointer("/record/uri").and_then(Value::as_str) { atproto_refs.insert(uri.to_string()); } if let Some(media) = embed.get("media") { collect_embed(media, urls, atproto_refs, embeds); } } else if kind.starts_with("app.bsky.embed.record") { *embeds += 1; if let Some(uri) = embed.pointer("/record/uri").and_then(Value::as_str) { atproto_refs.insert(uri.to_string()); } } else if kind.starts_with("app.bsky.embed.external") { if let Some(uri) = embed.pointer("/external/uri").and_then(Value::as_str) && let Some(url) = clean_url(uri) { urls.insert(url); } } else if kind.starts_with("app.bsky.embed.images") || kind.starts_with("app.bsky.embed.video") { *embeds += 1; }}
fn sentence_count(text: &str) -> usize { let mut count = 0; for line in text.lines() { let bytes = line.as_bytes(); let mut start = 0; for (index, byte) in bytes.iter().enumerate() { if !matches!(byte, b'.' | b'!' | b'?') { continue; } if bytes .get(index + 1) .is_some_and(|next| !next.is_ascii_whitespace()) { continue; } if line .get(start..=index) .is_some_and(|part| part.chars().any(|character| character.is_alphanumeric())) { count += 1; } start = index + 1; } if line .get(start..) .is_some_and(|part| part.chars().any(|character| character.is_alphanumeric())) { count += 1; } } count}
fn syllable_count(word: &str) -> usize { let cleaned: String = word .chars() .filter(|character| character.is_ascii_alphabetic()) .collect::<String>() .to_ascii_lowercase(); if cleaned.is_empty() { return 0; } let mut groups: usize = 0; let mut previous = false; for character in cleaned.chars() { let vowel = matches!(character, 'a' | 'e' | 'i' | 'o' | 'u' | 'y'); if vowel && !previous { groups += 1; } previous = vowel; } let silent = if cleaned.ends_with('e') && groups > 1 { 1 } else { 0 }; groups.saturating_sub(silent).max(1)}
fn mtld(tokens: &[String]) -> f64 { if tokens.len() < 50 { return 0.0; } let forward = mtld_pass(tokens.iter().map(String::as_str).collect()); let reverse: Vec<&str> = tokens.iter().rev().map(String::as_str).collect(); (forward + mtld_pass(reverse)) / 2.0}
fn mtld_pass(tokens: Vec<&str>) -> f64 { if tokens.is_empty() { return 0.0; } let threshold = 0.72; let mut segments = 0.0; let mut start = 0; let mut unique = 0; let mut counts: HashMap<&str, usize> = HashMap::new(); for (index, token) in tokens.iter().enumerate() { let count = counts.entry(*token).or_insert(0); if *count == 0 { unique += 1; } *count += 1; if unique as f64 / (index - start + 1) as f64 <= threshold { segments += 1.0; start = index + 1; unique = 0; counts.clear(); } } let remaining = tokens.len() - start; if remaining > 0 { let unique: HashSet<&str> = tokens[start..].iter().copied().collect(); let ttr = unique.len() as f64 / remaining as f64; segments += ((1.0 - ttr) / (1.0 - threshold)).max(0.0); } if segments > 0.0 { tokens.len() as f64 / segments } else { tokens.len() as f64 }}
fn hapax_ratio(tokens: &[String]) -> f64 { if tokens.is_empty() { return 0.0; } let mut counts: HashMap<&str, usize> = HashMap::new(); for token in tokens { *counts.entry(token.as_str()).or_insert(0) += 1; } counts.values().filter(|count| **count == 1).count() as f64 / tokens.len() as f64}
fn normalized_entropy(counts: &HashMap<String, usize>) -> f64 { let total: usize = counts.values().sum(); if total == 0 || counts.len() < 2 { return 0.0; } let entropy: f64 = counts .values() .map(|count| { let probability = *count as f64 / total as f64; -probability * probability.log2() }) .sum(); (entropy / (counts.len() as f64).log2()).clamp(0.0, 1.0)}
#[cfg(test)]mod tests { use chrono::Utc; use serde_json::json;
use super::*; use crate::model::PostValue;
fn post(index: usize, text: &str) -> PostRecord { let value: PostValue = serde_json::from_value(json!({ "text": text, "createdAt": "2026-01-01T00:00:00.000Z", })) .expect("post value"); PostRecord { uri: format!("at://did:plc:test/app.bsky.feed.post/{index}"), value, created_at: Utc::now(), } }
#[test] fn evidence_rewards_links_and_embeds() { let plain = analyze(&[post( 1, &"A long thread about writing code without any links at all. ".repeat(20), )]); let sourced = analyze(&[post( 2, &("A long thread about writing code with sources. ".repeat(20) + " https://example.com/a https://bsky.app/profile/did:plc:test/post/1"), )]); assert!(sourced.evidence > plain.evidence, "{sourced:?}"); assert!(sourced.score >= 0.0 && sourced.score <= 1.0); }
#[test] fn voice_rewards_substance_and_variety() { let thin = analyze(&[post(1, "thing thing thing thing")]); let full = analyze(&[post( 2, &"A measured paragraph about distributed systems and the people who run them. \ Another sentence adds a different shape, a longer clause, and a quieter ending." .repeat(4), )]); assert!(full.voice > thin.voice, "{full:?} vs {thin:?}"); }}