Ruby/model/journal.py

37 lines
982 B
Python

import os
import json
import random
JOURNAL_PATH = "data/memory/journal.json"
def record_to_journal(entry: dict):
if not os.path.exists(JOURNAL_PATH):
with open(JOURNAL_PATH, "w", encoding="utf-8") as f:
json.dump([], f)
with open(JOURNAL_PATH, "r", encoding="utf-8") as f:
try:
journal = json.load(f)
except json.JSONDecodeError:
journal = []
journal.append(entry)
with open(JOURNAL_PATH, "w", encoding="utf-8") as f:
json.dump(journal, f, indent=2)
def read_journal_entries():
if not os.path.exists(JOURNAL_PATH):
return []
with open(JOURNAL_PATH, "r", encoding="utf-8") as f:
lines = f.readlines()
return [line.split("|", 1)[-1].strip() for line in lines if "|" in line]
def sample_journal_entries(n=5):
"""Return up to `n` random entries from the journal."""
entries = read_journal_entries()
return random.sample(entries, min(n, len(entries)))