Skip to content

BUG: InsertPunctuationConverter inserts punctuation inside words with accents or Indic vowel signs #4474

Done

Description

Describe the bug

In its default between-words mode, InsertPunctuationConverter should only put punctuation before or after a word. But it splits words with \w+, which stops at combining marks (accents written as a separate code point, Indic vowel signs and viramas). Each mark becomes its own "non-word" token, so a word like नमस्ते is treated as several words and punctuation lands inside it, detaching the vowel sign from its letter. The word count used for word_swap_ratio is also wrong for these words.

This is the same class of bug fixed in SATAMaskingConverter by #4390.

Steps/Code to Reproduce

import asyncio
from pyrit.converter import InsertPunctuationConverter

async def main():
    for text in ["café", "नमस्ते"]:
        for seed in range(3):
            c = InsertPunctuationConverter(word_swap_ratio=1.0, seed=seed)
            r = await c.convert_async(prompt=text, punctuation_list=["!"])
            print(repr(r.output_text))

asyncio.run(main())

Expected Results

One ! before or after the whole word: '!café' / 'café!', '!नमस्ते' / 'नमस्ते!'.

Actual Results

'cafe!́'      # accent now sits on "!"
'!café'
'cafe!́'
'!नमस्!ते'
'नमस!्त!े'
'नमस!्!ते'

Root cause

# Words list contains single spaces, single word without punctuations, single punctuations
words = re.findall(r"\w+|[^\w\s]|\s", prompt)

re.findall(r"\w+|[^\w\s]|\s", prompt): combining marks are not \w, so they fall into [^\w\s] as separate tokens. Matching them as part of the preceding word (regex.findall(r"\w[\w\p{M}]*|[^\w\s]|\s", prompt), regex is already a dependency) fixes it.

I have a fix with a test and can open a PR.

Metadata

Metadata

Labels

Bug: triageconverters

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions