theghostcmd commited on
Commit
745e8b5
·
verified ·
1 Parent(s): db2c401

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +119 -0
app.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import logging
4
+ from fastapi import FastAPI, HTTPException
5
+ from pydantic import BaseModel
6
+ from typing import Dict, Any, Optional
7
+ import uvicorn
8
+
9
+ # Configure logging
10
+ logging.basicConfig(level=logging.INFO)
11
+ logger = logging.getLogger(__name__)
12
+
13
+ app = FastAPI()
14
+
15
+ # Global state for the environment
16
+ class EnvironmentState:
17
+ def __init__(self):
18
+ self.reset()
19
+
20
+ def reset(self):
21
+ self.step_count = 0
22
+ self.current_observation = {
23
+ "anomaly_score": 0.0,
24
+ "verdict": "normal",
25
+ "alerts": []
26
+ }
27
+ self.done = False
28
+ self.info = {}
29
+ logger.info("Environment reset")
30
+
31
+ def step(self, action: Dict[str, Any]) -> Dict[str, Any]:
32
+ """
33
+ Process one step of the environment.
34
+ action: dictionary containing e.g., {"packet_data": "..."}
35
+ Returns: observation, reward, done, info
36
+ """
37
+ self.step_count += 1
38
+
39
+ # --- REPLACE THIS WITH YOUR ACTUAL MAYONE DETECTION LOGIC ---
40
+ # Here you would call your framework's functions.
41
+ # For now, a dummy detection:
42
+ packet_data = action.get("packet_data", "")
43
+ if "malicious" in packet_data.lower() or "attack" in packet_data.lower():
44
+ anomaly_score = 0.92
45
+ verdict = "malicious"
46
+ alerts = ["Potential C2 beacon detected"]
47
+ else:
48
+ anomaly_score = 0.12
49
+ verdict = "normal"
50
+ alerts = []
51
+
52
+ observation = {
53
+ "anomaly_score": anomaly_score,
54
+ "verdict": verdict,
55
+ "alerts": alerts,
56
+ "step": self.step_count
57
+ }
58
+ reward = 1.0 if verdict == "malicious" else 0.0
59
+ done = self.step_count >= 100 # optional max steps
60
+ info = {"model": os.getenv("MODEL_NAME", "MayOne")}
61
+
62
+ self.current_observation = observation
63
+ self.done = done
64
+ self.info = info
65
+
66
+ logger.info(f"Step {self.step_count}: verdict={verdict}")
67
+ return {
68
+ "observation": observation,
69
+ "reward": reward,
70
+ "done": done,
71
+ "info": info
72
+ }
73
+
74
+ def get_state(self) -> Dict[str, Any]:
75
+ return {
76
+ "step_count": self.step_count,
77
+ "current_observation": self.current_observation,
78
+ "done": self.done,
79
+ "info": self.info
80
+ }
81
+
82
+ # Initialize global environment
83
+ env = EnvironmentState()
84
+
85
+ # --- API Endpoints required by OpenEnv ---
86
+
87
+ class ResetRequest(BaseModel):
88
+ config: Optional[Dict[str, Any]] = None
89
+
90
+ class StepRequest(BaseModel):
91
+ action: Dict[str, Any]
92
+
93
+ @app.post("/reset")
94
+ async def reset_endpoint(request: ResetRequest = None):
95
+ """Reset the environment to initial state."""
96
+ env.reset()
97
+ # Optionally apply config if provided
98
+ if request and request.config:
99
+ logger.info(f"Applying config: {request.config}")
100
+ return {"status": "ok", "observation": env.current_observation}
101
+
102
+ @app.post("/step")
103
+ async def step_endpoint(request: StepRequest):
104
+ """Take one step in the environment."""
105
+ result = env.step(request.action)
106
+ return result
107
+
108
+ @app.get("/state")
109
+ async def state_endpoint():
110
+ """Get current state of the environment."""
111
+ return env.get_state()
112
+
113
+ @app.get("/health")
114
+ async def health():
115
+ return {"status": "alive"}
116
+
117
+ if __name__ == "__main__":
118
+ port = int(os.getenv("PORT", 7860))
119
+ uvicorn.run(app, host="0.0.0.0", port=port)