GitHub Action commited on
Commit
b88fdd0
·
1 Parent(s): a96b48e

Sync from GitHub: 92276ee5ef403ac1dcc0973c85d28e87e82abdb8

Browse files
Files changed (3) hide show
  1. DEPLOYMENT_GUIDE.md +1 -1
  2. main.py +58 -1
  3. simulation.py +130 -0
DEPLOYMENT_GUIDE.md CHANGED
@@ -58,7 +58,7 @@ services:
58
 
59
  Run:
60
  ```bash
61
- docker-compose up -d
62
  ```
63
 
64
  ## ☁️ Platform-Specific Deployment
 
58
 
59
  Run:
60
  ```bash
61
+ docker compose up -d
62
  ```
63
 
64
  ## ☁️ Platform-Specific Deployment
main.py CHANGED
@@ -14,7 +14,7 @@ import pandas as pd
14
  import numpy as np
15
  from fastapi import FastAPI, HTTPException, Header
16
  from fastapi.middleware.cors import CORSMiddleware
17
- from fastapi.responses import JSONResponse
18
  from pydantic import BaseModel, Field, validator
19
  import uvicorn
20
 
@@ -22,6 +22,7 @@ import uvicorn
22
  sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
23
 
24
  from inference import FraudInference, load_inference_engine
 
25
  import warnings
26
 
27
  # Suppress warnings
@@ -310,6 +311,26 @@ async def startup_event():
310
  print(f"⚠️ Warning: Model not loaded on startup: {str(e)}")
311
  print("⚠️ API will attempt lazy loading on first request")
