ankitxraj21 commited on
Commit
4e66071
Β·
verified Β·
1 Parent(s): 153ae7c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +95 -120
app.py CHANGED
@@ -6,34 +6,35 @@ import matplotlib.pyplot as plt
6
  import numpy as np
7
  from datetime import datetime
8
 
9
- # ═══════════════════════════════════════════════════════════
10
- # GLOBAL STATE (REAL-TIME MEMORY)
11
- # ═══════════════════════════════════════════════════════════
12
- history = {
13
- "load": [],
14
- "latency": [],
15
- "cost": [],
16
- "servers": []
17
- }
18
-
19
- MAX_POINTS = 120
20
-
21
- # ═══════════════════════════════════════════════════════════
22
- # COLORS
23
- # ═══════════════════════════════════════════════════════════
24
- C = {
25
- "bg": "#0b0f1a",
26
- "cyan": "#00e5ff",
27
- "green": "#00ff9d",
28
- "red": "#ff3d5a",
29
- "amber": "#ffb300",
30
- "purple": "#c084fc"
31
  }
 
 
 
 
 
 
32
 
33
- # ═══════════════════════════════════════════════════════════
34
- # REAL SYSTEM METRICS (LIVE ENGINE)
35
- # ═══════════════════════════════════════════════════════════
36
- def get_real_metrics():
37
  cpu = psutil.cpu_percent()
38
  mem = psutil.virtual_memory().percent
39
 
@@ -44,78 +45,67 @@ def get_real_metrics():
44
 
45
  return load, latency, servers, cost
46
 
47
- # ═══════════════════════════════════════════════════════════
48
- # AI DECISION ENGINE (SMART)
49
- # ═══════════════════════════════════════════════════════════
50
- def ai_decision(load, latency, cost, auto_scaling):
51
-
52
- anomaly = False
53
-
54
- if len(history["load"]) > 10:
55
- avg = np.mean(history["load"][-10:])
56
- if load > avg * 1.4:
57
- anomaly = True
58
-
59
- if anomaly:
60
- return "🚨 ANOMALY DETECTED β†’ Emergency Scale Up", "HIGH"
61
-
62
- if load > 750 and latency > 90:
63
- return "πŸ”₯ Scale Up +2", "HIGH"
64
-
65
- if load < 300:
66
- return "🟒 Scale Down -1", "LOW"
67
-
68
- if cost > 0.7:
69
- return "πŸ’° Optimize Cost / Use Spot", "MEDIUM"
70
-
71
- return "βš–οΈ Stable System", "LOW"
72
-
73
- # ═══════════════════════════════════════════════════════════
74
- # PREDICTION ENGINE (SIMPLE FORECAST)
75
- # ═══════════════════════════════════════════════════════════
76
- def predict_next():
77
- if len(history["load"]) < 5:
78
- return 0, 0
79
-
80
- load_trend = np.mean(history["load"][-5:])
81
- lat_trend = np.mean(history["latency"][-5:])
82
-
83
- return int(load_trend * 1.05), int(lat_trend * 1.05)
84
-
85
- # ═══════════════════════════════════════════════════════════
86
- # GRAPH (MULTI-LINE REAL-TIME)
87
- # ══════════════════════���════════════════════════════════════
88
  def make_graph():
89
-
90
  fig, ax = plt.subplots(figsize=(7,3))
91
  fig.patch.set_facecolor("#0b0f1a")
92
  ax.set_facecolor("#0b0f1a")
93
 
94
  t = np.arange(len(history["load"]))
95
 
96
- ax.plot(t, history["load"], color=C["cyan"], label="Load")
97
- ax.plot(t, history["latency"], color=C["amber"], label="Latency")
98
- ax.plot(t, np.array(history["cost"])*1000, color=C["green"], label="Cost x1000")
99
 
100
  ax.legend()
101
  ax.grid(alpha=0.2)
102
 
 
 
 
 
103
  return fig
104
 
105
- # ═══════════════════════════════════════════════════════════
106
- # MAIN ENGINE LOOP
107
- # ═══════════════════════════════════════════════════════════
108
- def run_engine(user_control, auto_scaling):
109
 
110
- now = datetime.now().strftime("%H:%M:%S")
111
 
112
- # REAL METRICS
113
- load, latency, servers, cost = get_real_metrics()
114
 
115
- # APPLY USER CONTROL (simulate external pressure)
116
- load = int(load * (user_control / 50))
 
117
 
