chronoswarm / app.py
Tasosh's picture
Deploy ChronoSwarm Gradio app
6c7898e verified
Raw History Blame Contribute Delete
9.86 kB
"""Gradio front end for ChronoSwarm.
Deploy notes
------------
* Put the `chronoswarm/` package directory at the root of the Space, next to
this file, so `import chronoswarm` resolves without an install step.
* The fallback executor is used deliberately (`force_fallback=True`). It is not
a degraded mode - `test_fallback_executor_matches_langgraph` asserts identical
results - but unlike LangGraph it passes and returns the *same* state dict, so
the nodes mutate it in place and this file can poll `state["log"]` from
another thread to stream progress. With real LangGraph the outer reference
never updates and the log would stay empty until the run finished.
* No API key is set, so every LLM-backed agent runs its deterministic shadow.
The swarm is fully functional this way; see `chronoswarm/llm.py`.
* Spaces storage is ephemeral. Runs go to a temp directory and are handed back
as a zip; nothing is expected to survive a restart.
"""
from __future__ import annotations
import html
import os
import shutil
import socket
import sys
import tempfile
import threading
import traceback
from pathlib import Path
ROOT = Path(__file__).resolve().parent
PACKAGE_ROOT = ROOT / "chronoswarm"
if PACKAGE_ROOT.exists():
sys.path.insert(0, str(PACKAGE_ROOT))
import gradio as gr
from chronoswarm.dynamics import PROCESS_LIST
from chronoswarm.emit import emit_run
from chronoswarm.gallery import write_gallery
from chronoswarm.graph import build_graph, initial_state
from chronoswarm.schema import SwarmConfig, record_summary
# Free CPU Spaces are 2 vCPU. These ceilings keep a run inside a couple of
# minutes; the defaults keep it under one.
MAX_GENERATIONS = 14
MAX_POPULATION = 44
POLL_SECONDS = 0.4
def embed_gallery(path: str) -> str:
"""Inline the gallery in an iframe via `srcdoc`.
gr.HTML does not reliably execute inline <script>, so pasting the gallery
body in directly gives a static page with no animation. An iframe gets its
own document and origin, and the gallery is self-contained by design.
`srcdoc` rather than a `data:` URI: both work today, but browsers have
repeatedly tightened policy around `data:` documents, and srcdoc has no
such history. The cost is HTML-escaping ~75 KB, which is nothing.
"""
with open(path, encoding="utf-8") as f:
doc = f.read()
return (
f'<iframe srcdoc="{html.escape(doc, quote=True)}" '
'style="width:100%;height:78vh;border:1px solid var(--border-color-primary);'
'border-radius:10px;background:transparent" '
'sandbox="allow-scripts"></iframe>'
)
def results_table(state: dict) -> str:
rows = [
"| cell | archetype | process | fitness | recovery | proc. eff. | recipe fit | buildability |",
"|---|---|---|---|---|---|---|---|",
]
for r in state["release"]:
s = record_summary(r)
rows.append(
f"| `{s['gid']}` | {s['archetype']} | {s['process'].replace('_',' ')} | "
f"{s['fitness']:.3f} | {s['recovery']:.3f} | {s['proc_eff']:.3f} | "
f"{s['recipe_fit']:.3f} | {s['mfg']:.2f} |"
)
b = state["ledger"].stats()
c = state["cache"].stats()
a = state["archive"].stats()
rows += [
"",
f"**{b['spent']:.0f} / {b['budget']:.0f} credit units** in {b['wall_s']:.1f} s &nbsp;·&nbsp; "
f"cache hit rate {c['hit_rate']:.0%} ({c['units_saved']:.0f} units saved) &nbsp;·&nbsp; "
f"archive {a['cells_filled']} niches, QD score {a['qd_score']:.2f}",
"",
"Spend by stage: " + ", ".join(f"`{k}` {v:.0f}u" for k, v in b["by_stage"].items()),
]
return "\n".join(rows)
def evolve(generations, population, elites, seed, budget, processes,
progress=gr.Progress()):
"""Streaming generator. Yields (log, results, gallery, zip) on every poll."""
if not processes:
yield "Pick at least one process.", "", "", None
return
generations = int(min(generations, MAX_GENERATIONS))
population = int(min(population, MAX_POPULATION))
elites = int(min(elites, max(2, population // 3)))
out_dir = tempfile.mkdtemp(prefix="chronoswarm-")
run_dir = os.path.join(out_dir, "run")
cfg = SwarmConfig(
generations=generations,
population=population,
elites=elites,
seed=int(seed),
budget_units=float(budget),
llm_per_generation=0, # no API key on the Space; shadows only
processes=tuple(processes),
out_dir=run_dir,
verbose=False,
)
app = build_graph(force_fallback=True)
state = initial_state(cfg)
error: list[str] = []
def worker():
try:
app.invoke(state, config={"recursion_limit": generations * 24 + 64})
except Exception:
error.append(traceback.format_exc())
t = threading.Thread(target=worker, daemon=True)
t.start()
seen = 0
while t.is_alive():
t.join(POLL_SECONDS)
lines = state.get("log", [])
if len(lines) != seen:
seen = len(lines)
gen = state.get("generation", 0)
progress((min(gen, generations) / max(generations, 1)),
desc=f"generation {gen + 1} of {generations}")
yield "\n".join(lines[-40:]), "", "", None
if error:
yield "\n".join(state.get("log", [])) + "\n\nRUN FAILED\n" + error[0], "", "", None
return
log = "\n".join(state.get("log", []))
if not state.get("release"):
yield log + "\n\nNo cells survived. Try a larger population or budget.", "", "", None
return
emit_run(state, run_dir)
gallery_path = write_gallery(run_dir, os.path.join(run_dir, "gallery.html"))
zip_path = shutil.make_archive(os.path.join(out_dir, "chronoswarm-run"), "zip", run_dir)
yield log, results_table(state), embed_gallery(gallery_path), zip_path
INTRO = """
# ChronoSwarm
A LangGraph collective that evolves **energy-recycling kinetic mechanisms** and writes the
**motion recipes** that turn their motion into useful work.
Each released cell arrives with its mechanism, control loop, flat patterns, bill of materials,
and a recipe stating what process the motion performs, within what envelope, and which sensor
certifies each number. The animation below replays the real solved joint coordinates, not a
stylisation.
Everything runs on CPU with no API key — the LLM-backed agents fall back to deterministic
shadows, so runs are reproducible and free.
"""
NOTES = """
### Reading the numbers
* **recovery** — regenerated ÷ gross electrical draw. Bounded above by `η_drive · η_regen` ≈ 0.55,
so 0.30 is genuinely good, not a third of the way there.
* **recipe fit** — geometric mean of process-envelope membership. One badly missed axis pulls the
whole score down, by design.
* **buildability** — DFM score. Hard violations (yield, bore-vs-width, tolerance-driven stroke
error) kill a lineage outright rather than costing it points.
A short run explores less, so expect fewer archetypes in the release. The `compaction_tamping`
and `peristaltic_transfer` envelopes are tighter than `vibration_assisted_insertion`; if you
select only those, give it more generations.
"""
with gr.Blocks(title="ChronoSwarm", theme=gr.themes.Soft()) as demo:
gr.Markdown(INTRO)
with gr.Row():
with gr.Column(scale=1):
generations = gr.Slider(2, MAX_GENERATIONS, value=6, step=1, label="Generations")
population = gr.Slider(8, MAX_POPULATION, value=20, step=2, label="Population")
elites = gr.Slider(2, 10, value=6, step=1, label="Released cells (elites)")
seed = gr.Number(value=7, precision=0, label="Random seed")
budget = gr.Slider(500, 40000, value=12000, step=500,
label="Credit budget (1 unit ≈ 1 ms CPU)")
processes = gr.CheckboxGroup(
choices=list(PROCESS_LIST),
value=list(PROCESS_LIST),
label="Processes to evolve for",
)
run_btn = gr.Button("Evolve", variant="primary")
gr.Markdown(
"_Defaults take roughly 45 s on a free CPU Space. "
f"The ceiling ({MAX_GENERATIONS}×{MAX_POPULATION}) takes several minutes._"
)
with gr.Column(scale=2):
# NOTE: no show_copy_button - Gradio 6 dropped it from Textbox.
# This app targets the Gradio 5 line (see requirements.txt), but
# avoiding the kwarg keeps it importable on 6 as well.
log = gr.Textbox(label="Swarm log", lines=18, max_lines=18,
autoscroll=True)
results = gr.Markdown(label="Released cells")
gallery = gr.HTML(label="Evolved kinetic cells")
download = gr.File(label="Full run — cell bundles, CAD, firmware, BOM, metrics (.zip)")
gr.Markdown(NOTES)
run_btn.click(
evolve,
inputs=[generations, population, elites, seed, budget, processes],
outputs=[log, results, gallery, download],
)
def pick_server_port(default_port: int) -> int:
"""Return the next free port, falling back to a random OS-assigned port."""
for port in range(default_port, default_port + 20):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
try:
sock.bind(("127.0.0.1", port))
return port
except OSError:
continue
return 0
if __name__ == "__main__":
# one run at a time: two concurrent searches on 2 vCPU starve each other
demo.queue(default_concurrency_limit=1, max_size=12)
chosen_port = int(os.environ.get("PORT", 7865))
demo.launch(
server_name="0.0.0.0",
server_port=pick_server_port(chosen_port),
share=False,
)