Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
422078545e | ||
|
|
23975a8369 | ||
|
|
2a7cb467cf | ||
|
|
62df5c2764 | ||
|
|
e2cf1d7118 | ||
|
|
b0e35433ac |
@@ -112,7 +112,7 @@ Környezeti változók: `ASTRO_DATA_DIR` (alapérték: `data`), `BIND_ADDR` (`0.
|
|||||||
| `ayanamsa` | **`lahiri`**, `fagan_bradley`, `raman`, `krishnamurti`, `de_luce`, `yukteshwar`, `true_citra`, `galactic_center0_sag` (csak sziderikus zodiákusnál) |
|
| `ayanamsa` | **`lahiri`**, `fagan_bradley`, `raman`, `krishnamurti`, `de_luce`, `yukteshwar`, `true_citra`, `galactic_center0_sag` (csak sziderikus zodiákusnál) |
|
||||||
| `node_type` | **`true`**, `mean`: holdcsomópont |
|
| `node_type` | **`true`**, `mean`: holdcsomópont |
|
||||||
| `lilith_type` | **`mean`**, `true`: Fekete Hold |
|
| `lilith_type` | **`mean`**, `true`: Fekete Hold |
|
||||||
| `aspect_set` | **`major`** (együttállás, szextil, kvadrát, trigon, oppozíció), `extended` (+ félszextil, félkvadrát, kvintil, másfélkvadrát, bikvintil, kvinkunx) |
|
| `aspect_set` | `major` (együttállás, szextil, kvadrát, trigon, oppozíció), **`standard`** (a fők + kvinkunx 150°), `extended` (+ félszextil, félkvadrát, kvintil, másfélkvadrát, bikvintil) |
|
||||||
| `orb_multiplier` | **`1.0`** (0 < x ≤ 3) |
|
| `orb_multiplier` | **`1.0`** (0 < x ≤ 3) |
|
||||||
| `topocentric` | **`false`** |
|
| `topocentric` | **`false`** |
|
||||||
| `include_asteroids` | **`true`** (Ceres, Pallas, Juno, Vesta) |
|
| `include_asteroids` | **`true`** (Ceres, Pallas, Juno, Vesta) |
|
||||||
@@ -156,6 +156,8 @@ Környezeti változók: `ASTRO_DATA_DIR` (alapérték: `data`), `BIND_ADDR` (`0.
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
A holdfázis fő fázisai (újhold, első negyed, telihold, utolsó negyed) a pontos fényszögtől legfeljebb 12°-ig tartanak, és csak a megfelelő jegyek között: telihold csak szemben álló jegyekben (Kos–Mérleg, Bika–Skorpió …), újhold egy jegyben. Minden más helyzet sarló vagy domború hold.
|
||||||
|
|
||||||
Minden azonosító (bolygó, jegy, fényszög, fázis) angol `snake_case`; a magyar fordítás a frontend feladata.
|
Minden azonosító (bolygó, jegy, fényszög, fázis) angol `snake_case`; a magyar fordítás a frontend feladata.
|
||||||
|
|
||||||
### `POST /v1/synastry`: kérés
|
### `POST /v1/synastry`: kérés
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
/// Matches the backend's `ANALYSIS_PROMPT_VERSION` (part of the cache key).
|
/// Matches the backend's `ANALYSIS_PROMPT_VERSION` (part of the cache key).
|
||||||
pub const PROMPT_VERSION: &str = "v2";
|
pub const PROMPT_VERSION: &str = "v3";
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum Kind {
|
pub enum Kind {
|
||||||
@@ -168,7 +168,9 @@ Use the usual Hungarian astrological terms:
|
|||||||
- signs: Kos, Bika, Ikrek, Rák, Oroszlán, Szűz, Mérleg, Skorpió, Nyilas, Bak, Vízöntő, Halak (\"a Nap a Rák jegyében\", \"Kos Aszcendens\");
|
- signs: Kos, Bika, Ikrek, Rák, Oroszlán, Szűz, Mérleg, Skorpió, Nyilas, Bak, Vízöntő, Halak (\"a Nap a Rák jegyében\", \"Kos Aszcendens\");
|
||||||
- planets and points: Nap, Hold, Merkúr, Vénusz, Mars, Jupiter, Szaturnusz, Uránusz, Neptunusz, Plútó, Chiron (Kiron), \
|
- planets and points: Nap, Hold, Merkúr, Vénusz, Mars, Jupiter, Szaturnusz, Uránusz, Neptunusz, Plútó, Chiron (Kiron), \
|
||||||
Észak-Holdcsomópont, Dél-Holdcsomópont, Lilith (Fekete Hold), Aszcendens, Descendens, Medium Coeli (MC), Imum Coeli (IC), Szerencsepont;
|
Észak-Holdcsomópont, Dél-Holdcsomópont, Lilith (Fekete Hold), Aszcendens, Descendens, Medium Coeli (MC), Imum Coeli (IC), Szerencsepont;
|
||||||
- aspects: együttállás (konjunkció), szextil, kvadrát (négyzet), trigon, szembenállás (oppozíció);
|
- aspects: együttállás (konjunkció), szextil, kvadrát (négyzet), trigon, kvinkunx (150°), szembenállás (oppozíció);
|
||||||
|
- Moon phases: újhold, növő sarló, első negyed, növő (domború) hold, telihold, fogyó (domború) hold, utolsó negyed, \
|
||||||
|
fogyó sarló; name the phase given in the data, never another one;
|
||||||
- elements and modalities: tűz, föld, levegő, víz (\"tűz elem\", \"a föld hiánya\"); kardinális, fix, változó;
|
- elements and modalities: tűz, föld, levegő, víz (\"tűz elem\", \"a föld hiánya\"); kardinális, fix, változó;
|
||||||
Never leave English words (e.g. fire, earth, air, water) in the Hungarian text.
|
Never leave English words (e.g. fire, earth, air, water) in the Hungarian text.
|
||||||
- other: \"a 3. házban\", \"a horoszkóp uralkodója\", retrográd, uralom (domicilium), száműzetés, exaltáció, esés, nappali/éjszakai horoszkóp.";
|
- other: \"a 3. házban\", \"a horoszkóp uralkodója\", retrográd, uralom (domicilium), száműzetés, exaltáció, esés, nappali/éjszakai horoszkóp.";
|
||||||
|
|||||||
@@ -616,7 +616,7 @@ pub fn calculate_chart(engine: &dyn Ephemeris, input: &ChartInput) -> Result<Nat
|
|||||||
let elongation = normalize(moon - sun);
|
let elongation = normalize(moon - sun);
|
||||||
let moon_phase = MoonPhase {
|
let moon_phase = MoonPhase {
|
||||||
elongation,
|
elongation,
|
||||||
phase: phase_name(elongation),
|
phase: phase_name(sun, moon),
|
||||||
illumination: engine.illumination(Body::Moon, jd)?,
|
illumination: engine.illumination(Body::Moon, jd)?,
|
||||||
waxing: elongation < 180.0,
|
waxing: elongation < 180.0,
|
||||||
};
|
};
|
||||||
@@ -720,10 +720,28 @@ fn above_horizon(lon: f64, ascendant: f64) -> bool {
|
|||||||
angle::arc(ascendant, lon) >= 180.0
|
angle::arc(ascendant, lon) >= 180.0
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn phase_name(elongation: f64) -> MoonPhaseName {
|
/// At most this far from the exact new moon, quarter or full moon is the
|
||||||
|
/// Moon still in that phase, as astrologers read it.
|
||||||
|
const LUNATION_ORB: f64 = 12.0;
|
||||||
|
|
||||||
|
/// The Moon's phase from the longitudes of the Sun and the Moon. A main phase
|
||||||
|
/// (new, first quarter, full, last quarter) is the exact aspect of the lights
|
||||||
|
/// within [`LUNATION_ORB`] and in the matching signs: a full moon only between
|
||||||
|
/// opposite signs (Aries–Libra, Taurus–Scorpio, ...), a new moon in one sign.
|
||||||
|
/// Otherwise the Moon is crescent or gibbous, so a Moon 150° from the Sun (a
|
||||||
|
/// quincunx) or 30° past the opposition is not full.
|
||||||
|
pub(crate) fn phase_name(sun: f64, moon: f64) -> MoonPhaseName {
|
||||||
use MoonPhaseName::*;
|
use MoonPhaseName::*;
|
||||||
[NewMoon, WaxingCrescent, FirstQuarter, WaxingGibbous, FullMoon, WaningGibbous, LastQuarter, WaningCrescent]
|
let elongation = (moon - sun).rem_euclid(360.0);
|
||||||
[((elongation / 45.0).floor() as usize).min(7)]
|
let signs_apart = (ZodiacSign::from_longitude(moon).index() + 12 - ZodiacSign::from_longitude(sun).index()) % 12;
|
||||||
|
let main = [NewMoon, FirstQuarter, FullMoon, LastQuarter];
|
||||||
|
for (k, phase) in main.into_iter().enumerate() {
|
||||||
|
let off = (elongation - 90.0 * k as f64 + 180.0).rem_euclid(360.0) - 180.0;
|
||||||
|
if off.abs() <= LUNATION_ORB && signs_apart == 3 * k {
|
||||||
|
return phase;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
[WaxingCrescent, WaxingGibbous, WaningGibbous, WaningCrescent][((elongation / 90.0) as usize).min(3)]
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Points taking part in aspects as `(id, longitude, speed)`: everything but
|
/// Points taking part in aspects as `(id, longitude, speed)`: everything but
|
||||||
@@ -744,8 +762,10 @@ pub(crate) fn aspect_points(points: &[Point], angles: Option<&Angles>) -> Vec<(P
|
|||||||
|
|
||||||
pub(crate) fn aspect_kinds(set: AspectSet) -> Vec<AspectKind> {
|
pub(crate) fn aspect_kinds(set: AspectSet) -> Vec<AspectKind> {
|
||||||
let mut kinds = AspectKind::MAJOR.to_vec();
|
let mut kinds = AspectKind::MAJOR.to_vec();
|
||||||
if set == AspectSet::Extended {
|
match set {
|
||||||
kinds.extend(AspectKind::MINOR);
|
AspectSet::Major => {}
|
||||||
|
AspectSet::Standard => kinds.push(AspectKind::Quincunx),
|
||||||
|
AspectSet::Extended => kinds.extend(AspectKind::MINOR),
|
||||||
}
|
}
|
||||||
kinds
|
kinds
|
||||||
}
|
}
|
||||||
@@ -888,9 +908,31 @@ mod tests {
|
|||||||
// Ascendant at 0° Aries: Cancer (90°) is below (IC side), Capricorn (270°) above.
|
// Ascendant at 0° Aries: Cancer (90°) is below (IC side), Capricorn (270°) above.
|
||||||
assert!(!above_horizon(90.0, 0.0));
|
assert!(!above_horizon(90.0, 0.0));
|
||||||
assert!(above_horizon(270.0, 0.0));
|
assert!(above_horizon(270.0, 0.0));
|
||||||
assert_eq!(phase_name(0.0), MoonPhaseName::NewMoon);
|
use MoonPhaseName::*;
|
||||||
assert_eq!(phase_name(185.0), MoonPhaseName::FullMoon);
|
// (Sun, Moon) longitudes
|
||||||
assert_eq!(phase_name(359.9), MoonPhaseName::WaningCrescent);
|
assert_eq!(phase_name(10.0, 10.0), NewMoon);
|
||||||
|
assert_eq!(phase_name(15.0, 5.0), NewMoon); // 10° before, both in Aries
|
||||||
|
assert_eq!(phase_name(3.0, 355.0), WaningCrescent); // 8° before, but Pisces–Aries
|
||||||
|
assert_eq!(phase_name(28.0, 359.0), WaningCrescent); // 29° before, and in Pisces
|
||||||
|
assert_eq!(phase_name(10.0, 195.0), FullMoon); // Aries–Libra, 5° past
|
||||||
|
assert_eq!(phase_name(2.0, 170.0), WaxingGibbous); // 12° before, but Aries–Virgo
|
||||||
|
assert_eq!(phase_name(25.0, 199.0), FullMoon); // 6° before, Aries–Libra
|
||||||
|
assert_eq!(phase_name(10.0, 203.0), WaningGibbous); // 13° past: beyond the orb
|
||||||
|
// a quincunx between the lights is not a full moon
|
||||||
|
assert_eq!(phase_name(10.0, 159.0), WaxingGibbous);
|
||||||
|
assert_eq!(phase_name(10.0, 221.1), WaningGibbous);
|
||||||
|
assert_eq!(phase_name(10.0, 100.0), FirstQuarter); // Aries–Cancer
|
||||||
|
assert_eq!(phase_name(10.0, 285.0), LastQuarter); // Aries–Capricorn
|
||||||
|
assert_eq!(phase_name(10.0, 340.0), WaningCrescent);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_default_aspects_include_the_quincunx() {
|
||||||
|
let pts = [(PointId::Sun, 10.0, 1.0), (PointId::Moon, 159.0, 13.0)]; // 149° apart
|
||||||
|
assert_eq!(AspectSet::default(), AspectSet::Standard);
|
||||||
|
let found = find_aspects(&pts, AspectSet::Standard, 1.0);
|
||||||
|
assert_eq!(found.iter().map(|a| a.aspect).collect::<Vec<_>>(), [AspectKind::Quincunx]);
|
||||||
|
assert!(find_aspects(&pts, AspectSet::Major, 1.0).is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -37,8 +37,15 @@ const NEAR_DAYS: f64 = 200.0;
|
|||||||
|
|
||||||
const TRANSITING: [Body; 5] = [Body::Jupiter, Body::Saturn, Body::Uranus, Body::Neptune, Body::Pluto];
|
const TRANSITING: [Body; 5] = [Body::Jupiter, Body::Saturn, Body::Uranus, Body::Neptune, Body::Pluto];
|
||||||
const PROGRESSED: [Body; 5] = [Body::Sun, Body::Moon, Body::Mercury, Body::Venus, Body::Mars];
|
const PROGRESSED: [Body; 5] = [Body::Sun, Body::Moon, Body::Mercury, Body::Venus, Body::Mars];
|
||||||
const ASPECTS: [AspectKind; 5] =
|
/// The aspects of the default chart (`AspectSet::Standard`): the major ones and the quincunx.
|
||||||
[AspectKind::Conjunction, AspectKind::Sextile, AspectKind::Square, AspectKind::Trine, AspectKind::Opposition];
|
const ASPECTS: [AspectKind; 6] = [
|
||||||
|
AspectKind::Conjunction,
|
||||||
|
AspectKind::Sextile,
|
||||||
|
AspectKind::Square,
|
||||||
|
AspectKind::Trine,
|
||||||
|
AspectKind::Quincunx,
|
||||||
|
AspectKind::Opposition,
|
||||||
|
];
|
||||||
|
|
||||||
type Result<T> = std::result::Result<T, EngineError>;
|
type Result<T> = std::result::Result<T, EngineError>;
|
||||||
|
|
||||||
@@ -409,7 +416,7 @@ impl Year<'_> {
|
|||||||
|
|
||||||
// The progressed lunation phase: the progressed Moon's distance from the progressed Sun.
|
// The progressed lunation phase: the progressed Moon's distance from the progressed Sun.
|
||||||
let (sun, moon) = (&samples[0], &samples[1]);
|
let (sun, moon) = (&samples[0], &samples[1]);
|
||||||
let phase_at = |i: usize| phase_name((moon.lon[i] - sun.lon[i]).rem_euclid(360.0));
|
let phase_at = |i: usize| phase_name(sun.lon[i], moon.lon[i]);
|
||||||
let lunar_phase = phase_at(0);
|
let lunar_phase = phase_at(0);
|
||||||
let lunar_phase_change = if known {
|
let lunar_phase_change = if known {
|
||||||
(1..moon.lon.len())
|
(1..moon.lon.len())
|
||||||
|
|||||||
@@ -96,8 +96,10 @@ pub enum Ayanamsa {
|
|||||||
#[serde(rename_all = "snake_case")]
|
#[serde(rename_all = "snake_case")]
|
||||||
pub enum AspectSet {
|
pub enum AspectSet {
|
||||||
/// Conjunction, sextile, square, trine, opposition.
|
/// Conjunction, sextile, square, trine, opposition.
|
||||||
#[default]
|
|
||||||
Major,
|
Major,
|
||||||
|
/// The major aspects plus the quincunx (150°), which most astrologers read.
|
||||||
|
#[default]
|
||||||
|
Standard,
|
||||||
/// Major aspects plus semisextile, semisquare, quintile, sesquiquadrate, biquintile, quincunx.
|
/// Major aspects plus semisextile, semisquare, quintile, sesquiquadrate, biquintile, quincunx.
|
||||||
Extended,
|
Extended,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
-- The yearly forecast prompt is editable on the admin page too, and can be
|
||||||
|
-- tried on one of the admin's own forecasts.
|
||||||
|
ALTER TABLE prompt_revisions DROP CONSTRAINT prompt_revisions_kind_check;
|
||||||
|
ALTER TABLE prompt_revisions ADD CONSTRAINT prompt_revisions_kind_check
|
||||||
|
CHECK (kind IN ('summary', 'natal', 'synastry', 'forecast'));
|
||||||
|
|
||||||
|
ALTER TABLE prompt_previews DROP CONSTRAINT prompt_previews_target;
|
||||||
|
ALTER TABLE prompt_previews
|
||||||
|
ADD COLUMN forecast_id uuid REFERENCES forecasts ON DELETE CASCADE,
|
||||||
|
ADD CONSTRAINT prompt_previews_target CHECK (
|
||||||
|
(kind IN ('summary', 'natal') AND chart_id IS NOT NULL AND synastry_id IS NULL AND forecast_id IS NULL)
|
||||||
|
OR (kind = 'synastry' AND synastry_id IS NOT NULL AND chart_id IS NULL AND forecast_id IS NULL)
|
||||||
|
OR (kind = 'forecast' AND forecast_id IS NOT NULL AND chart_id IS NULL AND synastry_id IS NULL)
|
||||||
|
);
|
||||||
+3
-2
@@ -7,7 +7,7 @@ Egy év születésnaptól születésnapig, több bevett előrejelző módszerbő
|
|||||||
| Módszer | Mit ad | Hol számolódik |
|
| Módszer | Mit ad | Hol számolódik |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| **Szolár** (szoláris visszatérés) | Az a pillanat, amikor a Nap visszatér a születéskori hosszúságára; az erre a pillanatra és a születésnapi tartózkodási helyre felállított képlet „az év képlete”. | `astro_engine::forecast::solar_return`, a képlet a horoscope-api-ban |
|
| **Szolár** (szoláris visszatérés) | Az a pillanat, amikor a Nap visszatér a születéskori hosszúságára; az erre a pillanatra és a születésnapi tartózkodási helyre felállított képlet „az év képlete”. | `astro_engine::forecast::solar_return`, a képlet a horoscope-api-ban |
|
||||||
| **Tranzitok** | A Jupiter, Szaturnusz, Uránusz, Neptunusz és Plútó fő fényszögei (együttállás, szextil, kvadrát, trigon, szembenállás) a tíz bolygóhoz, az Aszcendenshez és az MC-hez, 1° hatásfokkal: pontos dátumok (retrográd áthaladásokkal) és hatásidők. A lassú bolygók házai és házváltásai. | `forecast.rs`, `Year::transits` |
|
| **Tranzitok** | A Jupiter, Szaturnusz, Uránusz, Neptunusz és Plútó fő fényszögei (együttállás, szextil, kvadrát, trigon, szembenállás) és a kvinkunx (150°) a tíz bolygóhoz, az Aszcendenshez és az MC-hez, 1° hatásfokkal: pontos dátumok (retrográd áthaladásokkal) és hatásidők. A lassú bolygók házai és házváltásai. | `forecast.rs`, `Year::transits` |
|
||||||
| **Szekunder direkció** | „Egy nap = egy év”: a progresszív Nap, Hold, Merkúr, Vénusz, Mars helye, jegy- és házváltásai, fényszögei a születési képlethez, a progresszív holdfázis. | `Year::progressions` |
|
| **Szekunder direkció** | „Egy nap = egy év”: a progresszív Nap, Hold, Merkúr, Vénusz, Mars helye, jegy- és házváltásai, fényszögei a születési képlethez, a progresszív holdfázis. | `Year::progressions` |
|
||||||
| **Éves profekció** | Minden életév egy házat aktivál (egész jegyes házak az Aszcendenstől); a jegy hagyományos uralkodója „az év ura”. | `Year::profection` |
|
| **Éves profekció** | Minden életév egy házat aktivál (egész jegyes házak az Aszcendenstől); a jegy hagyományos uralkodója „az év ura”. | `Year::profection` |
|
||||||
| **Fogyatkozások** | Az év nap- és holdfogyatkozásai (a félárnyékos holdfogyatkozás nélkül), a születési házuk, és ha 3°-on belül érintenek egy születési pontot. | Swiss Ephemeris `swe_sol_eclipse_when_glob`, `swe_lun_eclipse_when` |
|
| **Fogyatkozások** | Az év nap- és holdfogyatkozásai (a félárnyékos holdfogyatkozás nélkül), a születési házuk, és ha 3°-on belül érintenek egy születési pontot. | Swiss Ephemeris `swe_sol_eclipse_when_glob`, `swe_lun_eclipse_when` |
|
||||||
@@ -31,8 +31,9 @@ A modellhez nem megy születési dátum, hely vagy pontos életkor (csak évtize
|
|||||||
|
|
||||||
Trendekről, lehetőségekről és időzítésről szól, nem biztos eseményekről. Betegségről, halálról, balesetről, terhességről, perekről és pénzügyi nyereségről vagy veszteségről nem jósol (`FORECAST_RULES` a promptban).
|
Trendekről, lehetőségekről és időzítésről szól, nem biztos eseményekről. Betegségről, halálról, balesetről, terhességről, perekről és pénzügyi nyereségről vagy veszteségről nem jósol (`FORECAST_RULES` a promptban).
|
||||||
|
|
||||||
|
A rendszerprompt az admin felületen (Promptok → Éves előrejelzés) szerkeszthető, és mentés előtt kipróbálható az admin egyik saját, már kiszámolt évén. A változás csak az ezután kért elemzésekre hat. A modell kapta adatsor (`compact::forecast`) és a kimeneti séma a kódban van.
|
||||||
|
|
||||||
## Később
|
## Később
|
||||||
|
|
||||||
- Havi előrejelzés: holdvisszatérés és a hónap gyorsabb tranzitjai (Mars, Vénusz, Nap).
|
- Havi előrejelzés: holdvisszatérés és a hónap gyorsabb tranzitjai (Mars, Vénusz, Nap).
|
||||||
- Tranzitok a kompozit képletre: „mi vár rátok idén”.
|
- Tranzitok a kompozit képletre: „mi vár rátok idén”.
|
||||||
- Az admin promptszerkesztőben az előrejelzés promptja is szerkeszthető legyen.
|
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh
|
|||||||
| `SUPPORTED_LOCALES` | `hu,en` | felület- és elemzésnyelvek; az első az alapértelmezett |
|
| `SUPPORTED_LOCALES` | `hu,en` | felület- és elemzésnyelvek; az első az alapértelmezett |
|
||||||
| `ANALYSIS_MODEL` | `anthropic/claude-opus-5.5` | ez írja a fizetős részletes elemzéseket |
|
| `ANALYSIS_MODEL` | `anthropic/claude-opus-5.5` | ez írja a fizetős részletes elemzéseket |
|
||||||
| `SUMMARY_MODEL` | `anthropic/claude-sonnet-5.5` | ez írja minden mentett képlet ingyenes rövid összefoglalóját (kb. 1 cent darabonként) |
|
| `SUMMARY_MODEL` | `anthropic/claude-sonnet-5.5` | ez írja minden mentett képlet ingyenes rövid összefoglalóját (kb. 1 cent darabonként) |
|
||||||
| `ANALYSIS_PROMPT_VERSION` | `v2` | a prompt verziója (az elemzés-gyorsítótár kulcsának része) |
|
| `ANALYSIS_PROMPT_VERSION` | `v3` | a prompt verziója (az elemzés-gyorsítótár kulcsának része) |
|
||||||
| `MAX_CHARTS_PER_USER` | `1000` | biztonsági felső korlát a képletek számára |
|
| `MAX_CHARTS_PER_USER` | `1000` | biztonsági felső korlát a képletek számára |
|
||||||
| `BIND_ADDR`, `LOG_FORMAT`, `RUST_LOG` | `0.0.0.0:8081`, `text`, `info` | |
|
| `BIND_ADDR`, `LOG_FORMAT`, `RUST_LOG` | `0.0.0.0:8081`, `text`, `info` | |
|
||||||
|
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ pub struct Config {
|
|||||||
/// `SUMMARY_MODEL`: writes the free short summary of every saved chart
|
/// `SUMMARY_MODEL`: writes the free short summary of every saved chart
|
||||||
/// (default `anthropic/claude-sonnet-5.5`, about 1 US cent each).
|
/// (default `anthropic/claude-sonnet-5.5`, about 1 US cent each).
|
||||||
pub summary_model: String,
|
pub summary_model: String,
|
||||||
/// `ANALYSIS_PROMPT_VERSION` (default `v2`); part of the analysis cache key.
|
/// `ANALYSIS_PROMPT_VERSION` (default `v3`); part of the analysis cache key.
|
||||||
pub prompt_version: String,
|
pub prompt_version: String,
|
||||||
/// `MAX_CHARTS_PER_USER` (default 1000): a safety cap.
|
/// `MAX_CHARTS_PER_USER` (default 1000): a safety cap.
|
||||||
pub max_charts_per_user: i64,
|
pub max_charts_per_user: i64,
|
||||||
@@ -121,7 +121,7 @@ impl Config {
|
|||||||
supported_locales,
|
supported_locales,
|
||||||
analysis_model: var("ANALYSIS_MODEL").unwrap_or_else(|| "anthropic/claude-opus-5.5".into()),
|
analysis_model: var("ANALYSIS_MODEL").unwrap_or_else(|| "anthropic/claude-opus-5.5".into()),
|
||||||
summary_model: var("SUMMARY_MODEL").unwrap_or_else(|| "anthropic/claude-sonnet-5.5".into()),
|
summary_model: var("SUMMARY_MODEL").unwrap_or_else(|| "anthropic/claude-sonnet-5.5".into()),
|
||||||
prompt_version: var("ANALYSIS_PROMPT_VERSION").unwrap_or_else(|| "v2".into()),
|
prompt_version: var("ANALYSIS_PROMPT_VERSION").unwrap_or_else(|| "v3".into()),
|
||||||
max_charts_per_user: parsed("MAX_CHARTS_PER_USER", 1000)?,
|
max_charts_per_user: parsed("MAX_CHARTS_PER_USER", 1000)?,
|
||||||
free_person_slots: parsed("FREE_PERSON_SLOTS", 0)?,
|
free_person_slots: parsed("FREE_PERSON_SLOTS", 0)?,
|
||||||
signup_mode: match var("SIGNUP_MODE").as_deref() {
|
signup_mode: match var("SIGNUP_MODE").as_deref() {
|
||||||
|
|||||||
@@ -68,6 +68,9 @@ async fn main() -> anyhow::Result<()> {
|
|||||||
horoscope_api = %config.horoscope_api_url,
|
horoscope_api = %config.horoscope_api_url,
|
||||||
"database ready"
|
"database ready"
|
||||||
);
|
);
|
||||||
|
if std::env::args().nth(1).as_deref() == Some("recalculate") {
|
||||||
|
return routes::recalculate(&AppState::new(pool, config)).await;
|
||||||
|
}
|
||||||
let app = routes::router(Arc::new(AppState::new(pool, config)));
|
let app = routes::router(Arc::new(AppState::new(pool, config)));
|
||||||
let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
|
let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
|
||||||
tracing::info!(%addr, "listening");
|
tracing::info!(%addr, "listening");
|
||||||
|
|||||||
@@ -113,7 +113,7 @@ fn optional_body(body: &[u8]) -> Result<AnalysisRequest, ApiError> {
|
|||||||
serde_json::from_slice(body).map_err(|e| ApiError::BadRequest(format!("invalid request body: {e}")))
|
serde_json::from_slice(body).map_err(|e| ApiError::BadRequest(format!("invalid request body: {e}")))
|
||||||
}
|
}
|
||||||
|
|
||||||
enum Target {
|
pub(super) enum Target {
|
||||||
Natal { chart_id: Uuid, hash: String },
|
Natal { chart_id: Uuid, hash: String },
|
||||||
Summary { chart_id: Uuid, hash: String },
|
Summary { chart_id: Uuid, hash: String },
|
||||||
Synastry { synastry_id: Uuid, hash: String },
|
Synastry { synastry_id: Uuid, hash: String },
|
||||||
@@ -143,7 +143,7 @@ async fn request(
|
|||||||
/// Returns the existing analysis with the same cache key for this target,
|
/// Returns the existing analysis with the same cache key for this target,
|
||||||
/// copies a finished one from another chart with the same data, or queues a
|
/// copies a finished one from another chart with the same data, or queues a
|
||||||
/// new one (spending one `unit`, if given). 200, 201 and 202 respectively.
|
/// new one (spending one `unit`, if given). 200, 201 and 202 respectively.
|
||||||
async fn queue(
|
pub(super) async fn queue(
|
||||||
state: &AppState,
|
state: &AppState,
|
||||||
user: Uuid,
|
user: Uuid,
|
||||||
target: &Target,
|
target: &Target,
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ pub struct ChartRow {
|
|||||||
pub updated_at: OffsetDateTime,
|
pub updated_at: OffsetDateTime,
|
||||||
}
|
}
|
||||||
|
|
||||||
const CHART_COLUMNS: &str =
|
pub(super) const CHART_COLUMNS: &str =
|
||||||
"id, owner_id, label, is_primary, kind, birth_data, result, chart_hash, created_at, updated_at";
|
"id, owner_id, label, is_primary, kind, birth_data, result, chart_hash, created_at, updated_at";
|
||||||
|
|
||||||
impl ChartRow {
|
impl ChartRow {
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ use uuid::Uuid;
|
|||||||
|
|
||||||
use super::charts::{ChartRow, find_chart, owned_chart};
|
use super::charts::{ChartRow, find_chart, owned_chart};
|
||||||
use super::{Body, IdPath, St};
|
use super::{Body, IdPath, St};
|
||||||
|
use crate::AppState;
|
||||||
use crate::auth::AuthUser;
|
use crate::auth::AuthUser;
|
||||||
use crate::error::{ApiError, ApiResult};
|
use crate::error::{ApiError, ApiResult};
|
||||||
use crate::views::{rfc3339, sha256_hex};
|
use crate::views::{rfc3339, sha256_hex};
|
||||||
@@ -224,15 +225,7 @@ pub async fn create(
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut request = json!({ "birth": chart.birth_data, "year": year });
|
let (result, forecast_hash) = calculate(&state, &chart, year, location.as_ref(), &location_key).await?;
|
||||||
if let Some(l) = &location {
|
|
||||||
request["location"] = l.clone();
|
|
||||||
}
|
|
||||||
let mut result = state.horoscope.forecast(&request).await?;
|
|
||||||
if let Some(obj) = result.as_object_mut() {
|
|
||||||
obj.remove("meta");
|
|
||||||
}
|
|
||||||
let forecast_hash = forecast_hash(&chart.chart_hash, year, &location_key, &result);
|
|
||||||
let row: ForecastRow = sqlx::query_as(&format!(
|
let row: ForecastRow = sqlx::query_as(&format!(
|
||||||
"INSERT INTO forecasts (id, chart_id, chart_hash, year, location, location_key, result, forecast_hash, created_by) \
|
"INSERT INTO forecasts (id, chart_id, chart_hash, year, location, location_key, result, forecast_hash, created_by) \
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) \
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) \
|
||||||
@@ -253,6 +246,26 @@ pub async fn create(
|
|||||||
Ok((StatusCode::CREATED, Json(row.view())))
|
Ok((StatusCode::CREATED, Json(row.view())))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// One year of a stored chart as stored: `(result, forecast_hash)`.
|
||||||
|
pub(super) async fn calculate(
|
||||||
|
state: &AppState,
|
||||||
|
chart: &ChartRow,
|
||||||
|
year: i32,
|
||||||
|
location: Option<&Value>,
|
||||||
|
location_key: &str,
|
||||||
|
) -> Result<(Value, String), ApiError> {
|
||||||
|
let mut request = json!({ "birth": chart.birth_data, "year": year });
|
||||||
|
if let Some(l) = location {
|
||||||
|
request["location"] = l.clone();
|
||||||
|
}
|
||||||
|
let mut result = state.horoscope.forecast(&request).await?;
|
||||||
|
if let Some(obj) = result.as_object_mut() {
|
||||||
|
obj.remove("meta");
|
||||||
|
}
|
||||||
|
let hash = forecast_hash(&chart.chart_hash, year, location_key, &result);
|
||||||
|
Ok((result, hash))
|
||||||
|
}
|
||||||
|
|
||||||
/// Identifies a forecast independently of how the place was entered: the
|
/// Identifies a forecast independently of how the place was entered: the
|
||||||
/// chart, the year and the resolved place and time zone of the solar return.
|
/// chart, the year and the resolved place and time zone of the solar return.
|
||||||
fn forecast_hash(chart_hash: &str, year: i32, location_key: &str, result: &Value) -> String {
|
fn forecast_hash(chart_hash: &str, year: i32, location_key: &str, result: &Value) -> String {
|
||||||
|
|||||||
@@ -14,9 +14,12 @@ mod forecasts;
|
|||||||
mod invitations;
|
mod invitations;
|
||||||
mod payments;
|
mod payments;
|
||||||
mod prompts;
|
mod prompts;
|
||||||
|
mod recalculate;
|
||||||
mod shares;
|
mod shares;
|
||||||
mod synastries;
|
mod synastries;
|
||||||
|
|
||||||
|
pub use recalculate::run as recalculate;
|
||||||
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use axum::extract::{Path, State};
|
use axum::extract::{Path, State};
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ use crate::error::{ApiError, ApiResult};
|
|||||||
use crate::views::{rfc3339, rfc3339_opt};
|
use crate::views::{rfc3339, rfc3339_opt};
|
||||||
|
|
||||||
/// The kinds whose prompt the admin page edits.
|
/// The kinds whose prompt the admin page edits.
|
||||||
const EDITABLE: [Kind; 3] = [Kind::Summary, Kind::Natal, Kind::Synastry];
|
const EDITABLE: [Kind; 4] = [Kind::Summary, Kind::Natal, Kind::Synastry, Kind::Forecast];
|
||||||
const MAX_CHARS: usize = 50_000;
|
const MAX_CHARS: usize = 50_000;
|
||||||
const HISTORY: i64 = 20;
|
const HISTORY: i64 = 20;
|
||||||
/// Test runs of one admin waiting or being written at the same time.
|
/// Test runs of one admin waiting or being written at the same time.
|
||||||
@@ -162,6 +162,8 @@ pub struct StartPreview {
|
|||||||
chart_id: Option<Uuid>,
|
chart_id: Option<Uuid>,
|
||||||
/// One of the admin's own comparisons, for a synastry analysis.
|
/// One of the admin's own comparisons, for a synastry analysis.
|
||||||
synastry_id: Option<Uuid>,
|
synastry_id: Option<Uuid>,
|
||||||
|
/// A yearly forecast of one of the admin's own charts, for a forecast analysis.
|
||||||
|
forecast_id: Option<Uuid>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(sqlx::FromRow)]
|
#[derive(sqlx::FromRow)]
|
||||||
@@ -170,6 +172,7 @@ struct PreviewRow {
|
|||||||
kind: String,
|
kind: String,
|
||||||
chart_id: Option<Uuid>,
|
chart_id: Option<Uuid>,
|
||||||
synastry_id: Option<Uuid>,
|
synastry_id: Option<Uuid>,
|
||||||
|
forecast_id: Option<Uuid>,
|
||||||
language: String,
|
language: String,
|
||||||
model: String,
|
model: String,
|
||||||
status: String,
|
status: String,
|
||||||
@@ -184,7 +187,7 @@ struct PreviewRow {
|
|||||||
completed_at: Option<OffsetDateTime>,
|
completed_at: Option<OffsetDateTime>,
|
||||||
}
|
}
|
||||||
|
|
||||||
const PREVIEW_COLUMNS: &str = "id, kind, chart_id, synastry_id, language, model, status, content, error, model_used, \
|
const PREVIEW_COLUMNS: &str = "id, kind, chart_id, synastry_id, forecast_id, language, model, status, content, error, model_used, \
|
||||||
input_tokens, output_tokens, cost_usd, created_at, started_at, completed_at";
|
input_tokens, output_tokens, cost_usd, created_at, started_at, completed_at";
|
||||||
|
|
||||||
impl PreviewRow {
|
impl PreviewRow {
|
||||||
@@ -192,6 +195,7 @@ impl PreviewRow {
|
|||||||
let seconds = self.started_at.zip(self.completed_at).map(|(s, c)| (c - s).whole_seconds());
|
let seconds = self.started_at.zip(self.completed_at).map(|(s, c)| (c - s).whole_seconds());
|
||||||
json!({
|
json!({
|
||||||
"id": self.id, "kind": self.kind, "chart_id": self.chart_id, "synastry_id": self.synastry_id,
|
"id": self.id, "kind": self.kind, "chart_id": self.chart_id, "synastry_id": self.synastry_id,
|
||||||
|
"forecast_id": self.forecast_id,
|
||||||
"language": self.language, "model": self.model, "status": self.status, "content": self.content,
|
"language": self.language, "model": self.model, "status": self.status, "content": self.content,
|
||||||
"error": self.error, "model_used": self.model_used, "input_tokens": self.input_tokens,
|
"error": self.error, "model_used": self.model_used, "input_tokens": self.input_tokens,
|
||||||
"output_tokens": self.output_tokens, "cost_usd": self.cost_usd, "created_at": rfc3339(self.created_at),
|
"output_tokens": self.output_tokens, "cost_usd": self.cost_usd, "created_at": rfc3339(self.created_at),
|
||||||
@@ -208,29 +212,27 @@ pub async fn start_preview(
|
|||||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||||
let kind = parse_target(&state, &kind, &language)?;
|
let kind = parse_target(&state, &kind, &language)?;
|
||||||
let system = clean_system(&req.system)?;
|
let system = clean_system(&req.system)?;
|
||||||
// The target must be the admin's own: a chart, or for a synastry analysis a comparison.
|
// The target must be the admin's own: a chart, a comparison or a forecast.
|
||||||
let (chart_id, synastry_id, found) = match (kind, req.chart_id, req.synastry_id) {
|
let (chart_id, synastry_id, forecast_id) = (req.chart_id, req.synastry_id, req.forecast_id);
|
||||||
(Kind::Synastry, None, Some(id)) => {
|
let (query, id, what) = match (kind, chart_id, synastry_id, forecast_id) {
|
||||||
let row: Option<(Uuid,)> = sqlx::query_as("SELECT id FROM synastries WHERE id = $1 AND owner_id = $2")
|
(Kind::Summary | Kind::Natal, Some(id), None, None) => {
|
||||||
.bind(id)
|
("SELECT id FROM charts WHERE id = $1 AND owner_id = $2", id, "chart")
|
||||||
.bind(admin.id())
|
|
||||||
.fetch_optional(&state.db)
|
|
||||||
.await?;
|
|
||||||
(None, Some(id), row.map(|_| "synastry"))
|
|
||||||
}
|
}
|
||||||
(Kind::Summary | Kind::Natal, Some(id), None) => {
|
(Kind::Synastry, None, Some(id), None) => {
|
||||||
let row: Option<(Uuid,)> = sqlx::query_as("SELECT id FROM charts WHERE id = $1 AND owner_id = $2")
|
("SELECT id FROM synastries WHERE id = $1 AND owner_id = $2", id, "synastry")
|
||||||
.bind(id)
|
|
||||||
.bind(admin.id())
|
|
||||||
.fetch_optional(&state.db)
|
|
||||||
.await?;
|
|
||||||
(Some(id), None, row.map(|_| "chart"))
|
|
||||||
}
|
}
|
||||||
|
(Kind::Forecast, None, None, Some(id)) => (
|
||||||
|
"SELECT f.id FROM forecasts f JOIN charts c ON c.id = f.chart_id WHERE f.id = $1 AND c.owner_id = $2",
|
||||||
|
id,
|
||||||
|
"forecast",
|
||||||
|
),
|
||||||
(Kind::Synastry, ..) => return Err(ApiError::BadRequest("a synastry analysis needs synastry_id".into())),
|
(Kind::Synastry, ..) => return Err(ApiError::BadRequest("a synastry analysis needs synastry_id".into())),
|
||||||
|
(Kind::Forecast, ..) => return Err(ApiError::BadRequest("a forecast analysis needs forecast_id".into())),
|
||||||
_ => return Err(ApiError::BadRequest("this analysis needs chart_id".into())),
|
_ => return Err(ApiError::BadRequest("this analysis needs chart_id".into())),
|
||||||
};
|
};
|
||||||
|
let found: Option<(Uuid,)> = sqlx::query_as(query).bind(id).bind(admin.id()).fetch_optional(&state.db).await?;
|
||||||
if found.is_none() {
|
if found.is_none() {
|
||||||
return Err(ApiError::NotFound(if synastry_id.is_some() { "synastry" } else { "chart" }));
|
return Err(ApiError::NotFound(what));
|
||||||
}
|
}
|
||||||
let (open,): (i64,) = sqlx::query_as(
|
let (open,): (i64,) = sqlx::query_as(
|
||||||
"SELECT count(*) FROM prompt_previews WHERE created_by = $1 AND status IN ('pending', 'running')",
|
"SELECT count(*) FROM prompt_previews WHERE created_by = $1 AND status IN ('pending', 'running')",
|
||||||
@@ -249,13 +251,14 @@ pub async fn start_preview(
|
|||||||
_ => &state.config.analysis_model,
|
_ => &state.config.analysis_model,
|
||||||
};
|
};
|
||||||
let row: PreviewRow = sqlx::query_as(&format!(
|
let row: PreviewRow = sqlx::query_as(&format!(
|
||||||
"INSERT INTO prompt_previews (id, kind, chart_id, synastry_id, language, model, system, created_by) \
|
"INSERT INTO prompt_previews (id, kind, chart_id, synastry_id, forecast_id, language, model, system, created_by) \
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING {PREVIEW_COLUMNS}"
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING {PREVIEW_COLUMNS}"
|
||||||
))
|
))
|
||||||
.bind(Uuid::now_v7())
|
.bind(Uuid::now_v7())
|
||||||
.bind(kind.as_str())
|
.bind(kind.as_str())
|
||||||
.bind(chart_id)
|
.bind(chart_id)
|
||||||
.bind(synastry_id)
|
.bind(synastry_id)
|
||||||
|
.bind(forecast_id)
|
||||||
.bind(&language)
|
.bind(&language)
|
||||||
.bind(model)
|
.bind(model)
|
||||||
.bind(&system)
|
.bind(&system)
|
||||||
|
|||||||
@@ -0,0 +1,117 @@
|
|||||||
|
//! `backend recalculate`: after a change in the calculation, recalculates
|
||||||
|
//! every stored chart, comparison and forecast with the horoscope service,
|
||||||
|
//! then deletes all analyses and queues them again: a short summary and a
|
||||||
|
//! detailed analysis for every chart, one analysis for every comparison and
|
||||||
|
//! every forecast. Nobody is charged; each analysis is requested in the name
|
||||||
|
//! of the owner, in the owner's language.
|
||||||
|
|
||||||
|
use anyhow::Context;
|
||||||
|
use serde_json::Value;
|
||||||
|
use sqlx::PgPool;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use super::analyses::{Target, queue};
|
||||||
|
use super::charts::{CHART_COLUMNS, ChartRow};
|
||||||
|
use crate::AppState;
|
||||||
|
|
||||||
|
async fn all_charts(db: &PgPool) -> Result<Vec<ChartRow>, sqlx::Error> {
|
||||||
|
sqlx::query_as(&format!("SELECT {CHART_COLUMNS} FROM charts ORDER BY created_at")).fetch_all(db).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn locale(db: &PgPool, user: Uuid) -> Result<String, sqlx::Error> {
|
||||||
|
sqlx::query_scalar("SELECT locale FROM users WHERE id = $1").bind(user).fetch_one(db).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn run(state: &AppState) -> anyhow::Result<()> {
|
||||||
|
let db = &state.db;
|
||||||
|
|
||||||
|
let charts = all_charts(db).await?;
|
||||||
|
for chart in &charts {
|
||||||
|
let (_, result, hash) = super::charts::calculate(state, chart.birth_data.clone())
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("chart {}: {e:?}", chart.id))?;
|
||||||
|
sqlx::query("UPDATE charts SET result = $1, chart_hash = $2 WHERE id = $3")
|
||||||
|
.bind(&result)
|
||||||
|
.bind(&hash)
|
||||||
|
.bind(chart.id)
|
||||||
|
.execute(db)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
tracing::info!(count = charts.len(), "charts recalculated");
|
||||||
|
let charts = all_charts(db).await?;
|
||||||
|
let chart = |id: Uuid| charts.iter().find(|c| c.id == id).context("missing chart");
|
||||||
|
|
||||||
|
let synastries: Vec<(Uuid, Uuid, Uuid, Uuid)> =
|
||||||
|
sqlx::query_as("SELECT id, owner_id, chart1_id, chart2_id FROM synastries ORDER BY created_at")
|
||||||
|
.fetch_all(db)
|
||||||
|
.await?;
|
||||||
|
let mut synastry_hashes = Vec::new();
|
||||||
|
for &(id, owner, chart1, chart2) in &synastries {
|
||||||
|
let (result, hash) = super::synastries::calculate(state, chart(chart1)?, chart(chart2)?)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("synastry {id}: {e:?}"))?;
|
||||||
|
sqlx::query("UPDATE synastries SET result = $1, synastry_hash = $2 WHERE id = $3")
|
||||||
|
.bind(&result)
|
||||||
|
.bind(&hash)
|
||||||
|
.bind(id)
|
||||||
|
.execute(db)
|
||||||
|
.await?;
|
||||||
|
synastry_hashes.push((id, owner, hash));
|
||||||
|
}
|
||||||
|
tracing::info!(count = synastries.len(), "comparisons recalculated");
|
||||||
|
|
||||||
|
let forecasts: Vec<(Uuid, Uuid, i32, Option<Value>, String)> =
|
||||||
|
sqlx::query_as("SELECT id, chart_id, year, location, location_key FROM forecasts ORDER BY created_at")
|
||||||
|
.fetch_all(db)
|
||||||
|
.await?;
|
||||||
|
let mut forecast_hashes = Vec::new();
|
||||||
|
for (id, chart_id, year, location, location_key) in &forecasts {
|
||||||
|
let c = chart(*chart_id)?;
|
||||||
|
let (result, hash) = super::forecasts::calculate(state, c, *year, location.as_ref(), location_key)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("forecast {id}: {e:?}"))?;
|
||||||
|
let updated =
|
||||||
|
sqlx::query("UPDATE forecasts SET chart_hash = $1, result = $2, forecast_hash = $3 WHERE id = $4")
|
||||||
|
.bind(&c.chart_hash)
|
||||||
|
.bind(&result)
|
||||||
|
.bind(&hash)
|
||||||
|
.bind(id)
|
||||||
|
.execute(db)
|
||||||
|
.await;
|
||||||
|
match updated {
|
||||||
|
Ok(_) => forecast_hashes.push((*id, c.owner_id, hash)),
|
||||||
|
// The same year and place from an earlier version of the birth data: a duplicate now.
|
||||||
|
Err(sqlx::Error::Database(e)) if e.is_unique_violation() => {
|
||||||
|
sqlx::query("DELETE FROM forecasts WHERE id = $1").bind(id).execute(db).await?;
|
||||||
|
tracing::warn!(%id, "duplicate forecast removed");
|
||||||
|
}
|
||||||
|
Err(e) => return Err(e.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tracing::info!(count = forecast_hashes.len(), "forecasts recalculated");
|
||||||
|
|
||||||
|
let deleted = sqlx::query("DELETE FROM analyses").execute(db).await?.rows_affected();
|
||||||
|
let summary_model = &state.config.summary_model;
|
||||||
|
let analysis_model = &state.config.analysis_model;
|
||||||
|
let mut queued = 0;
|
||||||
|
for c in &charts {
|
||||||
|
let language = locale(db, c.owner_id).await?;
|
||||||
|
let summary = Target::Summary { chart_id: c.id, hash: c.chart_hash.clone() };
|
||||||
|
queue(state, c.owner_id, &summary, &language, summary_model, None).await?;
|
||||||
|
let natal = Target::Natal { chart_id: c.id, hash: c.chart_hash.clone() };
|
||||||
|
queue(state, c.owner_id, &natal, &language, analysis_model, None).await?;
|
||||||
|
queued += 2;
|
||||||
|
}
|
||||||
|
for (synastry_id, owner, hash) in synastry_hashes {
|
||||||
|
let target = Target::Synastry { synastry_id, hash };
|
||||||
|
queue(state, owner, &target, &locale(db, owner).await?, analysis_model, None).await?;
|
||||||
|
queued += 1;
|
||||||
|
}
|
||||||
|
for (forecast_id, owner, hash) in forecast_hashes {
|
||||||
|
let target = Target::Forecast { forecast_id, hash };
|
||||||
|
queue(state, owner, &target, &locale(db, owner).await?, analysis_model, None).await?;
|
||||||
|
queued += 1;
|
||||||
|
}
|
||||||
|
tracing::info!(deleted, queued, "analyses queued again");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -108,6 +108,23 @@ fn without(value: &Value, keys: &[&str]) -> Value {
|
|||||||
Value::Object(map)
|
Value::Object(map)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The comparison of two stored charts as stored: `(result, synastry_hash)`.
|
||||||
|
pub(super) async fn calculate(
|
||||||
|
state: &AppState,
|
||||||
|
chart1: &ChartRow,
|
||||||
|
chart2: &ChartRow,
|
||||||
|
) -> Result<(Value, String), ApiError> {
|
||||||
|
let request = json!({
|
||||||
|
"person1": without(&chart1.birth_data, &["options"]),
|
||||||
|
"person2": without(&chart2.birth_data, &["options"]),
|
||||||
|
"options": chart1.birth_data.get("options").cloned().unwrap_or_else(|| json!({})),
|
||||||
|
});
|
||||||
|
let response = state.horoscope.synastry(&request).await?;
|
||||||
|
let result = without(&response, &["person1", "person2", "meta"]);
|
||||||
|
let hash = synastry_hash(&chart1.chart_hash, &chart2.chart_hash, &result["settings"]);
|
||||||
|
Ok((result, hash))
|
||||||
|
}
|
||||||
|
|
||||||
/// Returns the synastry of the two charts, calculating and storing it when
|
/// Returns the synastry of the two charts, calculating and storing it when
|
||||||
/// it does not exist yet (in either order). `bool` = newly created.
|
/// it does not exist yet (in either order). `bool` = newly created.
|
||||||
pub async fn compute_synastry(
|
pub async fn compute_synastry(
|
||||||
@@ -130,14 +147,7 @@ pub async fn compute_synastry(
|
|||||||
return Ok((row, false));
|
return Ok((row, false));
|
||||||
}
|
}
|
||||||
|
|
||||||
let request = json!({
|
let (result, hash) = calculate(state, chart1, chart2).await?;
|
||||||
"person1": without(&chart1.birth_data, &["options"]),
|
|
||||||
"person2": without(&chart2.birth_data, &["options"]),
|
|
||||||
"options": chart1.birth_data.get("options").cloned().unwrap_or_else(|| json!({})),
|
|
||||||
});
|
|
||||||
let response = state.horoscope.synastry(&request).await?;
|
|
||||||
let result = without(&response, &["person1", "person2", "meta"]);
|
|
||||||
let hash = synastry_hash(&chart1.chart_hash, &chart2.chart_hash, &result["settings"]);
|
|
||||||
|
|
||||||
let inserted: Option<SynastryRow> = sqlx::query_as(&format!(
|
let inserted: Option<SynastryRow> = sqlx::query_as(&format!(
|
||||||
"INSERT INTO synastries (id, owner_id, chart1_id, chart2_id, result, synastry_hash) \
|
"INSERT INTO synastries (id, owner_id, chart1_id, chart2_id, result, synastry_hash) \
|
||||||
|
|||||||
@@ -124,6 +124,7 @@ fn google_token(sub: &str, email: &str, audience: &str) -> String {
|
|||||||
struct TestApp {
|
struct TestApp {
|
||||||
router: Router,
|
router: Router,
|
||||||
pool: PgPool,
|
pool: PgPool,
|
||||||
|
state: Arc<AppState>,
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Response {
|
struct Response {
|
||||||
@@ -141,7 +142,8 @@ impl TestApp {
|
|||||||
let fake = fake_services().await;
|
let fake = fake_services().await;
|
||||||
let mut config = Config::for_tests(String::new(), fake.clone(), format!("{fake}/jwks"));
|
let mut config = Config::for_tests(String::new(), fake.clone(), format!("{fake}/jwks"));
|
||||||
change(&mut config);
|
change(&mut config);
|
||||||
Self { router: routes::router(Arc::new(AppState::new(pool.clone(), config))), pool }
|
let state = Arc::new(AppState::new(pool.clone(), config));
|
||||||
|
Self { router: routes::router(state.clone()), pool, state }
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn call(&self, method: &str, uri: &str, token: Option<&str>, body: Option<Value>) -> Response {
|
async fn call(&self, method: &str, uri: &str, token: Option<&str>, body: Option<Value>) -> Response {
|
||||||
@@ -929,7 +931,8 @@ async fn admins_edit_analysis_prompts(pool: PgPool) {
|
|||||||
let prompts = r.body["prompts"].as_array().unwrap();
|
let prompts = r.body["prompts"].as_array().unwrap();
|
||||||
let keys: Vec<String> =
|
let keys: Vec<String> =
|
||||||
prompts.iter().map(|p| format!("{}/{}", p["kind"], p["language"]).replace('"', "")).collect();
|
prompts.iter().map(|p| format!("{}/{}", p["kind"], p["language"]).replace('"', "")).collect();
|
||||||
assert_eq!(keys, ["summary/hu", "summary/en", "natal/hu", "natal/en", "synastry/hu", "synastry/en"]);
|
let expected = ["summary", "natal", "synastry", "forecast"].map(|k| [format!("{k}/hu"), format!("{k}/en")]);
|
||||||
|
assert_eq!(keys, expected.concat());
|
||||||
let natal = &prompts[2];
|
let natal = &prompts[2];
|
||||||
assert_eq!((&natal["custom"], &natal["system"]), (&json!(false), &natal["default"]));
|
assert_eq!((&natal["custom"], &natal["system"]), (&json!(false), &natal["default"]));
|
||||||
assert!(natal["user_template"].as_str().unwrap().contains("{chart data}"));
|
assert!(natal["user_template"].as_str().unwrap().contains("{chart data}"));
|
||||||
@@ -1048,6 +1051,32 @@ async fn admins_try_prompt_drafts_on_own_charts(pool: PgPool) {
|
|||||||
"{}",
|
"{}",
|
||||||
r.body
|
r.body
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// a yearly forecast is tried on a forecast of one of the admin's charts
|
||||||
|
sqlx::query("UPDATE prompt_previews SET status = 'done'").execute(&pool).await.unwrap();
|
||||||
|
let own_id = own["id"].as_str().unwrap();
|
||||||
|
let forecast = app.post(&format!("/v1/charts/{own_id}/forecasts"), Some(&admin), json!({})).await;
|
||||||
|
assert_eq!(forecast.status, StatusCode::CREATED, "{}", forecast.body);
|
||||||
|
let annas_id = annas["id"].as_str().unwrap();
|
||||||
|
let annas_forecast = app.post(&format!("/v1/charts/{annas_id}/forecasts"), Some(&anna), json!({})).await;
|
||||||
|
let uri = "/v1/admin/prompts/forecast/hu/preview";
|
||||||
|
let r = app.call("POST", uri, Some(&admin), Some(json!({"system": "Próba.", "chart_id": own["id"]}))).await;
|
||||||
|
assert_eq!(r.status, StatusCode::BAD_REQUEST);
|
||||||
|
let body = json!({"system": "Próba.", "forecast_id": annas_forecast.body["id"]});
|
||||||
|
assert_eq!(app.call("POST", uri, Some(&admin), Some(body)).await.status, StatusCode::NOT_FOUND);
|
||||||
|
let body = json!({"system": "Próba.", "forecast_id": forecast.body["id"]});
|
||||||
|
let r = app.call("POST", uri, Some(&admin), Some(body)).await;
|
||||||
|
assert_eq!(
|
||||||
|
(r.status, r.body["forecast_id"].as_str()),
|
||||||
|
(StatusCode::ACCEPTED, forecast.body["id"].as_str()),
|
||||||
|
"{}",
|
||||||
|
r.body
|
||||||
|
);
|
||||||
|
// and its prompt is listed and can be saved like the others
|
||||||
|
let prompts = app.get("/v1/admin/prompts", Some(&admin)).await.body;
|
||||||
|
assert!(prompts["prompts"].as_array().unwrap().iter().any(|p| p["kind"] == "forecast"));
|
||||||
|
let r = app.call("PUT", "/v1/admin/prompts/forecast/hu", Some(&admin), Some(json!({"system": "Saját."}))).await;
|
||||||
|
assert_eq!((r.status, &r.body["custom"]), (StatusCode::OK, &json!(true)), "{}", r.body);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||||
@@ -1392,3 +1421,42 @@ async fn forecasts_are_free_their_analysis_uses_a_forecast_unit(pool: PgPool) {
|
|||||||
let (n,): (i64,) = sqlx::query_as("SELECT count(*) FROM forecasts").fetch_one(&pool).await.unwrap();
|
let (n,): (i64,) = sqlx::query_as("SELECT count(*) FROM forecasts").fetch_one(&pool).await.unwrap();
|
||||||
assert_eq!(n, 0);
|
assert_eq!(n, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||||
|
async fn recalculate_refreshes_calculations_and_queues_every_analysis_again(pool: PgPool) {
|
||||||
|
let app = TestApp::new(pool.clone()).await;
|
||||||
|
let anna = app.register("anna@example.com", "Anna").await;
|
||||||
|
let own = app.chart(&anna, "Saját", true, "1990-03-15").await;
|
||||||
|
let bela = app.chart(&anna, "Béla", false, "1985-08-02").await;
|
||||||
|
let syn = app.post("/v1/synastries", Some(&anna), json!({"chart1_id": own["id"], "chart2_id": bela["id"]})).await;
|
||||||
|
let own_id = own["id"].as_str().unwrap();
|
||||||
|
let forecast = app.post(&format!("/v1/charts/{own_id}/forecasts"), Some(&anna), json!({})).await;
|
||||||
|
assert_eq!(forecast.status, StatusCode::CREATED, "{}", forecast.body);
|
||||||
|
let before = app.get("/v1/me", Some(&anna)).await.body["analyses_left"].clone();
|
||||||
|
// stored with an older calculation
|
||||||
|
sqlx::query("UPDATE charts SET result = '{}', chart_hash = 'old'").execute(&pool).await.unwrap();
|
||||||
|
sqlx::query("UPDATE synastries SET result = '{}', synastry_hash = 'old'").execute(&pool).await.unwrap();
|
||||||
|
sqlx::query("UPDATE forecasts SET result = '{}', forecast_hash = 'old'").execute(&pool).await.unwrap();
|
||||||
|
|
||||||
|
routes::recalculate(&app.state).await.unwrap();
|
||||||
|
|
||||||
|
let (old,): (i64,) = sqlx::query_as(
|
||||||
|
"SELECT (SELECT count(*) FROM charts WHERE chart_hash = 'old' OR result = '{}') \
|
||||||
|
+ (SELECT count(*) FROM synastries WHERE synastry_hash = 'old' OR result = '{}') \
|
||||||
|
+ (SELECT count(*) FROM forecasts WHERE forecast_hash = 'old' OR result = '{}')",
|
||||||
|
)
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(old, 0);
|
||||||
|
let rows: Vec<(String, String, i32)> =
|
||||||
|
sqlx::query_as("SELECT kind, status, credits_charged FROM analyses ORDER BY kind")
|
||||||
|
.fetch_all(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let kinds: Vec<&str> = rows.iter().map(|r| r.0.as_str()).collect();
|
||||||
|
assert_eq!(kinds, ["forecast", "natal", "natal", "summary", "summary", "synastry"]);
|
||||||
|
assert!(rows.iter().all(|r| r.1 == "pending" && r.2 == 0), "{rows:?}");
|
||||||
|
assert_eq!(app.get("/v1/me", Some(&anna)).await.body["analyses_left"], before);
|
||||||
|
assert_eq!(syn.status, StatusCode::CREATED);
|
||||||
|
}
|
||||||
|
|||||||
@@ -28,6 +28,13 @@ const KINDS: { kind: PromptKind; id: string; label: string; about: string }[] =
|
|||||||
label: "Kapcsolati elemzés",
|
label: "Kapcsolati elemzés",
|
||||||
about: "Fizetős összevetés-elemzés két képletről: öt fejezet, erősségek, kihívások és útravaló. Kérésre készül.",
|
about: "Fizetős összevetés-elemzés két képletről: öt fejezet, erősségek, kihívások és útravaló. Kérésre készül.",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
kind: "forecast",
|
||||||
|
id: "elorejelzes",
|
||||||
|
label: "Éves előrejelzés",
|
||||||
|
about:
|
||||||
|
"Fizetős elemzés egy születésnaptól a következőig: szolár, lassú tranzitok, progresszió, profekció, fogyatkozások. Öt fejezet, lehetőségek, kihívások és útravaló. Kérésre készül.",
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
const LANGUAGES: Record<string, string> = { hu: "Magyar", en: "Angol" };
|
const LANGUAGES: Record<string, string> = { hu: "Magyar", en: "Angol" };
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import { AnalysisView } from "@/components/AnalysisView";
|
|||||||
import { api, errorText } from "@/lib/api";
|
import { api, errorText } from "@/lib/api";
|
||||||
import { formatDate } from "@/lib/astro";
|
import { formatDate } from "@/lib/astro";
|
||||||
import { listName } from "@/lib/synastry";
|
import { listName } from "@/lib/synastry";
|
||||||
import type { ChartListItem, PromptKind, PromptPreview, SynastryListItem } from "@/lib/types";
|
import type { ChartListItem, ForecastList, ForecastSummary, PromptKind, PromptPreview, SynastryListItem } from "@/lib/types";
|
||||||
|
|
||||||
const POLL_MS = 4000;
|
const POLL_MS = 4000;
|
||||||
const MAX_POLLS = 150; // 10 minutes
|
const MAX_POLLS = 150; // 10 minutes
|
||||||
@@ -36,6 +36,7 @@ export function PromptTrial({
|
|||||||
onLoad: (system: string) => void;
|
onLoad: (system: string) => void;
|
||||||
}) {
|
}) {
|
||||||
const synastry = kind === "synastry";
|
const synastry = kind === "synastry";
|
||||||
|
const forecastKind = kind === "forecast";
|
||||||
const [chartId, setChartId] = useState(charts.find((c) => c.is_primary)?.id ?? charts[0]?.id ?? "");
|
const [chartId, setChartId] = useState(charts.find((c) => c.is_primary)?.id ?? charts[0]?.id ?? "");
|
||||||
const [synastries, setSynastries] = useState<SynastryListItem[]>([]);
|
const [synastries, setSynastries] = useState<SynastryListItem[]>([]);
|
||||||
const [synastryId, setSynastryId] = useState("");
|
const [synastryId, setSynastryId] = useState("");
|
||||||
@@ -50,7 +51,23 @@ export function PromptTrial({
|
|||||||
})
|
})
|
||||||
.catch(() => setSynastries([]));
|
.catch(() => setSynastries([]));
|
||||||
}, [synastry]);
|
}, [synastry]);
|
||||||
const targetId = synastry ? synastryId : chartId;
|
// A forecast is tried on one of the chosen chart's calculated years.
|
||||||
|
const [forecasts, setForecasts] = useState<ForecastSummary[] | null>(null);
|
||||||
|
const [forecastId, setForecastId] = useState("");
|
||||||
|
const [allForecasts, setAllForecasts] = useState<ForecastSummary[]>([]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!forecastKind || !chartId) return;
|
||||||
|
setForecasts(null);
|
||||||
|
api<ForecastList>(`/charts/${chartId}/forecasts`)
|
||||||
|
.then((d) => {
|
||||||
|
setForecasts(d.forecasts);
|
||||||
|
setForecastId(d.forecasts[0]?.id ?? "");
|
||||||
|
setAllForecasts((all) => [...all.filter((f) => f.chart_id !== chartId), ...d.forecasts]);
|
||||||
|
})
|
||||||
|
.catch(() => setForecasts([]));
|
||||||
|
}, [forecastKind, chartId]);
|
||||||
|
const targetId = synastry ? synastryId : forecastKind ? forecastId : chartId;
|
||||||
|
const forecastName = (f: ForecastSummary) => `${f.year}–${f.year + 1} · ${f.place ?? "születési hely"}`;
|
||||||
const comparisonName = (s: SynastryListItem) => `${listName(s.chart1, charts)} és ${listName(s.chart2, charts)}`;
|
const comparisonName = (s: SynastryListItem) => `${listName(s.chart1, charts)} és ${listName(s.chart2, charts)}`;
|
||||||
const [trials, setTrials] = useState<Trial[]>([]);
|
const [trials, setTrials] = useState<Trial[]>([]);
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
@@ -62,7 +79,11 @@ export function PromptTrial({
|
|||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const preview = await api<PromptPreview>(`/admin/prompts/${kind}/${language}/preview`, {
|
const preview = await api<PromptPreview>(`/admin/prompts/${kind}/${language}/preview`, {
|
||||||
body: synastry ? { system: draft, synastry_id: synastryId } : { system: draft, chart_id: chartId },
|
body: synastry
|
||||||
|
? { system: draft, synastry_id: synastryId }
|
||||||
|
: forecastKind
|
||||||
|
? { system: draft, forecast_id: forecastId }
|
||||||
|
: { system: draft, chart_id: chartId },
|
||||||
});
|
});
|
||||||
setTrials((all) => [{ preview, system: draft }, ...all]);
|
setTrials((all) => [{ preview, system: draft }, ...all]);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -84,7 +105,8 @@ export function PromptTrial({
|
|||||||
<h2 id={`${selectId}-title`}>Kipróbálás</h2>
|
<h2 id={`${selectId}-title`}>Kipróbálás</h2>
|
||||||
<p className="hint">
|
<p className="hint">
|
||||||
A szerkesztőben lévő szöveggel (mentés nélkül is) megírja az elemzést egy saját{" "}
|
A szerkesztőben lévő szöveggel (mentés nélkül is) megírja az elemzést egy saját{" "}
|
||||||
{synastry ? "összevetésedre" : "képletedre"}. Az eredmény nem kerül {synastry ? "az összevetéshez" : "a képlethez"},
|
{synastry ? "összevetésedre" : forecastKind ? "előrejelzésedre" : "képletedre"}. Az eredmény nem kerül{" "}
|
||||||
|
{synastry ? "az összevetéshez" : forecastKind ? "az előrejelzéshez" : "a képlethez"},
|
||||||
csak itt látod. Valódi modellhívás, ezért költsége van.
|
csak itt látod. Valódi modellhívás, ezért költsége van.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
@@ -110,6 +132,54 @@ export function PromptTrial({
|
|||||||
</div>
|
</div>
|
||||||
) : charts.length === 0 ? (
|
) : charts.length === 0 ? (
|
||||||
<p className="muted">Kipróbáláshoz előbb legyen legalább egy képleted.</p>
|
<p className="muted">Kipróbáláshoz előbb legyen legalább egy képleted.</p>
|
||||||
|
) : forecastKind ? (
|
||||||
|
<div className="prompt-trial-form">
|
||||||
|
<div className="field">
|
||||||
|
<label htmlFor={selectId}>Képlet</label>
|
||||||
|
<select id={selectId} className="inp" value={chartId} onChange={(e) => setChartId(e.target.value)}>
|
||||||
|
{charts.map((c) => (
|
||||||
|
<option key={c.id} value={c.id}>
|
||||||
|
{c.is_primary ? `Én (${c.label})` : c.label}
|
||||||
|
{c.birth.time ? "" : " – idő nélkül"}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
{forecasts === null ? (
|
||||||
|
<p className="hint">Betöltés…</p>
|
||||||
|
) : forecasts.length === 0 ? (
|
||||||
|
<p className="muted">
|
||||||
|
Ehhez a képlethez még nincs kiszámolt év. Előbb kérj egyet az{" "}
|
||||||
|
<a href={`/kepletek/${chartId}/elorejelzes`}>előrejelzés oldalán</a> (a számítás ingyenes).
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="field">
|
||||||
|
<label htmlFor={`${selectId}-year`}>Év</label>
|
||||||
|
<select
|
||||||
|
id={`${selectId}-year`}
|
||||||
|
className="inp"
|
||||||
|
value={forecastId}
|
||||||
|
onChange={(e) => setForecastId(e.target.value)}
|
||||||
|
>
|
||||||
|
{forecasts.map((f) => (
|
||||||
|
<option key={f.id} value={f.id}>
|
||||||
|
{forecastName(f)}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-primary"
|
||||||
|
onClick={start}
|
||||||
|
disabled={busy || !targetId || !draft.trim()}
|
||||||
|
>
|
||||||
|
{busy ? "Indítás…" : "Kipróbálás"}
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="prompt-trial-form">
|
<div className="prompt-trial-form">
|
||||||
<div className="field">
|
<div className="field">
|
||||||
@@ -138,7 +208,13 @@ export function PromptTrial({
|
|||||||
key={t.preview.id}
|
key={t.preview.id}
|
||||||
trial={t}
|
trial={t}
|
||||||
chartLabel={
|
chartLabel={
|
||||||
t.preview.synastry_id
|
t.preview.forecast_id
|
||||||
|
? (() => {
|
||||||
|
const f = allForecasts.find((x) => x.id === t.preview.forecast_id);
|
||||||
|
const c = f && charts.find((x) => x.id === f.chart_id);
|
||||||
|
return f ? `${c?.label ?? "Képlet"}, ${forecastName(f)}` : "Előrejelzés";
|
||||||
|
})()
|
||||||
|
: t.preview.synastry_id
|
||||||
? (() => {
|
? (() => {
|
||||||
const s = synastries.find((x) => x.id === t.preview.synastry_id);
|
const s = synastries.find((x) => x.id === t.preview.synastry_id);
|
||||||
return s ? comparisonName(s) : "Összevetés";
|
return s ? comparisonName(s) : "Összevetés";
|
||||||
@@ -218,7 +294,13 @@ function TrialResult({
|
|||||||
{waiting ? (
|
{waiting ? (
|
||||||
<AnalysisLoading
|
<AnalysisLoading
|
||||||
compact
|
compact
|
||||||
text={p.kind === "summary" ? "Készül az összefoglaló, kb. 10–30 másodperc." : "Készül az elemzés, kb. 1–3 perc."}
|
text={
|
||||||
|
p.kind === "summary"
|
||||||
|
? "Készül az összefoglaló, kb. 10–30 másodperc."
|
||||||
|
: p.kind === "forecast"
|
||||||
|
? "Készül az előrejelzés, kb. 2–4 perc."
|
||||||
|
: "Készül az elemzés, kb. 1–3 perc."
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
) : p.status === "failed" ? (
|
) : p.status === "failed" ? (
|
||||||
<p className="msg msg-error" role="alert">
|
<p className="msg msg-error" role="alert">
|
||||||
@@ -231,7 +313,7 @@ function TrialResult({
|
|||||||
<p className="summary-text">{p.content.summary}</p>
|
<p className="summary-text">{p.content.summary}</p>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<AnalysisView content={p.content} kind={p.kind === "synastry" ? "synastry" : "natal"} />
|
<AnalysisView content={p.content} kind={p.kind} />
|
||||||
)
|
)
|
||||||
) : null}
|
) : null}
|
||||||
{meta.length > 0 && !waiting && <p className="hint">{meta.join(" · ")}</p>}
|
{meta.length > 0 && !waiting && <p className="hint">{meta.join(" · ")}</p>}
|
||||||
|
|||||||
@@ -229,7 +229,7 @@ export interface AdminUser {
|
|||||||
analyses_left: UnitBalance;
|
analyses_left: UnitBalance;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type PromptKind = "summary" | "natal" | "synastry";
|
export type PromptKind = "summary" | "natal" | "synastry" | "forecast";
|
||||||
|
|
||||||
export interface PromptRevision {
|
export interface PromptRevision {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -261,6 +261,7 @@ export interface PromptPreview {
|
|||||||
kind: PromptKind;
|
kind: PromptKind;
|
||||||
chart_id: string | null;
|
chart_id: string | null;
|
||||||
synastry_id: string | null;
|
synastry_id: string | null;
|
||||||
|
forecast_id: string | null;
|
||||||
language: string;
|
language: string;
|
||||||
model: string;
|
model: string;
|
||||||
status: "pending" | "running" | "done" | "failed";
|
status: "pending" | "running" | "done" | "failed";
|
||||||
|
|||||||
@@ -66,7 +66,7 @@ async fn info(State(state): State<Arc<AppState>>) -> Json<Value> {
|
|||||||
],
|
],
|
||||||
"node_type": [NodeType::True, NodeType::Mean],
|
"node_type": [NodeType::True, NodeType::Mean],
|
||||||
"lilith_type": [LilithType::Mean, LilithType::True],
|
"lilith_type": [LilithType::Mean, LilithType::True],
|
||||||
"aspect_set": [AspectSet::Major, AspectSet::Extended],
|
"aspect_set": [AspectSet::Major, AspectSet::Standard, AspectSet::Extended],
|
||||||
"ambiguous_time": ["reject", "earlier", "later"],
|
"ambiguous_time": ["reject", "earlier", "later"],
|
||||||
"calendar": ["gregorian", "julian"],
|
"calendar": ["gregorian", "julian"],
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -22,7 +22,8 @@ Háttérmunkák a közös PostgreSQL-adatbázis fölött: e-mail-küldés, szöv
|
|||||||
**Szöveges elemzések** (`analyses`, `pending` → `running` → `done`/`failed`)
|
**Szöveges elemzések** (`analyses`, `pending` → `running` → `done`/`failed`)
|
||||||
- A backend létrehozza a `pending` sort, és levon egy elemzési egységet. Egy trigger (`NOTIFY analyses`) felébreszti a workert; egyszerre `ANALYSIS_CONCURRENCY` elemzés készül.
|
- A backend létrehozza a `pending` sort, és levon egy elemzési egységet. Egy trigger (`NOTIFY analyses`) felébreszti a workert; egyszerre `ANALYSIS_CONCURRENCY` elemzés készül.
|
||||||
- A prompt a tárolt képletből készül (`src/analysis/compact.rs`). Ez egy tömör szöveg, amely csak a pozíciókat tartalmazza: jegyek, fokok, házak, fényszögek, elemek. **Név, születési dátum, idő, hely és koordináta nem megy ki.** Ismeretlen születési időnél nincsenek házak, Aszcendens és MC.
|
- A prompt a tárolt képletből készül (`src/analysis/compact.rs`). Ez egy tömör szöveg, amely csak a pozíciókat tartalmazza: jegyek, fokok, házak, fényszögek, elemek. **Név, születési dátum, idő, hely és koordináta nem megy ki.** Ismeretlen születési időnél nincsenek házak, Aszcendens és MC.
|
||||||
- A modell OpenRouteren keresztül válaszol, azzal a modellel, amely a sor `model` mezőjében áll. A válasznak kötött JSON-sémát kell követnie (`crates/analysis-prompt`, `PROMPT_VERSION = v2`; ha a sor `prompt_version`-je `v2-r<id>`, a system prompt az admin által szerkesztett `prompt_revisions` sorból jön):
|
- **5 fokos szabály:** ha egy pont legfeljebb 5°-kal (`CUSP_ORB`) a következő ház csúcsa előtt áll, a szöveg már abban a házban adja meg, és odaírja, hogy formálisan az előzőben van („house 11 (on the cusp: 2°00' before it, formally house 10)”). Így olvassák az asztrológusok. A számított ház, a képlet rajza és a táblázatok nem változnak. Ugyanez érvényes az összevetés házátfedéseire, a szolár Aszcendensre, az év urára és a fogyatkozásokra.
|
||||||
|
- A modell OpenRouteren keresztül válaszol, azzal a modellel, amely a sor `model` mezőjében áll. A válasznak kötött JSON-sémát kell követnie (`crates/analysis-prompt`, `PROMPT_VERSION = v3`; ha a sor `prompt_version`-je `v3-r<id>`, a system prompt az admin által szerkesztett `prompt_revisions` sorból jön):
|
||||||
- `title`, `summary`;
|
- `title`, `summary`;
|
||||||
- `sections`, radixnál: `personality`, `emotions`, `mind`, `love`, `work`, `growth`; szinasztriánál: `attraction`, `communication`, `emotional_bond`, `friction`, `long_term`;
|
- `sections`, radixnál: `personality`, `emotions`, `mind`, `love`, `work`, `growth`; szinasztriánál: `attraction`, `communication`, `emotional_bond`, `friction`, `long_term`;
|
||||||
- `strengths`, `challenges`, `advice`;
|
- `strengths`, `challenges`, `advice`;
|
||||||
|
|||||||
@@ -75,12 +75,49 @@ fn names(list: &Value) -> String {
|
|||||||
list.as_array().into_iter().flatten().filter_map(Value::as_str).map(point_name).collect::<Vec<_>>().join(", ")
|
list.as_array().into_iter().flatten().filter_map(Value::as_str).map(point_name).collect::<Vec<_>>().join(", ")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A point at most this far before the next house cusp is read in that house,
|
||||||
|
/// as astrologers do (the "5° rule"). The calculation keeps the exact house.
|
||||||
|
const CUSP_ORB: f64 = 5.0;
|
||||||
|
|
||||||
|
/// "2°05'"
|
||||||
|
fn degrees(x: f64) -> String {
|
||||||
|
let minutes = (x * 60.0).round() as i64;
|
||||||
|
format!("{}°{:02}'", minutes / 60, minutes % 60)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn point_longitude(chart: &Value, id: &str) -> Option<f64> {
|
||||||
|
points(chart).find(|p| p["id"] == id)?["longitude"].as_f64()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The house a point is read in: its own, or the next one when that cusp is
|
||||||
|
/// at most [`CUSP_ORB`] ahead, with how far ahead it is.
|
||||||
|
fn read_house(longitude: Option<f64>, house: i64, cusps: &Value) -> (i64, Option<f64>) {
|
||||||
|
let next = house % 12 + 1;
|
||||||
|
let cusp = cusps.as_array().into_iter().flatten().find(|c| c["house"].as_i64() == Some(next));
|
||||||
|
match (longitude, cusp.and_then(|c| c["longitude"].as_f64())) {
|
||||||
|
(Some(lon), Some(cusp)) if (cusp - lon).rem_euclid(360.0) <= CUSP_ORB => {
|
||||||
|
(next, Some((cusp - lon).rem_euclid(360.0)))
|
||||||
|
}
|
||||||
|
_ => (house, None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "house 11 (on the cusp: 2°05' before it, formally house 10)" or "house 10".
|
||||||
|
fn house_text(longitude: Option<f64>, house: i64, cusps: &Value) -> String {
|
||||||
|
match read_house(longitude, house, cusps) {
|
||||||
|
(read, Some(before)) => {
|
||||||
|
format!("house {read} (on the cusp: {} before it, formally house {house})", degrees(before))
|
||||||
|
}
|
||||||
|
(read, None) => format!("house {read}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// One line per point: "Sun: Cancer 0°24', house 3, retrograde, domicile".
|
/// One line per point: "Sun: Cancer 0°24', house 3, retrograde, domicile".
|
||||||
fn point_lines(out: &mut String, chart: &Value, prefix: &str, houses: bool) {
|
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(""))) {
|
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));
|
let mut line = format!("{prefix}- {}: {}", point_name(p["id"].as_str().unwrap_or("?")), position(p));
|
||||||
if houses && let Some(h) = p["house"].as_i64() {
|
if houses && let Some(h) = p["house"].as_i64() {
|
||||||
let _ = write!(line, ", house {h}");
|
let _ = write!(line, ", {}", house_text(p["longitude"].as_f64(), h, &chart["houses"]["cusps"]));
|
||||||
}
|
}
|
||||||
if p["retrograde"].as_bool() == Some(true) {
|
if p["retrograde"].as_bool() == Some(true) {
|
||||||
line.push_str(", retrograde");
|
line.push_str(", retrograde");
|
||||||
@@ -97,7 +134,10 @@ fn point_lines(out: &mut String, chart: &Value, prefix: &str, houses: bool) {
|
|||||||
.filter(|p| ASTEROIDS.contains(&p["id"].as_str().unwrap_or("")))
|
.filter(|p| ASTEROIDS.contains(&p["id"].as_str().unwrap_or("")))
|
||||||
.map(|p| {
|
.map(|p| {
|
||||||
let house = if houses {
|
let house = if houses {
|
||||||
p["house"].as_i64().map(|h| format!(" (house {h})")).unwrap_or_default()
|
p["house"]
|
||||||
|
.as_i64()
|
||||||
|
.map(|h| format!(" ({})", house_text(p["longitude"].as_f64(), h, &chart["houses"]["cusps"])))
|
||||||
|
.unwrap_or_default()
|
||||||
} else {
|
} else {
|
||||||
String::new()
|
String::new()
|
||||||
};
|
};
|
||||||
@@ -155,12 +195,15 @@ pub fn natal(chart: &Value) -> String {
|
|||||||
if kind == "modern" && ruler["traditional"]["planet"] == r["planet"] {
|
if kind == "modern" && ruler["traditional"]["planet"] == r["planet"] {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
let house = r["house"].as_i64().map_or_else(
|
||||||
|
|| "house ?".to_string(),
|
||||||
|
|h| house_text(point_longitude(chart, planet), h, &chart["houses"]["cusps"]),
|
||||||
|
);
|
||||||
let _ = writeln!(
|
let _ = writeln!(
|
||||||
out,
|
out,
|
||||||
"- Chart ruler ({kind}): {} in {}, house {}",
|
"- Chart ruler ({kind}): {} in {}, {house}",
|
||||||
point_name(planet),
|
point_name(planet),
|
||||||
capitalize(r["sign"].as_str().unwrap_or("?")),
|
capitalize(r["sign"].as_str().unwrap_or("?")),
|
||||||
r["house"]
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -199,7 +242,10 @@ pub fn natal(chart: &Value) -> String {
|
|||||||
}
|
}
|
||||||
if known && let Some(fortune) = chart["lots"]["fortune"].as_object() {
|
if known && let Some(fortune) = chart["lots"]["fortune"].as_object() {
|
||||||
let fortune = Value::Object(fortune.clone());
|
let fortune = Value::Object(fortune.clone());
|
||||||
let _ = writeln!(out, "- Part of Fortune: {}, house {}", position(&fortune), fortune["house"]);
|
if let Some(h) = fortune["house"].as_i64() {
|
||||||
|
let house = house_text(fortune["longitude"].as_f64(), h, &chart["houses"]["cusps"]);
|
||||||
|
let _ = writeln!(out, "- Part of Fortune: {}, {house}", position(&fortune));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
out
|
out
|
||||||
}
|
}
|
||||||
@@ -251,16 +297,23 @@ pub fn synastry(chart1: &Value, chart2: &Value, result: &Value) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let overlays = &result["house_overlays"];
|
let overlays = &result["house_overlays"];
|
||||||
for (key, label) in [
|
for (key, label, own, other) in [
|
||||||
("person1_in_person2", "Person 1's planets in Person 2's houses"),
|
("person1_in_person2", "Person 1's planets in Person 2's houses", chart1, chart2),
|
||||||
("person2_in_person1", "Person 2's planets in Person 1's houses"),
|
("person2_in_person1", "Person 2's planets in Person 1's houses", chart2, chart1),
|
||||||
] {
|
] {
|
||||||
let list: Vec<String> = overlays[key]
|
let list: Vec<String> = overlays[key]
|
||||||
.as_array()
|
.as_array()
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.flatten()
|
.flatten()
|
||||||
.filter(|o| MAIN_POINTS.contains(&o["point"].as_str().unwrap_or("")))
|
.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()?)))
|
.filter_map(|o| {
|
||||||
|
let point = o["point"].as_str()?;
|
||||||
|
let house = o["house"].as_i64()?;
|
||||||
|
Some(match read_house(point_longitude(own, point), house, &other["houses"]["cusps"]) {
|
||||||
|
(read, Some(_)) => format!("{} {read} (on the cusp, formally {house})", point_name(point)),
|
||||||
|
(read, None) => format!("{} {read}", point_name(point)),
|
||||||
|
})
|
||||||
|
})
|
||||||
.collect();
|
.collect();
|
||||||
if !list.is_empty() {
|
if !list.is_empty() {
|
||||||
let _ = writeln!(out, "\n{label}: {}", list.join(", "));
|
let _ = writeln!(out, "\n{label}: {}", list.join(", "));
|
||||||
@@ -357,7 +410,12 @@ pub fn forecast(chart: &Value, result: &Value) -> String {
|
|||||||
out.push_str("\nSOLAR RETURN CHART (cast for the moment of the solar return at the place of the birthday):\n");
|
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, "");
|
angle_lines(&mut out, sr, "");
|
||||||
if let Some(h) = sr["natal_house_of_ascendant"].as_i64() {
|
if let Some(h) = sr["natal_house_of_ascendant"].as_i64() {
|
||||||
let _ = writeln!(out, "- The solar return Ascendant falls in natal house {h}.");
|
let asc = sr["angles"]["ascendant"]["longitude"].as_f64();
|
||||||
|
let _ = writeln!(
|
||||||
|
out,
|
||||||
|
"- The solar return Ascendant falls in natal {}.",
|
||||||
|
house_text(asc, h, &chart["houses"]["cusps"])
|
||||||
|
);
|
||||||
}
|
}
|
||||||
point_lines(&mut out, sr, "", true);
|
point_lines(&mut out, sr, "", true);
|
||||||
aspect_lines(&mut out, &sr["aspects"], "Solar return aspects (tightest first):", 15);
|
aspect_lines(&mut out, &sr["aspects"], "Solar return aspects (tightest first):", 15);
|
||||||
@@ -370,13 +428,16 @@ pub fn forecast(chart: &Value, result: &Value) -> String {
|
|||||||
let planets = names(&p["planets_in_sign"]);
|
let planets = names(&p["planets_in_sign"]);
|
||||||
let _ = writeln!(
|
let _ = writeln!(
|
||||||
out,
|
out,
|
||||||
"\nANNUAL PROFECTION: the year activates natal house {} ({}); lord of the year: {} (natal {} in {}, house {}).{}",
|
"\nANNUAL PROFECTION: the year activates natal house {} ({}); lord of the year: {} (natal {} in {}, {}).{}",
|
||||||
p["house"],
|
p["house"],
|
||||||
capitalize(p["sign"].as_str().unwrap_or("?")),
|
capitalize(p["sign"].as_str().unwrap_or("?")),
|
||||||
point_name(p["lord"].as_str().unwrap_or("?")),
|
point_name(p["lord"].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("?")),
|
capitalize(p["lord_sign"].as_str().unwrap_or("?")),
|
||||||
p["lord_house"],
|
p["lord_house"].as_i64().map_or_else(
|
||||||
|
|| "house ?".to_string(),
|
||||||
|
|h| house_text(point_longitude(chart, p["lord"].as_str().unwrap_or("")), h, &chart["houses"]["cusps"])
|
||||||
|
),
|
||||||
if planets.is_empty() { String::new() } else { format!(" Natal planets in that sign: {planets}.") }
|
if planets.is_empty() { String::new() } else { format!(" Natal planets in that sign: {planets}.") }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -466,7 +527,7 @@ pub fn forecast(chart: &Value, result: &Value) -> String {
|
|||||||
position(e)
|
position(e)
|
||||||
);
|
);
|
||||||
if let Some(h) = e["house"].as_i64() {
|
if let Some(h) = e["house"].as_i64() {
|
||||||
let _ = write!(line, ", natal house {h}");
|
let _ = write!(line, ", natal {}", house_text(e["longitude"].as_f64(), h, &chart["houses"]["cusps"]));
|
||||||
}
|
}
|
||||||
let hits: Vec<String> = e["contacts"]
|
let hits: Vec<String> = e["contacts"]
|
||||||
.as_array()
|
.as_array()
|
||||||
@@ -525,6 +586,7 @@ fn aspect_lines(out: &mut String, aspects: &Value, heading: &str, limit: usize)
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
fn fixture(name: &str) -> Value {
|
fn fixture(name: &str) -> Value {
|
||||||
let path = format!("{}/testdata/{name}", env!("CARGO_MANIFEST_DIR"));
|
let path = format!("{}/testdata/{name}", env!("CARGO_MANIFEST_DIR"));
|
||||||
@@ -539,6 +601,19 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn points_just_before_a_cusp_are_read_in_the_next_house() {
|
||||||
|
let cusps = json!([{"house": 10, "longitude": 300.0}, {"house": 11, "longitude": 319.0}]);
|
||||||
|
// Moon at 17° with the 11th cusp at 19°: an astrologer reads it in the 11th.
|
||||||
|
assert_eq!(read_house(Some(317.0), 10, &cusps), (11, Some(2.0)));
|
||||||
|
assert_eq!(house_text(Some(317.0), 10, &cusps), "house 11 (on the cusp: 2°00' before it, formally house 10)");
|
||||||
|
assert_eq!(read_house(Some(313.0), 10, &cusps), (10, None));
|
||||||
|
assert_eq!(read_house(None, 10, &cusps), (10, None));
|
||||||
|
// across 0° Aries, and from the 12th to the 1st
|
||||||
|
let cusps = json!([{"house": 1, "longitude": 2.0}]);
|
||||||
|
assert_eq!(read_house(Some(358.5), 12, &cusps), (1, Some(3.5)));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn natal_with_birth_time() {
|
fn natal_with_birth_time() {
|
||||||
let text = natal(&fixture("natal-1990-03-15.json"));
|
let text = natal(&fixture("natal-1990-03-15.json"));
|
||||||
@@ -553,7 +628,8 @@ mod tests {
|
|||||||
"House cusps: 1 Leo 19°23' | 2 Virgo 9°35'",
|
"House cusps: 1 Leo 19°23' | 2 Virgo 9°35'",
|
||||||
"- Moon trine Chiron (orb 0.1°, applying)",
|
"- Moon trine Chiron (orb 0.1°, applying)",
|
||||||
"- Elements: air 2 (Venus, Mars); earth 3 (Saturn, Uranus, Neptune); fire 0;",
|
"- Elements: air 2 (Venus, Mars); earth 3 (Saturn, Uranus, Neptune); fire 0;",
|
||||||
"- Part of Fortune: Aries 5°10', house 8",
|
// 4' before the 9th cusp: read in the 9th
|
||||||
|
"- Part of Fortune: Aries 5°10', house 9 (on the cusp: 0°04' before it, formally house 8)",
|
||||||
] {
|
] {
|
||||||
assert!(text.contains(expected), "missing '{expected}' in:\n{text}");
|
assert!(text.contains(expected), "missing '{expected}' in:\n{text}");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ pub struct PreviewJob {
|
|||||||
pub kind: String,
|
pub kind: String,
|
||||||
pub chart_id: Option<Uuid>,
|
pub chart_id: Option<Uuid>,
|
||||||
pub synastry_id: Option<Uuid>,
|
pub synastry_id: Option<Uuid>,
|
||||||
|
pub forecast_id: Option<Uuid>,
|
||||||
pub language: String,
|
pub language: String,
|
||||||
pub model: String,
|
pub model: String,
|
||||||
pub system: String,
|
pub system: String,
|
||||||
@@ -159,7 +160,7 @@ impl Analyzer {
|
|||||||
"UPDATE prompt_previews SET status = 'running', started_at = now() \
|
"UPDATE prompt_previews SET status = 'running', started_at = now() \
|
||||||
WHERE id = (SELECT id FROM prompt_previews WHERE status = 'pending' \
|
WHERE id = (SELECT id FROM prompt_previews WHERE status = 'pending' \
|
||||||
ORDER BY created_at LIMIT 1 FOR UPDATE SKIP LOCKED) \
|
ORDER BY created_at LIMIT 1 FOR UPDATE SKIP LOCKED) \
|
||||||
RETURNING id, kind, chart_id, synastry_id, language, model, system",
|
RETURNING id, kind, chart_id, synastry_id, forecast_id, language, model, system",
|
||||||
)
|
)
|
||||||
.fetch_optional(&self.db)
|
.fetch_optional(&self.db)
|
||||||
.await?;
|
.await?;
|
||||||
@@ -177,7 +178,8 @@ impl Analyzer {
|
|||||||
Kind::parse(&job.kind).ok_or_else(|| LlmError::Permanent(format!("unknown kind '{}'", job.kind)))?;
|
Kind::parse(&job.kind).ok_or_else(|| LlmError::Permanent(format!("unknown kind '{}'", job.kind)))?;
|
||||||
let text = match kind {
|
let text = match kind {
|
||||||
Kind::Synastry => self.synastry_text(job.synastry_id).await?,
|
Kind::Synastry => self.synastry_text(job.synastry_id).await?,
|
||||||
_ => self.natal_text(job.chart_id).await?,
|
Kind::Forecast => self.forecast_text(job.forecast_id).await?,
|
||||||
|
Kind::Natal | Kind::Summary => self.natal_text(job.chart_id).await?,
|
||||||
};
|
};
|
||||||
let built = prompt::build(kind, &job.language, &text, Some(&job.system));
|
let built = prompt::build(kind, &job.language, &text, Some(&job.system));
|
||||||
let mut c = self.llm.complete(&job.model, &built).await?;
|
let mut c = self.llm.complete(&job.model, &built).await?;
|
||||||
|
|||||||
Reference in New Issue
Block a user