Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ The package version runs on its own semver; the schema it is generated from is `

## Unreleased

- **Each import door tells the names it made.** A name an element gets that is not one string of the export taken as written is now declared and counted, by kind. A joined name is the export's words with the door's between them (a LegendKeeper map document becomes a Map named `<resource>: <document>`); the door's own is a name for a thing the export never names (a frame's corner Marker, `<frame>: corner 1`; an arrow with no label, `Board link`). Each door lists its kinds in `MADE_NAMES`, a tuple of `MadeName` (`kind`, `type`, `pattern`, `source` `joined` or `ours`, and `regex`, read by `MadeName.fits(type, name)`); Notion's is empty. Each `ImportReport` gains `made_names` (kind to count) and prints one line a kind with its count and pattern. Nothing is added to an element. On the doors' real test exports: LegendKeeper's JSON export 80 made names of 280 (17 Narratives and 6 Maps `<resource>: <document>`, 56 frame corners, one nameless pin), its .lk export 78, each Kanka export 2 (`<entity>: hidden details`), World Anvil, Notion and Campfire none.

## 0.139.3 (2026-11-21)

- **The schema pin moves to `v0.34.1-dist.144`** (canonical 00.34.01 unchanged, no schema file moved, `_schema.py` changes only its provenance lines). The map-space page gains rule 15, bringing a point down to a child Map, with the reading `down_of` and a fourth fixture list, `down_cases` (28 cases). This package does not read it yet; no other case moves.
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,8 @@ print(report.render())

Each element heading becomes an element, its description the description. The file names no module, so the type is read from the template's own panel words (a Basic Information panel with Place of Residence is a Character, Location Details a Location; Species, Cultures, Items, Languages, Religions, Philosophies, Systems, Magic and Maps are mapped too, by one table, `MODULE_TYPES`); anything else becomes a Narrative (supertype `Article`). The report names, for each element, the panel words its type was read from. Every filled panel value is kept as `x_campfire_<panel>_<label>` (`x_campfire_basic_information_full_name`), a text panel as `x_campfire_<panel>`; an em dash is empty and not written. A document carries no ids, no links and no hidden marks, and the report says so each time: ids come from each element's type and name, so a later export gives the same elements only while the names hold. The file names no project either: `--project NAME` names the world and keys every id on it, so two projects exported under Campfire's default title, "Campfire Export", stay apart; without it the world takes the document's title. The one link made is a Character's Place of Residence that names a Location in the same export. No AI. Read on one real export (a Character and a Location); the other modules have not been seen in a file yet.

Every door names an element from the export's own text where it can. Where it cannot, the name is made, and the report says so in one line a kind, with the count and the pattern; nothing is added to the element. A made name is joined (the export's words with the door's between them: a LegendKeeper map document becomes a Map named `<resource>: <document>`) or the door's own, for a thing the export never names (a frame's corner Marker, `<frame>: corner 1`; a Kanka entity's private details, `<entity>: hidden details`). Each door lists what it makes in `MADE_NAMES` (`onlyworlds.legendkeeper.MADE_NAMES`, ...), one `MadeName` a kind, and `MadeName.fits(type, name)` tells whether a name has a kind's shape; the report's `made_names` holds the counts. The Notion door makes none.

## Export to OKF

A world folder can be exported as a valid [Open Knowledge Format](https://github.com/open-knowledge-format/open-knowledge-format) (OKF) 0.2 bundle, as the spec stands at one pinned commit (`onlyworlds.okf.OKF_COMMIT`): one markdown file per element, with its fields in the frontmatter, its text under headings and its links (in-prose `ow://` references included) as markdown links, plus an index per type. This needs PyYAML, which the rest of the package does not:
Expand Down
82 changes: 82 additions & 0 deletions src/onlyworlds/_made.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
"""The names an import door makes: an element name that is not one string of the export taken as written.

There are two kinds, and they are not the same. A ``joined`` name is the export's own words with ours between
them: a LegendKeeper map document of a page becomes a Map named ``<resource>: <document>``. An ``ours`` name is
one for a thing the export never names at all: a frame's corner Marker (``<frame>: corner 1``), a part of a
region (``<zone>: part 2``), a frame with no name (``Frame``), an arrow with no label (``Board link``). Only the
second is wholly the door's.

Each door lists the names it makes in its ``MADE_NAMES``, a tuple of ``MadeName`` (empty for a door that makes
none), and its report counts the elements of each kind: one line a kind, beside the elements and never in them
(no field on an element says its name was made). A reader such as a gate tells a made name with
``MadeName.fits``: the element's type, and its whole name matched by the record's ``regex``. A name that is the
export's text and fits a pattern too (a frame its author named ``Frame``) cannot be told apart by its name; the
door counts what it made, and a reader of names alone counts both.
"""

