40 lines
1.0 KiB
Python
40 lines
1.0 KiB
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:
|
|
try:
|
|
journal = json.load(f)
|
|
return [entry.get("text", "") for entry in journal if isinstance(entry, dict)]
|
|
except json.JSONDecodeError:
|
|
return []
|
|
|
|
|
|
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)))
|