Files
jap_learn/src/data/entities.rs
T

194 lines
5.9 KiB
Rust
Raw Normal View History

2026-08-24 11:40:31 +03:00
use crate::app::AppState;
use crate::core::srs::{FADE_PER_DAY, MAX_SCORE, OrderMode, WordOpenMode};
use crate::data::{INVALID_ID, Id};
2026-08-28 18:52:38 +03:00
use chrono::{DateTime, Local, NaiveDate, Utc};
use fsrs::{FSRS, MemoryState};
2026-08-24 11:40:31 +03:00
use log::info;
2026-08-28 18:52:38 +03:00
use rand::{RngExt, random, rng};
2026-08-24 11:40:31 +03:00
use rayon::prelude::*;
use rhai::{Engine, Scope};
use std::collections::HashMap;
use std::time::Instant;
2026-08-24 11:35:37 +03:00
#[derive(Clone, Debug)]
pub struct WordData {
pub id: Id,
pub key: String,
pub value: String,
pub tags: String,
pub additional: HashMap<String, String>,
pub group_id: Id,
}
#[derive(Clone)]
pub struct WordGroup {
pub id: Id,
pub name: String,
}
impl WordData {
pub fn new() -> Self {
Self {
id: INVALID_ID,
key: String::new(),
value: String::new(),
tags: String::new(),
additional: Default::default(),
group_id: 1.into(),
}
}
}
#[derive(Clone)]
pub struct HistoryItem {
pub timestamp: DateTime<Utc>,
pub word_id: Id,
pub mode: WordOpenMode,
pub before: u8,
pub after: u8,
2026-08-24 11:40:31 +03:00
}
#[derive(Clone)]
pub struct DeckSettings {
pub id: Id,
pub name: String,
pub forward: String,
pub backward: String,
pub filter: String,
pub count: Option<usize>,
pub open_mode: OrderMode,
}
impl DeckSettings {
pub(crate) fn with_name(name: String) -> DeckSettings {
DeckSettings {
id: 0.into(),
name,
forward: "".to_string(),
backward: "".to_string(),
filter: "true".to_string(),
count: None,
open_mode: OrderMode::Default,
}
}
pub fn check_filter(&self) -> bool {
let time = Instant::now();
let engine = Engine::new();
let ast = engine.compile(&self.filter);
info!("Compile time is {:?}", time.elapsed());
ast.is_ok()
}
pub fn get_word_list(&self, state: &AppState) -> Vec<usize> {
let time = Instant::now();
let mut list = vec![];
let engine = Engine::new();
let ast = engine.compile(&self.filter);
if let Ok(ast) = ast {
let groups = &state.word_groups;
list = state
.dictionary
.par_iter()
.enumerate()
.filter(|(_, word)| {
let mut more = rhai::Map::new();
for iced in &word.additional {
more.insert(iced.0.clone().into(), iced.1.clone().into());
}
let mut scope = Scope::new();
scope
.push_constant("id", word.id.0 as i64)
.push_constant("key", word.key.clone())
.push_constant("value", word.value.clone())
.push_constant("tags", word.tags.clone())
.push_constant("more", more)
.push_constant(
"group",
groups
.iter()
.find(|g| g.id == word.group_id)
.cloned()
2026-08-24 23:27:24 +03:00
.expect("No group id")
2026-08-24 11:40:31 +03:00
.name,
);
let result = engine.eval_ast_with_scope::<bool>(&mut scope, &ast);
2026-08-24 23:27:24 +03:00
if let Ok(result) = result {
2026-08-25 12:04:07 +03:00
return result;
2026-08-24 23:27:24 +03:00
}
false
2026-08-24 11:40:31 +03:00
})
.map(|(index, _)| index)
.collect();
info!("Collecting available words is {:?}", time.elapsed());
list
} else {
list
}
}
pub fn require_speech(&self) -> bool {
self.forward == "speech" || self.backward == "speech"
}
}
#[derive(Clone, PartialEq)]
pub struct CardStatistics {
pub id: Id,
pub word_id: Id,
pub set_id: Id,
pub last_open: DateTime<Utc>,
pub score: u8,
2026-08-28 18:52:38 +03:00
pub fsrs_opened: NaiveDate,
pub fsrs_memory: Option<MemoryState>,
pub fsrs_open_day: NaiveDate,
2026-08-24 11:40:31 +03:00
}
impl CardStatistics {
pub fn update(&mut self, status: WordOpenMode) {
match status {
WordOpenMode::Easy => {
self.score = (self.calculated_score() + 5.0).round() as u8;
}
WordOpenMode::Ok => self.score = (self.calculated_score() + 2.0).round() as u8,
WordOpenMode::Hard => {
self.score = (self.calculated_score() * 0.75).round() as u8;
}
WordOpenMode::None => {
self.score = (self.calculated_score() * 0.4) as u8;
}
}
self.score = self.score.clamp(1, MAX_SCORE);
self.last_open = Utc::now();
}
2026-08-28 18:52:38 +03:00
pub fn update_fsrs(&mut self, status: WordOpenMode, by_fsrs: bool, fsrs: FSRS)
{
2026-08-28 21:47:47 +03:00
let today = Local::now().date_naive().to_epoch_days();
2026-08-28 18:52:38 +03:00
let written = self.fsrs_opened.to_epoch_days();
let memory = fsrs
.next_states(self.fsrs_memory, 0.9, (today - written) as u32)
.expect("Wrong next stage calculation");
let next = match status {
WordOpenMode::Easy => memory.easy,
WordOpenMode::Ok => memory.good,
WordOpenMode::Hard => memory.hard,
WordOpenMode::None => memory.again,
};
let mut next_day = today + next.interval.round() as i32;
if next_day - today >= 5 {
let offset = ((rng().random::<f32>() - 0.5) * 3.0).round() as i32;
next_day += offset;
}
self.fsrs_memory = Some(next.memory);
self.fsrs_open_day = NaiveDate::from_epoch_days(next_day).unwrap();
self.fsrs_opened = self.last_open.date_naive();
}
2026-08-24 11:40:31 +03:00
pub fn calculated_score(&self) -> f32 {
let time = Utc::now() - self.last_open;
let days = time.num_days();
let multiplier = FADE_PER_DAY.powi(days as i32);
(self.score as f32 * multiplier).max(1.0)
}
}