//! Compact text views of charts for the language model. //! //! Only astrological positions go in: no names, birth date, time, place or //! coordinates. Plain text is shorter than the JSON and easier for models. use std::fmt::Write; use serde_json::Value; /// Points listed one per line; asteroids go on a shorter line. const MAIN_POINTS: [&str; 14] = [ "sun", "moon", "mercury", "venus", "mars", "jupiter", "saturn", "uranus", "neptune", "pluto", "chiron", "north_node", "south_node", "lilith", ]; const ASTEROIDS: [&str; 4] = ["ceres", "pallas", "juno", "vesta"]; const ANGLES: [&str; 4] = ["ascendant", "midheaven", "descendant", "imum_coeli"]; const MAX_SYNASTRY_ASPECTS: usize = 45; fn point_name(id: &str) -> String { match id { "north_node" => "North Node".into(), "south_node" => "South Node".into(), "lilith" => "Lilith (Black Moon)".into(), "midheaven" => "Midheaven (MC)".into(), "imum_coeli" => "Imum Coeli (IC)".into(), "ascendant" => "Ascendant".into(), "descendant" => "Descendant".into(), other => capitalize(other), } } fn capitalize(s: &str) -> String { let mut chars = s.chars(); chars.next().map(|c| c.to_uppercase().chain(chars).collect()).unwrap_or_default() } fn words(s: &str) -> String { s.replace('_', " ") } /// "Cancer 0°24'" from a position object (sign + degree_in_sign). fn position(p: &Value) -> String { let degree = p["degree_in_sign"].as_f64().unwrap_or(0.0); // Rounded to the second first, as in the `degree_in_sign_dms` field; never 30°. let secs = ((degree * 3600.0).round() as i64).clamp(0, 30 * 3600 - 1); let (d, m) = (secs / 3600, secs % 3600 / 60); format!("{} {d}°{m:02}'", capitalize(p["sign"].as_str().unwrap_or("?"))) } fn time_known(chart: &Value) -> bool { chart["time"]["time_known"].as_bool().unwrap_or(false) } fn is_main(id: &str) -> bool { MAIN_POINTS.contains(&id) || ANGLES.contains(&id) } fn points(chart: &Value) -> impl Iterator { chart["points"].as_array().into_iter().flatten() } fn names(list: &Value) -> String { list.as_array().into_iter().flatten().filter_map(Value::as_str).map(point_name).collect::>().join(", ") } /// One line per point: "Sun: Cancer 0°24', house 3, retrograde, domicile". fn point_lines(out: &mut String, chart: &Value, prefix: &str, houses: bool) { for p in points(chart).filter(|p| MAIN_POINTS.contains(&p["id"].as_str().unwrap_or(""))) { let mut line = format!("{prefix}- {}: {}", point_name(p["id"].as_str().unwrap_or("?")), position(p)); if houses && let Some(h) = p["house"].as_i64() { let _ = write!(line, ", house {h}"); } if p["retrograde"].as_bool() == Some(true) { line.push_str(", retrograde"); } for dignity in p["dignities"].as_array().into_iter().flatten().filter_map(Value::as_str) { let _ = write!(line, ", {}", words(dignity)); } if p["out_of_bounds"].as_bool() == Some(true) { line.push_str(", out of bounds"); } let _ = writeln!(out, "{line}"); } let minor: Vec = points(chart) .filter(|p| ASTEROIDS.contains(&p["id"].as_str().unwrap_or(""))) .map(|p| { let house = if houses { p["house"].as_i64().map(|h| format!(" (house {h})")).unwrap_or_default() } else { String::new() }; format!("{} {}{house}", point_name(p["id"].as_str().unwrap_or("?")), position(p)) }) .collect(); if !minor.is_empty() { let _ = writeln!(out, "{prefix}- Asteroids: {}", minor.join("; ")); } } fn angle_lines(out: &mut String, chart: &Value, prefix: &str) { let angles = &chart["angles"]; for (id, label) in [("ascendant", "Ascendant"), ("midheaven", "Midheaven (MC)")] { if angles[id].is_object() { let _ = writeln!(out, "{prefix}- {label}: {}", position(&angles[id])); } } } const BIRTH_TIME_UNKNOWN: &str = "Birth time: UNKNOWN. The chart is cast for noon, so there are no houses, \ no Ascendant and no Midheaven, and the Moon may be up to about 7° off (its sign is uncertain near a sign boundary)."; /// A natal chart (the horoscope-api `/v1/natal` result). pub fn natal(chart: &Value) -> String { let mut out = String::new(); let settings = &chart["settings"]; let known = time_known(chart); let _ = writeln!( out, "NATAL CHART ({} zodiac, {} houses)", settings["zodiac"].as_str().unwrap_or("tropical"), capitalize(&words( chart["houses"]["system"].as_str().or(settings["house_system"].as_str()).unwrap_or("placidus") )) ); let _ = writeln!(out, "{}", if known { "Birth time: known." } else { BIRTH_TIME_UNKNOWN }); let summary = &chart["summary"]; if let Some(sect) = summary["sect"].as_str() { let _ = writeln!(out, "Sect: {sect} chart."); } let phase = &chart["moon_phase"]; if let Some(name) = phase["phase"].as_str() { let illumination = phase["illumination"].as_f64().map(|i| format!(" ({:.0}% illuminated)", i * 100.0)); let _ = writeln!(out, "Moon phase: {}{}.", words(name), illumination.unwrap_or_default()); } if known { out.push_str("\nAngles:\n"); angle_lines(&mut out, chart, ""); let ruler = &summary["chart_ruler"]; for kind in ["traditional", "modern"] { let r = &ruler[kind]; if let Some(planet) = r["planet"].as_str() { if kind == "modern" && ruler["traditional"]["planet"] == r["planet"] { continue; } let _ = writeln!( out, "- Chart ruler ({kind}): {} in {}, house {}", point_name(planet), capitalize(r["sign"].as_str().unwrap_or("?")), r["house"] ); } } } out.push_str("\nPlanets and points:\n"); point_lines(&mut out, chart, "", known); if known && let Some(cusps) = chart["houses"]["cusps"].as_array() { let list: Vec = cusps.iter().map(|c| format!("{} {}", c["house"], position(c))).collect(); let _ = writeln!(out, "\nHouse cusps: {}", list.join(" | ")); } aspect_lines(&mut out, &chart["aspects"], "\nAspects (tightest first; orb in degrees):", usize::MAX); out.push_str("\nBalance (main planets):\n"); for (title, key) in [("Elements", "elements"), ("Modalities", "modalities")] { if let Some(groups) = summary[key].as_object() { let list: Vec = groups .iter() .map(|(name, g)| { let members = names(&g["points"]); if members.is_empty() { format!("{name} 0") } else { format!("{name} {} ({members})", g["count"]) } }) .collect(); let _ = writeln!(out, "- {title}: {}", list.join("; ")); } } if known && let Some(h) = summary["hemispheres"].as_object() { let list: Vec = h.iter().map(|(name, g)| format!("{} {}", words(name), g["count"])).collect(); let _ = writeln!(out, "- Hemispheres: {}", list.join(", ")); } let retro = names(&summary["retrograde"]); if !retro.is_empty() { let _ = writeln!(out, "- Retrograde: {retro}"); } if known && let Some(fortune) = chart["lots"]["fortune"].as_object() { let fortune = Value::Object(fortune.clone()); let _ = writeln!(out, "- Part of Fortune: {}, house {}", position(&fortune), fortune["house"]); } out } /// A synastry: both natal charts plus the synastry result (inter-aspects, /// house overlays, composite) as stored by the backend. pub fn synastry(chart1: &Value, chart2: &Value, result: &Value) -> String { let mut out = String::from("SYNASTRY: two natal charts compared (Person 1 and Person 2), tropical zodiac.\n"); for (label, chart) in [("Person 1", chart1), ("Person 2", chart2)] { let _ = writeln!(out, "\n{label}:"); if time_known(chart) { let _ = writeln!(out, " Birth time: known."); angle_lines(&mut out, chart, " "); } else { let _ = writeln!(out, " {BIRTH_TIME_UNKNOWN}"); } point_lines(&mut out, chart, " ", time_known(chart)); } let mut aspects: Vec<&Value> = result["aspects"] .as_array() .into_iter() .flatten() .filter(|a| is_main(a["person1"].as_str().unwrap_or("")) && is_main(a["person2"].as_str().unwrap_or(""))) .collect(); aspects.sort_by(|a, b| a["orb"].as_f64().unwrap_or(99.0).total_cmp(&b["orb"].as_f64().unwrap_or(99.0))); if !aspects.is_empty() { let _ = writeln!( out, "\nInter-chart aspects (Person 1's point first; tightest {} of {}):", aspects.len().min(MAX_SYNASTRY_ASPECTS), aspects.len() ); for a in aspects.iter().take(MAX_SYNASTRY_ASPECTS) { let _ = writeln!( out, "- {} {} {} (orb {:.1}°, {})", point_name(a["person1"].as_str().unwrap_or("?")), words(a["aspect"].as_str().unwrap_or("?")), point_name(a["person2"].as_str().unwrap_or("?")), a["orb"].as_f64().unwrap_or(0.0), a["nature"].as_str().unwrap_or("neutral") ); } } if let Some(by_nature) = result["summary"]["by_nature"].as_object() { let list: Vec = by_nature.iter().map(|(k, v)| format!("{k} {v}")).collect(); let _ = writeln!(out, "All aspects by nature: {}", list.join(", ")); } let overlays = &result["house_overlays"]; for (key, label) in [ ("person1_in_person2", "Person 1's planets in Person 2's houses"), ("person2_in_person1", "Person 2's planets in Person 1's houses"), ] { let list: Vec = overlays[key] .as_array() .into_iter() .flatten() .filter(|o| MAIN_POINTS.contains(&o["point"].as_str().unwrap_or(""))) .filter_map(|o| Some(format!("{} {}", point_name(o["point"].as_str()?), o["house"].as_i64()?))) .collect(); if !list.is_empty() { let _ = writeln!(out, "\n{label}: {}", list.join(", ")); } } let composite = &result["composite"]; if composite["points"].is_array() { let both_known = time_known(chart1) && time_known(chart2); let _ = writeln!(out, "\nComposite chart ({} method):", composite["method"].as_str().unwrap_or("midpoint")); if both_known { angle_lines(&mut out, composite, ""); } point_lines(&mut out, composite, "", both_known); aspect_lines(&mut out, &composite["aspects"], "Composite aspects (tightest first):", 12); } out } /// "2026-08-03, 2027-01-15 (retrograde)" from a list of exact hits. fn exact_dates(list: &Value) -> String { list.as_array() .into_iter() .flatten() .map(|e| { let date = e["date"].as_str().unwrap_or("?"); if e["retrograde"].as_bool() == Some(true) { format!("{date} (retrograde)") } else { date.to_string() } }) .collect::>() .join(", ") } /// One contact of a transiting or progressed planet with a natal point. fn contact_line(out: &mut String, c: &Value, moving: &str) { let planet = c["planet"].as_str().unwrap_or("?"); let natal = c["natal_point"].as_str().unwrap_or("?"); let mut line = format!( "- {moving}{} {} natal {} ({})", point_name(planet), words(c["aspect"].as_str().unwrap_or("?")), point_name(natal), c["nature"].as_str().unwrap_or("neutral") ); // A planet back at its own natal place (or in aspect to it, for transits): a life cycle. if planet == natal && (moving.is_empty() || c["aspect"] == "conjunction") { line.push_str(", cycle"); } let exact = exact_dates(&c["exact"]); if exact.is_empty() { let _ = write!( line, ": not exact this year, closest {:.1}° around {}", c["min_orb"].as_f64().unwrap_or(0.0), c["peak"].as_str().unwrap_or("?") ); } else { let _ = write!(line, ": exact {exact}"); } let periods: Vec = c["periods"] .as_array() .into_iter() .flatten() .map(|p| format!("{} to {}", p["start"].as_str().unwrap_or("?"), p["end"].as_str().unwrap_or("?"))) .collect(); if !periods.is_empty() { let _ = write!(line, "; within orb {}", periods.join(", ")); } if let Some(h) = c["house"].as_i64() { let _ = write!(line, "; {moving}{} in natal house {h}", point_name(planet)); } let _ = writeln!(out, "{line}"); } /// One year of a chart: the natal chart, then the stored horoscope-api /// `/v1/forecast` result (solar return chart, profection, transits, /// progressions, eclipses). The place of the birthday and the exact age are /// left out; the age goes in by decade. pub fn forecast(chart: &Value, result: &Value) -> String { let f = &result["forecast"]; let known = time_known(chart); let mut out = format!( "YEARLY FORECAST: one year of life, from the solar return on {} to the next one on {}.\n", f["start"].as_str().unwrap_or("?"), f["end"].as_str().unwrap_or("?") ); if let Some(age) = f["age"].as_i64() { let _ = writeln!(out, "Age group: {}s.", age / 10 * 10); } out.push('\n'); out.push_str(&natal(chart)); let sr = &result["solar_return"]; if sr.is_object() { out.push_str("\nSOLAR RETURN CHART (cast for the moment of the solar return at the place of the birthday):\n"); angle_lines(&mut out, sr, ""); if let Some(h) = sr["natal_house_of_ascendant"].as_i64() { let _ = writeln!(out, "- The solar return Ascendant falls in natal house {h}."); } point_lines(&mut out, sr, "", true); aspect_lines(&mut out, &sr["aspects"], "Solar return aspects (tightest first):", 15); } else { out.push_str("\nSOLAR RETURN CHART: none, because the birth time is unknown.\n"); } let p = &f["profection"]; if p.is_object() { let planets = names(&p["planets_in_sign"]); let _ = writeln!( out, "\nANNUAL PROFECTION: the year activates natal house {} ({}); lord of the year: {} (natal {} in {}, house {}).{}", p["house"], capitalize(p["sign"].as_str().unwrap_or("?")), point_name(p["lord"].as_str().unwrap_or("?")), point_name(p["lord"].as_str().unwrap_or("?")), capitalize(p["lord_sign"].as_str().unwrap_or("?")), p["lord_house"], if planets.is_empty() { String::new() } else { format!(" Natal planets in that sign: {planets}.") } ); } out.push_str("\nSLOW-PLANET TRANSITS to the natal chart (orb 1°; in order of their peak; dates are local days):\n"); let transits = f["transits"].as_array().map(Vec::as_slice).unwrap_or_default(); if transits.is_empty() { out.push_str("- none\n"); } for c in transits { contact_line(&mut out, c, ""); } let houses = f["transit_houses"].as_array().map(Vec::as_slice).unwrap_or_default(); if known && !houses.is_empty() { out.push_str("\nSlow planets in the natal houses:\n"); for h in houses { let mut line = format!( "- {}: house {} at the start", point_name(h["planet"].as_str().unwrap_or("?")), h["house_at_start"] ); for i in h["ingresses"].as_array().into_iter().flatten() { let retro = if i["retrograde"].as_bool() == Some(true) { " (retrograde)" } else { "" }; let _ = write!(line, "; enters house {} on {}{retro}", i["house"], i["date"].as_str().unwrap_or("?")); } let _ = writeln!(out, "{line}"); } } let prog = &f["progressions"]; out.push_str("\nSECONDARY PROGRESSIONS (a day for a year), at the start of the year:\n"); for b in prog["bodies"].as_array().into_iter().flatten() { let mut line = format!("- Progressed {}: {}", point_name(b["planet"].as_str().unwrap_or("?")), position(b)); if let Some(h) = b["house"].as_i64() { let _ = write!(line, ", natal house {h}"); } if b["retrograde"].as_bool() == Some(true) { line.push_str(", retrograde"); } if b["approximate"].as_bool() == Some(true) { line.push_str(" (uncertain: the birth time is unknown)"); } for i in b["sign_changes"].as_array().into_iter().flatten() { let _ = write!( line, "; enters {} on {}", capitalize(i["sign"].as_str().unwrap_or("?")), i["date"].as_str().unwrap_or("?") ); } for i in b["house_changes"].as_array().into_iter().flatten() { let _ = write!(line, "; enters natal house {} on {}", i["house"], i["date"].as_str().unwrap_or("?")); } let _ = writeln!(out, "{line}"); } if let Some(phase) = prog["lunar_phase"].as_str() { let change = &prog["lunar_phase_change"]; let change = if change.is_object() { format!( ", turns {} on {}", words(change["phase"].as_str().unwrap_or("?")), change["date"].as_str().unwrap_or("?") ) } else { String::new() }; let _ = writeln!(out, "- Progressed lunation phase: {}{change}", words(phase)); } let contacts = prog["contacts"].as_array().map(Vec::as_slice).unwrap_or_default(); if !contacts.is_empty() { out.push_str("Progressed planets in aspect to natal points (orb 1°):\n"); for c in contacts { contact_line(&mut out, c, "progressed "); } } let eclipses = f["eclipses"].as_array().map(Vec::as_slice).unwrap_or_default(); if !eclipses.is_empty() { out.push_str("\nECLIPSES during the year:\n"); for e in eclipses { let mut line = format!( "- {}: {} {} eclipse at {}", e["date"].as_str().unwrap_or("?"), e["eclipse_type"].as_str().unwrap_or("?"), e["kind"].as_str().unwrap_or("?"), position(e) ); if let Some(h) = e["house"].as_i64() { let _ = write!(line, ", natal house {h}"); } let hits: Vec = e["contacts"] .as_array() .into_iter() .flatten() .map(|c| { format!( "{} natal {} (orb {:.1}°)", words(c["aspect"].as_str().unwrap_or("?")), point_name(c["point"].as_str().unwrap_or("?")), c["orb"].as_f64().unwrap_or(0.0) ) }) .collect(); if hits.is_empty() { line.push_str("; no close contact with the natal chart"); } else { let _ = write!(line, "; {}", hits.join(", ")); } let _ = writeln!(out, "{line}"); } } out } /// Aspects between main points and angles, tightest first. fn aspect_lines(out: &mut String, aspects: &Value, heading: &str, limit: usize) { let mut list: Vec<&Value> = aspects .as_array() .into_iter() .flatten() .filter(|a| is_main(a["point1"].as_str().unwrap_or("")) && is_main(a["point2"].as_str().unwrap_or(""))) .collect(); if list.is_empty() { return; } list.sort_by(|a, b| a["orb"].as_f64().unwrap_or(99.0).total_cmp(&b["orb"].as_f64().unwrap_or(99.0))); let _ = writeln!(out, "{heading}"); for a in list.into_iter().take(limit) { let motion = match a["applying"].as_bool() { Some(true) => ", applying", Some(false) => ", separating", None => "", }; let _ = writeln!( out, "- {} {} {} (orb {:.1}°{motion})", point_name(a["point1"].as_str().unwrap_or("?")), words(a["aspect"].as_str().unwrap_or("?")), point_name(a["point2"].as_str().unwrap_or("?")), a["orb"].as_f64().unwrap_or(0.0) ); } } #[cfg(test)] mod tests { use super::*; fn fixture(name: &str) -> Value { let path = format!("{}/testdata/{name}", env!("CARGO_MANIFEST_DIR")); serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap() } /// Birth data that must never reach the model. fn assert_private(text: &str) { for secret in ["1990", "1988", "14:30", "08:10", "Szeged", "Pécs", "Hungary", "HU", "46.", "20.1", "Budapest"] { assert!(!text.contains(secret), "'{secret}' leaked into:\n{text}"); } } #[test] fn natal_with_birth_time() { let text = natal(&fixture("natal-1990-03-15.json")); assert_private(&text); for expected in [ "Birth time: known.", "- Ascendant: Leo 19°23'", "- Chart ruler (traditional): Sun in Pisces, house 8", "- Sun: Pisces 24°42', house 8", "- Pluto: Scorpio 17°36', house 4, retrograde, domicile", "- Asteroids: Ceres Gemini 25°43' (house 11);", "House cusps: 1 Leo 19°23' | 2 Virgo 9°35'", "- Moon trine Chiron (orb 0.1°, applying)", "- Elements: air 2 (Venus, Mars); earth 3 (Saturn, Uranus, Neptune); fire 0;", "- Part of Fortune: Aries 5°10', house 8", ] { assert!(text.contains(expected), "missing '{expected}' in:\n{text}"); } // Tightest aspect first. assert!(text.find("Moon trine Chiron").unwrap() < text.find("Moon square Ascendant").unwrap()); } #[test] fn natal_without_birth_time_has_no_houses() { let text = natal(&fixture("natal-1988-11-02-notime.json")); assert_private(&text); assert!(text.contains("Birth time: UNKNOWN")); for absent in ["house ", "House cusps", "Ascendant:", "Midheaven (MC):", "Chart ruler", "Hemispheres", "Fortune"] { assert!(!text.contains(absent), "'{absent}' in:\n{text}"); } assert!(text.contains("- Venus: Libra 4°12', domicile")); } #[test] fn forecast_view() { // The stored horoscope-api /v1/forecast result of the chart below (year 2026). let text = forecast(&fixture("natal-1990-03-15.json"), &fixture("forecast-1990-03-15.json")); assert_private(&text); for expected in [ "YEARLY FORECAST: one year of life, from the solar return on 2026-03-15 to the next one on 2027-03-15.", "Age group: 30s.", "NATAL CHART", "SOLAR RETURN CHART (cast for", "- The solar return Ascendant falls in natal house 10.", "ANNUAL PROFECTION: the year activates natal house 1 (Leo); lord of the year: Sun", "- progressed Moon trine natal Moon (harmonious): exact 2027-02-24", "- Neptune sextile natal Mars (harmonious): exact 2026-04-19, 2026-09-30 (retrograde), 2027-02-20", "Slow planets in the natal houses:", "SECONDARY PROGRESSIONS", "- Progressed lunation phase:", "ECLIPSES during the year:", ] { assert!(text.contains(expected), "missing '{expected}' in:\n{text}"); } for absent in ["Europe/Budapest", "08:02", "Age group: 36", "36s"] { assert!(!text.contains(absent), "'{absent}' in:\n{text}"); } } #[test] fn synastry_view() { // The full horoscope-api response, with both persons' birth data in it. let response = fixture("synastry-response.json"); let text = synastry(&response["person1"], &response["person2"], &response); assert_private(&text); for expected in [ "Person 1:\n Birth time: known.", " - Sun: Pisces 24°42', house 8", "Inter-chart aspects (Person 1's point first; tightest 45 of", "(orb 0.0°, harmonious)", "All aspects by nature: ", "Person 1's planets in Person 2's houses: Sun 4, Moon 12", "Composite chart (midpoint method):\n- Ascendant: Libra 8°39'", "Composite aspects (tightest first):\n- Saturn conjunction Neptune (orb 0.1°)", ] { assert!(text.contains(expected), "missing '{expected}' in:\n{text}"); } } }