File size: 7,417 Bytes
9a659d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
"""The learner's study library: saved stories and cards with review dates.

The library lives only in the learner's browser (``gr.BrowserState``); this
module holds plain functions over that dict and never writes to disk or logs
study material.

Each item keeps its practice cards and its place in Buzan's review rhythm
(``REVIEW_STEPS``: about 10 minutes, 1 day, 1 week, 1 month, 3-6 months).
A clean review moves the item to the next step. Any missed card restarts the
rhythm from the 1-day review, so the repaired pictures are checked tomorrow.
"""

from __future__ import annotations

import hashlib
import uuid
from datetime import date, timedelta
from typing import Any

from mnemonic_core import REVIEW_STEPS

LIBRARY_KEY = "memory-studio-library-v1"
MAX_LIBRARY_ITEMS = 200
MAX_NAME_LENGTH = 60
MAINTENANCE_DAYS = 180

KIND_NUMBER = "number"
KIND_LIST = "list"
KIND_WORD = "word"
KIND_NAMES = "names"
KIND_DATES = "dates"
KIND_MINDMAP = "mindmap"
KIND_LABELS = {
    KIND_NUMBER: "Number",
    KIND_LIST: "Ordered list",
    KIND_WORD: "Word card",
    KIND_NAMES: "Names & faces",
    KIND_DATES: "Dates",
    KIND_MINDMAP: "Mind Map",
}

# Days from the first study session to each review, e.g. (0, 1, 7, 30, 120).
_OFFSETS = tuple(days for _label, _when, days in REVIEW_STEPS)
DONE_STEP = len(_OFFSETS)


def content_key(kind: str, content: str) -> str:
    """A short fingerprint, so saving the same number twice updates one item."""
    digest = hashlib.sha256(f"{kind}\n{content}".encode("utf-8")).hexdigest()
    return digest[:16]


def _parse_date(value: Any) -> date | None:
    try:
        return date.fromisoformat(str(value))
    except (TypeError, ValueError):
        return None


def _clean_item(raw: Any) -> dict[str, Any] | None:
    """Accept only well-formed items; browser storage can hold anything."""
    if not isinstance(raw, dict) or raw.get("kind") not in KIND_LABELS:
        return None
    cards = [
        {"prompt": str(card["prompt"]), "answer": str(card["answer"])}
        for card in raw.get("cards") or []
        if isinstance(card, dict) and card.get("prompt") and card.get("answer")
    ]
    due = _parse_date(raw.get("due"))
    if not cards or due is None:
        return None
    try:
        step = min(max(int(raw.get("step", 0)), 0), DONE_STEP)
        reviews = max(int(raw.get("reviews", 0)), 0)
    except (TypeError, ValueError):
        return None
    return {
        "kind": raw["kind"],
        "name": str(raw.get("name") or KIND_LABELS[raw["kind"]])[:MAX_NAME_LENGTH],
        "key": str(raw.get("key") or ""),
        "cards": cards,
        "full": str(raw.get("full") or ""),
        "created": str(raw.get("created") or due.isoformat()),
        "step": step,
        "due": due.isoformat(),
        "reviews": reviews,
        "last": str(raw.get("last") or ""),
    }


def clean_library(library: Any) -> dict[str, dict[str, Any]]:
    """The valid items of a stored library, keyed by item id."""
    if not isinstance(library, dict):
        return {}
    cleaned = {}
    for item_id, raw in library.items():
        item = _clean_item(raw)
        if item is not None:
            cleaned[str(item_id)] = item
    return cleaned


def add_item(
    library: Any,
    kind: str,
    name: str,
    key: str,
    cards: list[dict[str, str]],
    full: str,
    today: date,
    default_name: str = "",
) -> tuple[dict[str, dict[str, Any]], str, bool]:
    """Add an item, or update the one with the same content.

    Returns (library, item id, updated). Updating replaces the cards (so edited
    words are practised) and keeps the review schedule and, unless a new
    ``name`` is given, the name. ``default_name`` names a new item saved without
    one. Raises ValueError when the library is full.
    """
    items = clean_library(library)
    name = " ".join(name.split())[:MAX_NAME_LENGTH]
    for item_id, item in items.items():
        if item["kind"] == kind and item["key"] == key:
            item["cards"] = cards
            item["full"] = full
            if name:
                item["name"] = name
            return items, item_id, True
    if len(items) >= MAX_LIBRARY_ITEMS:
        raise ValueError(
            f"Your library already holds {MAX_LIBRARY_ITEMS} items. Remove ones "
            "you have learned before adding more."
        )
    item_id = uuid.uuid4().hex[:10]
    items[item_id] = {
        "kind": kind,
        "name": name or default_name[:MAX_NAME_LENGTH] or KIND_LABELS[kind],
        "key": key,
        "cards": cards,
        "full": full,
        "created": today.isoformat(),
        "step": 0,
        "due": today.isoformat(),
        "reviews": 0,
        "last": "",
    }
    return items, item_id, False


def step_label(step: int) -> str:
    """'2nd review (1 day later)', or the long-term check after the rhythm."""
    if step >= DONE_STEP:
        return "long-term check (every 6 months)"
    label, when, _days = REVIEW_STEPS[step]
    return f"{label} review ({when.replace(' (long-term)', '')})"


def is_due(item: dict[str, Any], today: date) -> bool:
    due = _parse_date(item.get("due"))
    return due is not None and due <= today


def record_review(
    item: dict[str, Any], all_known: bool, today: date
) -> dict[str, Any]:
    """Move a due item along the review rhythm after a practice session."""
    step = item["step"]
    if not all_known:
        next_step, gap = 1, 1
    elif step >= DONE_STEP - 1:
        next_step, gap = DONE_STEP, MAINTENANCE_DAYS
    else:
        next_step, gap = step + 1, _OFFSETS[step + 1] - _OFFSETS[step]
    return {
        **item,
        "step": next_step,
        "due": (today + timedelta(days=gap)).isoformat(),
        "reviews": item["reviews"] + 1,
        "last": today.isoformat(),
    }


def due_text(item: dict[str, Any], today: date) -> str:
    due = _parse_date(item["due"]) or today
    days = (due - today).days
    if days < 0:
        return f"overdue since {due:%a %d %b}"
    if days == 0:
        return "today"
    if days == 1:
        return "tomorrow"
    return f"{due:%a %d %b %Y}"


def sorted_items(
    library: Any, today: date
) -> list[tuple[str, dict[str, Any]]]:
    """Due items first (most overdue first), then by next review date."""
    items = clean_library(library)
    return sorted(items.items(), key=lambda pair: (pair[1]["due"], pair[1]["name"]))


def due_count(library: Any, today: date) -> int:
    return sum(is_due(item, today) for item in clean_library(library).values())


def table_rows(library: Any, today: date) -> list[list[str]]:
    rows = []
    for _item_id, item in sorted_items(library, today):
        rows.append(
            [
                item["name"],
                KIND_LABELS[item["kind"]],
                step_label(item["step"]),
                due_text(item, today),
                str(item["reviews"]),
            ]
        )
    return rows


def choices(library: Any, today: date) -> list[tuple[str, str]]:
    """Dropdown (label, item id) pairs; the label never shows the content."""
    pairs = []
    for item_id, item in sorted_items(library, today):
        flag = "DUE · " if is_due(item, today) else ""
        pairs.append(
            (
                f"{flag}{item['name']} ({KIND_LABELS[item['kind']].lower()}, "
                f"{len(item['cards'])} card(s))",
                item_id,
            )
        )
    return pairs