Repository navigation
Expand file tree
/
Copy path07_audit_source_code.py
More file actions
236 lines (188 loc) · 6.22 KB
/
Copy path07_audit_source_code.py
File metadata and controls
236 lines (188 loc) · 6.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
from pathlib import Path
import re
import pandas as pd
PROJECT_DIR = Path(__file__).resolve().parent
INPUT_PATH = PROJECT_DIR / "SBAN_clean.parquet"
REPORT_DIR = PROJECT_DIR / "reports" / "audit"
COLUMN = "source_code"
ID_COL = "ID"
LABEL_COL = "dataset_name"
PROMPT_PHRASES = (
"paste the full source code",
"insert source code",
"paste code",
"your code",
"add main function",
"code goes",
"implementation goes",
"insert code",
"no modifications needed",
"corrected",
"here",
"no comments",
"additional",
)
ASSISTANT_PHRASES = (
"here is the",
"here's the",
"below is",
"as follows",
"let me",
"sure!",
"certainly",
"without comments",
"only the code",
"only code",
"corrected version",
"fix the code",
"complete_cleaned_code",
"main function is missing",
"no c++ solution",
"no output as the code",
)
COMMENT_INSTRUCTION_HINTS = (
"please remove",
"finish the code",
"add necessary",
"replace windows",
"missing headers",
"final code",
"resolve syntax",
"assume ",
"provided below",
"no c++ solution",
"complete_cleaned",
)
CODE_INDICATOR_RE = re.compile(
r"#include|#define|\{|;|\b(void|int|char|return|main|struct|class|typedef|enum|if|for|while)\b|__cdecl|__fastcall",
re.IGNORECASE,
)
PLACEHOLDER_RE = re.compile(
r"//\s*\.{3}|//\s*\.\.\.\s*$|<complete_cleaned_code>|//\s*\.\.\.\s*\n",
re.IGNORECASE,
)
def load_data() -> pd.DataFrame:
if not INPUT_PATH.exists():
raise FileNotFoundError(f"Dosya bulunamadı: {INPUT_PATH}")
return pd.read_parquet(INPUT_PATH, columns=[ID_COL, LABEL_COL, COLUMN])
def non_comment_lines(text: str) -> list[str]:
lines = []
for line in str(text).splitlines():
stripped = line.strip()
if not stripped:
continue
if stripped.startswith("//"):
continue
if stripped.startswith("/*") or stripped.startswith("*"):
continue
lines.append(stripped)
return lines
def has_code_indicators(text: str) -> bool:
return bool(CODE_INDICATOR_RE.search(str(text)))
def check_prompt_phrases(text: str) -> list[str]:
reasons = []
lower = str(text).lower()
for phrase in PROMPT_PHRASES:
if phrase in lower:
reasons.append(f"prompt_phrase:{phrase}")
return reasons
def check_assistant_phrases(text: str) -> list[str]:
reasons = []
lower = str(text).lower()
for phrase in ASSISTANT_PHRASES:
if phrase in lower:
reasons.append(f"assistant_phrase:{phrase}")
return reasons
def check_comment_instructions(text: str) -> list[str]:
reasons = []
for line in str(text).splitlines():
stripped = line.strip()
if not stripped.startswith("//"):
continue
lower = stripped.lower()
for hint in COMMENT_INSTRUCTION_HINTS:
if hint in lower:
reasons.append(f"instruction_comment:{hint}")
break
return reasons
def check_structure(text: str) -> list[str]:
text = str(text)
reasons = []
if "```" in text:
reasons.append("markdown_fence")
if PLACEHOLDER_RE.search(text):
reasons.append("placeholder_marker")
if len(text.strip()) < 20:
reasons.append("too_short:lt20")
if not non_comment_lines(text):
reasons.append("comment_only")
if not has_code_indicators(text):
reasons.append("no_code_indicators")
if len(text.strip()) < 50 and not has_code_indicators(text):
reasons.append("short_without_code")
return reasons
def audit_source(dataframe: pd.DataFrame) -> pd.DataFrame:
records = []
for _, row in dataframe.iterrows():
text = row[COLUMN]
reasons = []
reasons.extend(check_prompt_phrases(text))
reasons.extend(check_assistant_phrases(text))
reasons.extend(check_comment_instructions(text))
reasons.extend(check_structure(text))
if not reasons:
continue
unique_reasons = sorted(set(reasons))
high_reasons = {
"comment_only",
"no_code_indicators",
"markdown_fence",
"too_short:lt20",
"short_without_code",
}
severity = "high" if any(
reason.split(":")[0] in high_reasons
or reason.startswith("prompt_phrase:")
for reason in unique_reasons
) else "medium"
preview = str(text).replace("\n", " ")[:200]
records.append(
{
ID_COL: row[ID_COL],
LABEL_COL: row[LABEL_COL],
"severity": severity,
"reasons": "|".join(unique_reasons),
"reason_count": len(unique_reasons),
"preview": preview,
}
)
return pd.DataFrame(records)
def print_summary(flagged: pd.DataFrame, total_rows: int) -> None:
print(f"Toplam satır: {total_rows:,}")
print(f"Flagged ID: {len(flagged):,} ({len(flagged) / total_rows:.2%})")
print(f" high: {(flagged['severity'] == 'high').sum():,}")
print(f" medium: {(flagged['severity'] == 'medium').sum():,}")
print("\nDataset kırılımı:")
print(flagged[LABEL_COL].value_counts().sort_index().to_string())
reason_counts: dict[str, int] = {}
for reasons in flagged["reasons"]:
for reason in reasons.split("|"):
reason_counts[reason] = reason_counts.get(reason, 0) + 1
print("\nNeden sayıları:")
for reason, count in sorted(reason_counts.items(), key=lambda item: -item[1]):
print(f" {reason}: {count:,}")
def main() -> None:
dataframe = load_data()
flagged = audit_source(dataframe)
REPORT_DIR.mkdir(parents=True, exist_ok=True)
output_path = REPORT_DIR / "source_flagged_ids.csv"
flagged.sort_values([ "severity", LABEL_COL, ID_COL], ascending=[True, True, True]).to_csv(
output_path, index=False
)
ids_path = REPORT_DIR / "source_flagged_ids.txt"
ids_path.write_text("\n".join(flagged[ID_COL].astype(str).tolist()) + "\n")
print(f"Girdi: {INPUT_PATH.name}")
print_summary(flagged, len(dataframe))
print(f"\nKaydedildi:\n {output_path}\n {ids_path}")
if __name__ == "__main__":
main()