Upload 6 files
Browse files- FraudDetectionAgent.py +89 -0
- flagged_transactions.csv +2 -0
- index.html +195 -0
- main.py +120 -0
- requirements.txt +9 -0
- transactions.csv +9 -0
FraudDetectionAgent.py
ADDED
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pandas as pd
|
2 |
+
from sklearn.ensemble import IsolationForest
|
3 |
+
from smolagents import CodeAgent
|
4 |
+
|
5 |
+
|
6 |
+
class FraudDetectionAgent:
|
7 |
+
pass
|
8 |
+
|
9 |
+
|
10 |
+
CodeAgent = FraudDetectionAgent()
|
11 |
+
|
12 |
+
|
13 |
+
class TransactionModel:
|
14 |
+
def __init__(self, transaction_id: int, amount: float, timestamp: str, location_lat: float, location_long: float):
|
15 |
+
self.transaction_id = transaction_id
|
16 |
+
self.amount = amount
|
17 |
+
self.timestamp = timestamp
|
18 |
+
self.location_lat = location_lat
|
19 |
+
self.location_long = location_long
|
20 |
+
|
21 |
+
def to_dict(self):
|
22 |
+
return {
|
23 |
+
"transaction_id": self.transaction_id,
|
24 |
+
"amount": self.amount,
|
25 |
+
"timestamp": self.timestamp,
|
26 |
+
"location_lat": self.location_lat,
|
27 |
+
"location_long": self.location_long
|
28 |
+
}
|
29 |
+
|
30 |
+
|
31 |
+
class FraudResult:
|
32 |
+
def __init__(self, transaction_id: int, amount: float, timestamp: str, anomaly_score: int):
|
33 |
+
self.transaction_id = transaction_id
|
34 |
+
self.amount = amount
|
35 |
+
self.timestamp = timestamp
|
36 |
+
self.anomaly_score = anomaly_score
|
37 |
+
|
38 |
+
def to_dict(self):
|
39 |
+
return {
|
40 |
+
"transaction_id": self.transaction_id,
|
41 |
+
"amount": self.amount,
|
42 |
+
"timestamp": self.timestamp,
|
43 |
+
"anomaly_score": self.anomaly_score
|
44 |
+
}
|
45 |
+
|
46 |
+
|
47 |
+
class FraudDetectionAgent(FraudDetectionAgent):
|
48 |
+
def __init__(self, data_path: str):
|
49 |
+
super().__init__()
|
50 |
+
self.data_path = data_path
|
51 |
+
self.df = None
|
52 |
+
self.X = None
|
53 |
+
self.model = IsolationForest(contamination=0.01, random_state=42)
|
54 |
+
|
55 |
+
def load_data(self):
|
56 |
+
self.df = pd.read_csv(self.data_path)
|
57 |
+
print(f"Loaded {len(self.df)} transactions.")
|
58 |
+
|
59 |
+
def preprocess(self):
|
60 |
+
self.df['transaction_hour'] = pd.to_datetime(self.df['timestamp']).dt.hour
|
61 |
+
features = ['amount', 'transaction_hour', 'location_lat', 'location_long']
|
62 |
+
self.df = self.df.dropna(subset=features)
|
63 |
+
self.X = self.df[features]
|
64 |
+
|
65 |
+
def detect_fraud(self):
|
66 |
+
self.df['anomaly_score'] = self.model.fit_predict(self.X)
|
67 |
+
frauds = self.df[self.df['anomaly_score'] == -1]
|
68 |
+
print(f"Detected {len(frauds)} potential fraudulent transactions.")
|
69 |
+
return [
|
70 |
+
FraudResult(
|
71 |
+
row['transaction_id'],
|
72 |
+
row['amount'],
|
73 |
+
row['timestamp'],
|
74 |
+
row['anomaly_score']
|
75 |
+
).to_dict()
|
76 |
+
for _, row in frauds.iterrows()
|
77 |
+
]
|
78 |
+
|
79 |
+
def run(self):
|
80 |
+
self.load_data()
|
81 |
+
self.preprocess()
|
82 |
+
return self.detect_fraud()
|
83 |
+
|
84 |
+
|
85 |
+
if __name__ == "__main__":
|
86 |
+
agent = FraudDetectionAgent(data_path="transactions.csv")
|
87 |
+
agent.run()
|
88 |
+
print("\nFraud detection completed.")
|
89 |
+
|
flagged_transactions.csv
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
transaction_id,amount,timestamp,anomaly_score
|
2 |
+
7,8900.0,2023-05-01 01:45:00,-1
|
index.html
ADDED
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<!DOCTYPE html>
|
2 |
+
<html lang="en">
|
3 |
+
<head>
|
4 |
+
<meta charset="UTF-8">
|
5 |
+
<title>Fraud Detection Chatbot</title>
|
6 |
+
<style>
|
7 |
+
body {
|
8 |
+
font-family: 'Segoe UI', sans-serif;
|
9 |
+
margin: 0;
|
10 |
+
padding: 0;
|
11 |
+
background: #f1f2f7;
|
12 |
+
display: flex;
|
13 |
+
flex-direction: column;
|
14 |
+
align-items: center;
|
15 |
+
height: 100vh;
|
16 |
+
}
|
17 |
+
|
18 |
+
h2 {
|
19 |
+
margin: 20px;
|
20 |
+
color: #333;
|
21 |
+
}
|
22 |
+
|
23 |
+
#chat-box {
|
24 |
+
width: 90%;
|
25 |
+
max-width: 600px;
|
26 |
+
background: white;
|
27 |
+
border-radius: 10px;
|
28 |
+
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
29 |
+
display: flex;
|
30 |
+
flex-direction: column;
|
31 |
+
overflow: hidden;
|
32 |
+
flex-grow: 1;
|
33 |
+
}
|
34 |
+
|
35 |
+
#messages {
|
36 |
+
flex: 1;
|
37 |
+
overflow-y: auto;
|
38 |
+
padding: 20px;
|
39 |
+
}
|
40 |
+
|
41 |
+
.msg {
|
42 |
+
margin-bottom: 10px;
|
43 |
+
padding: 10px 14px;
|
44 |
+
border-radius: 20px;
|
45 |
+
max-width: 80%;
|
46 |
+
word-wrap: break-word;
|
47 |
+
line-height: 1.4;
|
48 |
+
}
|
49 |
+
|
50 |
+
.bot {
|
51 |
+
background-color: #e9ecef;
|
52 |
+
align-self: flex-start;
|
53 |
+
color: #333;
|
54 |
+
}
|
55 |
+
|
56 |
+
.user {
|
57 |
+
background-color: #0d6efd;
|
58 |
+
color: white;
|
59 |
+
align-self: flex-end;
|
60 |
+
}
|
61 |
+
|
62 |
+
#input-bar {
|
63 |
+
display: flex;
|
64 |
+
padding: 10px;
|
65 |
+
border-top: 1px solid #ddd;
|
66 |
+
background: #f9f9f9;
|
67 |
+
}
|
68 |
+
|
69 |
+
#input {
|
70 |
+
flex: 1;
|
71 |
+
padding: 10px;
|
72 |
+
border: 1px solid #ccc;
|
73 |
+
border-radius: 20px;
|
74 |
+
outline: none;
|
75 |
+
margin-right: 10px;
|
76 |
+
}
|
77 |
+
|
78 |
+
#send-btn, #upload-btn {
|
79 |
+
background-color: #0d6efd;
|
80 |
+
color: white;
|
81 |
+
border: none;
|
82 |
+
padding: 10px 14px;
|
83 |
+
border-radius: 20px;
|
84 |
+
cursor: pointer;
|
85 |
+
}
|
86 |
+
|
87 |
+
#fileInput {
|
88 |
+
margin: 10px 0;
|
89 |
+
}
|
90 |
+
|
91 |
+
@media (max-width: 600px) {
|
92 |
+
#chat-box {
|
93 |
+
width: 95%;
|
94 |
+
}
|
95 |
+
}
|
96 |
+
</style>
|
97 |
+
</head>
|
98 |
+
<body>
|
99 |
+
<h2>💬 Fraud Detection Chatbot</h2>
|
100 |
+
|
101 |
+
<div id="chat-box">
|
102 |
+
<div id="messages"></div>
|
103 |
+
|
104 |
+
<div style="padding: 10px; text-align: center;">
|
105 |
+
<input type="file" id="fileInput">
|
106 |
+
<button id="upload-btn" onclick="uploadFile()">Upload CSV</button>
|
107 |
+
</div>
|
108 |
+
|
109 |
+
<div id="input-bar">
|
110 |
+
<input id="input" type="text" placeholder="Type your message...">
|
111 |
+
<button id="send-btn" onclick="sendMessage()">Send</button>
|
112 |
+
</div>
|
113 |
+
</div>
|
114 |
+
|
115 |
+
<script>
|
116 |
+
const messages = document.getElementById("messages");
|
117 |
+
|
118 |
+
function addMessage(text, sender) {
|
119 |
+
const msg = document.createElement("div");
|
120 |
+
msg.className = `msg ${sender}`;
|
121 |
+
msg.textContent = text;
|
122 |
+
messages.appendChild(msg);
|
123 |
+
messages.scrollTop = messages.scrollHeight;
|
124 |
+
}
|
125 |
+
|
126 |
+
async function sendMessage() {
|
127 |
+
const input = document.getElementById("input");
|
128 |
+
const text = input.value.trim();
|
129 |
+
if (!text) return;
|
130 |
+
|
131 |
+
addMessage(text, "user");
|
132 |
+
input.value = "";
|
133 |
+
|
134 |
+
const res = await fetch("http://127.0.0.1:8000/chat/", {
|
135 |
+
method: "POST",
|
136 |
+
headers: { "Content-Type": "application/json" },
|
137 |
+
body: JSON.stringify({ message: text })
|
138 |
+
});
|
139 |
+
|
140 |
+
const data = await res.json();
|
141 |
+
addMessage(data.response, "bot");
|
142 |
+
}
|
143 |
+
|
144 |
+
async function uploadFile() {
|
145 |
+
const file = document.getElementById("fileInput").files[0];
|
146 |
+
if (!file) {
|
147 |
+
alert("Please select a CSV file first.");
|
148 |
+
return;
|
149 |
+
}
|
150 |
+
|
151 |
+
const formData = new FormData();
|
152 |
+
formData.append("file", file);
|
153 |
+
|
154 |
+
addMessage("🔄 Analyzing your file...", "bot");
|
155 |
+
|
156 |
+
const res = await fetch("http://127.0.0.1:8000/upload/", {
|
157 |
+
method: "POST",
|
158 |
+
body: formData
|
159 |
+
});
|
160 |
+
|
161 |
+
const data = await res.json();
|
162 |
+
addMessage(data.response, "bot");
|
163 |
+
}
|
164 |
+
async function uploadFile() {
|
165 |
+
const file = document.getElementById("fileInput").files[0];
|
166 |
+
if (!file) {
|
167 |
+
alert("Please select a CSV file first.");
|
168 |
+
return;
|
169 |
+
}
|
170 |
+
|
171 |
+
const formData = new FormData();
|
172 |
+
formData.append("file", file);
|
173 |
+
|
174 |
+
addMessage("🔄 Analyzing your file...", "bot");
|
175 |
+
|
176 |
+
try {
|
177 |
+
const res = await fetch("http://127.0.0.1:8000/upload/", {
|
178 |
+
method: "POST",
|
179 |
+
body: formData
|
180 |
+
});
|
181 |
+
|
182 |
+
if (!res.ok) {
|
183 |
+
throw new Error(`Server error: ${res.status}`);
|
184 |
+
}
|
185 |
+
|
186 |
+
const data = await res.json();
|
187 |
+
addMessage(data.response || "No response from server.", "bot");
|
188 |
+
} catch (err) {
|
189 |
+
addMessage(`❌ Error: ${err.message}`, "bot");
|
190 |
+
}
|
191 |
+
}
|
192 |
+
</script>
|
193 |
+
</body>
|
194 |
+
</html>
|
195 |
+
|
main.py
ADDED
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
|
3 |
+
from fastapi import FastAPI, UploadFile, File
|
4 |
+
|
5 |
+
from FraudDetectionAgent import CodeAgent
|
6 |
+
|
7 |
+
app = FastAPI()
|
8 |
+
|
9 |
+
|
10 |
+
@app.post("/detect-fraud/")
|
11 |
+
async def detect_fraud(file: UploadFile = File(...)):
|
12 |
+
contents = await file.read()
|
13 |
+
temp_path = "temp_transactions.csv"
|
14 |
+
|
15 |
+
with open(temp_path, "wb") as f:
|
16 |
+
f.write(contents)
|
17 |
+
|
18 |
+
agent = CodeAgent(data_path=temp_path)
|
19 |
+
frauds = agent.run()
|
20 |
+
|
21 |
+
os.remove(temp_path)
|
22 |
+
return {"flagged_transactions": frauds}
|
23 |
+
|
24 |
+
|
25 |
+
from fastapi import FastAPI, UploadFile, File
|
26 |
+
from pydantic import BaseModel
|
27 |
+
from FraudDetectionAgent import FraudDetectionAgent
|
28 |
+
import pandas as pd
|
29 |
+
import os
|
30 |
+
|
31 |
+
app = FastAPI()
|
32 |
+
|
33 |
+
|
34 |
+
# Basic chat message schema
|
35 |
+
class ChatMessage(BaseModel):
|
36 |
+
message: str
|
37 |
+
|
38 |
+
|
39 |
+
@app.post("/chat/")
|
40 |
+
def chat_with_agent(msg: ChatMessage):
|
41 |
+
user_input = msg.message.lower()
|
42 |
+
|
43 |
+
if "fraud" in user_input:
|
44 |
+
return {"response": "You can upload a CSV file at /detect-fraud/ to check for fraudulent transactions."}
|
45 |
+
elif "hello" in user_input or "hi" in user_input:
|
46 |
+
return {"response": "Hello! I can help you detect transaction frauds. Ask me how."}
|
47 |
+
else:
|
48 |
+
return {"response": "I'm still learning! Try asking about fraud detection or uploading a CSV."}
|
49 |
+
|
50 |
+
|
51 |
+
@app.post("/detect-fraud/")
|
52 |
+
async def detect_fraud(file: UploadFile = File(...)):
|
53 |
+
contents = await file.read()
|
54 |
+
temp_path = "temp_transactions.csv"
|
55 |
+
with open(temp_path, "wb") as f:
|
56 |
+
f.write(contents)
|
57 |
+
|
58 |
+
agent = FraudDetectionAgent(data_path=temp_path)
|
59 |
+
frauds = agent.run()
|
60 |
+
os.remove(temp_path)
|
61 |
+
return {"flagged_transactions": [f.to_dict() for f in frauds]}
|
62 |
+
|
63 |
+
|
64 |
+
from fastapi import FastAPI, UploadFile, File
|
65 |
+
from fastapi.middleware.cors import CORSMiddleware
|
66 |
+
from pydantic import BaseModel
|
67 |
+
from FraudDetectionAgent import CodeAgent
|
68 |
+
import pandas as pd
|
69 |
+
import os
|
70 |
+
|
71 |
+
app = FastAPI()
|
72 |
+
|
73 |
+
# Enable CORS for browser frontend
|
74 |
+
app.add_middleware(
|
75 |
+
CORSMiddleware,
|
76 |
+
allow_origins=["*"],
|
77 |
+
allow_credentials=True,
|
78 |
+
allow_methods=["*"],
|
79 |
+
allow_headers=["*"],
|
80 |
+
)
|
81 |
+
|
82 |
+
|
83 |
+
class ChatMessage(BaseModel):
|
84 |
+
message: str
|
85 |
+
|
86 |
+
|
87 |
+
@app.post("/chat/")
|
88 |
+
def chat_with_agent(msg: ChatMessage):
|
89 |
+
text = msg.message.lower()
|
90 |
+
if "fraud" in text:
|
91 |
+
return {"response": "You can upload a CSV of transactions below and I'll tell you which ones look suspicious."}
|
92 |
+
elif "hello" in text:
|
93 |
+
return {"response": "Hi there! I'm your fraud detection assistant. Upload a CSV to get started."}
|
94 |
+
else:
|
95 |
+
return {
|
96 |
+
"response": "I'm here to help with transaction fraud detection. Try asking about fraud or upload your data."}
|
97 |
+
|
98 |
+
|
99 |
+
@app.post("/upload/")
|
100 |
+
async def upload_file(file: UploadFile = File(...)):
|
101 |
+
try:
|
102 |
+
temp_file = "temp_data.csv"
|
103 |
+
with open(temp_file, "wb") as f:
|
104 |
+
f.write(await file.read())
|
105 |
+
|
106 |
+
agent = FraudDetectionAgent(data_path=temp_file)
|
107 |
+
frauds = agent.run()
|
108 |
+
os.remove(temp_file)
|
109 |
+
|
110 |
+
if not frauds:
|
111 |
+
return {"response": "✅ No fraud detected!"}
|
112 |
+
|
113 |
+
summary = "\n".join([
|
114 |
+
f"- ID: {f.get('transaction_id')}, Amount: ${f.get('amount')}"
|
115 |
+
for f in frauds[:5]
|
116 |
+
])
|
117 |
+
return {"response": f"⚠️ Detected {len(frauds)} suspicious transactions:\n{summary}"}
|
118 |
+
|
119 |
+
except Exception as e:
|
120 |
+
return {"response": f"❌ Error processing file: {str(e)}"}
|
requirements.txt
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
pip~=25.1.1
|
2 |
+
pillow~=11.2.1
|
3 |
+
filelock~=3.18.0
|
4 |
+
pandas~=2.2.3
|
5 |
+
fastapi~=0.115.12
|
6 |
+
pydantic~=2.11.4
|
7 |
+
scikit-learn~=1.6.1
|
8 |
+
smolagents~=1.16.0
|
9 |
+
uvicorn
|
transactions.csv
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
transaction_id,amount,timestamp,location_lat,location_long
|
2 |
+
1,120.50,2023-05-01 08:45:00,37.7749,-122.4194
|
3 |
+
2,9999.99,2023-05-01 02:13:00,40.7128,-74.0060
|
4 |
+
3,10.00,2023-05-01 14:32:00,37.7749,-122.4194
|
5 |
+
4,5000.00,2023-05-01 03:00:00,35.6895,139.6917
|
6 |
+
5,75.20,2023-05-01 17:15:00,34.0522,-118.2437
|
7 |
+
6,250.00,2023-05-01 13:22:00,37.7749,-122.4194
|
8 |
+
7,8900.00,2023-05-01 01:45:00,55.7558,37.6173
|
9 |
+
8,8.99,2023-05-01 11:15:00,37.7749,-122.4194
|