Spaces:
Running on Zero
Running on Zero
File size: 11,336 Bytes
e2bfc0b 9a659d2 e2bfc0b 9a659d2 e2bfc0b 9a659d2 e2bfc0b 9a659d2 e2bfc0b 9a659d2 e2bfc0b 9a659d2 e2bfc0b 9a659d2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 | """Deterministic Mind Map drawing for Memory Studio.
Turns a short indented outline into an SVG in Buzan's style: a central topic,
thick curved main branches that taper outward, one colour per branch, and one
key word written on each line. No model or UI dependency; nothing is saved.
"""
from __future__ import annotations
import html
import math
import re
MAX_MAIN_BRANCHES = 8
MAX_SUB_BRANCHES = 6
MAX_LABEL_LENGTH = 40
# Colours chosen to stay readable on the map's cream background.
BRANCH_COLORS = (
"#d62839",
"#e07a1f",
"#1f8a70",
"#2f6fb0",
"#7b3fb5",
"#b8860b",
"#c2185b",
"#3d8b37",
)
# Plain names for the colours above, so a recall prompt can say "the red one".
BRANCH_COLOR_NAMES = (
"red", "orange", "teal", "blue", "purple", "gold", "pink", "green",
)
# What a recall view hides: nothing, the details, or every branch label.
HIDE_NONE = ""
HIDE_DETAILS = "details"
HIDE_ALL = "all"
HIDDEN_LABEL = "?"
BACKGROUND = "#fffdf7"
CENTER_FILL = "#312e81"
_MAIN_LENGTH = 190.0
_SUB_LENGTH = 125.0
_MAIN_FONT = 19
_SUB_FONT = 15
def _clean_label(line: str) -> str:
text = re.sub(r"^\s*(?:\d+[.)]\s+|[-*•+]\s+)", "", line)
return " ".join(text.split())
def parse_outline(text: str) -> list[tuple[str, list[str]]]:
"""Parse an outline: unindented lines are main branches, indented lines
are sub-branches of the main branch above them. Raises ValueError with an
actionable message instead of dropping anything."""
branches: list[tuple[str, list[str]]] = []
for number, raw in enumerate((text or "").splitlines(), 1):
if not raw.strip():
continue
expanded = raw.replace("\t", " ")
indent = len(expanded) - len(expanded.lstrip(" "))
label = _clean_label(expanded)
if not label:
continue
if len(label) > MAX_LABEL_LENGTH:
raise ValueError(
f"Line {number} is {len(label)} characters. Mind Map branches "
f"hold a key word or two; keep each under {MAX_LABEL_LENGTH}."
)
if indent == 0:
branches.append((label, []))
elif not branches:
raise ValueError(
"The first line must be a main branch with no indentation."
)
else:
branches[-1][1].append(label)
if not branches:
raise ValueError(
"Add at least one main branch: one key word per line, with "
"sub-branches indented underneath."
)
if len(branches) > MAX_MAIN_BRANCHES:
raise ValueError(
f"Use up to {MAX_MAIN_BRANCHES} main branches; this outline has "
f"{len(branches)}. Group related ideas, or split it into two maps."
)
crowded = [label for label, subs in branches if len(subs) > MAX_SUB_BRANCHES]
if crowded:
raise ValueError(
f"Keep up to {MAX_SUB_BRANCHES} sub-branches per main branch. Too many "
"under: " + ", ".join(crowded) + ". Add another main branch instead."
)
return branches
def key_word_tips(topic: str, branches: list[tuple[str, list[str]]]) -> list[str]:
"""Gentle reminders of Buzan's key-word rule. Never blocks drawing."""
wordy = [
label
for label in [main for main, _subs in branches]
+ [sub for _main, subs in branches for sub in subs]
if len(label.split()) > 2
]
tips = []
if wordy:
tips.append(
"One key word per line recalls best. Consider shortening: "
+ ", ".join(f"**{label}**" for label in wordy[:6])
+ ("…" if len(wordy) > 6 else "")
+ "."
)
if len(topic.split()) > 4:
tips.append("Make the centre a short topic you can turn into one picture.")
if all(not subs for _main, subs in branches):
tips.append(
"Add a few indented sub-branches under each main idea; the details "
"hang off the key words."
)
return tips
def _text_width(text: str, font_size: int) -> float:
return max(1, len(text)) * font_size * 0.58
def _tapered_curve(
start: tuple[float, float],
end: tuple[float, float],
bend: float,
width_start: float,
width_end: float,
steps: int = 24,
) -> str:
"""A filled, gently curved branch that is thicker at its start."""
(x0, y0), (x2, y2) = start, end
mx, my = (x0 + x2) / 2, (y0 + y2) / 2
dx, dy = x2 - x0, y2 - y0
length = math.hypot(dx, dy) or 1.0
nx, ny = -dy / length, dx / length
x1, y1 = mx + nx * bend, my + ny * bend
left, right = [], []
for step in range(steps + 1):
t = step / steps
x = (1 - t) ** 2 * x0 + 2 * (1 - t) * t * x1 + t**2 * x2
y = (1 - t) ** 2 * y0 + 2 * (1 - t) * t * y1 + t**2 * y2
tx = 2 * (1 - t) * (x1 - x0) + 2 * t * (x2 - x1)
ty = 2 * (1 - t) * (y1 - y0) + 2 * t * (y2 - y1)
tl = math.hypot(tx, ty) or 1.0
px, py = -ty / tl, tx / tl
half = (width_start + (width_end - width_start) * t) / 2
left.append((x + px * half, y + py * half))
right.append((x - px * half, y - py * half))
points = left + right[::-1]
path = "M " + " L ".join(f"{x:.1f} {y:.1f}" for x, y in points) + " Z"
return path
def render_svg(
topic: str, branches: list[tuple[str, list[str]]], hide: str = HIDE_NONE
) -> str:
"""Draw the map. The viewBox is fitted to the drawing, so it scales cleanly.
``hide`` draws a recall view: each hidden label becomes "?" on a line of
the same length, so colours, positions, and shapes stay as cues while the
words themselves are left out of the SVG entirely.
"""
elements: list[str] = []
bounds = [0.0, 0.0, 0.0, 0.0] # min_x, min_y, max_x, max_y
def grow(x: float, y: float) -> None:
bounds[0], bounds[1] = min(bounds[0], x), min(bounds[1], y)
bounds[2], bounds[3] = max(bounds[2], x), max(bounds[3], y)
def word_on_line(
x: float,
y: float,
text: str,
size: int,
color: str,
rightward: bool,
bold: bool,
hidden: bool = False,
) -> None:
width = _text_width(text, size)
if hidden:
text = HIDDEN_LABEL
x_end = x + width + 8 if rightward else x - width - 8
elements.append(
f'<path d="M {x:.1f} {y:.1f} L {x_end:.1f} {y:.1f}" stroke="{color}" '
f'stroke-width="{3 if bold else 2}" stroke-linecap="round" fill="none"/>'
)
anchor = "start" if rightward else "end"
text_x = x + 4 if rightward else x - 4
weight = "700" if bold else "500"
elements.append(
f'<text x="{text_x:.1f}" y="{y - 6:.1f}" font-size="{size}" '
f'font-weight="{weight}" fill="{color}" text-anchor="{anchor}">'
f"{html.escape(text)}</text>"
)
grow(x_end, y - size - 8)
grow(x_end, y + 4)
count = len(branches)
center_rx = max(72.0, _text_width(topic, 22) / 2 + 26)
center_ry = 42.0
for index, (label, subs) in enumerate(branches):
color = BRANCH_COLORS[index % len(BRANCH_COLORS)]
angle = math.radians((index + 0.5) * 360 / count - 90)
if count == 1:
angle = 0.0
cos, sin = math.cos(angle), math.sin(angle)
start = (cos * center_rx * 0.8, sin * center_ry * 0.8)
end = (start[0] + cos * _MAIN_LENGTH, start[1] + sin * _MAIN_LENGTH)
bend = 26 if index % 2 else -26
elements.append(
f'<path d="{_tapered_curve(start, end, bend, 16, 4)}" fill="{color}"/>'
)
rightward = cos >= -1e-6
word_on_line(
end[0], end[1], label, _MAIN_FONT, color, rightward, True,
hide == HIDE_ALL,
)
main_width = _text_width(label, _MAIN_FONT) + 8
hub = (end[0] + (main_width if rightward else -main_width), end[1])
spread = min(70.0, 22.0 * max(1, len(subs) - 1))
base = 0.0 if rightward else math.pi
for sub_index, sub in enumerate(subs):
if len(subs) == 1:
offset = 0.0
else:
offset = -spread / 2 + spread * sub_index / (len(subs) - 1)
sub_angle = base + math.radians(offset if rightward else -offset)
sub_end = (
hub[0] + math.cos(sub_angle) * _SUB_LENGTH,
hub[1] + math.sin(sub_angle) * _SUB_LENGTH,
)
elements.append(
f'<path d="{_tapered_curve(hub, sub_end, 10, 5, 2)}" '
f'fill="{color}" opacity="0.85"/>'
)
word_on_line(
sub_end[0], sub_end[1], sub, _SUB_FONT, color, rightward, False,
hide in (HIDE_ALL, HIDE_DETAILS),
)
grow(*end)
elements.append(
f'<ellipse cx="0" cy="0" rx="{center_rx:.1f}" ry="{center_ry:.1f}" '
f'fill="{CENTER_FILL}"/>'
)
elements.append(
f'<text x="0" y="7" font-size="22" font-weight="700" fill="#ffffff" '
f'text-anchor="middle">{html.escape(topic)}</text>'
)
grow(-center_rx, -center_ry)
grow(center_rx, center_ry)
pad = 28
min_x, min_y = bounds[0] - pad, bounds[1] - pad
width, height = bounds[2] - bounds[0] + 2 * pad, bounds[3] - bounds[1] + 2 * pad
title = html.escape(f"Mind Map: {topic}")
return (
f'<svg xmlns="http://www.w3.org/2000/svg" role="img" '
f'aria-label="{title}" viewBox="{min_x:.0f} {min_y:.0f} {width:.0f} '
f'{height:.0f}" style="width:100%;height:auto;max-height:640px" '
f'font-family="system-ui, -apple-system, Segoe UI, Roboto, sans-serif">'
f"<title>{title}</title>"
f'<rect x="{min_x:.0f}" y="{min_y:.0f}" width="{width:.0f}" '
f'height="{height:.0f}" rx="18" fill="{BACKGROUND}"/>'
+ "".join(elements)
+ "</svg>"
)
def outline_markdown(topic: str, branches: list[tuple[str, list[str]]]) -> str:
lines = [f"## Mind Map: {topic}", ""]
for label, subs in branches:
lines.append(f"- **{label}**")
lines.extend(f" - {sub}" for sub in subs)
return "\n".join(lines)
def branch_color_name(index: int) -> str:
return BRANCH_COLOR_NAMES[index % len(BRANCH_COLOR_NAMES)]
def practice_cards(
topic: str, branches: list[tuple[str, list[str]]]
) -> list[dict[str, str]]:
"""Recall cards in the map's own order: the main branches, then each
branch's details. Colours are named because they are part of the map."""
count = len(branches)
cards = [
{
"prompt": f"**{topic}** has {count} main branch(es). Name them, "
"clockwise from the top.",
"answer": "\n".join(
f"{index}. **{label}** ({branch_color_name(index - 1)})"
for index, (label, _subs) in enumerate(branches, 1)
),
}
]
for index, (label, subs) in enumerate(branches):
if not subs:
continue
cards.append(
{
"prompt": f"On the **{topic}** map, the {branch_color_name(index)} "
f"branch **{label}** has {len(subs)} detail(s). Name them.",
"answer": ", ".join(f"**{sub}**" for sub in subs),
}
)
return cards
|