File size: 2,158 Bytes
38bc0dc | 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 | import sys
try:
sys.stdout.reconfigure(encoding='utf-8')
sys.stderr.reconfigure(encoding='utf-8')
except Exception:
pass
from ast_analyzer import extract_features
from feature_pipeline import prepare_inference_vector
from model_trainer import load_model
from explanation_engine import explain
try:
_MODEL = load_model()
except FileNotFoundError:
_MODEL = None
def _get_risk_level(score):
if score <= 30:
return "Low"
elif score <= 60:
return "Medium"
else:
return "High"
def evaluate(source):
if _MODEL is None:
return {
"error": True,
"message": "Model not found. Run train_model() first."
}
raw_features = extract_features(source)
if raw_features.get("error"):
return raw_features
X_scaled = prepare_inference_vector(raw_features)
probability = float(_MODEL.predict_proba(X_scaled)[0][1])
risk_score = int(probability * 100)
risk_level = _get_risk_level(risk_score)
explanations = explain(_MODEL, raw_features, top_n=3)
result = {
"risk_score": risk_score,
"risk_level": risk_level,
"confidence": round(probability, 2),
"top_risk_factors": explanations
}
return result
if __name__ == "__main__":
import json
print("=" * 60)
print(" SCORING API DEMO")
print("=" * 60)
clean_code = "def greet(name):\n return f'Hello {name}!'"
print("\n🟢 Testing Clean Code...")
clean_result = evaluate(clean_code)
print(json.dumps(clean_result, indent=2))
risky_code = "global_counter=0\ndef bloated_pipeline(data):\n global global_counter\n try:\n for x in data:\n if x>0:\n for i in range(x):\n try:\n if i%2==0: global_counter+=1\n except: pass\n except Exception: return -1\n return global_counter"
print("\n🔴 Testing Risky Code...")
risky_result = evaluate(risky_code)
print(json.dumps(risky_result, indent=2))
print("=" * 60)
|