Canstralian commited on
Commit
5b52a89
·
verified ·
1 Parent(s): 597286b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -41
app.py CHANGED
@@ -1,38 +1,55 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
  from transformers import pipeline
4
- from typing import List, Dict, Any
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
  def generate_attack(
7
  prompt: str,
8
- history: List[Any],
9
  ) -> List[str]:
10
  """
11
  Simulates a Blackhat AI scenario by generating attack strategies and potential impacts.
12
 
13
  Args:
14
  prompt (str): The user's input to the simulator.
15
- history (List[Dict]): The user's message history with timestamps.
16
 
17
  Returns:
18
  List[str]: A list of attack responses from the AI.
19
  """
 
 
 
20
  messages = [
21
- {
22
- "role": "system",
23
- "content": f"Responding to {prompt}..."
24
- }
25
  ]
26
-
27
- for val in history:
28
- if val[0]:
29
- messages.append({"role": "user", "content": val[0]})
30
- if val[1]:
31
- messages.append({"role": "assistant", "content": val[1]})
32
 
33
  messages.append({"role": "user", "content": prompt})
 
34
  response = ""
35
-
36
  for message in client.chat_completion(
37
  messages,
38
  max_tokens=100, # limit the length of responses
@@ -41,40 +58,39 @@ def generate_attack(
41
  top_p=None, # disable top-p filtering
42
  ):
43
  token = message.choices[0].delta.content
44
-
45
  response += token
46
  yield response
47
 
48
  def simulate_attack(
49
  prompt: str,
50
- history: List[Any],
51
  ) -> List[str]:
52
  """
53
  Simulates a Blackhat AI scenario by generating attack strategies and potential impacts.
54
 
55
  Args:
56
  prompt (str): The user's input to the simulator.
57
- history (List[Dict]): The user's message history with timestamps.
58
 
59
  Returns:
60
  List[str]: A list of attack responses from the AI.
61
  """
 
 
 
62
  messages = [
63
- {
64
- "role": "system",
65
- "content": f"Simulating a Blackhat AI scenario..."
66
- }
67
  ]
68
-
69
- for val in history:
70
- if val[0]:
71
- messages.append({"role": "user", "content": val[0]})
72
- if val[1]:
73
- messages.append({"role": "assistant", "content": val[1]})
74
 
75
  messages.append({"role": "user", "content": prompt})
 
76
  response = ""
77
-
78
  for message in client.chat_completion(
79
  messages,
80
  max_tokens=100, # limit the length of responses
@@ -83,26 +99,44 @@ def simulate_attack(
83
  top_p=None, # disable top-p filtering
84
  ):
85
  token = message.choices[0].delta.content
86
-
87
  response += token
88
  yield response
89
 
90
- # Define the Gradio ChatInterface with security-focused configuration
91
- demo = gr.ChatInterface(
92
- generate_attack,
93
- additional_inputs=[
94
- gr.Textbox(
95
- value=(
96
- "You are an AI simulator for cybersecurity training, designed to generate attack scenarios, analyze their impacts, and suggest countermeasures."
97
- ),
98
- label="System message",
99
- ),
100
- # ... (other inputs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  ],
 
102
  title="Blackhat AI Simulator",
103
  description=(
104
- "This simulator generates adversarial scenarios, analyzes attack vectors, and provides ethical countermeasures. Use responsibly for cybersecurity training and awareness."
 
105
  ),
 
106
  )
107
 
108
  if __name__ == "__main__":
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
  from transformers import pipeline
4
+ from typing import List, Dict, Any, Tuple
5
+ import re
6
+
7
+ # Assuming that `InferenceClient` is initialized properly
8
+ client = InferenceClient()
9
+
10
+ def is_valid_input(input_str: str) -> bool:
11
+ """
12
+ Validates the input using regex to prevent malicious patterns.
13
+
14
+ Args:
15
+ input_str (str): The user's input string to be validated.
16
+
17
+ Returns:
18
+ bool: True if input is safe; False otherwise.
19
+ """
20
+ pattern = r'^[A-Za-z0-9\s,.!?-]*$' # Allows alphanumeric and some punctuation
21
+ return bool(re.match(pattern, input_str))
22
 
23
  def generate_attack(
24
  prompt: str,
25
+ history: List[Tuple[str, str]],
26
  ) -> List[str]:
27
  """
28
  Simulates a Blackhat AI scenario by generating attack strategies and potential impacts.
29
 
30
  Args:
31
  prompt (str): The user's input to the simulator.
32
+ history (List[Tuple[str, str]]): The user's message history with timestamps, where each tuple contains (user_message, assistant_response).
33
 
34
  Returns:
35
  List[str]: A list of attack responses from the AI.
36
  """
37
+ if not is_valid_input(prompt):
38
+ raise ValueError("Invalid input detected. Please use only alphanumeric characters and allowed punctuation.")
39
+
40
  messages = [
41
+ {"role": "system", "content": f"Responding to {prompt}..."}
 
 
 
42
  ]
43
+
44
+ for user_msg, assistant_msg in history:
45
+ if user_msg:
46
+ messages.append({"role": "user", "content": user_msg})
47
+ if assistant_msg:
48
+ messages.append({"role": "assistant", "content": assistant_msg})
49
 
50
  messages.append({"role": "user", "content": prompt})
51
+
52
  response = ""
 
53
  for message in client.chat_completion(
54
  messages,
55
  max_tokens=100, # limit the length of responses
 
58
  top_p=None, # disable top-p filtering
59
  ):
60
  token = message.choices[0].delta.content
 
61
  response += token
62
  yield response
63
 
64
  def simulate_attack(
65
  prompt: str,
66
+ history: List[Tuple[str, str]],
67
  ) -> List[str]:
68
  """
69
  Simulates a Blackhat AI scenario by generating attack strategies and potential impacts.
70
 
71
  Args:
72
  prompt (str): The user's input to the simulator.
73
+ history (List[Tuple[str, str]]): The user's message history with timestamps, where each tuple contains (user_message, assistant_response).
74
 
75
  Returns:
76
  List[str]: A list of attack responses from the AI.
77
  """
78
+ if not is_valid_input(prompt):
79
+ raise ValueError("Invalid input detected. Please use only alphanumeric characters and allowed punctuation.")
80
+
81
  messages = [
82
+ {"role": "system", "content": "Simulating a Blackhat AI scenario..."}
 
 
 
83
  ]
84
+
85
+ for user_msg, assistant_msg in history:
86
+ if user_msg:
87
+ messages.append({"role": "user", "content": user_msg})
88
+ if assistant_msg:
89
+ messages.append({"role": "assistant", "content": assistant_msg})
90
 
91
  messages.append({"role": "user", "content": prompt})
92
+
93
  response = ""
 
94
  for message in client.chat_completion(
95
  messages,
96
  max_tokens=100, # limit the length of responses
 
99
  top_p=None, # disable top-p filtering
100
  ):
101
  token = message.choices[0].delta.content
 
102
  response += token
103
  yield response
104
 
105
+ # Define the Gradio ChatInterface with file upload and security-focused configuration
106
+ def handle_file_upload(file: Any) -> str:
107
+ """
108
+ Handles file uploads by extracting contents or performing actions based on the file type.
109
+
110
+ Args:
111
+ file (Any): The uploaded file.
112
+
113
+ Returns:
114
+ str: A response or summary of the file content.
115
+ """
116
+ if file is None:
117
+ return "No file uploaded."
118
+
119
+ file_type = file.name.split('.')[-1].lower()
120
+ if file_type in ['txt', 'json', 'csv']:
121
+ content = file.read().decode("utf-8")
122
+ return f"File uploaded: {file.name}, {len(content)} characters."
123
+ else:
124
+ return "Unsupported file type. Please upload a .txt, .json, or .csv file."
125
+
126
+ demo = gr.Interface(
127
+ fn=generate_attack,
128
+ inputs=[
129
+ gr.Textbox(label="User Prompt", placeholder="Enter attack scenario...", lines=2),
130
+ gr.File(label="Upload File", file_types=["txt", "json", "csv"], file_count="single"),
131
+ gr.Textbox(value="You are an AI simulator for cybersecurity training, designed to generate attack scenarios, analyze their impacts, and suggest countermeasures.", label="System Message")
132
  ],
133
+ outputs="text",
134
  title="Blackhat AI Simulator",
135
  description=(
136
+ "This simulator generates adversarial scenarios, analyzes attack vectors, and provides ethical countermeasures. "
137
+ "Use responsibly for cybersecurity training and awareness."
138
  ),
139
+ theme="dark"
140
  )
141
 
142
  if __name__ == "__main__":