broadfield's picture
Add OpenJev CPU Gradio app (zero GPU)
7563a50 verified
Raw History Blame Contribute Delete
13.4 kB
#!/usr/bin/env python3
"""OpenJev on CPU — a zero-GPU Gradio Space.
Runs the official `openjev/openjev-GGUF` OpenJev-Q4_K_M.gguf (16.5 GB) on CPU only
(n_gpu_layers=0) with llama-cpp-python, and serves the same one-pass decision protocol
as the hosted openjev-server:
* prompt: State:\\n...\\n\\nQuestion: ...\\nOptions:\\n[A] ...\\n\\nAnswer with the letter...
* readout: temperature-scaled softmax over the candidate letter tokens at the first
output position — one forward pass per question, nothing generated.
* API: POST /v1/systemone, /v1/version, /v1/prewarm, /healthz, /readyz
(same shapes as openjev-server; see core readout_core.py).
Two views:
1. Chat UI — write a state, then decision requests as fenced codeblocks (```systemone).
2. Raw API — the exact /v1/systemone request body, answered directly.
"""
from __future__ import annotations
import copy
import json
import os
import re
import threading
import uuid
import gradio as gr
from core_engine import CoreEngine, CTX, GGUF_FILE, GGUF_REPO
from readout_core import BadQuestion, CPUReadout, ReadoutIncomplete
# --------------------------------------------------------------------------- model
ENGINE = CoreEngine()
READOUT = CPUReadout(ENGINE)
_LOAD_LOCK = threading.Lock()
MODEL_STR = f"{GGUF_REPO}/{GGUF_FILE}"
BT = chr(96) # backtick — used to build fenced-systemone blocks without escape ambiguity
SYSTEMONE_RE = re.compile(BT * 3 + r"systemone\s*(.*?)" + BT * 3, re.DOTALL)
CHAT_EXAMPLE_STATE = {
"page": "checkout",
"elements": [
{"tag": "button", "text": "Place order", "index": 1},
{"tag": "a", "text": "Continue shopping", "index": 2},
{"tag": "input", "text": "Coupon", "index": 3},
],
"user": "anon",
}
FENCE = BT * 3 # ``` — used when embedding example JSON in the UI
DEFAULT_QUESTIONS: dict[str, dict] = {
"q1": {
"type": "choice",
"instructions": "Which action completes the purchase?",
"criteria": {
"click_place_order": "click the Place order button",
"continue_shopping": "go back to the cart",
"enter_coupon": "type a coupon code",
},
},
"q2": {
"type": "noul",
"instructions": "Is it likely the user intends to finish checkout now?",
"criteria": {"true": "Yes, they want to complete the purchase", "false": "No, they want to browse more"},
},
}
# --------------------------------------------------------------------------- load-once
def ensure_loaded() -> None:
"""Load the model once (16.5 GB from HF). Runs in the background on first use."""
if ENGINE.healthy():
return
acquired = _LOAD_LOCK.acquire(timeout=1)
try:
if not ENGINE.healthy() and acquired:
ENGINE.load()
finally:
if acquired:
_LOAD_LOCK.release()
# --------------------------------------------------------------------------- decision core
def _answer_body(body: dict) -> dict:
"""Answer one /v1/systemone body; raises BadQuestion/ReadoutIncomplete for 422/502."""
state = body.get("state")
if state is None:
raise BadQuestion("state is required")
if not isinstance(body.get("questions"), dict) or not body["questions"]:
raise BadQuestion("questions must be a non-empty object")
questions = {k: copy.deepcopy(v) for k, v in body["questions"].items()}
answers, tokens = READOUT.answer_all(state, questions)
return {
"id": f"oj-{uuid.uuid4().hex[:16]}",
"model": MODEL_STR,
"answers": answers,
"usage": {"input_tokens": tokens, "output_tokens": 0},
}
def _format_answer(answers: dict[str, dict]) -> str:
"""Pretty-print a systemone response for the chat view."""
out = []
for qid, a in answers.items():
kind = a.get("type")
if kind == "choice":
probs = " ".join(f"{k}: {v*100:.1f}%" for k, v in a.get("probabilities", {}).items())
out.append(f"**{qid}** → `{a['choice']}` (confidence {a.get('confidence', 0):.2f})\n {probs}")
elif kind == "score":
out.append(f"**{qid}** → score `{a['score']}` (confidence {a.get('confidence', 0):.2f})")
probs = " ".join(f"{k}: {v*100:.1f}%" for k, v in a.get("probabilities", {}).items())
out.append(f" {probs}")
elif kind == "noul":
out.append(f"**{qid}** → `{'yes' if a['noul'] >= 0.5 else 'no'}` (p(yes) = {a['noul']:.3f})")
return "\n".join(out)
# --------------------------------------------------------------------------- gradio handlers (UI)
def answer_chat(state_text: str, screenshot: str | None, questions_block: str, history: list) -> tuple[list, str]:
"""Chat endpoint: expects a state (text or JSON) + decision requests in ```systemone blocks."""
if not state_text.strip() and not screenshot:
raise gr.Error("Please provide a state, or paste a screenshot.")
if not questions_block.strip():
raise gr.Error("Please include at least one ```systemone ...``` decision block.")
blocks = SYSTEMONE_RE.findall(questions_block)
if not blocks:
raise gr.Error("No ```systemone``` block found. Wrap your decision request like:\n```systemone\n{...}\n```")
# Compose the state object from text + optional screenshot.
state = state_text.strip()
if screenshot:
state_obj = {"screenshot": screenshot, "state": state}
else:
try:
state_obj = json.loads(state) if state.startswith(("{", "[")) else state
except json.JSONDecodeError:
state_obj = state
buf: list[dict] = []
for block in blocks:
try:
body = json.loads(block)
except json.JSONDecodeError as exc:
raise gr.Error(f"Invalid JSON in systemone block: {exc}")
body.setdefault("state", state_obj)
buf.append(_answer_body(body))
lines = [f"**state:**\n{FENCE}json\n{json.dumps(state_obj, ensure_ascii=False, indent=2)[:1200]}\n{FENCE}", ""]
for i, ans in enumerate(buf, 1):
lines.append(f"**request {i}** — `{ans['id']}` ({ans['usage']['input_tokens']} input tokens)")
lines.append(_format_answer(ans["answers"]))
lines.append("")
history = history + [(questions_block, "\n".join(lines))]
return history, ""
def answer_raw(request_json: str, state_json: str) -> str:
"""Raw API tab: paste a full /v1/systemone body, or a questions object + separate state."""
try:
body = json.loads(request_json)
except json.JSONDecodeError as exc:
raise gr.Error(f"Invalid JSON: {exc}")
if isinstance(body, dict) and "state" not in body and "questions" not in body:
body = {"state": state_json, "questions": body}
if not isinstance(body, dict) or "state" not in body or "questions" not in body:
raise gr.Error("Body must be a /v1/systemone request: {\"state\": ..., \"questions\": {...}}")
try:
result = _answer_body(body)
return json.dumps(result, ensure_ascii=False, indent=2)
except BadQuestion as exc:
return json.dumps({"error": {"code": 422, "message": str(exc)}}, indent=2)
except ReadoutIncomplete as exc:
return json.dumps({"error": {"code": 502, "message": str(exc)}}, indent=2)
def status_view() -> str:
loaded = ENGINE.healthy()
info = ENGINE.info()
state = "✅ loaded" if loaded else ("⏳ loading…" if info.get("load_error") is None and not loaded else f"❌ error: {info.get('load_error')}")
return (
f"**model:** `{MODEL_STR}`\n"
f"**state:** {state}\n"
f"**context:** {info.get('n_ctx')} tokens · **threads:** {info.get('n_threads')} · **GPU layers:** {info.get('gpu_layers')}\n"
f"**letters:** {info.get('letters')} candidate labels · **quant:** {info.get('quant')}"
)
# --------------------------------------------------------------------------- optional FastAPI passthrough (OPENJEV_HTTP=1)
def _start_http() -> None:
"""Optional: a tiny FastAPI/uvicorn exposing /v1/systemone.
Gradio owns :7860; when OPENJEV_HTTP=1 we launch uvicorn on the same host with a
different internal approach — the API shape is identical to openjev-server. On CPU
the single-process answer loop is sequential anyway, so this is best-effort.
"""
if os.environ.get("OPENJEV_HTTP") != "1":
return
try:
import uvicorn
from fastapi import FastAPI, HTTPException, Request
except Exception:
return
app = FastAPI(title="openjev-cpu", version="0.1.0")
@app.get("/healthz")
async def healthz():
return {"ok": True}
@app.get("/readyz")
async def readyz():
return {"ok": ENGINE.healthy(), "backend": "llama.cpp-cpu"}
@app.get("/v1/version")
async def version():
return {
"server": "openjev-server",
"version": "0.2.0",
"backend": "llama.cpp-cpu",
"model_dir": GGUF_REPO,
"profile": "openjev",
"T": READOUT.profile.temp,
"noul_t": READOUT.profile.noul_t,
"noul_bias": READOUT.profile.noul_bias,
"flags": {"perms": 1, "stagger": True, "compact": False, "compact_cap": 0, "layout": "", "pad": 0, "targeted": True, "instr_style": "pyrepr"},
"readout_sha256": "cpu-port",
}
@app.post("/v1/systemone")
async def systemone(request: Request):
body = await request.json()
try:
return _answer_body(body)
except BadQuestion as exc:
raise HTTPException(422, {"code": 422, "message": str(exc)})
except ReadoutIncomplete as exc:
raise HTTPException(502, {"code": 502, "message": str(exc)})
threading.Thread(target=lambda: uvicorn.run(app, host="0.0.0.0", port=7861, log_level="warning"), daemon=True).start()
# --------------------------------------------------------------------------- build UI
with gr.Blocks(title="OpenJev on CPU", theme=gr.themes.Soft()) as demo:
gr.Markdown(
"""## ⚖️ OpenJev on CPU — zero GPU
Runs the official **`openjev/openjev-GGUF`** `OpenJev-Q4_K_M.gguf` (16.5 GB) with `llama-cpp-python` on **CPU only** (`n_gpu_layers=0`).
One forward pass per question — no generation, no chain-of-thought. Same decision protocol as the hosted openjev-server.
"""
)
with gr.Tab("Chat"):
with gr.Row():
with gr.Column():
state_input = gr.Textbox(
label="State (text or JSON)",
lines=5,
value=json.dumps(CHAT_EXAMPLE_STATE, indent=2),
info="The situation / page / DOM the model decides about.",
)
screenshot = gr.Image(label="Screenshot (optional, text-state only in this build)", type="filepath", sources=["upload", "clipboard"])
questions_block = gr.Textbox(
label=f"Decision requests ({FENCE}systemone blocks)",
lines=8,
value=FENCE + "systemone\n" + json.dumps(DEFAULT_QUESTIONS, indent=2) + "\n" + FENCE,
info="Each fenced block is one /v1/systemone request. Add multiple blocks for one state.",
)
send = gr.Button("Decide", variant="primary")
with gr.Column():
status = gr.Markdown(status_view())
chat = gr.Chatbot(label="Decisions", height=420)
send.click(answer_chat, [state_input, screenshot, questions_block, chat], [chat, questions_block])
with gr.Tab("Raw API"):
gr.Markdown("Paste a **`/v1/systemone`** request body. Same contract as `openjev-server`.")
with gr.Row():
with gr.Column():
raw_state = gr.Textbox(label="state", lines=4, value=json.dumps(CHAT_EXAMPLE_STATE, indent=2))
raw_body = gr.Textbox(
label="questions",
lines=8,
value=json.dumps(DEFAULT_QUESTIONS, indent=2),
info="You can paste the WHOLE body here; if it has no 'state'/'questions' keys, it is treated as the questions object.",
)
raw_go = gr.Button("Run", variant="primary")
with gr.Column():
raw_out = gr.Textbox(label="response", lines=16, interactive=False)
raw_go.click(answer_raw, [raw_body, raw_state], raw_out)
with gr.Accordion("How it works", open=False):
gr.Markdown(
"""`/v1/systemone` sends: `{state, questions:{qid:{type, instructions, criteria}}}`.
The state is prefixed `State:\\n…`, each question is appended as `Question: … Options:[A] … [B] …` and the model's **first output position** letter-token log-probs are read, temperature-scaled by `T=0.85`, softmaxed → a probability for every option. `noul` is calibrated with `noul_t=1.829074`.
**One forward pass per question — nothing generated.** On this CPU Space expect **~2–6 s/question** (16.5 GB Q4_K_M, single pass). This is not the hosted 125 ms H100 API: it is a free, zero-GPU, self-hosted decision endpoint.
"""
)
if __name__ == "__main__":
_start_http()
demo.queue(default_concurrency_limit=1).launch(show_api=False, server_name="0.0.0.0", server_port=7860)