recettes 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
recettes/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Static recipe website generator."""
recettes/cli.py ADDED
@@ -0,0 +1,395 @@
1
+ from __future__ import annotations
2
+
3
+ import html
4
+ import json
5
+ import re
6
+ import shutil
7
+ from fractions import Fraction
8
+ from pathlib import Path
9
+ from typing import Annotated
10
+ from urllib.parse import quote, unquote, urlsplit, urlunsplit
11
+
12
+ import frontmatter
13
+ import typer
14
+ from markdown_it import MarkdownIt
15
+
16
+ app = typer.Typer(no_args_is_help=True, help="Build a static recipe website from Markdown.")
17
+ INGREDIENT_RE = re.compile(r"\{\{\s*(.*?)\s*\}\}")
18
+ QUANTITY_RE = re.compile(
19
+ r"^(?P<amount>\d+(?:[.,]\d+)?(?:\s*/\s*\d+(?:[.,]\d+)?)?)"
20
+ r"\s*(?P<unit>c\.?\s*à\.?\s*[sc]\.?|cas|cac|tablespoons?|tbsp|teaspoons?|tsp|cups?|"
21
+ r"ounces?|oz|pounds?|lbs?|kg|mg|g|ml|cl|l)?\s*(?P<name>.*)$",
22
+ re.IGNORECASE,
23
+ )
24
+ TOKEN_RE = re.compile(r"RECIPEINGREDIENTTOKEN(\d+)END")
25
+ IMAGE_RE = re.compile(r"^(?P<stem>.+)-(?P<number>\d+)\.(?P<ext>jpe?g|png|webp|avif)$", re.I)
26
+ MARKDOWN = MarkdownIt("default", {"html": False, "typographer": True})
27
+
28
+
29
+ @app.callback()
30
+ def main() -> None:
31
+ """Build and maintain a static recipe website."""
32
+
33
+
34
+ def fail(message: str) -> None:
35
+ raise typer.BadParameter(message)
36
+
37
+
38
+ def parse_quantity(value: str) -> tuple[float | None, str, str]:
39
+ match = QUANTITY_RE.fullmatch(value.strip())
40
+ if not match:
41
+ return None, "", value.strip()
42
+ amount_text = match.group("amount").replace(" ", "").replace(",", ".")
43
+ try:
44
+ amount = float(Fraction(amount_text))
45
+ except (ValueError, ZeroDivisionError):
46
+ return None, "", value.strip()
47
+ raw_unit = (match.group("unit") or "").lower().replace(" ", "").replace(".", "")
48
+ unit = {
49
+ "càs": "cas",
50
+ "càc": "cac",
51
+ "tablespoon": "tbsp",
52
+ "tablespoons": "tbsp",
53
+ "teaspoon": "tsp",
54
+ "teaspoons": "tsp",
55
+ "cup": "cups",
56
+ "ounce": "oz",
57
+ "ounces": "oz",
58
+ "pound": "lb",
59
+ "pounds": "lb",
60
+ "lbs": "lb",
61
+ }.get(raw_unit, raw_unit)
62
+ return amount, unit, match.group("name").strip()
63
+
64
+
65
+ def parse_tags(value: object) -> list[str]:
66
+ if isinstance(value, str):
67
+ tags = value.split(",")
68
+ elif isinstance(value, list):
69
+ tags = [str(tag) for tag in value]
70
+ else:
71
+ return []
72
+ return [tag.strip() for tag in tags if tag.strip()]
73
+
74
+
75
+ def aggregate_ingredients(ingredients: list[dict[str, object]]) -> list[dict[str, object]]:
76
+ grouped: dict[tuple[str, str], dict[str, object]] = {}
77
+ for ingredient in ingredients:
78
+ amount = ingredient["amount"]
79
+ unit = str(ingredient["unit"])
80
+ name = str(ingredient["name"])
81
+ normalized_name = " ".join(name.casefold().split())
82
+ if amount is None:
83
+ key = ("plain", normalized_name)
84
+ elif normalized_name:
85
+ key = (unit, normalized_name)
86
+ else:
87
+ key = (unit, "")
88
+ if key not in grouped:
89
+ grouped[key] = dict(ingredient)
90
+ elif amount is not None:
91
+ grouped[key]["amount"] = float(grouped[key]["amount"]) + float(amount)
92
+ return list(grouped.values())
93
+
94
+
95
+ def markdown_with_ingredients(markdown: str) -> tuple[str, list[dict[str, object]]]:
96
+ ingredients: list[dict[str, object]] = []
97
+
98
+ def replace(match: re.Match[str]) -> str:
99
+ raw = match.group(1).strip()
100
+ amount, unit, name = parse_quantity(raw)
101
+ ingredients.append({"amount": amount, "unit": unit, "name": name, "raw": raw})
102
+ return f"RECIPEINGREDIENTTOKEN{len(ingredients) - 1}END"
103
+
104
+ rendered = MARKDOWN.render(INGREDIENT_RE.sub(replace, markdown))
105
+ return rendered, ingredients
106
+
107
+
108
+ def first_paragraph(markdown: str, limit: int = 180) -> str:
109
+ tokens = MARKDOWN.parse(markdown)
110
+ for index, token in enumerate(tokens):
111
+ if token.type != "paragraph_open":
112
+ continue
113
+ inline = tokens[index + 1]
114
+ if inline.type != "inline":
115
+ continue
116
+ parts = []
117
+ for child in inline.children or []:
118
+ if child.type in {"text", "code_inline", "image"}:
119
+ parts.append(child.content)
120
+ elif child.type in {"softbreak", "hardbreak"}:
121
+ parts.append(" ")
122
+ text = "".join(parts)
123
+ text = INGREDIENT_RE.sub(lambda match: match.group(1), text)
124
+ text = re.sub(r"\s+", " ", text).strip()
125
+ if text:
126
+ return text[:limit].rstrip()
127
+ return ""
128
+
129
+
130
+ def recipe_images(markdown_path: Path) -> list[Path]:
131
+ images = []
132
+ for path in markdown_path.parent.iterdir():
133
+ match = IMAGE_RE.fullmatch(path.name)
134
+ if path.is_file() and match and match.group("stem") == markdown_path.stem:
135
+ images.append(path)
136
+ return sorted(images, key=lambda path: int(IMAGE_RE.fullmatch(path.name).group("number")))
137
+
138
+
139
+ def recipe_slug(path: Path) -> str:
140
+ return path.stem
141
+
142
+
143
+ def rewrite_recipe_links(content: str, source_path: Path, recipe_slugs: dict[Path, str]) -> str:
144
+ def replace_href(match: re.Match[str]) -> str:
145
+ href = html.unescape(match.group(1))
146
+ parsed = urlsplit(href)
147
+ if parsed.scheme or parsed.netloc or parsed.path.startswith("/") or not parsed.path:
148
+ return match.group(0)
149
+
150
+ target_path = (source_path.parent / unquote(parsed.path)).resolve()
151
+ candidates = [target_path]
152
+ if target_path.suffix == "":
153
+ candidates.append(target_path.with_suffix(".md"))
154
+ target_slug = next(
155
+ (recipe_slugs[candidate] for candidate in candidates if candidate in recipe_slugs),
156
+ None,
157
+ )
158
+ if target_slug is None:
159
+ return match.group(0)
160
+
161
+ target_url = urlunsplit(
162
+ (
163
+ "",
164
+ "",
165
+ f"../recipes/{quote(target_slug, safe='-_')}.html",
166
+ parsed.query,
167
+ parsed.fragment,
168
+ )
169
+ )
170
+ return f'href="{html.escape(target_url, quote=True)}"'
171
+
172
+ return re.sub(r'href="([^"]*)"', replace_href, content)
173
+
174
+
175
+ def recipe_page(path: Path, image_dir: Path, recipe_slugs: dict[Path, str]) -> dict[str, object]:
176
+ try:
177
+ document = frontmatter.load(path)
178
+ except (OSError, ValueError) as exc:
179
+ fail(f"Could not read recipe '{path.name}': {exc}")
180
+ metadata = document.metadata
181
+ portions_value = metadata.get("portions")
182
+ portions = None
183
+ if portions_value not in (None, ""):
184
+ try:
185
+ portions = int(portions_value)
186
+ except (TypeError, ValueError):
187
+ fail(f"Recipe '{path.name}' has invalid portions; use a positive integer")
188
+ if isinstance(portions_value, bool) or (
189
+ isinstance(portions_value, float) and not portions_value.is_integer()
190
+ ):
191
+ fail(f"Recipe '{path.name}' has invalid portions; use a positive integer")
192
+ if portions < 1:
193
+ fail(f"Recipe '{path.name}' has invalid portions; use a positive integer")
194
+
195
+ title = str(metadata.get("title") or path.stem.replace("-", " ").title())
196
+ slug = recipe_slug(path)
197
+ content, ingredients = markdown_with_ingredients(document.content)
198
+ content = rewrite_recipe_links(content, path, recipe_slugs)
199
+ images = recipe_images(path)
200
+ for image in images:
201
+ image_dir.mkdir(parents=True, exist_ok=True)
202
+ shutil.copyfile(image, image_dir / image.name)
203
+
204
+ excluded = {"title", "tags", "portions"}
205
+ properties = [
206
+ {"name": str(key), "value": value} for key, value in metadata.items() if key not in excluded
207
+ ]
208
+ return {
209
+ "slug": slug,
210
+ "title": title,
211
+ "lang": str(metadata.get("lang", "")),
212
+ "tags": parse_tags(metadata.get("tags")),
213
+ "properties": properties,
214
+ "excerpt": first_paragraph(document.content),
215
+ "portions": portions,
216
+ "ingredients": ingredients,
217
+ "ingredient_list": aggregate_ingredients(ingredients),
218
+ "content": content,
219
+ "images": [image.name for image in images],
220
+ }
221
+
222
+
223
+ def attr(value: object) -> str:
224
+ return html.escape(str(value), quote=True)
225
+
226
+
227
+ def format_amount(amount: float) -> str:
228
+ return f"{round(amount, 2):.2f}".rstrip("0").rstrip(".")
229
+
230
+
231
+ def ingredient_html(ingredient: dict[str, object], tag: str) -> str:
232
+ amount = ingredient["amount"]
233
+ if amount is None:
234
+ text = str(ingredient["name"] or ingredient["raw"])
235
+ return f"<{tag} data-ingredient>{html.escape(text)}</{tag}>"
236
+ unit, name = str(ingredient["unit"]), str(ingredient["name"])
237
+ text = " ".join(part for part in (format_amount(float(amount)), unit, name) if part)
238
+ return (
239
+ f'<{tag} data-ingredient data-amount="{attr(float(amount))}" '
240
+ f'data-unit="{attr(unit)}" data-name="{attr(name)}">{html.escape(text)}</{tag}>'
241
+ )
242
+
243
+
244
+ def insert_ingredients(content: str, ingredients: list[dict[str, object]]) -> str:
245
+ def replace(match: re.Match[str]) -> str:
246
+ return ingredient_html(ingredients[int(match.group(1))], "span")
247
+
248
+ # Only substitute in text, never inside tags/attributes (e.g. image alt text).
249
+ parts = re.split(r"(<[^>]*>)", content)
250
+ return "".join(part if part.startswith("<") else TOKEN_RE.sub(replace, part) for part in parts)
251
+
252
+
253
+ def display_value(value: object) -> str:
254
+ if isinstance(value, list):
255
+ return ", ".join(display_value(item) for item in value)
256
+ if isinstance(value, dict):
257
+ return json.dumps(value, ensure_ascii=False, default=str)
258
+ if isinstance(value, bool):
259
+ return str(value).lower()
260
+ return "" if value is None else str(value)
261
+
262
+
263
+ def recipe_html_parts(recipe: dict[str, object]) -> dict[str, str]:
264
+ tags = "".join(
265
+ f'<a class="tag" href="../index.html?tag={attr(quote(tag, safe="-_.!~*()"))}">'
266
+ f"{html.escape(tag)}</a>"
267
+ for tag in recipe["tags"]
268
+ )
269
+ properties = "".join(
270
+ f'<div class="recipe-property"><dt>{html.escape(str(item["name"]))}</dt>'
271
+ f"<dd>{html.escape(display_value(item['value']))}</dd></div>"
272
+ for item in recipe["properties"]
273
+ )
274
+ gallery = "".join(
275
+ f'<figure><img loading="lazy" src="../assets/images/{attr(quote(image, safe=""))}" '
276
+ f'alt="{attr(recipe["title"])} {index}"></figure>'
277
+ for index, image in enumerate(recipe["images"], start=1)
278
+ )
279
+ portions = recipe["portions"]
280
+ return {
281
+ "tags": tags,
282
+ "properties": properties,
283
+ "properties_hidden": "" if properties else " hidden",
284
+ "servings_attrs": f' data-portions="{portions}"' if portions else " hidden",
285
+ "portions": str(portions or ""),
286
+ "ingredient_list": "".join(
287
+ ingredient_html(item, "li") for item in recipe["ingredient_list"]
288
+ ),
289
+ "gallery": gallery,
290
+ # Last: inserted recipe content must not be scanned for other placeholders.
291
+ "content": insert_ingredients(str(recipe["content"]), recipe["ingredients"]),
292
+ }
293
+
294
+
295
+ def recipe_index_data(recipes: list[dict[str, object]]) -> str:
296
+ entries = []
297
+ for recipe in recipes:
298
+ search_terms = [
299
+ str(recipe["title"]),
300
+ *recipe["tags"],
301
+ str(recipe["content"]),
302
+ *(str(ingredient["raw"]) for ingredient in recipe["ingredients"]),
303
+ *(f"{property_['name']} {property_['value']}" for property_ in recipe["properties"]),
304
+ ]
305
+ entries.append(
306
+ {
307
+ "slug": recipe["slug"],
308
+ "title": recipe["title"],
309
+ "tags": recipe["tags"],
310
+ "excerpt": recipe["excerpt"],
311
+ "search": " ".join([*search_terms, str(recipe["excerpt"])]),
312
+ "lang": recipe["lang"],
313
+ }
314
+ )
315
+ return json.dumps(entries, ensure_ascii=False)
316
+
317
+
318
+ def render_template(path: Path, **values: str) -> str:
319
+ template = path.read_text(encoding="utf-8")
320
+ for name, value in values.items():
321
+ template = template.replace("{{ " + name + " }}", value)
322
+ return template
323
+
324
+
325
+ def build(source: Path, destination: Path, title: str = "Recettes") -> int:
326
+ source = source.resolve()
327
+ destination = destination.resolve()
328
+ if not source.is_dir():
329
+ fail(f"Recipe directory does not exist: {source}")
330
+ if source == destination or source in destination.parents:
331
+ fail("Output directory must be outside the recipe source directory")
332
+ paths = sorted(path for path in source.glob("*.md") if path.is_file())
333
+ if not paths:
334
+ fail(f"No Markdown recipes found in {source}")
335
+
336
+ package_dir = Path(__file__).parent
337
+ static = package_dir / "static"
338
+ templates = package_dir / "templates"
339
+ assets = destination / "assets"
340
+ assets.mkdir(parents=True, exist_ok=True)
341
+ for filename in ("style.css", "app.js", "recipe.js"):
342
+ shutil.copyfile(static / filename, assets / filename)
343
+ image_dir = assets / "images"
344
+ recipes_dir = destination / "recipes"
345
+ recipes_dir.mkdir(parents=True, exist_ok=True)
346
+ recipes = []
347
+ recipe_slugs = {path.resolve(): recipe_slug(path) for path in paths}
348
+ seen = set()
349
+ for path in paths:
350
+ slug = recipe_slug(path)
351
+ if slug in seen:
352
+ fail(f"Recipe filenames must be unique: {path.name}")
353
+ seen.add(slug)
354
+ recipe = recipe_page(path, image_dir, recipe_slugs)
355
+ recipes.append(recipe)
356
+ page = render_template(
357
+ templates / "recipe.html",
358
+ title=html.escape(str(recipe["title"])),
359
+ lang=html.escape(str(recipe["lang"]), quote=True),
360
+ **recipe_html_parts(recipe),
361
+ )
362
+ (recipes_dir / f"{slug}.html").write_text(page, encoding="utf-8")
363
+ prefetch_links = "\n ".join(
364
+ f'<link rel="prefetch" href="recipes/{quote(str(recipe["slug"]), safe="-_")}.html">'
365
+ for recipe in recipes
366
+ )
367
+ languages = {str(recipe["lang"]) for recipe in recipes if recipe["lang"]}
368
+ index = render_template(
369
+ templates / "index.html",
370
+ title=html.escape(title),
371
+ lang=html.escape(next(iter(languages)) if len(languages) == 1 else "", quote=True),
372
+ prefetch_links=prefetch_links,
373
+ )
374
+ (destination / "index.html").write_text(index, encoding="utf-8")
375
+ (destination / "recipes.json").write_text(recipe_index_data(recipes), encoding="utf-8")
376
+ return len(recipes)
377
+
378
+
379
+ @app.command("build")
380
+ def build_command(
381
+ source: Annotated[Path, typer.Argument(help="Directory containing recipe Markdown files")],
382
+ destination: Annotated[
383
+ Path, typer.Option("--destination", "-d", help="Generated website directory")
384
+ ] = Path("site"),
385
+ title: Annotated[
386
+ str, typer.Option("--title", help="Title for the home page")
387
+ ] = "Recettes",
388
+ ) -> None:
389
+ """Build the static recipe website."""
390
+ count = build(source, destination, title)
391
+ typer.echo(f"Built {count} recipes into {destination}")
392
+
393
+
394
+ if __name__ == "__main__":
395
+ app()
recettes/static/app.js ADDED
@@ -0,0 +1,77 @@
1
+ const recipes = await fetch("./recipes.json").then((response) =>
2
+ response.json(),
3
+ );
4
+ const searchInput = document.querySelector("#recipe-search");
5
+ const tagCloud = document.querySelector("#tag-cloud");
6
+ const recipeGrid = document.querySelector("#recipe-grid");
7
+ const tagTemplate = document.querySelector("#tag-cloud-item-template");
8
+ const cardTemplate = document.querySelector("#recipe-card-template");
9
+ const recipeTagTemplate = document.querySelector("#recipe-tag-template");
10
+ const params = new URLSearchParams(window.location.search);
11
+ let activeTag = params.get("tag") || "";
12
+ const tagCounts = new Map();
13
+ for (const recipe of recipes) {
14
+ for (const tag of recipe.tags) {
15
+ tagCounts.set(tag, (tagCounts.get(tag) || 0) + 1);
16
+ }
17
+ }
18
+ const maxCount = Math.max(...tagCounts.values(), 1);
19
+
20
+ for (const [tag, count] of [...tagCounts].sort(([left], [right]) =>
21
+ left.localeCompare(right),
22
+ )) {
23
+ const fragment = tagTemplate.content.cloneNode(true);
24
+ const button = fragment.querySelector("button");
25
+ button.dataset.tag = tag;
26
+ button.style.setProperty("--tag-weight", 1 + (count - 1) / maxCount);
27
+ button.querySelector("[data-tag-name]").textContent = tag;
28
+ button.querySelector("[data-tag-count]").textContent = count;
29
+ button.addEventListener("click", () => {
30
+ activeTag = activeTag === tag ? "" : tag;
31
+ updateRecipes();
32
+ });
33
+ tagCloud.append(fragment);
34
+ }
35
+
36
+ for (const recipe of recipes) {
37
+ const fragment = cardTemplate.content.cloneNode(true);
38
+ const card = fragment.querySelector(".recipe-card");
39
+ const link = card.querySelector("a");
40
+ link.href = `recipes/${encodeURIComponent(recipe.slug)}.html`;
41
+ card.dataset.search = recipe.search.toLocaleLowerCase(
42
+ recipe.lang || undefined,
43
+ );
44
+ card.dataset.tags = JSON.stringify(recipe.tags);
45
+ card.querySelector("[data-recipe-title]").textContent = recipe.title;
46
+ const excerpt = card.querySelector("[data-recipe-excerpt]");
47
+ excerpt.textContent = recipe.excerpt;
48
+ excerpt.hidden = !recipe.excerpt;
49
+ const recipeTags = card.querySelector("[data-recipe-tags]");
50
+ for (const tag of recipe.tags) {
51
+ const tagFragment = recipeTagTemplate.content.cloneNode(true);
52
+ tagFragment.querySelector("[data-tag-label]").textContent = tag;
53
+ recipeTags.append(tagFragment);
54
+ }
55
+ recipeGrid.append(fragment);
56
+ }
57
+
58
+ const cards = [...recipeGrid.querySelectorAll(".recipe-card")];
59
+ const tagButtons = [...tagCloud.querySelectorAll(".tag-cloud-item")];
60
+
61
+ function updateRecipes() {
62
+ const query = searchInput.value.trim().toLocaleLowerCase();
63
+ for (const card of cards) {
64
+ const tags = JSON.parse(card.dataset.tags);
65
+ card.hidden =
66
+ !card.dataset.search.includes(query) ||
67
+ Boolean(activeTag && !tags.includes(activeTag));
68
+ }
69
+ for (const button of tagButtons) {
70
+ const active = button.dataset.tag === activeTag;
71
+ button.classList.toggle("active", active);
72
+ button.setAttribute("aria-pressed", String(active));
73
+ }
74
+ }
75
+
76
+ searchInput.addEventListener("input", updateRecipes);
77
+ updateRecipes();
@@ -0,0 +1,29 @@
1
+ const servingsControl = document.querySelector("#servings-control");
2
+ const servingsCount = document.querySelector("#servings-count");
3
+ const portions = Number(servingsControl.dataset.portions) || null;
4
+ const formatter = new Intl.NumberFormat(
5
+ document.documentElement.lang || undefined,
6
+ { maximumFractionDigits: 2 },
7
+ );
8
+ let servings = portions;
9
+
10
+ function updateQuantities() {
11
+ const scale = portions == null ? 1 : servings / portions;
12
+ for (const element of document.querySelectorAll("[data-amount]")) {
13
+ const { amount, unit, name } = element.dataset;
14
+ element.textContent = [formatter.format(Number(amount) * scale), unit, name]
15
+ .filter(Boolean)
16
+ .join(" ");
17
+ }
18
+ }
19
+
20
+ // Re-render once to localize number formatting (e.g. "0,5" in French).
21
+ updateQuantities();
22
+
23
+ for (const control of document.querySelectorAll("[data-servings-step]")) {
24
+ control.addEventListener("click", () => {
25
+ servings = Math.max(1, servings + Number(control.dataset.servingsStep));
26
+ servingsCount.textContent = servings;
27
+ updateQuantities();
28
+ });
29
+ }