diff --git a/scripts/sitegen/emulatorpage.py b/scripts/sitegen/emulatorpage.py index 2ed4687d6..e4bbda314 100644 --- a/scripts/sitegen/emulatorpage.py +++ b/scripts/sitegen/emulatorpage.py @@ -54,7 +54,7 @@ from sitegen.render import ( record_emulator_cards, ) from sitegen.sources import source_ref_markdown, link_prose_citations, revision_markdown -from sitegen.startwith import card_runs +from sitegen.parts import even_runs, weighted_runs from sitegen.structured import emulator_file_aliases @@ -364,15 +364,11 @@ def emulator_parts(name: str, files: list, profile: dict | None = None, words = _entry_row_words(files, profile, available or (lambda _f: True)) sizes = [words[i] for i in order] ceiling = max(EMULATOR_PART_WORDS, max(sizes)) - count = max(len(card_runs(order, ceiling, sizes)), -(-len(files) // EMULATOR_CARDS_PER_PART)) + count = max(len(weighted_runs(order, ceiling, sizes)), -(-len(files) // EMULATOR_CARDS_PER_PART)) while True: # The fewest words a part can hold for the parts to be ``count``: # cut at the ceiling, the last part took what the others left. - share = min(-(-sum(sizes) // count), ceiling) - runs = card_runs(order, share, sizes) - while len(runs) > count: - share = min(share + max(1, share // 50), ceiling) - runs = card_runs(order, share, sizes) + runs = even_runs(order, sizes, count, ceiling) if max(len(run) for run in runs) <= EMULATOR_CARDS_PER_PART: return [(f"{name}-files-{index}", run) for index, run in enumerate(runs, 1)] count += 1 diff --git a/scripts/sitegen/parts.py b/scripts/sitegen/parts.py index 45c40c84c..3ba7bcf2b 100644 --- a/scripts/sitegen/parts.py +++ b/scripts/sitegen/parts.py @@ -3,8 +3,9 @@ from __future__ import annotations import json -from collections.abc import Callable +from collections.abc import Callable, Sequence from pathlib import Path +from typing import TypeVar from core.paths import REPO_ROOT from sitegen import starlight as sitestarlight @@ -83,20 +84,58 @@ def character_count(lines: list[str]) -> int: return sum(len(line) + 1 for line in lines) +_T = TypeVar("_T") + + +def weighted_runs(items: Sequence[_T], budget: float, sizes: Sequence[float]) -> list[list[_T]]: + """Items in runs of at most ``budget``, in order, ``sizes`` giving each + item's weight. An item heavier than the budget gets a run of its own.""" + runs: list[list[_T]] = [[]] + size: float = 0 + for item, weight in zip(items, sizes): + if runs[-1] and size + weight > budget: + runs.append([]) + size = 0 + runs[-1].append(item) + size += weight + return runs + + +def even_runs( + items: Sequence[_T], sizes: Sequence[int], count: int, ceiling: int | None = None +) -> list[list[_T]]: + """Items in at most ``count`` runs, each near the mean: cut at a budget, + the last run took what the others left. The share grows from the mean, + never past ``ceiling``, until ``count`` runs hold everything.""" + share = -(-sum(sizes) // count) + if ceiling is not None: + share = min(share, ceiling) + runs = weighted_runs(items, share, sizes) + while len(runs) > count: + share += max(1, share // 50) + if ceiling is not None: + share = min(share, ceiling) + runs = weighted_runs(items, share, sizes) + return runs + + def blocks_in_runs(blocks: list[list[str]], budget: int, weigh: Callable[[list[str]], float] = character_count) -> list[list[str]]: """Blocks (table rows, folded lists) in runs of at most ``budget``, by default in characters, a block never cut.""" - runs: list[list[str]] = [[]] - size: float = 0 - for block in blocks: - weight = weigh(block) - if runs[-1] and size + weight > budget: - runs.append([]) - size = 0 - runs[-1].extend(block) - size += weight - return runs + runs = weighted_runs(blocks, budget, [weigh(block) for block in blocks]) + return [[line for block in run for line in block] for run in runs] + + +def part_stems(stem: str, count: int) -> list[str]: + """The page names of a list cut in ``count`` parts: the first keeps the stem.""" + return [stem + (f"-{n}" if n > 1 else "") for n in range(1, count + 1)] + + +def part_links(stems: list[str], here: str | None = None) -> str: + """Every part linked, ``here`` named without a link.""" + return ", ".join(f"[part {i}]({other}.md)" if other != here else f"part {i}" + for i, other in enumerate(stems, 1)) def parent_front_matter(parent: tuple[str, str] | None) -> list[str]: @@ -118,7 +157,7 @@ def list_pages( went, as the page it left says it. ``parent`` (label, site path) is the page the parts belong to, for the breadcrumb.""" runs = blocks_in_runs(blocks, budget) - stems = [stem + (f"-{n}" if n > 1 else "") for n in range(1, len(runs) + 1)] + stems = part_stems(stem, len(runs)) for n, (here, run) in enumerate(zip(stems, runs), 1): part = f" (part {n} of {len(runs)})" if len(runs) > 1 else "" # The page description is the opening of the intro: parts sharing @@ -127,11 +166,9 @@ def list_pages( moved[here] = "\n".join([ "---", "level: reference", *parent_front_matter(parent), "---", "", f"# {title}{part}", "", opening, "", - *([", ".join(f"[part {i}]({other}.md)" if other != here else f"part {i}" - for i, other in enumerate(stems, 1)), ""] if len(runs) > 1 else []), + *([part_links(stems, here), ""] if len(runs) > 1 else []), *head, *run, "", date_line(), ]) + "\n" if len(stems) == 1: return f"[a page of their own]({stems[0]}.md)" - return "pages of their own: " + ", ".join( - f"[part {i}]({other}.md)" for i, other in enumerate(stems, 1)) + return "pages of their own: " + part_links(stems) diff --git a/scripts/sitegen/platformfiles.py b/scripts/sitegen/platformfiles.py index 6bf1e312a..d91d94851 100644 --- a/scripts/sitegen/platformfiles.py +++ b/scripts/sitegen/platformfiles.py @@ -28,6 +28,8 @@ from sitegen.parts import ( blocks_in_runs, character_count, parent_front_matter, + part_links, + part_stems, ) from sitegen.render import ( code_span, @@ -427,8 +429,7 @@ def render_platform_systems( runs = [sec["head"] + _platform_file_list(run, sec["has_path"], anchor) for run in blocks_in_runs([[row] for row in sec["rows"]], PLATFORM_PART_BUDGET, _page_share)] - stems = [f"{key}-{anchor}" + (f"-{n}" if n > 1 else "") - for n in range(1, len(runs) + 1)] + stems = part_stems(f"{key}-{anchor}", len(runs)) for n, (stem, run) in enumerate(zip(stems, runs), 1): part = f" (part {n} of {len(runs)})" if len(runs) > 1 else "" # A console query landed here with no way to the console's @@ -440,9 +441,7 @@ def render_platform_systems( f"Part of the [{display} page]({key}.md#{anchor}), whose other systems " f"are listed there. Each file below is as {display} declares it, with " "its status in the pack.", - *([""] + [", ".join( - f"[part {i}]({other}.md)" if other != stem else f"part {i}" - for i, other in enumerate(stems, 1))] if len(runs) > 1 else []), + *(["", part_links(stems, stem)] if len(runs) > 1 else []), "", "## Files", "", *markup.details("note", ROLE_LEGEND_TITLE, [ROLE_LEGEND]), *search_excluded(run), "", date_line(), @@ -452,8 +451,7 @@ def render_platform_systems( tag = "OK" if ok_count == total else count_text(total - ok_count, "issue") count = f"{count_text(total, 'file')} ({tag})" lines.extend([ - f"[{count}]({stems[0]}.md)" if len(stems) == 1 else f"{count}: " + ", ".join( - f"[part {i}]({stem}.md)" for i, stem in enumerate(stems, 1)), + f"[{count}]({stems[0]}.md)" if len(stems) == 1 else f"{count}: " + part_links(stems), "", ]) continue diff --git a/scripts/sitegen/startwith.py b/scripts/sitegen/startwith.py index 49b966e3a..fd426a8bd 100644 --- a/scripts/sitegen/startwith.py +++ b/scripts/sitegen/startwith.py @@ -13,7 +13,6 @@ from sitegen.cards import ROMSET_FAQ, emulator_display, romset_releases from sitegen.consolecards import ( Card, START_WITH_NAMES, - Item, NO_PRIORITY, add_name, card_rank, @@ -693,21 +692,6 @@ def cards_markdown(cards: list[Card]) -> list[str]: return lines -def card_runs(cards: list[Item], budget: int, sizes: list[int]) -> list[list[Item]]: - """Cards in runs of at most ``budget`` bytes, in order, ``sizes`` - giving each card's weight.""" - parts: list[list[Item]] = [[]] - size = 0 - for index, card in enumerate(cards): - weight = sizes[index] - if parts[-1] and size + weight > budget: - parts.append([]) - size = 0 - parts[-1].append(card) - size += weight - return parts - - def console_heading(manufacturer: str, console: str, label: str = "") -> str: """A console's heading, its name alone. An icon on 79 of 544 headings read as missing art on the rest, set the text at two positions on one diff --git a/scripts/sitegen/systempages.py b/scripts/sitegen/systempages.py index 7802a5f80..75324323d 100644 --- a/scripts/sitegen/systempages.py +++ b/scripts/sitegen/systempages.py @@ -31,13 +31,12 @@ from sitegen.decorate import DEMOTED_WEIGHT, SEARCH_WEIGHT from sitegen.fields import search_excluded from sitegen.home import next_block from sitegen.install import console_install_block, platform_display -from sitegen.parts import parent_front_matter +from sitegen.parts import character_count, even_runs, parent_front_matter, part_stems, weighted_runs from sitegen.render import count_text, slugify_anchor, console_href, record_console_pages from sitegen.startwith import ( OTHER_ARCADE, cards_markdown, console_heading, - card_runs, romset_note, section_label, start_order, @@ -289,10 +288,6 @@ class _ConsoleParts: lead: set[str] -def _card_weight(card: list[str]) -> int: - return sum(len(line) + 1 for line in card) - - @dataclass class _MakerPages: """What a manufacturer's pages are built from, and how each part reads.""" @@ -401,19 +396,14 @@ class _MakerPages: # holds are its own. cards = self.cards_of(console, set(), by_name) with markup.using("mkdocs"): - sizes = [_card_weight(card) for _variant, card, _sha1 in self.cards_of( + sizes = [character_count(card) for _variant, card, _sha1 in self.cards_of( console, set(), by_name)] - parts = card_runs(cards, self.budget, sizes) + parts = weighted_runs(cards, self.budget, sizes) if len(parts) < 2: return parts # Even parts: cut at budget, the PlayStation 2 was 137 cards # and 4. The same number of parts, each near the mean. - share = -(-sum(sizes) // len(parts)) - even = card_runs(cards, share, sizes) - while len(even) > len(parts): - share += max(1, share // 50) - even = card_runs(cards, share, sizes) - return even + return even_runs(cards, sizes, len(parts)) def moved(self, weights: dict[str, int], rendered: dict[str, float]) -> set[str]: """Every board has a page of its own. Then the heaviest sections move @@ -485,7 +475,7 @@ class _MakerPages: board = self.boards.get(console) base = (f"arcade-{board_slug(board)}" if board else f"{self.slug}-{slugify_anchor(console) or 'files'}") - stems = [base if index == 0 else f"{base}-{index + 1}" for index in range(len(parts))] + stems = part_stems(base, len(parts)) clash = set(stems) & set(pages) if clash: raise RuntimeError(f"two system sections take one page: {sorted(clash)}") @@ -548,7 +538,7 @@ def system_pages( measured = maker.all_sections() measured_text = maker.whole_page(measured) weights = { - console: sum(_card_weight(card) for _variant, card, _sha1 in cards) + console: sum(character_count(card) for _variant, card, _sha1 in cards) for console, cards in measured.items() } # An install box is a few lines of Markdown and about nine times that