Create typo_mutator.py
Browse files
prompt_injection/mutators/typo_mutator.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import random
|
| 3 |
+
import math
|
| 4 |
+
import string
|
| 5 |
+
from prompt_injection.mutators.base import PromptMutator
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class TypoPromptMutator(PromptMutator):
|
| 9 |
+
def __init__(self,percentage=0.05):
|
| 10 |
+
self.percentage=percentage
|
| 11 |
+
|
| 12 |
+
def mutate(self,sample:str)->str:
|
| 13 |
+
return self.__add_typos_to_text(sample,self.percentage)
|
| 14 |
+
|
| 15 |
+
def get_name(self):
|
| 16 |
+
return f'TypoPromptMutator-{self.percentage}'
|
| 17 |
+
|
| 18 |
+
def __introduce_typos(self,word):
|
| 19 |
+
char_list = list(word)
|
| 20 |
+
i = random.randint(0, len(char_list) - 1)
|
| 21 |
+
char_list[i] = random.choice(string.ascii_lowercase)
|
| 22 |
+
return ''.join(char_list)
|
| 23 |
+
|
| 24 |
+
def __add_typos_to_text(self,text, change_percentage=0.05):
|
| 25 |
+
words = text.split()
|
| 26 |
+
num_words = len(words)
|
| 27 |
+
num_changes = math.ceil(num_words * change_percentage)
|
| 28 |
+
words_to_change = random.sample(words, min(num_changes, num_words))
|
| 29 |
+
for i, word in enumerate(words):
|
| 30 |
+
if word in words_to_change:
|
| 31 |
+
words[i] = self.__introduce_typos(word)
|
| 32 |
+
|
| 33 |
+
return ' '.join(words)
|