Spaces:
Running on Zero
Running on Zero
Commit ·
e65f6d3
1
Parent(s): e53b561
Update Space: remove LIG, use fast forward pass and Feature-level XAI per thesis specs
Browse files- README.md +4 -3
- app.py +94 -53
- html_renderer.py +0 -111
- requirements.txt +0 -1
README.md
CHANGED
|
@@ -13,9 +13,10 @@ license: mit
|
|
| 13 |
# 🕵️♂️ C++ AI Code Detector Pro
|
| 14 |
|
| 15 |
Hệ thống phát hiện mã nguồn C++ do AI sinh ra (AI Generated vs Human Written) sử dụng kiến trúc lai **Hybrid AI**:
|
| 16 |
-
- **Deep Learning:** GraphCodeBERT / RoBERTa (
|
| 17 |
-
- **Machine Learning & Feature Engineering:** 44 đặc trưng cú pháp, cấu trúc và thói quen lập trình C++ kết hợp **LightGBM**
|
| 18 |
-
- **Adaptive Controlled Fusion:** Cơ chế hợp nhất thích ứng có kiểm soát giúp tối đa hóa độ chính xác và
|
|
|
|
| 19 |
|
| 20 |
---
|
| 21 |
|
|
|
|
| 13 |
# 🕵️♂️ C++ AI Code Detector Pro
|
| 14 |
|
| 15 |
Hệ thống phát hiện mã nguồn C++ do AI sinh ra (AI Generated vs Human Written) sử dụng kiến trúc lai **Hybrid AI**:
|
| 16 |
+
- **Deep Learning:** GraphCodeBERT / RoBERTa (Single-Fold) với cơ chế phân loại ngữ nghĩa sâu cực nhanh.
|
| 17 |
+
- **Machine Learning & Feature Engineering:** 44 đặc trưng cú pháp, cấu trúc và thói quen lập trình C++ kết hợp **LightGBM**.
|
| 18 |
+
- **Adaptive Controlled Fusion:** Cơ chế hợp nhất thích ứng có kiểm soát giúp tối đa hóa độ chính xác và giải quyết xung đột vùng biên.
|
| 19 |
+
- **Feature-level Explainability:** Phân tích dấu vân tay phong cách lập trình (Stylometric Fingerprints) và bóc tách các đặc trưng định hướng dấu vết AI sinh mã.
|
| 20 |
|
| 21 |
---
|
| 22 |
|
app.py
CHANGED
|
@@ -8,10 +8,9 @@ import pandas as pd
|
|
| 8 |
import torch
|
| 9 |
import torch.nn.functional as F
|
| 10 |
from transformers import RobertaTokenizer, RobertaForSequenceClassification
|
| 11 |
-
from captum.attr import LayerIntegratedGradients
|
| 12 |
import gradio as gr
|
| 13 |
|
| 14 |
-
# Try importing Hugging Face ZeroGPU decorator
|
| 15 |
try:
|
| 16 |
import spaces
|
| 17 |
gpu_decorator = spaces.GPU
|
|
@@ -23,9 +22,8 @@ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
| 23 |
if BASE_DIR not in sys.path:
|
| 24 |
sys.path.insert(0, BASE_DIR)
|
| 25 |
|
| 26 |
-
# Import local
|
| 27 |
from feature_extractor import CppFeatureExtractorV8, strip_metadata_headers
|
| 28 |
-
from html_renderer import render_html_heatmap
|
| 29 |
|
| 30 |
from huggingface_hub import hf_hub_download
|
| 31 |
|
|
@@ -58,13 +56,14 @@ def get_pkl_path_or_hub(filename: str) -> str:
|
|
| 58 |
return ""
|
| 59 |
|
| 60 |
# ==============================================================================
|
| 61 |
-
# LOAD MODELS
|
| 62 |
# ==============================================================================
|
| 63 |
print("⏳ Loading RoBERTa models...")
|
| 64 |
path_oop, sub_oop = get_model_path_or_hub("fold_1_oop")
|
| 65 |
path_normal, sub_normal = get_model_path_or_hub("fold_1_basic")
|
| 66 |
|
| 67 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
|
|
|
| 68 |
|
| 69 |
try:
|
| 70 |
if sub_oop:
|
|
@@ -97,6 +96,7 @@ extractor = CppFeatureExtractorV8()
|
|
| 97 |
model_path = get_pkl_path_or_hub("LightGBM_Regulated.pkl")
|
| 98 |
scaler_path = get_pkl_path_or_hub("scaler.pkl")
|
| 99 |
feat_path = get_pkl_path_or_hub("final_features.pkl")
|
|
|
|
| 100 |
DEFAULT_FEATURES = [
|
| 101 |
'comment_ratio', 'empty_line_ratio', 'emoji_marker_score', 'avg_line_length',
|
| 102 |
'max_line_length', 'tab_vs_space_ratio', 'trailing_space_ratio', 'brace_style_consistency',
|
|
@@ -135,39 +135,80 @@ if feat_path:
|
|
| 135 |
print(f"⚠️ Feature names unpickle fallback to DEFAULT_FEATURES: {e}")
|
| 136 |
feature_names = DEFAULT_FEATURES
|
| 137 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
# ==============================================================================
|
| 139 |
-
# INFERENCE LOGIC
|
| 140 |
# ==============================================================================
|
| 141 |
def classify_oop_or_normal(code: str) -> str:
|
| 142 |
oop_keywords = ["class ", "struct ", "public:", "private:", "protected:", "virtual ", "override", "std::unique_ptr"]
|
| 143 |
hits = sum(1 for kw in oop_keywords if kw in code)
|
| 144 |
return "OOP" if hits >= 2 else "NORMAL"
|
| 145 |
|
| 146 |
-
def
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
|
| 167 |
@gpu_decorator
|
| 168 |
def predict_code(code_text: str, threshold: float = 0.5):
|
| 169 |
if not code_text or not code_text.strip():
|
| 170 |
-
return {"Lỗi": "Vui lòng nhập code C++"}, {},
|
| 171 |
|
| 172 |
t0 = time.perf_counter()
|
| 173 |
clean_code = strip_metadata_headers(code_text)
|
|
@@ -177,12 +218,14 @@ def predict_code(code_text: str, threshold: float = 0.5):
|
|
| 177 |
active_model = model_oop if code_type == "OOP" and model_oop is not None else model_normal
|
| 178 |
model_label = f"C++ {code_type} Model"
|
| 179 |
|
| 180 |
-
# 2. Machine Learning
|
| 181 |
lgbm_score = 0.5
|
| 182 |
extracted_features = {}
|
| 183 |
features_df = pd.DataFrame()
|
| 184 |
-
if extractor is not None
|
| 185 |
extracted_features = extractor.extract(clean_code)
|
|
|
|
|
|
|
| 186 |
df = pd.DataFrame([extracted_features]).fillna(0)
|
| 187 |
try:
|
| 188 |
X_all = df[scaler.feature_names_in_]
|
|
@@ -192,16 +235,13 @@ def predict_code(code_text: str, threshold: float = 0.5):
|
|
| 192 |
indices = [all_feat.index(f) for f in feat_list]
|
| 193 |
X_final = X_scaled[:, indices]
|
| 194 |
lgbm_score = float(lgbm_model.predict_proba(X_final)[0][1])
|
| 195 |
-
|
| 196 |
-
# Format dataframe for display
|
| 197 |
-
feat_rows = [{"Đặc trưng": k, "Giá trị": f"{v:.4f}" if isinstance(v, float) else str(v)} for k, v in extracted_features.items()]
|
| 198 |
-
features_df = pd.DataFrame(feat_rows)
|
| 199 |
except Exception:
|
| 200 |
lgbm_score = 0.5
|
|
|
|
| 201 |
|
| 202 |
-
# 3. Deep Learning
|
| 203 |
dl_score = 0.5
|
| 204 |
-
html_heatmap = ""
|
| 205 |
if active_model and tokenizer:
|
| 206 |
cur_device = next(active_model.parameters()).device
|
| 207 |
inputs = tokenizer(
|
|
@@ -212,19 +252,12 @@ def predict_code(code_text: str, threshold: float = 0.5):
|
|
| 212 |
return_attention_mask=True
|
| 213 |
)
|
| 214 |
inputs = {k: v.to(cur_device) for k, v in inputs.items()}
|
| 215 |
-
input_ids = inputs["input_ids"]
|
| 216 |
|
| 217 |
with torch.no_grad():
|
| 218 |
logits = active_model(**inputs).logits
|
| 219 |
probs = F.softmax(logits, dim=-1)
|
| 220 |
dl_score = float(probs[0][1].item())
|
| 221 |
|
| 222 |
-
try:
|
| 223 |
-
tokens, attributions = run_lig_attribution(active_model, tokenizer, input_ids, target_class=1, n_steps=10)
|
| 224 |
-
html_heatmap = render_html_heatmap(tokens, attributions, title=f"LIG Attribution — {model_label}")
|
| 225 |
-
except Exception as e:
|
| 226 |
-
html_heatmap = f"<p>Lỗi tạo heatmap: {e}</p>"
|
| 227 |
-
|
| 228 |
# 4. Controlled Adaptive Fusion
|
| 229 |
final_score = 0.48 * dl_score + 0.52 * lgbm_score
|
| 230 |
conflict = False
|
|
@@ -249,9 +282,10 @@ def predict_code(code_text: str, threshold: float = 0.5):
|
|
| 249 |
"Điểm Machine Learning (LightGBM)": f"{lgbm_score:.4f}",
|
| 250 |
"Hợp nhất có kiểm soát (Fusion)": "Đã kích hoạt" if conflict else "Chuẩn",
|
| 251 |
"Thời gian xử lý": f"{latency_ms:.0f} ms",
|
|
|
|
| 252 |
}
|
| 253 |
|
| 254 |
-
return label_output, metrics_output,
|
| 255 |
|
| 256 |
# ==============================================================================
|
| 257 |
# GRADIO INTERFACE
|
|
@@ -309,9 +343,18 @@ int main() {
|
|
| 309 |
return 0;
|
| 310 |
}"""
|
| 311 |
|
| 312 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 313 |
gr.Markdown("# 🕵️♂️ C++ AI Code Detector Pro")
|
| 314 |
-
gr.Markdown(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 315 |
|
| 316 |
with gr.Row():
|
| 317 |
with gr.Column(scale=5):
|
|
@@ -332,18 +375,16 @@ with gr.Blocks(title="C++ AI Code Detector Pro") as demo:
|
|
| 332 |
output_label = gr.Label(label="Kết luận phân loại", num_top_classes=2)
|
| 333 |
output_metrics = gr.JSON(label="Chỉ số phân tích chi tiết (Metrics)")
|
| 334 |
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
output_heatmap = gr.HTML()
|
| 339 |
-
with gr.TabItem("📊 Đặc trưng cú pháp & hình thái (Stylometric Features)"):
|
| 340 |
-
output_features = gr.Dataframe(headers=["Đặc trưng", "Giá trị"], interactive=False)
|
| 341 |
|
| 342 |
analyze_btn.click(
|
| 343 |
fn=predict_code,
|
| 344 |
inputs=[code_input, threshold_slider],
|
| 345 |
-
outputs=[output_label, output_metrics,
|
| 346 |
)
|
| 347 |
|
| 348 |
if __name__ == "__main__":
|
| 349 |
-
|
|
|
|
|
|
| 8 |
import torch
|
| 9 |
import torch.nn.functional as F
|
| 10 |
from transformers import RobertaTokenizer, RobertaForSequenceClassification
|
|
|
|
| 11 |
import gradio as gr
|
| 12 |
|
| 13 |
+
# Try importing Hugging Face ZeroGPU decorator (fallback for local CPU/GPU)
|
| 14 |
try:
|
| 15 |
import spaces
|
| 16 |
gpu_decorator = spaces.GPU
|
|
|
|
| 22 |
if BASE_DIR not in sys.path:
|
| 23 |
sys.path.insert(0, BASE_DIR)
|
| 24 |
|
| 25 |
+
# Import local feature extractor
|
| 26 |
from feature_extractor import CppFeatureExtractorV8, strip_metadata_headers
|
|
|
|
| 27 |
|
| 28 |
from huggingface_hub import hf_hub_download
|
| 29 |
|
|
|
|
| 56 |
return ""
|
| 57 |
|
| 58 |
# ==============================================================================
|
| 59 |
+
# LOAD MODELS (GLOBAL CACHE)
|
| 60 |
# ==============================================================================
|
| 61 |
print("⏳ Loading RoBERTa models...")
|
| 62 |
path_oop, sub_oop = get_model_path_or_hub("fold_1_oop")
|
| 63 |
path_normal, sub_normal = get_model_path_or_hub("fold_1_basic")
|
| 64 |
|
| 65 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 66 |
+
print(f"🖥️ Inference Device: {DEVICE}")
|
| 67 |
|
| 68 |
try:
|
| 69 |
if sub_oop:
|
|
|
|
| 96 |
model_path = get_pkl_path_or_hub("LightGBM_Regulated.pkl")
|
| 97 |
scaler_path = get_pkl_path_or_hub("scaler.pkl")
|
| 98 |
feat_path = get_pkl_path_or_hub("final_features.pkl")
|
| 99 |
+
|
| 100 |
DEFAULT_FEATURES = [
|
| 101 |
'comment_ratio', 'empty_line_ratio', 'emoji_marker_score', 'avg_line_length',
|
| 102 |
'max_line_length', 'tab_vs_space_ratio', 'trailing_space_ratio', 'brace_style_consistency',
|
|
|
|
| 135 |
print(f"⚠️ Feature names unpickle fallback to DEFAULT_FEATURES: {e}")
|
| 136 |
feature_names = DEFAULT_FEATURES
|
| 137 |
|
| 138 |
+
# Metadata and descriptions for feature interpretability
|
| 139 |
+
FEATURE_METADATA = {
|
| 140 |
+
'comment_ratio': ('Tỷ lệ dòng chú thích', 'Phong cách', 'AI thường có tỷ lệ comment cao hơn để diễn giải code'),
|
| 141 |
+
'empty_line_ratio': ('Tỷ lệ dòng trống', 'Phong cách', 'Cấu trúc phân tách logic code'),
|
| 142 |
+
'avg_line_length': ('Độ dài dòng trung bình', 'Phong cách', 'Độ dài ký tự trên mỗi dòng'),
|
| 143 |
+
'brace_style_consistency': ('Độ nhất quán dấu ngoặc { }', 'Phong cách', 'AI thường đạt 1.0 (nhất quán tuyệt đối theo chuẩn formatting)'),
|
| 144 |
+
'tab_vs_space_ratio': ('Tỷ lệ Tab vs Space', 'Phong cách', 'Thói quen canh lề thụt đầu dòng'),
|
| 145 |
+
'single_char_var_ratio': ('Tỷ lệ biến 1 ký tự (i, j, n)', 'Định danh', 'Lập trình viên thường dùng nhiều biến ngắn (i, j, k), AI ưa chuộng biến tường minh'),
|
| 146 |
+
'avg_identifier_length': ('Độ dài tên biến trung bình', 'Định danh', 'AI thường đặt tên biến dài mang tính tự giải thích (verbose)'),
|
| 147 |
+
'identifier_length_variance': ('Phương sai độ dài biến', 'Định danh', 'Độ đa dạng trong quy ước đặt tên của lập trình viên'),
|
| 148 |
+
'unique_identifier_ratio': ('Tỷ lệ biến số độc nhất', 'Định danh', 'Mức độ tái sử dụng biến'),
|
| 149 |
+
'has_bits_stdc': ('Sử dụng <bits/stdc++.h>', 'Thói quen C++', 'Đặc trưng mạnh của lập trình viên competitive programming'),
|
| 150 |
+
'has_fast_io': ('Tối ưu Fast I/O (cin.tie)', 'Thói quen C++', 'Thói quen tối ưu nhập xuất của con người'),
|
| 151 |
+
'using_std_ratio': ('Sử dụng "using namespace std"', 'Thói quen C++', 'Lập trình viên hay viết tắt namespace, AI thường dùng std:: tường minh'),
|
| 152 |
+
'std_prefix_ratio': ('Tỷ lệ tiền tố std::', 'Thói quen C++', 'AI có xu hướng giữ nguyên tiền tố namespace'),
|
| 153 |
+
'class_count': ('Số lượng lớp (Class)', 'OOP', 'Đo lường mức độ lập trình hướng đối tượng'),
|
| 154 |
+
'struct_count': ('Số lượng Struct', 'OOP', 'Đo lường cấu trúc dữ liệu tùy chỉnh'),
|
| 155 |
+
'virtual_override_ratio': ('Tỷ lệ virtual / override', 'OOP', 'Tính đa hình nâng cao trong C++'),
|
| 156 |
+
'getter_setter_ratio': ('Tỷ lệ Getter/Setter', 'OOP', 'Mẫu đóng gói dữ liệu thường thấy ở AI sinh mã'),
|
| 157 |
+
'halstead_volume': ('Khối lượng phần mềm Halstead', 'Độ phức tạp', 'Đo lường kích thước lượng từ vựng và toán tử'),
|
| 158 |
+
'maintainability_index': ('Chỉ số bảo trì (MI)', 'Độ phức tạp', 'Khả năng đọc hiểu và bảo trì code'),
|
| 159 |
+
'shannon_entropy': ('Độ hỗn loạn thông tin (Entropy)', 'Độ phức tạp', 'Độ đa dạng và ngẫu nhiên của phân phối ký tự'),
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
# ==============================================================================
|
| 163 |
+
# INFERENCE LOGIC (PURE FORWARD PASS — NO LIG)
|
| 164 |
# ==============================================================================
|
| 165 |
def classify_oop_or_normal(code: str) -> str:
|
| 166 |
oop_keywords = ["class ", "struct ", "public:", "private:", "protected:", "virtual ", "override", "std::unique_ptr"]
|
| 167 |
hits = sum(1 for kw in oop_keywords if kw in code)
|
| 168 |
return "OOP" if hits >= 2 else "NORMAL"
|
| 169 |
|
| 170 |
+
def interpret_feature_signals(extracted: dict, feat_list: list) -> pd.DataFrame:
|
| 171 |
+
"""Build feature-level XAI interpretation table."""
|
| 172 |
+
rows = []
|
| 173 |
+
for k in feat_list:
|
| 174 |
+
val = extracted.get(k, 0.0)
|
| 175 |
+
meta = FEATURE_METADATA.get(k, (k, "Chung", "Đặc trưng phân loại"))
|
| 176 |
+
name_vn, group, desc = meta
|
| 177 |
+
|
| 178 |
+
# Heuristic directional bias based on empirical research
|
| 179 |
+
signal = "Trung lập"
|
| 180 |
+
if k == 'single_char_var_ratio' and val > 0.15:
|
| 181 |
+
signal = "👤 Người viết (Biến ngắn gọn)"
|
| 182 |
+
elif k == 'has_bits_stdc' and val > 0.5:
|
| 183 |
+
signal = "👤 Người viết (Thư viện gộp)"
|
| 184 |
+
elif k == 'has_fast_io' and val > 0.5:
|
| 185 |
+
signal = "👤 Người viết (Fast I/O)"
|
| 186 |
+
elif k == 'using_std_ratio' and val > 0.5:
|
| 187 |
+
signal = "👤 Người viết (namespace mở)"
|
| 188 |
+
elif k == 'comment_ratio' and val > 0.12:
|
| 189 |
+
signal = "🤖 AI Sinh ra (Comment chi tiết)"
|
| 190 |
+
elif k == 'avg_identifier_length' and val > 8.0:
|
| 191 |
+
signal = "🤖 AI Sinh ra (Tên biến dài)"
|
| 192 |
+
elif k == 'brace_style_consistency' and val >= 0.98:
|
| 193 |
+
signal = "🤖 AI Sinh ra (Format chuẩn mực)"
|
| 194 |
+
elif k == 'std_prefix_ratio' and val > 0.6:
|
| 195 |
+
signal = "🤖 AI Sinh ra (std:: tường minh)"
|
| 196 |
+
elif k == 'getter_setter_ratio' and val > 0:
|
| 197 |
+
signal = "🤖 AI Sinh ra (Getter/Setter)"
|
| 198 |
+
|
| 199 |
+
rows.append({
|
| 200 |
+
"Đặc trưng": name_vn,
|
| 201 |
+
"Nhóm": group,
|
| 202 |
+
"Giá trị": f"{val:.4f}" if isinstance(val, float) else str(val),
|
| 203 |
+
"Tín hiệu định hướng": signal,
|
| 204 |
+
"Giải thích học thuật": desc
|
| 205 |
+
})
|
| 206 |
+
return pd.DataFrame(rows)
|
| 207 |
|
| 208 |
@gpu_decorator
|
| 209 |
def predict_code(code_text: str, threshold: float = 0.5):
|
| 210 |
if not code_text or not code_text.strip():
|
| 211 |
+
return {"Lỗi": "Vui lòng nhập code C++"}, {}, pd.DataFrame()
|
| 212 |
|
| 213 |
t0 = time.perf_counter()
|
| 214 |
clean_code = strip_metadata_headers(code_text)
|
|
|
|
| 218 |
active_model = model_oop if code_type == "OOP" and model_oop is not None else model_normal
|
| 219 |
model_label = f"C++ {code_type} Model"
|
| 220 |
|
| 221 |
+
# 2. Machine Learning (Stylometric 44 features)
|
| 222 |
lgbm_score = 0.5
|
| 223 |
extracted_features = {}
|
| 224 |
features_df = pd.DataFrame()
|
| 225 |
+
if extractor is not None:
|
| 226 |
extracted_features = extractor.extract(clean_code)
|
| 227 |
+
|
| 228 |
+
if lgbm_model is not None and scaler is not None and feature_names is not None:
|
| 229 |
df = pd.DataFrame([extracted_features]).fillna(0)
|
| 230 |
try:
|
| 231 |
X_all = df[scaler.feature_names_in_]
|
|
|
|
| 235 |
indices = [all_feat.index(f) for f in feat_list]
|
| 236 |
X_final = X_scaled[:, indices]
|
| 237 |
lgbm_score = float(lgbm_model.predict_proba(X_final)[0][1])
|
| 238 |
+
features_df = interpret_feature_signals(extracted_features, feat_list)
|
|
|
|
|
|
|
|
|
|
| 239 |
except Exception:
|
| 240 |
lgbm_score = 0.5
|
| 241 |
+
features_df = pd.DataFrame([{"Đặc trưng": k, "Giá trị": str(v)} for k, v in extracted_features.items()])
|
| 242 |
|
| 243 |
+
# 3. Deep Learning (GraphCodeBERT Pure Forward Pass)
|
| 244 |
dl_score = 0.5
|
|
|
|
| 245 |
if active_model and tokenizer:
|
| 246 |
cur_device = next(active_model.parameters()).device
|
| 247 |
inputs = tokenizer(
|
|
|
|
| 252 |
return_attention_mask=True
|
| 253 |
)
|
| 254 |
inputs = {k: v.to(cur_device) for k, v in inputs.items()}
|
|
|
|
| 255 |
|
| 256 |
with torch.no_grad():
|
| 257 |
logits = active_model(**inputs).logits
|
| 258 |
probs = F.softmax(logits, dim=-1)
|
| 259 |
dl_score = float(probs[0][1].item())
|
| 260 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 261 |
# 4. Controlled Adaptive Fusion
|
| 262 |
final_score = 0.48 * dl_score + 0.52 * lgbm_score
|
| 263 |
conflict = False
|
|
|
|
| 282 |
"Điểm Machine Learning (LightGBM)": f"{lgbm_score:.4f}",
|
| 283 |
"Hợp nhất có kiểm soát (Fusion)": "Đã kích hoạt" if conflict else "Chuẩn",
|
| 284 |
"Thời gian xử lý": f"{latency_ms:.0f} ms",
|
| 285 |
+
"Phương pháp giải thích": "Feature-level Explainability (Stylometric XAI)"
|
| 286 |
}
|
| 287 |
|
| 288 |
+
return label_output, metrics_output, features_df
|
| 289 |
|
| 290 |
# ==============================================================================
|
| 291 |
# GRADIO INTERFACE
|
|
|
|
| 343 |
return 0;
|
| 344 |
}"""
|
| 345 |
|
| 346 |
+
custom_css = """
|
| 347 |
+
footer {visibility: hidden;}
|
| 348 |
+
.gradio-container {max-width: 1200px !important; margin: auto;}
|
| 349 |
+
"""
|
| 350 |
+
|
| 351 |
+
with gr.Blocks(title="C++ AI Code Detector Pro", css=custom_css) as demo:
|
| 352 |
gr.Markdown("# 🕵️♂️ C++ AI Code Detector Pro")
|
| 353 |
+
gr.Markdown(
|
| 354 |
+
"Hệ thống phát hiện mã nguồn C++ do AI sinh ra (AI Generated vs Human Written) sử dụng kiến trúc lai **Hybrid AI**: "
|
| 355 |
+
"kết hợp ngữ nghĩa sâu của **GraphCodeBERT**, 44 đặc trưng phong cách lập trình (**LightGBM Stylometry**), "
|
| 356 |
+
"và cơ chế giải thích ở cấp độ thuộc tính (**Feature-level XAI**)."
|
| 357 |
+
)
|
| 358 |
|
| 359 |
with gr.Row():
|
| 360 |
with gr.Column(scale=5):
|
|
|
|
| 375 |
output_label = gr.Label(label="Kết luận phân loại", num_top_classes=2)
|
| 376 |
output_metrics = gr.JSON(label="Chỉ số phân tích chi tiết (Metrics)")
|
| 377 |
|
| 378 |
+
gr.Markdown("### 📊 Giải thích chi tiết theo thuộc tính phong cách (Feature-level XAI & Stylometric Fingerprints)")
|
| 379 |
+
gr.Markdown("Bảng phân rã các đặc trưng phong cách, thói quen cú pháp và hình thái mã nguồn C++ để phát hiện dấu vết sinh mã của AI:")
|
| 380 |
+
output_features = gr.Dataframe(headers=["Đặc trưng", "Nhóm", "Giá trị", "Tín hiệu định hướng", "Giải thích học thuật"], interactive=False)
|
|
|
|
|
|
|
|
|
|
| 381 |
|
| 382 |
analyze_btn.click(
|
| 383 |
fn=predict_code,
|
| 384 |
inputs=[code_input, threshold_slider],
|
| 385 |
+
outputs=[output_label, output_metrics, output_features]
|
| 386 |
)
|
| 387 |
|
| 388 |
if __name__ == "__main__":
|
| 389 |
+
port = int(os.environ.get("PORT", 7860))
|
| 390 |
+
demo.launch(server_name="0.0.0.0", server_port=port, share=False)
|
html_renderer.py
DELETED
|
@@ -1,111 +0,0 @@
|
|
| 1 |
-
import html
|
| 2 |
-
import numpy as np
|
| 3 |
-
from collections import defaultdict
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
def render_html_heatmap(
|
| 7 |
-
tokens: list[str],
|
| 8 |
-
attributions: list[float],
|
| 9 |
-
title: str = "CODE ANALYSIS",
|
| 10 |
-
) -> str:
|
| 11 |
-
"""Render an HTML heatmap visualization of token attributions."""
|
| 12 |
-
if tokens is None or attributions is None or len(tokens) == 0 or len(attributions) == 0:
|
| 13 |
-
return "<p>Chưa có dữ liệu gán nhãn token.</p>"
|
| 14 |
-
|
| 15 |
-
attributions = list(attributions)
|
| 16 |
-
|
| 17 |
-
aggregated_blocks = []
|
| 18 |
-
current_tokens = []
|
| 19 |
-
current_score_sum = 0.0
|
| 20 |
-
token_count = 0
|
| 21 |
-
|
| 22 |
-
for token, score in zip(tokens, attributions):
|
| 23 |
-
if token in ['<s>', '</s>', '<pad>']:
|
| 24 |
-
continue
|
| 25 |
-
|
| 26 |
-
is_start_new_word = token.startswith('Ġ') or token.startswith('Ċ')
|
| 27 |
-
if is_start_new_word and current_tokens:
|
| 28 |
-
raw_str = "".join(current_tokens)
|
| 29 |
-
full_word = raw_str.replace("Ġ", " ").replace("Ċ", "\n")
|
| 30 |
-
if full_word:
|
| 31 |
-
avg_score = current_score_sum / token_count if token_count > 0 else 0
|
| 32 |
-
aggregated_blocks.append((full_word, avg_score))
|
| 33 |
-
current_tokens = []
|
| 34 |
-
current_score_sum = 0.0
|
| 35 |
-
token_count = 0
|
| 36 |
-
|
| 37 |
-
current_tokens.append(token)
|
| 38 |
-
current_score_sum += score
|
| 39 |
-
token_count += 1
|
| 40 |
-
|
| 41 |
-
if current_tokens:
|
| 42 |
-
raw_str = "".join(current_tokens)
|
| 43 |
-
full_word = raw_str.replace("Ġ", " ").replace("Ċ", "\n")
|
| 44 |
-
if full_word:
|
| 45 |
-
aggregated_blocks.append((full_word, current_score_sum / token_count))
|
| 46 |
-
|
| 47 |
-
word_stats = defaultdict(list)
|
| 48 |
-
for word, score in aggregated_blocks:
|
| 49 |
-
clean_word = word.strip()
|
| 50 |
-
if clean_word:
|
| 51 |
-
word_stats[clean_word].append(score)
|
| 52 |
-
|
| 53 |
-
unique_words_list = [(word, sum(score_list) / len(score_list)) for word, score_list in word_stats.items()]
|
| 54 |
-
pos_words = sorted([(w, s) for w, s in unique_words_list if s > 0], key=lambda x: x[1], reverse=True)
|
| 55 |
-
neg_words = sorted([(w, s) for w, s in unique_words_list if s < 0], key=lambda x: x[1])
|
| 56 |
-
|
| 57 |
-
top_k = 50
|
| 58 |
-
ai_list_html = [
|
| 59 |
-
f"<tr><td style='color:#2ecc71; font-weight:bold; padding:4px 8px; border-bottom:1px solid #f0f0f0;'>{html.escape(w)}</td><td style='text-align:right; color:#555; padding:4px 8px; border-bottom:1px solid #f0f0f0;'>{s:.3f}</td></tr>"
|
| 60 |
-
for w, s in pos_words[:top_k]
|
| 61 |
-
]
|
| 62 |
-
human_list_html = [
|
| 63 |
-
f"<tr><td style='color:#e74c3c; font-weight:bold; padding:4px 8px; border-bottom:1px solid #f0f0f0;'>{html.escape(w)}</td><td style='text-align:right; color:#555; padding:4px 8px; border-bottom:1px solid #f0f0f0;'>{s:.3f}</td></tr>"
|
| 64 |
-
for w, s in neg_words[:top_k]
|
| 65 |
-
]
|
| 66 |
-
|
| 67 |
-
code_html_parts = []
|
| 68 |
-
all_scores = [abs(s) for w, s in aggregated_blocks]
|
| 69 |
-
max_impact = float(np.max(all_scores)) if len(all_scores) > 0 and float(np.max(all_scores)) > 0 else 1.0
|
| 70 |
-
|
| 71 |
-
for word, score in aggregated_blocks:
|
| 72 |
-
safe_word = html.escape(word)
|
| 73 |
-
relative_score = abs(score) / max_impact
|
| 74 |
-
alpha = min(float(np.power(relative_score, 0.35)), 1.0)
|
| 75 |
-
bg_color = "transparent"
|
| 76 |
-
if alpha >= 0.02:
|
| 77 |
-
bg_color = f"rgba(46, 204, 113, {alpha:.2f})" if score > 0 else f"rgba(231, 76, 60, {alpha:.2f})"
|
| 78 |
-
code_html_parts.append(f'<span style="background-color: {bg_color}; border-radius: 2px;">{safe_word}</span>')
|
| 79 |
-
|
| 80 |
-
code_html = "".join(code_html_parts)
|
| 81 |
-
|
| 82 |
-
human_table = "".join(human_list_html) if human_list_html else "<tr><td colspan='2' align='center' style='padding:10px; color:#999'>None</td></tr>"
|
| 83 |
-
ai_table = "".join(ai_list_html) if ai_list_html else "<tr><td colspan='2' align='center' style='padding:10px; color:#999'>None</td></tr>"
|
| 84 |
-
|
| 85 |
-
return f"""
|
| 86 |
-
<html>
|
| 87 |
-
<head><meta charset="utf-8"></head>
|
| 88 |
-
<body style="margin:0; padding:0; background-color: #f8f9fa;">
|
| 89 |
-
<div style="display: flex; gap: 20px; font-family: 'Segoe UI', sans-serif; margin-bottom: 30px;">
|
| 90 |
-
<div style="flex: 3; border: 1px solid #ccc; border-radius: 8px; background-color: #fff; overflow: hidden; box-shadow: 0 4px 10px rgba(0,0,0,0.08);">
|
| 91 |
-
<div style="background-color: #2c3e50; padding: 12px 15px; border-bottom: 1px solid #000; font-weight: bold; color: #ecf0f1; font-size: 14px;">📑 {html.escape(title)}</div>
|
| 92 |
-
<div style="padding: 15px; font-family: 'Consolas', 'Monaco', monospace; font-size: 13px; line-height: 1.6; color: #222; height: auto; overflow-y: visible; white-space: pre-wrap;">{code_html}</div>
|
| 93 |
-
</div>
|
| 94 |
-
<div style="flex: 1.2; display: flex; flex-direction: column; gap: 15px; max-height: 800px; position: sticky; top: 0;">
|
| 95 |
-
<div style="border: 1px solid #f5c6cb; border-radius: 8px; background-color: #fff; overflow: hidden; display: flex; flex-direction: column; flex: 1;">
|
| 96 |
-
<div style="background-color: #f8d7da; padding: 10px; text-align: center; color: #721c24; font-weight: bold; font-size: 13px; border-bottom: 1px solid #f5c6cb;">👤 Human Signals (Negative)</div>
|
| 97 |
-
<div style="padding: 0; overflow-y: auto; flex: 1; max-height: 350px;">
|
| 98 |
-
<table style="width:100%; font-size:12px; border-collapse: collapse; margin: 0;"><tbody>{human_table}</tbody></table>
|
| 99 |
-
</div>
|
| 100 |
-
</div>
|
| 101 |
-
<div style="border: 1px solid #c3e6cb; border-radius: 8px; background-color: #fff; overflow: hidden; display: flex; flex-direction: column; flex: 1;">
|
| 102 |
-
<div style="background-color: #d4edda; padding: 10px; text-align: center; color: #155724; font-weight: bold; font-size: 13px; border-bottom: 1px solid #c3e6cb;">🤖 AI Signals (Positive)</div>
|
| 103 |
-
<div style="padding: 0; overflow-y: auto; flex: 1; max-height: 350px;">
|
| 104 |
-
<table style="width:100%; font-size:12px; border-collapse: collapse; margin: 0;"><tbody>{ai_table}</tbody></table>
|
| 105 |
-
</div>
|
| 106 |
-
</div>
|
| 107 |
-
</div>
|
| 108 |
-
</div>
|
| 109 |
-
</body>
|
| 110 |
-
</html>
|
| 111 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
requirements.txt
CHANGED
|
@@ -1,7 +1,6 @@
|
|
| 1 |
torch>=2.0.0
|
| 2 |
transformers>=4.36.0
|
| 3 |
lightgbm>=4.0.0
|
| 4 |
-
captum>=0.7.0
|
| 5 |
scikit-learn>=1.3.0
|
| 6 |
numpy>=1.24.0
|
| 7 |
pandas>=2.0.0
|
|
|
|
| 1 |
torch>=2.0.0
|
| 2 |
transformers>=4.36.0
|
| 3 |
lightgbm>=4.0.0
|
|
|
|
| 4 |
scikit-learn>=1.3.0
|
| 5 |
numpy>=1.24.0
|
| 6 |
pandas>=2.0.0
|