File size: 16,970 Bytes
374f3ad
 
 
 
 
 
 
 
 
 
 
 
e65f6d3
374f3ad
 
 
 
 
 
 
 
 
 
 
e65f6d3
374f3ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e65f6d3
374f3ad
 
 
 
 
 
e65f6d3
374f3ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e65f6d3
54398ca
 
 
 
 
 
 
 
 
 
374f3ad
 
 
54398ca
374f3ad
54398ca
374f3ad
 
54398ca
 
 
 
 
 
374f3ad
54398ca
 
 
 
 
 
 
 
 
374f3ad
54398ca
 
374f3ad
e65f6d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
374f3ad
e65f6d3
374f3ad
 
 
 
 
 
e65f6d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
374f3ad
 
 
 
e65f6d3
374f3ad
 
 
 
 
 
 
 
 
e65f6d3
374f3ad
 
 
e65f6d3
374f3ad
e65f6d3
 
374f3ad
 
 
 
 
 
 
 
 
e65f6d3
374f3ad
 
e65f6d3
374f3ad
e65f6d3
374f3ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e65f6d3
374f3ad
 
e65f6d3
374f3ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e65f6d3
 
 
 
 
 
374f3ad
e65f6d3
 
 
 
 
374f3ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e65f6d3
 
 
374f3ad
 
 
 
e65f6d3
374f3ad
 
 
e65f6d3
 
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
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)