Spaces:
Sleeping
Sleeping
Update app.py
Browse files5 unmodified lines67891011121314264 unmodified lines27928028128228328428510 unmodified lines29629729829930030130220 unmodified lines3233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693705 unmodified lines3763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144153 unmodified lines4194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734 unmodified lines47847948048148248348448548617 unmodified lines5045055065075085095102 unmodified lines51351451551651751851952052123 unmodified lines5455465475485495505511 unmodified line5535545555565575585591 unmodified line5615625635645655 unmodified linesimport matplotlib.patches as mpatchesimport numpy as npfrom datetime import datetimefrom flask import Flask, request, jsonifyfrom environment import CloudCostEnv # Assuming your environment.py has this classimport os# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# COLOR SYSTEM264 unmodified lines}def get_decision(user_load, spot_avail, chaos_monkey, budget_on, latency):if chaos_monkey and latency > 120: key = "chaos_resp"elif user_load > 80 and latency > 80: key = "scale_up"elif user_load < 35: key = "scale_down"elif budget_on and spot_avail > 50: key = "spot_switch"10 unmodified linesreturn "๐ข HEALTHY โ All Systems Nominal", "green"# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# MAIN SIMULATION โ returns exactly 23 values, matching outputs# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ_tick = 020 unmodified linesuser_load, spot_avail, chaos_monkey, budget_on, latency)health_txt, _ = health_badge(latency, load, drisk)decision_md = f"""### ๐ง AI Decision**โ {action}**| | ||---|---|| Confidence | `{conf}%` || Reason | {reason} || Scenario | {scenario.split(':')[0]} || Time | `{t}` |"""xai_md = "### ๐ก Why did AI decide this?\n" + "".join(f"- โ {r}\n" for r in xai)health_md = f"""### {health_txt}| Metric | Value ||---|---|| Latency | `{latency} ms` || Load | `{load} req/s` || Downtime risk | `{drisk}` || Agent score | `{score} / 1.0` |"""pred_cost = round(burn * (user_load / 48), 2)pred_lat = round(latency * (user_load / 58), 1)risk_lbl = ("๐ด HIGH" if pred_lat > 100 or pred_cost > 0.65else "๐ก MEDIUM" if pred_lat > 60else "๐ข LOW")whatif_md = f"""### ๐ฎ What-If Simulation*If Load = {int(user_load)}% continues...*| Prediction | Value ||---|---|| Predicted cost | `${pred_cost}/hr` || Predicted latency | `{pred_lat} ms` || Risk level | {risk_lbl} || Estimated savings | `{savings}` |"""log = f"[{t}] {scenario}\n"log += f"[{t}] Load: {load} req/s | Servers: {servers} | Burn: ${burn}/hr\n"log += f"[{t}] Latency: {latency} ms | Risk: {drisk}\n"log += f"[{t}] DECISION: {action} (conf {conf}%)\n"log += f"[{t}] Score: {score} / 1.0 | Savings: {savings}"# โโ charts โโgauge_fig = make_gauge_chart(int(user_load), "User Load", C["cyan"], seed)burst_fig = make_radial_burst(load, "req/s", C["purple"], seed)burst2_fig = make_radial_burst(int(score*100), "Scoreร100", C["green"], seed+1)5 unmodified linesbefore_fig = make_before_after(auto_scaling)whatif_fig = make_whatif(int(user_load), int(spot_avail))# โโ 23 return values โ perfectly matches outputs list below โโreturn (f"๐ {load} req/s", # load_outf"๐ฅ๏ธ {servers} instances", # server_outf"๐ธ ${burn}/hr", # burn_outf"โก {latency} ms", # latency_outf"๐ฐ {savings} saved", # savings_outf"๐ {score} / 1.0", # score_outdecision_md, # decision_outxai_md, # xai_outhealth_md, # health_outwhatif_md, # whatif_outlog, # log_outspend_str, # spend_out2drisk, # risk_outscore, # score_num โ raw float, fixes the Error buggauge_fig, # gauge_plotburst_fig, # burst_plotburst2_fig, # burst2_plotarea_fig, # area_plotbar_fig, # bar_plotwave_fig, # wave_plotlat_fig, # lat_plotreward_fig, # reward_plotbefore_fig, # before_plotwhatif_fig, # whatif_plot โ 24 total)# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# CSS# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโCSS = """@import url('https://fonts.googleapis.com/css2?family=Space+Mono&family=Inter:wght@400;600;700;800&display=swap');body, .gradio-container {background: #06091a !important;color: #e2eeff !important;3 unmodified linesbackground: rgba(11,17,32,0.85) !important;border: 0.5px solid #1e3a5f !important;border-radius: 14px !important;backdrop-filter: blur(12px) !important;}.hero-metric textarea, .hero-metric input {font-size: 22px !important; font-weight: 800 !important;color: #00e5ff !important; text-align: center !important;background: rgba(0,229,255,0.06) !important;border: 1px solid rgba(0,229,255,0.25) !important;border-radius: 12px !important; padding: 18px 10px !important;}.sec-metric textarea, .sec-metric input {font-size: 17px !important; font-weight: 700 !important;color: #a78bfa !important; text-align: center !important;background: rgba(167,139,250,0.06) !important;border: 0.5px solid rgba(167,139,250,0.22) !important;border-radius: 10px !important; padding: 12px 8px !important;}.card-decision { background: rgba(255,61,90,0.07) !important; border: 1px solid rgba(255,61,90,0.35) !important; border-radius: 14px !important; padding: 6px 10px !important; }.card-decision h3 { color: #ff3d5a !important; }.card-xai { background: rgba(0,229,255,0.05) !important; border: 1px solid rgba(0,229,255,0.25) !important; border-radius: 14px !important; padding: 6px 10px !important; }.card-xai h3 { color: #00e5ff !important; }.card-health { background: rgba(0,255,157,0.06) !important; border: 1px solid rgba(0,255,157,0.28) !important; border-radius: 14px !important; padding: 6px 10px !important; }.card-health h3 { color: #00ff9d !important; }.card-whatif { background: rgba(192,132,252,0.06) !important; border: 1px solid rgba(192,132,252,0.28) !important; border-radius: 14px !important; padding: 6px 10px !important; }.card-whatif h3 { color: #c084fc !important; }.gr-button-primary {background: linear-gradient(135deg, rgba(0,229,255,0.15), rgba(0,255,157,0.10)) !important;border: 1.5px solid #00e5ff !important; color: #00e5ff !important;font-size: 15px !important; font-weight: 700 !important;letter-spacing: 2px !important; border-radius: 12px !important;padding: 14px 0 !important; text-transform: uppercase !important;}.gr-button-primary:hover { background: rgba(0,229,255,0.22) !important; border-color: #00ff9d !important; color: #00ff9d !important; }label, .gr-input-label { color: #4a6080 !important; font-size: 11px !important; letter-spacing: 1.5px !important; text-transform: uppercase !important; }input, select, textarea { background: #0a1020 !important; color: #e2eeff !important; border: 0.5px solid #1e3a5f !important; border-radius: 8px !important; font-family: 'Inter', sans-serif !important; }.log-panel textarea { font-family: 'Space Mono', monospace !important; font-size: 11.5px !important; color: #7ab0d0 !important; background: #050810 !important; border: 0.5px solid #1e3a5f !important; border-radius: 10px !important; line-height: 1.9 !important; }.score-box input { font-size: 30px !important; font-weight: 900 !important; color: #00ff9d !important; text-align: center !important; background: rgba(0,255,157,0.07) !important; border: 1px solid rgba(0,255,157,0.30) !important; border-radius: 12px !important; }.gr-plot { background: rgba(11,17,32,0.90) !important; border: 0.5px solid #1e3a5f !important; border-radius: 12px !important; padding: 6px !important; }.gr-markdown table { font-size: 13px !important; width: 100% !important; }.gr-markdown td, .gr-markdown th { padding: 5px 8px !important; border-color: #1e3a5f !important; }.gr-markdown h3 { font-size: 14px !important; margin-bottom: 8px !important; }.gr-markdown code { background: rgba(0,229,255,0.10) !important; color: #00e5ff !important; border-radius: 4px !important; padding: 1px 6px !important; font-family: 'Space Mono', monospace !important; font-size: 12px !important; }hr { border-color: #1e3a5f !important; margin: 14px 0 !important; }.gr-markdown h2 { color: #00e5ff !important; letter-spacing: 1px !important; border-bottom: 1px solid #1e3a5f !important; padding-bottom: 6px !important; }"""# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# UI# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโwith gr.Blocks(css=CSS, title="โ๏ธ Cloud-Cost Guardian AI") as demo:gr.Markdown("# โ๏ธ Cloud-Cost Guardian AI\n#### RL-Powered Autonomous Infrastructure โ Live Intelligence Dashboard\n---")4 unmodified linesscore_out = gr.Textbox(label="๐ Agent Score", interactive=False, elem_classes="hero-metric")with gr.Row(equal_height=True):server_out = gr.Textbox(label="๐ฅ๏ธ Servers", interactive=False, elem_classes="sec-metric")burn_out = gr.Textbox(label="๐ธ Burn Rate", interactive=False, elem_classes="sec-metric")latency_out = gr.Textbox(label="โก Latency", interactive=False, elem_classes="sec-metric")gr.Markdown("---")17 unmodified linesxai_out = gr.Markdown("### ๐ก Explainable AI\n*Waiting...*", elem_classes="card-xai")with gr.Column(scale=1, min_width=260):health_out = gr.Markdown("### ๐ข Health Status\n*Click Run...*", elem_classes="card-health")whatif_out = gr.Markdown("### ๐ฎ What-If Simulation\n*Adjust sliders...*",elem_classes="card-whatif")gr.Markdown("---")2 unmodified lineswith gr.Column(scale=3):log_out = gr.Textbox(lines=5, label="๐ Agent Action Log", interactive=False, elem_classes="log-panel")with gr.Column(scale=1):spend_out2 = gr.Textbox(label="Total Spend", interactive=False)risk_out = gr.Textbox(label="Downtime Risk", interactive=False)score_num = gr.Number( label="Agent Score / 1.0", interactive=False, elem_classes="score-box")gr.Markdown("---")gr.Markdown("## ๐ฏ Radial Intelligence โ Live Gauges")23 unmodified linesgr.Markdown("> ๐ก **Pro tip:** Turn on **Chaos Monkey** + set Load to **90%** for maximum drama!")# โโ wire โ outputs count must equal return tuple length (24) โโrun_btn.click(fn=run_simulation,inputs=[scenario, user_load, spot_avail, chaos_monkey, budget_constr, auto_scaling],1 unmodified lineload_out, server_out, burn_out, latency_out, savings_out, score_out,decision_out, xai_out, health_out, whatif_out,log_out, spend_out2, risk_out,score_num, # gr.Number โ now receives raw float from return tuplegauge_plot, burst_plot, burst2_plot,area_plot, bar_plot,wave_plot, lat_plot,1 unmodified line])if __name__ == "__main__":demo.launch(share=True)5 unmodified lines67891011121314151617181920212223242526272829303132333435363738264 unmodified lines30330430530630730830910 unmodified lines32032132232332432532620 unmodified lines3473483493503513523533543553563573583593603613623633643653663675 unmodified lines3733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084093 unmodified lines4134144154164174184194204214224234244254264274284294304314324334344354364374384394404 unmodified lines44544644744844945045145245317 unmodified lines4714724734744754764772 unmodified lines48048148248348448548648748823 unmodified lines5125135145155165171 unmodified line5195205215225235245251 unmodified line5275285295305315325335345355365375 unmodified linesimport matplotlib.patches as mpatchesimport numpy as npfrom datetime import datetimefrom fastapi import FastAPIfrom pydantic import BaseModelimport uvicornfrom environment import CloudCostEnv# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# FASTAPI โ Checker endpoints (DO NOT REMOVE)# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโfapp = FastAPI()_env = CloudCostEnv()class StepRequest(BaseModel):action: int@fapp.post("/reset")async def api_reset():state = await _env.reset()return state@fapp.post("/step")async def api_step(req: StepRequest):state, reward, done = await _env.step(req.action)return {"state": state, "reward": reward, "done": done}@fapp.get("/state")async def api_state():return await _env.state()# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# COLOR SYSTEM264 unmodified lines}def get_decision(user_load, spot_avail, chaos_monkey, budget_on, latency):if chaos_monkey and latency > 120: key = "chaos_resp"elif user_load > 80 and latency > 80: key = "scale_up"elif user_load < 35: key = "scale_down"elif budget_on and spot_avail > 50: key = "spot_switch"10 unmodified linesreturn "๐ข HEALTHY โ All Systems Nominal", "green"# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# MAIN SIMULATION# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ_tick = 020 unmodified linesuser_load, spot_avail, chaos_monkey, budget_on, latency)health_txt, _ = health_badge(latency, load, drisk)decision_md = f"""### ๐ง AI Decision\n**โ {action}**\n\n| | |\n|---|---|\n| Confidence | `{conf}%` |\n| Reason | {reason} |\n| Scenario | {scenario.split(':')[0]} |\n| Time | `{t}` |\n"""xai_md = "### ๐ก Why did AI decide this?\n" + "".join(f"- โ {r}\n" for r in xai)health_md = f"""### {health_txt}\n\n| Metric | Value |\n|---|---|\n| Latency | `{latency} ms` |\n| Load | `{load} req/s` |\n| Downtime risk | `{drisk}` |\n| Agent score | `{score} / 1.0` |\n"""pred_cost = round(burn * (user_load / 48), 2)pred_lat = round(latency * (user_load / 58), 1)risk_lbl = ("๐ด HIGH" if pred_lat > 100 or pred_cost > 0.65else "๐ก MEDIUM" if pred_lat > 60else "๐ข LOW")whatif_md = f"""### ๐ฎ What-If Simulation\n*If Load = {int(user_load)}% continues...*\n\n| Prediction | Value |\n|---|---|\n| Predicted cost | `${pred_cost}/hr` |\n| Predicted latency | `{pred_lat} ms` |\n| Risk level | {risk_lbl} |\n| Estimated savings | `{savings}` |\n"""log = f"[{t}] {scenario}\n"log += f"[{t}] Load: {load} req/s | Servers: {servers} | Burn: ${burn}/hr\n"log += f"[{t}] Latency: {latency} ms | Risk: {drisk}\n"log += f"[{t}] DECISION: {action} (conf {conf}%)\n"log += f"[{t}] Score: {score} / 1.0 | Savings: {savings}"gauge_fig = make_gauge_chart(int(user_load), "User Load", C["cyan"], seed)burst_fig = make_radial_burst(load, "req/s", C["purple"], seed)burst2_fig = make_radial_burst(int(score*100), "Scoreร100", C["green"], seed+1)5 unmodified linesbefore_fig = make_before_after(auto_scaling)whatif_fig = make_whatif(int(user_load), int(spot_avail))return (f"๐ {load} req/s",f"๐ฅ๏ธ {servers} instances",f"๐ธ ${burn}/hr",f"โก {latency} ms",f"๐ฐ {savings} saved",f"๐ {score} / 1.0",decision_md,xai_md,health_md,whatif_md,log,spend_str,drisk,score,gauge_fig,burst_fig,burst2_fig,area_fig,bar_fig,wave_fig,lat_fig,reward_fig,before_fig,whatif_fig,)# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# CSS# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโCSS = """body, .gradio-container {background: #06091a !important;color: #e2eeff !important;3 unmodified linesbackground: rgba(11,17,32,0.85) !important;border: 0.5px solid #1e3a5f !important;border-radius: 14px !important;}.hero-metric textarea, .hero-metric input {font-size: 22px !important; font-weight: 800 !important;color: #00e5ff !important; text-align: center !important;}.card-decision { background: rgba(255,61,90,0.07) !important; border: 1px solid rgba(255,61,90,0.35) !important; border-radius: 14px !important; padding: 6px 10px !important; }.card-xai { background: rgba(0,229,255,0.05) !important; border: 1px solid rgba(0,229,255,0.25) !important; border-radius: 14px !important; padding: 6px 10px !important; }.card-health { background: rgba(0,255,157,0.06) !important; border: 1px solid rgba(0,255,157,0.28) !important; border-radius: 14px !important; padding: 6px 10px !important; }.card-whatif { background: rgba(192,132,252,0.06) !important; border: 1px solid rgba(192,132,252,0.28) !important; border-radius: 14px !important; padding: 6px 10px !important; }.gr-button-primary {background: linear-gradient(135deg, rgba(0,229,255,0.15), rgba(0,255,157,0.10)) !important;border: 1.5px solid #00e5ff !important; color: #00e5ff !important;font-size: 15px !important; font-weight: 700 !important;border-radius: 12px !important; padding: 14px 0 !important;}.log-panel textarea { font-family: monospace !important; font-size: 11.5px !important; color: #7ab0d0 !important; background: #050810 !important; }"""# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# GRADIO UI# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโwith gr.Blocks(title="โ๏ธ Cloud-Cost Guardian AI") as demo:gr.Markdown("# โ๏ธ Cloud-Cost Guardian AI\n#### RL-Powered Autonomous Infrastructure โ Live Intelligence Dashboard\n---")4 unmodified linesscore_out = gr.Textbox(label="๐ Agent Score", interactive=False, elem_classes="hero-metric")with gr.Row(equal_height=True):server_out = gr.Textbox(label="๐ฅ๏ธ Servers", interactive=False)burn_out = gr.Textbox(label="๐ธ Burn Rate", interactive=False)latency_out = gr.Textbox(label="โก Latency", interactive=False)gr.Markdown("---")17 unmodified linesxai_out = gr.Markdown("### ๐ก Explainable AI\n*Waiting...*", elem_classes="card-xai")with gr.Column(scale=1, min_width=260):health_out = gr.Markdown("### ๐ข Health Status\n*Click Run...*", elem_classes="card-health")whatif_out = gr.Markdown("### ๐ฎ What-If Simulation\n*Adjust sliders...*",elem_classes="card-whatif")gr.Markdown("---")2 unmodified lineswith gr.Column(scale=3):log_out = gr.Textbox(lines=5, label="๐ Agent Action Log", interactive=False, elem_classes="log-panel")with gr.Column(scale=1):spend_out2 = gr.Textbox(label="Total Spend", interactive=False)risk_out = gr.Textbox(label="Downtime Risk", interactive=False)score_num = gr.Number( label="Agent Score / 1.0", interactive=False)gr.Markdown("---")gr.Markdown("## ๐ฏ Radial Intelligence โ Live Gauges")23 unmodified linesgr.Markdown("> ๐ก **Pro tip:** Turn on **Chaos Monkey** + set Load to **90%** for maximum drama!")run_btn.click(fn=run_simulation,inputs=[scenario, user_load, spot_avail, chaos_monkey, budget_constr, auto_scaling],1 unmodified lineload_out, server_out, burn_out, latency_out, savings_out, score_out,decision_out, xai_out, health_out, whatif_out,log_out, spend_out2, risk_out,score_num,gauge_plot, burst_plot, burst2_plot,area_plot, bar_plot,wave_plot, lat_plot,1 unmodified line])# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# MOUNT GRADIO INTO FASTAPI โ checker gets /reset /step /state# Dashboard available at /ui# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโapp = gr.mount_gradio_app(fapp, demo, path="/ui")if __name__ == "__main__":uvicorn.run(app, host="0.0.0.0", port=7860)
app.py+81-109