Spaces:
Running on Zero
Running on Zero
Download study_library.py from prasadpatil25/memory-studio: direct link, hf CLI and curl.
- Browser
- Download file 7.42 kB
-
https://huggingface.co/spaces/prasadpatil25/memory-studio/resolve/main/study_library.py
- Command line
-
hf download hf://spaces/prasadpatil25/memory-studio/study_library.py
-
curl -L -o study_library.py https://huggingface.co/spaces/prasadpatil25/memory-studio/resolve/main/study_library.py
7.42 kB
| """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 | |