Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,13 +1,13 @@
|
|
| 1 |
# ============================================================
|
| 2 |
-
#
|
| 3 |
# Author: Liam Grinstead (RFT Systems) | All Rights Reserved
|
| 4 |
# ============================================================
|
| 5 |
"""
|
| 6 |
Deterministic, signed validation harness for the
|
| 7 |
-
Rendered Frame Theory (RFT-Ω) harmonic
|
| 8 |
"""
|
| 9 |
|
| 10 |
-
import os,
|
| 11 |
from datetime import datetime
|
| 12 |
from typing import Dict, Any, List, Tuple
|
| 13 |
import numpy as np
|
|
@@ -19,6 +19,7 @@ try:
|
|
| 19 |
except Exception:
|
| 20 |
HAVE_FASTAPI = False
|
| 21 |
|
|
|
|
| 22 |
# ------------------ About / Legal ---------------------------
|
| 23 |
RFT_VERSION = "v4.0-total-proof-stable"
|
| 24 |
RFT_DOI = "https://doi.org/10.5281/zenodo.17466722"
|
|
@@ -41,7 +42,8 @@ ABOUT_BLOCK = {
|
|
| 41 |
"legal": LEGAL_NOTICE,
|
| 42 |
}
|
| 43 |
|
| 44 |
-
|
|
|
|
| 45 |
RUN_HISTORY_TS: List[float] = []
|
| 46 |
MAX_RUNS_PER_MINUTE = 60
|
| 47 |
|
|
@@ -54,6 +56,7 @@ def _rate_limit_ok() -> Tuple[bool, str]:
|
|
| 54 |
RUN_HISTORY_TS.append(now)
|
| 55 |
return True, "ok"
|
| 56 |
|
|
|
|
| 57 |
# ------------------ Profiles / Simulation -------------------
|
| 58 |
PROFILES = {
|
| 59 |
"AI / Neural": {"base": (0.86, 0.80), "w": (0.65, 0.35)},
|
|
@@ -62,7 +65,8 @@ PROFILES = {
|
|
| 62 |
"Extreme Perturbation":{"base": (0.82, 0.77), "w": (0.50, 0.50)},
|
| 63 |
}
|
| 64 |
|
| 65 |
-
def _rng(seed:int)->np.random.RandomState:
|
|
|
|
| 66 |
|
| 67 |
def simulate_step(rng:np.random.RandomState, profile:str, sigma:float, noise_dist:str)->Dict[str,Any]:
|
| 68 |
base_q, base_z = PROFILES[profile]["base"]
|
|
@@ -76,20 +80,28 @@ def simulate_step(rng:np.random.RandomState, profile:str, sigma:float, noise_dis
|
|
| 76 |
q = float(np.clip(base_q + wq*q_noise, 0.0, 0.99))
|
| 77 |
z = float(np.clip(base_z + wz*z_noise, 0.0, 0.99))
|
| 78 |
variance = abs(q_noise)+abs(z_noise)
|
| 79 |
-
if variance > 0.15:
|
| 80 |
-
|
| 81 |
-
|
|
|
|
|
|
|
|
|
|
| 82 |
return {"sigma": round(sigma,6),"QΩ":q,"ζ_sync":z,"status":status}
|
| 83 |
|
|
|
|
| 84 |
# ------------------ Schedules -------------------------------
|
| 85 |
def build_sigma_series(schedule_type:str, params:Dict[str,Any])->List[float]:
|
| 86 |
if schedule_type=="single":
|
| 87 |
return [float(params.get("sigma",0.05))]
|
| 88 |
elif schedule_type=="ramp":
|
| 89 |
-
return list(np.linspace(float(params.get("start",0.0)),
|
|
|
|
|
|
|
| 90 |
elif schedule_type=="random":
|
| 91 |
r = random.Random(int(params.get("seed",0)))
|
| 92 |
-
return [r.uniform(float(params.get("min",0.0)),
|
|
|
|
|
|
|
| 93 |
elif schedule_type=="impulse":
|
| 94 |
base,spike,at,steps = float(params.get("base",0.05)), float(params.get("spike",0.25)), int(params.get("at",5)), int(params.get("steps",10))
|
| 95 |
s=[base]*steps
|
|
@@ -103,34 +115,45 @@ def build_sigma_series(schedule_type:str, params:Dict[str,Any])->List[float]:
|
|
| 103 |
return s
|
| 104 |
return [float(params.get("sigma",0.05))]
|
| 105 |
|
|
|
|
| 106 |
# ------------------ Integrity helpers -----------------------
|
| 107 |
-
def sha512_hex(s:str)->str:
|
|
|
|
|
|
|
| 108 |
def make_run_id(seed:int,profile:str)->str:
|
| 109 |
-
|
|
|
|
| 110 |
|
| 111 |
def write_bundle(run_dir:str,config:Dict[str,Any],results:Dict[str,Any])->Tuple[str,str]:
|
| 112 |
os.makedirs(run_dir,exist_ok=True)
|
| 113 |
-
with open(os.path.join(run_dir,"run.json"),"w") as f:
|
|
|
|
| 114 |
canonical=json.dumps({"config":config,"results":results},sort_keys=True)
|
| 115 |
digest=sha512_hex(canonical)
|
| 116 |
-
with open(os.path.join(run_dir,"run.sha512"),"w") as f:
|
| 117 |
-
|
| 118 |
-
with open(os.path.join(run_dir,"
|
|
|
|
|
|
|
|
|
|
| 119 |
zip_path=os.path.join(run_dir,"rft_run_bundle.zip")
|
| 120 |
with zipfile.ZipFile(zip_path,"w",zipfile.ZIP_DEFLATED) as z:
|
| 121 |
for fn in ["run.json","run.sha512","ABOUT.json","NOTICE.txt"]:
|
| 122 |
z.write(os.path.join(run_dir,fn),arcname=fn)
|
| 123 |
return zip_path,digest
|
| 124 |
|
|
|
|
| 125 |
# ------------------ Core runner -----------------------------
|
| 126 |
def run_total_proof(profile,noise_dist,schedule_type,schedule_params_text,seed,samples):
|
| 127 |
ok,msg=_rate_limit_ok()
|
| 128 |
-
if not ok:
|
|
|
|
| 129 |
try:
|
| 130 |
params=json.loads(schedule_params_text) if schedule_params_text.strip() else {}
|
| 131 |
if not isinstance(params,dict): raise ValueError
|
| 132 |
except Exception as e:
|
| 133 |
return {"error":f"Invalid schedule_params JSON: {e}","rft_notice":LEGAL_NOTICE},None
|
|
|
|
| 134 |
sigma_series=build_sigma_series(schedule_type,params)
|
| 135 |
rng_master=_rng(seed)
|
| 136 |
results_steps=[]; trigger_count=0
|
|
@@ -172,6 +195,7 @@ def run_total_proof(profile,noise_dist,schedule_type,schedule_params_text,seed,s
|
|
| 172 |
"rft_notice":LEGAL_NOTICE}
|
| 173 |
return {"config":config,"head":head,"results":results},zip_path
|
| 174 |
|
|
|
|
| 175 |
# ------------------ Gradio UI -------------------------------
|
| 176 |
DEFAULT_PARAMS=json.dumps({"sigma":0.05},indent=2)
|
| 177 |
HELP_TEXT=("Schedule JSON examples:\n"
|
|
@@ -197,11 +221,14 @@ with gr.Blocks(title="RFT-Ω Total-Proof API") as demo:
|
|
| 197 |
run_btn=gr.Button("Run Deterministic Simulation & Sign Results")
|
| 198 |
out_json=gr.JSON(label="Signed Run Summary")
|
| 199 |
out_bundle=gr.File(label="Download Signed Bundle (zip)")
|
| 200 |
-
def _on_run(p,nd,st,sp_json,seed,samples):
|
| 201 |
-
|
|
|
|
|
|
|
| 202 |
outputs=[out_json,out_bundle])
|
| 203 |
gr.Markdown("Ops endpoints: `/healthz`, `/about` (FastAPI mounted if available).")
|
| 204 |
|
|
|
|
| 205 |
# ------------------ FastAPI Mount ---------------------------
|
| 206 |
if HAVE_FASTAPI:
|
| 207 |
api=FastAPI(title="RFT-Ω Total-Proof Ops")
|
|
@@ -213,9 +240,10 @@ if HAVE_FASTAPI:
|
|
| 213 |
else:
|
| 214 |
app=demo
|
| 215 |
|
|
|
|
| 216 |
# ------------------ Launch (stable queue) -------------------
|
| 217 |
if __name__=="__main__":
|
| 218 |
-
demo.queue(
|
| 219 |
server_name="0.0.0.0",
|
| 220 |
server_port=7860,
|
| 221 |
show_error=True,
|
|
|
|
| 1 |
# ============================================================
|
| 2 |
+
# RFT-Ω FRAMEWORK — TOTAL-PROOF API (Sprint 1, Stable Build)
|
| 3 |
# Author: Liam Grinstead (RFT Systems) | All Rights Reserved
|
| 4 |
# ============================================================
|
| 5 |
"""
|
| 6 |
Deterministic, signed validation harness for the
|
| 7 |
+
Rendered Frame Theory (RFT-Ω) harmonic-stability kernel.
|
| 8 |
"""
|
| 9 |
|
| 10 |
+
import os, json, time, hashlib, zipfile, random
|
| 11 |
from datetime import datetime
|
| 12 |
from typing import Dict, Any, List, Tuple
|
| 13 |
import numpy as np
|
|
|
|
| 19 |
except Exception:
|
| 20 |
HAVE_FASTAPI = False
|
| 21 |
|
| 22 |
+
|
| 23 |
# ------------------ About / Legal ---------------------------
|
| 24 |
RFT_VERSION = "v4.0-total-proof-stable"
|
| 25 |
RFT_DOI = "https://doi.org/10.5281/zenodo.17466722"
|
|
|
|
| 42 |
"legal": LEGAL_NOTICE,
|
| 43 |
}
|
| 44 |
|
| 45 |
+
|
| 46 |
+
# ------------------ Rate-limit ------------------------------
|
| 47 |
RUN_HISTORY_TS: List[float] = []
|
| 48 |
MAX_RUNS_PER_MINUTE = 60
|
| 49 |
|
|
|
|
| 56 |
RUN_HISTORY_TS.append(now)
|
| 57 |
return True, "ok"
|
| 58 |
|
| 59 |
+
|
| 60 |
# ------------------ Profiles / Simulation -------------------
|
| 61 |
PROFILES = {
|
| 62 |
"AI / Neural": {"base": (0.86, 0.80), "w": (0.65, 0.35)},
|
|
|
|
| 65 |
"Extreme Perturbation":{"base": (0.82, 0.77), "w": (0.50, 0.50)},
|
| 66 |
}
|
| 67 |
|
| 68 |
+
def _rng(seed:int)->np.random.RandomState:
|
| 69 |
+
return np.random.RandomState(seed)
|
| 70 |
|
| 71 |
def simulate_step(rng:np.random.RandomState, profile:str, sigma:float, noise_dist:str)->Dict[str,Any]:
|
| 72 |
base_q, base_z = PROFILES[profile]["base"]
|
|
|
|
| 80 |
q = float(np.clip(base_q + wq*q_noise, 0.0, 0.99))
|
| 81 |
z = float(np.clip(base_z + wz*z_noise, 0.0, 0.99))
|
| 82 |
variance = abs(q_noise)+abs(z_noise)
|
| 83 |
+
if variance > 0.15:
|
| 84 |
+
status="critical"
|
| 85 |
+
elif variance > 0.07:
|
| 86 |
+
status="perturbed"
|
| 87 |
+
else:
|
| 88 |
+
status="nominal"
|
| 89 |
return {"sigma": round(sigma,6),"QΩ":q,"ζ_sync":z,"status":status}
|
| 90 |
|
| 91 |
+
|
| 92 |
# ------------------ Schedules -------------------------------
|
| 93 |
def build_sigma_series(schedule_type:str, params:Dict[str,Any])->List[float]:
|
| 94 |
if schedule_type=="single":
|
| 95 |
return [float(params.get("sigma",0.05))]
|
| 96 |
elif schedule_type=="ramp":
|
| 97 |
+
return list(np.linspace(float(params.get("start",0.0)),
|
| 98 |
+
float(params.get("stop",0.3)),
|
| 99 |
+
int(params.get("steps",10))))
|
| 100 |
elif schedule_type=="random":
|
| 101 |
r = random.Random(int(params.get("seed",0)))
|
| 102 |
+
return [r.uniform(float(params.get("min",0.0)),
|
| 103 |
+
float(params.get("max",0.3)))
|
| 104 |
+
for _ in range(int(params.get("steps",10)))]
|
| 105 |
elif schedule_type=="impulse":
|
| 106 |
base,spike,at,steps = float(params.get("base",0.05)), float(params.get("spike",0.25)), int(params.get("at",5)), int(params.get("steps",10))
|
| 107 |
s=[base]*steps
|
|
|
|
| 115 |
return s
|
| 116 |
return [float(params.get("sigma",0.05))]
|
| 117 |
|
| 118 |
+
|
| 119 |
# ------------------ Integrity helpers -----------------------
|
| 120 |
+
def sha512_hex(s:str)->str:
|
| 121 |
+
return hashlib.sha512(s.encode()).hexdigest()
|
| 122 |
+
|
| 123 |
def make_run_id(seed:int,profile:str)->str:
|
| 124 |
+
raw=f"{time.time_ns()}::{seed}::{profile}::{random.random()}"
|
| 125 |
+
return hashlib.sha256(raw.encode()).hexdigest()[:16]
|
| 126 |
|
| 127 |
def write_bundle(run_dir:str,config:Dict[str,Any],results:Dict[str,Any])->Tuple[str,str]:
|
| 128 |
os.makedirs(run_dir,exist_ok=True)
|
| 129 |
+
with open(os.path.join(run_dir,"run.json"),"w") as f:
|
| 130 |
+
json.dump({"config":config,"results":results},f,indent=2)
|
| 131 |
canonical=json.dumps({"config":config,"results":results},sort_keys=True)
|
| 132 |
digest=sha512_hex(canonical)
|
| 133 |
+
with open(os.path.join(run_dir,"run.sha512"),"w") as f:
|
| 134 |
+
f.write(digest+"\n")
|
| 135 |
+
with open(os.path.join(run_dir,"ABOUT.json"),"w") as f:
|
| 136 |
+
json.dump(ABOUT_BLOCK,f,indent=2)
|
| 137 |
+
with open(os.path.join(run_dir,"NOTICE.txt"),"w") as f:
|
| 138 |
+
f.write(LEGAL_NOTICE+"\n")
|
| 139 |
zip_path=os.path.join(run_dir,"rft_run_bundle.zip")
|
| 140 |
with zipfile.ZipFile(zip_path,"w",zipfile.ZIP_DEFLATED) as z:
|
| 141 |
for fn in ["run.json","run.sha512","ABOUT.json","NOTICE.txt"]:
|
| 142 |
z.write(os.path.join(run_dir,fn),arcname=fn)
|
| 143 |
return zip_path,digest
|
| 144 |
|
| 145 |
+
|
| 146 |
# ------------------ Core runner -----------------------------
|
| 147 |
def run_total_proof(profile,noise_dist,schedule_type,schedule_params_text,seed,samples):
|
| 148 |
ok,msg=_rate_limit_ok()
|
| 149 |
+
if not ok:
|
| 150 |
+
return {"error":msg,"rft_notice":LEGAL_NOTICE},None
|
| 151 |
try:
|
| 152 |
params=json.loads(schedule_params_text) if schedule_params_text.strip() else {}
|
| 153 |
if not isinstance(params,dict): raise ValueError
|
| 154 |
except Exception as e:
|
| 155 |
return {"error":f"Invalid schedule_params JSON: {e}","rft_notice":LEGAL_NOTICE},None
|
| 156 |
+
|
| 157 |
sigma_series=build_sigma_series(schedule_type,params)
|
| 158 |
rng_master=_rng(seed)
|
| 159 |
results_steps=[]; trigger_count=0
|
|
|
|
| 195 |
"rft_notice":LEGAL_NOTICE}
|
| 196 |
return {"config":config,"head":head,"results":results},zip_path
|
| 197 |
|
| 198 |
+
|
| 199 |
# ------------------ Gradio UI -------------------------------
|
| 200 |
DEFAULT_PARAMS=json.dumps({"sigma":0.05},indent=2)
|
| 201 |
HELP_TEXT=("Schedule JSON examples:\n"
|
|
|
|
| 221 |
run_btn=gr.Button("Run Deterministic Simulation & Sign Results")
|
| 222 |
out_json=gr.JSON(label="Signed Run Summary")
|
| 223 |
out_bundle=gr.File(label="Download Signed Bundle (zip)")
|
| 224 |
+
def _on_run(p,nd,st,sp_json,seed,samples):
|
| 225 |
+
return run_total_proof(p,nd,st,sp_json,int(seed),int(samples))
|
| 226 |
+
run_btn.click(_on_run,
|
| 227 |
+
inputs=[profile,noise_dist,schedule_type,schedule_params,seed_in,samples_in],
|
| 228 |
outputs=[out_json,out_bundle])
|
| 229 |
gr.Markdown("Ops endpoints: `/healthz`, `/about` (FastAPI mounted if available).")
|
| 230 |
|
| 231 |
+
|
| 232 |
# ------------------ FastAPI Mount ---------------------------
|
| 233 |
if HAVE_FASTAPI:
|
| 234 |
api=FastAPI(title="RFT-Ω Total-Proof Ops")
|
|
|
|
| 240 |
else:
|
| 241 |
app=demo
|
| 242 |
|
| 243 |
+
|
| 244 |
# ------------------ Launch (stable queue) -------------------
|
| 245 |
if __name__=="__main__":
|
| 246 |
+
demo.queue().launch(
|
| 247 |
server_name="0.0.0.0",
|
| 248 |
server_port=7860,
|
| 249 |
show_error=True,
|