312
  print("⚠️ This is normal for serverless environments (e.g., Vercel)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
313
 
314
  @app.get("/")
315
  async def root():
@@ -494,6 +515,42 @@ async def predict_batch(request: BatchPredictRequest):
494
  except Exception as e:
495
  raise HTTPException(status_code=500, detail=f"Batch prediction failed: {str(e)}")
496
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
497
  # ============================================================================
498
  # ERROR HANDLERS
499
  # ============================================================================
 
14
  import numpy as np
15
  from fastapi import FastAPI, HTTPException, Header
16
  from fastapi.middleware.cors import CORSMiddleware
17
+ from fastapi.responses import JSONResponse, StreamingResponse
18
  from pydantic import BaseModel, Field, validator
19
  import uvicorn
20
 
 
22
  sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
23
 
24
  from inference import FraudInference, load_inference_engine
25
+ from simulation import simulation_manager, SimulationConfig
26
  import warnings
27
 
28
  # Suppress warnings
 
311
  print(f"⚠️ Warning: Model not loaded on startup: {str(e)}")
312
  print("⚠️ API will attempt lazy loading on first request")
313
  print("⚠️ This is normal for serverless environments (e.g., Vercel)")
314
+
315
+ # Load simulation dataset
316
+ try:
317
+ print("📦 Loading simulation dataset...")
318
+ # Try to find the dataset
319
+ possible_paths = [
320
+ "dataset/test_dataset.csv.gz",
321
+ "dataset/test_dataset.csv",
322
+ "../dataset/test_dataset.csv.gz"
323
+ ]
324
+
325
+ path_to_use = "dataset/test_dataset.csv.gz" # Default
326
+ for p in possible_paths:
327
+ if os.path.exists(p):
328
+ path_to_use = p
329
+ break
330
+
331
+ simulation_manager.load_dataset(path_to_use)
332
+ except Exception as e:
333
+ print(f"⚠️ Failed to load simulation dataset: {str(e)}")
334
 
335
  @app.get("/")
336
  async def root():
 
515
  except Exception as e:
516
  raise HTTPException(status_code=500, detail=f"Batch prediction failed: {str(e)}")
517
 
518
+ # ============================================================================
519
+ # SIMULATION ENDPOINTS
520
+ # ============================================================================
521
+
522
+ @app.post("/simulate/start")
523
+ async def start_simulation():
524
+ """Start the transaction simulation"""
525
+ try:
526
+ status = simulation_manager.start()
527
+ return status
528
+ except ValueError as e:
529
+ raise HTTPException(status_code=400, detail=str(e))
530
+
531
+ @app.post("/simulate/stop")
532
+ async def stop_simulation():
533
+ """Stop/Pause the transaction simulation"""
534
+ return simulation_manager.stop()
535
+
536
+ @app.post("/simulate/reset")
537
+ async def reset_simulation():
538
+ """Reset the simulation to the beginning"""
539
+ return simulation_manager.reset()
540
+
541
+ @app.post("/simulate/config")
542
+ async def configure_simulation(config: SimulationConfig):
543
+ """Configure simulation speed"""
544
+ return simulation_manager.set_speed(config.speed)
545
+
546
+ @app.get("/simulate/stream")
547
+ async def stream_simulation():
548
+ """Stream simulated transactions via SSE"""
549
+ return StreamingResponse(
550
+ simulation_manager.stream_generator(),
551
+ media_type="text/event-stream"
552
+ )
553
+
554
  # ============================================================================
555
  # ERROR HANDLERS
556
  # ============================================================================
simulation.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import asyncio
3
+ import json
4
+ import os
5
+ import time
6
+ from typing import Optional, Generator, AsyncGenerator
7
+ from pydantic import BaseModel
8
+
9
+ class SimulationConfig(BaseModel):
10
+ speed: float = 1.0 # Multiplier, or seconds delay? Let's say speed multiplier (1x, 2x...)
11
+ # But for simplicity, let's treat it as "transactions per second" or delay.
12
+ # The requirement says "Speed Slider: Adjusts how fast...".
13
+ # Let's map speed 1-10 to delay.
14
+ # Speed 1 = 2 sec delay, Speed 10 = 0.1 sec delay.
15
+
16
+ class SimulationStatus(BaseModel):
17
+ status: str # "running", "paused", "stopped"
18
+ current_index: int
19
+ total_transactions: int
20
+ speed: float
21
+
22
+ class SimulationManager:
23
+ def __init__(self):
24
+ self.dataset: Optional[pd.DataFrame] = None
25
+ self.current_index = 0
26
+ self.is_running = False
27
+ self.speed = 1.0 # Default 1x speed
28
+ self.delay = 1.0 # Seconds between transactions
29
+ self.dataset_path = None
30
+
31
+ def load_dataset(self, path: str):
32
+ self.dataset_path = path
33
+ # Check if file exists, if not try to find it
34
+ if not os.path.exists(path):
35
+ # Try finding it in common locations
36
+ possible_paths = [
37
+ path,
38
+ f"dataset/{path}",
39
+ f"../dataset/{path}",
40
+ "dataset/test_dataset.csv.gz",
41
+ "dataset/test_dataset.csv"
42
+ ]
43
+ for p in possible_paths:
44
+ if os.path.exists(p):
45
+ self.dataset_path = p
46
+ break
47
+
48
+ if self.dataset_path and os.path.exists(self.dataset_path):
49
+ print(f"Loading simulation dataset from {self.dataset_path}")
50
+ # Load only necessary columns to save memory if needed
51
+ self.dataset = pd.read_csv(self.dataset_path)
52
+ # Ensure it's sorted by step
53
+ if 'step' in self.dataset.columns:
54
+ self.dataset = self.dataset.sort_values('step')
55
+ print(f"Loaded {len(self.dataset)} transactions for simulation")
56
+ else:
57
+ print("Simulation dataset not found!")
58
+
59
+ def start(self):
60
+ if self.dataset is None:
61
+ raise ValueError("Dataset not loaded")
62
+ self.is_running = True
63
+ return self.get_status()
64
+
65
+ def stop(self):
66
+ self.is_running = False
67
+ return self.get_status()
68
+
69
+ def reset(self):
70
+ self.current_index = 0
71
+ self.is_running = False
72
+ return self.get_status()
73
+
74
+ def set_speed(self, speed: float):
75
+ self.speed = max(0.1, min(speed, 10.0)) # Clamp between 0.1 and 10
76
+ # Formula: Higher speed = Lower delay.
77
+ # Base delay = 2 seconds (at 1x)
78
+ # Delay = 2 / speed
79
+ self.delay = 2.0 / self.speed
80
+ return self.get_status()
81
+
82
+ def get_status(self):
83
+ return {
84
+ "status": "running" if self.is_running else "paused",
85
+ "current_index": self.current_index,
86
+ "total_transactions": len(self.dataset) if self.dataset is not None else 0,
87
+ "speed": self.speed
88
+ }
89
+
90
+ async def stream_generator(self) -> AsyncGenerator[str, None]:
91
+ """
92
+ Yields SSE formatted data:
93
+ data: {json_content}\n\n
94
+ """
95
+ while True:
96
+ if not self.is_running:
97
+ await asyncio.sleep(0.5)
98
+ # yield Comment to keep connection alive
99
+ yield ": keep-alive\n\n"
100
+ continue
101
+
102
+ if self.dataset is None or self.current_index >= len(self.dataset):
103
+ self.is_running = False
104
+ yield f"data: {json.dumps({'event': 'finished'})}\\n\\n"
105
+ break
106
+
107
+ # Get current transaction
108
+ row = self.dataset.iloc[self.current_index]
109
+ transaction = row.to_dict()
110
+
111
+ # Convert numpy types to native python types for JSON serialization
112
+ for key, value in transaction.items():
113
+ if hasattr(value, 'item'):
114
+ transaction[key] = value.item()
115
+
116
+ # Create payload
117
+ payload = {
118
+ "transaction": transaction,
119
+ "index": self.current_index,
120
+ "total": len(self.dataset)
121
+ }
122
+
123
+ yield f"data: {json.dumps(payload)}\\n\\n"
124
+
125
+ self.current_index += 1
126
+
127
+ # Wait based on speed
128
+ await asyncio.sleep(self.delay)
129
+
130
+ simulation_manager = SimulationManager()