diff --git a/.gitattributes b/.gitattributes index b4823b0..3160fbc 100644 --- a/.gitattributes +++ b/.gitattributes @@ -24,5 +24,7 @@ codegen/layout/directions.json -text tests/fixtures/layout/** -text # The address-in-prose cases (serial 123), the same bytes as the npm SDK's copy (the test holds its sha256). tests/fixtures/address-in-prose.json -text +# The name finder's shared cases, the same bytes as the npm SDK's copy (both tests hold its sha256). +tests/fixtures/name-finder.cases.json -text # The Kanka door's tables and wording, the same bytes as the npm SDK's copy (both tests hold its sha256). src/onlyworlds/convert/kanka.json -text diff --git a/CHANGELOG.md b/CHANGELOG.md index 1f8b450..9a6799b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ The package version runs on its own semver; the schema it is generated from is ` ## Unreleased +## 0.141.0 (2026-11-23) + +- **`name_finder(elements, case=...)`**: a world's element names found in prose. It reads the names once and answers `find(text)`, which lists every `NameFound` (`start`, `end`, `element`) in order, `element` being the object that was passed in, so a tool can mark the words that are elements. It finds and never writes. `case` must be given, `"exact"` or `"folded"` (simple case folding, Unicode 15.1), with no default; `names` gives the names an element is found by, by default its `name` alone. The rule: a whole name only, where the character on each side is not a letter, a combining mark, a decimal digit or an underscore in any script (so `Kira's` holds the name and `Kiran` does not); trimmed, three characters at least; the longest whole name where several start at one place; a name two elements share is never answered, nor anything inside it; nothing inside an address or a Markdown link. Limits: text is compared as written, with no Unicode normalisation; a space in a name matches that one space; in a script written without spaces between words a name is whole only between punctuation or spaces. The work for one text is at most its length times the longest name's length, whatever the number of names, with no pattern that backtracks. The npm SDK's `nameFinder` (4.194.0) is the same rule on the same file of cases (`tests/fixtures/name-finder.cases.json`, 47 cases, each want written by hand); the two differ only in what `start` and `end` count, code points here and UTF-16 units there. +- The README said that finding where an address starts in a text was the caller's work; `find_ow_links` does it, and the Addresses section now says so. +- `draught()`'s docstring said the server had sent the compact packet by default since 2026-11-02. The REST route's default is `false` until 2027-05-02, when it becomes `true`; the MCP tool `get_draught` defaults to `true` already. The docstring now says so. + ## 0.140.0 (2026-11-22) - **The schema pin moves to `v0.34.1-dist.145`** (canonical 00.34.01 unchanged, no schema file moved, `_schema.py` changes only its provenance lines). The charter page's rule 4 now names the `description` as the text an AI follows, the Charter's and each skill Object's, whole as the world holds it; a leading Charter whose `description` holds nothing gives that reader no house rules. The charter fixture gains four cases, each a newer marked Charter with an empty `description` beside an older one with text: the newer leads and its `skill` is empty. `charter_of` already answered all four so; no answer on an existing case moves. diff --git a/README.md b/README.md index 1247568..9be0c31 100644 --- a/README.md +++ b/README.md @@ -365,7 +365,30 @@ reading = parse_ow_link(text) # AddressReading: form, world, world_is_slug, typ # a refusal raises AddressError: err.reason is the profile's name ("bad_id", "uppercase", ...) ``` -A field that holds an address is text: never fetch or resolve it on the server. `parse_ow_link` reads one string whole, so `ow://object/.` is refused. In prose, `read_ow_link_at(text, index)` reads the address that starts at `index` and answers an `AddressAt` (`reading`, `end`: the index just past it) or `None`; the address continues past its id only with `@` and a moment and `?lens=` and a lens, so a full stop, another query key and a fragment are left as prose. Finding where an address starts is yours. The profile: [`profiles/address.md`](https://github.com/OnlyWorlds/schema-dist/blob/main/profiles/address.md), with its fixture, which is this module's test. +A field that holds an address is text: never fetch or resolve it on the server. `parse_ow_link` reads one string whole, so `ow://object/.` is refused. In prose, `read_ow_link_at(text, index)` reads the address that starts at `index` and answers an `AddressAt` (`reading`, `end`: the index just past it) or `None`; the address continues past its id only with `@` and a moment and `?lens=` and a lens, so a full stop, another query key and a fragment are left as prose. `find_ow_links(text)` finds every address in a text, each an `AddressFound` (`start`, `end`, `reading`). The profile: [`profiles/address.md`](https://github.com/OnlyWorlds/schema-dist/blob/main/profiles/address.md), with its fixture, which is this module's test. + +### Names in prose + +`name_finder` reads a world's element names once and answers a function that finds them in any text, so a tool can show which words are elements: a mark for a reader, a suggestion, a link a person chooses to make. It finds and never writes. + +```python +from onlyworlds import name_finder + +elements = [{"id": "a1", "name": "Iron Gate"}, {"id": "b2", "name": "Kira"}] +find = name_finder(elements, case="exact") # once per world +found = find("Kira's watch ends at the Iron Gate.") +# [NameFound(start=0, end=4, element=elements[1]), NameFound(start=25, end=34, element=elements[0])] +``` + +`case` must be given: `"exact"` for a page that marks names unasked, `"folded"` (case ignored) for an editor that only suggests. The rule, the same in the npm SDK's `nameFinder`: + +- A whole name only: the character on each side is not a letter, a combining mark, a decimal digit or an underscore, in any script. `Kira's` and `Kira-led` hold the name; `Kiran` does not. +- A name is trimmed and is three characters at least. Where several names start at one place, the longest whole one is taken. +- A name two elements share is never answered, and nothing inside it is: the text stays plain there. +- Nothing is read inside an address or a Markdown link `[label](target)`. +- Every mention is answered, in order. `element` is the object you passed in; `start` and `end` count code points (the npm SDK counts UTF-16 units). + +`names` gives the names an element is found by, such as a tool's own aliases: `name_finder(elements, case="folded", names=lambda el: [el["name"], *el.get("aliases", [])])`. Which elements go in is yours to choose. Three limits: text is compared as written, with no Unicode normalisation; a space in a name matches that one space; and in a script written without spaces between words (Chinese, Japanese, Thai) a name is whole only between punctuation or spaces. The work for one text is at most its length times the longest name's length, whatever the number of names. ### Open with diff --git a/src/onlyworlds/__init__.py b/src/onlyworlds/__init__.py index 25a38b9..27308a7 100644 --- a/src/onlyworlds/__init__.py +++ b/src/onlyworlds/__init__.py @@ -134,6 +134,7 @@ thread_of, unread_for, ) +from .name_finder import NameFound, name_finder from .names import type_word from .openers import Opener, Tool, ToolOpen, openers_for from .push import Patch, PushPlan, PushResult, plan_push, push, verify_level @@ -236,6 +237,7 @@ "MapSpaceMap", "MapSpaceOutline", "MapSpacePin", + "NameFound", "Opener", "Patch", "PreconditionFailed", @@ -314,6 +316,7 @@ "layout_of", "lenses_in_use", "map_space", + "name_finder", "note_of", "openers_for", "out_degree_of", diff --git a/src/onlyworlds/_version.py b/src/onlyworlds/_version.py index 120dcc3..8734918 100644 --- a/src/onlyworlds/_version.py +++ b/src/onlyworlds/_version.py @@ -1 +1 @@ -__version__ = "0.140.0" +__version__ = "0.141.0" diff --git a/src/onlyworlds/name_finder.py b/src/onlyworlds/name_finder.py new file mode 100644 index 0000000..d611eca --- /dev/null +++ b/src/onlyworlds/name_finder.py @@ -0,0 +1,200 @@ +"""Element names found in prose: ``name_finder`` reads a world's names once and answers a function that finds +them in any text. It finds and never writes: what a tool does with a found name (a mark for a reader, a +suggestion, a link a person chooses to make) is the tool's. + +A rule of this package and the npm SDK's ``nameFinder``, not of the standard: both run one file of cases +(``tests/fixtures/name-finder.cases.json``, the same bytes in both repositories).""" + +from __future__ import annotations + +import unicodedata +from collections.abc import Callable, Iterable, Mapping +from dataclasses import dataclass +from typing import Any, Literal + +from .address import find_ow_links +from .room import _WHITE_SPACE +from .worldfile import simple_case_fold + +__all__ = ["NameFound", "name_finder"] + +_NAME_MIN = 3 +"""A name shorter than this many characters (code points, after its white space is trimmed) is never looked for.""" + +_ASCII_WORD = frozenset("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_") + + +@dataclass(frozen=True) +class NameFound[T]: + """One name found in a text: ``start`` and ``end`` in the text (code points; the npm SDK's ``nameFinder`` + counts UTF-16 units), and ``element``, the same object ``name_finder`` was given.""" + + start: int + end: int + element: T + + +class _Hit[T]: + __slots__ = ("element", "id", "shared") + + def __init__(self, id: str, element: T) -> None: + self.id = id + self.element = element + self.shared = False + + +class _Node[T]: + __slots__ = ("hit", "next") + + def __init__(self) -> None: + self.next: dict[str, _Node[T]] = {} + self.hit: _Hit[T] | None = None + + +def _in_a_word(ch: str) -> bool: + """A letter of any script, a combining mark, a decimal digit or an underscore: beside one, a name is inside a + word.""" + if ch < "\x80": + return ch in _ASCII_WORD + return ch.isalpha() or unicodedata.category(ch) == "Nd" or unicodedata.category(ch).startswith("M") + + +def _markdown_links(text: str) -> list[tuple[int, int]]: + """Every Markdown link ``[label](target)`` as ``(start, end)``: a ``[``, a label up to the first ``]``, a ``(`` + right after it, a target up to the first ``)``. One pass: each bracket and parenthesis is searched for once.""" + spans: list[tuple[int, int]] = [] + close = -2 + paren = -2 + opened = text.find("[") + while opened != -1: + if close <= opened: + close = text.find("]", opened + 1) + if close == -1: + break + if not text.startswith("(", close + 1): + opened = text.find("[", opened + 1) + continue + if paren < close + 2: + paren = text.find(")", close + 2) + if paren == -1: + break + spans.append((opened, paren + 1)) + opened = text.find("[", paren + 1) + return spans + + +def _passed_over(text: str) -> list[tuple[int, int]]: + """The stretches no name is read in: every address and every Markdown link, in order, none overlapping.""" + spans = _markdown_links(text) + spans.extend((a.start, a.end) for a in find_ow_links(text)) + spans.sort() + out: list[tuple[int, int]] = [] + for start, end in spans: + if out and start < out[-1][1]: + if end > out[-1][1]: + out[-1] = (out[-1][0], end) + else: + out.append((start, end)) + return out + + +def name_finder[T: Mapping[str, Any]]( + elements: Iterable[T], + *, + case: Literal["exact", "folded"], + names: Callable[[T], Iterable[object]] | None = None, +) -> Callable[[str], list[NameFound[T]]]: + """A finder of a world's element names in prose: read the names once, then call the answer on each text. + + ``elements`` is any iterable of mappings with a string ``id`` and a ``name``. ``case`` must be given: ``"exact"`` + (a name as written) or ``"folded"`` (simple case folding, Unicode 15.1, the fold the ``.owworld`` reader uses); + there is no default, so a tool never gets the other rule by leaving it out. ``names`` gives the names an element + is found by, by default its ``name`` alone; a value that is not a string is passed over. + + The answer, ``find(text)``, lists every ``NameFound`` (``start``, ``end``, ``element``) in order, none + overlapping: + + - A whole name only: the character on each side of it is not a letter, a combining mark, a decimal digit or an + underscore, in any script. So ``Kira's`` and ``Kira-led`` hold the name ``Kira``, and ``Kiran`` does not. + - A name is trimmed of white space and is three characters at least; a shorter one is never looked for. + - Where several names start at one place, the longest whole one is taken (``Iron Gate`` over ``Iron``). + - A name two elements share is never answered, and nothing inside it is: the text stays plain there. One + element listed twice, or found by two of its own names, is one element. + - Nothing is read inside an address (what ``find_ow_links`` finds) or a Markdown link ``[label](target)``, and + no name is read across the edge of one. + - Text is compared as written: no Unicode normalisation, and a space in a name matches that one space. + + ``element`` in an answer is the object that was passed in. Nothing given is changed. The work for one text is + at most its length times the longest name's length, whatever the number of names, with no pattern that + backtracks. ``start`` and ``end`` count code points (the npm SDK's ``nameFinder`` counts UTF-16 units). A + ``case`` that is neither word, a ``names`` that cannot be called, an element without a string ``id``, or a + ``text`` that is not a string is a ``TypeError``.""" + if case not in ("exact", "folded"): + raise TypeError(f"name_finder: case is 'exact' or 'folded'; got {case!r}.") + if names is not None and not callable(names): + raise TypeError("name_finder: names is a function from an element to its names.") + if isinstance(elements, (str, bytes, Mapping)) or not isinstance(elements, Iterable): + raise TypeError("name_finder: elements is an iterable of mappings with an id and a name.") + folded = case == "folded" + root: _Node[T] = _Node() + for element in elements: + if not isinstance(element, Mapping) or not isinstance(element.get("id"), str) or element["id"] == "": + raise TypeError("name_finder: every element is a mapping with a string id.") + for raw in names(element) if names is not None else (element.get("name"),): + if not isinstance(raw, str): + continue + name = raw.strip(_WHITE_SPACE) + if len(name) < _NAME_MIN: + continue + node = root + for ch in simple_case_fold(name) if folded else name: + child = node.next.get(ch) + if child is None: + child = node.next[ch] = _Node() + node = child + if node.hit is None: + node.hit = _Hit(element["id"], element) + elif node.hit.id != element["id"]: + node.hit.shared = True + + def find(text: str) -> list[NameFound[T]]: + if not isinstance(text, str): + raise TypeError("name_finder: text must be a string") + found: list[NameFound[T]] = [] + firsts = root.next + if not firsts: + return found + spans = _passed_over(text) + hay = simple_case_fold(text) if folded else text + length = len(text) + span = 0 + i = 0 + while i < length: + if span < len(spans) and i >= spans[span][0]: + i = spans[span][1] + span += 1 + continue + if hay[i] in firsts and (i == 0 or not _in_a_word(text[i - 1])): + limit = spans[span][0] if span < len(spans) else length + node = root + j = i + best: _Hit[T] | None = None + best_end = -1 + while j < limit: + child = node.next.get(hay[j]) + if child is None: + break + node = child + j += 1 + if node.hit is not None and (j >= length or not _in_a_word(text[j])): + best = node.hit + best_end = j + if best is not None: + if not best.shared: + found.append(NameFound(i, best_end, best.element)) + i = best_end + continue + i += 1 + return found + + return find diff --git a/tests/fixtures/name-finder.cases.json b/tests/fixtures/name-finder.cases.json new file mode 100644 index 0000000..56b4ead --- /dev/null +++ b/tests/fixtures/name-finder.cases.json @@ -0,0 +1,1225 @@ +{ + "about": "Cases for nameFinder (@onlyworlds/sdk) and name_finder (the onlyworlds Python package): the same bytes in both repositories. In a case, an element with a names list is found by those names (the names option), one without by its name; want lists what find(text) answers, in order, each the place of its first character and its length, both in code points, and the id of its element. A timed case is built from its recipe ({i} is the count from 0) and must answer count names in under underMs milliseconds. Made by test/fixtures/generate-name-finder-cases.mjs in the SDK repository; every want is written by hand there.", + "version": 1, + "underMs": 2000, + "cases": [ + { + "name": "two names, in order", + "case": "exact", + "elements": [ + { + "id": "a", + "name": "Iron Gate" + }, + { + "id": "b", + "name": "Kira" + } + ], + "text": "Kira's watch ends at the Iron Gate.", + "want": [ + { + "at": 0, + "length": 4, + "id": "b" + }, + { + "at": 25, + "length": 9, + "id": "a" + } + ] + }, + { + "name": "a possessive and a hyphen leave the name whole", + "case": "exact", + "elements": [ + { + "id": "t", + "name": "Odran" + }, + { + "id": "j", + "name": "Tamsin" + } + ], + "text": "Odran's map, a Tamsin-led crew.", + "want": [ + { + "at": 0, + "length": 5, + "id": "t" + }, + { + "at": 15, + "length": 6, + "id": "j" + } + ] + }, + { + "name": "a name inside a longer word is not found, at either end", + "case": "exact", + "elements": [ + { + "id": "k", + "name": "Kira" + } + ], + "text": "Kiran and McKira and McKiran.", + "want": [] + }, + { + "name": "a digit on either side is inside a word", + "case": "exact", + "elements": [ + { + "id": "u", + "name": "Unit 7" + }, + { + "id": "k", + "name": "Kira" + } + ], + "text": "Unit 7. Unit 73. 2Kira. Kira2.", + "want": [ + { + "at": 0, + "length": 6, + "id": "u" + } + ] + }, + { + "name": "an underscore on either side is inside a word", + "case": "exact", + "elements": [ + { + "id": "k", + "name": "Kira" + } + ], + "text": "Kira_x, _Kira, Kira.", + "want": [ + { + "at": 15, + "length": 4, + "id": "k" + } + ] + }, + { + "name": "a name that starts or ends with a letter outside ASCII is found whole", + "case": "exact", + "elements": [ + { + "id": "e", + "name": "\u00c9lodie" + }, + { + "id": "z", + "name": "Zo\u00eb" + } + ], + "text": "Then \u00c9lodie rode with Zo\u00eb.", + "want": [ + { + "at": 5, + "length": 6, + "id": "e" + }, + { + "at": 22, + "length": 3, + "id": "z" + } + ] + }, + { + "name": "a letter outside ASCII after or before a name is inside a word", + "case": "exact", + "elements": [ + { + "id": "a", + "name": "Ana" + }, + { + "id": "z", + "name": "Zo\u00eb" + }, + { + "id": "w", + "name": "lodie" + } + ], + "text": "Ana\u00efs and Zo\u00ebx and \u00c9lodie.", + "want": [] + }, + { + "name": "a combining mark after a name is inside a word", + "case": "exact", + "elements": [ + { + "id": "a", + "name": "Ana" + } + ], + "text": "Ana\u0301 came, then Ana.", + "want": [ + { + "at": 16, + "length": 3, + "id": "a" + } + ] + }, + { + "name": "a decimal digit of another script is inside a word; a superscript is not", + "case": "exact", + "elements": [ + { + "id": "k", + "name": "Kira" + } + ], + "text": "Kira\u0663 and Kira\u00b2.", + "want": [ + { + "at": 10, + "length": 4, + "id": "k" + } + ] + }, + { + "name": "places count code points: a character above the BMP before a name", + "case": "exact", + "elements": [ + { + "id": "k", + "name": "Kira" + } + ], + "text": "\ud83d\udc09 Kira \ud83d\udc09\ud83d\udc09 Kira", + "want": [ + { + "at": 2, + "length": 4, + "id": "k" + }, + { + "at": 10, + "length": 4, + "id": "k" + } + ] + }, + { + "name": "a name of letters above the BMP; two of them are too short", + "case": "exact", + "elements": [ + { + "id": "d", + "name": "\ud801\udc00\ud801\udc01\ud801\udc02" + }, + { + "id": "s", + "name": "\ud801\udc00\ud801\udc01" + } + ], + "text": "\ud801\udc00\ud801\udc01\ud801\udc02 and \ud801\udc00\ud801\udc01.", + "want": [ + { + "at": 0, + "length": 3, + "id": "d" + } + ] + }, + { + "name": "the longest whole name wins", + "case": "exact", + "elements": [ + { + "id": "i", + "name": "Iron" + }, + { + "id": "g", + "name": "Iron Gate" + } + ], + "text": "The Iron Gate and the Iron Gates and Iron.", + "want": [ + { + "at": 4, + "length": 9, + "id": "g" + }, + { + "at": 22, + "length": 4, + "id": "i" + }, + { + "at": 37, + "length": 4, + "id": "i" + } + ] + }, + { + "name": "the leftmost name is taken, and the search goes on after it", + "case": "exact", + "elements": [ + { + "id": "g", + "name": "Iron Gate" + }, + { + "id": "k", + "name": "Gate Keeper" + } + ], + "text": "The Iron Gate Keeper and the Gate Keeper.", + "want": [ + { + "at": 4, + "length": 9, + "id": "g" + }, + { + "at": 29, + "length": 11, + "id": "k" + } + ] + }, + { + "name": "every mention is answered", + "case": "exact", + "elements": [ + { + "id": "k", + "name": "Kira" + }, + { + "id": "m", + "name": "Mira" + } + ], + "text": "Kira,Mira;Kira Kira", + "want": [ + { + "at": 0, + "length": 4, + "id": "k" + }, + { + "at": 5, + "length": 4, + "id": "m" + }, + { + "at": 10, + "length": 4, + "id": "k" + }, + { + "at": 15, + "length": 4, + "id": "k" + } + ] + }, + { + "name": "a name two elements share stays plain", + "case": "exact", + "elements": [ + { + "id": "a", + "name": "Ember" + }, + { + "id": "b", + "name": "Ember" + }, + { + "id": "k", + "name": "Kira" + } + ], + "text": "Ember called to Kira.", + "want": [ + { + "at": 16, + "length": 4, + "id": "k" + } + ] + }, + { + "name": "nothing inside a shared name is answered", + "case": "exact", + "elements": [ + { + "id": "a", + "name": "Old Ember" + }, + { + "id": "b", + "name": "Old Ember" + }, + { + "id": "e", + "name": "Ember" + } + ], + "text": "Old Ember, then Ember.", + "want": [ + { + "at": 16, + "length": 5, + "id": "e" + } + ] + }, + { + "name": "a shared name is plain where a longer name is not whole", + "case": "exact", + "elements": [ + { + "id": "a", + "name": "Ember" + }, + { + "id": "b", + "name": "Ember" + }, + { + "id": "l", + "name": "Ember Lake" + } + ], + "text": "Ember Lakes, then Ember Lake.", + "want": [ + { + "at": 18, + "length": 10, + "id": "l" + } + ] + }, + { + "name": "one element listed twice, or found by the same name twice, is one element", + "case": "exact", + "elements": [ + { + "id": "k", + "name": "Kira" + }, + { + "id": "k", + "name": "Kira" + }, + { + "id": "m", + "names": [ + "Mira", + "Mira" + ] + } + ], + "text": "Kira and Mira.", + "want": [ + { + "at": 0, + "length": 4, + "id": "k" + }, + { + "at": 9, + "length": 4, + "id": "m" + } + ] + }, + { + "name": "an element is found by each of its names", + "case": "exact", + "elements": [ + { + "id": "v", + "names": [ + "Consul Varro", + "Varro", + "the Consul" + ] + } + ], + "text": "Consul Varro spoke. Varro sat. So did the Consul.", + "want": [ + { + "at": 0, + "length": 12, + "id": "v" + }, + { + "at": 20, + "length": 5, + "id": "v" + }, + { + "at": 38, + "length": 10, + "id": "v" + } + ] + }, + { + "name": "two elements that share one of several names: that name is plain, the others are found", + "case": "exact", + "elements": [ + { + "id": "v", + "names": [ + "Varro", + "the Consul" + ] + }, + { + "id": "w", + "names": [ + "Wren", + "the Consul" + ] + } + ], + "text": "Varro and Wren: which is the Consul?", + "want": [ + { + "at": 0, + "length": 5, + "id": "v" + }, + { + "at": 10, + "length": 4, + "id": "w" + } + ] + }, + { + "name": "a name under three characters is never looked for; three is enough", + "case": "exact", + "elements": [ + { + "id": "a", + "name": "Al" + }, + { + "id": "b", + "name": " Bo " + }, + { + "id": "c", + "name": "Ada" + } + ], + "text": "Al met Bo and Ada.", + "want": [ + { + "at": 14, + "length": 3, + "id": "c" + } + ] + }, + { + "name": "a name is trimmed of white space, every kind of it", + "case": "exact", + "elements": [ + { + "id": "k", + "name": " Kira\u00a0" + }, + { + "id": "m", + "name": "\u2003Mira\u0085" + } + ], + "text": "Kira and Mira.", + "want": [ + { + "at": 0, + "length": 4, + "id": "k" + }, + { + "at": 9, + "length": 4, + "id": "m" + } + ] + }, + { + "name": "a byte order mark and a file separator are not white space: the name keeps them", + "case": "exact", + "elements": [ + { + "id": "k", + "name": "\ufeffKira" + }, + { + "id": "m", + "name": "\u001cMira" + } + ], + "text": "Kira and Mira.", + "want": [] + }, + { + "name": "exact: another case is another word", + "case": "exact", + "elements": [ + { + "id": "c", + "name": "Consul" + } + ], + "text": "The consul and the CONSUL and the Consul.", + "want": [ + { + "at": 34, + "length": 6, + "id": "c" + } + ] + }, + { + "name": "folded: case is ignored, and the answer is the text as written", + "case": "folded", + "elements": [ + { + "id": "c", + "name": "Consul" + } + ], + "text": "The consul and the CONSUL and the Consul.", + "want": [ + { + "at": 4, + "length": 6, + "id": "c" + }, + { + "at": 19, + "length": 6, + "id": "c" + }, + { + "at": 34, + "length": 6, + "id": "c" + } + ] + }, + { + "name": "folded: two names that differ only by case are shared", + "case": "folded", + "elements": [ + { + "id": "a", + "name": "Ember" + }, + { + "id": "b", + "name": "EMBER" + }, + { + "id": "k", + "name": "Kira" + } + ], + "text": "Ember, ember, KIRA.", + "want": [ + { + "at": 14, + "length": 4, + "id": "k" + } + ] + }, + { + "name": "exact: two names that differ only by case are two names", + "case": "exact", + "elements": [ + { + "id": "a", + "name": "Ember" + }, + { + "id": "b", + "name": "EMBER" + } + ], + "text": "Ember, ember, EMBER.", + "want": [ + { + "at": 0, + "length": 5, + "id": "a" + }, + { + "at": 14, + "length": 5, + "id": "b" + } + ] + }, + { + "name": "folded: letters outside ASCII fold too, and above the BMP", + "case": "folded", + "elements": [ + { + "id": "e", + "name": "\u00c9lodie" + }, + { + "id": "d", + "name": "\ud801\udc00\ud801\udc01\ud801\udc02" + } + ], + "text": "\u00e9lodie and \ud801\udc28\ud801\udc29\ud801\udc2a.", + "want": [ + { + "at": 0, + "length": 6, + "id": "e" + }, + { + "at": 11, + "length": 3, + "id": "d" + } + ] + }, + { + "name": "folded: the long s and the Kelvin sign fold to s and k", + "case": "folded", + "elements": [ + { + "id": "r", + "name": "Rose" + }, + { + "id": "k", + "name": "Kira" + } + ], + "text": "Ro\u017fe and \u212aira.", + "want": [ + { + "at": 0, + "length": 4, + "id": "r" + }, + { + "at": 9, + "length": 4, + "id": "k" + } + ] + }, + { + "name": "folded: simple folding only: a dotted capital I stays itself, and a sharp s is never two letters", + "case": "folded", + "elements": [ + { + "id": "i", + "name": "\u0130stan" + }, + { + "id": "s", + "name": "Stra\u00dfe" + } + ], + "text": "istan, Istan, \u0130STAN, STRASSE, STRA\u1e9eE.", + "want": [ + { + "at": 14, + "length": 5, + "id": "i" + }, + { + "at": 30, + "length": 6, + "id": "s" + } + ] + }, + { + "name": "text is compared as written: a letter with a combining mark is not its one-character form", + "case": "folded", + "elements": [ + { + "id": "e", + "name": "\u00c9lodie" + } + ], + "text": "E\u0301lodie rode.", + "want": [] + }, + { + "name": "a space in a name is that one space", + "case": "exact", + "elements": [ + { + "id": "g", + "name": "Iron Gate" + } + ], + "text": "Iron Gate, Iron\nGate, Iron-Gate, Iron Gate.", + "want": [ + { + "at": 34, + "length": 9, + "id": "g" + } + ] + }, + { + "name": "a name may hold punctuation, and may start or end with it", + "case": "exact", + "elements": [ + { + "id": "s", + "name": "St. Brannoc's" + }, + { + "id": "q", + "name": "\"Lucky\" Finn" + }, + { + "id": "w", + "name": "Who?" + } + ], + "text": "At St. Brannoc's, \"Lucky\" Finn asked Who? and Who?s.", + "want": [ + { + "at": 3, + "length": 13, + "id": "s" + }, + { + "at": 18, + "length": 12, + "id": "q" + }, + { + "at": 37, + "length": 4, + "id": "w" + } + ] + }, + { + "name": "nothing is read inside an address, in either form", + "case": "folded", + "elements": [ + { + "id": "c", + "name": "character" + }, + { + "id": "i", + "name": "iron" + }, + { + "id": "k", + "name": "Kira" + } + ], + "text": "ow://character/01a1d4ef-0000-7000-8000-000000000084 and https://www.onlyworlds.com/w/iron-gate/character/01a1d4ef-0000-7000-8000-000000000084 and ow://0193a1c2-7d3e-7f00-8a11-3c5e7b9d2f40/character/01a1d4ef-0000-7000-8000-000000000084, said Kira.", + "want": [ + { + "at": 241, + "length": 4, + "id": "k" + } + ] + }, + { + "name": "an address that is not one is prose", + "case": "folded", + "elements": [ + { + "id": "c", + "name": "character" + } + ], + "text": "elbow://character/x and ow://character/not-an-id", + "want": [ + { + "at": 8, + "length": 9, + "id": "c" + }, + { + "at": 29, + "length": 9, + "id": "c" + } + ] + }, + { + "name": "nothing is read inside a Markdown link, label or target", + "case": "exact", + "elements": [ + { + "id": "k", + "name": "Kira" + }, + { + "id": "g", + "name": "Iron Gate" + } + ], + "text": "[Kira](ow://character/01a1d4ef-0000-7000-8000-000000000084) met Kira at [the Iron Gate](https://example.com/Kira).", + "want": [ + { + "at": 64, + "length": 4, + "id": "k" + } + ] + }, + { + "name": "an address inside a link's target does not end the link", + "case": "exact", + "elements": [ + { + "id": "k", + "name": "Kira" + }, + { + "id": "m", + "name": "Mira" + } + ], + "text": "[x](ow://character/01a1d4ef-0000-7000-8000-000000000084 Kira) Mira", + "want": [ + { + "at": 62, + "length": 4, + "id": "m" + } + ] + }, + { + "name": "brackets that are not a link are prose", + "case": "exact", + "elements": [ + { + "id": "k", + "name": "Kira" + } + ], + "text": "[Kira] and [Kira] (x) and [Kira](unclosed", + "want": [ + { + "at": 1, + "length": 4, + "id": "k" + }, + { + "at": 12, + "length": 4, + "id": "k" + }, + { + "at": 27, + "length": 4, + "id": "k" + } + ] + }, + { + "name": "a bracket that is not a link does not hide a later link", + "case": "exact", + "elements": [ + { + "id": "k", + "name": "Kira" + } + ], + "text": "[sic] [Kira](x) and Kira.", + "want": [ + { + "at": 20, + "length": 4, + "id": "k" + } + ] + }, + { + "name": "a link takes its label from the first bracket and its target to the first parenthesis", + "case": "exact", + "elements": [ + { + "id": "k", + "name": "Kira" + }, + { + "id": "m", + "name": "Mira" + } + ], + "text": "[a [Kira](Mira) Mira) and [Kira]Mira[x](y)", + "want": [ + { + "at": 16, + "length": 4, + "id": "m" + }, + { + "at": 27, + "length": 4, + "id": "k" + }, + { + "at": 32, + "length": 4, + "id": "m" + } + ] + }, + { + "name": "no name is read across the edge of a link; a shorter whole one before it is", + "case": "exact", + "elements": [ + { + "id": "n", + "name": "Gate [1" + }, + { + "id": "g", + "name": "Gate" + } + ], + "text": "Gate [1](note) and Gate [1.", + "want": [ + { + "at": 0, + "length": 4, + "id": "g" + }, + { + "at": 19, + "length": 7, + "id": "n" + } + ] + }, + { + "name": "a name is found right beside a link", + "case": "exact", + "elements": [ + { + "id": "k", + "name": "Kira" + } + ], + "text": "Kira[x](y)Kira", + "want": [ + { + "at": 0, + "length": 4, + "id": "k" + }, + { + "at": 10, + "length": 4, + "id": "k" + } + ] + }, + { + "name": "a script written without spaces: a name is whole only between punctuation or spaces", + "case": "exact", + "elements": [ + { + "id": "t", + "name": "\u6771\u4eac\u90fd" + } + ], + "text": "\u306f\u6771\u4eac\u90fd\u306b\u3002\u6771\u4eac\u90fd\u3002", + "want": [ + { + "at": 6, + "length": 3, + "id": "t" + } + ] + }, + { + "name": "a name that is not a string is passed over", + "case": "exact", + "elements": [ + { + "id": "n", + "name": null + }, + { + "id": "x", + "name": 7 + }, + { + "id": "m" + }, + { + "id": "l", + "names": [ + "Kira", + null, + 7 + ] + } + ], + "text": "Kira and 7 and null.", + "want": [ + { + "at": 0, + "length": 4, + "id": "l" + } + ] + }, + { + "name": "a name alone is the whole text", + "case": "exact", + "elements": [ + { + "id": "k", + "name": "Kira" + } + ], + "text": "Kira", + "want": [ + { + "at": 0, + "length": 4, + "id": "k" + } + ] + }, + { + "name": "no elements, and no text", + "case": "exact", + "elements": [], + "text": "Kira.", + "want": [] + }, + { + "name": "an empty text", + "case": "exact", + "elements": [ + { + "id": "k", + "name": "Kira" + } + ], + "text": "", + "want": [] + } + ], + "timed": [ + { + "name": "open brackets only", + "elements": { + "count": 1000, + "pattern": "Name{i} Thing" + }, + "text": { + "repeat": "[", + "times": 300000 + }, + "count": 0 + }, + { + "name": "links that never close", + "elements": { + "count": 1000, + "pattern": "Name{i} Thing" + }, + "text": { + "repeat": "[x](", + "times": 100000 + }, + "count": 0 + }, + { + "name": "closing brackets with no link", + "elements": { + "count": 1000, + "pattern": "Name{i} Thing" + }, + "text": { + "repeat": "[x] ", + "times": 100000 + }, + "count": 0 + }, + { + "name": "twenty thousand names, each found five times", + "elements": { + "count": 20000, + "pattern": "Name{i} Thing" + }, + "text": { + "cycle": "Name{i} Thing and ", + "count": 20000, + "times": 100000 + }, + "count": 100000 + }, + { + "name": "one name two hundred thousand times", + "elements": { + "count": 1, + "pattern": "Kira" + }, + "text": { + "repeat": "Kira ", + "times": 200000 + }, + "count": 200000 + }, + { + "name": "a long name that almost matches at every word", + "elements": { + "count": 1, + "pattern": "a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a b" + }, + "text": { + "repeat": "a ", + "times": 200000 + }, + "count": 0 + }, + { + "name": "address prefixes with no address", + "elements": { + "count": 1000, + "pattern": "Name{i} Thing" + }, + "text": { + "repeat": "ow://character/", + "times": 60000 + }, + "count": 0 + } + ] +} diff --git a/tests/test_name_finder.py b/tests/test_name_finder.py new file mode 100644 index 0000000..feee2ce --- /dev/null +++ b/tests/test_name_finder.py @@ -0,0 +1,135 @@ +"""``name_finder``: a world's element names found in prose. The shared cases (``tests/fixtures/name-finder.cases.json``, +the same bytes as the npm SDK's ``test/fixtures/name-finder.cases.json``; both suites hold its sha256, every want +written by hand in the SDK's generator), their timed recipes, then what the cases cannot hold: the object answered, +purity and the refusals.""" + +from __future__ import annotations + +import hashlib +import json +import time +from pathlib import Path +from typing import Any + +import pytest + +from onlyworlds import NameFound, name_finder + +FIXTURE = Path(__file__).resolve().parent / "fixtures" / "name-finder.cases.json" +FIXTURE_SHA256 = "4c4d7d3b4480e4c20bab799972faf90c542b5b570c1b43f7882291444c31007a" +DATA: dict[str, Any] = json.loads(FIXTURE.read_bytes()) +PYTHON_FACTOR = 5 +"""The cases' ``underMs`` is the npm SDK's line, where the slowest recipe takes about a tenth of a second. Here the +slowest recipe's whole test took 0.76 s when this was written, so the line is five times ``underMs``: far above a +slow machine's run, and far below a search that is not linear, which takes minutes on these texts.""" + + +def _names_of(element: dict[str, Any]) -> list[Any]: + names = element.get("names") + return names if isinstance(names, list) else [element.get("name")] + + +def _answer(case: dict[str, Any]) -> list[dict[str, Any]]: + find = name_finder(case["elements"], case=case["case"], names=_names_of) + return [{"at": f.start, "length": f.end - f.start, "id": f.element["id"]} for f in find(case["text"])] + + +def test_the_cases_file_is_the_pinned_bytes_the_ones_the_npm_sdk_runs() -> None: + assert hashlib.sha256(FIXTURE.read_bytes()).hexdigest() == FIXTURE_SHA256 + assert DATA["version"] == 1 + assert len(DATA["cases"]) >= 47 + + +def test_every_shared_case() -> None: + wrong = [ + f"{case['name']}\n want {case['want']}\n got {got}" + for case in DATA["cases"] + if (got := _answer(case)) != case["want"] + ] + assert not wrong, f"{len(wrong)} case(s) disagree:\n " + "\n ".join(wrong) + + +def test_the_shared_cases_hold_answers_of_both_kinds() -> None: + assert any(case["want"] for case in DATA["cases"]) + assert any(not case["want"] for case in DATA["cases"]) + for fold in ("exact", "folded"): + assert any(case["case"] == fold and case["want"] for case in DATA["cases"]), fold + + +def _build(recipe: dict[str, Any]) -> tuple[list[dict[str, str]], str]: + made = recipe["elements"] + elements = [{"id": f"e{i}", "name": made["pattern"].replace("{i}", str(i))} for i in range(made["count"])] + text = recipe["text"] + if "repeat" in text: + return elements, text["repeat"] * text["times"] + return elements, "".join(text["cycle"].replace("{i}", str(i % text["count"])) for i in range(text["times"])) + + +@pytest.mark.parametrize("recipe", DATA["timed"], ids=lambda r: r["name"]) +def test_linear_in_the_text_on_the_timed_recipes(recipe: dict[str, Any]) -> None: + elements, text = _build(recipe) + find = name_finder(elements, case="exact") + start = time.perf_counter() + found = find(text) + ms = (time.perf_counter() - start) * 1000 + assert len(found) == recipe["count"] + assert ms < DATA["underMs"] * PYTHON_FACTOR, f"{round(ms)} ms" + + +def test_the_timed_recipes_are_the_seven() -> None: + assert len(DATA["timed"]) >= 7 + + +def test_start_and_end_count_code_points_and_the_slice_is_the_name_as_written() -> None: + dragon = chr(0x1F409) + text = f"{dragon} Kira met {dragon}{dragon} KIRA." + find = name_finder([{"id": "k", "name": "Kira"}], case="folded") + assert [(f.start, f.end, text[f.start : f.end]) for f in find(text)] == [(2, 6, "Kira"), (14, 18, "KIRA")] + + +def test_element_is_the_object_passed_in_and_the_default_name_is_its_name() -> None: + kira = {"id": "k", "name": "Kira", "type": "character", "description": "A watchman."} + (found,) = name_finder([kira], case="exact")("Kira.") + assert found == NameFound(0, 4, kira) + assert found.element is kira + assert name_finder(iter([kira]), case="exact")("Kira.")[0].element is kira + + +def test_nothing_given_is_changed_and_the_names_are_read_once() -> None: + elements: list[dict[str, Any]] = [ + {"id": "k", "name": " Kira ", "aliases": ["The Watch"]}, + {"id": "g", "name": "Iron Gate"}, + ] + before = json.dumps(elements, sort_keys=True) + find = name_finder(elements, case="folded", names=lambda e: [e["name"], *e.get("aliases", [])]) + text = "the watch saw Kira at the IRON GATE" + first = find(text) + assert json.dumps(elements, sort_keys=True) == before + assert [f.element["id"] for f in first] == ["k", "k", "g"] + first.clear() + assert len(find(text)) == 3 + elements.append({"id": "x", "name": "saw"}) + assert len(find(text)) == 3 + + +def test_refusals_each_by_name() -> None: + els = [{"id": "k", "name": "Kira"}] + with pytest.raises(TypeError, match="case"): + name_finder(els) # type: ignore[call-arg] + with pytest.raises(TypeError, match="fold"): + name_finder(els, case="exact", fold=True) # type: ignore[call-arg] + for bad in ("Exact", None, True, ""): + with pytest.raises(TypeError, match="case is 'exact' or 'folded'"): + name_finder(els, case=bad) # type: ignore[arg-type] + with pytest.raises(TypeError, match="names is a function"): + name_finder(els, case="exact", names=["Kira"]) # type: ignore[arg-type] + not_lists: list[Any] = [None, "Kira", {"id": "k", "name": "Kira"}, 7] + for not_elements in not_lists: + with pytest.raises(TypeError, match="elements is an iterable"): + name_finder(not_elements, case="exact") + for not_element in ({"name": "Kira"}, {"id": 7, "name": "Kira"}, {"id": "", "name": "Kira"}, None, "Kira"): + with pytest.raises(TypeError, match="every element is a mapping with a string id"): + name_finder([not_element], case="exact") # type: ignore[type-var] + for not_text in (None, 7, ["Kira"], b"Kira"): + with pytest.raises(TypeError, match="text must be a string"): + name_finder(els, case="exact")(not_text) # type: ignore[arg-type]