File size: 1,477 Bytes
6786ca9
 
 
 
36ef700
 
b5e6606
 
 
 
 
6786ca9
36ef700
 
6786ca9
36ef700
6786ca9
e5ec122
6786ca9
 
b5e6606
36ef700
 
 
 
 
 
 
 
 
e5ec122
 
 
 
6786ca9
36ef700
 
 
 
 
 
b5e6606
36ef700
e5ec122
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
import numpy as np
from sklearn.ensemble import IsolationForest
from utils.preprocessing import extract_features

# Dummy training data (should be replaced with real labeled data)
train_data = np.array([
    [5, 0, 30, 0.1],
    [10, 1, 50, 0.2],
    [2, 2, 10, 0.3],
    [8, 0, 45, 0.05],
    [3, 1, 12, 0.4]
])
model = IsolationForest(contamination=0.2, random_state=42)
model.fit(train_data)

def detect_anomaly_plain_text(agent_data):
    features = extract_features(agent_data)
    prediction = model.predict([features])[0]  # -1 = anomaly
    flagged = prediction == -1

    reasons = []
    if flagged:
        if agent_data["missed_visits"] >= 5:
            reasons.append("a spike in missed visits")
        if agent_data["weekly_calls"] <= 3:
            reasons.append("low call frequency")
        if agent_data["lead_drop_rate"] > 0.6:
            reasons.append("a high lead drop rate")
        if agent_data["travel_distance"] < 10:
            reasons.append("unusual travel distance")
        
        # 🔧 New fallback reason if no rule matches but model flags it
        if not reasons:
            reasons.append("an unusual behavior pattern detected by the model")

    reason_text = (
        f"Agent {agent_data['agent_id']} has been flagged for anomalous behavior due to "
        + ", ".join(reasons) + "."
        if flagged else
        f"Agent {agent_data['agent_id']} shows normal behavior based on current data."
    )

    return reason_text