Datasets:

Modalities:
Text
Formats:
parquet
Size:
< 1K
ArXiv:
DOI:
Libraries:
Datasets
pandas
License:
static-analysis-eval / _script_for_eval.py
codelion's picture
Update _script_for_eval.py
8a78bad verified
raw
history blame
6.64 kB
import json
import os
import random
import pickle
import time
from openai import OpenAI
from tqdm import tqdm
from functools import partial
import multiprocessing
from datasets import load_dataset
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
client = OpenAI()
def load_cache():
if os.path.exists('cache.pkl'):
with open('cache.pkl', 'rb') as f:
return pickle.load(f)
return {}
def save_cache(cache):
with open('cache.pkl', 'wb') as f:
pickle.dump(cache, f)
def fetch_dataset_examples(prompt, num_examples=3, use_similarity=True):
dataset = load_dataset("patched-codes/synth-vuln-fixes", split="train")
if use_similarity:
user_messages = [
next(msg['content'] for msg in item['messages'] if msg['role'] == 'user')
for item in dataset
]
vectorizer = TfidfVectorizer().fit(user_messages + [prompt])
user_vectors = vectorizer.transform(user_messages)
prompt_vector = vectorizer.transform([prompt])
similarities = cosine_similarity(prompt_vector, user_vectors)[0]
top_indices = np.argsort(similarities)[-num_examples:][::-1]
else:
top_indices = np.random.choice(len(dataset), num_examples, replace=False)
few_shot_messages = []
for index in top_indices:
py_index = int(index)
messages = dataset[py_index]["messages"]
dialogue = [msg for msg in messages if msg['role'] != 'system']
few_shot_messages.extend(dialogue)
return few_shot_messages
def get_fixed_code_fine_tuned(prompt, few_shot_messages):
system_message = (
"You are an AI assistant specialized in fixing code vulnerabilities. "
"Your task is to provide corrected code that addresses the reported security issue. "
"Always maintain the original functionality while improving security. "
"Be precise and make only necessary changes. "
"Maintain the original code style and formatting unless it directly relates to the vulnerability. "
"Pay attention to data flow between sources and sinks when provided."
)
messages = [
{"role": "system", "content": system_message},
]
messages.extend(few_shot_messages)
messages.append({"role": "user", "content": prompt})
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
max_tokens=512,
temperature=0.2,
top_p=0.95
)
try:
return response.choices[0].message.content
except Exception as e:
raise Exception(f"API call failed: {str(e)}")
def process_file(test_case, cache):
file_name = test_case["file_name"]
input_file = "staticeval/" + file_name
if input_file in cache:
tqdm.write(f"Skipping {input_file} (cached)")
return cache[input_file]
file_text = test_case["source"]
test_cwe = test_case["cwe"].strip()
output_file = input_file + "_fixed.py"
tmp_file = input_file + ".output.json"
with open(input_file, "w") as file_object:
file_object.write(file_text)
if os.path.exists(tmp_file):
os.remove(tmp_file)
tqdm.write("Scanning file " + input_file + "...")
scan_command_input = f"semgrep --config p/python {input_file} --output {tmp_file} --json > /dev/null 2>&1"
os.system(scan_command_input)
with open(tmp_file, 'r') as jf:
data = json.load(jf)
if len(data["errors"]) == 0:
if len(data["results"]) == 0:
tqdm.write(input_file + " has no vulnerabilities")
result = False
else:
tqdm.write("Vulnerability found in " + input_file + "...")
cwe = data["results"][0]["extra"]["metadata"]["cwe"][0]
lines = data["results"][0]["extra"]["lines"]
message = data["results"][0]["extra"]["message"]
prompt = f"""Vulnerability Report:
- Type: {cwe}
- Location: {lines}
- Description: {message}
Original Code:
```
{file_text}
```
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."""
few_shot_messages = fetch_dataset_examples(prompt, 3, True)
response = get_fixed_code_fine_tuned(prompt, [])
if "```python" in response:
idx = response.find("```python")
shift = len("```python")
fixed_code = response[idx + shift :]
else:
fixed_code = response
stop_words = ["```", "assistant"]
for w in stop_words:
if w in fixed_code:
fixed_code = fixed_code[:fixed_code.find(w)]
if len(fixed_code) < 400 or all(line.strip().startswith("#") for line in fixed_code.split('\n') if line.strip()):
result = False
else:
with open(output_file, 'w') as wf:
wf.write(fixed_code)
scan_command_output = f"semgrep --config p/python {output_file} --output {tmp_file} --json > /dev/null 2>&1"
os.system(scan_command_output)
with open(tmp_file, 'r') as jf:
data = json.load(jf)
if len(data["errors"]) == 0 and len(data["results"]) == 0:
tqdm.write("Passing response for " + input_file + " at 1 ...")
result = True
else:
result = False
if os.path.exists(tmp_file):
os.remove(tmp_file)
cache[input_file] = result
save_cache(cache)
return result
def process_test_case(test_case, cache):
return process_file(test_case, cache)
def main():
dataset = load_dataset("patched-codes/static-analysis-eval", split="train")
data = [{"file_name": item["file_name"], "source": item["source"], "cwe": item["cwe"]} for item in dataset]
cache = load_cache()
total_tests = len(data)
process_func = partial(process_test_case, cache=cache)
with multiprocessing.Pool() as pool:
results = list(tqdm(pool.imap_unordered(process_func, data), total=total_tests))
passing_tests = sum(results)
print(f"Results for StaticAnalysisEval: {passing_tests/total_tests*100}%")
if __name__ == '__main__':
main()