glitchlings 0.4.5__cp311-cp311-win_amd64.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.

Potentially problematic release.


This version of glitchlings might be problematic. Click here for more details.

Files changed (53) hide show
  1. glitchlings/__init__.py +71 -0
  2. glitchlings/__main__.py +8 -0
  3. glitchlings/_zoo_rust.cp311-win_amd64.pyd +0 -0
  4. glitchlings/compat.py +282 -0
  5. glitchlings/config.py +386 -0
  6. glitchlings/config.toml +3 -0
  7. glitchlings/data/__init__.py +1 -0
  8. glitchlings/data/hokey_assets.json +193 -0
  9. glitchlings/dlc/__init__.py +7 -0
  10. glitchlings/dlc/_shared.py +153 -0
  11. glitchlings/dlc/huggingface.py +81 -0
  12. glitchlings/dlc/prime.py +254 -0
  13. glitchlings/dlc/pytorch.py +166 -0
  14. glitchlings/dlc/pytorch_lightning.py +209 -0
  15. glitchlings/lexicon/__init__.py +192 -0
  16. glitchlings/lexicon/_cache.py +108 -0
  17. glitchlings/lexicon/data/default_vector_cache.json +82 -0
  18. glitchlings/lexicon/metrics.py +162 -0
  19. glitchlings/lexicon/vector.py +652 -0
  20. glitchlings/lexicon/wordnet.py +228 -0
  21. glitchlings/main.py +364 -0
  22. glitchlings/util/__init__.py +195 -0
  23. glitchlings/util/adapters.py +27 -0
  24. glitchlings/util/hokey_generator.py +144 -0
  25. glitchlings/util/stretch_locator.py +140 -0
  26. glitchlings/util/stretchability.py +375 -0
  27. glitchlings/zoo/__init__.py +172 -0
  28. glitchlings/zoo/_ocr_confusions.py +32 -0
  29. glitchlings/zoo/_rate.py +131 -0
  30. glitchlings/zoo/_rust_extensions.py +143 -0
  31. glitchlings/zoo/_sampling.py +54 -0
  32. glitchlings/zoo/_text_utils.py +100 -0
  33. glitchlings/zoo/adjax.py +128 -0
  34. glitchlings/zoo/apostrofae.py +127 -0
  35. glitchlings/zoo/assets/__init__.py +0 -0
  36. glitchlings/zoo/assets/apostrofae_pairs.json +32 -0
  37. glitchlings/zoo/core.py +582 -0
  38. glitchlings/zoo/hokey.py +173 -0
  39. glitchlings/zoo/jargoyle.py +335 -0
  40. glitchlings/zoo/mim1c.py +109 -0
  41. glitchlings/zoo/ocr_confusions.tsv +30 -0
  42. glitchlings/zoo/redactyl.py +193 -0
  43. glitchlings/zoo/reduple.py +148 -0
  44. glitchlings/zoo/rushmore.py +153 -0
  45. glitchlings/zoo/scannequin.py +171 -0
  46. glitchlings/zoo/typogre.py +231 -0
  47. glitchlings/zoo/zeedub.py +185 -0
  48. glitchlings-0.4.5.dist-info/METADATA +648 -0
  49. glitchlings-0.4.5.dist-info/RECORD +53 -0
  50. glitchlings-0.4.5.dist-info/WHEEL +5 -0
  51. glitchlings-0.4.5.dist-info/entry_points.txt +2 -0
  52. glitchlings-0.4.5.dist-info/licenses/LICENSE +201 -0
  53. glitchlings-0.4.5.dist-info/top_level.txt +1 -0
