Canstralian commited on
Commit
8cf959b
·
verified ·
1 Parent(s): 1e85f11

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -35
app.py CHANGED
@@ -2,9 +2,10 @@ import gradio as gr
2
  from transformers import pipeline, Trainer, TrainingArguments, AutoModelForCausalLM, AutoTokenizer
3
  from typing import List, Dict
4
  import os
 
5
 
6
- # Initialize the Hugging Face pipeline (make sure to replace with your model name)
7
- model_name = "your_huggingface_model_name" # Ensure to use a valid model
8
  tokenizer = AutoTokenizer.from_pretrained(model_name)
9
  try:
10
  model = AutoModelForCausalLM.from_pretrained(model_name)
@@ -16,13 +17,7 @@ except Exception as e:
16
  def generate_attack(prompt: str, history: List[Dict[str, str]]) -> List[str]:
17
  """
18
  Simulates a Blackhat AI scenario by generating attack strategies and potential impacts.
19
- Args:
20
- prompt (str): The user's input to the simulator.
21
- history (List[Dict]): The user's message history with timestamps.
22
- Returns:
23
- List[str]: A list of attack responses from the AI.
24
  """
25
- # Validate inputs
26
  if not prompt.strip():
27
  return ["Error: Prompt cannot be empty."]
28
  if not isinstance(history, list) or not all(isinstance(h, dict) for h in history):
@@ -47,20 +42,20 @@ def generate_attack(prompt: str, history: List[Dict[str, str]]) -> List[str]:
47
  return [f"Error generating response: {e}"]
48
 
49
  # Function for fine-tuning the model with the uploaded dataset
50
- def fine_tune_model(dataset: str) -> str:
51
  """
52
  Fine-tunes the model using the uploaded dataset.
53
- Args:
54
- dataset (str): The path to the dataset for fine-tuning.
55
- Returns:
56
- str: A message indicating whether fine-tuning was successful or failed.
57
  """
58
  try:
59
- # Process the dataset (dummy processing for illustration)
60
- with open(dataset, "r") as file:
61
- data = file.readlines()
62
-
63
- # Simulate fine-tuning with the provided dataset
 
 
 
 
64
  train_args = TrainingArguments(
65
  output_dir="./results",
66
  evaluation_strategy="steps",
@@ -69,11 +64,11 @@ def fine_tune_model(dataset: str) -> str:
69
  num_train_epochs=1,
70
  logging_dir="./logs",
71
  )
72
-
73
  trainer = Trainer(
74
  model=model,
75
  args=train_args,
76
- train_dataset=data,
77
  tokenizer=tokenizer
78
  )
79
 
@@ -96,33 +91,23 @@ demo = gr.Interface(
96
  gr.Textbox(label="Fine-Tuning Status", interactive=False)
97
  ],
98
  title="Blackhat AI Simulator with Live Fine-Tuning",
99
- description=(
100
- "This simulator generates adversarial scenarios, analyzes attack vectors, "
101
- "and provides ethical countermeasures. Use responsibly for cybersecurity training and awareness."
102
- )
103
  )
104
 
 
105
  def handle_fine_tuning(dataset_file):
106
- """
107
- This function is used to trigger the fine-tuning process after file upload.
108
- """
109
  if dataset_file is not None:
110
- dataset_path = os.path.join("uploads", dataset_file.name)
111
- with open(dataset_path, "wb") as f:
112
- f.write(dataset_file.read())
113
- return fine_tune_model(dataset_path)
114
  else:
115
  return "No dataset uploaded."
116
 
117
- # Add a separate fine-tuning section to the interface
118
  demo.add_component(
119
  gr.Button("Fine-Tune Model", variant="primary", elem_id="fine-tune-btn"),
120
  gr.File(label="Upload Dataset for Fine-Tuning", file_count="single", type="file"),
121
  outputs=gr.Textbox(label="Fine-Tuning Status")
122
  )
123
 
124
- # Bind the fine-tuning button
125
- demo.interactive(fn=handle_fine_tuning)
126
-
127
  if __name__ == "__main__":
128
  demo.launch()
 
2
  from transformers import pipeline, Trainer, TrainingArguments, AutoModelForCausalLM, AutoTokenizer
3
  from typing import List, Dict
4
  import os
5
+ from datasets import Dataset
6
 
7
+ # Initialize the Hugging Face pipeline (replace with a valid model)
8
+ model_name = "gpt2" # Example model, replace with your own
9
  tokenizer = AutoTokenizer.from_pretrained(model_name)
10
  try:
11
  model = AutoModelForCausalLM.from_pretrained(model_name)
 
17
  def generate_attack(prompt: str, history: List[Dict[str, str]]) -> List[str]:
18
  """
19
  Simulates a Blackhat AI scenario by generating attack strategies and potential impacts.
 
 
 
 
 
20
  """
 
21
  if not prompt.strip():
22
  return ["Error: Prompt cannot be empty."]
23
  if not isinstance(history, list) or not all(isinstance(h, dict) for h in history):
 
42
  return [f"Error generating response: {e}"]
43
 
44
  # Function for fine-tuning the model with the uploaded dataset
45
+ def fine_tune_model(dataset_file) -> str:
46
  """
47
  Fine-tunes the model using the uploaded dataset.
 
 
 
 
48
  """
49
  try:
50
+ # Process the dataset
51
+ dataset_path = os.path.join("uploads", dataset_file.name)
52
+ with open(dataset_path, "wb") as f:
53
+ f.write(dataset_file.read())
54
+
55
+ # Load the dataset (make sure it's in the right format)
56
+ dataset = Dataset.from_text(dataset_path)
57
+
58
+ # Fine-tune the model (dummy training example for illustration)
59
  train_args = TrainingArguments(
60
  output_dir="./results",
61
  evaluation_strategy="steps",
 
64
  num_train_epochs=1,
65
  logging_dir="./logs",
66
  )
67
+
68
  trainer = Trainer(
69
  model=model,
70
  args=train_args,
71
+ train_dataset=dataset,
72
  tokenizer=tokenizer
73
  )
74
 
 
91
  gr.Textbox(label="Fine-Tuning Status", interactive=False)
92
  ],
93
  title="Blackhat AI Simulator with Live Fine-Tuning",
94
+ description="Generate adversarial scenarios and fine-tune the model with custom datasets."
 
 
 
95
  )
96
 
97
+ # Event handler for fine-tuning after dataset upload
98
  def handle_fine_tuning(dataset_file):
 
 
 
99
  if dataset_file is not None:
100
+ return fine_tune_model(dataset_file)
 
 
 
101
  else:
102
  return "No dataset uploaded."
103
 
104
+ # Add a button to trigger fine-tuning manually
105
  demo.add_component(
106
  gr.Button("Fine-Tune Model", variant="primary", elem_id="fine-tune-btn"),
107
  gr.File(label="Upload Dataset for Fine-Tuning", file_count="single", type="file"),
108
  outputs=gr.Textbox(label="Fine-Tuning Status")
109
  )
110
 
111
+ # Launch the interface
 
 
112
  if __name__ == "__main__":
113
  demo.launch()