-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrun_local.py
More file actions
173 lines (146 loc) · 5.2 KB
/
Copy pathrun_local.py
File metadata and controls
173 lines (146 loc) · 5.2 KB
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
#!/usr/bin/env python3
"""
Run UPI Fraud Detection System locally without Docker
This is a simplified version for development and testing
"""
import subprocess
import time
import requests
import sys
import os
from pathlib import Path
def install_requirements():
"""Install Python requirements"""
print("📦 Installing Python requirements...")
try:
subprocess.run([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"], check=True)
print("✅ Requirements installed successfully")
return True
except subprocess.CalledProcessError as e:
print(f"❌ Failed to install requirements: {e}")
return False
def start_api_server():
"""Start the FastAPI server locally"""
print("🚀 Starting FastAPI server...")
# Change to serving directory
os.chdir("serving")
try:
# Start the server in background
process = subprocess.Popen([
sys.executable, "-m", "uvicorn", "main:app",
"--host", "0.0.0.0", "--port", "8000", "--reload"
])
print("✅ FastAPI server started")
print(" API URL: http://localhost:8000")
print(" API Docs: http://localhost:8000/docs")
return process
except Exception as e:
print(f"❌ Failed to start API server: {e}")
return None
def wait_for_api():
"""Wait for API to be ready"""
print("⏳ Waiting for API to be ready...")
for attempt in range(30):
try:
response = requests.get("http://localhost:8000/health", timeout=5)
if response.status_code == 200:
print("✅ API is ready!")
return True
except:
pass
print(f" Attempt {attempt + 1}/30...")
time.sleep(2)
print("❌ API failed to start within 60 seconds")
return False
def test_api():
"""Test the API endpoints"""
print("\n🧪 Testing API endpoints...")
# Test health check
try:
response = requests.get("http://localhost:8000/health")
if response.status_code == 200:
print("✅ Health check passed")
else:
print("❌ Health check failed")
return False
except Exception as e:
print(f"❌ Health check error: {e}")
return False
# Test prediction
try:
test_data = {
"transaction_id": "TEST_001",
"upi_id": "test@paytm",
"amount": 5000.0,
"merchant_id": "MERCHANT_001",
"merchant_category": "ecommerce",
"device_id": "device_123",
"ip_address": "192.168.1.100",
"location": {"lat": 28.6139, "lon": 77.2090},
"timestamp": "2024-01-15T14:30:25Z",
"payment_method": "UPI"
}
response = requests.post("http://localhost:8000/predict", json=test_data)
if response.status_code == 200:
data = response.json()
print(f"✅ Prediction test passed")
print(f" Risk Score: {data['risk_score']:.3f}")
print(f" Decision: {data['decision']}")
print(f" Processing Time: {data['processing_time_ms']:.2f}ms")
else:
print(f"❌ Prediction test failed: {response.status_code}")
return False
except Exception as e:
print(f"❌ Prediction test error: {e}")
return False
return True
def show_status():
"""Show system status"""
print("\n" + "=" * 60)
print("🎉 UPI Fraud Detection System is running locally!")
print("=" * 60)
print("\n📊 Access URLs:")
print(" • API: http://localhost:8000")
print(" • API Documentation: http://localhost:8000/docs")
print(" • Health Check: http://localhost:8000/health")
print(" • Metrics: http://localhost:8000/metrics")
print("\n🔧 Management Commands:")
print(" • Test API: python test_system.py")
print(" • Stop server: Ctrl+C")
print(" • View logs: Check terminal output")
print("\n📝 Next Steps:")
print(" 1. Open http://localhost:8000/docs to test the API")
print(" 2. Run python test_system.py to run comprehensive tests")
print(" 3. For full system with dashboard, install Docker")
def main():
"""Main function"""
print("🚀 UPI Fraud Detection System - Local Mode")
print("=" * 50)
# Install requirements
if not install_requirements():
sys.exit(1)
# Start API server
api_process = start_api_server()
if not api_process:
sys.exit(1)
# Wait for API to be ready
if not wait_for_api():
print("❌ API failed to start. Check the logs above.")
api_process.terminate()
sys.exit(1)
# Test API
if not test_api():
print("❌ API tests failed. Check the logs above.")
api_process.terminate()
sys.exit(1)
# Show status
show_status()
try:
print("\n🔄 Server is running. Press Ctrl+C to stop.")
api_process.wait()
except KeyboardInterrupt:
print("\n🛑 Stopping server...")
api_process.terminate()
print("✅ Server stopped")
if __name__ == "__main__":
main()