Spaces:
Running on Zero
Running on Zero
Download names_dates.py from prasadpatil25/memory-studio: direct link, hf CLI and curl.
- Browser
- Download file 16.7 kB
-
https://huggingface.co/spaces/prasadpatil25/memory-studio/resolve/main/names_dates.py
- Command line
-
hf download hf://spaces/prasadpatil25/memory-studio/names_dates.py
-
curl -L -o names_dates.py https://huggingface.co/spaces/prasadpatil25/memory-studio/resolve/main/names_dates.py
16.7 kB
| """Names & faces and Dates: two builders from *Use Your Head*. | |
| Names & faces: pick one distinctive feature of the face, turn the name into a | |
| sound-alike picture (Margaret -> "more + great"), and make that picture do | |
| something to the feature. Recall runs face -> name, the way you meet people. | |
| Dates: turn the digits of a date into Major System words and link them to a | |
| picture of the event (Hastings, 1066 -> toes + judge). | |
| This module has no UI or model code. Names are personal data: nothing here | |
| stores or logs them; the app keeps them only in the session unless the learner | |
| saves a card to the library in their own browser. | |
| """ | |
| from __future__ import annotations | |
| import re | |
| from typing import Any, Callable | |
| from mnemonic_core import _with_article, cell_text, check_word_for_chunk, table_to_rows | |
| from pronunciation import sound_alikes | |
| MAX_PEOPLE = 20 | |
| MAX_EVENTS = 20 | |
| MAX_FIELD = 120 | |
| NAME_HEADERS = ["Name", "Face feature", "Sound-alike", "Link scene", "Where you met"] | |
| DATE_HEADERS = ["Event", "Date", "Chunks", "Words", "Link scene"] | |
| FEATURE_HINT = "add one feature (e.g. bushy eyebrows)" | |
| _SEPARATORS = ("|", ";", "\t") | |
| def _split_fields(line: str, extra: tuple[str, ...] = ()) -> list[str]: | |
| for separator in _SEPARATORS + extra: | |
| if separator in line: | |
| return [" ".join(part.split()) for part in line.split(separator)] | |
| return [" ".join(line.split())] | |
| def _lines(text: str) -> list[str]: | |
| return [ | |
| re.sub(r"^\s*(?:\d+[.)]\s+|[-*•]\s+)", "", line).strip() | |
| for line in (text or "").splitlines() | |
| if line.strip() | |
| ] | |
| # --------------------------------------------------------------------------- | |
| # Names & faces | |
| # --------------------------------------------------------------------------- | |
| def parse_people(text: str) -> list[tuple[str, str, str]]: | |
| """One person per line: name | face feature | where you met (optional).""" | |
| people = [] | |
| for line in _lines(text): | |
| fields = (_split_fields(line) + ["", ""])[:3] | |
| name, feature, context = fields | |
| if not name: | |
| raise ValueError(f"'{line[:40]}' has no name before the first |.") | |
| if len(name) > 60 or len(feature) > MAX_FIELD or len(context) > MAX_FIELD: | |
| raise ValueError( | |
| f"Keep each name under 60 characters and each detail under " | |
| f"{MAX_FIELD}: '{name[:40]}'." | |
| ) | |
| people.append((name, feature, context)) | |
| if not people: | |
| raise ValueError( | |
| "Enter one person per line, for example: Margaret Chen | big round " | |
| "glasses | finance team." | |
| ) | |
| if len(people) > MAX_PEOPLE: | |
| raise ValueError(f"Enter up to {MAX_PEOPLE} people at a time.") | |
| return people | |
| def name_sound_alike(name: str) -> tuple[str, list[str]]: | |
| """Draft a sound-alike for every word of a name. | |
| Returns (draft, notes). Parts are joined with " / "; a part the dictionary | |
| does not know, or that no common word comes close to, is left as "?" and | |
| explained in the notes. | |
| """ | |
| drafts, notes = [], [] | |
| for part in [p for p in re.split(r"[\s\-]+", name) if p]: | |
| options = sound_alikes(part) | |
| if options: | |
| drafts.append(options[0]) | |
| if len(options) > 1: | |
| notes.append(f"{part}: also " + "; ".join(options[1:])) | |
| else: | |
| drafts.append("?") | |
| notes.append( | |
| f"{part}: " | |
| + ( | |
| "not in the pronunciation dictionary" | |
| if options is None | |
| else "no common words come close" | |
| ) | |
| + "; say it aloud and pick words that sound like it" | |
| ) | |
| return " / ".join(drafts), notes | |
| def _sound_words(sound: str) -> list[str]: | |
| words = re.split(r"\s*(?:/|\+)\s*", sound or "") | |
| return [w for w in (" ".join(x.split()) for x in words) if w and w not in {"?", "…"}] | |
| def name_scene(name: str, feature: str, sound: str) -> str: | |
| """A Link-style scene: the sound-alike picture acts on the face feature.""" | |
| words = _sound_words(sound) | |
| if not words: | |
| return "" | |
| place = f"their {feature}" if feature and feature != FEATURE_HINT else "their face" | |
| # Sound-alike pieces are often not objects ("me + call"), so the phrase is | |
| # quoted as a sound to picture rather than listed as things. | |
| return ( | |
| f"Watch \"{' '.join(words)}\" burst out of {place} with a loud BANG, " | |
| f"huge and bright. Say \"{name}\" as you see it." | |
| ) | |
| def draft_people_rows( | |
| people: list[tuple[str, str, str]], | |
| ) -> tuple[list[list[str]], list[str]]: | |
| rows, notes = [], [] | |
| for name, feature, context in people: | |
| sound, part_notes = name_sound_alike(name) | |
| notes.extend(f"**{name}**: {note}" for note in part_notes) | |
| rows.append([name, feature, sound, name_scene(name, feature, sound), context]) | |
| return rows, notes | |
| def validate_people_rows( | |
| names: list[str], table: Any | |
| ) -> tuple[list[list[str]], list[str], list[str]]: | |
| """Rows must keep every person, in order. Returns (rows, errors, notes).""" | |
| raw_rows = [list(row) + [""] * 5 for row in table_to_rows(table)] | |
| if not raw_rows: | |
| return [], ["Draft the table first, then fill in each face feature."], [] | |
| if len(raw_rows) != len(names): | |
| return [], [ | |
| f"The table has {len(raw_rows)} row(s) but you entered {len(names)} " | |
| "people. Do not add or remove rows; draft again if the list changed." | |
| ], [] | |
| rows, errors, notes = [], [], [] | |
| for index, (expected, raw) in enumerate(zip(names, raw_rows), 1): | |
| name, feature, sound, scene, context = (cell_text(v) for v in raw[:5]) | |
| if name.casefold() != expected.casefold(): | |
| errors.append( | |
| f"Row {index}: expected **{expected}** but found " | |
| f"**{name or '(blank)'}**. Keep the names in the order you entered." | |
| ) | |
| continue | |
| if feature == FEATURE_HINT: | |
| feature = "" | |
| if not feature and not context: | |
| errors.append( | |
| f"Row {index} (**{name}**): add a face feature or where you met, " | |
| "so the card has something to recognise them by." | |
| ) | |
| if not _sound_words(sound): | |
| notes.append(f"**{name}**: no sound-alike yet. Say the name aloud and add one.") | |
| elif not scene: | |
| scene = name_scene(name, feature, sound) | |
| if not feature: | |
| notes.append( | |
| f"**{name}**: no face feature. Buzan's method links the name to " | |
| "something you will see next time: a nose, eyebrows, a smile." | |
| ) | |
| rows.append([name, feature, sound, scene, context]) | |
| return rows, errors, notes | |
| def people_markdown(rows: list[list[str]]) -> str: | |
| lines = [ | |
| "## Names & faces", | |
| "", | |
| "Look at the feature, see the picture act on it, and say the name.", | |
| "", | |
| ] | |
| for index, (name, feature, sound, scene, context) in enumerate(rows, 1): | |
| lines.append(f"### {index}. {name}") | |
| lines.append("") | |
| if feature: | |
| lines.append(f"- **Face feature:** {feature}") | |
| if context: | |
| lines.append(f"- **Where you met:** {context}") | |
| if sound: | |
| lines.append( | |
| "- **Sound-alike:** " | |
| + " / ".join( | |
| " + ".join(f"**{w}**" for w in part.split(" + ")) | |
| for part in sound.split(" / ") | |
| ) | |
| ) | |
| if scene: | |
| lines.append(f"- **Scene:** {scene}") | |
| lines.append("") | |
| lines.extend( | |
| [ | |
| "### Make it stick", | |
| "", | |
| "1. Use each name aloud soon after you hear it, and once more when " | |
| "you say goodbye.", | |
| "2. Cover the names, read each face feature, and recall the name " | |
| "through its picture.", | |
| "3. Review on the same rhythm as everything else.", | |
| ] | |
| ) | |
| return "\n".join(lines) | |
| def people_practice(rows: list[list[str]]) -> list[dict[str, str]]: | |
| cards = [] | |
| for name, feature, sound, scene, context in rows: | |
| clues = [] | |
| if feature: | |
| clues.append(f"**{feature}**") | |
| if context: | |
| clues.append(f"met at {context}" if feature else f"**{context}**") | |
| answer = f"**{name}**" | |
| if sound: | |
| answer += f" (sounds like {sound})" | |
| if scene: | |
| answer += f"\n\n{scene}" | |
| cards.append( | |
| {"prompt": "Who is this? " + ", ".join(clues), "answer": answer} | |
| ) | |
| return cards | |
| # --------------------------------------------------------------------------- | |
| # Dates | |
| # --------------------------------------------------------------------------- | |
| MONTHS = { | |
| name: f"{number:02d}" | |
| for number, names in enumerate( | |
| ( | |
| ("january", "jan"), | |
| ("february", "feb"), | |
| ("march", "mar"), | |
| ("april", "apr"), | |
| ("may",), | |
| ("june", "jun"), | |
| ("july", "jul"), | |
| ("august", "aug"), | |
| ("september", "sep", "sept"), | |
| ("october", "oct"), | |
| ("november", "nov"), | |
| ("december", "dec"), | |
| ), | |
| 1, | |
| ) | |
| for name in names | |
| } | |
| _ORDINALS = {"st", "nd", "rd", "th"} | |
| def parse_events(text: str) -> list[tuple[str, str]]: | |
| """One event per line: event | date (also "event: date" or "event - date").""" | |
| events = [] | |
| for line in _lines(text): | |
| fields = _split_fields(line, (" - ", " – ", ": ")) | |
| if len(fields) < 2 or not fields[0] or not fields[-1]: | |
| raise ValueError( | |
| f"'{line[:50]}' needs an event and a date, for example: Battle of " | |
| "Hastings | 1066." | |
| ) | |
| event, when = fields[0], " ".join(fields[1:]) | |
| if len(event) > MAX_FIELD or len(when) > 40: | |
| raise ValueError(f"Shorten '{event[:40]}' or its date.") | |
| events.append((event, when)) | |
| if not events: | |
| raise ValueError( | |
| "Enter one event per line, for example: Battle of Hastings | 1066, or " | |
| "Mum's birthday | 14 March." | |
| ) | |
| if len(events) > MAX_EVENTS: | |
| raise ValueError(f"Enter up to {MAX_EVENTS} events at a time.") | |
| return events | |
| def date_chunks(when: str) -> tuple[list[str], list[str]]: | |
| """Digits of a date, in the order typed, as Major chunks. | |
| Month names become two digits (March -> 03); "14th" counts as 14; other | |
| words (weekdays, AD, BC) are reported as not encoded. A group of three or | |
| more digits is split into pairs, so 1066 -> 10 66 and 476 -> 47 6. | |
| Returns (chunks, ignored words). Raises ValueError if no digits remain. | |
| """ | |
| chunks, ignored = [], [] | |
| for token in re.findall(r"\d+|[A-Za-z]+", when or ""): | |
| if token.isdigit(): | |
| if len(token) <= 2: | |
| chunks.append(token) | |
| else: | |
| chunks.extend(token[i : i + 2] for i in range(0, len(token), 2)) | |
| elif token.casefold() in MONTHS: | |
| chunks.append(MONTHS[token.casefold()]) | |
| elif token.casefold() not in _ORDINALS: | |
| ignored.append(token) | |
| if not chunks: | |
| raise ValueError(f"'{when}' has no digits or month name to encode.") | |
| if len("".join(chunks)) > 12: | |
| raise ValueError(f"'{when}' is too long for one date; keep it to 12 digits.") | |
| return chunks, ignored | |
| def _split_words(text: str, count: int) -> list[str]: | |
| pieces = [" ".join(p.split()) for p in (text or "").split(",")] | |
| pieces = [p for p in pieces if p] | |
| if len(pieces) == 1 and count > 1: | |
| pieces = pieces[0].split() | |
| return pieces | |
| def date_scene(event: str, words: list[str]) -> str: | |
| if not words: | |
| return "" | |
| if len(words) == 1: | |
| action = f"a giant {words[0]} crashes into the middle of it" | |
| else: | |
| action = ( | |
| f"a giant {words[0]} crashes into {_with_article(words[1])}" | |
| + "".join(f", then {_with_article(word)}" for word in words[2:]) | |
| ) | |
| return f"Picture {event}. Suddenly {action}. Everyone gasps." | |
| def draft_event_rows( | |
| events: list[tuple[str, str]], | |
| word_for: Callable[[str], tuple[str, str] | None], | |
| ) -> tuple[list[list[str]], list[str]]: | |
| rows, notes = [], [] | |
| for event, when in events: | |
| chunks, ignored = date_chunks(when) | |
| words = [(word_for(chunk) or ("", ""))[0] for chunk in chunks] | |
| if ignored: | |
| notes.append( | |
| f"**{event}**: not encoded: {', '.join(ignored)}. Remember it " | |
| "separately." | |
| ) | |
| rows.append( | |
| [ | |
| event, | |
| when, | |
| " ".join(chunks), | |
| ", ".join(w for w in words), | |
| date_scene(event, [w for w in words if w]), | |
| ] | |
| ) | |
| return rows, notes | |
| def validate_event_rows( | |
| events: list[tuple[str, str]], table: Any | |
| ) -> tuple[list[dict[str, Any]], list[str], list[str]]: | |
| """Check every event is present in order and each word encodes its chunk.""" | |
| raw_rows = [list(row) + [""] * 5 for row in table_to_rows(table)] | |
| if not raw_rows: | |
| return [], ["Draft the table first."], [] | |
| if len(raw_rows) != len(events): | |
| return [], [ | |
| f"The table has {len(raw_rows)} row(s) but you entered {len(events)} " | |
| "events. Do not add or remove rows; draft again if the list changed." | |
| ], [] | |
| reviewed, errors, notes = [], [], [] | |
| for index, ((event, when), raw) in enumerate(zip(events, raw_rows), 1): | |
| name, _date, _chunks, words_text, scene = (cell_text(v) for v in raw[:5]) | |
| if name.casefold() != event.casefold(): | |
| errors.append( | |
| f"Row {index}: expected **{event}** but found **{name or '(blank)'}**. " | |
| "Keep the events in the order you entered." | |
| ) | |
| continue | |
| chunks, _ignored = date_chunks(when) | |
| words = _split_words(words_text, len(chunks)) | |
| if len(words) != len(chunks): | |
| errors.append( | |
| f"**{event}**: {len(chunks)} chunk(s) ({' '.join(chunks)}) need " | |
| f"{len(chunks)} word(s), separated by commas; found {len(words)}." | |
| ) | |
| continue | |
| for chunk, word in zip(chunks, words): | |
| ok, check = check_word_for_chunk(word, chunk) | |
| if not ok: | |
| errors.append(f"**{event}**: `{chunk}` = **{word}**: {check}.") | |
| if not scene: | |
| scene = date_scene(event, words) | |
| else: | |
| missing = [w for w in words if w.casefold() not in scene.casefold()] | |
| if missing: | |
| notes.append( | |
| f"**{event}**: the scene does not mention " | |
| + ", ".join(f"**{w}**" for w in missing) | |
| + ". Update it, or clear it to get a fresh one." | |
| ) | |
| reviewed.append( | |
| {"event": event, "when": when, "chunks": chunks, "words": words, "scene": scene} | |
| ) | |
| return reviewed, errors, notes | |
| def event_rows_for_table(reviewed: list[dict[str, Any]]) -> list[list[str]]: | |
| return [ | |
| [r["event"], r["when"], " ".join(r["chunks"]), ", ".join(r["words"]), r["scene"]] | |
| for r in reviewed | |
| ] | |
| def events_markdown(reviewed: list[dict[str, Any]]) -> str: | |
| lines = [ | |
| "## Dates", | |
| "", | |
| "See the event, watch the date pictures act on it, then decode them.", | |
| "", | |
| ] | |
| for index, row in enumerate(reviewed, 1): | |
| chain = " → ".join(f"**{word}**" for word in row["words"]) | |
| lines.extend( | |
| [ | |
| f"### {index}. {row['event']}: {row['when']}", | |
| "", | |
| f"{row['scene']}", | |
| "", | |
| f"**Say it back:** {chain} = `{' '.join(row['chunks'])}`", | |
| "", | |
| ] | |
| ) | |
| lines.extend( | |
| [ | |
| "_Only the bold words carry digits. Digits keep the order you typed " | |
| "the date in; month names became two digits (March = 03)._", | |
| ] | |
| ) | |
| return "\n".join(lines) | |
| def event_practice(reviewed: list[dict[str, Any]]) -> list[dict[str, str]]: | |
| return [ | |
| { | |
| "prompt": f"When is **{row['event']}**? Recall the pictures, then " | |
| "decode the date.", | |
| "answer": f"**{row['when']}**: " | |
| + " → ".join(f"**{w}**" for w in row["words"]) | |
| + f" (`{' '.join(row['chunks'])}`)\n\n{row['scene']}", | |
| } | |
| for row in reviewed | |
| ] | |