Repository navigation
FEAT: Add RegionalIndicatorConverter (regional_indicator converter) #4450
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
7
commits into
microsoft:main
Choose a base branch
from
romanlutz:gap1-regional
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.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
085f5aa
FEAT: Add RegionalIndicatorConverter (regional_indicator converter)
romanlutz f7cf0ca
Merge latest main into gap1-regional
romanlutz ff7f7cf
Merge latest main into gap1-regional
romanlutz e0e9ad1
TEST: Cover regional_indicator scenario registration end to end
romanlutz 2480ef8
DOC: Update garak scanner technique list to 20 (add Columnar, Regiona…
romanlutz e5136fe
FIX: Separate converted regional-indicator tiles from existing indica…
romanlutz b73d165
Merge remote-tracking branch 'origin/main' into gap1-regional
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,89 @@ | ||
| # Copyright (c) Microsoft Corporation. | ||
| # Licensed under the MIT license. | ||
|
|
||
|
|
||
| from pyrit.converter.converter import Converter, ConverterResult | ||
| from pyrit.models import PromptDataType | ||
|
|
||
|
|
||
| class RegionalIndicatorConverter(Converter): | ||
| """ | ||
| Converts ASCII letters to Unicode Regional Indicator Symbols (the "flag letters"). | ||
|
|
||
| Each letter A-Z (case-insensitive) is mapped to the corresponding code point in the | ||
| Regional Indicator Symbol block, U+1F1E6 (REGIONAL INDICATOR SYMBOL LETTER A) through | ||
| U+1F1FF (REGIONAL INDICATOR SYMBOL LETTER Z). These square letter tiles were introduced | ||
| to encode ISO 3166-1 region codes: rendered in pairs they become emoji flags (for | ||
| example "US" -> the flag of the United States), but a single tile displays as a | ||
| boxed capital letter. | ||
|
|
||
| To keep the output readable letter-by-letter rather than collapsing consecutive pairs | ||
| into flag emoji, a ZERO WIDTH NON-JOINER (U+200C) is inserted between two adjacent | ||
| regional indicators whenever at least one of them was produced by this converter. The | ||
| joiner is invisible and breaks the flag sequence defined in UTS #51, so "US" renders as | ||
| two boxed letters instead of one flag. Two regional indicators that were both already in | ||
| the input (an existing flag) are left joined, so pre-existing flags are preserved. | ||
| Non-letter characters (digits, punctuation, spaces, and anything outside the Latin | ||
| alphabet) are left unchanged, which also naturally breaks any flag run. | ||
|
|
||
| This is a purely typographic transform with no formal academic source; it was | ||
| popularized as an emoji-flag obfuscation trick, in the spirit of the P4RS3LT0NGV3 | ||
| (parseltongue) toolkit: https://github.com/BASI-LABS/parseltongue | ||
|
|
||
| Note: This converter is useful for testing how AI systems handle text disguised as | ||
| emoji-flag tiles, which can be used to obfuscate potentially harmful content. | ||
| """ | ||
|
|
||
| SUPPORTED_INPUT_TYPES = ("text",) | ||
| SUPPORTED_OUTPUT_TYPES = ("text",) | ||
|
|
||
| #: First code point of the Regional Indicator Symbol block (letter A). | ||
| _REGIONAL_INDICATOR_A = 0x1F1E6 | ||
| #: Last code point of the Regional Indicator Symbol block (letter Z). | ||
| _REGIONAL_INDICATOR_Z = 0x1F1FF | ||
| #: Zero-width non-joiner inserted between adjacent tiles to prevent flag formation. | ||
| _SEPARATOR = "" | ||
|
|
||
| async def convert_async(self, *, prompt: str, input_type: PromptDataType = "text") -> ConverterResult: | ||
| """ | ||
| Convert the given text into Regional Indicator Symbols. | ||
|
|
||
| Args: | ||
| prompt (str): The text to convert. | ||
| input_type (PromptDataType, optional): Type of input data. Defaults to "text". | ||
|
|
||
| Returns: | ||
| ConverterResult: The text with ASCII letters replaced by regional indicators. | ||
|
|
||
| Raises: | ||
| ValueError: If the input type is not supported (only "text" is supported). | ||
| """ | ||
| if not self.input_supported(input_type): | ||
| raise ValueError("Input type not supported") | ||
|
|
||
| result: list[str] = [] | ||
| # Track the previously emitted character: whether it was a regional indicator at all, and | ||
| # whether that indicator was one this converter produced (vs. already present in the input). | ||
| previous_was_indicator = False | ||
| previous_was_converted = False | ||
| for char in prompt: | ||
| if "a" <= char.lower() <= "z" and char.isascii(): | ||
| emitted = chr(self._REGIONAL_INDICATOR_A + ord(char.lower()) - ord("a")) | ||
| is_indicator = True | ||
| is_converted = True | ||
| else: | ||
| emitted = char | ||
| is_converted = False | ||
| is_indicator = self._REGIONAL_INDICATOR_A <= ord(char) <= self._REGIONAL_INDICATOR_Z | ||
|
|
||
| # Separate two adjacent indicators only when at least one was produced here, so a newly | ||
| # converted letter cannot form a flag with a neighbor. Two indicators that were both | ||
| # already in the input (an existing flag) are left joined. | ||
| if is_indicator and previous_was_indicator and (is_converted or previous_was_converted): | ||
| result.append(self._SEPARATOR) | ||
|
|
||
| result.append(emitted) | ||
| previous_was_indicator = is_indicator | ||
| previous_was_converted = is_converted and is_indicator | ||
|
|
||
| return ConverterResult(output_text="".join(result), output_type="text") |
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
152 changes: 152 additions & 0 deletions
152
tests/unit/converter/test_regional_indicator_converter.py
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,152 @@ | ||
| # Copyright (c) Microsoft Corporation. | ||
| # Licensed under the MIT license. | ||
|
|
||
| import pytest | ||
|
|
||
| from pyrit.converter import ConverterResult, RegionalIndicatorConverter | ||
|
|
||
| # U+1F1E6 REGIONAL INDICATOR SYMBOL LETTER A. | ||
| REGIONAL_INDICATOR_A = 0x1F1E6 | ||
| # Zero-width non-joiner inserted between adjacent tiles. | ||
| ZWNJ = "" | ||
|
|
||
|
|
||
| def _tile(letter: str) -> str: | ||
| """Return the regional indicator tile for a single ASCII letter a-z/A-Z.""" | ||
| return chr(REGIONAL_INDICATOR_A + ord(letter.lower()) - ord("a")) | ||
|
|
||
|
|
||
| async def test_regional_indicator_simple_letters(): | ||
| """Each letter maps to its regional indicator, separated by a zero-width non-joiner.""" | ||
| converter = RegionalIndicatorConverter() | ||
|
|
||
| result = await converter.convert_async(prompt="abc", input_type="text") | ||
|
|
||
| assert isinstance(result, ConverterResult) | ||
| assert result.output_type == "text" | ||
| assert result.output_text == _tile("a") + ZWNJ + _tile("b") + ZWNJ + _tile("c") | ||
|
|
||
|
|
||
| async def test_regional_indicator_case_insensitive(): | ||
| """Uppercase and lowercase letters map to the same tiles.""" | ||
| converter = RegionalIndicatorConverter() | ||
|
|
||
| lower = await converter.convert_async(prompt="hello", input_type="text") | ||
| upper = await converter.convert_async(prompt="HELLO", input_type="text") | ||
|
|
||
| assert lower.output_text == upper.output_text | ||
|
|
||
|
|
||
| async def test_regional_indicator_known_code_points(): | ||
| """A -> U+1F1E6 and Z -> U+1F1FF (block boundaries).""" | ||
| converter = RegionalIndicatorConverter() | ||
|
|
||
| result = await converter.convert_async(prompt="AZ", input_type="text") | ||
|
|
||
| assert result.output_text == chr(0x1F1E6) + ZWNJ + chr(0x1F1FF) | ||
|
|
||
|
|
||
| async def test_regional_indicator_non_letters_unchanged(): | ||
| """Digits, punctuation, and spaces pass through unchanged and break the tile run.""" | ||
| converter = RegionalIndicatorConverter() | ||
|
|
||
| result = await converter.convert_async(prompt="a1 b", input_type="text") | ||
|
|
||
| # "a" then "1", space pass through, then "b". No separator is inserted because | ||
| # the letters are not adjacent. | ||
| assert result.output_text == _tile("a") + "1 " + _tile("b") | ||
|
|
||
|
|
||
| async def test_regional_indicator_separator_only_between_adjacent_tiles(): | ||
| """The non-joiner appears only between consecutive tiles, not around non-letters.""" | ||
| converter = RegionalIndicatorConverter() | ||
|
|
||
| result = await converter.convert_async(prompt="ab cd", input_type="text") | ||
|
|
||
| expected = _tile("a") + ZWNJ + _tile("b") + " " + _tile("c") + ZWNJ + _tile("d") | ||
| assert result.output_text == expected | ||
| # The space-separated pair should not be joined. | ||
| assert f"{_tile('b')} {_tile('c')}" in result.output_text | ||
|
|
||
|
|
||
| async def test_regional_indicator_single_letter_has_no_separator(): | ||
| """A single letter produces one tile with no separator.""" | ||
| converter = RegionalIndicatorConverter() | ||
|
|
||
| result = await converter.convert_async(prompt="x", input_type="text") | ||
|
|
||
| assert result.output_text == _tile("x") | ||
| assert ZWNJ not in result.output_text | ||
|
|
||
|
|
||
| async def test_regional_indicator_separates_converted_tile_from_existing_indicator_after(): | ||
| """A converted letter next to a pre-existing indicator in the input must not form a flag.""" | ||
| converter = RegionalIndicatorConverter() | ||
|
|
||
| # Input: existing indicator U (already a tile) immediately followed by the letter S. | ||
| result = await converter.convert_async(prompt=_tile("u") + "S", input_type="text") | ||
|
|
||
| # Without the fix this returned the joined pair _tile("u")+_tile("s") -> the "US" flag. | ||
| assert result.output_text == _tile("u") + ZWNJ + _tile("s") | ||
|
|
||
|
|
||
| async def test_regional_indicator_separates_converted_tile_from_existing_indicator_before(): | ||
| """Same, with the existing indicator on the other side of the converted letter.""" | ||
| converter = RegionalIndicatorConverter() | ||
|
|
||
| # Input: the letter U followed by an existing indicator S. | ||
| result = await converter.convert_async(prompt="U" + _tile("s"), input_type="text") | ||
|
|
||
| assert result.output_text == _tile("u") + ZWNJ + _tile("s") | ||
|
|
||
|
|
||
| async def test_regional_indicator_preserves_existing_flag(): | ||
| """Two indicators that were both already in the input (an existing flag) are left joined.""" | ||
| converter = RegionalIndicatorConverter() | ||
|
|
||
| existing_flag = _tile("u") + _tile("s") | ||
| result = await converter.convert_async(prompt=existing_flag, input_type="text") | ||
|
|
||
| # Neither tile was produced by the converter, so no separator is inserted. | ||
| assert result.output_text == existing_flag | ||
| assert ZWNJ not in result.output_text | ||
|
|
||
|
|
||
| async def test_regional_indicator_empty_prompt(): | ||
| """An empty prompt yields empty output.""" | ||
| converter = RegionalIndicatorConverter() | ||
|
|
||
| result = await converter.convert_async(prompt="", input_type="text") | ||
|
|
||
| assert result.output_text == "" | ||
|
|
||
|
|
||
| async def test_regional_indicator_non_ascii_letters_pass_through(): | ||
| """Accented and non-Latin letters have no regional indicator and are left unchanged.""" | ||
| converter = RegionalIndicatorConverter() | ||
|
|
||
| result = await converter.convert_async(prompt="café中", input_type="text") | ||
|
|
||
| assert result.output_text == _tile("c") + ZWNJ + _tile("a") + ZWNJ + _tile("f") + "é中" | ||
|
|
||
|
|
||
| async def test_regional_indicator_input_type_not_supported(): | ||
| """Non-text input types raise ValueError.""" | ||
| converter = RegionalIndicatorConverter() | ||
|
|
||
| with pytest.raises(ValueError, match="Input type not supported"): | ||
| await converter.convert_async(prompt="test", input_type="image_path") | ||
|
|
||
|
|
||
| def test_regional_indicator_input_supported(): | ||
| """input_supported only accepts text.""" | ||
| converter = RegionalIndicatorConverter() | ||
| assert converter.input_supported("text") is True | ||
| assert converter.input_supported("image_path") is False | ||
|
|
||
|
|
||
| def test_regional_indicator_output_supported(): | ||
| """output_supported only accepts text.""" | ||
| converter = RegionalIndicatorConverter() | ||
| assert converter.output_supported("text") is True | ||
| assert converter.output_supported("image_path") is False |
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.
This still applies at the current head: the paired notebook has neither the import nor the example. Also update the saved modality table in
0_converters.ipynb, which omitsRegionalIndicatorConverter; the converter instructions require that reference update. Its source already discovers converters dynamically, so no hard-coded row is needed.Verified on commit
085f5aa95f50f863e6dd2935f666c6013b5aa575.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 code defects on this PR (the flag-boundary separation and the scenario-selection test) are fixed in the latest push. The paired-notebook sync is not included:
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 correct saved output for here. Leaving this open so it is tracked.