Files
sorsfonalak/crates/analysis-prompt/src/tarot.rs
T
fecoandClaude Opus 5.5 7f6f05150e
CI / test (push) Successful in 1m27s
CI / build (push) Successful in 5m37s
CI / deploy (push) Skipped
Tarot readings have a topic: general, relationship, work, self-knowledge
The new reading form starts with the topic; it steers how the model
reads the cards (with the topic's own limits, e.g. no break-up
predictions for relationships) and shows on the reading and in the
list. Readings from before count as general.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-20 16:25:12 +00:00

468 lines
20 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Tarot readings: the deck, the spreads, the prompt and the answer schema.
//!
//! The backend draws the cards and stores them with the question (the
//! `tarot` column of the analysis, see [`Reading`]); the worker writes the
//! reading with the model of the detailed analyses.
use std::sync::OnceLock;
use serde_json::{Value, json};
use crate::{HUNGARIAN_TERMS, Prompt};
/// The 78 cards, shared with the frontend (which draws them from the same file).
const DECK_JSON: &str = include_str!("../../../services/frontend/src/content/tarot-deck.json");
/// Longest question, in characters.
pub const TAROT_QUESTION_MAX_CHARS: usize = 300;
/// A card of the deck (the fields the prompt and the views need).
#[derive(Debug, Clone)]
pub struct Card {
pub id: String,
pub name_hu: String,
pub name_en: String,
pub element: String,
pub astro: String,
pub keywords: Vec<String>,
pub upright: String,
pub reversed: String,
}
pub fn deck() -> &'static [Card] {
static DECK: OnceLock<Vec<Card>> = OnceLock::new();
DECK.get_or_init(|| {
let raw: Vec<Value> = serde_json::from_str(DECK_JSON).expect("tarot-deck.json is valid JSON");
let text = |c: &Value, k: &str| c[k].as_str().unwrap_or_default().to_string();
raw.iter()
.map(|c| Card {
id: text(c, "id"),
name_hu: text(c, "nameHu"),
name_en: text(c, "nameEn"),
element: text(c, "element"),
astro: text(c, "astroRuler"),
keywords: c["keywords"]
.as_array()
.into_iter()
.flatten()
.filter_map(Value::as_str)
.map(str::to_string)
.collect(),
upright: text(c, "upright"),
reversed: text(c, "reversed"),
})
.collect()
})
}
pub fn card(id: &str) -> Option<&'static Card> {
deck().iter().find(|c| c.id == id)
}
/// A place in a spread.
#[derive(Debug, Clone, Copy)]
pub struct Position {
pub title: &'static str,
/// What the card in this place tells about.
pub about: &'static str,
}
#[derive(Debug, Clone, Copy)]
pub struct Spread {
pub id: &'static str,
pub name: &'static str,
pub positions: &'static [Position],
}
pub const SPREADS: [Spread; 3] = [
Spread {
id: "daily",
name: "Napi iránymutatás",
positions: &[Position {
title: "A nap üzenete",
about: "Mire hangolódj ma, és milyen minőség támogat leginkább.",
}],
},
Spread {
id: "trinity",
name: "Sorsfonalak hármas",
positions: &[
Position { title: "Gyökér és előzmény", about: "Honnan ered a mostani helyzet energiája." },
Position { title: "Jelenlegi fókusz", about: "Mi zajlik most a felszínen és a mélyben." },
Position { title: "Kibontakozás", about: "Merre tart a folyamat, ha tudatosan együttműködsz vele." },
],
},
Spread {
id: "astro_cross",
name: "Képlet-kereszt",
positions: &[
Position { title: "Központi téma", about: "A kérdés szíve és a jelenlegi sorspont." },
Position {
title: "Hold-mélység (belső)", about: "Tudattalan érzelmi mozgatórugók és megérzések."
},
Position {
title: "Nap-tér (tudatos)", about: "Amire már rálátsz, és ami felé az akaratod irányul."
},
Position {
title: "Kvadrát (kihívás)", about: "A súrlódás, amely cselekvésre és növekedésre hív."
},
Position {
title: "Aszcendens (útmutatás)", about: "A legtisztább következő lépés kifelé és előre."
},
],
},
];
pub fn spread(id: &str) -> Option<&'static Spread> {
SPREADS.iter().find(|s| s.id == id)
}
/// What the reading is about: it steers how the cards are read.
#[derive(Debug, Clone, Copy)]
pub struct Topic {
pub id: &'static str,
pub name: &'static str,
/// The instruction for the model (Hungarian, English).
pub focus: (&'static str, &'static str),
}
pub const TOPICS: [Topic; 4] = [
Topic {
id: "general",
name: "Általános",
focus: (
"Általános jóslás: az olvasó élete egészére vonatkoztasd a lapokat.",
"A general reading: relate the cards to the reader's life as a whole.",
),
},
Topic {
id: "love",
name: "Párkapcsolat",
focus: (
"Párkapcsolati jóslás: minden lapot a szerelem, a vonzalom, a közelség, a bizalom és a kommunikáció \
szemszögéből olvass, akár van kapcsolata az olvasónak, akár keres. Ne feltételezd a partner nemét, és ne \
jósolj szakítást, hűtlenséget vagy azt, hogy valaki biztosan visszatér.",
"A relationship reading: read every card through love, attraction, closeness, trust and communication, \
whether the reader is in a relationship or looking for one. Do not assume the partner's gender, and do \
not predict a break-up, infidelity or that someone will surely come back.",
),
},
Topic {
id: "work",
name: "Munka és hivatás",
focus: (
"Munka és hivatás: a lapokat a munka, a hivatás, a tanulás, a munkahelyi kapcsolatok és a fejlődés \
szemszögéből olvasd. Ne adj pénzügyi vagy jogi tanácsot, és ne jósolj elbocsátást vagy anyagi \
nyereséget, veszteséget.",
"Work and calling: read the cards through work, vocation, learning, relationships at work and growth. \
Give no financial or legal advice, and do not predict dismissal or financial gains or losses.",
),
},
Topic {
id: "self",
name: "Önismeret",
focus: (
"Önismeret: a lapokat a belső világ, az érzelmek, a minták és a lelki fejlődés szemszögéből olvasd; a \
külső események helyett arra figyelj, mit tanulhat az olvasó önmagáról.",
"Self-knowledge: read the cards through the inner world, feelings, patterns and inner growth; rather \
than outer events, focus on what the reader can learn about themselves.",
),
},
];
/// A topic by id (`None`, and readings from before topics: general).
pub fn topic(id: Option<&str>) -> Option<&'static Topic> {
match id {
None => TOPICS.first(),
Some(id) => TOPICS.iter().find(|t| t.id == id),
}
}
/// The Hungarian name of a zodiac sign as the charts store it ("cancer").
pub fn sign_hu(sign: &str) -> &'static str {
match sign.to_ascii_lowercase().as_str() {
"aries" => "Kos",
"taurus" => "Bika",
"gemini" => "Ikrek",
"cancer" => "Rák",
"leo" => "Oroszlán",
"virgo" => "Szűz",
"libra" => "Mérleg",
"scorpio" => "Skorpió",
"sagittarius" => "Nyilas",
"capricorn" => "Bak",
"aquarius" => "Vízöntő",
"pisces" => "Halak",
_ => "?",
}
}
/// What a reading is written from (the `tarot` column of the analysis):
/// `{"spread": "trinity", "question": "…" | null, "cards": [{"card": "major-2",
/// "reversed": false}, …], "sun": "cancer", "moon": "pisces", "ascendant": "aries" | null}`.
/// The cards are in the order of the spread's positions.
pub struct Reading<'a> {
pub spread: &'static Spread,
pub topic: &'static Topic,
pub question: Option<&'a str>,
/// (card, reversed) per position.
pub cards: Vec<(&'static Card, bool)>,
pub sun: Option<&'a str>,
pub moon: Option<&'a str>,
pub ascendant: Option<&'a str>,
}
impl<'a> Reading<'a> {
pub fn parse(value: &'a Value) -> Result<Self, String> {
let spread_id = value["spread"].as_str().unwrap_or_default();
let spread = spread(spread_id).ok_or_else(|| format!("unknown spread '{spread_id}'"))?;
let cards = value["cards"]
.as_array()
.ok_or("no cards")?
.iter()
.map(|c| {
let id = c["card"].as_str().unwrap_or_default();
card(id)
.map(|card| (card, c["reversed"].as_bool().unwrap_or(false)))
.ok_or_else(|| format!("unknown card '{id}'"))
})
.collect::<Result<Vec<_>, _>>()?;
if cards.len() != spread.positions.len() {
return Err(format!("{} cards for a spread of {}", cards.len(), spread.positions.len()));
}
let text = |k: &str| value[k].as_str().map(str::trim).filter(|s| !s.is_empty());
Ok(Self {
spread,
topic: topic(text("topic")).ok_or("unknown topic")?,
question: text("question"),
cards,
sun: text("sun"),
moon: text("moon"),
ascendant: text("ascendant"),
})
}
}
/// The JSON schema of a reading (strict mode: every property required).
pub fn tarot_schema() -> Value {
json!({
"type": "object",
"additionalProperties": false,
"required": ["title", "summary", "cards", "synthesis", "advice"],
"properties": {
"title": {"type": "string", "description": "Short, evocative title for this reading (at most 8 words)"},
"summary": {"type": "string", "description": "2-3 sentences: the heart of the answer"},
"cards": {
"type": "array",
"description": "One item per card, in the order of the positions",
"items": {
"type": "object",
"additionalProperties": false,
"required": ["body"],
"properties": {
"body": {"type": "string", "description": "1-2 paragraphs about this card in its position"}
}
}
},
"synthesis": {"type": "string", "description": "How the cards read together, 1-3 paragraphs separated by a blank line"},
"advice": {"type": "string", "description": "A closing, encouraging paragraph with one or two concrete steps"}
}
})
}
/// Words of the whole reading, by the number of cards.
fn length(cards: usize) -> (usize, usize) {
match cards {
1 => (250, 400),
2..=3 => (450, 700),
_ => (650, 950),
}
}
fn hungarian_system(cards: usize) -> String {
let (min, max) = length(cards);
format!(
"Tapasztalt, empatikus, lélektani szemléletű tarot-olvasó vagy, aki az asztrológiát is ismeri. A Sorsfonalak \
alkalmazás számára személyes kártyajóslást írsz egy kirakásról, amelyet az olvasó kérdésére húzott.
Magyarul írj, természetes, igényes magyarsággal, ahogy egy magyar anyanyelvű szerző írna: a szöveg ne hasson fordításnak.
Szabályok:
- Csak a megadott lapokat értelmezd, a megadott pozíciókban és állásban (álló vagy fordított). A lapok alapjelentése \
kiindulópont: a saját tudásod a lapok hagyományos szimbolikájáról (Rider–Waite) kiegészítheti, de ne mondjon neki ellent.
- Minden lapot a pozíciója fényében olvass, és mindig a kérdésre vonatkoztasd. Ha nincs kérdés, az olvasó jelenlegi \
életszakaszáról szólj általánosan.
- A lapok együtt mesélnek: mutasd meg, hogyan kapcsolódnak egymáshoz (ismétlődő elemek, színek, nagy árkánumok \
súlya, az álló és fordított lapok aránya).
- Az olvasó Napját, Holdját és Aszcendensét (ha meg van adva) egy-két helyen, finoman kapcsold a lapokhoz, például a \
lapok elemén vagy asztrológiai megfelelésén keresztül; ne írj belőle horoszkópot.
- Közvetlenül az olvasóhoz szólj, tegező formában (egyes szám második személyben, „te”).
- A tarot tükör, nem ítélet: lehetőségekről, hajlamokról és választásokról írj, soha ne biztos jövőbeli eseményekről. \
Ne jósolj betegséget, halált, balesetet, terhességet, válást vagy pénzügyi nyereséget és veszteséget, és ne adj orvosi, \
jogi vagy pénzügyi tanácsot. Ha a kérdés ilyesmire irányul, a lelki oldalára válaszolj, és jelezd, hogy a konkrét \
döntéshez szakember kell.
- Hangnem: meleg, őszinte, megerősítő és konkrét; a nehéz lapoknál is mutasd meg a kiutat. Kerüld a közhelyeket és a \
töltelékszöveget.
- A szövegek egyszerű bekezdések, üres sorral elválasztva, címsor és felsorolás nélkül; **félkövért** takarékosan \
használhatsz. A lapok nevét a magyar nevükön írd.
- Terjedelem: az egész jóslás kb. {min}–{max} szó.
- Egyetlen, a megadott sémának megfelelő JSON-objektummal válaszolj, semmi mással; a „cards” tömbben pontosan annyi \
elem legyen, ahány lap van, a pozíciók sorrendjében.{HUNGARIAN_TERMS}"
)
}
fn english_system(language: &str, cards: usize) -> String {
let (min, max) = length(cards);
format!(
"You are an experienced, empathetic tarot reader with a psychological approach who also knows astrology. You \
write a personal tarot reading for the Sorsfonalak app about a spread the reader drew for their question.
Write in {language}.
Rules:
- Read only the given cards, in their positions and orientation (upright or reversed). The base meanings are the \
starting point; your knowledge of the traditional (Rider-Waite) symbolism may add to them but must not contradict them.
- Read each card in the light of its position and always relate it to the question. Without a question, speak about \
the reader's present phase of life.
- Show how the cards tell one story together (recurring elements and suits, the weight of the major arcana, upright \
versus reversed cards).
- Link the reader's Sun, Moon and Ascendant (when given) to the cards once or twice, gently, e.g. through the cards' \
elements or astrological correspondences; do not write a horoscope.
- Address the reader directly, in the second person.
- Tarot is a mirror, not a verdict: write about possibilities, tendencies and choices, never certain future events. \
Do not predict illness, death, accidents, pregnancy, divorce or financial gains and losses, and give no medical, legal \
or financial advice; if the question asks for that, answer its emotional side and say a professional is needed for the \
decision itself.
- Tone: warm, honest, encouraging and specific; show the way forward even with hard cards. Avoid clichés and filler.
- Plain paragraphs separated by a blank line, no headings or lists; use **bold** sparingly.
- Length: about {min}-{max} words in all.
- Answer with a single JSON object matching the schema and nothing else; the \"cards\" array has exactly one item per \
card, in the order of the positions.",
language = crate::language_name(language),
)
}
/// The prompt of a reading.
pub fn build_tarot(language: &str, reading: &Reading) -> Prompt {
let hu = language == "hu";
let mut user = String::new();
let none = if hu { "nincs megadva" } else { "not given" };
user.push_str(&format!(
"{}: {}. {}\n\n",
if hu { "Téma" } else { "Topic" },
reading.topic.name,
if hu { reading.topic.focus.0 } else { reading.topic.focus.1 },
));
match reading.question {
Some(q) => user.push_str(&format!("{}: {}\n\n", if hu { "A kérdés" } else { "The question" }, q.trim())),
None => user.push_str(if hu {
"Nincs konkrét kérdés: az olvasó a témában a jelenlegi életszakaszára kér útmutatást.\n\n"
} else {
"No specific question: the reader asks for guidance on the topic in their present phase of life.\n\n"
}),
}
let sign = |s: Option<&str>| {
s.map_or(none.to_string(), |s| if hu { sign_hu(s).to_string() } else { crate::capitalize(s) })
};
user.push_str(&format!(
"{}: {} {}, {} {}, {} {}\n\n",
if hu { "Az olvasó képlete" } else { "The reader's chart" },
if hu { "Nap:" } else { "Sun:" },
sign(reading.sun),
if hu { "Hold:" } else { "Moon:" },
sign(reading.moon),
if hu { "Aszcendens:" } else { "Ascendant:" },
sign(reading.ascendant),
));
user.push_str(&format!(
"{}: {} ({} {})\n",
if hu { "Kirakás" } else { "Spread" },
reading.spread.name,
reading.cards.len(),
if hu { "lap" } else { "cards" },
));
for (i, (position, (card, reversed))) in reading.spread.positions.iter().zip(&reading.cards).enumerate() {
let orientation = match (hu, reversed) {
(true, true) => "fordított",
(true, false) => "álló",
(false, true) => "reversed",
(false, false) => "upright",
};
user.push_str(&format!(
"\n{n}. {title} ({about})\n {name} ({en}), {orientation}\n {kw}: {keywords}\n {el}: {element}; {astro_label}: {astro}\n {meaning_label}: {meaning}\n",
n = i + 1,
title = position.title,
about = position.about,
name = card.name_hu,
en = card.name_en,
kw = if hu { "Kulcsszavak" } else { "Keywords" },
keywords = card.keywords.join(", "),
el = if hu { "Elem" } else { "Element" },
element = card.element,
astro_label = if hu { "Asztrológiai megfelelés" } else { "Astrological correspondence" },
astro = card.astro,
meaning_label = if hu { "Alapjelentés ebben az állásban" } else { "Base meaning in this orientation (Hungarian)" },
meaning = if *reversed { &card.reversed } else { &card.upright },
));
}
user.push_str(if hu { "\nMost írd meg a jóslást." } else { "\nWrite the reading now." });
Prompt {
system: if hu { hungarian_system(reading.cards.len()) } else { english_system(language, reading.cards.len()) },
user,
schema_name: "tarot_reading",
schema: tarot_schema(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_deck_has_78_distinct_cards_with_meanings() {
let deck = deck();
assert_eq!(deck.len(), 78);
let mut ids: Vec<&str> = deck.iter().map(|c| c.id.as_str()).collect();
ids.sort_unstable();
ids.dedup();
assert_eq!(ids.len(), 78);
assert!(deck.iter().all(|c| !c.name_hu.is_empty() && !c.upright.is_empty() && !c.reversed.is_empty()));
assert_eq!(card("major-2").unwrap().name_hu, "A Főpapnő");
}
#[test]
fn readings_parse_and_build_a_prompt() {
let value = json!({"spread": "trinity", "question": "Merre induljak tovább?",
"cards": [{"card": "major-0", "reversed": false}, {"card": "cups-3", "reversed": true},
{"card": "major-17", "reversed": false}],
"sun": "cancer", "moon": "pisces", "ascendant": null});
let reading = Reading::parse(&value).unwrap();
let prompt = build_tarot("hu", &reading);
// Readings without a topic (the first ones) are general.
assert!(prompt.user.starts_with("Téma: Általános."));
assert!(prompt.user.contains("A kérdés: Merre induljak tovább?"));
assert!(prompt.user.contains("Nap: Rák, Hold: Halak, Aszcendens: nincs megadva"));
assert!(prompt.user.contains("2. Jelenlegi fókusz"));
assert!(prompt.user.contains("fordított"));
assert!(prompt.user.contains(&card("cups-3").unwrap().reversed));
assert!(prompt.system.contains("650") || prompt.system.contains("450"));
assert_eq!(prompt.schema["required"][2], "cards");
let english = build_tarot("en", &reading);
assert!(english.user.contains("Sun: Cancer") && english.system.contains("English"));
let mut love = value.clone();
love["topic"] = json!("love");
let prompt = build_tarot("hu", &Reading::parse(&love).unwrap());
assert!(
prompt.user.starts_with("Téma: Párkapcsolat.") && prompt.user.contains("Ne feltételezd a partner nemét")
);
love["topic"] = json!("pénz");
assert!(Reading::parse(&love).is_err());
let wrong = json!({"spread": "daily", "cards": [{"card": "major-0"}, {"card": "major-1"}]});
assert!(Reading::parse(&wrong).is_err());
assert!(Reading::parse(&json!({"spread": "daily", "cards": [{"card": "nincs"}]})).is_err());
}
}