Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -185,17 +185,14 @@ def _extract_json_from_text(text: str) -> str:
|
|
| 185 |
if not text:
|
| 186 |
return ""
|
| 187 |
|
| 188 |
-
# 1. First, search for explicit markdown blocks
|
| 189 |
blocks = re.findall(r'```(?:json)?\s*(\{.*?\})\s*```', text, re.DOTALL | re.IGNORECASE)
|
| 190 |
for b in blocks:
|
| 191 |
cleaned = b.strip()
|
| 192 |
-
# Verify it looks like our AXL/Collapser schema
|
| 193 |
if any(k in cleaned for k in ['"variables"', '"constraints"', '"hypothesis_markdown"', '"name"']):
|
| 194 |
return cleaned
|
| 195 |
if blocks:
|
| 196 |
return blocks[0].strip()
|
| 197 |
|
| 198 |
-
# 2. Scope-matching parser to isolate valid candidates
|
| 199 |
candidates = []
|
| 200 |
for match in re.finditer(r'\{', text):
|
| 201 |
start_idx = match.start()
|
|
@@ -209,20 +206,17 @@ def _extract_json_from_text(text: str) -> str:
|
|
| 209 |
candidates.append(text[start_idx:i+1])
|
| 210 |
break
|
| 211 |
|
| 212 |
-
# Prioritize candidates containing key schema elements
|
| 213 |
for cand in candidates:
|
| 214 |
cleaned = cand.strip()
|
| 215 |
if any(k in cleaned for k in ['"variables"', '"constraints"', '"hypothesis_markdown"', '"name"']):
|
| 216 |
return cleaned
|
| 217 |
|
| 218 |
-
# Fallback to the largest bracket scope
|
| 219 |
if candidates:
|
| 220 |
return max(candidates, key=len).strip()
|
| 221 |
|
| 222 |
return text
|
| 223 |
|
| 224 |
def call_external_ai(url: str, model: str, system_prompt: str, prompt: str) -> str:
|
| 225 |
-
"""Interfaces with the external Express.js server."""
|
| 226 |
url = url.rstrip("/")
|
| 227 |
try:
|
| 228 |
res = requests.post(f"{url}/api/chats", timeout=10)
|
|
@@ -269,7 +263,7 @@ def encode_problem(text: str, api_key: str, use_ext: bool, ext_url: str, ext_mod
|
|
| 269 |
|
| 270 |
raw = raw.strip()
|
| 271 |
if not raw:
|
| 272 |
-
raise ValueError("The AI model returned an empty response.
|
| 273 |
|
| 274 |
json_str = _extract_json_from_text(raw)
|
| 275 |
if not json_str:
|
|
@@ -320,49 +314,8 @@ def collapse_solution(payload: dict, api_key: str, use_ext: bool, ext_url: str,
|
|
| 320 |
return f"JSON Decode Error from Collapser: {e}\n\nRaw Output:\n{raw}"
|
| 321 |
|
| 322 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 323 |
-
# SECTION 4: THE ORCHESTRATOR LOOP
|
| 324 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 325 |
-
def quick_solver_callback(axl_def: AXLProblemDef, N: int) -> Dict[str, float]:
|
| 326 |
-
try:
|
| 327 |
-
prob = build_core_problem(axl_def)
|
| 328 |
-
int_vars = [v for v in prob.variables if v in prob.int_vars
|
| 329 |
-
and math.isfinite(prob.bounds[v][0])
|
| 330 |
-
and prob.bounds[v][1] - prob.bounds[v][0] <= 100]
|
| 331 |
-
|
| 332 |
-
if int_vars:
|
| 333 |
-
grids = []
|
| 334 |
-
for v in int_vars:
|
| 335 |
-
lo = int(math.ceil(prob.bounds[v][0]))
|
| 336 |
-
hi = int(math.floor(prob.bounds[v][1]))
|
| 337 |
-
grids.append([(v, float(val)) for val in range(lo, hi+1)])
|
| 338 |
-
|
| 339 |
-
import itertools
|
| 340 |
-
for combo in itertools.product(*grids):
|
| 341 |
-
pinned = dict(combo)
|
| 342 |
-
resolved, _ = core.algebraic_propagate_pinned(prob, pinned)
|
| 343 |
-
ok, msg = oracle.ground_truth_verify(resolved, N)
|
| 344 |
-
if ok: return resolved
|
| 345 |
-
else:
|
| 346 |
-
if 't' in prob.variables:
|
| 347 |
-
lo, hi = prob.bounds['t']
|
| 348 |
-
for t_val in range(max(2, int(lo)), min(100, int(hi)) + 1):
|
| 349 |
-
pinned = {'t': float(t_val)}
|
| 350 |
-
resolved, _ = core.algebraic_propagate_pinned(prob, pinned)
|
| 351 |
-
ok, msg = oracle.ground_truth_verify(resolved, N)
|
| 352 |
-
if ok: return resolved
|
| 353 |
-
if 's' in prob.variables and 'd' in prob.variables:
|
| 354 |
-
lo_s, hi_s = prob.bounds['s']
|
| 355 |
-
lo_d, hi_d = prob.bounds['d']
|
| 356 |
-
for s_val in range(max(2, int(lo_s)), min(200, int(hi_s)) + 1, 2):
|
| 357 |
-
for d_val in range(max(0, int(lo_d)), min(100, int(hi_d)) + 1, 2):
|
| 358 |
-
pinned = {'s': float(s_val), 'd': float(d_val)}
|
| 359 |
-
resolved, _ = core.algebraic_propagate_pinned(prob, pinned)
|
| 360 |
-
ok, msg = oracle.ground_truth_verify(resolved, N)
|
| 361 |
-
if ok: return resolved
|
| 362 |
-
return {}
|
| 363 |
-
except Exception as e:
|
| 364 |
-
print(f"Quick solver callback error: {e}")
|
| 365 |
-
return {}
|
| 366 |
|
| 367 |
def global_solve_task(original_text: str, api_key: str, template_name: str = None,
|
| 368 |
use_ext: bool = False, ext_url: str = "", ext_model: str = ""):
|
|
@@ -385,56 +338,43 @@ def global_solve_task(original_text: str, api_key: str, template_name: str = Non
|
|
| 385 |
if axl_def.minimize_var: _add_log(f" MINIMIZE: {axl_def.minimize_var}")
|
| 386 |
|
| 387 |
is_factorization = any(v['name'] in ['p', 'q', 't', 's', 'd'] for v in axl_def.variables)
|
| 388 |
-
preflight_passed = True
|
| 389 |
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
init_b, init_ce
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
)
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
)
|
| 417 |
-
|
| 418 |
-
_add_log(f"Deduction Engine Complete. Best CE = {ce:.6f}")
|
| 419 |
-
g1_pass = ce < core.SOLVE_THRESHOLD
|
| 420 |
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
_add_log(f"GROUND TRUTH: {gt_msg}")
|
| 427 |
-
|
| 428 |
-
if not gt_passed:
|
| 429 |
-
failure_type = adv.failure_taxonomy(binding, N_target, ce)
|
| 430 |
-
_update_state(infeasibility_report=f"GROUND TRUTH FAILED: {gt_msg}\nTaxonomy: {failure_type}")
|
| 431 |
-
g2_pass = False
|
| 432 |
-
|
| 433 |
-
_update_state(phase="COLLAPSING", best_ce=ce if preflight_passed else 0)
|
| 434 |
|
| 435 |
payload = {
|
| 436 |
-
"solved": g1_pass and g2_pass
|
| 437 |
-
"raw_binding": {k: core.safe_round(v, 4) for k, v in binding.items()}
|
| 438 |
"infeasibility_report": GLOBAL_SOLVE_STATE["infeasibility_report"]
|
| 439 |
}
|
| 440 |
|
|
@@ -586,7 +526,6 @@ with gr.Blocks(title="Practicality 28.0") as demo:
|
|
| 586 |
ui_timer.tick(fn=fetch_dashboard, inputs=[dash_cache], outputs=[live_html, dash_cache])
|
| 587 |
ui_timer.tick(fn=fetch_answers, inputs=[ans_cache], outputs=[ans_box, raw_box, ans_cache])
|
| 588 |
|
| 589 |
-
# Event handlers routed cleanly
|
| 590 |
solve_btn.click(fn=handle_solve, inputs=[prob_input, api_key_input, use_ext_toggle, ext_url_input, ext_model_dropdown, ans_cache], outputs=[ans_cache])
|
| 591 |
hyp_solve_btn.click(fn=handle_hyp_solve, inputs=[hyp_dropdown, api_key_input, use_ext_toggle, ext_url_input, ext_model_dropdown, ans_cache], outputs=[ans_cache])
|
| 592 |
q_btn.click(fn=handle_q_run, inputs=[ans_cache], outputs=[ans_cache])
|
|
|
|
| 185 |
if not text:
|
| 186 |
return ""
|
| 187 |
|
|
|
|
| 188 |
blocks = re.findall(r'```(?:json)?\s*(\{.*?\})\s*```', text, re.DOTALL | re.IGNORECASE)
|
| 189 |
for b in blocks:
|
| 190 |
cleaned = b.strip()
|
|
|
|
| 191 |
if any(k in cleaned for k in ['"variables"', '"constraints"', '"hypothesis_markdown"', '"name"']):
|
| 192 |
return cleaned
|
| 193 |
if blocks:
|
| 194 |
return blocks[0].strip()
|
| 195 |
|
|
|
|
| 196 |
candidates = []
|
| 197 |
for match in re.finditer(r'\{', text):
|
| 198 |
start_idx = match.start()
|
|
|
|
| 206 |
candidates.append(text[start_idx:i+1])
|
| 207 |
break
|
| 208 |
|
|
|
|
| 209 |
for cand in candidates:
|
| 210 |
cleaned = cand.strip()
|
| 211 |
if any(k in cleaned for k in ['"variables"', '"constraints"', '"hypothesis_markdown"', '"name"']):
|
| 212 |
return cleaned
|
| 213 |
|
|
|
|
| 214 |
if candidates:
|
| 215 |
return max(candidates, key=len).strip()
|
| 216 |
|
| 217 |
return text
|
| 218 |
|
| 219 |
def call_external_ai(url: str, model: str, system_prompt: str, prompt: str) -> str:
|
|
|
|
| 220 |
url = url.rstrip("/")
|
| 221 |
try:
|
| 222 |
res = requests.post(f"{url}/api/chats", timeout=10)
|
|
|
|
| 263 |
|
| 264 |
raw = raw.strip()
|
| 265 |
if not raw:
|
| 266 |
+
raise ValueError("The AI model returned an empty response.")
|
| 267 |
|
| 268 |
json_str = _extract_json_from_text(raw)
|
| 269 |
if not json_str:
|
|
|
|
| 314 |
return f"JSON Decode Error from Collapser: {e}\n\nRaw Output:\n{raw}"
|
| 315 |
|
| 316 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 317 |
+
# SECTION 4: THE ORCHESTRATOR LOOP (Adversary Pre-Flight Removed)
|
| 318 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 319 |
|
| 320 |
def global_solve_task(original_text: str, api_key: str, template_name: str = None,
|
| 321 |
use_ext: bool = False, ext_url: str = "", ext_model: str = ""):
|
|
|
|
| 338 |
if axl_def.minimize_var: _add_log(f" MINIMIZE: {axl_def.minimize_var}")
|
| 339 |
|
| 340 |
is_factorization = any(v['name'] in ['p', 'q', 't', 's', 'd'] for v in axl_def.variables)
|
|
|
|
| 341 |
|
| 342 |
+
_update_state(phase="RAY TRACING")
|
| 343 |
+
base_prob = build_core_problem(axl_def)
|
| 344 |
+
|
| 345 |
+
init_b, init_ce = axioms._mprt_sample(base_prob, 1000)
|
| 346 |
+
_add_log("Searching continuous relaxation...")
|
| 347 |
+
|
| 348 |
+
templates = axioms.generate_templates(base_prob, axioms.compute_sketch(base_prob))
|
| 349 |
+
|
| 350 |
+
tracer = axioms.SequenceRayTracer(
|
| 351 |
+
log_callback=_add_log,
|
| 352 |
+
update_state_callback=lambda **kwargs: _update_state(**kwargs)
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
binding, ce, traces, best_ray_name = tracer.trace(
|
| 356 |
+
base_prob, init_b, init_ce, templates, max_rays=1500
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
_add_log(f"Deduction Engine Complete. Best CE = {ce:.6f}")
|
| 360 |
+
g1_pass = ce < core.SOLVE_THRESHOLD
|
| 361 |
+
|
| 362 |
+
g2_pass = True
|
| 363 |
+
if is_factorization and len(axl_def.observations) > 0:
|
| 364 |
+
N_target = int(list(axl_def.observations.values())[0])
|
| 365 |
+
# Call ground_truth_verify via the oracle module import
|
| 366 |
+
gt_passed, gt_msg = oracle.ground_truth_verify(binding, N_target)
|
| 367 |
+
_add_log(f"GROUND TRUTH: {gt_msg}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 368 |
|
| 369 |
+
if not gt_passed:
|
| 370 |
+
_update_state(infeasibility_report=f"GROUND TRUTH FAILED: {gt_msg}")
|
| 371 |
+
g2_pass = False
|
| 372 |
+
|
| 373 |
+
_update_state(phase="COLLAPSING", best_ce=ce)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 374 |
|
| 375 |
payload = {
|
| 376 |
+
"solved": g1_pass and g2_pass,
|
| 377 |
+
"raw_binding": {k: core.safe_round(v, 4) for k, v in binding.items()},
|
| 378 |
"infeasibility_report": GLOBAL_SOLVE_STATE["infeasibility_report"]
|
| 379 |
}
|
| 380 |
|
|
|
|
| 526 |
ui_timer.tick(fn=fetch_dashboard, inputs=[dash_cache], outputs=[live_html, dash_cache])
|
| 527 |
ui_timer.tick(fn=fetch_answers, inputs=[ans_cache], outputs=[ans_box, raw_box, ans_cache])
|
| 528 |
|
|
|
|
| 529 |
solve_btn.click(fn=handle_solve, inputs=[prob_input, api_key_input, use_ext_toggle, ext_url_input, ext_model_dropdown, ans_cache], outputs=[ans_cache])
|
| 530 |
hyp_solve_btn.click(fn=handle_hyp_solve, inputs=[hyp_dropdown, api_key_input, use_ext_toggle, ext_url_input, ext_model_dropdown, ans_cache], outputs=[ans_cache])
|
| 531 |
q_btn.click(fn=handle_q_run, inputs=[ans_cache], outputs=[ans_cache])
|