from __future__ import annotations

import re
from collections.abc import Iterable, Mapping, Sequence
from dataclasses import dataclass
from typing import Literal

__all__ = ["ANY_TYPE", "MadeName"]

#: A ``MadeName.type`` for a name the door gives an element of whatever type it became (a page with no name).
ANY_TYPE = "*"


@dataclass(frozen=True)
class MadeName:
"""One kind of name a door makes. ``kind`` is its stable id (lowercase, hyphens: ``map-document``). ``type``
is the element type it names, written as an element's ``type`` is (``map``), or ``ANY_TYPE``. ``pattern`` is
its human form (``<resource>: <document>``): angle brackets around the export's words, the rest the door's.
``source`` is ``joined`` (the export's words, the door's joint) or ``ours`` (a name for a thing the export
names nowhere). ``regex`` matches a whole name of the kind (Python ``re.fullmatch``); the export's words in
it are ``.+``, so it pins the made part only."""

kind: str
type: str
pattern: str
source: Literal["joined", "ours"]
regex: str

def fits(self, etype: str, name: str) -> bool:
"""True when an element of type ``etype`` named ``name`` has a name of this kind's shape."""
return self.type in (ANY_TYPE, etype) and re.fullmatch(self.regex, name) is not None


def _counts(made: Sequence[MadeName], kinds: Mapping[str, str], ids: Iterable[str]) -> dict[str, int]:
"""The kinds counted over the elements written: ``kinds`` maps an element id to the kind its door recorded
when it named it, ``ids`` are the ids written. In the declared order, a kind with none left out. A recorded
kind the door does not declare is a ValueError: the declaration and the door disagree."""
declared = {m.kind for m in made}
tally: dict[str, int] = {}
for eid in ids:
kind = kinds.get(eid)
if kind is None:
continue
if kind not in declared:
raise ValueError(f"a made name of kind {kind!r}, which MADE_NAMES does not declare")
tally[kind] = tally.get(kind, 0) + 1
return {m.kind: tally[m.kind] for m in made if m.kind in tally}


_SAID = {
"joined": "joined: the export's words, ours between them",
"ours": "ours: the export gives it no name",
}


def _lines(made: Sequence[MadeName], counts: Mapping[str, int]) -> list[str]:
"""The report's lines for the names made: a heading with the total, then one line a kind with a count."""
if not any(counts.values()):
return []
by_kind = {m.kind: m for m in made}
lines = [f"Names made by the import, not taken whole from the export ({sum(counts.values())}), one line a kind:"]
for kind, n in counts.items():
m = by_kind[kind]
what = "any type" if m.type == ANY_TYPE else m.type
lines.append(f" - {m.kind}, {what} {m.pattern!r}: {n} ({_SAID[m.source]})")
return lines
19 changes: 18 additions & 1 deletion src/onlyworlds/campfire.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,13 +92,15 @@
from pathlib import Path
from typing import Any

from ._made import ANY_TYPE, MadeName, _counts, _lines
from ._version import __version__
from .folder import FORMAT_VERSION, ONE_SOURCE_ONE_WORLD, write_folder
from .kanka import _blocks, _Node, _Tree

