Structural and Behavioral Hybrid Framework for AI-Generated Code Detection
CodeGuardX detects whether Python source code was written by a human or generated by AI, using a three-pronged approach: AST structural analysis, sandboxed behavioral execution, and coding style metrics — fused into a single ML classification.
CodeGuardX/
├── backend/ # FastAPI backend
│ ├── main.py # API entry point
│ ├── requirements.txt
│ └── modules/
│ ├── input_handler.py # Module 1: Validation & normalization
│ ├── ast_analyzer.py # Module 2: AST structural features
│ ├── behavioral_analyzer.py # Module 3: Sandboxed execution
│ ├── style_analyzer.py # Module 4: Style pattern features
│ ├── feature_fusion.py # Module 5: Feature vector fusion
│ └── classifier.py # Module 6: ML model inference
├── ml/ # ML training pipeline
│ ├── dataset_generator.py # Synthetic dataset creation
│ ├── train_model.py # Model training & evaluation
│ └── dataset.csv # (generated)
├── frontend/ # React + Vite UI
│ └── src/
│ ├── App.jsx
│ ├── api.js
│ └── components/
│ ├── CodeEditor.jsx
│ └── ResultPanel.jsx
└── README.md
- Python 3.9+
- Node.js 18+
cd backend
pip install -r requirements.txtcd ml
pip install -r requirements_ml.txt
python dataset_generator.py # Creates dataset.csv
python train_model.py # Trains model -> backend/model/model.pklTraining takes 1-3 minutes due to sandboxed code execution for behavioral features. The server will work with a heuristic fallback even before training.
cd backend
python3.11.exe -m uvicorn main:app --reload --host 0.0.0.0 --port 8000API docs: http://localhost:8000/docs
cd frontend
npm install
npm run devOpen: http://localhost:5173
Request:
{ "code": "def add(a, b):\n return a + b" }Response:
{
"prediction": "Human-written",
"confidence": 0.87,
"model_used": "ml_model",
"feature_summary": { "tree_depth": 3, "num_functions": 1, ... },
"analysis_time_ms": 423.5
}| Category | Count | Key Features |
|---|---|---|
| Structural | 17 | tree_depth, num_nodes, num_functions, nesting_level, node_type_diversity |
| Behavioral | 6 | raises_exception, execution_time_ms, output_lines, timed_out |
| Style | 10 | comment_density, snake_case_ratio, docstring_count, avg_identifier_length |
Behavioral analysis uses an isolated subprocess with:
- 5-second hard timeout
- Restricted builtins (no open, exec, eval, import)
- stdin closed; stdout/stderr captured only
| Layer | Technology |
|---|---|
| Frontend | React 18, Vite 5, Vanilla CSS |
| Backend | FastAPI, Uvicorn, Pydantic |
| ML | scikit-learn, XGBoost, joblib |
| Analysis | Python ast module, subprocess sandbox |