118
- # STORE HISTORY
119
  history["load"].append(load)
120
  history["latency"].append(latency)
121
  history["cost"].append(cost)
@@ -124,71 +114,56 @@ def run_engine(user_control, auto_scaling):
124
  for k in history:
125
  history[k] = history[k][-MAX_POINTS:]
126
 
127
- # AI DECISION
128
- decision, risk = ai_decision(load, latency, cost, auto_scaling)
129
-
130
- # PREDICTION
131
- p_load, p_lat = predict_next()
132
 
133
- # LOG
134
- log = f"""
135
- [{now}] Load={load} | Lat={latency} | Cost={cost}
136
- β†’ {decision}
137
- β†’ Predicted Next: Load={p_load}, Lat={p_lat}
138
- """
139
 
140
- # GRAPH
141
  fig = make_graph()
142
 
143
  return (
144
- load,
145
- latency,
146
- servers,
147
- cost,
148
- decision,
149
- risk,
150
- p_load,
151
- p_lat,
152
  log,
153
  fig
154
  )
155
 
156
- # ═══════════════════════════════════════════════════════════
157
- # UI (PRO DASHBOARD)
158
- # ═══════════════════════════════════════════════════════════
159
- with gr.Blocks(title="PRO AI Cloud Engine") as demo:
160
 
161
- gr.Markdown("# πŸš€ PRO AI Cloud Engine (Live System)")
 
 
 
162
 
163
  with gr.Row():
164
- user_control = gr.Slider(10,100,value=50,label="External Load Pressure")
165
- auto_scaling = gr.Checkbox(value=True,label="AI Auto Scaling")
166
 
167
  with gr.Row():
168
- load_out = gr.Number(label="Load (req/s)")
169
- lat_out = gr.Number(label="Latency (ms)")
170
- srv_out = gr.Number(label="Servers")
171
- cost_out = gr.Number(label="Cost ($/hr)")
172
 
173
  with gr.Row():
174
  decision_out = gr.Textbox(label="AI Decision")
175
  risk_out = gr.Textbox(label="Risk Level")
176
 
177
- with gr.Row():
178
- pred_load = gr.Number(label="Predicted Load")
179
- pred_lat = gr.Number(label="Predicted Latency")
180
-
181
- log_out = gr.Textbox(label="System Log", lines=6)
182
  graph = gr.Plot()
183
 
