Skip to content

Commit e607135

Browse files
committed
Add ruff
1 parent 82b41e4 commit e607135

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

64 files changed

+244
-229
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,5 +161,6 @@ cython_debug/
161161

162162
.env
163163
.DS_Store
164+
.ruff_cache
164165
TODO.md
165166
!aisploit/target

aisploit/classifiers/huggingface/pipeline_prompt_injection_identifier.py

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -32,17 +32,9 @@ def __init__(
3232
def score(self, input: str) -> Score[float]:
3333
result = self._model(input)
3434

35-
score = (
36-
result[0]["score"]
37-
if result[0]["label"] == self._injection_label
38-
else 1 - result[0]["score"]
39-
)
35+
score = result[0]["score"] if result[0]["label"] == self._injection_label else 1 - result[0]["score"]
4036

41-
explanation = (
42-
"Prompt injection attack detected"
43-
if score > self._threshold
44-
else "No prompt injection"
45-
)
37+
explanation = "Prompt injection attack detected" if score > self._threshold else "No prompt injection"
4638

4739
return Score[float](
4840
flagged=score > self._threshold,

aisploit/classifiers/openai/moderation.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
from typing import Optional
21
import os
2+
from typing import Optional
3+
34
from openai import OpenAI
45
from openai.types.moderation import Moderation
56

aisploit/classifiers/text.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import re
2+
23
from ..core import BaseTextClassifier, Score
34

45

@@ -51,9 +52,5 @@ def __init__(self, *, substring: str, ignore_case=True, flag_matches=True) -> No
5152
ignore_case (bool, optional): Flag indicating whether to ignore case when matching substrings. Defaults to True.
5253
flag_matches (bool, optional): Flag indicating whether matches should be flagged. Defaults to True.
5354
"""
54-
compiled_pattern = (
55-
re.compile(substring, re.IGNORECASE)
56-
if ignore_case
57-
else re.compile(substring)
58-
)
55+
compiled_pattern = re.compile(substring, re.IGNORECASE) if ignore_case else re.compile(substring)
5956
super().__init__(pattern=compiled_pattern, flag_matches=flag_matches)

aisploit/converters/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
from .base64 import Base64Converter
2-
from .case import LowercaseConverter, UppercaseConverter, TitlecaseConverter
2+
from .case import LowercaseConverter, TitlecaseConverter, UppercaseConverter
33
from .gender import GenderConverter
44
from .join import JoinConverter
55
from .keyboard_typo import (
6-
KeyboardTypoConverter,
76
KEYBOARD_NEIGHBORS_QWERTY,
87
KEYBOARD_NEIGHBORS_QWERTZ,
8+
KeyboardTypoConverter,
99
)
1010
from .no_op import NoOpConverter
1111
from .remove_punctuation import RemovePunctuationConverter

aisploit/converters/gender.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import textwrap
2-
from langchain_core.prompts import ChatPromptTemplate
2+
33
from langchain_core.output_parsers import StrOutputParser
4-
from ..core import BaseChatModelConverter, BaseChatModel
4+
from langchain_core.prompts import ChatPromptTemplate
5+
6+
from ..core import BaseChatModel, BaseChatModelConverter
57

68
_template = ChatPromptTemplate.from_template(
79
textwrap.dedent(

aisploit/converters/keyboard_typo.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -76,10 +76,7 @@ def __init__(
7676
def _convert(self, prompt: str) -> str:
7777
typoPrompt = ""
7878
for char in prompt:
79-
if (
80-
random.random() < self._typo_probability
81-
and char.lower() in self._keyboard_neighbors
82-
):
79+
if random.random() < self._typo_probability and char.lower() in self._keyboard_neighbors:
8380
# Replace the character with a random neighboring key
8481
neighbor_keys = self._keyboard_neighbors[char.lower()]
8582
typo_char = random.choice(neighbor_keys)

aisploit/converters/remove_punctuation.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import string
2+
23
from ..core import BaseConverter
34

45

aisploit/converters/sequence.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from typing import Sequence
2+
23
from langchain_core.prompt_values import StringPromptValue
34

45
from ..core import BaseConverter
@@ -11,8 +12,6 @@ def __init__(self, *, converters: Sequence[BaseConverter] = []) -> None:
1112
def _convert(self, prompt: str) -> str:
1213
converted_prompt = prompt
1314
for converter in self._converters:
14-
converted_prompt = converter.convert(
15-
StringPromptValue(text=converted_prompt)
16-
).to_string()
15+
converted_prompt = converter.convert(StringPromptValue(text=converted_prompt)).to_string()
1716

1817
return converted_prompt

aisploit/converters/stemming.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import nltk
2-
from nltk.tokenize import word_tokenize
32
from nltk.stem.porter import PorterStemmer
3+
from nltk.tokenize import word_tokenize
4+
45
from ..core import BaseConverter
56

67

aisploit/converters/unicode_confusable.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import random
2+
23
from confusables import confusable_characters
4+
35
from ..core import BaseConverter
46

57

aisploit/core/__init__.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
from .callbacks import BaseCallbackHandler, Callbacks, CallbackManager
1+
from .callbacks import BaseCallbackHandler, CallbackManager, Callbacks
22
from .classifier import BaseClassifier, BaseTextClassifier, Score
3-
from .converter import BaseConverter, BaseChatModelConverter
3+
from .converter import BaseChatModelConverter, BaseConverter
44
from .dataset import BaseDataset, YamlDeserializable
55
from .generator import BaseGenerator
66
from .job import BaseJob
7-
from .model import BaseLLM, BaseChatModel, BaseModel, BaseEmbeddings
7+
from .model import BaseChatModel, BaseEmbeddings, BaseLLM, BaseModel
88
from .prompt import BasePromptValue
99
from .report import BaseReport
1010
from .target import BaseTarget, Response

aisploit/core/callbacks.py

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,14 @@
11
from typing import Sequence
22

3-
from .prompt import BasePromptValue
43
from .classifier import Score
4+
from .prompt import BasePromptValue
55
from .target import Response
66

77

88
class BaseCallbackHandler:
99
"""Base class for callback handlers."""
1010

11-
def on_redteam_attempt_start(
12-
self, attempt: int, prompt: BasePromptValue, *, run_id: str
13-
):
11+
def on_redteam_attempt_start(self, attempt: int, prompt: BasePromptValue, *, run_id: str):
1412
"""Called when a red team attempt starts.
1513
1614
Args:
@@ -20,9 +18,7 @@ def on_redteam_attempt_start(
2018
"""
2119
pass
2220

23-
def on_redteam_attempt_end(
24-
self, attempt: int, response: Response, score: Score, *, run_id: str
25-
):
21+
def on_redteam_attempt_end(self, attempt: int, response: Response, score: Score, *, run_id: str):
2622
"""Called when a red team attempt ends.
2723
2824
Args:
@@ -68,7 +64,7 @@ def __init__(
6864
self,
6965
*,
7066
run_id: str,
71-
callbacks: Sequence[BaseCallbackHandler] = [],
67+
callbacks: Sequence[BaseCallbackHandler] | None,
7268
) -> None:
7369
"""Initialize the CallbackManager.
7470
@@ -77,7 +73,7 @@ def __init__(
7773
callbacks (Sequence[BaseCallbackHandler], optional): The list of callback handlers. Defaults to [].
7874
"""
7975
self.run_id = run_id
80-
self._callbacks = callbacks
76+
self._callbacks = callbacks or []
8177

8278
def on_redteam_attempt_start(self, attempt: int, prompt: BasePromptValue):
8379
"""Notify callback handlers when a red team attempt starts.
@@ -87,9 +83,7 @@ def on_redteam_attempt_start(self, attempt: int, prompt: BasePromptValue):
8783
prompt (BasePromptValue): The prompt value.
8884
"""
8985
for cb in self._callbacks:
90-
cb.on_redteam_attempt_start(
91-
attempt=attempt, prompt=prompt, run_id=self.run_id
92-
)
86+
cb.on_redteam_attempt_start(attempt=attempt, prompt=prompt, run_id=self.run_id)
9387

9488
def on_redteam_attempt_end(self, attempt: int, response: Response, score: Score):
9589
"""Notify callback handlers when a red team attempt ends.
@@ -100,9 +94,7 @@ def on_redteam_attempt_end(self, attempt: int, response: Response, score: Score)
10094
score (Score): The score of the attempt.
10195
"""
10296
for cb in self._callbacks:
103-
cb.on_redteam_attempt_end(
104-
attempt=attempt, response=response, score=score, run_id=self.run_id
105-
)
97+
cb.on_redteam_attempt_end(attempt=attempt, response=response, score=score, run_id=self.run_id)
10698

10799
def on_scanner_plugin_start(self, name: str):
108100
"""Notify callback handlers when a scanner plugin starts.

aisploit/core/classifier.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
from typing import TypeVar, Generic
21
from abc import ABC, abstractmethod
32
from dataclasses import dataclass
3+
from typing import Generic, TypeVar
44

55
T = TypeVar("T")
66
Input = TypeVar("Input")

aisploit/core/converter.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1-
from typing import Union
21
from abc import ABC, abstractmethod
2+
from typing import Union
3+
34
from langchain_core.prompt_values import StringPromptValue
5+
46
from .model import BaseChatModel
57
from .prompt import BasePromptValue
68

aisploit/core/dataset.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
from abc import ABC
2-
import yaml
31
from pathlib import Path
4-
from typing import Generic, Type, TypeVar, Sequence
2+
from typing import Generic, Sequence, Type, TypeVar
3+
4+
import yaml
55

66
T = TypeVar("T")
77

@@ -18,8 +18,8 @@ def __len__(self):
1818
return len(self._entries)
1919

2020

21-
class YamlDeserializable(ABC):
22-
"""Abstract base class for objects that can be deserialized from YAML."""
21+
class YamlDeserializable:
22+
"""Base class for objects that can be deserialized from YAML."""
2323

2424
@classmethod
2525
def from_yaml_file(cls: Type[T], file: Path) -> T:
@@ -44,6 +44,6 @@ def from_yaml_file(cls: Type[T], file: Path) -> T:
4444
try:
4545
yaml_data = yaml.safe_load(f)
4646
except yaml.YAMLError as exc:
47-
raise ValueError(f"Invalid YAML file '{file}': {exc}")
47+
raise ValueError(f"Invalid YAML file '{file}'") from exc
4848

4949
return cls(**yaml_data)

aisploit/core/generator.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
from typing import Generic, TypeVar
21
from abc import ABC, abstractmethod
2+
from typing import Generic, TypeVar
3+
34
from .dataset import BaseDataset
45

56
T = TypeVar("T")

aisploit/core/job.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
1-
from abc import ABC
21
from uuid import uuid4
32

43

5-
class BaseJob(ABC):
4+
class BaseJob:
65
def __init__(self, *, verbose=False) -> None:
76
self.verbose = verbose
87

aisploit/core/model.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
from abc import abstractmethod
22
from typing import Union
3+
4+
from langchain_core.embeddings import Embeddings
35
from langchain_core.language_models import LanguageModelInput
46
from langchain_core.messages import BaseMessage
57
from langchain_core.runnables import Runnable
6-
from langchain_core.embeddings import Embeddings
78

89

910
class BaseLLM(Runnable[LanguageModelInput, str]):

aisploit/core/report.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
from typing import Any, Generic, TypeVar, List
2-
from datetime import datetime
31
from abc import ABC, abstractmethod
2+
from datetime import datetime
43
from pathlib import Path
5-
from jinja2 import Template
4+
from typing import Any, Generic, List, TypeVar
65

6+
from jinja2 import Template
77

88
T = TypeVar("T")
99

aisploit/core/target.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
from typing import Dict, Any
21
from abc import ABC, abstractmethod
32
from dataclasses import dataclass, field
3+
from typing import Any, Dict
44

55
from .prompt import BasePromptValue
66

aisploit/datasets/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
from .prompt import PromptDataset, Prompt, JailbreakPromptDataset
2-
from .sample import SampleDataset, Sample
1+
from .prompt import JailbreakPromptDataset, Prompt, PromptDataset
2+
from .sample import Sample, SampleDataset
33

44
__all__ = [
55
"PromptDataset",

aisploit/datasets/prompt.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import os
2-
from pathlib import Path
3-
from typing import Sequence, Optional
42
from dataclasses import dataclass
3+
from pathlib import Path
4+
from typing import Optional, Sequence
55

66
from ..core.dataset import BaseDataset, YamlDeserializable
77

@@ -31,9 +31,7 @@ def __init__(self, prompts: Sequence[Prompt]) -> None:
3131
self._entries = prompts
3232

3333
@classmethod
34-
def load_from_directory(
35-
cls, path: Path, tags_filter: Optional[Sequence[str]] = None
36-
) -> "PromptDataset":
34+
def load_from_directory(cls, path: Path, tags_filter: Optional[Sequence[str]] = None) -> "PromptDataset":
3735
"""Create a JailbreakDataset instance by loading prompts from a directory.
3836
3937
Args:
@@ -46,9 +44,7 @@ def load_from_directory(
4644
prompts = []
4745
for file_name in os.listdir(path):
4846
prompt = Prompt.from_yaml_file(path / file_name)
49-
if not prompt.skip and (
50-
not tags_filter or set(prompt.tags).intersection(tags_filter)
51-
):
47+
if not prompt.skip and (not tags_filter or set(prompt.tags).intersection(tags_filter)):
5248
prompts.append(prompt)
5349
return cls(prompts)
5450

aisploit/datasets/sample.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import os
2-
from typing import Sequence, Optional
3-
from pathlib import Path
42
from dataclasses import dataclass
3+
from pathlib import Path
4+
from typing import Optional, Sequence
55

66
from ..core.dataset import BaseDataset, YamlDeserializable
77

@@ -29,9 +29,7 @@ def __init__(self, samples: Sequence[Sample]) -> None:
2929
self._entries = samples
3030

3131
@classmethod
32-
def load_from_directory(
33-
cls, path: Path, tags_filter: Optional[Sequence[str]] = None
34-
) -> "SampleDataset":
32+
def load_from_directory(cls, path: Path, tags_filter: Optional[Sequence[str]] = None) -> "SampleDataset":
3533
"""Create a SampleDataset instance by loading samples from a directory.
3634
3735
Args:
@@ -44,8 +42,6 @@ def load_from_directory(
4442
samples = []
4543
for file_name in os.listdir(path):
4644
sample = Sample.from_yaml_file(path / file_name)
47-
if not sample.skip and (
48-
not tags_filter or set(sample.tags).intersection(tags_filter)
49-
):
45+
if not sample.skip and (not tags_filter or set(sample.tags).intersection(tags_filter)):
5046
samples.append(sample)
5147
return cls(samples)

aisploit/demo/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from .gandalf import GandalfBot, GandalfScorer, GandalfLevel
1+
from .gandalf import GandalfBot, GandalfLevel, GandalfScorer
22
from .rag import VectorStoreRAG
33

44
__all__ = [

0 commit comments

Comments
 (0)