Datasets:

Modalities:
Text
Formats:
parquet
Size:
< 1K
ArXiv:
DOI:
Libraries:
Datasets
pandas
License:
codelion commited on
Commit
4b9af9d
·
verified ·
1 Parent(s): 8a0f3ff

Upload _script_for_gen.py

Browse files
Files changed (1) hide show
  1. _script_for_gen.py +203 -0
_script_for_gen.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import random
4
+ import string
5
+ import subprocess
6
+ import tempfile
7
+ import logging
8
+ import argparse
9
+ from github import Github
10
+ from git import Repo
11
+ from datasets import load_dataset, Dataset
12
+
13
+ # Set up logging
14
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
15
+ logger = logging.getLogger(__name__)
16
+
17
+ # Read GitHub API token from environment variable
18
+ GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN")
19
+ HF_TOKEN = os.environ.get("HF_TOKEN")
20
+
21
+ if not GITHUB_TOKEN:
22
+ logger.error("GITHUB_TOKEN environment variable is not set.")
23
+ raise ValueError("GITHUB_TOKEN environment variable is not set. Please set it before running the script.")
24
+
25
+ if not HF_TOKEN:
26
+ logger.error("HF_TOKEN environment variable is not set.")
27
+ raise ValueError("HF_TOKEN environment variable is not set. Please set it before running the script.")
28
+
29
+ # Initialize GitHub API client
30
+ g = Github(GITHUB_TOKEN)
31
+
32
+ def search_top_repos():
33
+ """Search for top 100 Python repositories with at least 1000 stars and 100 forks."""
34
+ logger.info("Searching for top 100 Python repositories...")
35
+ query = "language:python stars:>=1000 forks:>=100"
36
+ repos = g.search_repositories(query=query, sort="stars", order="desc")
37
+ top_repos = list(repos[:100])
38
+ logger.info(f"Found {len(top_repos)} repositories")
39
+ return top_repos
40
+
41
+ def clone_repo(repo, tmp_dir):
42
+ """Clone a repository to a temporary directory."""
43
+ logger.info(f"Cloning repository: {repo.full_name}")
44
+ repo_dir = os.path.join(tmp_dir, repo.name)
45
+ Repo.clone_from(repo.clone_url, repo_dir)
46
+ logger.info(f"Repository cloned to {repo_dir}")
47
+ return repo_dir
48
+
49
+ def run_semgrep(repo_dir):
50
+ """Run Semgrep on the repository and return the JSON output."""
51
+ logger.info(f"Running Semgrep on {repo_dir}")
52
+ cmd = f"semgrep scan --config auto --json {repo_dir}"
53
+ result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
54
+ logger.info("Semgrep scan completed")
55
+ return json.loads(result.stdout)
56
+
57
+ def extract_vulnerable_files(semgrep_output):
58
+ """Extract files with exactly one vulnerability and their CWE."""
59
+ logger.info("Extracting vulnerable files from Semgrep output")
60
+ vulnerable_files = {}
61
+ total_vulns = 0
62
+ for result in semgrep_output.get("results", []):
63
+ file_path = result.get("path")
64
+ cwe = result.get("extra", {}).get("metadata", {}).get("cwe", "Unknown")
65
+
66
+ if file_path not in vulnerable_files:
67
+ vulnerable_files[file_path] = {"count": 0, "cwe": cwe}
68
+
69
+ vulnerable_files[file_path]["count"] += 1
70
+ total_vulns += 1
71
+
72
+ single_vulnerability_files = {file: info["cwe"] for file, info in vulnerable_files.items() if info["count"] == 1}
73
+ logger.info(f"Found {total_vulns} total vulnerabilities")
74
+ logger.info(f"Found {len(single_vulnerability_files)} files with exactly one vulnerability")
75
+ return single_vulnerability_files, total_vulns
76
+
77
+ def count_tokens(text):
78
+ """Approximate token count using whitespace splitting."""
79
+ return len(text.split())
80
+
81
+ def generate_random_filename():
82
+ """Generate a random 6-digit filename with .py extension."""
83
+ return ''.join(random.choices(string.digits, k=6)) + ".py"
84
+
85
+ def process_repository(repo, output_file):
86
+ """Process a single repository and append new data items to the output file."""
87
+ logger.info(f"Processing repository: {repo.full_name}")
88
+ with tempfile.TemporaryDirectory() as tmp_dir:
89
+ repo_dir = clone_repo(repo, tmp_dir)
90
+ semgrep_output = run_semgrep(repo_dir)
91
+ vulnerable_files, total_vulns = extract_vulnerable_files(semgrep_output)
92
+
93
+ items_added = 0
94
+ for file_path, cwe in vulnerable_files.items():
95
+ if items_added >= 3:
96
+ logger.info(f"Reached maximum of 3 items for repository {repo.full_name}. Stopping processing.")
97
+ break
98
+
99
+ full_path = os.path.join(repo_dir, file_path)
100
+ logger.info(f"Analyzing file: {file_path}")
101
+ with open(full_path, 'r') as f:
102
+ source_code = f.read()
103
+
104
+ token_count = count_tokens(source_code)
105
+ if 512 <= token_count <= 1024:
106
+ new_item = {
107
+ "source": source_code,
108
+ "file_name": generate_random_filename(),
109
+ "cwe": cwe
110
+ }
111
+
112
+ with open(output_file, 'a') as f:
113
+ json.dump(new_item, f)
114
+ f.write('\n')
115
+ items_added += 1
116
+ logger.info(f"Added new item with CWE: {cwe}")
117
+ else:
118
+ logger.info(f"File skipped: token count ({token_count}) out of range")
119
+
120
+ logger.info(f"Processed {repo.full_name}: found {total_vulns} vulnerabilities, added {items_added} new items")
121
+
122
+ def preprocess_data(data):
123
+ """Ensure all fields are consistently typed across all items."""
124
+ if not data:
125
+ return data
126
+
127
+ # Identify fields that are sometimes lists
128
+ list_fields = set()
129
+ for item in data:
130
+ for key, value in item.items():
131
+ if isinstance(value, list):
132
+ list_fields.add(key)
133
+
134
+ # Ensure these fields are always lists
135
+ for item in data:
136
+ for key in list_fields:
137
+ if key not in item:
138
+ item[key] = []
139
+ elif not isinstance(item[key], list):
140
+ item[key] = [item[key]]
141
+
142
+ return data
143
+
144
+ def merge_and_push_dataset(jsonl_file, new_dataset_name):
145
+ """Push to Hugging Face."""
146
+ logging.info("Starting dataset push process")
147
+
148
+ # Load the new data from the JSONL file
149
+ logging.info("Loading new data from JSONL file")
150
+ with open(jsonl_file, 'r') as f:
151
+ new_data = [json.loads(line) for line in f]
152
+
153
+ logging.info(f"Loaded {len(new_data)} records from JSONL file")
154
+
155
+ # Preprocess the data
156
+ logging.info("Preprocessing data")
157
+ preprocessed_data = preprocess_data(new_data)
158
+
159
+ # Create dataset from the preprocessed data
160
+ logging.info("Creating dataset")
161
+ try:
162
+ dataset = Dataset.from_list(preprocessed_data)
163
+ except pa.lib.ArrowInvalid as e:
164
+ logging.error(f"Error creating dataset: {str(e)}")
165
+ logging.info("Attempting to create dataset with type inference disabled")
166
+ dataset = Dataset.from_list(preprocessed_data, features=pa.schema([]))
167
+
168
+ # Push the dataset to the new repository
169
+ logging.info(f"Pushing dataset with {len(dataset)} records to Hugging Face")
170
+ dataset.push_to_hub(new_dataset_name, private=True, token=HF_TOKEN)
171
+
172
+ logging.info("Dataset push process completed")
173
+
174
+ def main():
175
+ parser = argparse.ArgumentParser(description="Extend and upload static-analysis-eval dataset")
176
+ parser.add_argument("--push_to_dataset", help="Merge and push dataset to specified Hugging Face repository")
177
+ args = parser.parse_args()
178
+
179
+ if args.push_to_dataset:
180
+ # Merge and push the dataset
181
+ jsonl_file = "output.jsonl"
182
+ merge_and_push_dataset(jsonl_file, args.push_to_dataset)
183
+ else:
184
+ # Perform the regular dataset extension process
185
+ output_file = "static_analysis_eval.jsonl"
186
+ logger.info(f"Starting dataset extension process. Output file: {output_file}")
187
+
188
+ # Ensure the output file exists
189
+ open(output_file, 'a').close()
190
+
191
+ top_repos = search_top_repos()
192
+
193
+ for i, repo in enumerate(top_repos, 1):
194
+ try:
195
+ logger.info(f"Processing repository {i} of {len(top_repos)}: {repo.full_name}")
196
+ process_repository(repo, output_file)
197
+ except Exception as e:
198
+ logger.error(f"Error processing repository {repo.full_name}: {str(e)}", exc_info=True)
199
+
200
+ logger.info("Dataset extension process completed")
201
+
202
+ if __name__ == "__main__":
203
+ main()