glitchlings 1.0.0__cp313-cp313-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.
Files changed (86) hide show
  1. glitchlings/__init__.py +101 -0
  2. glitchlings/__main__.py +8 -0
  3. glitchlings/_corruption_engine/__init__.py +12 -0
  4. glitchlings/_corruption_engine.cp313-win_amd64.pyd +0 -0
  5. glitchlings/assets/__init__.py +180 -0
  6. glitchlings/assets/apostrofae_pairs.json +32 -0
  7. glitchlings/assets/ekkokin_homophones.json +2014 -0
  8. glitchlings/assets/hokey_assets.json +193 -0
  9. glitchlings/assets/lexemes/academic.json +1049 -0
  10. glitchlings/assets/lexemes/colors.json +1333 -0
  11. glitchlings/assets/lexemes/corporate.json +716 -0
  12. glitchlings/assets/lexemes/cyberpunk.json +22 -0
  13. glitchlings/assets/lexemes/lovecraftian.json +23 -0
  14. glitchlings/assets/lexemes/synonyms.json +3354 -0
  15. glitchlings/assets/mim1c_homoglyphs.json.gz.b64 +1064 -0
  16. glitchlings/assets/ocr_confusions.tsv +30 -0
  17. glitchlings/assets/pipeline_assets.json +29 -0
  18. glitchlings/attack/__init__.py +184 -0
  19. glitchlings/attack/analysis.py +1321 -0
  20. glitchlings/attack/core.py +819 -0
  21. glitchlings/attack/core_execution.py +378 -0
  22. glitchlings/attack/core_planning.py +612 -0
  23. glitchlings/attack/encode.py +114 -0
  24. glitchlings/attack/metrics.py +211 -0
  25. glitchlings/attack/metrics_dispatch.py +70 -0
  26. glitchlings/attack/tokenization.py +338 -0
  27. glitchlings/attack/tokenizer_metrics.py +373 -0
  28. glitchlings/auggie.py +285 -0
  29. glitchlings/compat/__init__.py +9 -0
  30. glitchlings/compat/loaders.py +355 -0
  31. glitchlings/compat/types.py +41 -0
  32. glitchlings/conf/__init__.py +39 -0
  33. glitchlings/conf/loaders.py +331 -0
  34. glitchlings/conf/schema.py +156 -0
  35. glitchlings/conf/types.py +72 -0
  36. glitchlings/config.toml +2 -0
  37. glitchlings/constants.py +139 -0
  38. glitchlings/dev/__init__.py +3 -0
  39. glitchlings/dev/docs.py +45 -0
  40. glitchlings/dlc/__init__.py +21 -0
  41. glitchlings/dlc/_shared.py +300 -0
  42. glitchlings/dlc/gutenberg.py +400 -0
  43. glitchlings/dlc/huggingface.py +68 -0
  44. glitchlings/dlc/langchain.py +147 -0
  45. glitchlings/dlc/nemo.py +283 -0
  46. glitchlings/dlc/prime.py +215 -0
  47. glitchlings/dlc/pytorch.py +98 -0
  48. glitchlings/dlc/pytorch_lightning.py +173 -0
  49. glitchlings/internal/__init__.py +16 -0
  50. glitchlings/internal/rust.py +159 -0
  51. glitchlings/internal/rust_ffi.py +599 -0
  52. glitchlings/main.py +426 -0
  53. glitchlings/protocols.py +91 -0
  54. glitchlings/runtime_config.py +24 -0
  55. glitchlings/util/__init__.py +41 -0
  56. glitchlings/util/adapters.py +65 -0
  57. glitchlings/util/keyboards.py +508 -0
  58. glitchlings/util/transcripts.py +108 -0
  59. glitchlings/zoo/__init__.py +161 -0
  60. glitchlings/zoo/assets/__init__.py +29 -0
  61. glitchlings/zoo/core.py +852 -0
  62. glitchlings/zoo/core_execution.py +154 -0
  63. glitchlings/zoo/core_planning.py +451 -0
  64. glitchlings/zoo/corrupt_dispatch.py +291 -0
  65. glitchlings/zoo/hokey.py +139 -0
  66. glitchlings/zoo/jargoyle.py +301 -0
  67. glitchlings/zoo/mim1c.py +269 -0
  68. glitchlings/zoo/pedant/__init__.py +109 -0
  69. glitchlings/zoo/pedant/core.py +99 -0
  70. glitchlings/zoo/pedant/forms.py +50 -0
  71. glitchlings/zoo/pedant/stones.py +83 -0
  72. glitchlings/zoo/redactyl.py +94 -0
  73. glitchlings/zoo/rng.py +280 -0
  74. glitchlings/zoo/rushmore.py +416 -0
  75. glitchlings/zoo/scannequin.py +370 -0
  76. glitchlings/zoo/transforms.py +331 -0
  77. glitchlings/zoo/typogre.py +194 -0
  78. glitchlings/zoo/validation.py +643 -0
  79. glitchlings/zoo/wherewolf.py +120 -0
  80. glitchlings/zoo/zeedub.py +165 -0
  81. glitchlings-1.0.0.dist-info/METADATA +404 -0
  82. glitchlings-1.0.0.dist-info/RECORD +86 -0
  83. glitchlings-1.0.0.dist-info/WHEEL +5 -0
  84. glitchlings-1.0.0.dist-info/entry_points.txt +3 -0
  85. glitchlings-1.0.0.dist-info/licenses/LICENSE +201 -0
  86. glitchlings-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,120 @@
