glitchlings 0.3.0__cp312-cp312-macosx_11_0_universal2.whl → 0.4.1__cp312-cp312-macosx_11_0_universal2.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.

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