glitchlings 0.10.2__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.

Files changed (83) hide show
  1. glitchlings/__init__.py +99 -0
  2. glitchlings/__main__.py +8 -0
  3. glitchlings/_zoo_rust/__init__.py +12 -0
  4. glitchlings/_zoo_rust.cpython-312-darwin.so +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 +147 -0
  19. glitchlings/attack/analysis.py +1321 -0
  20. glitchlings/attack/core.py +493 -0
  21. glitchlings/attack/core_execution.py +367 -0
  22. glitchlings/attack/core_planning.py +612 -0
  23. glitchlings/attack/encode.py +114 -0
  24. glitchlings/attack/metrics.py +218 -0
  25. glitchlings/attack/metrics_dispatch.py +70 -0
  26. glitchlings/attack/tokenization.py +227 -0
  27. glitchlings/auggie.py +284 -0
  28. glitchlings/compat/__init__.py +9 -0
  29. glitchlings/compat/loaders.py +355 -0
  30. glitchlings/compat/types.py +41 -0
  31. glitchlings/conf/__init__.py +41 -0
  32. glitchlings/conf/loaders.py +331 -0
  33. glitchlings/conf/schema.py +156 -0
  34. glitchlings/conf/types.py +72 -0
  35. glitchlings/config.toml +2 -0
  36. glitchlings/constants.py +59 -0
  37. glitchlings/dev/__init__.py +3 -0
  38. glitchlings/dev/docs.py +45 -0
  39. glitchlings/dlc/__init__.py +19 -0
  40. glitchlings/dlc/_shared.py +296 -0
  41. glitchlings/dlc/gutenberg.py +400 -0
  42. glitchlings/dlc/huggingface.py +68 -0
  43. glitchlings/dlc/prime.py +215 -0
  44. glitchlings/dlc/pytorch.py +98 -0
  45. glitchlings/dlc/pytorch_lightning.py +173 -0
  46. glitchlings/internal/__init__.py +16 -0
  47. glitchlings/internal/rust.py +159 -0
  48. glitchlings/internal/rust_ffi.py +490 -0
  49. glitchlings/main.py +426 -0
  50. glitchlings/protocols.py +91 -0
  51. glitchlings/runtime_config.py +24 -0
  52. glitchlings/util/__init__.py +27 -0
  53. glitchlings/util/adapters.py +65 -0
  54. glitchlings/util/keyboards.py +356 -0
  55. glitchlings/util/transcripts.py +108 -0
  56. glitchlings/zoo/__init__.py +161 -0
  57. glitchlings/zoo/assets/__init__.py +29 -0
  58. glitchlings/zoo/core.py +678 -0
  59. glitchlings/zoo/core_execution.py +154 -0
  60. glitchlings/zoo/core_planning.py +451 -0
  61. glitchlings/zoo/corrupt_dispatch.py +295 -0
  62. glitchlings/zoo/hokey.py +139 -0
  63. glitchlings/zoo/jargoyle.py +243 -0
  64. glitchlings/zoo/mim1c.py +148 -0
  65. glitchlings/zoo/pedant/__init__.py +109 -0
  66. glitchlings/zoo/pedant/core.py +105 -0
  67. glitchlings/zoo/pedant/forms.py +74 -0
  68. glitchlings/zoo/pedant/stones.py +74 -0
  69. glitchlings/zoo/redactyl.py +97 -0
  70. glitchlings/zoo/rng.py +259 -0
  71. glitchlings/zoo/rushmore.py +416 -0
  72. glitchlings/zoo/scannequin.py +66 -0
  73. glitchlings/zoo/transforms.py +346 -0
  74. glitchlings/zoo/typogre.py +128 -0
  75. glitchlings/zoo/validation.py +477 -0
  76. glitchlings/zoo/wherewolf.py +120 -0
  77. glitchlings/zoo/zeedub.py +93 -0
  78. glitchlings-0.10.2.dist-info/METADATA +337 -0
  79. glitchlings-0.10.2.dist-info/RECORD +83 -0
  80. glitchlings-0.10.2.dist-info/WHEEL +5 -0
  81. glitchlings-0.10.2.dist-info/entry_points.txt +3 -0
  82. glitchlings-0.10.2.dist-info/licenses/LICENSE +201 -0
  83. glitchlings-0.10.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,45 @@
