embedstamp 0.1.4__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.
embedstamp/__init__.py ADDED
@@ -0,0 +1,95 @@
1
+ """embedstamp: stamp a vector index with its embedding model's fingerprint.
2
+
3
+ Quick tour::
4
+
5
+ fp = stamp(embed, model="my-model") # fingerprint from fixed probe sentences
6
+ SidecarStore("index.embedstamp.json").save(fp)
7
+ verdict = verify(fp, embed, model="my-model") # same / drift / different
8
+ guard = Guard(store, embed, model="my-model") # raises before a mismatched query
9
+ migrate(index, new_embed, new_model="other", switch=True) # blue/green re-embedding
10
+
11
+ Names that need an optional extra are loaded on first use, so ``import embedstamp`` stays light::
12
+
13
+ from embedstamp import ChromaStore # extra "chroma" (also: embedstamp.stores.chroma)
14
+ from embedstamp import FastEmbedEmbedder # extra "fastembed" (also: embedstamp.embedders.fastembed)
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import importlib
20
+ from typing import TYPE_CHECKING, Any
21
+
22
+ from .embedders import FakeEmbedder, resolve_embedder
23
+ from .errors import (
24
+ EmbeddingMismatchError,
25
+ EmbedstampError,
26
+ FingerprintNotFoundError,
27
+ FingerprintTooLargeError,
28
+ SwitchRefusedError,
29
+ )
30
+ from .errors import missing_extra_error as _missing_extra_error
31
+ from .fingerprint import Fingerprint, stamp
32
+ from .guard import Guard
33
+ from .migrate import MigrationReport, migrate, overlap_at_k
34
+ from .stores import FingerprintStore, MigratableStore, resolve_store
35
+ from .stores.local import LocalIndex
36
+ from .stores.sidecar import SidecarStore
37
+ from .verify import Thresholds, Verdict, verify
38
+
39
+ if TYPE_CHECKING: # pragma: no cover - type checkers see the lazy names as normal imports
40
+ from .embedders.fastembed import FastEmbedEmbedder
41
+ from .stores.chroma import ChromaStore
42
+
43
+ __version__ = "0.1.4"
44
+
45
+ # 선택 의존성(extra)이 필요한 이름: 이름 -> (실제 모듈, 필요한 패키지, extra 이름).
46
+ # import embedstamp 할 때는 불러오지 않고, 처음 꺼내 쓰는 순간 __getattr__ 이 불러온다.
47
+ _OPTIONAL: dict[str, tuple[str, str, str]] = {
48
+ "ChromaStore": (".stores.chroma", "chromadb", "chroma"),
49
+ "FastEmbedEmbedder": (".embedders.fastembed", "fastembed", "fastembed"),
50
+ }
51
+
52
+
53
+ def __getattr__(name: str) -> Any:
54
+ """Load ``ChromaStore`` / ``FastEmbedEmbedder`` on first access (PEP 562)."""
55
+ if name not in _OPTIONAL:
56
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
57
+ module_name, package, extra = _OPTIONAL[name]
58
+ try:
59
+ importlib.import_module(package) # extra 가 없으면 여기서 실패한다
60
+ except ImportError as exc:
61
+ # `from embedstamp import ChromaStore` 가 "cannot import name" 대신 고치는 방법을 보여 주게 한다
62
+ raise _missing_extra_error(name, package, extra) from exc
63
+ value = getattr(importlib.import_module(module_name, __name__), name)
64
+ globals()[name] = value # 다음부터는 __getattr__ 을 거치지 않는다
65
+ return value
66
+
67
+
68
+ def __dir__() -> list[str]:
69
+ return sorted([*globals(), *_OPTIONAL])
70
+
71
+
72
+ # ChromaStore·FastEmbedEmbedder 는 extra 가 없으면 import 할 수 없으므로 `import *` 대상에서 뺀다.
73
+ __all__ = [
74
+ "EmbeddingMismatchError",
75
+ "EmbedstampError",
76
+ "FakeEmbedder",
77
+ "Fingerprint",
78
+ "FingerprintNotFoundError",
79
+ "FingerprintStore",
80
+ "FingerprintTooLargeError",
81
+ "Guard",
82
+ "LocalIndex",
83
+ "MigratableStore",
84
+ "MigrationReport",
85
+ "SidecarStore",
86
+ "SwitchRefusedError",
87
+ "Thresholds",
88
+ "Verdict",
89
+ "migrate",
90
+ "overlap_at_k",
91
+ "resolve_embedder",
92
+ "resolve_store",
93
+ "stamp",
94
+ "verify",
95
+ ]
embedstamp/_vectors.py ADDED
@@ -0,0 +1,49 @@
1
+ """Small numpy helpers shared by the fingerprint, verify and store modules (internal)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable, Sequence
6
+ from typing import Any
7
+
8
+ import numpy as np
9
+
10
+ #: An embedder maps a list of texts to an ``(n, d)`` array-like of vectors.
11
+ Embedder = Callable[[Sequence[str]], Any]
12
+
13
+
14
+ def as_matrix(raw: Any, n_expected: int | None = None) -> np.ndarray:
15
+ """Convert an embedder result to a finite float32 ``(n, d)`` matrix or raise ValueError."""
16
+ arr = np.asarray(raw)
17
+ if arr.ndim == 1 and n_expected == 1:
18
+ arr = arr[None, :]
19
+ if arr.ndim != 2 or arr.shape[1] == 0:
20
+ raise ValueError(
21
+ f"embedder must return an (n, d) array of vectors, got shape {arr.shape}; "
22
+ "wrap your model so that it maps list[str] to a 2-D array"
23
+ )
24
+ if n_expected is not None and arr.shape[0] != n_expected:
25
+ raise ValueError(
26
+ f"embedder returned {arr.shape[0]} vectors for {n_expected} texts; "
27
+ "it must return one vector per input text, in order"
28
+ )
29
+ out = arr.astype(np.float32)
30
+ if not np.isfinite(out).all():
31
+ raise ValueError("embedder returned NaN or infinite values; check the model output")
32
+ return out
33
+
34
+
35
+ def raw_dtype(raw: Any) -> str:
36
+ """Name of the dtype the embedder produced before conversion to float32."""
37
+ return np.asarray(raw).dtype.name
38
+
39
+
40
+ def unit_rows(mat: np.ndarray) -> np.ndarray:
41
+ """Return rows scaled to unit length (zero rows stay zero)."""
42
+ norms = np.linalg.norm(mat, axis=1, keepdims=True)
43
+ norms[norms == 0] = 1.0
44
+ return mat / norms
45
+
46
+
47
+ def row_cosines(a: np.ndarray, b: np.ndarray) -> np.ndarray:
48
+ """Cosine similarity of matching rows of ``a`` and ``b``."""
49
+ return np.einsum("ij,ij->i", unit_rows(a.astype(np.float64)), unit_rows(b.astype(np.float64)))
embedstamp/cli.py ADDED
@@ -0,0 +1,317 @@
1
+ """Command line interface: demo, stamp, check, show, migrate (English and Korean)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import contextlib
7
+ import dataclasses
8
+ import json
9
+ import os
10
+ import sys
11
+ from collections.abc import Iterator, Mapping, Sequence
12
+ from typing import Any
13
+
14
+ from . import __version__
15
+ from .demo import run_demo
16
+ from .embedders import resolve_embedder
17
+ from .errors import EmbedstampError, FingerprintTooLargeError, SwitchRefusedError
18
+ from .fingerprint import stamp
19
+ from .i18n import Translator, resolve_lang
20
+ from .migrate import migrate
21
+ from .stores import MigratableStore, resolve_store
22
+ from .verify import verify
23
+
24
+ EXIT_SAME, EXIT_ERROR, EXIT_USAGE, EXIT_SAVE_FAILED = 0, 1, 2, 4
25
+ EXIT_DRIFT, EXIT_DIFFERENT, EXIT_NO_FINGERPRINT, EXIT_SWITCH_REFUSED = 10, 11, 12, 13
26
+ _CHECK_EXIT = {"same": EXIT_SAME, "drift": EXIT_DRIFT, "different": EXIT_DIFFERENT}
27
+
28
+
29
+ def _prescan_lang(argv: Sequence[str]) -> str | None:
30
+ """Find ``--lang`` before argparse runs, so that --help can already be localised."""
31
+ for i, arg in enumerate(argv):
32
+ if arg == "--lang" and i + 1 < len(argv):
33
+ return argv[i + 1]
34
+ if arg.startswith("--lang="):
35
+ return arg.split("=", 1)[1]
36
+ return None
37
+
38
+
39
+ # argparse 가 사용자에게 보여 주는 영어 원문(msgid) -> 메시지 표의 키.
40
+ # argparse 는 모든 문구를 모듈 전역 gettext 함수 `_`·`ngettext` 로 감싸 만든다.
41
+ # 그래서 파싱하는 동안만 그 두 함수를 바꿔 끼우면 오류·사용법 문구가 한 곳(locales)에서 번역된다.
42
+ # 표에 없는 원문(개발자용 오류 등)은 영어 그대로 둔다.
43
+ _ARGPARSE_MSGIDS: dict[str, str] = {
44
+ "%(prog)s: error: %(message)s\n": "argparse.error",
45
+ "usage: ": "argparse.usage",
46
+ "%(heading)s:": "argparse.heading",
47
+ " (default: %(default)s)": "argparse.default",
48
+ "subcommands": "argparse.subcommands",
49
+ "argument %(argument_name)s: %(message)s": "argparse.argument",
50
+ "the following arguments are required: %s": "argparse.required",
51
+ "one of the arguments %s is required": "argparse.one_of_required",
52
+ "unrecognized arguments: %s": "argparse.unrecognized",
53
+ "invalid %(type)s value: %(value)r": "argparse.invalid_type",
54
+ "invalid choice: %(value)r (choose from %(choices)s)": "argparse.invalid_choice",
55
+ "unknown parser %(parser_name)r (choices: %(choices)s)": "argparse.unknown_parser",
56
+ "expected one argument": "argparse.expected_one",
57
+ "expected at most one argument": "argparse.expected_at_most_one",
58
+ "expected at least one argument": "argparse.expected_at_least_one",
59
+ "expected %s argument": "argparse.expected_n",
60
+ "expected %s arguments": "argparse.expected_n_plural",
61
+ "ambiguous option: %(option)s could match %(matches)s": "argparse.ambiguous",
62
+ "not allowed with argument %s": "argparse.not_allowed_with",
63
+ "ignored explicit argument %r": "argparse.ignored_explicit",
64
+ "unexpected option string: %s": "argparse.unexpected_option",
65
+ "can't open '%(filename)s': %(error)s": "argparse.cant_open",
66
+ }
67
+
68
+
69
+ @contextlib.contextmanager
70
+ def _argparse_language(tr: Translator) -> Iterator[None]:
71
+ """While active, argparse builds its messages from the chosen language's table."""
72
+ original_gettext, original_ngettext = argparse._, argparse.ngettext
73
+
74
+ def gettext(msgid: str) -> str:
75
+ key = _ARGPARSE_MSGIDS.get(msgid)
76
+ return tr.raw(key) if key else msgid
77
+
78
+ def ngettext(singular: str, plural: str, n: int) -> str:
79
+ return gettext(singular if n == 1 else plural)
80
+
81
+ argparse._ = gettext # type: ignore[attr-defined]
82
+ argparse.ngettext = ngettext # type: ignore[attr-defined]
83
+ try:
84
+ yield
85
+ finally: # 라이브러리로 import 한 다른 코드의 argparse 에 영향이 남지 않게 반드시 되돌린다
86
+ argparse._ = original_gettext # type: ignore[attr-defined]
87
+ argparse.ngettext = original_ngettext # type: ignore[attr-defined]
88
+
89
+
90
+ def _formatter_for(tr: Translator) -> type[argparse.HelpFormatter]:
91
+ """A help formatter whose "usage:" prefix is localised."""
92
+
93
+ class _Formatter(argparse.HelpFormatter):
94
+ def add_usage(self, usage: Any, actions: Any, groups: Any, prefix: str | None = None) -> None:
95
+ if prefix is None: # argparse passes "" itself when it builds sub-command prog names
96
+ prefix = tr("help.usage") + ": "
97
+ super().add_usage(usage, actions, groups, prefix=prefix)
98
+
99
+ return _Formatter
100
+
101
+
102
+ def _localise(parser: argparse.ArgumentParser, tr: Translator) -> None:
103
+ """Add a localised -h and rename argparse's built-in group titles."""
104
+ parser.add_argument("-h", "--help", action="help", default=argparse.SUPPRESS, help=tr("help.help"))
105
+ parser._positionals.title = tr("help.positional")
106
+ parser._optionals.title = tr("help.options")
107
+
108
+
109
+ def _build_parser(tr: Translator) -> argparse.ArgumentParser:
110
+ fmt = _formatter_for(tr)
111
+ parser = argparse.ArgumentParser(
112
+ prog="embedstamp", description=tr("app.description"), epilog=tr("app.epilog"),
113
+ add_help=False, formatter_class=fmt,
114
+ )
115
+ _localise(parser, tr)
116
+ parser.add_argument("--version", action="version", version=f"embedstamp {__version__}",
117
+ help=tr("help.version"))
118
+ parser.add_argument("--lang", metavar="en|ko", help=tr("opt.lang"))
119
+ sub = parser.add_subparsers(dest="command", required=True, metavar="{demo,stamp,check,show,migrate}")
120
+
121
+ def add(name: str) -> argparse.ArgumentParser:
122
+ p = sub.add_parser(name, help=tr(f"cmd.{name}"), description=tr(f"cmd.{name}"),
123
+ add_help=False, formatter_class=fmt)
124
+ _localise(p, tr)
125
+ p.add_argument("--lang", metavar="en|ko", default=argparse.SUPPRESS, help=tr("opt.lang"))
126
+ return p
127
+
128
+ add("demo")
129
+
130
+ p = add("stamp")
131
+ p.add_argument("--store", required=True, help=tr("opt.store"))
132
+ p.add_argument("--embedder", required=True, help=tr("opt.embedder"))
133
+ p.add_argument("--model", help=tr("opt.model"))
134
+ p.add_argument("--doc-prefix", default="", help=tr("opt.doc_prefix"))
135
+ p.add_argument("--query-prefix", default="", help=tr("opt.query_prefix"))
136
+ p.add_argument("--compact", action="store_true", help=tr("opt.compact"))
137
+
138
+ p = add("check")
139
+ p.add_argument("--store", required=True, help=tr("opt.store"))
140
+ p.add_argument("--embedder", required=True, help=tr("opt.embedder"))
141
+ p.add_argument("--model", help=tr("opt.model"))
142
+ p.add_argument("--doc-prefix", default="", help=tr("opt.doc_prefix"))
143
+ p.add_argument("--query-prefix", default="", help=tr("opt.query_prefix"))
144
+ p.add_argument("--json", action="store_true", help=tr("opt.json"))
145
+
146
+ p = add("show")
147
+ p.add_argument("--store", required=True, help=tr("opt.store"))
148
+ p.add_argument("--json", action="store_true", help=tr("opt.json"))
149
+
150
+ p = add("migrate")
151
+ p.add_argument("--store", required=True, help=tr("opt.store"))
152
+ p.add_argument("--to", required=True, dest="to", help=tr("opt.to"))
153
+ p.add_argument("--from", dest="from_", help=tr("opt.from"))
154
+ p.add_argument("--queries", help=tr("opt.queries"))
155
+ p.add_argument("-k", type=int, default=10, help=tr("opt.k"))
156
+ p.add_argument("--batch-size", type=int, default=64, help=tr("opt.batch_size"))
157
+ p.add_argument("--doc-prefix", default="", help=tr("opt.doc_prefix"))
158
+ p.add_argument("--query-prefix", default="", help=tr("opt.query_prefix"))
159
+ p.add_argument("--switch", action="store_true", help=tr("opt.switch"))
160
+ p.add_argument("--min-self-recall", type=float, default=0.9, help=tr("opt.min_self_recall"))
161
+ return parser
162
+
163
+
164
+ def _fmt(value: float | None) -> str:
165
+ return "n/a" if value is None else f"{value:.4f}"
166
+
167
+
168
+ def _error(text: str) -> None:
169
+ """Print to stderr after flushing stdout, so lines appear in the order they happened.
170
+
171
+ stdout 은 파이프·파일로 보낼 때 버퍼에 쌓이고 stderr 는 바로 나가서, 그대로 두면
172
+ 오류가 그보다 먼저 찍은 진행 줄보다 앞에 보인다.
173
+ """
174
+ sys.stdout.flush()
175
+ print(text, file=sys.stderr, flush=True)
176
+
177
+
178
+ def _cmd_stamp(args: argparse.Namespace, tr: Translator) -> int:
179
+ store = resolve_store(args.store)
180
+ embed, spec_model = resolve_embedder(args.embedder)
181
+ fp = stamp(embed, model=args.model or spec_model, doc_prefix=args.doc_prefix,
182
+ query_prefix=args.query_prefix, compact=args.compact)
183
+ try:
184
+ store.save(fp)
185
+ except (OSError, FingerprintTooLargeError) as exc:
186
+ _error(tr("err.generic", message=exc))
187
+ return EXIT_SAVE_FAILED
188
+ print(tr("stamp.done", store=args.store, model=fp.model, dim=fp.dim, digest=fp.digest[:12],
189
+ size=len(fp.to_json().encode("utf-8"))))
190
+ return EXIT_SAME
191
+
192
+
193
+ def _cmd_check(args: argparse.Namespace, tr: Translator) -> int:
194
+ store = resolve_store(args.store)
195
+ embed, spec_model = resolve_embedder(args.embedder) # validate the spec before touching the store
196
+ stored = store.load()
197
+ if stored is None:
198
+ if args.json:
199
+ print(json.dumps({"status": "missing", "min_cos": None, "reasons": ["fingerprint_not_found"]}))
200
+ else:
201
+ _error(tr("check.nofp", store=args.store))
202
+ return EXIT_NO_FINGERPRINT
203
+ verdict = verify(stored, embed, model=args.model or spec_model, doc_prefix=args.doc_prefix,
204
+ query_prefix=args.query_prefix)
205
+ if args.json:
206
+ print(json.dumps({
207
+ "status": verdict.status, "min_cos": verdict.min_cos, "mean_cos": verdict.mean_cos,
208
+ "reasons": list(verdict.reasons), "stored_model": verdict.stored.model,
209
+ "current_model": verdict.current.model,
210
+ }))
211
+ else:
212
+ print(tr("check.status", status=verdict.status, min_cos=_fmt(verdict.min_cos),
213
+ mean_cos=_fmt(verdict.mean_cos)))
214
+ print(tr("check.models", stored=verdict.stored.model, current=verdict.current.model))
215
+ if verdict.reasons:
216
+ print(tr("check.reasons"))
217
+ for code in verdict.reasons:
218
+ print(f" - {code}: {tr('reason.' + code)}")
219
+ print(tr(f"check.hint.{verdict.status}"))
220
+ return _CHECK_EXIT[verdict.status]
221
+
222
+
223
+ def _cmd_show(args: argparse.Namespace, tr: Translator) -> int:
224
+ store = resolve_store(args.store)
225
+ fp = store.load()
226
+ if fp is None:
227
+ _error(tr("check.nofp", store=args.store))
228
+ return EXIT_NO_FINGERPRINT
229
+ if args.json:
230
+ data: dict[str, Any] = dataclasses.asdict(fp)
231
+ data["probes_fp16"] = fp.probes_fp16 is not None # the raw payload is too long to print
232
+ data.pop("projection32")
233
+ print(json.dumps(data, ensure_ascii=False))
234
+ return EXIT_SAME
235
+ print(tr("show.title", store=args.store))
236
+ print(tr("show.model", model=fp.model))
237
+ print(tr("show.dim", dim=fp.dim, dtype=fp.dtype))
238
+ print(tr("show.norm", normalized=fp.normalized, norm_mean=fp.norm_mean))
239
+ print(tr("show.prefixes", doc_prefix=fp.doc_prefix, query_prefix=fp.query_prefix))
240
+ print(tr("show.probes", probe_set=fp.probe_set, n_probes=fp.n_probes,
241
+ mode="full" if fp.probes_fp16 else "compact"))
242
+ print(tr("show.digest", digest=fp.digest))
243
+ print(tr("show.created", created_at=fp.created_at))
244
+ return EXIT_SAME
245
+
246
+
247
+ def _cmd_migrate(args: argparse.Namespace, tr: Translator) -> int:
248
+ store = resolve_store(args.store)
249
+ if not isinstance(store, MigratableStore):
250
+ _error(tr("err.generic", message=tr("err.not_migratable")))
251
+ return EXIT_USAGE
252
+ new_embed, new_model = resolve_embedder(args.to)
253
+ old_embed = resolve_embedder(args.from_)[0] if args.from_ else None
254
+ queries = None
255
+ if args.queries:
256
+ with open(args.queries, encoding="utf-8") as fh:
257
+ queries = [line.strip() for line in fh if line.strip()]
258
+ # 문서가 없는 인덱스(예: `stamp` 만 한 local://)는 "진행 중" 줄을 찍기 전에 대처법과 함께 멈춘다
259
+ if store.count() == 0:
260
+ _error(tr("err.generic", message=tr("err.empty_source", store=args.store)))
261
+ return EXIT_ERROR
262
+ print(tr("migrate.start", store=args.store, model=new_model), flush=True)
263
+ try:
264
+ report = migrate(
265
+ store, new_embed, new_model=new_model, old_embed=old_embed, queries=queries, k=args.k,
266
+ batch_size=args.batch_size, switch=args.switch, doc_prefix=args.doc_prefix,
267
+ query_prefix=args.query_prefix, min_self_recall=args.min_self_recall,
268
+ progress=lambda done, total: print(tr("migrate.progress", done=done, total=total), flush=True),
269
+ )
270
+ except SwitchRefusedError as exc:
271
+ _error(tr("migrate.refused", message=exc))
272
+ return EXIT_SWITCH_REFUSED
273
+ # green= 에는 green 컬렉션을 만든 이름(예: docs__green)을 보여 준다. 전환 뒤의 이름은 아래 switched 줄에 있다.
274
+ print(tr("migrate.report", n_docs=report.n_docs, n_embedded=report.n_embedded,
275
+ n_skipped=report.n_skipped, green=report.built_name or report.green_name))
276
+ if report.n_embedded == 0 and report.n_skipped > 0: # 이전 실행에서 이미 다 채운 green 을 다시 쓴 경우
277
+ print(tr("migrate.reused", green=report.built_name or report.green_name))
278
+ print(tr("migrate.self_recall", k=report.k, value=f"{report.self_recall_at_k:.2f}"))
279
+ if report.overlap_at_k is not None:
280
+ print(tr("migrate.overlap", k=report.k, value=f"{report.overlap_at_k:.2f}"))
281
+ if report.switched:
282
+ print(tr("migrate.switched", store=report.green_name, model=new_model, blue=report.blue_name))
283
+ after = report.verdict_after_switch
284
+ if after is not None: # 전환 직후 실제로 다시 잰 수치를 보여 준다
285
+ print(tr("check.status", status=after.status, min_cos=_fmt(after.min_cos),
286
+ mean_cos=_fmt(after.mean_cos)))
287
+ else:
288
+ print(tr("migrate.not_switched", green=report.green_name))
289
+ return EXIT_SAME
290
+
291
+
292
+ def main(argv: Sequence[str] | None = None, env: Mapping[str, str] | None = None) -> int:
293
+ """Entry point; returns the process exit code."""
294
+ args_list = list(sys.argv[1:] if argv is None else argv)
295
+ environment = os.environ if env is None else env
296
+ tr = Translator(resolve_lang(_prescan_lang(args_list), environment))
297
+ try:
298
+ with _argparse_language(tr): # 도움말·사용법 오류 문구도 고른 언어로
299
+ parser = _build_parser(tr)
300
+ args = parser.parse_args(args_list)
301
+ except SystemExit as exc: # --help, --version and usage errors
302
+ return int(exc.code) if isinstance(exc.code, int) else EXIT_USAGE
303
+ try:
304
+ if args.command == "demo":
305
+ return run_demo(tr)
306
+ handler = {"stamp": _cmd_stamp, "check": _cmd_check, "show": _cmd_show, "migrate": _cmd_migrate}
307
+ return handler[args.command](args, tr)
308
+ except ValueError as exc:
309
+ _error(tr("err.generic", message=exc))
310
+ return EXIT_USAGE
311
+ except (EmbedstampError, ImportError, OSError) as exc:
312
+ _error(tr("err.generic", message=exc))
313
+ return EXIT_ERROR
314
+
315
+
316
+ if __name__ == "__main__": # pragma: no cover
317
+ sys.exit(main())
@@ -0,0 +1,160 @@
1
+ Simmer the tomato sauce with garlic and basil for twenty minutes before adding pasta.
2
+ Fresh bread needs yeast, flour, water and a long slow rise in a warm kitchen.
3
+ Sear the steak in a hot cast iron pan and let it rest before slicing.
4
+ A pinch of salt makes chocolate cookies taste sweeter and richer.
5
+ Roast vegetables at high heat so the edges caramelize and turn golden.
6
+ Whisk eggs with milk and fold gently to make a fluffy omelette.
7
+ Marinate chicken in yogurt and spices overnight for tender grilled skewers.
8
+ Rice should be rinsed until the water runs clear, then steamed with a tight lid.
9
+ Knead the pizza dough until smooth and stretch it thin before baking in a very hot oven.
10
+ Soup tastes better the next day because the flavors have time to blend.
11
+ Sharpen your kitchen knife regularly because a dull blade slips and cuts fingers.
12
+ Toast spices in a dry pan to release their aroma before grinding.
13
+ Poach salmon gently in broth with lemon slices and fresh dill.
14
+ Use a thermometer to bake a cake evenly and avoid a raw center.
15
+ Pickle cucumbers in vinegar, sugar and mustard seeds for a crunchy snack.
16
+ Fry dumplings until the bottom is crisp, then add water and steam them.
17
+ Slow cooked beef stew with carrots and potatoes warms a cold winter evening.
18
+ Mix olive oil, lemon juice and herbs into a bright salad dressing.
19
+ Caramelize onions slowly over low heat for a sweet base in French onion soup.
20
+ Let the dough proof twice for a lighter crumb in homemade bread rolls.
21
+ Tomato seedlings need bright light and warm soil to grow strong stems.
22
+ Compost kitchen scraps and leaves to feed your garden beds with rich humus.
23
+ Water the lawn early in the morning so the sun does not evaporate it.
24
+ Prune rose bushes in late winter to encourage healthy blooms in spring.
25
+ Mulch around young trees keeps the soil moist and suppresses weeds.
26
+ Sunflowers follow the sun and attract bees to the vegetable garden.
27
+ Plant garlic cloves in autumn and harvest the bulbs the following summer.
28
+ Aphids on the leaves can be washed off with soapy water or ladybugs.
29
+ Raised garden beds drain well and warm up early in the growing season.
30
+ Rotate crops each year to keep soil healthy and reduce plant disease.
31
+ Herbs like basil and mint grow well in pots on a sunny windowsill.
32
+ Fertilize the flower beds with compost tea during the blooming season.
33
+ Bulbs such as tulips and daffodils must be planted before the first frost.
34
+ Thin carrot seedlings so each root has room to swell in loose soil.
35
+ Hang a bird feeder near the garden to welcome sparrows and finches.
36
+ Greenhouses protect delicate seedlings from frost and strong wind.
37
+ Dead heading faded flowers keeps petunias blooming all summer long.
38
+ Drip irrigation delivers water to the roots and saves a lot of water.
39
+ Cover strawberry plants with a net so birds cannot steal the ripe fruit.
40
+ Soil acidity affects blueberries, so test the pH before you plant shrubs.
41
+ Jupiter is the largest planet and has dozens of moons orbiting around it.
42
+ A telescope with a wide aperture gathers more light from faint galaxies.
43
+ The Milky Way is a spiral galaxy containing hundreds of billions of stars.
44
+ A lunar eclipse happens when Earth passes between the sun and the moon.
45
+ Comets grow bright tails when ice melts as they approach the sun.
46
+ Saturn rings are made of ice particles and rocky debris orbiting the planet.
47
+ Black holes bend light because their gravity is so strong that nothing escapes.
48
+ Astronomers measure the distance to stars using parallax and bright supernovae.
49
+ Mars has polar ice caps and the tallest volcano in the solar system.
50
+ A light year is the distance light travels in one year through space.
51
+ Meteor showers appear when Earth crosses the dusty trail of a comet.
52
+ Neutron stars are the dense remains of massive stars after a supernova.
53
+ The International Space Station orbits Earth every ninety minutes.
54
+ Nebulae are clouds of gas and dust where new stars are born.
55
+ Rockets burn fuel to reach orbital speed and escape the atmosphere.
56
+ Telescopes in orbit avoid the blur caused by air above our planet.
57
+ The moon causes ocean tides with its gravitational pull on the sea.
58
+ Exoplanets are found when a star dims slightly as a planet crosses its disk.
59
+ Dark matter holds galaxies together though no telescope can see it directly.
60
+ Venus is hotter than Mercury because thick clouds trap heat in its atmosphere.
61
+ An emergency fund should cover three to six months of living expenses.
62
+ Compound interest makes savings grow faster the longer you leave them invested.
63
+ Index funds offer low fees and broad diversification across many companies.
64
+ A budget lists income and expenses so you can see where money goes each month.
65
+ Pay off credit card debt first because its interest rate is usually very high.
66
+ Inflation reduces the purchasing power of cash held in a bank account.
67
+ A mortgage spreads the cost of a house over decades with monthly payments.
68
+ Diversify your portfolio between stocks, bonds and cash to reduce risk.
69
+ Tax deductions lower your taxable income and the amount you owe each year.
70
+ Retirement accounts let your investments grow with tax advantages.
71
+ A credit score rises when you pay bills on time and keep balances low.
72
+ Dividends are shares of company profit paid to stockholders each quarter.
73
+ Insurance protects your savings from large unexpected medical or car bills.
74
+ Track subscriptions monthly because small recurring fees add up quickly.
75
+ Rent versus buy depends on mortgage rates, home prices and how long you stay.
76
+ Bond prices fall when interest rates rise, which surprises many investors.
77
+ Set up automatic transfers so savings happen before you can spend the money.
78
+ Negotiate your salary using market data and a list of your achievements.
79
+ Currency exchange rates change daily and affect the cost of foreign travel.
80
+ A sinking fund saves a little each month for a planned large purchase.
81
+ Good hiking boots with ankle support prevent blisters on long mountain trails.
82
+ Pack water, a map, a headlamp and snacks before heading up the trail.
83
+ Check the weather forecast because storms on a summit can be dangerous.
84
+ Trekking poles reduce strain on your knees during steep descents.
85
+ Camp at least seventy meters from rivers and leave no trace behind.
86
+ A compass and a paper map still work when your phone battery dies.
87
+ Start the climb early to reach the summit before afternoon clouds roll in.
88
+ Layered clothing lets you adjust to cold mornings and warm afternoons on the trail.
89
+ Wool socks keep your feet warm and dry when crossing a wet valley.
90
+ Backpacks should carry most of the weight on your hips instead of your shoulders.
91
+ Wild camping needs a light tent, a sleeping bag and a small stove.
92
+ Trail markers painted on rocks and trees show the path through the forest.
93
+ Altitude sickness causes headaches, so climb slowly and drink plenty of water.
94
+ Following a ridge gives wide views of lakes, valleys and distant peaks.
95
+ Bring a first aid kit with bandages for blisters and sprains on the trail.
96
+ Autumn hikes reward you with colorful leaves and quiet mountain paths.
97
+ Filter stream water or use tablets before drinking it on a backcountry trip.
98
+ Share your route with a friend before a solo hike into remote country.
99
+ Waterfalls are most powerful in spring when snow melt fills the rivers.
100
+ Night hiking with a headlamp lets you see stars far from city lights.
101
+ A function should do one thing well and have a clear descriptive name.
102
+ Unit tests catch bugs early and make refactoring safer for the whole team.
103
+ Version control with git records every change to the source code.
104
+ A hash map gives constant time lookups for keys in most programs.
105
+ Recursion solves a problem by calling the same function on smaller input.
106
+ Code review finds mistakes and spreads knowledge among developers.
107
+ Type hints help editors find bugs in Python code before you run it.
108
+ Caching stores expensive results so the program does not recompute them.
109
+ An API endpoint accepts a request and returns a JSON response to the client.
110
+ Database indexes speed up queries but slow down writes slightly.
111
+ Logging errors with context makes debugging production servers much easier.
112
+ Continuous integration runs the test suite automatically on every commit.
113
+ A compiler translates source code into machine instructions for the processor.
114
+ Asynchronous code lets a program wait for network calls without blocking.
115
+ Refactoring improves the structure of code without changing its behavior.
116
+ Docker containers package an application with its libraries for consistent deployment.
117
+ SQL joins combine rows from two tables using a shared column.
118
+ Memory leaks happen when a program keeps references to objects it no longer needs.
119
+ Encryption protects passwords and personal data stored on the server.
120
+ Sorting algorithms such as quicksort and mergesort run in logarithmic depth.
121
+ Regular aerobic exercise strengthens the heart and improves sleep quality.
122
+ Adults need seven to nine hours of sleep to recover and concentrate well.
123
+ Protein helps muscles repair after a hard strength training workout.
124
+ Stretching before running warms the muscles and lowers the risk of injury.
125
+ Drink water throughout the day because dehydration causes tiredness and headaches.
126
+ Vegetables, fruit and whole grains supply fiber that supports digestion.
127
+ Meditation and slow breathing reduce stress and lower blood pressure.
128
+ Walking thirty minutes a day improves mood and helps control body weight.
129
+ Vitamin D from sunlight keeps bones strong, especially during the winter.
130
+ Too much sugar raises the risk of diabetes and tooth decay.
131
+ Rest days let the body rebuild muscle between intense gym sessions.
132
+ Good posture at a desk prevents back pain and neck stiffness.
133
+ Regular health checkups can find high cholesterol before symptoms appear.
134
+ Yoga improves balance and flexibility and calms the mind after work.
135
+ Interval training alternates fast sprints with slow recovery to burn calories.
136
+ Limit caffeine in the evening so it does not disturb your sleep.
137
+ Cycling is a low impact exercise that is gentle on the joints.
138
+ Washing hands often with soap prevents the spread of colds and flu.
139
+ A balanced breakfast with oats, fruit and nuts keeps energy steady.
140
+ Warm up for ten minutes before lifting heavy weights at the gym.
141
+ A piano has eighty eight keys and can play melody and harmony together.
142
+ Guitar chords such as G, C and D are the first ones beginners learn.
143
+ A metronome keeps a steady tempo while you practice difficult passages.
144
+ Jazz musicians improvise solos over chord progressions in the middle of a song.
145
+ The violin is tuned in perfect fifths and played with a horsehair bow.
146
+ Drummers keep the beat with the kick drum and the snare drum.
147
+ A major scale sounds bright while a minor scale sounds sad.
148
+ Choirs blend soprano, alto, tenor and bass voices into rich harmony.
149
+ Reading sheet music means following notes, rhythm and dynamics on the staff.
150
+ A good microphone and a quiet room improve a home recording dramatically.
151
+ Orchestras are led by a conductor who shapes tempo and expression.
152
+ Synthesizers create sounds by shaping electronic waveforms with filters.
153
+ Practice scales slowly every day to build finger strength and accuracy.
154
+ A bass guitar anchors the groove between the drums and the harmony.
155
+ Songwriters often start with a chord progression and add a melody on top.
156
+ Vinyl records are played with a needle that follows grooves in the plastic.
157
+ Singers warm up their voices with humming and gentle lip trills.
158
+ Folk music passes simple melodies from generation to generation by ear.
159
+ A flute produces sound when air splits across the edge of the mouthpiece.
160
+ Concert halls are designed so that every seat can hear the orchestra clearly.
@@ -0,0 +1,16 @@
1
+ how long should dough rise for bread
2
+ best way to cook steak in a pan
3
+ when to plant garlic and tulip bulbs
4
+ how to protect tomato seedlings and strawberries
5
+ why do comets grow bright tails near the sun
6
+ what is inside the rings of Saturn
7
+ how much money should an emergency fund hold
8
+ why bond prices fall when interest rates rise
9
+ what to pack for a mountain hike
10
+ how to avoid blisters and altitude sickness on the trail
11
+ why write unit tests before refactoring code
12
+ how do database indexes and caching speed up programs
13
+ how much sleep and exercise keep the heart healthy
14
+ how to reduce stress with breathing and yoga
15
+ how do beginners practice guitar chords and scales
16
+ what does a conductor do in an orchestra