Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions doc/code/converters/1_text_to_text_converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
MorseConverter,
NatoConverter,
NegationTrapConverter,
PigLatinConverter,
ROT13Converter,
TokenBijectionConverter,
VigenereConverter,
Expand All @@ -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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Synchronize the published converter notebooks

Update the paired 1_text_to_text_converters.ipynb with this import, example, and saved output. The documentation builds the committed notebooks without executing the percent-format source, so readers do not see the Pig Latin example added here. Also refresh 0_converters.ipynb's generated modality table, which omits PigLatinConverter; the existing table code already discovers the converter.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The two code defects in this thread-set (whitespace splitting and the regex backtracking) are fixed in the latest push. The paired-notebook sync is not in this push: 1_text_to_text_converters.ipynb and the 0_converters.ipynb modality table need a docs build that executes the notebooks (later cells call live LLM targets and need credentials), which I can't produce a correct saved output for here. Leaving this thread open so it is tracked; happy to add the notebook once it can be regenerated with a real run.

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
Expand Down
4 changes: 2 additions & 2 deletions doc/scanner/garak.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
4 changes: 2 additions & 2 deletions doc/scanner/garak.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions pyrit/converter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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",
Expand Down
183 changes: 183 additions & 0 deletions pyrit/converter/pig_latin_converter.py
Original file line number Diff line number Diff line change
@@ -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
3 changes: 3 additions & 0 deletions pyrit/scenario/scenarios/garak/encoding.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
LeetspeakConverter,
MorseConverter,
NatoConverter,
PigLatinConverter,
ROT13Converter,
SearchReplaceConverter,
ZalgoConverter,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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"),
Expand Down
Loading
Loading