__all__ = [
"CAMPFIRE_NAMESPACE",
"EXT_PREFIX",
"MADE_NAMES",
"MODULE_TYPES",
"PRODUCER_INPUT",
"SEEN_MODULES",
Expand All @@ -107,6 +109,7 @@
"ElementPlan",
"Folded",
"ImportReport",
"MadeName",
"ModuleEvidence",
"import_campfire",
"main",
Expand All @@ -126,6 +129,12 @@
#: came from (the World Anvil ruling, 2026-10-23, and the same for Campfire).
UNTYPED_SUPERTYPE = "Article"

#: The names this door makes (``MadeName``: one for a thing Campfire leaves unnamed), one record a kind, each
#: kind counted in the report. An element with no heading is named by its place among the file's elements.
MADE_NAMES: tuple[MadeName, ...] = (
MadeName("untitled-element", ANY_TYPE, "Untitled (<n>)", "ours", r"Untitled \([0-9]+\)"),
)

#: The most an export may hold, in bytes: a file past it is refused, not read.
MAX_EXPORT_BYTES = 256 * 1024 * 1024

Expand Down Expand Up @@ -329,6 +338,8 @@ class ImportReport:
#: (element, the key it got): a second element of one type and name
renamed: list[tuple[str, str]] = field(default_factory=list)
folded: list[Folded] = field(default_factory=list)
#: names made here, not taken whole from the export: a ``MADE_NAMES`` kind -> its elements, in declared order
made_names: dict[str, int] = field(default_factory=dict)
notes: list[str] = field(default_factory=list)
#: where the folder was written; None for a plan
out: Path | None = None
Expand Down Expand Up @@ -413,6 +424,7 @@ def render(self) -> str:
if self.renamed:
lines.append(f"A second element of one type and name ({len(self.renamed)}), keyed apart:")
lines += [f" - {e!r}: id from {k!r}" for e, k in self.renamed]
lines += _lines(MADE_NAMES, self.made_names)
if self.notes:
lines.append(f"Notes ({len(self.notes)}):")
lines += [f" - {n}" for n in self.notes]
Expand Down Expand Up @@ -446,6 +458,8 @@ class _Item:
etype: str = "narrative"
eid: str = ""
consumed: set[int] = field(default_factory=set)
#: the MADE_NAMES kind of its name, when the door made it; never written on the element
made: str = ""


class _Importer:
Expand Down Expand Up @@ -490,6 +504,7 @@ def _element(self, node: _Node) -> _Item:
name = _plain(title) if title is not None else ""
if title is not None:
consumed.add(id(title))
title_text = name
if not name:
name = f"Untitled ({len(self.items) + 1})"
self.report.notes.append(f"an element with no heading; named {name!r}")
Expand All @@ -498,7 +513,7 @@ def _element(self, node: _Node) -> _Item:
if desc is not None:
consumed.add(id(desc))
description = _markdown(desc)
item = _Item(node, name, description, [], consumed=consumed)
item = _Item(node, name, description, [], consumed=consumed, made="" if title_text else "untitled-element")
for page in (n for n in _walk(node) if "page-section" in _classes(n)):
self.pages += 1
ptitle = _find(page, _has("page-title"))
Expand Down Expand Up @@ -642,6 +657,8 @@ def bodies(self) -> dict[str, list[dict[str, Any]]]:
self._guard(item, body)
out.setdefault(item.etype, []).append(body)
self.report.counts = {t: len(b) for t, b in sorted(out.items())}
named = {item.eid: item.made for item in self.items if item.made}
self.report.made_names = _counts(MADE_NAMES, named, (b["id"] for bs in out.values() for b in bs))
self._page_guard()
if self.pages:
self.report.notes.append(f"{self.pages} page(s) of panels; a page's name is layout, not kept")
Expand Down
25 changes: 25 additions & 0 deletions src/onlyworlds/kanka.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@
from pathlib import Path
from typing import Any

from ._made import ANY_TYPE, MadeName, _counts, _lines
from ._schema import FIELD_KINDS, LINK_TARGETS
from ._version import __version__
from .folder import FORMAT_VERSION, ONE_SOURCE_ONE_WORLD, write_folder
Expand All @@ -191,13 +192,15 @@
__all__ = [
"EXT_PREFIX",
"KANKA_NAMESPACE",
"MADE_NAMES",
"MODULE_TYPES",
"PRODUCER_INPUT",
"PROVEN_MODULES",
"STARTER_WINDOW",
"Folded",
"Hidden",
"ImportReport",
"MadeName",
"ModulePlan",
"Picture",
"Unplaced",
Expand Down Expand Up @@ -256,6 +259,15 @@
"map": "parent_map",
}

#: The names this door makes (``MadeName``: one for a thing Kanka never names, or leaves unnamed), one
#: record a kind, each kind counted in the report.
MADE_NAMES: tuple[MadeName, ...] = (
MadeName("hidden-details", "narrative", "<entity>: hidden details", "ours", r".+: hidden details"),
MadeName("untitled-post", "narrative", "Post", "ours", r"Post"),
MadeName("untitled-relationship", "relation", "Relationship", "ours", r"Relationship"),
MadeName("untitled-entity", ANY_TYPE, "Untitled (<entity id>)", "ours", r"Untitled \(.+\)"),
)

#: Kanka's image store: per upload ``<uuid>.json`` and the image ``<uuid>.<ext>``; not a module.
_GALLERY = "gallery"

Expand Down Expand Up @@ -743,6 +755,8 @@ class ImportReport:
pictures: list[Picture] = field(default_factory=list)
#: carriers of a tag its Narrative does not link (a hidden element under a visible tag, a type with no field)
untagged: list[Untagged] = field(default_factory=list)
#: names made here, not taken whole from the export: a ``MADE_NAMES`` kind -> its elements, in declared order
made_names: dict[str, int] = field(default_factory=dict)
notes: list[str] = field(default_factory=list)
#: where the folder was written; None for a plan
out: Path | None = None
Expand Down Expand Up @@ -842,6 +856,7 @@ def render(self) -> str:
if self.unresolved:
lines.append(f"Links and mentions whose target is not in the folder ({len(self.unresolved)}):")
lines += [f" - {u.element!r}, {u.where}: {u.target}: {u.why}" for u in self.unresolved]
lines += _lines(MADE_NAMES, self.made_names)
if self.notes:
lines.append(f"Notes ({len(self.notes)}):")
lines += [f" - {n}" for n in self.notes]
Expand Down Expand Up @@ -891,6 +906,8 @@ def __init__(self, files: Mapping[str, Callable[[], bytes]], source: Path, notes
self.relations: list[dict[str, Any]] = []
#: hidden Narratives: one per private post, one per entity's hidden details
self.narratives: list[dict[str, Any]] = []
#: element id -> the MADE_NAMES kind of the name it was given, for the report's count
self._named: dict[str, str] = {}
#: gallery/: upload uuid -> (its JSON's path without ``.json``, the JSON); the uuids an entity names
self.uploads: dict[str, tuple[str, dict[str, Any]]] = {}
self.named_uploads: set[str] = set()
Expand Down Expand Up @@ -957,6 +974,8 @@ def collect(self) -> None:
item = _Item(
folder, rel, row, ent, entity_id, etype, self._id(str(entity_id)), name, folder in MODULE_TYPES
)
if not str(ent.get("name") or row.get("name") or "").strip():
self._named[item.eid] = "untitled-entity"
if _on(ent.get("is_private")) or _on(row.get("is_private")):
item.hidden = True
self.report.hidden.entities += 1
Expand Down Expand Up @@ -1224,6 +1243,8 @@ def _post_narrative(self, item: _Item, p: dict[str, Any], name: str) -> None:
if _on(p.get(k)):
ext[f"{EXT_PREFIX}{k}"] = p[k]
self._hidden_narrative(f"post:{p.get('id')}", name, text, item, ext, mentions)
if not str(p.get("name") or "").strip():
self._named[self._id(f"post:{p.get('id')}")] = "untitled-post"
self.report.hidden.posts += 1

def _details(self, item: _Item) -> None:
Expand All @@ -1235,6 +1256,7 @@ def _details(self, item: _Item) -> None:
self._hidden_narrative(
f"hidden:{item.entity_id}", f"{item.name}: hidden details", story, item, ext, item.secret_mentions
)
self._named[self._id(f"hidden:{item.entity_id}")] = "hidden-details"
self.report.hidden.details += 1

def _character(self, item: _Item) -> None:
Expand Down Expand Up @@ -1546,6 +1568,8 @@ def _relation(self, rid: int, owner: _Item, rel: dict[str, Any], mirror: dict[st
if end.eid not in links:
links.append(end.eid)
body: dict[str, Any] = {"type": "relation", "id": self._id("relation", str(rid)), "name": name}
if not text:
self._named[body["id"]] = "untitled-relationship"
sides = (rel, mirror) if mirror is not None else (rel,)
if owner.hidden or target.hidden or any(not _public(s.get("visibility_id")) for s in sides):
body["hidden"] = True
Expand Down Expand Up @@ -1590,6 +1614,7 @@ def bodies(self) -> dict[str, list[dict[str, Any]]]:
for body in self.narratives + self.relations:
out.setdefault(body["type"], []).append(body)
self.report.counts = {t: len(b) for t, b in sorted(out.items())}
self.report.made_names = _counts(MADE_NAMES, self._named, (b["id"] for bs in out.values() for b in bs))
if self.items:
self.report.notes.append(f"not kept: {_NOT_KEPT}")
return out
Expand Down
Loading