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