Repository navigation
FEAT: Add PigLatinConverter (pig_latin converter) #4447
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Roman Lutz (romanlutz)
wants to merge
5
commits into
microsoft:main
Choose a base branch
from
romanlutz:gap1-piglatin
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+386
−5
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
77dcf5f
FEAT: Add PigLatinConverter (pig_latin converter)
romanlutz 61eb332
Merge latest main into gap1-piglatin
romanlutz f1b7a14
Merge latest main into gap1-piglatin
romanlutz 3806abc
FIX: PigLatinConverter splits on all whitespace and avoids regex back…
romanlutz 047ea81
Merge remote-tracking branch 'origin/main' into gap1-piglatin
romanlutz File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.ipynbwith 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 refresh0_converters.ipynb's generated modality table, which omitsPigLatinConverter; the existing table code already discovers the converter.There was a problem hiding this comment.
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.ipynband the0_converters.ipynbmodality 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.