184
- # πŸ”₯ LIVE ENGINE
185
  demo.load(
186
  run_engine,
187
- inputs=[user_control, auto_scaling],
188
  outputs=[
189
  load_out, lat_out, srv_out, cost_out,
190
  decision_out, risk_out,
191
- pred_load, pred_lat,
192
  log_out, graph
193
  ],
194
  every=1
 
6
  import numpy as np
7
  from datetime import datetime
8
 
9
+ # ═══════════════════════════════════════════════════
10
+ # GLOBAL STATE
11
+ # ═══════════════════════════════════════════════════
12
+ history = {"load": [], "latency": [], "cost": [], "servers": []}
13
+ MAX_POINTS = 100
14
+
15
+ # ═══════════════════════════════════════════════════
16
+ # CUSTOM CSS (PRO UI)
17
+ # ═══════════════════════════════════════════════════
18
+ custom_css = """
19
+ body { background: #0b0f1a; color: white; }
20
+ .card {
21
+ background: rgba(255,255,255,0.05);
22
+ border-radius: 16px;
23
+ padding: 15px;
24
+ box-shadow: 0 0 15px rgba(0,0,0,0.3);
25
+ text-align: center;
 
 
 
 
 
26
  }
27
+ .metric { font-size: 28px; font-weight: bold; }
28
+ .green { color: #00ff9d; }
29
+ .red { color: #ff3d5a; }
30
+ .yellow { color: #ffb300; }
31
+ .cyan { color: #00e5ff; }
32
+ """
33
 
34
+ # ═══════════════════════════════════════════════════
35
+ # METRICS ENGINE
36
+ # ═══════════════════════════════════════════════════
37
+ def get_metrics():
38
  cpu = psutil.cpu_percent()
39
  mem = psutil.virtual_memory().percent
40
 
 
45
 
46
  return load, latency, servers, cost
47
 
48
+ # ═══════════════════════════════════════════════════
49
+ # AI DECISION
50
+ # ═══════════════════════════════════════════════════
51
+ def ai_decision(load, latency, cost):
52
+ if load > 800 or latency > 100:
53
+ return "πŸ”₯ Scale Up Immediately", "HIGH"
54
+ elif load < 300:
55
+ return "🟒 Scale Down Resources", "LOW"
56
+ elif cost > 0.7:
57
+ return "πŸ’° Optimize Cost", "MEDIUM"
58
+ return "βš–οΈ System Stable", "LOW"
59
+
60
+ # ═══════════════════════════════════════════════════
61
+ # CARD FORMATTER
62
+ # ═══════════════════════════════════════════════════
63
+ def card(title, value, color):
64
+ return f"""
65
+ <div class="card">
66
+ <div>{title}</div>
67
+ <div class="metric {color}">{value}</div>
68
+ </div>
69
+ """
70
+
71
+ # ═══════════════════════════════════════════════════
72
+ # GRAPH
73
+ # ═══════════════════════════════════════════════════
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  def make_graph():
 
75
  fig, ax = plt.subplots(figsize=(7,3))
76
  fig.patch.set_facecolor("#0b0f1a")
77
  ax.set_facecolor("#0b0f1a")
78
 
79
  t = np.arange(len(history["load"]))
80
 
81
+ ax.plot(t, history["load"], linewidth=2, label="Load")
82
+ ax.plot(t, history["latency"], linewidth=2, label="Latency")
83
+ ax.plot(t, np.array(history["cost"])*1000, linewidth=2, label="Cost x1000")
84
 
85
  ax.legend()
86
  ax.grid(alpha=0.2)
87
 
88
+ ax.spines[:].set_visible(False)
89
+ ax.tick_params(colors="white")
90
+ ax.set_title("Live Metrics", color="white")
91
+
92
  return fig
93
 
94
+ # ═══════════════════════════════════════════════════
95
+ # MAIN ENGINE
96
+ # ═══════════════════════════════════════════════════
97
+ def run_engine(load_slider, chaos):
98
 
99
+ load, latency, servers, cost = get_metrics()
100
 
101
+ # simulate user load
102
+ load = int(load * (load_slider / 50))
103
 
104
+ # chaos mode
105
+ if chaos:
106
+ load *= random.randint(1, 3)
107
 
108
+ # store history
109
  history["load"].append(load)
110
  history["latency"].append(latency)
111
  history["cost"].append(cost)
 
114
  for k in history:
115
  history[k] = history[k][-MAX_POINTS:]
116
 
117
+ decision, risk = ai_decision(load, latency, cost)
 
 
 
 
118
 
119
+ log = f"[{datetime.now().strftime('%H:%M:%S')}] Load={load}, Lat={latency}, Cost={cost}"
 
 
 
 
 
120
 
 
121
  fig = make_graph()
122
 
123
  return (
124
+ card("πŸš€ Load", load, "cyan"),
125
+ card("⚑ Latency", latency, "yellow"),
126
+ card("πŸ–₯ Servers", servers, "green"),
127
+ card("πŸ’° Cost/hr", f"${cost}", "green"),
128
+ f"πŸ€– {decision}",
129
+ f"Risk: {risk}",
 
 
130
  log,
131
  fig
132
  )
133
 
134
+ # ═══════════════════════════════════════════════════
135
+ # UI
136
+ # ═══════════════════════════════════════════════════
137
+ with gr.Blocks(css=custom_css) as demo:
138
 
139
+ gr.Markdown("""
140
+ # πŸš€ Cloud-Cost Guardian AI
141
+ ### Autonomous AI for Real-Time Scaling & Cost Optimization
142
+ """)
143
 
144
  with gr.Row():
145
+ load_slider = gr.Slider(10, 100, value=50, label="External Load")
146
+ chaos = gr.Checkbox(label="πŸ”₯ Chaos Mode")
147
 
148
  with gr.Row():
149
+ load_out = gr.HTML()
150
+ lat_out = gr.HTML()
151
+ srv_out = gr.HTML()
152
+ cost_out = gr.HTML()
153
 
154
  with gr.Row():
155
  decision_out = gr.Textbox(label="AI Decision")
156
  risk_out = gr.Textbox(label="Risk Level")
157
 
158
+ log_out = gr.Textbox(label="System Log")
 
 
 
 
159
  graph = gr.Plot()
160
 
 
161
  demo.load(
162
  run_engine,
163
+ inputs=[load_slider, chaos],
164
  outputs=[
165
  load_out, lat_out, srv_out, cost_out,
166
  decision_out, risk_out,
 
167
  log_out, graph
168
  ],
169
  every=1