Upload _script_for_eval.py
Browse files- _script_for_eval.py +61 -54
_script_for_eval.py
CHANGED
@@ -132,7 +132,7 @@ def get_fixed_code_fine_tuned(prompt, few_shot_messages, model_name):
|
|
132 |
else:
|
133 |
raise Exception(f"API call failed after {max_retries} attempts: {str(e)}")
|
134 |
|
135 |
-
def process_file(test_case, cache, fixed_files, model_name, use_cache, n_shot, use_similarity):
|
136 |
file_name = test_case["file_name"]
|
137 |
input_file = os.path.join("staticeval", file_name)
|
138 |
|
@@ -170,57 +170,61 @@ def process_file(test_case, cache, fixed_files, model_name, use_cache, n_shot, u
|
|
170 |
result = False
|
171 |
else:
|
172 |
tqdm.write("Vulnerability found in " + input_file + "...")
|
173 |
-
|
174 |
-
lines = data["results"][0]["extra"]["lines"]
|
175 |
-
message = data["results"][0]["extra"]["message"]
|
176 |
-
|
177 |
-
prompt = f"""Vulnerability Report:
|
178 |
-
- Type: {cwe}
|
179 |
-
- Location: {lines}
|
180 |
-
- Description: {message}
|
181 |
-
|
182 |
-
Original Code:
|
183 |
-
```
|
184 |
-
{file_text}
|
185 |
-
```
|
186 |
-
|
187 |
-
Task: Fix the vulnerability in the code above. Provide only the complete fixed code without explanations or comments. Make minimal changes necessary to address the security issue while preserving the original functionality."""
|
188 |
-
|
189 |
-
few_shot_messages = fetch_dataset_examples(prompt, n_shot, use_similarity)
|
190 |
-
response = get_fixed_code_fine_tuned(prompt, few_shot_messages, model_name)
|
191 |
-
|
192 |
-
if "```python" in response:
|
193 |
-
idx = response.find("```python")
|
194 |
-
shift = len("```python")
|
195 |
-
fixed_code = response[idx + shift :]
|
196 |
-
else:
|
197 |
-
fixed_code = response
|
198 |
-
|
199 |
-
stop_words = ["```", "assistant"]
|
200 |
-
|
201 |
-
for w in stop_words:
|
202 |
-
if w in fixed_code:
|
203 |
-
fixed_code = fixed_code[:fixed_code.find(w)]
|
204 |
-
if len(fixed_code) < 400:
|
205 |
-
result = False
|
206 |
-
if has_all_comments(fixed_code):
|
207 |
-
result = False
|
208 |
-
if os.path.exists(output_file):
|
209 |
-
os.remove(output_file)
|
210 |
-
with open(output_file, 'w') as wf:
|
211 |
-
wf.write(fixed_code)
|
212 |
-
if os.path.exists(tmp_file):
|
213 |
-
os.remove(tmp_file)
|
214 |
-
scan_command_output = f"semgrep --config p/python {output_file} --output {tmp_file} --json > /dev/null 2>&1"
|
215 |
-
os.system(scan_command_output)
|
216 |
-
with open(tmp_file, 'r') as jf:
|
217 |
-
data = json.load(jf)
|
218 |
-
if len(data["errors"]) == 0 and len(data["results"]) == 0:
|
219 |
-
tqdm.write("Passing response for " + input_file + " at 1 ...")
|
220 |
result = True
|
221 |
fixed_files.append(file_name)
|
222 |
else:
|
223 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
224 |
else:
|
225 |
tqdm.write(f"Semgrep reported errors for {input_file}")
|
226 |
result = False
|
@@ -235,8 +239,8 @@ def process_file(test_case, cache, fixed_files, model_name, use_cache, n_shot, u
|
|
235 |
tqdm.write(f"Error processing {input_file}: {str(e)}")
|
236 |
return False
|
237 |
|
238 |
-
def process_test_case(test_case, cache, fixed_files, model_name, use_cache, n_shot, use_similarity):
|
239 |
-
return process_file(test_case, cache, fixed_files, model_name, use_cache, n_shot, use_similarity)
|
240 |
|
241 |
def main():
|
242 |
parser = argparse.ArgumentParser(description="Run Static Analysis Evaluation")
|
@@ -244,12 +248,14 @@ def main():
|
|
244 |
parser.add_argument("--cache", action="store_true", help="Enable caching of results")
|
245 |
parser.add_argument("--n_shot", type=int, default=0, help="Number of examples to use for few-shot learning")
|
246 |
parser.add_argument("--use_similarity", action="store_true", help="Use similarity for fetching dataset examples")
|
|
|
247 |
args = parser.parse_args()
|
248 |
|
249 |
-
model_name = args.model
|
250 |
use_cache = args.cache
|
251 |
n_shot = args.n_shot
|
252 |
use_similarity = args.use_similarity
|
|
|
253 |
sanitized_model_name = f"{sanitize_filename(model_name)}-{n_shot}-shot{'-sim' if use_similarity else ''}"
|
254 |
|
255 |
dataset = load_dataset("patched-codes/static-analysis-eval", split="train")
|
@@ -265,7 +271,7 @@ def main():
|
|
265 |
manager = multiprocessing.Manager()
|
266 |
fixed_files = manager.list()
|
267 |
|
268 |
-
process_func = partial(process_test_case, cache=cache, fixed_files=fixed_files, model_name=model_name, use_cache=use_cache, n_shot=n_shot, use_similarity=use_similarity)
|
269 |
|
270 |
with multiprocessing.Pool(processes=4) as pool:
|
271 |
results = list(tqdm(pool.imap(process_func, data), total=total_tests))
|
@@ -280,7 +286,7 @@ def main():
|
|
280 |
log_file.write(f"Evaluation Run Log\n")
|
281 |
log_file.write(f"==================\n\n")
|
282 |
log_file.write(f"Date and Time: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
|
283 |
-
log_file.write(f"Model: {model_name}\n")
|
284 |
log_file.write(f"Semgrep Version: {semgrep_version}\n")
|
285 |
log_file.write(f"Caching: {'Enabled' if use_cache else 'Disabled'}\n\n")
|
286 |
log_file.write(f"Total Tests: {total_tests}\n")
|
@@ -288,6 +294,7 @@ def main():
|
|
288 |
log_file.write(f"Score: {score:.2f}%\n\n")
|
289 |
log_file.write(f"Number of few-shot examples: {n_shot}\n")
|
290 |
log_file.write(f"Use similarity for examples: {'Yes' if use_similarity else 'No'}\n")
|
|
|
291 |
log_file.write("Fixed Files:\n")
|
292 |
for file in fixed_files:
|
293 |
log_file.write(f"- {file}\n")
|
|
|
132 |
else:
|
133 |
raise Exception(f"API call failed after {max_retries} attempts: {str(e)}")
|
134 |
|
135 |
+
def process_file(test_case, cache, fixed_files, model_name, use_cache, n_shot, use_similarity, oracle_mode):
|
136 |
file_name = test_case["file_name"]
|
137 |
input_file = os.path.join("staticeval", file_name)
|
138 |
|
|
|
170 |
result = False
|
171 |
else:
|
172 |
tqdm.write("Vulnerability found in " + input_file + "...")
|
173 |
+
if oracle_mode:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
174 |
result = True
|
175 |
fixed_files.append(file_name)
|
176 |
else:
|
177 |
+
cwe = data["results"][0]["extra"]["metadata"]["cwe"][0]
|
178 |
+
lines = data["results"][0]["extra"]["lines"]
|
179 |
+
message = data["results"][0]["extra"]["message"]
|
180 |
+
|
181 |
+
prompt = f"""Vulnerability Report:
|
182 |
+
- Type: {cwe}
|
183 |
+
- Location: {lines}
|
184 |
+
- Description: {message}
|
185 |
+
|
186 |
+
Original Code:
|
187 |
+
```
|
188 |
+
{file_text}
|
189 |
+
```
|
190 |
+
|
191 |
+
Task: Fix the vulnerability in the code above. Provide only the complete fixed code without explanations or comments. Make minimal changes necessary to address the security issue while preserving the original functionality."""
|
192 |
+
|
193 |
+
few_shot_messages = fetch_dataset_examples(prompt, n_shot, use_similarity)
|
194 |
+
response = get_fixed_code_fine_tuned(prompt, few_shot_messages, model_name)
|
195 |
+
|
196 |
+
if "```python" in response:
|
197 |
+
idx = response.find("```python")
|
198 |
+
shift = len("```python")
|
199 |
+
fixed_code = response[idx + shift :]
|
200 |
+
else:
|
201 |
+
fixed_code = response
|
202 |
+
|
203 |
+
stop_words = ["```", "assistant"]
|
204 |
+
|
205 |
+
for w in stop_words:
|
206 |
+
if w in fixed_code:
|
207 |
+
fixed_code = fixed_code[:fixed_code.find(w)]
|
208 |
+
if len(fixed_code) < 400:
|
209 |
+
result = False
|
210 |
+
if has_all_comments(fixed_code):
|
211 |
+
result = False
|
212 |
+
if os.path.exists(output_file):
|
213 |
+
os.remove(output_file)
|
214 |
+
with open(output_file, 'w') as wf:
|
215 |
+
wf.write(fixed_code)
|
216 |
+
if os.path.exists(tmp_file):
|
217 |
+
os.remove(tmp_file)
|
218 |
+
scan_command_output = f"semgrep --config p/python {output_file} --output {tmp_file} --json > /dev/null 2>&1"
|
219 |
+
os.system(scan_command_output)
|
220 |
+
with open(tmp_file, 'r') as jf:
|
221 |
+
data = json.load(jf)
|
222 |
+
if len(data["errors"]) == 0 and len(data["results"]) == 0:
|
223 |
+
tqdm.write("Passing response for " + input_file + " at 1 ...")
|
224 |
+
result = True
|
225 |
+
fixed_files.append(file_name)
|
226 |
+
else:
|
227 |
+
result = False
|
228 |
else:
|
229 |
tqdm.write(f"Semgrep reported errors for {input_file}")
|
230 |
result = False
|
|
|
239 |
tqdm.write(f"Error processing {input_file}: {str(e)}")
|
240 |
return False
|
241 |
|
242 |
+
def process_test_case(test_case, cache, fixed_files, model_name, use_cache, n_shot, use_similarity, oracle_mode):
|
243 |
+
return process_file(test_case, cache, fixed_files, model_name, use_cache, n_shot, use_similarity, oracle_mode)
|
244 |
|
245 |
def main():
|
246 |
parser = argparse.ArgumentParser(description="Run Static Analysis Evaluation")
|
|
|
248 |
parser.add_argument("--cache", action="store_true", help="Enable caching of results")
|
249 |
parser.add_argument("--n_shot", type=int, default=0, help="Number of examples to use for few-shot learning")
|
250 |
parser.add_argument("--use_similarity", action="store_true", help="Use similarity for fetching dataset examples")
|
251 |
+
parser.add_argument("--oracle", action="store_true", help="Run in oracle mode (assume all vulnerabilities are fixed)")
|
252 |
args = parser.parse_args()
|
253 |
|
254 |
+
model_name = "oracle" if args.oracle else args.model
|
255 |
use_cache = args.cache
|
256 |
n_shot = args.n_shot
|
257 |
use_similarity = args.use_similarity
|
258 |
+
oracle_mode = args.oracle
|
259 |
sanitized_model_name = f"{sanitize_filename(model_name)}-{n_shot}-shot{'-sim' if use_similarity else ''}"
|
260 |
|
261 |
dataset = load_dataset("patched-codes/static-analysis-eval", split="train")
|
|
|
271 |
manager = multiprocessing.Manager()
|
272 |
fixed_files = manager.list()
|
273 |
|
274 |
+
process_func = partial(process_test_case, cache=cache, fixed_files=fixed_files, model_name=model_name, use_cache=use_cache, n_shot=n_shot, use_similarity=use_similarity, oracle_mode=oracle_mode)
|
275 |
|
276 |
with multiprocessing.Pool(processes=4) as pool:
|
277 |
results = list(tqdm(pool.imap(process_func, data), total=total_tests))
|
|
|
286 |
log_file.write(f"Evaluation Run Log\n")
|
287 |
log_file.write(f"==================\n\n")
|
288 |
log_file.write(f"Date and Time: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
|
289 |
+
log_file.write(f"Model: {'' if oracle_mode else model_name}\n")
|
290 |
log_file.write(f"Semgrep Version: {semgrep_version}\n")
|
291 |
log_file.write(f"Caching: {'Enabled' if use_cache else 'Disabled'}\n\n")
|
292 |
log_file.write(f"Total Tests: {total_tests}\n")
|
|
|
294 |
log_file.write(f"Score: {score:.2f}%\n\n")
|
295 |
log_file.write(f"Number of few-shot examples: {n_shot}\n")
|
296 |
log_file.write(f"Use similarity for examples: {'Yes' if use_similarity else 'No'}\n")
|
297 |
+
log_file.write(f"Oracle mode: {'Yes' if oracle_mode else 'No'}\n")
|
298 |
log_file.write("Fixed Files:\n")
|
299 |
for file in fixed_files:
|
300 |
log_file.write(f"- {file}\n")
|