Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
-
PRACTICALITY SYSTEM 28.0 β MODULAR
|
| 4 |
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 5 |
Architecture:
|
| 6 |
- practicality_core.py : Tensor Math, Interval Arithmetic, Adam Optimizer
|
|
@@ -10,7 +10,7 @@ Architecture:
|
|
| 10 |
"""
|
| 11 |
|
| 12 |
import os, time, threading, json, re, textwrap, copy
|
| 13 |
-
import traceback, html
|
| 14 |
from collections import deque, defaultdict
|
| 15 |
from typing import Dict, List, Tuple, Any, Optional, Set
|
| 16 |
from dataclasses import dataclass, field
|
|
@@ -27,7 +27,7 @@ import practicality_axioms as axioms
|
|
| 27 |
import practicality_oracle as oracle
|
| 28 |
|
| 29 |
DEFAULT_GEMINI_API_KEY = os.environ.get("AI_Key", "")
|
| 30 |
-
GEMINI_MODEL = "gemini-
|
| 31 |
|
| 32 |
print(f"[SYSTEM 28.0] Orchestrator Initialized. Compute: {core.DEVICE.type.upper()}")
|
| 33 |
|
|
@@ -158,9 +158,14 @@ def build_core_problem(axl_def: AXLProblemDef) -> core.Problem:
|
|
| 158 |
|
| 159 |
var_names = list(bounds.keys())
|
| 160 |
compiled_constraints = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
for c in axl_def.constraints:
|
| 162 |
-
|
| 163 |
-
|
| 164 |
compiled_constraints.append(mc)
|
| 165 |
|
| 166 |
prob = core.Problem(
|
|
@@ -222,13 +227,51 @@ def collapse_solution(payload: dict, api_key: str) -> str:
|
|
| 222 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 223 |
# SECTION 4: THE ORCHESTRATOR LOOP
|
| 224 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
|
|
|
| 225 |
def quick_solver_callback(axl_def: AXLProblemDef, N: int) -> Dict[str, float]:
|
| 226 |
try:
|
| 227 |
prob = build_core_problem(axl_def)
|
| 228 |
-
|
| 229 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 230 |
except Exception as e:
|
| 231 |
-
|
| 232 |
return {}
|
| 233 |
|
| 234 |
def global_solve_task(original_text: str, api_key: str, template_name: str = None):
|
|
@@ -267,21 +310,25 @@ def global_solve_task(original_text: str, api_key: str, template_name: str = Non
|
|
| 267 |
if preflight_passed:
|
| 268 |
_update_state(phase="RAY TRACING")
|
| 269 |
base_prob = build_core_problem(axl_def)
|
|
|
|
|
|
|
| 270 |
init_b, init_ce = axioms._mprt_sample(base_prob, 1000)
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 274 |
)
|
| 275 |
|
| 276 |
-
|
| 277 |
-
|
|
|
|
| 278 |
|
| 279 |
-
|
| 280 |
-
binding, ce, _, _ = results[0]
|
| 281 |
-
else:
|
| 282 |
-
binding, ce = init_b, init_ce
|
| 283 |
-
|
| 284 |
-
_add_log(f"Descent Complete. Final CE = {ce:.6f}")
|
| 285 |
g1_pass = ce < core.SOLVE_THRESHOLD
|
| 286 |
|
| 287 |
g2_pass = True
|
|
@@ -314,7 +361,6 @@ def global_solve_task(original_text: str, api_key: str, template_name: str = Non
|
|
| 314 |
error_msg = f"π₯ FATAL ERROR ({type(e).__name__}): {str(e)}"
|
| 315 |
_add_log(error_msg)
|
| 316 |
|
| 317 |
-
# Display the full traceback nicely in the answer box
|
| 318 |
md_error = f"## π₯ SYSTEM CRASH\n\n**Error Type:** `{type(e).__name__}`\n**Message:** {str(e)}\n\n### Traceback\n```python\n{tb_str}\n```"
|
| 319 |
_update_state(phase="ERROR", answer=md_error)
|
| 320 |
|
|
@@ -329,15 +375,14 @@ def trigger_hyp_solve(template_name, api_key):
|
|
| 329 |
if GLOBAL_SOLVE_STATE["is_running"]: return
|
| 330 |
threading.Thread(target=global_solve_task, args=("", api_key, template_name), daemon=True).start()
|
| 331 |
|
|
|
|
| 332 |
def run_quantum_demo():
|
| 333 |
_update_state(is_running=True, phase="QUANTUM SIMULATION", answer="Running Physics Simulator...\nCheck console for output.", high_level_logs=[])
|
| 334 |
def _run():
|
| 335 |
try:
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
qh.run_shors_demo(35)
|
| 340 |
-
qh.benchmark_heisenberg_vs_schrodinger(20)
|
| 341 |
_update_state(phase="DONE", answer="Quantum simulation complete. Output logged to console.")
|
| 342 |
except Exception as e:
|
| 343 |
tb_str = traceback.format_exc()
|
|
@@ -371,9 +416,7 @@ def build_live_html():
|
|
| 371 |
|
| 372 |
log_html = "<ul style='margin:0;padding-left:20px;color:#aaa;font-size:0.82em'>"
|
| 373 |
for l in logs[-15:]:
|
| 374 |
-
# Escape HTML to prevent broken formatting on tracebacks
|
| 375 |
safe_l = html.escape(str(l)).replace('\n', '<br>')
|
| 376 |
-
# Highlight fatal errors in red
|
| 377 |
if "FATAL ERROR" in safe_l or "CRASH" in safe_l:
|
| 378 |
log_html += f"<li style='margin-bottom:4px;color:#FF6B6B;font-weight:bold;'>{safe_l}</li>"
|
| 379 |
else:
|
|
@@ -470,5 +513,4 @@ with gr.Blocks(title="Practicality 28.0") as demo:
|
|
| 470 |
q_btn.click(fn=handle_q_run, inputs=[ans_cache], outputs=[ans_cache])
|
| 471 |
|
| 472 |
if __name__ == "__main__":
|
| 473 |
-
# CSS properly initialized inside launch()
|
| 474 |
demo.launch(server_name="0.0.0.0", server_port=7860, share=False, css=CSS)
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
+
PRACTICALITY SYSTEM 28.0 β MODULAR ORACLE ENGINE
|
| 4 |
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 5 |
Architecture:
|
| 6 |
- practicality_core.py : Tensor Math, Interval Arithmetic, Adam Optimizer
|
|
|
|
| 10 |
"""
|
| 11 |
|
| 12 |
import os, time, threading, json, re, textwrap, copy
|
| 13 |
+
import traceback, html, itertools, math
|
| 14 |
from collections import deque, defaultdict
|
| 15 |
from typing import Dict, List, Tuple, Any, Optional, Set
|
| 16 |
from dataclasses import dataclass, field
|
|
|
|
| 27 |
import practicality_oracle as oracle
|
| 28 |
|
| 29 |
DEFAULT_GEMINI_API_KEY = os.environ.get("AI_Key", "")
|
| 30 |
+
GEMINI_MODEL = "gemini-2.5-flash"
|
| 31 |
|
| 32 |
print(f"[SYSTEM 28.0] Orchestrator Initialized. Compute: {core.DEVICE.type.upper()}")
|
| 33 |
|
|
|
|
| 158 |
|
| 159 |
var_names = list(bounds.keys())
|
| 160 |
compiled_constraints = []
|
| 161 |
+
|
| 162 |
+
# Bug 2 Fix: Safe, mathematically accurate EQ/GEQ/LEQ kinds translation
|
| 163 |
+
kind_map = {'EQ': 'equality', 'GEQ': 'inequality', 'LEQ': 'inequality'}
|
| 164 |
+
dir_map = {'EQ': 'eq', 'GEQ': 'geq', 'LEQ': 'leq'}
|
| 165 |
+
|
| 166 |
for c in axl_def.constraints:
|
| 167 |
+
k = c['kind'].upper()
|
| 168 |
+
mc = core.compile_mc(kind_map[k], c['expr'], dir_map[k], var_names, c.get('weight', 1.0))
|
| 169 |
compiled_constraints.append(mc)
|
| 170 |
|
| 171 |
prob = core.Problem(
|
|
|
|
| 227 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 228 |
# SECTION 4: THE ORCHESTRATOR LOOP
|
| 229 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 230 |
+
|
| 231 |
+
# Bug 1 Fix: Explicit, exact integer-propagation solve callback
|
| 232 |
def quick_solver_callback(axl_def: AXLProblemDef, N: int) -> Dict[str, float]:
|
| 233 |
try:
|
| 234 |
prob = build_core_problem(axl_def)
|
| 235 |
+
|
| 236 |
+
# Pull integer vars bounded up to width 100
|
| 237 |
+
int_vars = [v for v in prob.variables if v in prob.int_vars
|
| 238 |
+
and math.isfinite(prob.bounds[v][0])
|
| 239 |
+
and prob.bounds[v][1] - prob.bounds[v][0] <= 100]
|
| 240 |
+
|
| 241 |
+
if int_vars:
|
| 242 |
+
grids = []
|
| 243 |
+
for v in int_vars:
|
| 244 |
+
lo = int(math.ceil(prob.bounds[v][0]))
|
| 245 |
+
hi = int(math.floor(prob.bounds[v][1]))
|
| 246 |
+
grids.append([(v, float(val)) for val in range(lo, hi+1)])
|
| 247 |
+
|
| 248 |
+
for combo in itertools.product(*grids):
|
| 249 |
+
pinned = dict(combo)
|
| 250 |
+
resolved, _ = core.algebraic_propagate_pinned(prob, pinned)
|
| 251 |
+
ok, msg = oracle.ground_truth_verify(resolved, N)
|
| 252 |
+
if ok: return resolved
|
| 253 |
+
else:
|
| 254 |
+
# 1D single-parameter search (e.g. 1D Sine Snap)
|
| 255 |
+
if 't' in prob.variables:
|
| 256 |
+
lo, hi = prob.bounds['t']
|
| 257 |
+
for t_val in range(max(2, int(lo)), min(100, int(hi)) + 1):
|
| 258 |
+
pinned = {'t': float(t_val)}
|
| 259 |
+
resolved, _ = core.algebraic_propagate_pinned(prob, pinned)
|
| 260 |
+
ok, msg = oracle.ground_truth_verify(resolved, N)
|
| 261 |
+
if ok: return resolved
|
| 262 |
+
# s, d Fermat grid search
|
| 263 |
+
if 's' in prob.variables and 'd' in prob.variables:
|
| 264 |
+
lo_s, hi_s = prob.bounds['s']
|
| 265 |
+
lo_d, hi_d = prob.bounds['d']
|
| 266 |
+
for s_val in range(max(2, int(lo_s)), min(200, int(hi_s)) + 1, 2):
|
| 267 |
+
for d_val in range(max(0, int(lo_d)), min(100, int(hi_d)) + 1, 2):
|
| 268 |
+
pinned = {'s': float(s_val), 'd': float(d_val)}
|
| 269 |
+
resolved, _ = core.algebraic_propagate_pinned(prob, pinned)
|
| 270 |
+
ok, msg = oracle.ground_truth_verify(resolved, N)
|
| 271 |
+
if ok: return resolved
|
| 272 |
+
return {}
|
| 273 |
except Exception as e:
|
| 274 |
+
print(f"Quick solver callback error: {e}")
|
| 275 |
return {}
|
| 276 |
|
| 277 |
def global_solve_task(original_text: str, api_key: str, template_name: str = None):
|
|
|
|
| 310 |
if preflight_passed:
|
| 311 |
_update_state(phase="RAY TRACING")
|
| 312 |
base_prob = build_core_problem(axl_def)
|
| 313 |
+
|
| 314 |
+
# Setup initial seeds & execute exhaustive templates
|
| 315 |
init_b, init_ce = axioms._mprt_sample(base_prob, 1000)
|
| 316 |
+
_add_log("Searching continuous relaxation...")
|
| 317 |
+
|
| 318 |
+
templates = axioms.generate_templates(base_prob, axioms.compute_sketch(base_prob))
|
| 319 |
+
_add_log(f"Assembled {len(templates)} integer grid mappings.")
|
| 320 |
+
|
| 321 |
+
# Restoring full 27.7 Ray Tracer engine with bandit feedback & batons
|
| 322 |
+
tracer = axioms.SequenceRayTracer(
|
| 323 |
+
log_callback=_add_log,
|
| 324 |
+
update_state_callback=lambda **kwargs: _update_state(**kwargs)
|
| 325 |
)
|
| 326 |
|
| 327 |
+
binding, ce, traces, best_ray_name = tracer.trace(
|
| 328 |
+
base_prob, init_b, init_ce, templates, max_rays=1500
|
| 329 |
+
)
|
| 330 |
|
| 331 |
+
_add_log(f"Deduction Engine Complete. Best CE = {ce:.6f}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 332 |
g1_pass = ce < core.SOLVE_THRESHOLD
|
| 333 |
|
| 334 |
g2_pass = True
|
|
|
|
| 361 |
error_msg = f"π₯ FATAL ERROR ({type(e).__name__}): {str(e)}"
|
| 362 |
_add_log(error_msg)
|
| 363 |
|
|
|
|
| 364 |
md_error = f"## π₯ SYSTEM CRASH\n\n**Error Type:** `{type(e).__name__}`\n**Message:** {str(e)}\n\n### Traceback\n```python\n{tb_str}\n```"
|
| 365 |
_update_state(phase="ERROR", answer=md_error)
|
| 366 |
|
|
|
|
| 375 |
if GLOBAL_SOLVE_STATE["is_running"]: return
|
| 376 |
threading.Thread(target=global_solve_task, args=("", api_key, template_name), daemon=True).start()
|
| 377 |
|
| 378 |
+
# Bug 3 Fix: Shors Demo imports directly from oracle without ModuleNotFoundError
|
| 379 |
def run_quantum_demo():
|
| 380 |
_update_state(is_running=True, phase="QUANTUM SIMULATION", answer="Running Physics Simulator...\nCheck console for output.", high_level_logs=[])
|
| 381 |
def _run():
|
| 382 |
try:
|
| 383 |
+
oracle.run_shors_demo(15)
|
| 384 |
+
oracle.run_shors_demo(35)
|
| 385 |
+
oracle.benchmark_heisenberg_vs_schrodinger(20)
|
|
|
|
|
|
|
| 386 |
_update_state(phase="DONE", answer="Quantum simulation complete. Output logged to console.")
|
| 387 |
except Exception as e:
|
| 388 |
tb_str = traceback.format_exc()
|
|
|
|
| 416 |
|
| 417 |
log_html = "<ul style='margin:0;padding-left:20px;color:#aaa;font-size:0.82em'>"
|
| 418 |
for l in logs[-15:]:
|
|
|
|
| 419 |
safe_l = html.escape(str(l)).replace('\n', '<br>')
|
|
|
|
| 420 |
if "FATAL ERROR" in safe_l or "CRASH" in safe_l:
|
| 421 |
log_html += f"<li style='margin-bottom:4px;color:#FF6B6B;font-weight:bold;'>{safe_l}</li>"
|
| 422 |
else:
|
|
|
|
| 513 |
q_btn.click(fn=handle_q_run, inputs=[ans_cache], outputs=[ans_cache])
|
| 514 |
|
| 515 |
if __name__ == "__main__":
|
|
|
|
| 516 |
demo.launch(server_name="0.0.0.0", server_port=7860, share=False, css=CSS)
|