@@ -0,0 +1,652 @@
1
+ """Vector-space lexicon implementation and cache building utilities."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import importlib
7
+ import importlib.util
8
+ import json
9
+ import math
10
+ import sys
11
+ from pathlib import Path
12
+ from typing import Any, Callable, Iterable, Iterator, Mapping, MutableMapping, Sequence
13
+
14
+ from . import LexiconBackend
15
+ from ._cache import CacheSnapshot
16
+ from ._cache import load_cache as _load_cache_file
17
+ from ._cache import write_cache as _write_cache_file
18
+
19
+ # Minimum number of neighbors to consider for similarity queries
20
+ MIN_NEIGHBORS = 1
21
+
22
+
23
+ def _cosine_similarity(vector_a: Sequence[float], vector_b: Sequence[float]) -> float:
24
+ """Return the cosine similarity between two dense vectors."""
25
+ dot_product = 0.0
26
+ norm_a = 0.0
27
+ norm_b = 0.0
28
+ for value_a, value_b in zip(vector_a, vector_b):
29
+ dot_product += value_a * value_b
30
+ norm_a += value_a * value_a
31
+ norm_b += value_b * value_b
32
+
33
+ if norm_a == 0.0 or norm_b == 0.0:
34
+ return 0.0
35
+
36
+ magnitude = math.sqrt(norm_a) * math.sqrt(norm_b)
37
+ if magnitude == 0.0:
38
+ return 0.0
39
+
40
+ return dot_product / magnitude
41
+
42
+
43
+ class _Adapter:
44
+ """Base adapter that exposes nearest-neighbour queries for embeddings."""
45
+
46
+ def contains(self, word: str) -> bool:
47
+ raise NotImplementedError
48
+
49
+ def nearest(self, word: str, *, limit: int) -> list[tuple[str, float]]:
50
+ raise NotImplementedError
51
+
52
+ def iter_keys(self) -> Iterator[str]:
53
+ raise NotImplementedError
54
+
55
+
56
+ class _MappingAdapter(_Adapter):
57
+ """Adapter for in-memory ``Mapping[str, Sequence[float]]`` embeddings."""
58
+
59
+ def __init__(self, mapping: Mapping[str, Sequence[float]]) -> None:
60
+ self._mapping = mapping
61
+
62
+ def contains(self, word: str) -> bool:
63
+ return word in self._mapping
64
+
65
+ def nearest(self, word: str, *, limit: int) -> list[tuple[str, float]]:
66
+ if word not in self._mapping:
67
+ return []
68
+
69
+ target_vector = self._mapping[word]
70
+ scores: list[tuple[str, float]] = []
71
+ for candidate, candidate_vector in self._mapping.items():
72
+ if candidate == word:
73
+ continue
74
+ similarity = _cosine_similarity(target_vector, candidate_vector)
75
+ if similarity == 0.0:
76
+ continue
77
+ scores.append((candidate, similarity))
78
+
79
+ scores.sort(key=lambda pair: pair[1], reverse=True)
80
+ if limit < len(scores):
81
+ return scores[:limit]
82
+ return scores
83
+
84
+ def iter_keys(self) -> Iterator[str]:
85
+ return iter(self._mapping.keys())
86
+
87
+
88
+ class _GensimAdapter(_Adapter):
89
+ """Adapter that proxies to ``gensim`` ``KeyedVectors`` instances."""
90
+
91
+ def __init__(self, keyed_vectors: Any) -> None:
92
+ self._keyed_vectors = keyed_vectors
93
+
94
+ def contains(self, word: str) -> bool:
95
+ return word in self._keyed_vectors.key_to_index
96
+
97
+ def nearest(self, word: str, *, limit: int) -> list[tuple[str, float]]:
98
+ try:
99
+ raw_neighbors = self._keyed_vectors.most_similar(word, topn=limit)
100
+ except KeyError:
101
+ return []
102
+
103
+ return [(candidate, float(score)) for candidate, score in raw_neighbors]
104
+
105
+ def iter_keys(self) -> Iterator[str]:
106
+ return iter(self._keyed_vectors.key_to_index.keys())
107
+
108
+
109
+ class _SpaCyAdapter(_Adapter):
110
+ """Adapter that interacts with spaCy ``Language`` objects."""
111
+
112
+ def __init__(self, language: Any) -> None:
113
+ self._language = language
114
+ self._vectors = language.vocab.vectors
115
+ spec = importlib.util.find_spec("numpy")
116
+ if spec is None:
117
+ raise RuntimeError("spaCy vector lexicons require NumPy to be installed.")
118
+ self._numpy = importlib.import_module("numpy")
119
+
120
+ def contains(self, word: str) -> bool:
121
+ strings = self._language.vocab.strings
122
+ return word in strings and strings[word] in self._vectors
123
+
124
+ def nearest(self, word: str, *, limit: int) -> list[tuple[str, float]]:
125
+ strings = self._language.vocab.strings
126
+ if word not in strings:
127
+ return []
128
+
129
+ key = strings[word]
130
+ if key not in self._vectors:
131
+ return []
132
+
133
+ vector = self._vectors.get(key)
134
+ query = self._numpy.asarray([vector])
135
+ keys, scores = self._vectors.most_similar(query, n=limit)
136
+ candidates: list[tuple[str, float]] = []
137
+ for candidate_key, score in zip(keys[0], scores[0]):
138
+ candidate_word = strings[candidate_key]
139
+ if candidate_word == word:
140
+ continue
141
+ candidates.append((candidate_word, float(score)))
142
+ return candidates
143
+
144
+ def iter_keys(self) -> Iterator[str]:
145
+ strings = self._language.vocab.strings
146
+ for key in self._vectors.keys():
147
+ yield strings[key]
148
+
149
+
150
+ def _load_json_vectors(path: Path) -> Mapping[str, Sequence[float]]:
151
+ """Load embeddings from a JSON mapping of token to vector list."""
152
+ with path.open("r", encoding="utf8") as handle:
153
+ payload = json.load(handle)
154
+
155
+ if not isinstance(payload, Mapping):
156
+ raise RuntimeError("Vector JSON payload must map tokens to dense vectors.")
157
+
158
+ validated: dict[str, list[float]] = {}
159
+ for token, raw_vector in payload.items():
160
+ if not isinstance(token, str):
161
+ raise RuntimeError("Vector JSON keys must be strings.")
162
+ if not isinstance(raw_vector, Sequence):
163
+ raise RuntimeError(f"Vector for '{token}' must be a sequence of floats.")
164
+ validated[token] = [float(value) for value in raw_vector]
165
+
166
+ return validated
167
+
168
+
169
+ def _load_gensim_vectors(path: Path, *, binary: bool | None = None) -> Any:
170
+ """Load ``gensim`` vectors from ``path``."""
171
+ if importlib.util.find_spec("gensim") is None:
172
+ raise RuntimeError("The gensim package is required to load keyed vector embeddings.")
173
+
174
+ keyed_vectors_module = importlib.import_module("gensim.models.keyedvectors")
175
+ if binary is None:
176
+ binary = path.suffix in {".bin", ".gz"}
177
+
178
+ if path.suffix in {".kv", ".kv2"}:
179
+ return keyed_vectors_module.KeyedVectors.load(str(path), mmap="r")
180
+
181
+ return keyed_vectors_module.KeyedVectors.load_word2vec_format(str(path), binary=binary)
182
+
183
+
184
+ def _load_spacy_language(model_name: str) -> Any:
185
+ """Load a spaCy language pipeline by name."""
186
+ if importlib.util.find_spec("spacy") is None:
187
+ raise RuntimeError(
188
+ "spaCy is required to use spaCy-backed vector lexicons; install the 'vectors' extra."
189
+ )
190
+
191
+ spacy_module = importlib.import_module("spacy")
192
+ return spacy_module.load(model_name)
193
+
194
+
195
+ def _load_sentence_transformer(model_name: str) -> Any:
196
+ """Return a ``SentenceTransformer`` instance for ``model_name``."""
197
+
198
+ if importlib.util.find_spec("sentence_transformers") is None:
199
+ raise RuntimeError(
200
+ "sentence-transformers is required for this source; install the 'st' extra."
201
+ )
202
+
203
+ module = importlib.import_module("sentence_transformers")
204
+ try:
205
+ model_cls = getattr(module, "SentenceTransformer")
206
+ except AttributeError as exc: # pragma: no cover - defensive
207
+ raise RuntimeError("sentence-transformers does not expose SentenceTransformer") from exc
208
+
209
+ return model_cls(model_name)
210
+
211
+
212
+ def _build_sentence_transformer_embeddings(
213
+ model_name: str, tokens: Sequence[str]
214
+ ) -> Mapping[str, Sequence[float]]:
215
+ """Return embeddings for ``tokens`` using ``model_name``."""
216
+
217
+ if not tokens:
218
+ return {}
219
+
220
+ model = _load_sentence_transformer(model_name)
221
+
222
+ unique_tokens: list[str] = []
223
+ seen: set[str] = set()
224
+ for token in tokens:
225
+ normalized = token.strip()
226
+ if not normalized or normalized in seen:
227
+ continue
228
+ unique_tokens.append(normalized)
229
+ seen.add(normalized)
230
+
231
+ if not unique_tokens:
232
+ return {}
233
+
234
+ embeddings = model.encode(
235
+ unique_tokens,
236
+ batch_size=64,
237
+ normalize_embeddings=True,
238
+ convert_to_numpy=True,
239
+ )
240
+
241
+ return {
242
+ token: [float(value) for value in vector]
243
+ for token, vector in zip(unique_tokens, embeddings, strict=True)
244
+ }
245
+
246
+
247
+ def _resolve_source(source: Any | None) -> _Adapter | None:
248
+ """Return an adapter instance for ``source`` if possible."""
249
+ if source is None:
250
+ return None
251
+
252
+ if isinstance(source, _Adapter):
253
+ return source
254
+
255
+ if isinstance(source, Mapping):
256
+ return _MappingAdapter(source)
257
+
258
+ module_name = type(source).__module__
259
+ if module_name.startswith("gensim") and hasattr(source, "most_similar"):
260
+ return _GensimAdapter(source)
261
+
262
+ if module_name.startswith("spacy") and hasattr(source, "vocab"):
263
+ return _SpaCyAdapter(source)
264
+
265
+ if isinstance(source, (str, Path)):
266
+ text_source = str(source)
267
+ if text_source.startswith("spacy:"):
268
+ model = text_source.split(":", 1)[1]
269
+ return _SpaCyAdapter(_load_spacy_language(model))
270
+
271
+ resolved_path = Path(text_source)
272
+ if not resolved_path.exists():
273
+ raise RuntimeError(f"Vector source '{text_source}' does not exist.")
274
+
275
+ suffix = resolved_path.suffix.lower()
276
+ if suffix == ".json":
277
+ return _MappingAdapter(_load_json_vectors(resolved_path))
278
+
279
+ if suffix in {".kv", ".kv2", ".bin", ".gz", ".txt", ".vec"}:
280
+ binary_flag = False if suffix in {".txt", ".vec"} else None
281
+ return _GensimAdapter(_load_gensim_vectors(resolved_path, binary=binary_flag))
282
+
283
+ if hasattr(source, "most_similar") and hasattr(source, "key_to_index"):
284
+ return _GensimAdapter(source)
285
+
286
+ if hasattr(source, "vocab") and hasattr(source.vocab, "vectors"):
287
+ return _SpaCyAdapter(source)
288
+
289
+ raise RuntimeError("Unsupported vector source supplied to VectorLexicon.")
290
+
291
+
292
+ class VectorLexicon(LexiconBackend):
293
+ """Lexicon implementation backed by dense word embeddings."""
294
+
295
+ def __init__(
296
+ self,
297
+ *,
298
+ source: Any | None = None,
299
+ cache: Mapping[str, Sequence[str]] | None = None,
300
+ cache_path: str | Path | None = None,
301
+ max_neighbors: int = 50,
302
+ min_similarity: float = 0.0,
303
+ normalizer: Callable[[str], str] | None = None,
304
+ case_sensitive: bool = False,
305
+ seed: int | None = None,
306
+ ) -> None:
307
+ """Initialise the lexicon with an embedding ``source`` and optional cache."""
308
+ super().__init__(seed=seed)
309
+ self._adapter = _resolve_source(source)
310
+ self._max_neighbors = max(MIN_NEIGHBORS, max_neighbors)
311
+ self._min_similarity = min_similarity
312
+ self._cache: MutableMapping[str, list[str]] = {}
313
+ self._cache_path: Path | None
314
+ self._cache_checksum: str | None = None
315
+ if cache_path is not None:
316
+ path = Path(cache_path)
317
+ snapshot = _load_cache_file(path)
318
+ self._cache.update(snapshot.entries)
319
+ self._cache_checksum = snapshot.checksum
320
+ self._cache_path = path
321
+ else:
322
+ self._cache_path = None
323
+ if cache is not None:
324
+ for key, values in cache.items():
325
+ self._cache[str(key)] = [str(value) for value in values]
326
+ self._cache_dirty = False
327
+ self._case_sensitive = case_sensitive
328
+ if normalizer is not None:
329
+ self._lookup_normalizer: Callable[[str], str] = normalizer
330
+ self._dedupe_normalizer: Callable[[str], str] = normalizer
331
+ elif case_sensitive:
332
+ self._lookup_normalizer = str.lower
333
+ self._dedupe_normalizer = lambda value: value
334
+ else:
335
+ self._lookup_normalizer = str.lower
336
+ self._dedupe_normalizer = str.lower
337
+
338
+ def _normalize_for_lookup(self, word: str) -> str:
339
+ return self._lookup_normalizer(word)
340
+
341
+ def _normalize_for_dedupe(self, word: str) -> str:
342
+ return self._dedupe_normalizer(word)
343
+
344
+ def _fetch_neighbors(
345
+ self, *, original: str, normalized: str, limit: int
346
+ ) -> list[tuple[str, float]]:
347
+ if self._adapter is None:
348
+ return []
349
+
350
+ attempts = [original]
351
+ if normalized != original:
352
+ attempts.append(normalized)
353
+
354
+ collected: list[tuple[str, float]] = []
355
+ seen: set[str] = set()
356
+ for token in attempts:
357
+ neighbors = self._adapter.nearest(token, limit=limit)
358
+ for candidate, score in neighbors:
359
+ if candidate in seen:
360
+ continue
361
+ collected.append((candidate, score))
362
+ seen.add(candidate)
363
+ if len(collected) >= limit:
364
+ break
365
+
366
+ if len(collected) > limit:
367
+ return collected[:limit]
368
+ return collected
369
+
370
+ def _ensure_cached(
371
+ self, *, original: str, normalized: str, limit: int | None = None
372
+ ) -> list[str]:
373
+ cache_key = normalized if not self._case_sensitive else original
374
+ if cache_key in self._cache:
375
+ return self._cache[cache_key]
376
+
377
+ neighbor_limit = self._max_neighbors if limit is None else max(MIN_NEIGHBORS, limit)
378
+ neighbors = self._fetch_neighbors(
379
+ original=original, normalized=normalized, limit=neighbor_limit
380
+ )
381
+ synonyms: list[str] = []
382
+ seen_candidates: set[str] = set()
383
+ original_lookup = normalized
384
+ original_dedupe = self._normalize_for_dedupe(original)
385
+ for candidate, similarity in neighbors:
386
+ if similarity < self._min_similarity:
387
+ continue
388
+ if self._case_sensitive:
389
+ if candidate == original:
390
+ continue
391
+ dedupe_key = self._normalize_for_dedupe(candidate)
392
+ if dedupe_key == original_dedupe:
393
+ continue
394
+ else:
395
+ candidate_lookup = self._normalize_for_lookup(candidate)
396
+ if candidate_lookup == original_lookup:
397
+ continue
398
+ dedupe_key = candidate_lookup
399
+ if dedupe_key in seen_candidates:
400
+ continue
401
+ seen_candidates.add(dedupe_key)
402
+ synonyms.append(candidate)
403
+
404
+ self._cache[cache_key] = synonyms
405
+ if self._cache_path is not None:
406
+ self._cache_dirty = True
407
+ return synonyms
408
+
409
+ def get_synonyms(self, word: str, pos: str | None = None, n: int = 5) -> list[str]:
410
+ """Return up to ``n`` deterministic synonyms drawn from the embedding cache."""
411
+ normalized = self._normalize_for_lookup(word)
412
+ synonyms = self._ensure_cached(original=word, normalized=normalized)
413
+ return self._deterministic_sample(synonyms, limit=n, word=word, pos=pos)
414
+
415
+ def precompute(self, word: str, *, limit: int | None = None) -> list[str]:
416
+ """Populate the cache for ``word`` and return the stored synonyms."""
417
+ normalized = self._normalize_for_lookup(word)
418
+ return list(self._ensure_cached(original=word, normalized=normalized, limit=limit))
419
+
420
+ def iter_vocabulary(self) -> Iterator[str]:
421
+ """Yield vocabulary tokens from the underlying embedding source."""
422
+ if self._adapter is None:
423
+ return iter(())
424
+ return self._adapter.iter_keys()
425
+
426
+ def export_cache(self) -> dict[str, list[str]]:
427
+ """Return a copy of the in-memory synonym cache."""
428
+ return {key: list(values) for key, values in self._cache.items()}
429
+
430
+ @classmethod
431
+ def load_cache(cls, path: str | Path) -> CacheSnapshot:
432
+ """Load and validate a cache file for reuse."""
433
+ return _load_cache_file(Path(path))
434
+
435
+ def save_cache(self, path: str | Path | None = None) -> Path:
436
+ """Persist the current cache to disk, returning the path used."""
437
+ if path is None:
438
+ if self._cache_path is None:
439
+ raise RuntimeError("No cache path supplied to VectorLexicon.")
440
+ target = self._cache_path
441
+ else:
442
+ target = Path(path)
443
+ self._cache_path = target
444
+
445
+ snapshot = _write_cache_file(target, self._cache)
446
+ self._cache_checksum = snapshot.checksum
447
+ self._cache_dirty = False
448
+ return target
449
+
450
+ def supports_pos(self, pos: str | None) -> bool:
451
+ """Always return ``True`` because vector sources do not encode POS metadata."""
452
+ return True
453
+
454
+ def __repr__(self) -> str: # pragma: no cover - debug helper
455
+ source_name = self._adapter.__class__.__name__ if self._adapter else "None"
456
+ return (
457
+ f"VectorLexicon(source={source_name}, max_neighbors={self._max_neighbors}, "
458
+ f"seed={self.seed!r})"
459
+ )
460
+
461
+
462
+ def build_vector_cache(
463
+ *,
464
+ source: Any,
465
+ words: Iterable[str],
466
+ output_path: Path,
467
+ max_neighbors: int = 50,
468
+ min_similarity: float = 0.0,
469
+ case_sensitive: bool = False,
470
+ seed: int | None = None,
471
+ normalizer: Callable[[str], str] | None = None,
472
+ ) -> Path:
473
+ """Generate a synonym cache for ``words`` using ``source`` embeddings."""
474
+ lexicon = VectorLexicon(
475
+ source=source,
476
+ max_neighbors=max_neighbors,
477
+ min_similarity=min_similarity,
478
+ case_sensitive=case_sensitive,
479
+ normalizer=normalizer,
480
+ seed=seed,
481
+ )
482
+
483
+ for word in words:
484
+ lexicon.precompute(word)
485
+
486
+ return lexicon.save_cache(output_path)
487
+
488
+
489
+ def load_vector_source(spec: str) -> Any:
490
+ """Resolve ``spec`` strings for the cache-building CLI."""
491
+ if spec.startswith("spacy:"):
492
+ model_name = spec.split(":", 1)[1]
493
+ return _load_spacy_language(model_name)
494
+
495
+ path = Path(spec).expanduser()
496
+ if not path.exists():
497
+ raise RuntimeError(f"Vector source '{spec}' does not exist.")
498
+
499
+ if path.suffix.lower() == ".json":
500
+ return _load_json_vectors(path)
501
+
502
+ return _load_gensim_vectors(path)
503
+
504
+
505
+ def _parse_cli(argv: Sequence[str] | None = None) -> argparse.Namespace:
506
+ parser = argparse.ArgumentParser(
507
+ prog="python -m glitchlings.lexicon.vector",
508
+ description="Precompute synonym caches for the vector lexicon backend.",
509
+ )
510
+ parser.add_argument(
511
+ "--source",
512
+ required=True,
513
+ help=(
514
+ "Vector source specification. Use 'spacy:<model>' for spaCy pipelines, "
515
+ "'sentence-transformers:<model>' for HuggingFace checkpoints (requires --tokens), "
516
+ "or provide a path to a gensim KeyedVectors/word2vec file."
517
+ ),
518
+ )
519
+ parser.add_argument(
520
+ "--output",
521
+ required=True,
522
+ type=Path,
523
+ help="Path to the JSON file that will receive the synonym cache.",
524
+ )
525
+ parser.add_argument(
526
+ "--tokens",
527
+ type=Path,
528
+ help="Optional newline-delimited vocabulary file to restrict generation.",
529
+ )
530
+ parser.add_argument(
531
+ "--max-neighbors",
532
+ type=int,
533
+ default=50,
534
+ help="Number of nearest neighbours to cache per token (default: 50).",
535
+ )
536
+ parser.add_argument(
537
+ "--min-similarity",
538
+ type=float,
539
+ default=0.0,
540
+ help="Minimum cosine similarity required to keep a synonym (default: 0.0).",
541
+ )
542
+ parser.add_argument(
543
+ "--seed",
544
+ type=int,
545
+ help="Optional deterministic seed to bake into the resulting cache.",
546
+ )
547
+ parser.add_argument(
548
+ "--case-sensitive",
549
+ action="store_true",
550
+ help="Preserve original casing instead of lower-casing cache keys.",
551
+ )
552
+ parser.add_argument(
553
+ "--normalizer",
554
+ choices=["lower", "identity"],
555
+ default="lower",
556
+ help="Token normalization strategy for cache keys (default: lower).",
557
+ )
558
+ parser.add_argument(
559
+ "--overwrite",
560
+ action="store_true",
561
+ help="Allow overwriting an existing cache file.",
562
+ )
563
+ parser.add_argument(
564
+ "--limit",
565
+ type=int,
566
+ help="Optional maximum number of tokens to process.",
567
+ )
568
+ return parser.parse_args(argv)
569
+
570
+
571
+ def _iter_tokens_from_file(path: Path) -> Iterator[str]:
572
+ with path.open("r", encoding="utf8") as handle:
573
+ for line in handle:
574
+ token = line.strip()
575
+ if token:
576
+ yield token
577
+
578
+
579
+ def main(argv: Sequence[str] | None = None) -> int:
580
+ """Entry-point for ``python -m glitchlings.lexicon.vector``."""
581
+ args = _parse_cli(argv)
582
+
583
+ if args.output.exists() and not args.overwrite:
584
+ raise SystemExit(
585
+ f"Refusing to overwrite existing cache at {args.output!s}; pass --overwrite."
586
+ )
587
+
588
+ if args.normalizer == "lower":
589
+ normalizer: Callable[[str], str] | None = None if args.case_sensitive else str.lower
590
+ else:
591
+
592
+ def _identity(value: str) -> str:
593
+ return value
594
+
595
+ normalizer = _identity
596
+
597
+ tokens_from_file: list[str] | None = None
598
+ if args.tokens is not None:
599
+ tokens_from_file = list(_iter_tokens_from_file(args.tokens))
600
+ if args.limit is not None:
601
+ tokens_from_file = tokens_from_file[: args.limit]
602
+
603
+ source_spec = args.source
604
+ token_iter: Iterable[str]
605
+ if source_spec.startswith("sentence-transformers:"):
606
+ model_name = source_spec.split(":", 1)[1].strip()
607
+ if not model_name:
608
+ model_name = "sentence-transformers/all-mpnet-base-v2"
609
+ if tokens_from_file is None:
610
+ raise SystemExit(
611
+ "Sentence-transformers sources require --tokens to supply a vocabulary."
612
+ )
613
+ source = _build_sentence_transformer_embeddings(model_name, tokens_from_file)
614
+ token_iter = tokens_from_file
615
+ else:
616
+ source = load_vector_source(source_spec)
617
+ if tokens_from_file is not None:
618
+ token_iter = tokens_from_file
619
+ else:
620
+ lexicon = VectorLexicon(
621
+ source=source,
622
+ max_neighbors=args.max_neighbors,
623
+ min_similarity=args.min_similarity,
624
+ case_sensitive=args.case_sensitive,
625
+ normalizer=normalizer,
626
+ seed=args.seed,
627
+ )
628
+ iterator = lexicon.iter_vocabulary()
629
+ if args.limit is not None:
630
+ token_iter = (token for index, token in enumerate(iterator) if index < args.limit)
631
+ else:
632
+ token_iter = iterator
633
+
634
+ build_vector_cache(
635
+ source=source,
636
+ words=token_iter,
637
+ output_path=args.output,
638
+ max_neighbors=args.max_neighbors,
639
+ min_similarity=args.min_similarity,
640
+ case_sensitive=args.case_sensitive,
641
+ seed=args.seed,
642
+ normalizer=normalizer,
643
+ )
644
+
645
+ return 0
646
+
647
+
648
+ if __name__ == "__main__": # pragma: no cover - manual CLI entry point
649
+ sys.exit(main())
650
+
651
+
652
+ __all__ = ["VectorLexicon", "build_vector_cache", "load_vector_source", "main"]