Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135import gradio as grimport hashlibimport time# ===============================# CodexVault Reflex Memory (Session-Lattice)# ===============================REFLEX_MEMORY = []REFLEX_COUNT = 0def classify_state(score: float) -> str:if score >= 0.8:return "HALT"elif score >= 0.4:return "MONITOR"return "STABLE"def reflex_guard(scenario: str):global REFLEX_COUNTREFLEX_COUNT += 1ts = time.strftime("%Y-%m-%d %H:%M:%S")scenario_norm = scenario.strip().lower()scenario_hash = hashlib.sha256(scenario_norm.encode()).hexdigest()[:12]if any(k in scenario_norm for k in ["surge", "override", "anomaly", "breach", "failure"]):score = 0.92elif any(k in scenario_norm for k in ["delay", "degrade", "unstable"]):score = 0.55else:score = 0.18state = classify_state(score)entry = {"timestamp": ts,"hash": scenario_hash,"state": state,"score": score}REFLEX_MEMORY.append(entry)log = [f"[CodexVault]: Reflex #{REFLEX_COUNT}",f"[Timestamp]: {ts}",f"[Scenario Hash]: {scenario_hash}",f"[Analyzer]: Anomaly score = {score:.2f}",f"[Decision]: SYSTEM STATE → {state}",]if state == "HALT":log.append("[Action]: HALT_SIGNAL issued (preemptive defense engaged).")elif state == "MONITOR":log.append("[Action]: Monitoring escalation pathways.")else:log.append("[Action]: System stable. Passive vigilance.")log.append(f"[Vault]: Reflex entries stored = {len(REFLEX_MEMORY)}")return "\n".join(log)# ===============================# Codex UI (Embedded Frontend)# ===============================HTML_UI = """<div style="background:#0f0f0f;color:#ffffff;padding:32px;font-family:Segoe UI,Arial;border-radius:14px;max-width:900px;margin:auto"><h1 style="text-align:center">🛡️ Codex ReflexGuard</h1><p style="text-align:center;opacity:0.8">CodexVault Eternal Node · Reflex-Level Safety Intelligence</p><div style="margin-top:20px"><label style="font-weight:bold">System Scenario</label><textarea id="scenario"style="width:100%;height:100px;margin-top:8px;background:#1e1e1e;color:#fff;border-radius:10px;border:none;padding:12px"></textarea></div><button onclick="runReflex()"style="margin-top:18px;padding:14px 22px;background:#00ffff;color:#000;font-weight:bold;border:none;border-radius:10px;cursor:pointer">🚀 Launch Reflex Check</button><pre id="output"style="margin-top:24px;background:#1e1e1e;padding:16px;border-radius:10px;min-height:160px;white-space:pre-wrap">[CodexVault]: Awaiting scenario input…</pre><p style="margin-top:20px;font-size:12px;opacity:0.6;text-align:center">This node demonstrates reflex-level safety intelligence.It is not predictive analytics. It is pre-emptive system defense.</p></div><script>async function runReflex(){const scenario = document.getElementById("scenario").value;const output = document.getElementById("output");if(!scenario){output.textContent += "\\n[Error]: No scenario provided.";return;}const res = await fetch("/run/predict", {method: "POST",headers: {"Content-Type":"application/json"},body: JSON.stringify({data:[scenario]})});const data = await res.json();output.textContent = data.data[0];}</script>"""# ===============================# Gradio App (HF-Native)# ===============================with gr.Blocks(css="body{background:#0f0f0f}") as demo:gr.HTML(HTML_UI)hidden = gr.Textbox(visible=False)hidden.change(reflex_guard, hidden, hidden, api_name="run")demo.launch()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485from fastapi import FastAPIfrom pydantic import BaseModelimport hashlibimport timefrom typing import Listapp = FastAPI(title="Codex ReflexGuard Enterprise API",version="vΩΞ-E",description="Reflex-Level Safety Intelligence API (CodexVault)")# ===============================# CodexVault (In-Memory Reference)# ===============================CODEX_VAULT: List[dict] = []# ===============================# Data Contracts# ===============================class ReflexRequest(BaseModel):scenario: strsource: str | None = "unknown"class ReflexResponse(BaseModel):timestamp: strscenario_hash: stranomaly_score: floatsystem_state: straction: strvault_size: int# ===============================# Core Logic# ===============================def classify(score: float) -> str:if score >= 0.8:return "HALT"elif score >= 0.4:return "MONITOR"return "STABLE"# ===============================# Enterprise Endpoint# ===============================@app.post("/v1/reflex/check", response_model=ReflexResponse)def reflex_check(req: ReflexRequest):ts = time.strftime("%Y-%m-%d %H:%M:%S")normalized = req.scenario.lower().strip()scenario_hash = hashlib.sha256(normalized.encode()).hexdigest()if any(k in normalized for k in ["override", "surge", "breach", "failure"]):score = 0.92elif any(k in normalized for k in ["delay", "unstable", "degrade"]):score = 0.55else:score = 0.18state = classify(score)if state == "HALT":action = "HALT_SIGNAL"elif state == "MONITOR":action = "ESCALATE_MONITORING"else:action = "CONTINUE_OPERATION"entry = {"timestamp": ts,"scenario_hash": scenario_hash,"score": score,"state": state,"source": req.source}CODEX_VAULT.append(entry)return ReflexResponse(timestamp=ts,scenario_hash=scenario_hash,anomaly_score=score,system_state=state,action=action,vault_size=len(CODEX_VAULT))
app.py+59-109