import spaces # must come before torch
import html
import json
import sys
import time
import gradio as gr
import torch
from huggingface_hub import snapshot_download
MODEL_ID = "SupersonicLabs/Julia-2"
# bf16 checkpoint + the authors' own `julia2` runtime (it ships in the model repo; no transformers needed)
ROOT = snapshot_download(
MODEL_ID,
allow_patterns=["model.safetensors", "config.json", "trunk/*", "tokenizer/*", "runtime/julia2/*"],
)
sys.path.insert(0, f"{ROOT}/runtime")
from julia2 import Runtime # noqa: E402
# Load on CPU in bf16 (all dtype work happens on real tensors), then move every tower to CUDA eagerly.
rt = Runtime(ROOT, device="cpu", cpu_dtype=torch.bfloat16)
DEV = torch.device("cuda")
rt.trunk.to(DEV)
rt.trunk.device = DEV
rt.trunk.use_graphs = False # CUDA-graph capture is a ms-level optimisation; keep the eager path on ZeroGPU
rt.trunk._ws = {}
if rt.vision is not None:
rt.vision.to(DEV)
rt.vision.device = DEV
if rt.audio is not None:
rt.audio.to(DEV) # keeps encoder bf16 / projector fp32
rt.audio.device = DEV
rt.device = DEV
# ----------------------------------------------------------------------------- rendering
def _bar(label, p, best=False, desc=""):
pct = max(0.0, min(1.0, float(p))) * 100
color = "var(--color-accent)" if best else "var(--neutral-400)"
d = f'
']
for key, a in answers.items():
q = questions.get(key, {})
crit = q.get("criteria") or {}
title = html.escape(q.get("instructions", key))
if a["type"] == "noul":
p = a["noul"]
verdict = "Yes" if p >= 0.5 else "No"
out.append(f'
{html.escape(key)} · noul'
f'{verdict} · P(true) = {p:.3f}
{title}
')
out.append(_bar("true", p, p >= 0.5))
out.append(_bar("false", 1 - p, p < 0.5))
else:
probs = a["probabilities"]
best = a.get("choice", str(a.get("score")))
if a["type"] == "choice":
head = f'{html.escape(str(best))} · confidence {a["confidence"]:.2f}'
else:
head = f'level {a["score"]} · expected {a["expected_level"]:.2f}'
out.append(f'
{html.escape(key)} · {a["type"]}'
f'{head}
{title}
')
levels = crit if isinstance(crit, dict) else {str(i): d for i, d in enumerate(crit)}
for k, p in probs.items():
d = levels.get(k, "") if isinstance(levels, dict) else ""
out.append(_bar(k, p, str(k) == str(best), d if d != k else ""))
out.append("
")
out.append("
")
return "".join(out)
def _parse_state(state):
s = (state or "").strip()
if s[:1] in "{[":
try:
v = json.loads(s)
return v if isinstance(v, dict) else json.dumps(v, ensure_ascii=False)
except Exception:
pass
return s
# ----------------------------------------------------------------------------- inference
@spaces.GPU(duration=5)
def decide(state: str, questions_json: str, image=None, audio: str | None = None):
"""Score decisions about a situation with Julia-2.
Args:
state: the situation — plain text or a JSON object (ticket, record, transcript context, policy...).
questions_json: JSON object {key: {"type": "choice"|"noul"|"score", "instructions": str, "criteria": ...}}.
image: optional image placed in the state (read by the model's own vision tower).
audio: optional path to a speech recording placed after the text of the state (no transcription step).
Returns:
HTML rendering of the probabilities and the raw Julia-2 answer JSON.
"""
try:
questions = json.loads(questions_json)
except Exception as e:
raise gr.Error(f"Questions must be valid JSON: {e}")
if not isinstance(questions, dict) or not questions:
raise gr.Error("Questions must be a non-empty JSON object {key: question}.")
for k, q in questions.items():
if not isinstance(q, dict) or q.get("type") not in ("choice", "noul", "score"):
raise gr.Error(f"Question '{k}' needs a type of 'choice', 'noul' or 'score'.")
if q["type"] in ("choice", "score") and not q.get("criteria"):
raise gr.Error(f"Question '{k}' ({q['type']}) needs 'criteria'.")
st = _parse_state(state)
if image is None and audio is None:
req_state = st
else:
parts = []
if image is not None:
parts.append({"type": "image", "image": image})
text = st if isinstance(st, str) else json.dumps(st, ensure_ascii=False)
if text:
parts.append({"type": "text", "text": text})
if audio:
parts.append({"type": "input_audio", "input_audio": audio})
req_state = parts
t0 = time.perf_counter()
try:
res = rt.predict_questions(req_state, questions)
except ValueError as e:
raise gr.Error(str(e))
res["latency_ms"] = round((time.perf_counter() - t0) * 1000, 1)
return render(res["answers"], questions), res
def decide_text(state: str, questions_json: str):
"""Text/JSON-only variant of `decide`."""
return decide(state, questions_json)
def decide_image(state: str, questions_json: str, image):
"""Variant of `decide` with an image in the state."""
return decide(state, questions_json, image)
def decide_audio(state: str, questions_json: str, audio: str):
"""Variant of `decide` with a speech recording in the state."""
return decide(state, questions_json, None, audio)
# ----------------------------------------------------------------------------- examples (from the model card / runtime tests)
def J(d):
return json.dumps(d, indent=2, ensure_ascii=False)
EX_TICKET_STATE = J({"ticket": "I was charged twice for order #4821 and the second charge is still pending.", "customer_tier": "gold"})
EX_TICKET_Q = J({
"intent": {"type": "choice", "instructions": "What does the customer want?",
"criteria": {"refund": "Get money back", "cancel": "Cancel the order", "track": "Track a delivery"}},
"urgent": {"type": "noul", "instructions": "Should this ticket be escalated today?"},
"priority": {"type": "score", "instructions": "Support priority", "criteria": ["low", "medium", "high"]},
})
EX_POLICY_STATE = J({
"order": {"id": "A-963", "days_since_purchase": 41, "charges": [{"amount_usd": 75, "status": "captured"}]},
"refund_policy": "Duplicate captured charges are refundable within 30 days of purchase. Pending or voided charges are never refunded.",
})
EX_POLICY_Q = J({"eligible": {"type": "noul", "instructions": "Is the customer eligible for a refund under the policy?"}})
EX_ROUTE_STATE = "Hi, since this morning the app logs me out every time I open it, and I also noticed a charge of $12.99 I don't recognise. Can someone look into both? This is really frustrating."
EX_ROUTE_Q = J({
"team": {"type": "choice", "instructions": "Which team should handle this ticket?",
"criteria": {"refund": "The customer wants money back for a charge that already happened",
"chargeback": "The customer says the charge was not made by them (possible fraud)",
"cancel": "The customer wants to stop an order or a subscription before it is charged",
"tech": "Technical support: login, app errors, connectivity"}},
"angry": {"type": "noul", "instructions": "Is the customer angry?"},
"sentiment": {"type": "choice", "instructions": "What is the sentiment of the message?",
"criteria": {"negative": "negative", "neutral": "neutral", "positive": "positive"}},
})
EX_IMG_STATE = "Delivery complaint #5531. The customer ordered: 1x classic cheeseburger with fries. They attached this photo and say the order arrived wrong."
EX_IMG_Q = J({
"food": {"type": "choice", "instructions": "What food is shown in the photo?",
"criteria": {"burger": "A burger / sandwich", "pizza": "A pizza", "salad": "A salad", "sushi": "Sushi", "dessert": "A dessert or cake"}},
"matches_order": {"type": "noul", "instructions": "Does the photo show the kind of dish the customer ordered?"},
})
CALL_QS = {
"scam": {"type": "noul", "instructions": "Is this call a scam attempt?"},
"credentials": {"type": "noul", "instructions": "Is the caller asking for a PIN, password, verification code, card number or a money transfer?"},
"pressure": {"type": "noul", "instructions": "Is the caller applying urgency, threats or emotional pressure?"},
"impersonation": {"type": "noul", "instructions": "Is the caller impersonating a bank, government agency, police or a well-known company (claiming to be one without verification)?"},
"intent": {"type": "choice", "instructions": "What does the caller want from this call?",
"criteria": {"payment_request": "the caller wants the customer to pay or transfer money",
"account_verification": "the caller wants account, card or identity details confirmed",
"delivery_scheduling": "the caller wants to arrange or confirm a delivery",
"sales_offer": "the caller is selling a product or service",
"prize_or_refund": "the caller announces a prize, refund or compensation",
"support_resolution": "the caller is resolving a support ticket or problem",
"emergency_help": "the caller asks for urgent help for a relative or emergency",
"survey": "the caller runs a survey or satisfaction check"}},
}
EX_CALL_Q = J(CALL_QS)
EX_SCAM_STATE = "Context: " + json.dumps({
"customer_name": "David Okafor", "age": 44, "lives": "Manchester, UK",
"employment": "salaried employee, taxes handled through his employer's payroll",
"notes": "has received no letters from the tax authority; knows the real tax office only contacts people by post and never demands immediate payment by phone"}) + "\nCall recording:"
EX_LEGIT_STATE = "Context: " + json.dumps({
"customer_name": "Helen Marsh", "age": 67, "utility": "Brightwater Electric",
"account_status": "active, auto-pay enrolled, no balance owed",
"scheduled": "a smart meter replacement appointment booked online by the customer last week for Thursday between nine and eleven in the morning",
"notes": "the customer's account notes show a technician visit is pending"}) + "\nCall recording:"
# ----------------------------------------------------------------------------- UI
CSS = """
#col-container { max-width: 1200px; margin: 0 auto; }
.dark .gradio-container { color: var(--body-text-color); }
.j2-card { border: 1px solid var(--border-color-primary); border-radius: 10px; padding: 10px 14px; margin-bottom: 10px; background: var(--block-background-fill); }
.j2-h { font-size: 0.85em; opacity: 0.8; display: flex; justify-content: space-between; gap: 8px; }
.j2-key { font-family: var(--font-mono); font-weight: 700; }
.j2-v { font-weight: 700; color: var(--body-text-color); }
.j2-q { margin: 4px 0 8px; font-weight: 600; }
.j2-row { display: grid; grid-template-columns: minmax(120px, 34%) 1fr 56px; gap: 8px; align-items: center; margin: 3px 0; }
.j2-lbl { font-size: 0.9em; overflow: hidden; }
.j2-desc { font-size: 0.78em; opacity: 0.7; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.j2-track { height: 12px; border-radius: 6px; background: var(--neutral-200); overflow: hidden; }
.dark .j2-track { background: var(--neutral-700); }
.j2-fill { height: 100%; border-radius: 6px; }
.j2-pct { font-family: var(--font-mono); font-size: 0.85em; text-align: right; }
"""
with gr.Blocks(title="Julia-2 decisions") as demo:
with gr.Column(elem_id="col-container"):
gr.Markdown(
"# Julia-2: from context to decisions\n"
"Give [SupersonicLabs/Julia-2](https://huggingface.co/SupersonicLabs/Julia-2) a **situation** (text, JSON, an image "
"and/or speech) and the **decisions** you need, each with its allowed options. It reads the state once and returns a "
"calibrated probability for every option. Nothing is generated. Question types: `choice` (one of N), `noul` (yes/no → "
"P(true)), `score` (ordered levels)."
)
with gr.Row():
with gr.Column(scale=1):
state = gr.Textbox(label="State (text or JSON)", lines=8, value=EX_ROUTE_STATE,
placeholder="A support ticket, a transaction record, an agent trace, a call context…")
questions = gr.Code(label="Questions (JSON)", language="json", lines=14, value=EX_ROUTE_Q)
with gr.Accordion("Optional: image / speech in the state", open=False):
image = gr.Image(label="Image", type="pil", height=240)
audio = gr.Audio(label="Speech recording", type="filepath")
run = gr.Button("Decide", variant="primary")
with gr.Column(scale=1):
out_html = gr.HTML(label="Decisions")
with gr.Accordion("Raw answer JSON", open=False):
out_json = gr.JSON(label="Julia-2 answer")
run.click(decide, inputs=[state, questions, image, audio], outputs=[out_html, out_json], api_name="decide")
gr.Markdown("### Examples")
gr.Examples(
label="Text & JSON",
examples=[[EX_ROUTE_STATE, EX_ROUTE_Q], [EX_POLICY_STATE, EX_POLICY_Q], [EX_TICKET_STATE, EX_TICKET_Q]],
inputs=[state, questions], outputs=[out_html, out_json], fn=decide_text,
cache_examples=True, cache_mode="lazy", api_name=False,
)
gr.Examples(
label="Speech (calls from the Julia-2 runtime tests)",
examples=[[EX_SCAM_STATE, EX_CALL_Q, "examples/scam_call.flac"], [EX_LEGIT_STATE, EX_CALL_Q, "examples/legit_call.flac"]],
inputs=[state, questions, audio], outputs=[out_html, out_json], fn=decide_audio,
cache_examples=True, cache_mode="lazy", api_name=False,
)
gr.Examples(
label="Image",
examples=[[EX_IMG_STATE, EX_IMG_Q, "examples/burger.jpg"]],
inputs=[state, questions, image], outputs=[out_html, out_json], fn=decide_image,
cache_examples=True, cache_mode="lazy", api_name=False,
)
if __name__ == "__main__":
demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)