1
+ """Developer helpers for refreshing generated documentation assets."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import runpy
6
+ from pathlib import Path
7
+
8
+ REPO_ROOT = Path(__file__).resolve().parents[3]
9
+ DOCS_DIR = REPO_ROOT / "docs"
10
+
11
+
12
+ def _run_script(path: Path) -> None:
13
+ if not path.exists():
14
+ raise FileNotFoundError(f"Documentation helper not found: {path}")
15
+ runpy.run_path(str(path))
16
+
17
+
18
+ def refresh_cli_reference() -> None:
19
+ """Regenerate the CLI reference docs page."""
20
+ _run_script(DOCS_DIR / "build_cli_reference.py")
21
+
22
+
23
+ def refresh_monster_manual() -> None:
24
+ """Regenerate the Monster Manual."""
25
+ _run_script(DOCS_DIR / "build_monster_manual.py")
26
+
27
+
28
+ def refresh_gallery() -> None:
29
+ """Regenerate the glitchling gallery page."""
30
+ _run_script(DOCS_DIR / "build_glitchling_gallery.py")
31
+
32
+
33
+ def refresh_all() -> None:
34
+ """Regenerate CLI reference, Monster Manual, and gallery docs in one call."""
35
+ refresh_cli_reference()
36
+ refresh_monster_manual()
37
+ refresh_gallery()
38
+
39
+
40
+ def main() -> None:
41
+ refresh_all()
42
+
43
+
44
+ if __name__ == "__main__":
45
+ main()
@@ -0,0 +1,19 @@
1
+ """Optional DLC integrations for Glitchlings.
2
+
3
+ This module provides explicit wrapper classes for integrating glitchlings
4
+ with popular ML frameworks:
5
+
6
+ - :class:`~glitchlings.dlc.huggingface.GlitchedDataset`: Wrap Hugging Face datasets
7
+ - :class:`~glitchlings.dlc.pytorch.GlitchedDataLoader`: Wrap PyTorch data loaders
8
+ - :class:`~glitchlings.dlc.pytorch_lightning.GlitchedLightningDataModule`: Wrap
9
+ Lightning data modules
10
+ - :class:`~glitchlings.dlc.gutenberg.GlitchenbergAPI`: Wrap Project Gutenberg API
11
+
12
+ Example:
13
+ >>> from glitchlings.dlc.huggingface import GlitchedDataset
14
+ >>> from datasets import Dataset
15
+ >>> dataset = Dataset.from_dict({"text": ["hello", "world"]})
16
+ >>> corrupted = GlitchedDataset(dataset, "typogre", column="text")
17
+ """
18
+
19
+ __all__: list[str] = []
@@ -0,0 +1,296 @@
1
+ """Shared utilities for DLC integrations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping, Sequence
6
+ from typing import Any, cast
7
+
8
+ from ..util.transcripts import is_transcript
9
+ from ..zoo.core import Gaggle
10
+
11
+
12
+ def resolve_columns(dataset: Any, columns: Sequence[str] | None) -> list[str]:
13
+ """Identify which dataset columns should be corrupted."""
14
+ available = set(getattr(dataset, "column_names", ()))
15
+
16
+ if columns is not None:
17
+ missing = sorted(set(columns) - available)
18
+ if missing:
19
+ missing_str = ", ".join(missing)
20
+ raise ValueError(f"Columns not found in dataset: {missing_str}")
21
+ return list(columns)
22
+
23
+ for candidate in ("prompt", "question"):
24
+ if candidate in available:
25
+ return [candidate]
26
+
27
+ try:
28
+ dataset_length = len(dataset)
29
+ except TypeError:
30
+ preview_rows: list[dict[str, Any]]
31
+ take_fn = getattr(dataset, "take", None)
32
+ if callable(take_fn):
33
+ preview_rows = list(take_fn(1))
34
+ else:
35
+ iterator = iter(dataset)
36
+ try:
37
+ first_row = next(iterator)
38
+ except StopIteration:
39
+ preview_rows = []
40
+ else:
41
+ preview_rows = [first_row]
42
+ sample = dict(preview_rows[0]) if preview_rows else {}
43
+ else:
44
+ sample = dataset[0] if dataset_length else {}
45
+ inferred = [
46
+ name for name in getattr(dataset, "column_names", ()) if isinstance(sample.get(name), str)
47
+ ]
48
+
49
+ if inferred:
50
+ return inferred
51
+
52
+ raise ValueError("Unable to determine which dataset columns to corrupt.")
53
+
54
+
55
+ def normalize_column_spec(
56
+ columns: str | int | Sequence[str | int] | None,
57
+ ) -> list[str | int] | None:
58
+ """Normalize a column specification into a list of keys or indices.
59
+
60
+ Args:
61
+ columns: Column specification as a single value, sequence of values, or None.
62
+
63
+ Returns:
64
+ A list of column identifiers, or None if input was None.
65
+
66
+ Raises:
67
+ ValueError: If an empty sequence is provided.
68
+ """
69
+ if columns is None:
70
+ return None
71
+
72
+ if isinstance(columns, (str, int)):
73
+ return [columns]
74
+
75
+ normalized = list(columns)
76
+ if not normalized:
77
+ raise ValueError("At least one column must be specified")
78
+ return normalized
79
+
80
+
81
+ def is_textual_candidate(value: Any) -> bool:
82
+ """Return ``True`` when ``value`` looks like text that glitchlings can corrupt.
83
+
84
+ Args:
85
+ value: The value to check for textual content.
86
+
87
+ Returns:
88
+ True if the value appears to be textual content.
89
+ """
90
+ if isinstance(value, str):
91
+ return True
92
+
93
+ if is_transcript(value, allow_empty=False, require_all_content=True):
94
+ return True
95
+
96
+ if isinstance(value, Sequence) and not isinstance(value, (bytes, bytearray, str)):
97
+ if not value:
98
+ return False
99
+ if all(isinstance(item, str) for item in value):
100
+ return True
101
+ if is_transcript(list(value), allow_empty=False, require_all_content=True):
102
+ return True
103
+
104
+ return False
105
+
106
+
107
+ def corrupt_text_value(value: Any, gaggle: Gaggle) -> Any:
108
+ """Return ``value`` with glitchlings applied when possible.
109
+
110
+ Args:
111
+ value: The value to corrupt (string, transcript, or sequence of strings).
112
+ gaggle: The gaggle of glitchlings to apply.
113
+
114
+ Returns:
115
+ The corrupted value, preserving the original type where possible.
116
+ """
117
+ if isinstance(value, str):
118
+ return gaggle.corrupt(value)
119
+
120
+ if is_transcript(value, allow_empty=True):
121
+ return gaggle.corrupt(value)
122
+
123
+ if isinstance(value, list) and value and all(isinstance(item, str) for item in value):
124
+ return [gaggle.corrupt(item) for item in value]
125
+
126
+ if isinstance(value, tuple) and value and all(isinstance(item, str) for item in value):
127
+ return tuple(gaggle.corrupt(item) for item in value)
128
+
129
+ return value
130
+
131
+
132
+ def infer_batch_targets(batch: Any) -> list[str | int] | None:
133
+ """Infer which fields should be glitched from a representative batch.
134
+
135
+ Args:
136
+ batch: A batch from a DataLoader (mapping, sequence, or textual value).
137
+
138
+ Returns:
139
+ A list of column keys (strings) or indices (ints), or None if the batch
140
+ itself is textual content.
141
+
142
+ Raises:
143
+ ValueError: If unable to infer textual columns/indices.
144
+ TypeError: If the batch type is unsupported.
145
+ """
146
+ if isinstance(batch, Mapping):
147
+ inferred = [key for key, value in batch.items() if is_textual_candidate(value)]
148
+ if inferred:
149
+ return inferred
150
+ raise ValueError("Unable to infer which mapping columns contain text")
151
+
152
+ if isinstance(batch, Sequence) and not isinstance(batch, (bytes, bytearray, str)):
153
+ inferred_indices: list[str | int] = [
154
+ idx for idx, value in enumerate(batch) if is_textual_candidate(value)
155
+ ]
156
+ if inferred_indices:
157
+ return inferred_indices
158
+ raise ValueError("Unable to infer which sequence indices contain text")
159
+
160
+ if is_textual_candidate(batch):
161
+ return None
162
+
163
+ raise TypeError("Unsupported DataLoader batch type for glitching")
164
+
165
+
166
+ def corrupt_batch(batch: Any, targets: list[str | int] | None, gaggle: Gaggle) -> Any:
167
+ """Return batch with glitchlings applied to the specified targets.
168
+
169
+ Args:
170
+ batch: The batch to corrupt (mapping, sequence, or textual value).
171
+ targets: List of column keys (strings) or indices (ints), or None to
172
+ corrupt the entire batch as textual content.
173
+ gaggle: The gaggle of glitchlings to apply.
174
+
175
+ Returns:
176
+ The corrupted batch, preserving the original type.
177
+
178
+ Raises:
179
+ TypeError: If batch type is unsupported or targets are incompatible.
180
+ ValueError: If a specified target is not found in the batch.
181
+ """
182
+ if targets is None:
183
+ return corrupt_text_value(batch, gaggle)
184
+
185
+ if isinstance(batch, Mapping):
186
+ # Use copy() if available, otherwise dict()
187
+ if hasattr(batch, "copy"):
188
+ mutated = batch.copy()
189
+ else:
190
+ mutated = dict(batch)
191
+
192
+ for key in targets:
193
+ if not isinstance(key, str):
194
+ raise TypeError("Mapping batches require string column names")
195
+ if key not in mutated:
196
+ raise ValueError(f"Column '{key}' not found in DataLoader batch")
197
+ mutated[key] = corrupt_text_value(mutated[key], gaggle)
198
+ return mutated
199
+
200
+ if isinstance(batch, Sequence) and not isinstance(batch, (bytes, bytearray, str)):
201
+ mutated_sequence = list(batch)
202
+ for index in targets:
203
+ if not isinstance(index, int):
204
+ raise TypeError("Sequence batches require integer column indices")
205
+ try:
206
+ mutated_sequence[index] = corrupt_text_value(mutated_sequence[index], gaggle)
207
+ except IndexError as exc: # pragma: no cover - defensive
208
+ raise IndexError("Column index out of range for DataLoader batch") from exc
209
+ if isinstance(batch, tuple):
210
+ return tuple(mutated_sequence)
211
+ return mutated_sequence
212
+
213
+ raise TypeError("Unsupported DataLoader batch type for glitching")
214
+
215
+
216
+ class BaseGlitchedDataLoader:
217
+ """Proxy dataloader that glitches batches produced by the wrapped loader.
218
+
219
+ This class wraps a dataloader and applies glitchlings to specified columns
220
+ in each batch as it's yielded. It supports both mapping-based batches (dict-like)
221
+ and sequence-based batches (list/tuple-like).
222
+ """
223
+
224
+ def __init__(self, dataloader: Any, columns: list[str | int], gaggle: Gaggle) -> None:
225
+ """Initialize the glitched dataloader.
226
+
227
+ Args:
228
+ dataloader: The underlying dataloader to wrap.
229
+ columns: List of column names (strings) or indices (ints) to corrupt.
230
+ gaggle: The gaggle of glitchlings to apply.
231
+ """
232
+ self._dataloader = dataloader
233
+ self._columns = columns
234
+ self._gaggle = gaggle
235
+
236
+ def __iter__(self) -> Any:
237
+ """Yield corrupted batches from the underlying dataloader."""
238
+ for batch in self._dataloader:
239
+ yield corrupt_batch(batch, self._columns, self._gaggle)
240
+
241
+ def __len__(self) -> int:
242
+ """Return the number of batches in the dataloader."""
243
+ return len(self._dataloader)
244
+
245
+ def __getattr__(self, attribute: str) -> Any:
246
+ """Proxy attribute access to the underlying dataloader."""
247
+ return getattr(self._dataloader, attribute)
248
+
249
+
250
+ def wrap_dataloader(dataloader: Any, columns: list[str | int], gaggle: Gaggle) -> Any:
251
+ """Wrap a dataloader (or nested structure) to apply glitchlings lazily.
252
+
253
+ This function recursively wraps dataloaders in nested structures (mappings,
254
+ lists, tuples, etc.) so that all dataloaders in the structure will yield
255
+ corrupted batches.
256
+
257
+ Args:
258
+ dataloader: The dataloader or nested structure to wrap.
259
+ columns: List of column names (strings) or indices (ints) to corrupt.
260
+ gaggle: The gaggle of glitchlings to apply.
261
+
262
+ Returns:
263
+ The wrapped dataloader or structure, with the same type as the input.
264
+ """
265
+ if dataloader is None:
266
+ return None
267
+
268
+ if isinstance(dataloader, Mapping):
269
+ mapping_type = cast(type[Any], dataloader.__class__)
270
+ return mapping_type(
271
+ {key: wrap_dataloader(value, columns, gaggle) for key, value in dataloader.items()}
272
+ )
273
+
274
+ if isinstance(dataloader, list):
275
+ return [wrap_dataloader(value, columns, gaggle) for value in dataloader]
276
+
277
+ if isinstance(dataloader, tuple):
278
+ return tuple(wrap_dataloader(value, columns, gaggle) for value in dataloader)
279
+
280
+ if isinstance(dataloader, Sequence) and not isinstance(dataloader, (str, bytes, bytearray)):
281
+ sequence_type = cast(type[Any], dataloader.__class__)
282
+ return sequence_type(wrap_dataloader(value, columns, gaggle) for value in dataloader)
283
+
284
+ return BaseGlitchedDataLoader(dataloader, columns, gaggle)
285
+
286
+
287
+ __all__ = [
288
+ "BaseGlitchedDataLoader",
289
+ "corrupt_batch",
290
+ "corrupt_text_value",
291
+ "infer_batch_targets",
292
+ "is_textual_candidate",
293
+ "normalize_column_spec",
294
+ "resolve_columns",
295
+ "wrap_dataloader",
296
+ ]