diff --git a/doc/code/converters/1_text_to_text_converters.py b/doc/code/converters/1_text_to_text_converters.py index 8c04acc6af..b805bf6e3c 100644 --- a/doc/code/converters/1_text_to_text_converters.py +++ b/doc/code/converters/1_text_to_text_converters.py @@ -64,6 +64,7 @@ MorseConverter, NatoConverter, NegationTrapConverter, + PigLatinConverter, ROT13Converter, TokenBijectionConverter, VigenereConverter, @@ -84,6 +85,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/doc/scanner/garak.ipynb b/doc/scanner/garak.ipynb index 4b3f1143a4..e51ee50167 100644 --- a/doc/scanner/garak.ipynb +++ b/doc/scanner/garak.ipynb @@ -303,9 +303,9 @@ "pyrit_scan run garak.encoding --target openai_chat --techniques base64 --max-total 1\n", "```\n", "\n", - "**Available techniques** (20 encodings): Base64, Base2048, Base16, Base32, ASCII85, Hex,\n", + "**Available techniques** (21 encodings): Base64, Base2048, Base16, Base32, ASCII85, Hex,\n", "QuotedPrintable, UUencode, ROT13, Braille, Atbash, MorseCode, NATO, Ecoji, Zalgo, LeetSpeak,\n", - "AsciiSmuggler, Bifid, ColumnarTransposition, UbbiDubbi\n", + "AsciiSmuggler, Bifid, ColumnarTransposition, UbbiDubbi, PigLatin\n", "\n", "**Aggregate techniques:** `ALL` (every encoding, exhaustive) and `DEFAULT` (a broad curated subset\n", "spanning every encoding family — base-N, byte-encodings, substitution ciphers, and symbolic\n", diff --git a/doc/scanner/garak.py b/doc/scanner/garak.py index 33b72d4a44..fd32f1e52a 100644 --- a/doc/scanner/garak.py +++ b/doc/scanner/garak.py @@ -136,9 +136,9 @@ # pyrit_scan run garak.encoding --target openai_chat --techniques base64 --max-total 1 # ``` # -# **Available techniques** (20 encodings): Base64, Base2048, Base16, Base32, ASCII85, Hex, +# **Available techniques** (21 encodings): Base64, Base2048, Base16, Base32, ASCII85, Hex, # QuotedPrintable, UUencode, ROT13, Braille, Atbash, MorseCode, NATO, Ecoji, Zalgo, LeetSpeak, -# AsciiSmuggler, Bifid, ColumnarTransposition, UbbiDubbi +# AsciiSmuggler, Bifid, ColumnarTransposition, UbbiDubbi, PigLatin # # **Aggregate techniques:** `ALL` (every encoding, exhaustive) and `DEFAULT` (a broad curated subset # spanning every encoding family — base-N, byte-encodings, substitution ciphers, and symbolic diff --git a/pyrit/converter/__init__.py b/pyrit/converter/__init__.py index 1e6375f545..7c8bb74985 100644 --- a/pyrit/converter/__init__.py +++ b/pyrit/converter/__init__.py @@ -89,6 +89,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 @@ -222,6 +223,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..b2107ac003 --- /dev/null +++ b/pyrit/converter/pig_latin_converter.py @@ -0,0 +1,183 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import string + +from pyrit.converter.text_selection_strategy import ( + AllWordsSelectionStrategy, + WordSelectionStrategy, +) +from pyrit.converter.word_level_converter import WordLevelConverter +from pyrit.models import ComponentIdentifier + +_ASCII_LETTERS = frozenset(string.ascii_letters) +_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. + """ + # ``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( + 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 + + @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. + + Args: + word (str): The token to convert (may carry leading/trailing punctuation). + + Returns: + str: The Pig Latin token with punctuation and capitalization preserved. + """ + 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 + 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 3d07dd9d46..60960ba156 100644 --- a/pyrit/scenario/scenarios/garak/encoding.py +++ b/pyrit/scenario/scenarios/garak/encoding.py @@ -22,6 +22,7 @@ LeetspeakConverter, MorseConverter, NatoConverter, + PigLatinConverter, ROT13Converter, SearchReplaceConverter, ZalgoConverter, @@ -130,6 +131,7 @@ class EncodingTechnique(ScenarioTechnique): AsciiSmuggler = ("ascii_smuggler", set[str]()) Bifid = ("bifid", set[str]()) ColumnarTransposition = ("columnar_transposition", set[str]()) + PigLatin = ("pig_latin", set[str]()) UbbiDubbi = ("ubbi_dubbi", set[str]()) @classmethod @@ -319,6 +321,7 @@ def _converter_variants() -> list[tuple[list[Converter], str, str]]: ([AsciiSmugglerConverter()], "ascii_smuggler", "ascii_smuggler"), ([BifidConverter()], "bifid", "bifid"), ([ColumnarTranspositionConverter(key="ZEBRAS")], "columnar_transposition", "columnar_transposition"), + ([PigLatinConverter()], "pig_latin", "pig_latin"), # "ubbi_dubbi": a language game that prefixes each vowel run with "ub", popularized by # the PBS children's show Zoom (1972). https://en.wikipedia.org/wiki/Ubbi_dubbi ([SearchReplaceConverter(pattern=r"([aeiouAEIOU]+)", replace=r"ub\1")], "ubbi_dubbi", "ubbi_dubbi"), 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..2a9257394e --- /dev/null +++ b/tests/unit/converter/test_pig_latin_converter.py @@ -0,0 +1,189 @@ +# 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,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", + [ + # 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 da4c169488..fd1b5e3f24 100644 --- a/tests/unit/scenario/garak/test_encoding.py +++ b/tests/unit/scenario/garak/test_encoding.py @@ -258,7 +258,7 @@ 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) == 20 + assert len(all_names) == 21 # The niche/lossy schemes stay ALL-only. assert all_names - default_names == { "braille", @@ -268,6 +268,7 @@ def test_default_aggregate_curates_representative_subset(self): "ubbi_dubbi", "bifid", "columnar_transposition", + "pig_latin", } def test_get_aggregate_tags_includes_default(self):