1
+ """Homophone substitution glitchling implementation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import random
7
+ from typing import TYPE_CHECKING, Any, Iterable, Mapping, Sequence
8
+
9
+ from glitchlings.assets import load_homophone_groups
10
+ from glitchlings.constants import DEFAULT_WHEREWOLF_RATE, DEFAULT_WHEREWOLF_WEIGHTING
11
+ from glitchlings.internal.rust_ffi import resolve_seed, substitute_homophones_rust
12
+
13
+ from .core import AttackOrder, AttackWave
14
+ from .core import Glitchling as _GlitchlingRuntime
15
+
16
+ _homophone_groups: tuple[tuple[str, ...], ...] = load_homophone_groups()
17
+
18
+
19
+ def _normalise_group(group: Sequence[str]) -> tuple[str, ...]:
20
+ """Return a tuple of lowercase homophones preserving original order."""
21
+
22
+ # Use dict.fromkeys to preserve the original ordering while de-duplicating.
23
+ return tuple(dict.fromkeys(word.lower() for word in group if word))
24
+
25
+
26
+ def _build_lookup(groups: Iterable[Sequence[str]]) -> Mapping[str, tuple[str, ...]]:
27
+ """Return a mapping from word -> homophone group."""
28
+
29
+ lookup: dict[str, tuple[str, ...]] = {}
30
+ for group in groups:
31
+ normalised = _normalise_group(group)
32
+ if len(normalised) < 2:
33
+ continue
34
+ for word in normalised:
35
+ lookup[word] = normalised
36
+ return lookup
37
+
38
+
39
+ _homophone_lookup = _build_lookup(_homophone_groups)
40
+
41
+
42
+ class _GlitchlingProtocol:
43
+ kwargs: dict[str, Any]
44
+
45
+ def __init__(self, *args: Any, **kwargs: Any) -> None: ...
46
+
47
+ def reset_rng(self, seed: int | None = None) -> None: ...
48
+
49
+ def pipeline_operation(self) -> dict[str, object] | None: ...
50
+
51
+
52
+ if TYPE_CHECKING:
53
+ from .core import Glitchling as _GlitchlingBase
54
+ else:
55
+ _GlitchlingBase = _GlitchlingRuntime
56
+
57
+
58
+ def substitute_homophones(
59
+ text: str,
60
+ rate: float | None = None,
61
+ seed: int | None = None,
62
+ rng: random.Random | None = None,
63
+ ) -> str:
64
+ """Replace words in ``text`` with curated homophones."""
65
+
66
+ effective_rate = DEFAULT_WHEREWOLF_RATE if rate is None else rate
67
+
68
+ clamped_rate = 0.0 if math.isnan(effective_rate) else max(0.0, min(1.0, effective_rate))
69
+
70
+ return substitute_homophones_rust(
71
+ text,
72
+ clamped_rate,
73
+ DEFAULT_WHEREWOLF_WEIGHTING,
74
+ resolve_seed(seed, rng),
75
+ )
76
+
77
+
78
+ class Wherewolf(_GlitchlingBase):
79
+ """Glitchling that swaps words for curated homophones."""
80
+
81
+ flavor = "Homophonic idiolectician. There leased favourite flavour? Orange."
82
+
83
+ def __init__(
84
+ self,
85
+ *,
86
+ rate: float | None = None,
87
+ seed: int | None = None,
88
+ **kwargs: Any,
89
+ ) -> None:
90
+ effective_rate = DEFAULT_WHEREWOLF_RATE if rate is None else rate
91
+ super().__init__(
92
+ name="Wherewolf",
93
+ corruption_function=substitute_homophones,
94
+ scope=AttackWave.WORD,
95
+ order=AttackOrder.EARLY,
96
+ seed=seed,
97
+ pipeline_operation=_build_pipeline_descriptor,
98
+ rate=effective_rate,
99
+ **kwargs,
100
+ )
101
+
102
+
103
+ def _build_pipeline_descriptor(glitch: _GlitchlingBase) -> dict[str, object]:
104
+ rate_value = glitch.kwargs.get("rate")
105
+ rate = DEFAULT_WHEREWOLF_RATE if rate_value is None else float(rate_value)
106
+ return {
107
+ "type": "wherewolf",
108
+ "rate": rate,
109
+ "weighting": DEFAULT_WHEREWOLF_WEIGHTING,
110
+ }
111
+
112
+
113
+ wherewolf = Wherewolf()
114
+
115
+
116
+ __all__ = [
117
+ "Wherewolf",
118
+ "wherewolf",
119
+ "substitute_homophones",
120
+ ]
@@ -0,0 +1,165 @@
1
+ from __future__ import annotations
2
+
3
+ import random
4
+ from collections.abc import Sequence
5
+ from typing import Any, Literal, cast
6
+
7
+ from glitchlings.constants import (
8
+ DEFAULT_ZEEDUB_MAX_CONSECUTIVE,
9
+ DEFAULT_ZEEDUB_PLACEMENT,
10
+ DEFAULT_ZEEDUB_RATE,
11
+ DEFAULT_ZEEDUB_VISIBILITY,
12
+ ZEEDUB_DEFAULT_ZERO_WIDTHS,
13
+ )
14
+ from glitchlings.internal.rust_ffi import (
15
+ inject_zero_widths_rust,
16
+ resolve_seed,
17
+ )
18
+
19
+ from .core import AttackOrder, AttackWave, Glitchling, PipelineOperationPayload
20
+ from .validation import (
21
+ normalize_zeedub_max_consecutive,
22
+ normalize_zeedub_placement,
23
+ normalize_zeedub_visibility,
24
+ )
25
+
26
+ _DEFAULT_ZERO_WIDTH_CHARACTERS: tuple[str, ...] = ZEEDUB_DEFAULT_ZERO_WIDTHS
27
+
28
+
29
+ def insert_zero_widths(
30
+ text: str,
31
+ rate: float | None = None,
32
+ seed: int | None = None,
33
+ rng: random.Random | None = None,
34
+ *,
35
+ characters: Sequence[str] | None = None,
36
+ visibility: str | None = None,
37
+ placement: str | None = None,
38
+ max_consecutive: int | None = None,
39
+ ) -> str:
40
+ """Inject zero-width characters between non-space character pairs.
41
+
42
+ Args:
43
+ text: Input text.
44
+ rate: Probability of injection at each eligible position.
45
+ seed: Deterministic seed.
46
+ rng: Optional random.Random instance for seed derivation.
47
+ characters: Custom palette of zero-width characters. If None or empty,
48
+ the palette is auto-populated from the visibility mode.
49
+ visibility: Visibility mode ('glyphless', 'with_joiners', 'semi_visible').
50
+ Controls which characters are used when characters is not provided.
51
+ placement: Placement mode ('random', 'grapheme_boundary', 'script_aware').
52
+ max_consecutive: Maximum consecutive insertions (0 for unlimited, default 4).
53
+
54
+ Returns:
55
+ Text with injected zero-width characters.
56
+ """
57
+ effective_rate = DEFAULT_ZEEDUB_RATE if rate is None else rate
58
+
59
+ # Pass empty list when characters is None to let Rust use visibility mode's palette
60
+ cleaned_palette: list[str] = []
61
+ if characters is not None:
62
+ cleaned_palette = [char for char in characters if char]
63
+
64
+ if not text:
65
+ return text
66
+
67
+ clamped_rate = max(0.0, effective_rate)
68
+ if clamped_rate == 0.0:
69
+ return text
70
+
71
+ seed_value = resolve_seed(seed, rng)
72
+ return inject_zero_widths_rust(
73
+ text,
74
+ clamped_rate,
75
+ cleaned_palette,
76
+ seed_value,
77
+ visibility=visibility,
78
+ placement=placement,
79
+ max_consecutive=max_consecutive,
80
+ )
81
+
82
+
83
+ class Zeedub(Glitchling):
84
+ """Glitchling that plants zero-width glyphs inside words.
85
+
86
+ Zeedub supports three placement modes:
87
+
88
+ - **random** (default): Insert between any adjacent non-whitespace characters
89
+ - **grapheme_boundary**: Only insert at grapheme cluster boundaries (safer)
90
+ - **script_aware**: ZWJ/ZWNJ only where linguistically meaningful
91
+
92
+ And three visibility modes:
93
+
94
+ - **glyphless** (default): ZWSP, ZWNJ, ZWJ, WJ, CGJ—true invisibles only
95
+ - **with_joiners**: Adds variation selectors (VS1–VS16)
96
+ - **semi_visible**: Adds hair space, thin space, narrow NBSP
97
+
98
+ By default, caps consecutive invisible insertions at 4 to prevent
99
+ pathological sequences. Set max_consecutive=0 to disable this limit.
100
+ """
101
+
102
+ flavor = "I'm invoking my right to remain silent."
103
+
104
+ def __init__(
105
+ self,
106
+ *,
107
+ rate: float | None = None,
108
+ seed: int | None = None,
109
+ characters: Sequence[str] | None = None,
110
+ visibility: Literal["glyphless", "with_joiners", "semi_visible"] | None = None,
111
+ placement: Literal["random", "grapheme_boundary", "script_aware"] | None = None,
112
+ max_consecutive: int | None = None,
113
+ **kwargs: Any,
114
+ ) -> None:
115
+ effective_rate = DEFAULT_ZEEDUB_RATE if rate is None else rate
116
+ effective_visibility = normalize_zeedub_visibility(visibility, DEFAULT_ZEEDUB_VISIBILITY)
117
+ effective_placement = normalize_zeedub_placement(placement, DEFAULT_ZEEDUB_PLACEMENT)
118
+ effective_max_consecutive = normalize_zeedub_max_consecutive(
119
+ max_consecutive, DEFAULT_ZEEDUB_MAX_CONSECUTIVE
120
+ )
121
+
122
+ super().__init__(
123
+ name="Zeedub",
124
+ corruption_function=insert_zero_widths,
125
+ scope=AttackWave.CHARACTER,
126
+ order=AttackOrder.LAST,
127
+ seed=seed,
128
+ rate=effective_rate,
129
+ characters=tuple(characters) if characters is not None else None,
130
+ visibility=effective_visibility,
131
+ placement=effective_placement,
132
+ max_consecutive=effective_max_consecutive,
133
+ **kwargs,
134
+ )
135
+
136
+ def pipeline_operation(self) -> PipelineOperationPayload:
137
+ rate = float(self.kwargs.get("rate", DEFAULT_ZEEDUB_RATE))
138
+
139
+ # Pass empty list when characters is None to let Rust use visibility mode's palette
140
+ raw_characters = self.kwargs.get("characters")
141
+ palette: list[str] = []
142
+ if raw_characters is not None:
143
+ palette = [str(char) for char in raw_characters if char]
144
+
145
+ visibility = str(self.kwargs.get("visibility", DEFAULT_ZEEDUB_VISIBILITY))
146
+ placement = str(self.kwargs.get("placement", DEFAULT_ZEEDUB_PLACEMENT))
147
+ max_consecutive = int(self.kwargs.get("max_consecutive", DEFAULT_ZEEDUB_MAX_CONSECUTIVE))
148
+
149
+ return cast(
150
+ PipelineOperationPayload,
151
+ {
152
+ "type": "zwj",
153
+ "rate": rate,
154
+ "characters": palette,
155
+ "visibility": visibility,
156
+ "placement": placement,
157
+ "max_consecutive": max_consecutive,
158
+ },
159
+ )
160
+
161
+
162
+ zeedub = Zeedub()
163
+
164
+
165
+ __all__ = ["Zeedub", "zeedub", "insert_zero_widths"]
@@ -0,0 +1,404 @@
1
+ Metadata-Version: 2.4
2
+ Name: glitchlings
3
+ Version: 1.0.0
4
+ Summary: Deterministic, high performance, principled natural language augmentation.
5
+ Author: osoleve
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/osoleve/glitchlings
8
+ Project-URL: Repository, https://github.com/osoleve/glitchlings.git
9
+ Project-URL: Issues, https://github.com/osoleve/glitchlings/issues
10
+ Project-URL: Changelog, https://github.com/osoleve/glitchlings/releases
11
+ Keywords: nlp,adversarial augmentation,text augmentation,data augmentation,domain randomization,tokenizer,tokenization,robustness
12
+ Classifier: Development Status :: 5 - Production/Stable
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Rust
21
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
+ Classifier: Topic :: Software Development :: Testing
23
+ Requires-Python: >=3.10
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: tomli>=2.0.1; python_version < "3.11"
27
+ Requires-Dist: importlib-resources>=5.0.0; python_version < "3.11"
28
+ Requires-Dist: packaging>=23.0
29
+ Requires-Dist: pyyaml>=6.0.0
30
+ Provides-Extra: all
31
+ Requires-Dist: hypothesis>=6.140.0; extra == "all"
32
+ Requires-Dist: interrogate>=1.5.0; extra == "all"
33
+ Requires-Dist: jellyfish==1.2.0; extra == "all"
34
+ Requires-Dist: langchain-core>=0.3.0; extra == "all"
35
+ Requires-Dist: mkdocs>=1.6.0; extra == "all"
36
+ Requires-Dist: mkdocs-material>=9.5.0; extra == "all"
37
+ Requires-Dist: mkdocstrings[python]>=0.24.0; extra == "all"
38
+ Requires-Dist: mkdocstrings-python>=1.10.0; extra == "all"
39
+ Requires-Dist: mypy>=1.8.0; extra == "all"
40
+ Requires-Dist: numpy<3.0,>=1.24; extra == "all"
41
+ Requires-Dist: pre-commit>=3.8.0; extra == "all"
42
+ Requires-Dist: py-gutenberg==1.0.0; extra == "all"
43
+ Requires-Dist: pytest>=8.0.0; extra == "all"
44
+ Requires-Dist: pytest-cov>=4.1.0; extra == "all"
45
+ Requires-Dist: ruff>=0.6.0; extra == "all"
46
+ Requires-Dist: types-PyYAML>=6.0.0; extra == "all"
47
+ Requires-Dist: verifiers>=0.1.8; extra == "all"
48
+ Requires-Dist: tiktoken>=0.3.0; extra == "all"
49
+ Requires-Dist: tokenizers>=0.13.0; extra == "all"
50
+ Provides-Extra: tok
51
+ Requires-Dist: tiktoken>=0.3.0; extra == "tok"
52
+ Requires-Dist: tokenizers>=0.13.0; extra == "tok"
53
+ Provides-Extra: gutenberg
54
+ Requires-Dist: py-gutenberg==1.0.0; extra == "gutenberg"
55
+ Provides-Extra: hf
56
+ Requires-Dist: datasets>=4.0.0; extra == "hf"
57
+ Provides-Extra: lightning
58
+ Requires-Dist: pytorch_lightning>=2.0.0; extra == "lightning"
59
+ Provides-Extra: langchain
60
+ Requires-Dist: langchain-core>=0.3.0; extra == "langchain"
61
+ Provides-Extra: prime
62
+ Requires-Dist: verifiers>=0.1.8; extra == "prime"
63
+ Requires-Dist: jellyfish==1.2.0; extra == "prime"
64
+ Provides-Extra: torch
65
+ Requires-Dist: torch>=2.0.0; extra == "torch"
66
+ Provides-Extra: dev
67
+ Requires-Dist: pytest>=8.0.0; extra == "dev"
68
+ Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
69
+ Requires-Dist: hypothesis>=6.140.0; extra == "dev"
70
+ Requires-Dist: numpy<3.0,>=1.24; extra == "dev"
71
+ Requires-Dist: mkdocs>=1.6.0; extra == "dev"
72
+ Requires-Dist: mkdocstrings[python]>=0.24.0; extra == "dev"
73
+ Requires-Dist: mkdocs-material>=9.5.0; extra == "dev"
74
+ Requires-Dist: mkdocstrings-python>=1.10.0; extra == "dev"
75
+ Requires-Dist: interrogate>=1.5.0; extra == "dev"
76
+ Requires-Dist: ruff>=0.6.0; extra == "dev"
77
+ Requires-Dist: mypy>=1.8.0; extra == "dev"
78
+ Requires-Dist: pre-commit>=3.8.0; extra == "dev"
79
+ Requires-Dist: types-PyYAML>=6.0.0; extra == "dev"
80
+ Dynamic: license-file
81
+
82
+ #
83
+
84
+ ```plaintext
85
+ .─') _ .─') _
86
+ ( OO) ) ( OO ) )
87
+ ░██████ ░██ ░██ ░██ ░██ ░██ ░██
88
+ ░██ ░██ ░██ ░██ ░██ ░██
89
+ ░██ ░██ ░██░████████ ░███████ ░████████ ░██ ░██░████████ ░████████ ░███████
90
+ ░██ █████ ░██ ░██ ░██ ░██('─.░██ ░██ ░██ ░██ ░██░██ ░██ ░██.─')░██ ░██
91
+ ░██ ██ ░██ ░██ ░██ ░██( OO ) ╱░██ ░██ ░██ ░██░██ ░██ ░██(OO)░██ ░███████
92
+ ░██ ░███ ░██ ░██ ░██ ░██ ░██ ░██ ░██ ░██ ░██░██ ░██ ░██ o ░███ ░██
93
+ ░█████░█ ░██ ░██ ░████ ░███████ ░██ ░██ ░██ ░██░██ ░██ ░█████░██ ░███████
94
+ ░██
95
+ ░███████
96
+
97
+ Every language game breeds monsters.
98
+ ```
99
+
100
+ ![Python Versions](https://img.shields.io/pypi/pyversions/glitchlings.svg)
101
+ [![PyPI version](https://img.shields.io/pypi/v/glitchlings.svg)](https://pypi.org/project/glitchlings/)
102
+ ![Wheel](https://img.shields.io/pypi/wheel/glitchlings.svg)
103
+ ![Linting and Typing](https://github.com/osoleve/glitchlings/actions/workflows/ci.yml/badge.svg)
104
+ ![Entropy Budget](https://img.shields.io/badge/entropy-lifegiving-magenta.svg)
105
+ ![Chaos](https://img.shields.io/badge/chaos-friend--shaped-chartreuse.svg)
106
+ ![Charm](https://img.shields.io/badge/jouissance-indefatigable-cyan.svg)
107
+ ![Lore Compliance](https://img.shields.io/badge/ISO--474--▓▓-Z--Compliant-blue.svg)
108
+
109
+ `Glitchlings` are **utilities for corrupting the text inputs to your language models in deterministic, _linguistically principled_** ways.
110
+ Each embodies a different way that documents can be compromised in the wild.
111
+
112
+ If reinforcement learning environments are games, then `Glitchling`s are enemies to breathe new life into old challenges.
113
+
114
+ They do this by breaking surface patterns in the input while keeping the target output intact.
115
+
116
+ Some `Glitchling`s are petty nuisances. Some `Glitchling`s are eldritch horrors.
117
+ Together, they create truly nightmarish scenarios for your language models.
118
+
119
+ After all, what good is general intelligence if it can't handle a little chaos?
120
+
121
+ -_The Curator_
122
+
123
+ ## Motivation
124
+
125
+ If your model performs well on a particular task, but not when `Glitchling`s are present, it's a sign that it hasn't actually generalized to the problem.
126
+
127
+ Conversely, training a model to perform well in the presence of the types of perturbations introduced by `Glitchling`s should help it generalize better.
128
+
129
+ ## Quickstart
130
+
131
+ ```python
132
+ pip install -U glitchlings
133
+ ```
134
+
135
+ The fastest way to get started is to ask my assistant, `Auggie`, to prepare a custom mix of glitchlings for you:
136
+
137
+ ```python
138
+ from glitchlings import Auggie, SAMPLE_TEXT
139
+
140
+ auggie = (
141
+ Auggie(seed=404)
142
+ .typo(rate=0.015)
143
+ .confusable(rate=0.01)
144
+ .homophone(rate=0.02)
145
+ )
146
+
147
+ print(auggie(SAMPLE_TEXT))
148
+ ```
149
+
150
+ > One morning, when Gregor Samsa woke from troubld dreams, he found himself transformed in his bed into a horible vermin. He layed on his armour-like back, and if he lifted his head a little he could see his brown belly, slightly domed and divided by arches into stiff sections. The bedding was hardly able to cover it and seemed ready to slide off any moment. His many legs, pitifully thin compared with the size of the rest of him, waved about helplessly as he looked.
151
+
152
+ **You're more than welcome to summon them directly, if you're feeling brave:**
153
+
154
+ ```python
155
+ from glitchlings import Gaggle, SAMPLE_TEXT, Typogre, Mim1c, Wherewolf
156
+
157
+ gaggle = Gaggle(
158
+ [
159
+ Typogre(rate=0.015),
160
+ Mim1c(rate=0.01),
161
+ Wherewolf(rate=0.02),
162
+ ],
163
+ seed=404
164
+ )
165
+ ```
166
+
167
+ Consult the [Glitchlings Usage Guide](docs/index.md)
168
+ for end-to-end instructions spanning the Python API, CLI, and third-party integrations.
169
+
170
+ ## Your First Battle
171
+
172
+ Summon your chosen `Glitchling` (_or a few, if ya nasty_) and call it on your text or slot it into `Dataset.map(...)`, supplying a seed if desired.
173
+ Glitchlings are standard Python classes:
174
+
175
+ ```python
176
+ from glitchlings import Gaggle, Typogre, Mim1c
177
+
178
+ custom_typogre = Typogre(rate=0.1)
179
+ selective_mimic = Mim1c(rate=0.05, classes=["LATIN", "GREEK"])
180
+
181
+ gaggle = Gaggle([custom_typogre, selective_mimic], seed=99)
182
+ corrupted = gaggle("We Await Silent Tristero's Empire.")
183
+ print(corrupted)
184
+ ```
185
+
186
+ Calling a `Glitchling` on a `str` transparently calls `.corrupt(str, ...) -> str`.
187
+ This means that as long as your glitchlings get along logically, they play nicely with one another.
188
+
189
+ When summoned as or gathered into a `Gaggle`, the `Glitchling`s will automatically order themselves into attack waves, based on the scope of the change they make:
190
+
191
+ 1. Document
192
+ 2. Paragraph
193
+ 3. Sentence
194
+ 4. Word
195
+ 5. Character
196
+
197
+ They're horrible little gremlins, but they're not _unreasonable_.
198
+
199
+ ## Command-Line Interface (CLI)
200
+
201
+ Keyboard warriors can challenge them directly via the `glitchlings` command (see the generated CLI reference in `docs/cli.md` for the full contract):
202
+
203
+ ```bash
204
+ # Discover which glitchlings are currently on the loose.
205
+ glitchlings --list
206
+
207
+ # Review the full CLI contract.
208
+ glitchlings --help
209
+
210
+ # Run Typogre against the contents of a file and inspect the diff.
211
+ glitchlings -g typogre --input-file documents/report.txt --diff
212
+
213
+ # Configure glitchlings inline by passing keyword arguments.
214
+ glitchlings -g "Typogre(rate=0.05)" "Ghouls just wanna have fun"
215
+
216
+ # Pipe text straight into the CLI for an on-the-fly corruption.
217
+ echo "Beware LLM-written flavor-text" | glitchlings -g mim1c
218
+
219
+ # Emit an Attack summary with metrics and counts.
220
+ glitchlings --attack --sample
221
+
222
+ # Emit a full Attack report with tokens, token IDs, and metrics.
223
+ glitchlings --report --sample
224
+ ```
225
+
226
+ ## Configuration Files
227
+
228
+ Configurations live in plain YAML files so you can version-control experiments without touching code:
229
+
230
+ ```bash
231
+ # Load a roster from a YAML attack configuration.
232
+ glitchlings --config experiments/chaos.yaml "Let slips the glitchlings of war"
233
+ ```
234
+
235
+ ```yaml
236
+ # experiments/chaos.yaml
237
+ seed: 31337
238
+ glitchlings:
239
+ - name: Typogre
240
+ rate: 0.04
241
+ - "Rushmore(rate=0.12, unweighted=True)"
242
+ - name: Zeedub
243
+ parameters:
244
+ rate: 0.02
245
+ characters: ["\u200b", "\u2060"]
246
+ ```
247
+
248
+ ## Attack on Token
249
+
250
+ Looking to compare before/after corruption with metrics and stable seeds? Reach for the [`Attack` helper](docs/attack.md), which bundles tokenization, metrics, and transcript batching into a single utility. It accepts plain `list[str]` batches, renders quick `summary()` reports, and can compare multiple tokenizers via `Attack.compare(...)` when you need a metrics matrix.
251
+
252
+ ## Development
253
+
254
+ Follow the [development setup guide](docs/development.md) for editable installs, automated tests, and tips on enabling the Rust pipeline while you hack on new glitchlings.
255
+
256
+ ## Starter 'lings
257
+
258
+ For maintainability reasons, all `Glitchling` have consented to be given nicknames once they're in your care. See the [Monster Manual](MONSTER_MANUAL.md) for a complete bestiary.
259
+
260
+ ### Typogre
261
+
262
+ _What a nice word, would be a shame if something happened to it._
263
+
264
+ > _**Fatfinger.**_ Typogre introduces character-level errors (duplicating, dropping, adding, or swapping) based on the layout of a keyboard (QWERTY by default, with Dvorak and Colemak variants built-in).
265
+ >
266
+ > Typogre supports **motor coordination weighting** based on biomechanical research from the Aalto 136M Keystrokes dataset. Use `motor_weighting="wet_ink"` for uncorrected errors (cross-hand typos slip through) or `motor_weighting="hastily_edited"` for raw typing patterns before correction.
267
+
268
+ ### Mim1c
269
+
270
+ _Wait, was that...?_
271
+
272
+ > _**Confusion.**_ Mim1c replaces non-space characters with Unicode Confusables, characters that are distinct but would not usually confuse a human reader.
273
+ >
274
+ > **Substitution Modes:**
275
+ > - `single_script` (safest): Only same-script confusables (Latin→Latin variants)
276
+ > - `mixed_script` (default): Allow cross-script substitutions (Latin↔Cyrillic↔Greek)
277
+ > - `compatibility`: Include fullwidth, math alphanumerics, enclosed forms
278
+ > - `aggressive`: All confusable types combined
279
+ >
280
+ > **Locality Control:** Caps consecutive substitutions at 3 by default to prevent "ransom note" effect. Set `max_consecutive=0` to disable.
281
+ >
282
+ > **Script Affinity:** In mixed_script mode, substitutions are weighted by visual plausibility (Latin↔Cyrillic: 0.9, Latin↔Greek: 0.8).
283
+
284
+ ### Hokey
285
+
286
+ _She's soooooo coooool!_
287
+
288
+ > _**Passionista.**_ Hokey gets a little excited and streeeeetches words for emphasis.
289
+ >
290
+ > _Apocryphal Glitchling contributed by Chloé Nunes_
291
+
292
+ ### Scannequin
293
+
294
+ _How can a computer need reading glasses?_
295
+
296
+ > _**OCArtifacts.**_ Scannequin mimics optical character recognition errors by swapping visually similar character sequences (like rn↔m, cl↔d, O↔0, l/I/1).
297
+
298
+ ### Zeedub
299
+
300
+ _Watch your step around here._
301
+
302
+ > _**Invisible Ink.**_ Zeedub slips zero-width codepoints between non-space character pairs, forcing models to reason about text whose visible form masks hidden glyphs.
303
+ >
304
+ > **Placement Modes:**
305
+ > - `random` (default): Insert between any adjacent non-whitespace characters
306
+ > - `grapheme_boundary`: Only insert at grapheme cluster boundaries (safer for rendering)
307
+ > - `script_aware`: ZWJ/ZWNJ only where linguistically meaningful (Arabic, Indic scripts, emoji)
308
+ >
309
+ > **Visibility Modes:**
310
+ > - `glyphless` (default): True invisibles only (ZWSP, ZWNJ, ZWJ, WJ, CGJ, BOM)
311
+ > - `with_joiners`: Adds variation selectors VS1–VS16
312
+ > - `semi_visible`: Adds hair space, thin space, narrow NBSP
313
+ >
314
+ > **Safety:** Caps consecutive insertions at 4 by default to prevent pathological sequences. Set `max_consecutive=0` to disable.
315
+
316
+ ### Wherewolf
317
+
318
+ _Did you hear what I heard?_
319
+
320
+ > _**Echo Chamber.**_ Wherewolf swaps words with curated homophones so the text still sounds right while the spelling drifts. Groups are normalised to prevent duplicates and casing is preserved when substitutions fire.
321
+
322
+ ### Jargoyle
323
+
324
+ _Uh oh. The worst person you know just bought a thesaurus._
325
+
326
+ > _**Sesquipedalianism.**_ Jargoyle insufferably replaces words with synonyms at random, without regard for connotational or denotational differences.
327
+
328
+ ### Rushmore
329
+
330
+ _I accidentally an entire word._
331
+
332
+ > _**Tactical Scrambler.**_ Rushmore randomly drops, duplicates, or swaps words in the text to simulate hasty writing, editing mistakes, or transmission errors.
333
+
334
+ ### Redactyl
335
+
336
+ _Oops, that was my black highlighter._
337
+
338
+ > _**FOIA Reply.**_ Redactyl obscures random words in your document like an NSA analyst with a bad sense of humor.
339
+
340
+ ## Apocrypha
341
+
342
+ Cave paintings and oral tradition contain many depictions of strange, otherworldly `Glitchling`s.
343
+ These _Apocryphal `Glitchling`_ are said to possess unique abilities or behaviors.
344
+ If you encounter one of these elusive beings, please document your findings and share them with _The Curator_.
345
+
346
+ ### Ensuring Reproducible Corruption
347
+
348
+ Every `Glitchling` should own its own independent `random.Random` instance. That means:
349
+
350
+ - No `random.seed(...)` calls touch Python's global RNG.
351
+ - Supplying a `seed` when you construct a `Glitchling` (or when you `summon(...)`) makes its behavior reproducible.
352
+ - Re-running a `Gaggle` with the same master seed and the same input text (_and same external data!_) yields identical corruption output.
353
+ - Corruption functions are written to accept an `rng` parameter internally so that all randomness is centralized and testable.
354
+
355
+ #### At Wits' End?
356
+
357
+ If you're trying to add a new glitchling and can't seem to make it deterministic, here are some places to look for determinism-breaking code:
358
+
359
+ 1. Search for any direct calls to `random.choice`, `random.shuffle`, or `set(...)` ordering without going through the provided `rng`.
360
+ 2. Ensure you sort collections before shuffling or sampling.
361
+ 3. Make sure indices are chosen from a stable reference (e.g., original text) when applying length‑changing edits.
362
+ 4. Make sure there are enough sort keys to maintain stability.
363
+
364
+ ## References
365
+
366
+ Glitchlings incorporates research from the following sources:
367
+
368
+ - **Aalto 136M Keystrokes Dataset** — Motor coordination weights for Typogre's biomechanically-informed error sampling:
369
+ > Dhakal, V., Feit, A. M., Kristensson, P. O., & Oulasvirta, A. (2018). Observations on Typing from 136 Million Keystrokes. *Proceedings of the 2018 CHI Conference on Human Factors in Computing Systems (CHI '18)*, Article 646. https://doi.org/10.1145/3173574.3174220
370
+
371
+ - **Expressive Lengthening Research** — Linguistic foundations for Hokey's stretchability scoring and site selection:
372
+ > Brody, S., & Diakopoulos, N. (2011). Cooooooooooooooollllllllllllll!!!!!!!!!!!!!!: Using Word Lengthening to Detect Sentiment in Microtext. *Proceedings of the 2011 Conference on Empirical Methods in Natural Language Processing (EMNLP '11)*, 562–570. https://aclanthology.org/D11-1052
373
+
374
+ > Gray, B., Bruxvoort, C., Beigman Klebanov, B., & Leong, B. (2020). Expressive Lengthening in Social Media. *Proceedings of the 12th Language Resources and Evaluation Conference (LREC 2020)*, 4517–4523. https://aclanthology.org/2020.lrec-1.556
375
+
376
+ - **OCR Degradation Modeling** — Theoretical foundations for Scannequin's document-level corruption, burst error clustering, and segmentation failures:
377
+ > Kanungo, T., Haralick, R. M., & Phillips, I. (1994). Nonlinear Local and Global Document Degradation Models. *International Journal of Imaging Systems and Technology*, 5(3), 220–230. https://doi.org/10.1002/ima.1850050305
378
+
379
+ > Li, Y., Lopresti, D., Nagy, G., & Tompkins, A. (1996). Validation of Image Defect Models for Optical Character Recognition. *IEEE Transactions on Pattern Analysis and Machine Intelligence*, 18(2), 99–107. https://doi.org/10.1109/34.481540
380
+
381
+ > Kolak, O., & Resnik, P. (2002). OCR Error Correction Using a Noisy Channel Model. *Proceedings of the Second International Conference on Human Language Technology Research (HLT '02)*, 257–262. https://dl.acm.org/doi/10.5555/1289189.1289227
382
+
383
+ - **OCR Evaluation Methodology** — Benchmark methodology informing Scannequin's quality presets and parameter calibration:
384
+ > Rice, S. V., Jenkins, F. R., & Nartker, T. A. (1995). The Fourth Annual Test of OCR Accuracy. Technical Report 95-04, Information Science Research Institute, University of Nevada, Las Vegas. https://tesseract-ocr.github.io/docs/AT-1995.pdf
385
+
386
+ > Lucas, S. M., Panaretos, A., Sosa, L., Tang, A., Wong, S., & Young, R. (2005). ICDAR 2003 Robust Reading Competitions: Entries, Results, and Future Directions. *International Journal on Document Analysis and Recognition*, 7(2–3), 105–122. https://doi.org/10.1007/s10032-004-0134-3
387
+
388
+ - **Unicode Text Segmentation** — Grapheme cluster boundary rules for Zeedub's `grapheme_boundary` placement mode:
389
+ > The Unicode Consortium. (2024). Unicode Standard Annex #29: Unicode Text Segmentation. https://www.unicode.org/reports/tr29/
390
+
391
+ - **Unicode Security Considerations** — Default_Ignorable handling and safety constraints informing Zeedub's visibility classification and max_consecutive limits:
392
+ > The Unicode Consortium. (2014). Unicode Technical Report #36: Unicode Security Considerations. https://www.unicode.org/reports/tr36/
393
+
394
+ - **Unicode Confusables** — Script-aware confusable character mappings for Mim1c's substitution modes and script classification:
395
+ > The Unicode Consortium. (2024). Unicode Technical Standard #39: Unicode Security Mechanisms. https://www.unicode.org/reports/tr39/
396
+
397
+ > The Unicode Consortium. (2024). Confusables Data File. https://www.unicode.org/Public/security/latest/confusables.txt
398
+
399
+ - **Hypercorrection Research** — Sociolinguistic foundations for Pedant's coordinate-structure pronoun overcorrection and split infinitive patterns:
400
+ > Collins, P. (2022). Hypercorrection in English: an intervarietal corpus-based study. *English Language & Linguistics*, 26(2), 279–305. https://doi.org/10.1017/S1360674321000101
401
+
402
+ > Labov, W. (1966). Hypercorrection by the Lower Middle Class as a Factor in Linguistic Change. *Sociolinguistic Patterns*, 122–142. University of Pennsylvania Press.
403
+
404
+ > Angermeyer, P. S., & Singler, J. V. (2003). The case for politeness: Pronoun variation in co-ordinate NPs in object position in English. *Language Variation and Change*, 15(2), 171–209. https://doi.org/10.1017/S0954394503152027