from textattack import Attack as TAAttack
from textattack.constraints.pre_transformation import (
RepeatModification,
StopwordModification,
)
from textattack.transformations import (
CompositeTransformation,
WordSwapEmbedding,
WordSwapHomoglyphSwap,
WordSwapNeighboringCharacterSwap,
WordSwapRandomCharacterDeletion,
WordSwapRandomCharacterInsertion,
)
from textattack.constraints.semantics.sentence_encoders import UniversalSentenceEncoder
from textattack.goal_functions import UntargetedClassification
from textattack.search_methods import GreedyWordSwapWIR
from abs_text_attack.core.interfaces import Attack
[документация]
class TextBugger(Attack):
[документация]
@staticmethod
def build(model_wrapper, kwargs = {}):
use_params = kwargs.get("use_params", {})
gws_params = kwargs.get("gws_params", {})
word_swap_emb_params = kwargs.get("word_swap_emb_params", {})
transformation = CompositeTransformation(
[
WordSwapRandomCharacterInsertion(
random_one=True,
letters_to_insert=" ",
skip_first_char=True,
skip_last_char=True,
),
WordSwapRandomCharacterDeletion(
random_one=True, skip_first_char=True, skip_last_char=True
),
WordSwapNeighboringCharacterSwap(
random_one=True, skip_first_char=True, skip_last_char=True
),
WordSwapHomoglyphSwap(),
WordSwapEmbedding(max_candidates=word_swap_emb_params.get("max_candidates", 5)),
]
)
constraints = [RepeatModification(), StopwordModification()]
constraints.append(UniversalSentenceEncoder(threshold=use_params.get("threshold", 0.8)))
goal_function = UntargetedClassification(model_wrapper)
search_method = GreedyWordSwapWIR(wir_method=gws_params.get("gws_params", "delete"))
return TAAttack(goal_function, constraints, transformation, search_method)