aien-translate
aien-dev/aien-translate
Brought by drakestapleton
aien-translate / src / cache.rs
| 1 | //! Saved translations, so the same text is never sent to the model twice. |
| 2 | |
| 3 | use rusqlite::{params, Connection, OptionalExtension}; |
| 4 | use sha2::{Digest, Sha256}; |
| 5 | use std::path::Path; |
| 6 | use std::sync::Mutex; |
| 7 | |
| 8 | pub struct Cache { |
| 9 | conn: Mutex<Connection>, |
| 10 | } |
| 11 | |
| 12 | impl Cache { |
| 13 | pub fn open(path: &Path) -> rusqlite::Result<Self> { |
| 14 | if let Some(dir) = path.parent() { |
| 15 | let _ = std::fs::create_dir_all(dir); |
| 16 | } |
| 17 | Self::init(Connection::open(path)?) |
| 18 | } |
| 19 | |
| 20 | pub fn in_memory() -> rusqlite::Result<Self> { |
| 21 | Self::init(Connection::open_in_memory()?) |
| 22 | } |
| 23 | |
| 24 | fn init(conn: Connection) -> rusqlite::Result<Self> { |
| 25 | conn.execute_batch( |
| 26 | "PRAGMA journal_mode=WAL; |
| 27 | CREATE TABLE IF NOT EXISTS translation ( |
| 28 | key TEXT PRIMARY KEY, |
| 29 | src_lang TEXT NOT NULL, |
| 30 | dst_lang TEXT NOT NULL, |
| 31 | source TEXT NOT NULL, |
| 32 | output TEXT NOT NULL, |
| 33 | model TEXT NOT NULL, |
| 34 | created INTEGER NOT NULL |
| 35 | );", |
| 36 | )?; |
| 37 | Ok(Self { conn: Mutex::new(conn) }) |
| 38 | } |
| 39 | |
| 40 | pub fn key(model: &str, from: &str, to: &str, text: &str) -> String { |
| 41 | let mut h = Sha256::new(); |
| 42 | for part in [crate::PROMPT_VERSION, model, from, to, text] { |
| 43 | h.update(part.as_bytes()); |
| 44 | h.update([0u8]); |
| 45 | } |
| 46 | h.finalize().iter().map(|b| format!("{b:02x}")).collect() |
| 47 | } |
| 48 | |
| 49 | pub fn get(&self, key: &str) -> Option<String> { |
| 50 | let conn = self.conn.lock().unwrap(); |
| 51 | conn.query_row("SELECT output FROM translation WHERE key = ?1", params![key], |r| r.get(0)) |
| 52 | .optional() |
| 53 | .ok() |
| 54 | .flatten() |
| 55 | } |
| 56 | |
| 57 | pub fn put(&self, key: &str, model: &str, from: &str, to: &str, source: &str, output: &str) { |
| 58 | let now = std::time::SystemTime::now() |
| 59 | .duration_since(std::time::UNIX_EPOCH) |
| 60 | .map(|d| d.as_secs() as i64) |
| 61 | .unwrap_or(0); |
| 62 | let conn = self.conn.lock().unwrap(); |
| 63 | let _ = conn.execute( |
| 64 | "INSERT OR REPLACE INTO translation (key, src_lang, dst_lang, source, output, model, created) |
| 65 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", |
| 66 | params![key, from, to, source, output, model, now], |
| 67 | ); |
| 68 | } |
| 69 | } |