nguyenvannhi224's picture
Update Space: remove LIG, use fast forward pass and Feature-level XAI per thesis specs
e65f6d3
Raw History Blame Contribute Delete
17 kB
import os
import sys
import time
import math
import joblib
import numpy as np
import pandas as pd
import torch
import torch.nn.functional as F
from transformers import RobertaTokenizer, RobertaForSequenceClassification
import gradio as gr
# Try importing Hugging Face ZeroGPU decorator (fallback for local CPU/GPU)
try:
import spaces
gpu_decorator = spaces.GPU
except ImportError:
def gpu_decorator(func):
return func
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
if BASE_DIR not in sys.path:
sys.path.insert(0, BASE_DIR)
# Import local feature extractor
from feature_extractor import CppFeatureExtractorV8, strip_metadata_headers
from huggingface_hub import hf_hub_download
HF_REPO_ID = "nguyenvannhi224/cpp-code-detector-models"
def resolve_model_dir(relative_name: str) -> str:
candidates = [
os.path.join(BASE_DIR, "local_models", relative_name),
os.path.join(BASE_DIR, relative_name),
os.path.join(os.path.dirname(BASE_DIR), "local_models", relative_name),
]
for c in candidates:
if os.path.exists(c):
return c
return candidates[0]
def get_model_path_or_hub(subfolder: str):
local_p = resolve_model_dir(subfolder)
if os.path.isdir(local_p) and os.path.exists(os.path.join(local_p, "model.safetensors")):
return local_p, None
return HF_REPO_ID, subfolder
def get_pkl_path_or_hub(filename: str) -> str:
local_p = resolve_model_dir(os.path.join("saved_models", filename))
if os.path.exists(local_p):
return local_p
try:
return hf_hub_download(repo_id=HF_REPO_ID, filename=f"saved_models/{filename}")
except Exception:
return ""
# ==============================================================================
# LOAD MODELS (GLOBAL CACHE)
# ==============================================================================
print("⏳ Loading RoBERTa models...")
path_oop, sub_oop = get_model_path_or_hub("fold_1_oop")
path_normal, sub_normal = get_model_path_or_hub("fold_1_basic")
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
print(f"🖥️ Inference Device: {DEVICE}")
try:
if sub_oop:
tokenizer = RobertaTokenizer.from_pretrained(path_oop, subfolder=sub_oop)
model_oop = RobertaForSequenceClassification.from_pretrained(path_oop, subfolder=sub_oop).to(DEVICE)
else:
tokenizer = RobertaTokenizer.from_pretrained(path_oop)
model_oop = RobertaForSequenceClassification.from_pretrained(path_oop).to(DEVICE)
model_oop.eval()
print("✅ Loaded OOP model")
except Exception as e:
tokenizer = RobertaTokenizer.from_pretrained("microsoft/graphcodebert-base")
model_oop = None
print(f"⚠️ Failed to load OOP model: {e}")
try:
if sub_normal:
model_normal = RobertaForSequenceClassification.from_pretrained(path_normal, subfolder=sub_normal).to(DEVICE)
else:
model_normal = RobertaForSequenceClassification.from_pretrained(path_normal).to(DEVICE)
model_normal.eval()
print("✅ Loaded Normal model")
except Exception as e:
model_normal = None
print(f"⚠️ Failed to load Normal model: {e}")
print("⏳ Loading LightGBM & Scaler...")
extractor = CppFeatureExtractorV8()
model_path = get_pkl_path_or_hub("LightGBM_Regulated.pkl")
scaler_path = get_pkl_path_or_hub("scaler.pkl")
feat_path = get_pkl_path_or_hub("final_features.pkl")
DEFAULT_FEATURES = [
'comment_ratio', 'empty_line_ratio', 'emoji_marker_score', 'avg_line_length',
'max_line_length', 'tab_vs_space_ratio', 'trailing_space_ratio', 'brace_style_consistency',
'avg_identifier_length', 'identifier_length_variance', 'single_char_var_ratio',
'unique_identifier_ratio', 'keyword_to_identifier_ratio', 'halstead_volume',
'halstead_difficulty', 'maintainability_index', 'code_to_comment_ratio', 'max_nesting_depth',
'total_includes', 'has_bits_stdc', 'macro_count', 'const_usage_ratio', 'shannon_entropy',
'struct_count', 'virtual_override_ratio', 'using_std_ratio', 'raw_pointer_ratio',
'getter_setter_ratio', 'std_prefix_ratio', 'cpp_cast_ratio'
]
lgbm_model = None
scaler = None
feature_names = DEFAULT_FEATURES
if model_path:
try:
lgbm_model = joblib.load(model_path)
print("✅ LightGBM model loaded")
except Exception as e:
print(f"⚠️ LightGBM model load failed: {e}")
if scaler_path:
try:
scaler = joblib.load(scaler_path)
print("✅ Scaler loaded")
except Exception as e:
print(f"⚠️ Scaler load failed: {e}")
if feat_path:
try:
raw_feat = joblib.load(feat_path)
feature_names = list(raw_feat)
print("✅ Feature names loaded")
except Exception as e:
print(f"⚠️ Feature names unpickle fallback to DEFAULT_FEATURES: {e}")
feature_names = DEFAULT_FEATURES
# Metadata and descriptions for feature interpretability
FEATURE_METADATA = {
'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'),
'empty_line_ratio': ('Tỷ lệ dòng trống', 'Phong cách', 'Cấu trúc phân tách logic code'),
'avg_line_length': ('Độ dài dòng trung bình', 'Phong cách', 'Độ dài ký tự trên mỗi dòng'),
'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)'),
'tab_vs_space_ratio': ('Tỷ lệ Tab vs Space', 'Phong cách', 'Thói quen canh lề thụt đầu dòng'),
'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'),
'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)'),
'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'),
'unique_identifier_ratio': ('Tỷ lệ biến số độc nhất', 'Định danh', 'Mức độ tái sử dụng biến'),
'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'),
'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'),
'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'),
'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'),
'class_count': ('Số lượng lớp (Class)', 'OOP', 'Đo lường mức độ lập trình hướng đối tượng'),
'struct_count': ('Số lượng Struct', 'OOP', 'Đo lường cấu trúc dữ liệu tùy chỉnh'),
'virtual_override_ratio': ('Tỷ lệ virtual / override', 'OOP', 'Tính đa hình nâng cao trong C++'),
'getter_setter_ratio': ('Tỷ lệ Getter/Setter', 'OOP', 'Mẫu đóng gói dữ liệu thường thấy ở AI sinh mã'),
'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ử'),
'maintainability_index': ('Chỉ số bảo trì (MI)', 'Độ phức tạp', 'Khả năng đọc hiểu và bảo trì code'),
'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ự'),
}
# ==============================================================================
# INFERENCE LOGIC (PURE FORWARD PASS — NO LIG)
# ==============================================================================
def classify_oop_or_normal(code: str) -> str:
oop_keywords = ["class ", "struct ", "public:", "private:", "protected:", "virtual ", "override", "std::unique_ptr"]
hits = sum(1 for kw in oop_keywords if kw in code)
return "OOP" if hits >= 2 else "NORMAL"
def interpret_feature_signals(extracted: dict, feat_list: list) -> pd.DataFrame:
"""Build feature-level XAI interpretation table."""
rows = []
for k in feat_list:
val = extracted.get(k, 0.0)
meta = FEATURE_METADATA.get(k, (k, "Chung", "Đặc trưng phân loại"))
name_vn, group, desc = meta
# Heuristic directional bias based on empirical research
signal = "Trung lập"
if k == 'single_char_var_ratio' and val > 0.15:
signal = "👤 Người viết (Biến ngắn gọn)"
elif k == 'has_bits_stdc' and val > 0.5:
signal = "👤 Người viết (Thư viện gộp)"
elif k == 'has_fast_io' and val > 0.5:
signal = "👤 Người viết (Fast I/O)"
elif k == 'using_std_ratio' and val > 0.5:
signal = "👤 Người viết (namespace mở)"
elif k == 'comment_ratio' and val > 0.12:
signal = "🤖 AI Sinh ra (Comment chi tiết)"
elif k == 'avg_identifier_length' and val > 8.0:
signal = "🤖 AI Sinh ra (Tên biến dài)"
elif k == 'brace_style_consistency' and val >= 0.98:
signal = "🤖 AI Sinh ra (Format chuẩn mực)"
elif k == 'std_prefix_ratio' and val > 0.6:
signal = "🤖 AI Sinh ra (std:: tường minh)"
elif k == 'getter_setter_ratio' and val > 0:
signal = "🤖 AI Sinh ra (Getter/Setter)"
rows.append({
"Đặc trưng": name_vn,
"Nhóm": group,
"Giá trị": f"{val:.4f}" if isinstance(val, float) else str(val),
"Tín hiệu định hướng": signal,
"Giải thích học thuật": desc
})
return pd.DataFrame(rows)
@gpu_decorator
def predict_code(code_text: str, threshold: float = 0.5):
if not code_text or not code_text.strip():
return {"Lỗi": "Vui lòng nhập code C++"}, {}, pd.DataFrame()
t0 = time.perf_counter()
clean_code = strip_metadata_headers(code_text)
# 1. Routing
code_type = classify_oop_or_normal(clean_code)
active_model = model_oop if code_type == "OOP" and model_oop is not None else model_normal
model_label = f"C++ {code_type} Model"
# 2. Machine Learning (Stylometric 44 features)
lgbm_score = 0.5
extracted_features = {}
features_df = pd.DataFrame()
if extractor is not None:
extracted_features = extractor.extract(clean_code)
if lgbm_model is not None and scaler is not None and feature_names is not None:
df = pd.DataFrame([extracted_features]).fillna(0)
try:
X_all = df[scaler.feature_names_in_]
X_scaled = scaler.transform(X_all)
feat_list = list(feature_names)
all_feat = list(scaler.feature_names_in_)
indices = [all_feat.index(f) for f in feat_list]
X_final = X_scaled[:, indices]
lgbm_score = float(lgbm_model.predict_proba(X_final)[0][1])
features_df = interpret_feature_signals(extracted_features, feat_list)
except Exception:
lgbm_score = 0.5
features_df = pd.DataFrame([{"Đặc trưng": k, "Giá trị": str(v)} for k, v in extracted_features.items()])
# 3. Deep Learning (GraphCodeBERT Pure Forward Pass)
dl_score = 0.5
if active_model and tokenizer:
cur_device = next(active_model.parameters()).device
inputs = tokenizer(
clean_code,
return_tensors="pt",
truncation=True,
max_length=512,
return_attention_mask=True
)
inputs = {k: v.to(cur_device) for k, v in inputs.items()}
with torch.no_grad():
logits = active_model(**inputs).logits
probs = F.softmax(logits, dim=-1)
dl_score = float(probs[0][1].item())
# 4. Controlled Adaptive Fusion
final_score = 0.48 * dl_score + 0.52 * lgbm_score
conflict = False
if abs(dl_score - lgbm_score) >= 0.40:
conflict = True
if 0.40 <= dl_score <= 0.70:
final_score = 0.70 * dl_score + 0.30 * lgbm_score
pred_label = "AI GENERATED" if final_score >= threshold else "HUMAN WRITTEN"
latency_ms = (time.perf_counter() - t0) * 1000
label_output = {
"AI GENERATED": float(final_score),
"HUMAN WRITTEN": float(1.0 - final_score),
}
metrics_output = {
"Kết luận": pred_label,
"Xác suất AI": f"{final_score * 100:.1f}%",
"Mô hình định tuyến": model_label,
"Điểm Deep Learning (GraphCodeBERT)": f"{dl_score:.4f}",
"Điểm Machine Learning (LightGBM)": f"{lgbm_score:.4f}",
"Hợp nhất có kiểm soát (Fusion)": "Đã kích hoạt" if conflict else "Chuẩn",
"Thời gian xử lý": f"{latency_ms:.0f} ms",
"Phương pháp giải thích": "Feature-level Explainability (Stylometric XAI)"
}
return label_output, metrics_output, features_df
# ==============================================================================
# GRADIO INTERFACE
# ==============================================================================
example_human = """#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
if (!(cin >> n)) return 0;
vector<int> a(n);
for (int i = 0; i < n; i++) cin >> a[i];
sort(a.begin(), a.end());
for (int x : a) cout << x << " ";
cout << "\\n";
return 0;
}"""
example_ai = """#include <iostream>
#include <vector>
#include <numeric>
#include <stdexcept>
class StatisticsAnalyzer {
private:
std::vector<double> dataset;
public:
explicit StatisticsAnalyzer(const std::vector<double>& data) : dataset(data) {
if (data.empty()) {
throw std::invalid_argument("Dataset cannot be empty.");
}
}
double calculateMean() const {
double sum = std::accumulate(dataset.begin(), dataset.end(), 0.0);
return sum / dataset.size();
}
};
int main() {
try {
std::vector<double> numbers = {10.5, 20.3, 30.2, 40.8};
StatisticsAnalyzer analyzer(numbers);
std::cout << "Mean: " << analyzer.calculateMean() << std::endl;
} catch (const std::exception& ex) {
std::cerr << "Error: " << ex.what() << std::endl;
}
return 0;
}"""
custom_css = """
footer {visibility: hidden;}
.gradio-container {max-width: 1200px !important; margin: auto;}
"""
with gr.Blocks(title="C++ AI Code Detector Pro", css=custom_css) as demo:
gr.Markdown("# 🕵️‍♂️ C++ AI Code Detector Pro")
gr.Markdown(
"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**: "
"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**), "
"và cơ chế giải thích ở cấp độ thuộc tính (**Feature-level XAI**)."
)
with gr.Row():
with gr.Column(scale=5):
code_input = gr.Code(label="Mã nguồn C++ cần phân tích", language="cpp", lines=16, value=example_human)
threshold_slider = gr.Slider(0.1, 0.9, value=0.5, step=0.05, label="Ngưỡng phân loại AI (Threshold)")
analyze_btn = gr.Button("🚀 PHÂN TÍCH NGAY", variant="primary")
gr.Examples(
examples=[
[example_human, 0.5],
[example_ai, 0.5],
],
inputs=[code_input, threshold_slider],
label="📁 Bấm chọn code mẫu để thử nhanh:"
)
with gr.Column(scale=5):
output_label = gr.Label(label="Kết luận phân loại", num_top_classes=2)
output_metrics = gr.JSON(label="Chỉ số phân tích chi tiết (Metrics)")
gr.Markdown("### 📊 Giải thích chi tiết theo thuộc tính phong cách (Feature-level XAI & Stylometric Fingerprints)")
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:")
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)
analyze_btn.click(
fn=predict_code,
inputs=[code_input, threshold_slider],
outputs=[output_label, output_metrics, output_features]
)
if __name__ == "__main__":
port = int(os.environ.get("PORT", 7860))
demo.launch(server_name="0.0.0.0", server_port=port, share=False)