From 77dcf5ff1f6501acfc115493d98035e03e353987 Mon Sep 17 00:00:00 2001 From: Roman Lutz Date: Thu, 19 Nov 2026 15:23:53 -0800 Subject: [PATCH 1/2] FEAT: Add PigLatinConverter (pig_latin converter) Co-Authored-By: Claude Opus 4.8 --- .../converters/1_text_to_text_converters.py | 2 + pyrit/converter/__init__.py | 2 + pyrit/converter/pig_latin_converter.py | 164 ++++++++++++++++++ pyrit/scenario/scenarios/garak/encoding.py | 3 + .../converter/test_pig_latin_converter.py | 164 ++++++++++++++++++ .../registry/converter_identifier_samples.py | 1 + tests/unit/scenario/garak/test_encoding.py | 4 +- 7 files changed, 338 insertions(+), 2 deletions(-) create mode 100644 pyrit/converter/pig_latin_converter.py create mode 100644 tests/unit/converter/test_pig_latin_converter.py diff --git a/doc/code/converters/1_text_to_text_converters.py b/doc/code/converters/1_text_to_text_converters.py index 578a90c251..421ded545c 100644 --- a/doc/code/converters/1_text_to_text_converters.py +++ b/doc/code/converters/1_text_to_text_converters.py @@ -63,6 +63,7 @@ MorseConverter, NatoConverter, NegationTrapConverter, + PigLatinConverter, ROT13Converter, TokenBijectionConverter, VigenereConverter, @@ -83,6 +84,7 @@ print("ROT13:", await ROT13Converter().convert_async(prompt=prompt)) # type: ignore print("Base64:", await Base64Converter().convert_async(prompt=prompt)) # type: ignore print("Base2048:", await Base2048Converter().convert_async(prompt=prompt)) # type: ignore +print("Pig Latin:", await PigLatinConverter().convert_async(prompt=prompt)) # type: ignore print("Binary:", await BinaryConverter().convert_async(prompt=prompt)) # type: ignore print("BinAscii:", await BinAsciiConverter().convert_async(prompt=prompt)) # type: ignore print("Morse:", await MorseConverter().convert_async(prompt=prompt)) # type: ignore diff --git a/pyrit/converter/__init__.py b/pyrit/converter/__init__.py index 1c8722e5b2..6704ca7acf 100644 --- a/pyrit/converter/__init__.py +++ b/pyrit/converter/__init__.py @@ -88,6 +88,7 @@ from pyrit.converter.noise_converter import NoiseConverter from pyrit.converter.pdf_converter import PDFConverter from pyrit.converter.persuasion_converter import PersuasionConverter + from pyrit.converter.pig_latin_converter import PigLatinConverter from pyrit.converter.pinyin_converter import PinyinConverter from pyrit.converter.policy_puppetry_converter import PolicyPuppetryConverter, PolicyPuppetryTemplate from pyrit.converter.prompt_template_converter import PromptTemplateConverter @@ -220,6 +221,7 @@ "NoiseConverter": "pyrit.converter.noise_converter", "PDFConverter": "pyrit.converter.pdf_converter", "PersuasionConverter": "pyrit.converter.persuasion_converter", + "PigLatinConverter": "pyrit.converter.pig_latin_converter", "PinyinConverter": "pyrit.converter.pinyin_converter", "PolicyPuppetryConverter": "pyrit.converter.policy_puppetry_converter", "PolicyPuppetryTemplate": "pyrit.converter.policy_puppetry_converter", diff --git a/pyrit/converter/pig_latin_converter.py b/pyrit/converter/pig_latin_converter.py new file mode 100644 index 0000000000..5929d4da40 --- /dev/null +++ b/pyrit/converter/pig_latin_converter.py @@ -0,0 +1,164 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import re + +from pyrit.converter.text_selection_strategy import ( + AllWordsSelectionStrategy, + WordSelectionStrategy, +) +from pyrit.converter.word_level_converter import WordLevelConverter +from pyrit.models import ComponentIdentifier + +# Split a whitespace-delimited token into leading non-letters, an alphabetic core +# (from the first letter to the last letter, interior punctuation included), and +# trailing non-letters. Leading/trailing punctuation is preserved verbatim so that +# marks like ``"`` ``(`` ``)`` ``.`` ``,`` stay where they were. +_TOKEN_PATTERN = re.compile(r"^([^A-Za-z]*)(.*?)([^A-Za-z]*)$") + +_VOWELS = frozenset("aeiou") +_VALID_VOWEL_SUFFIXES = ("way", "yay", "ay") + + +class PigLatinConverter(WordLevelConverter): + """ + Converts text into Pig Latin, the English schoolyard language game. + + Pig Latin is a folk/word game with NO formal academic source; the ruleset below follows the + conventional description (e.g. the Wikipedia "Pig Latin" article). Because usage varies between + speakers, the exact handling of edge cases (the vowel-initial suffix, the letter ``y``, words + with no vowels) is a documented choice rather than a canonical standard. + + Ruleset applied to each whitespace-delimited token: + + 1. Leading and trailing non-letter characters (punctuation, digits, brackets, quotes) are split + off and re-attached unchanged. Only the alphabetic core is transformed. + 2. Consonant-initial words: the leading consonant cluster is moved to the end and ``"ay"`` is + appended. Example: ``"hello"`` -> ``"ellohay"``, ``"string"`` -> ``"ingstray"``. + 3. Vowel-initial words (first letter in ``a e i o u``): a suffix is appended. The default suffix + is ``"way"`` (``"apple"`` -> ``"appleway"``); ``"yay"`` and ``"ay"`` are also selectable. + 4. The letter ``y`` is treated as a consonant when it is the first letter (so it can lead a + cluster: ``"yellow"`` -> ``"ellowyay"``) but as a vowel elsewhere, which lets it terminate a + consonant cluster (``"my"`` -> ``"ymay"``, ``"rhythm"`` -> ``"ythmrhay"``). + 5. Words with no vowel at all keep their whole core as the "cluster" (``"nth"`` -> ``"nthay"``). + 6. Capitalization is reapplied to the result: an all-uppercase core (more than one letter) + yields an uppercase result (``"HELLO"`` -> ``"ELLOHAY"``); a title-cased core capitalizes the + first letter of the result (``"Hello"`` -> ``"Ellohay"``); otherwise the result is lowercase. + + The transform is intentionally lossy/ambiguous (several inputs can map to the same output), so it + is registered as an ALL-only encoding technique in the garak Encoding scenario. + """ + + def __init__( + self, + *, + vowel_initial_suffix: str = "way", + word_selection_strategy: WordSelectionStrategy | None = None, + ) -> None: + """ + Initialize the Pig Latin converter. + + Args: + vowel_initial_suffix (str): Suffix appended to vowel-initial words. One of ``"way"`` + (default), ``"yay"``, or ``"ay"``. + word_selection_strategy (WordSelectionStrategy | None): Strategy for selecting which words + to convert. If None, all words will be converted. + + Raises: + ValueError: If ``vowel_initial_suffix`` is not one of the supported values. + """ + super().__init__(word_selection_strategy=word_selection_strategy) + + if vowel_initial_suffix not in _VALID_VOWEL_SUFFIXES: + raise ValueError( + f"vowel_initial_suffix must be one of {_VALID_VOWEL_SUFFIXES}, got {vowel_initial_suffix!r}." + ) + self._vowel_initial_suffix = vowel_initial_suffix + + def _build_identifier(self) -> ComponentIdentifier: + """ + Build the converter identifier with Pig Latin parameters. + + Returns: + ComponentIdentifier: The identifier for this converter. + """ + selection_params = ( + {} + if type(self._word_selection_strategy) is AllWordsSelectionStrategy + else super()._build_identifier().params + ) + return self._create_identifier( + params={ + **selection_params, + "vowel_initial_suffix": self._vowel_initial_suffix, + }, + ) + + def _pig_latin_core(self, core_lower: str) -> str: + """ + Apply the Pig Latin transform to the lowercased alphabetic core of a single word. + + Args: + core_lower (str): The word core, already lowercased, beginning with a letter. + + Returns: + str: The transformed (still lowercase) core. + """ + if core_lower[0] in _VOWELS: + return core_lower + self._vowel_initial_suffix + + # Consonant-initial: find where the leading consonant cluster ends. The first letter is a + # consonant, so scan from index 1; ``y`` counts as a vowel here (it terminates the cluster). + split_index = 1 + while split_index < len(core_lower): + char = core_lower[split_index] + if char in _VOWELS or char == "y": + break + split_index += 1 + + cluster = core_lower[:split_index] + rest = core_lower[split_index:] + return rest + cluster + "ay" + + @staticmethod + def _apply_case(*, core: str, transformed: str) -> str: + """ + Reapply the original word's capitalization to the (lowercase) transformed word. + + Args: + core (str): The original, un-lowercased word core. + transformed (str): The transformed word, in lowercase. + + Returns: + str: The transformed word with capitalization restored. + """ + letters = [char for char in core if char.isalpha()] + if len(letters) > 1 and all(char.isupper() for char in letters): + return transformed.upper() + if letters and letters[0].isupper(): + return transformed[:1].upper() + transformed[1:] + return transformed + + async def convert_word_async(self, word: str) -> str: + """ + Convert a single whitespace-delimited token into Pig Latin. + + Args: + word (str): The token to convert (may carry leading/trailing punctuation). + + Returns: + str: The Pig Latin token with punctuation and capitalization preserved. + """ + match = _TOKEN_PATTERN.match(word) + # The pattern matches any string, so ``match`` is never None; the guard satisfies type checkers. + if match is None: # pragma: no cover + return word + # ``re.Match.group`` is typed ``str | Any``; wrap in ``str`` so the concatenated return + # below is definitively ``str`` (the groups always participate, so this never changes a value). + prefix, core, suffix = str(match.group(1)), str(match.group(2)), str(match.group(3)) + if not core: + # Token has no letters (e.g. pure punctuation or digits); leave it unchanged. + return word + transformed = self._pig_latin_core(core.lower()) + transformed = self._apply_case(core=core, transformed=transformed) + return prefix + transformed + suffix diff --git a/pyrit/scenario/scenarios/garak/encoding.py b/pyrit/scenario/scenarios/garak/encoding.py index 2540179e26..3be7a04ebb 100644 --- a/pyrit/scenario/scenarios/garak/encoding.py +++ b/pyrit/scenario/scenarios/garak/encoding.py @@ -21,6 +21,7 @@ LeetspeakConverter, MorseConverter, NatoConverter, + PigLatinConverter, ROT13Converter, ZalgoConverter, ) @@ -127,6 +128,7 @@ class EncodingTechnique(ScenarioTechnique): LeetSpeak = ("leet_speak", {"default"}) AsciiSmuggler = ("ascii_smuggler", set[str]()) Bifid = ("bifid", set[str]()) + PigLatin = ("pig_latin", set[str]()) @classmethod def get_aggregate_tags(cls) -> set[str]: @@ -314,6 +316,7 @@ def _converter_variants() -> list[tuple[list[Converter], str, str]]: ([LeetspeakConverter()], "leet_speak", "leet_speak"), ([AsciiSmugglerConverter()], "ascii_smuggler", "ascii_smuggler"), ([BifidConverter()], "bifid", "bifid"), + ([PigLatinConverter()], "pig_latin", "pig_latin"), ] # These are the same as Garak encoding attacks diff --git a/tests/unit/converter/test_pig_latin_converter.py b/tests/unit/converter/test_pig_latin_converter.py new file mode 100644 index 0000000000..262833c71b --- /dev/null +++ b/tests/unit/converter/test_pig_latin_converter.py @@ -0,0 +1,164 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import asyncio + +import pytest + +from pyrit.converter import PigLatinConverter + + +@pytest.mark.parametrize( + "input_text,expected_output", + [ + # Simple consonant-initial words: move the single leading consonant and add "ay". + ("hello", "ellohay"), + ("pig", "igpay"), + # Leading consonant *cluster* moves together. + ("string", "ingstray"), + ("glove", "oveglay"), + ("three", "eethray"), + ], +) +def test_consonant_cluster(input_text, expected_output): + converter = PigLatinConverter() + result = asyncio.run(converter.convert_async(prompt=input_text)) + assert result.output_text == expected_output + + +@pytest.mark.parametrize( + "input_text,expected_output", + [ + ("apple", "appleway"), + ("egg", "eggway"), + ("industry", "industryway"), + ("out", "outway"), + ], +) +def test_vowel_initial_default_suffix(input_text, expected_output): + converter = PigLatinConverter() + result = asyncio.run(converter.convert_async(prompt=input_text)) + assert result.output_text == expected_output + + +@pytest.mark.parametrize( + "suffix,expected_output", + [ + ("way", "appleway"), + ("yay", "appleyay"), + ("ay", "appleay"), + ], +) +def test_vowel_initial_configurable_suffix(suffix, expected_output): + converter = PigLatinConverter(vowel_initial_suffix=suffix) + result = asyncio.run(converter.convert_async(prompt="apple")) + assert result.output_text == expected_output + + +def test_invalid_suffix_raises(): + with pytest.raises(ValueError): + PigLatinConverter(vowel_initial_suffix="oink") + + +@pytest.mark.parametrize( + "input_text,expected_output", + [ + # Leading 'y' acts as a consonant and can lead the cluster. + ("yellow", "ellowyay"), + # Non-initial 'y' acts as a vowel and terminates the consonant cluster. + ("my", "ymay"), + ("rhythm", "ythmrhay"), + ("sky", "yskay"), + ], +) +def test_y_handling(input_text, expected_output): + converter = PigLatinConverter() + result = asyncio.run(converter.convert_async(prompt=input_text)) + assert result.output_text == expected_output + + +@pytest.mark.parametrize( + "input_text,expected_output", + [ + # Words with no vowel keep their whole core as the cluster. + ("nth", "nthay"), + ("shh", "shhay"), + ], +) +def test_no_vowel_words(input_text, expected_output): + converter = PigLatinConverter() + result = asyncio.run(converter.convert_async(prompt=input_text)) + assert result.output_text == expected_output + + +@pytest.mark.parametrize( + "input_text,expected_output", + [ + # Trailing punctuation stays attached after the word. + ("hello,", "ellohay,"), + ("hello.", "ellohay."), + ("hello!", "ellohay!"), + # Leading and trailing punctuation both preserved. + ("(hello)", "(ellohay)"), + ('"apple"', '"appleway"'), + # Interior apostrophe is kept inside the core. + ("it's", "it'sway"), + ], +) +def test_punctuation_preserved(input_text, expected_output): + converter = PigLatinConverter() + result = asyncio.run(converter.convert_async(prompt=input_text)) + assert result.output_text == expected_output + + +@pytest.mark.parametrize( + "input_text,expected_output", + [ + # Title case -> capitalized result. + ("Hello", "Ellohay"), + ("Apple", "Appleway"), + # All uppercase (more than one letter) -> uppercase result. + ("HELLO", "ELLOHAY"), + ("APPLE", "APPLEWAY"), + # Lowercase stays lowercase. + ("hello", "ellohay"), + ], +) +def test_capitalization(input_text, expected_output): + converter = PigLatinConverter() + result = asyncio.run(converter.convert_async(prompt=input_text)) + assert result.output_text == expected_output + + +def test_sentence_preserves_structure(): + converter = PigLatinConverter() + result = asyncio.run(converter.convert_async(prompt="The quick brown fox.")) + # "The" -> title-cased; punctuation attached to "fox". + assert result.output_text == "Ethay uickqay ownbray oxfay." + + +@pytest.mark.parametrize( + "input_text", + [ + # Tokens with no letters are returned unchanged. + "123", + "!!!", + "...", + ], +) +def test_non_letter_tokens_unchanged(input_text): + converter = PigLatinConverter() + result = asyncio.run(converter.convert_async(prompt=input_text)) + assert result.output_text == input_text + + +def test_empty_string(): + converter = PigLatinConverter() + result = asyncio.run(converter.convert_async(prompt="")) + assert result.output_text == "" + + +def test_unsupported_input_type_raises(): + converter = PigLatinConverter() + with pytest.raises(ValueError): + asyncio.run(converter.convert_async(prompt="hello", input_type="image_path")) diff --git a/tests/unit/registry/converter_identifier_samples.py b/tests/unit/registry/converter_identifier_samples.py index 117d61e2ee..6e1eafb358 100644 --- a/tests/unit/registry/converter_identifier_samples.py +++ b/tests/unit/registry/converter_identifier_samples.py @@ -410,6 +410,7 @@ def make_samples(folder: Path) -> dict[str, tuple[Any, ...]]: "seed": (0, 1), "random_seed": (0, 1), "CaesarConverter.caesar_offset": (1, -1, 2, 0, 24, 25), + "PigLatinConverter.vowel_initial_suffix": ("yay", "ay"), "trap_template": ( "{prompt} is {wrong_value}", "Is {prompt} {wrong_value}?", diff --git a/tests/unit/scenario/garak/test_encoding.py b/tests/unit/scenario/garak/test_encoding.py index 5db1297404..a5ca47a94c 100644 --- a/tests/unit/scenario/garak/test_encoding.py +++ b/tests/unit/scenario/garak/test_encoding.py @@ -253,9 +253,9 @@ def test_default_aggregate_curates_representative_subset(self): } all_names = {t.value for t in EncodingTechnique.get_all_techniques()} assert default_names < all_names - assert len(all_names) == 18 + assert len(all_names) == 19 # The niche/lossy schemes stay ALL-only. - assert all_names - default_names == {"braille", "ecoji", "zalgo", "ascii_smuggler", "bifid"} + assert all_names - default_names == {"braille", "ecoji", "zalgo", "ascii_smuggler", "bifid", "pig_latin"} def test_get_aggregate_tags_includes_default(self): """The scenario exposes both ``all`` and ``default`` as aggregate tags.""" From 3806abca7761282ea44925a69739fd86f8f88894 Mon Sep 17 00:00:00 2001 From: Roman Lutz Date: Sat, 21 Nov 2026 10:36:51 -0800 Subject: [PATCH 2/2] FIX: PigLatinConverter splits on all whitespace and avoids regex backtracking Addresses review feedback on #4447: - Split on any whitespace (word_split_separator=None) instead of spaces only, so tabs and newlines are word boundaries. Previously 'hello\nworld' was returned unconverted and 'hello\tworld' was transformed as one token. - Replace the lazy/greedy token regex (quadratic backtracking on punctuation-heavy tokens such as 'a' + '!'*n + 'b', which blocked the event loop) with a single linear affix scan to first/last ASCII letter. Adds tests for tab/newline splitting and a 10k-punctuation token. Co-Authored-By: Claude Opus 4.8 --- pyrit/converter/pig_latin_converter.py | 49 +++++++++++++------ .../converter/test_pig_latin_converter.py | 25 ++++++++++ 2 files changed, 59 insertions(+), 15 deletions(-) diff --git a/pyrit/converter/pig_latin_converter.py b/pyrit/converter/pig_latin_converter.py index 5929d4da40..b2107ac003 100644 --- a/pyrit/converter/pig_latin_converter.py +++ b/pyrit/converter/pig_latin_converter.py @@ -1,7 +1,7 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. -import re +import string from pyrit.converter.text_selection_strategy import ( AllWordsSelectionStrategy, @@ -10,12 +10,7 @@ from pyrit.converter.word_level_converter import WordLevelConverter from pyrit.models import ComponentIdentifier -# Split a whitespace-delimited token into leading non-letters, an alphabetic core -# (from the first letter to the last letter, interior punctuation included), and -# trailing non-letters. Leading/trailing punctuation is preserved verbatim so that -# marks like ``"`` ``(`` ``)`` ``.`` ``,`` stay where they were. -_TOKEN_PATTERN = re.compile(r"^([^A-Za-z]*)(.*?)([^A-Za-z]*)$") - +_ASCII_LETTERS = frozenset(string.ascii_letters) _VOWELS = frozenset("aeiou") _VALID_VOWEL_SUFFIXES = ("way", "yay", "ay") @@ -67,7 +62,10 @@ def __init__( Raises: ValueError: If ``vowel_initial_suffix`` is not one of the supported values. """ - super().__init__(word_selection_strategy=word_selection_strategy) + # ``word_split_separator=None`` splits on any whitespace (tabs and newlines, not just spaces), + # matching the documented "whitespace-delimited token" behavior. Runs of whitespace are then + # normalized to single spaces on rejoin, which is acceptable for this intentionally lossy game. + super().__init__(word_selection_strategy=word_selection_strategy, word_split_separator=None) if vowel_initial_suffix not in _VALID_VOWEL_SUFFIXES: raise ValueError( @@ -139,6 +137,33 @@ def _apply_case(*, core: str, transformed: str) -> str: return transformed[:1].upper() + transformed[1:] return transformed + @staticmethod + def _split_affixes(word: str) -> tuple[str, str, str]: + """ + Split a token into leading non-letters, an ASCII-letter core, and trailing non-letters. + + The core runs from the first ASCII letter to the last (interior punctuation included); + leading/trailing marks like ``"`` ``(`` ``)`` ``.`` ``,`` are preserved verbatim. This is a + single linear scan, avoiding the catastrophic backtracking a lazy/greedy regex exhibits on + punctuation-heavy tokens. + + Args: + word (str): The token to split. + + Returns: + tuple[str, str, str]: ``(prefix, core, suffix)``; ``core`` is empty when the token has + no ASCII letters. + """ + first = last = None + for index, char in enumerate(word): + if char in _ASCII_LETTERS: + if first is None: + first = index + last = index + if first is None or last is None: + return word, "", "" + return word[:first], word[first : last + 1], word[last + 1 :] + async def convert_word_async(self, word: str) -> str: """ Convert a single whitespace-delimited token into Pig Latin. @@ -149,13 +174,7 @@ async def convert_word_async(self, word: str) -> str: Returns: str: The Pig Latin token with punctuation and capitalization preserved. """ - match = _TOKEN_PATTERN.match(word) - # The pattern matches any string, so ``match`` is never None; the guard satisfies type checkers. - if match is None: # pragma: no cover - return word - # ``re.Match.group`` is typed ``str | Any``; wrap in ``str`` so the concatenated return - # below is definitively ``str`` (the groups always participate, so this never changes a value). - prefix, core, suffix = str(match.group(1)), str(match.group(2)), str(match.group(3)) + prefix, core, suffix = self._split_affixes(word) if not core: # Token has no letters (e.g. pure punctuation or digits); leave it unchanged. return word diff --git a/tests/unit/converter/test_pig_latin_converter.py b/tests/unit/converter/test_pig_latin_converter.py index 262833c71b..2a9257394e 100644 --- a/tests/unit/converter/test_pig_latin_converter.py +++ b/tests/unit/converter/test_pig_latin_converter.py @@ -137,6 +137,31 @@ def test_sentence_preserves_structure(): assert result.output_text == "Ethay uickqay ownbray oxfay." +@pytest.mark.parametrize( + "input_text,expected_output", + [ + # Tabs and newlines are word boundaries too (not only spaces); every word is converted. + ("hello\tworld", "ellohay orldway"), + ("hello\nworld", "ellohay orldway"), + ("one two\tthree\nfour", "oneway otway eethray ourfay"), + ], +) +def test_splits_on_all_whitespace(input_text, expected_output): + converter = PigLatinConverter() + result = asyncio.run(converter.convert_async(prompt=input_text)) + assert result.output_text == expected_output + + +def test_punctuation_heavy_token_is_linear_and_correct(): + # A long interior punctuation run must not trigger catastrophic regex backtracking; the linear + # affix scan returns promptly. The core runs first-letter..last-letter (interior '!' kept), and + # 'a' is vowel-initial, so "way" is appended. + token = "a" + "!" * 10000 + "b" + converter = PigLatinConverter() + result = asyncio.run(converter.convert_async(prompt=token)) + assert result.output_text == token + "way" + + @pytest.mark.parametrize( "input_text", [