import os
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
import spaces # noqa: E402 (must precede torch)
import concurrent.futures # noqa: E402
import html # noqa: E402
import json # noqa: E402
import sys # noqa: E402
import time # noqa: E402
import types # noqa: E402
import gradio as gr # noqa: E402
import torch # noqa: E402
from huggingface_hub import snapshot_download # noqa: E402
MODEL_ID = "Cloudflare/clairic-flash"
# ---------------------------------------------------------------------------
# ZeroGPU compatibility shims
# ---------------------------------------------------------------------------
# The release runtime targets Hopper (sm_90) and calls DeepGEMM / FlashInfer
# for a couple of BF16 GEMMs and Gemma-style RMSNorms. ZeroGPU runs on
# Blackwell sm_120, where DeepGEMM has no kernels, so we provide numerically
# equivalent pure-PyTorch implementations of exactly the functions it uses.
def _install_shims() -> None:
dg = types.ModuleType("deep_gemm")
def bf16_gemm_nn(a, b, out):
torch.matmul(a, b, out=out)
dg.bf16_gemm_nn = bf16_gemm_nn
dg.get_num_sms = lambda: torch.cuda.get_device_properties(0).multi_processor_count
dg.get_tc_util = lambda: 100
dg.get_pdl = lambda: False
sys.modules["deep_gemm"] = dg
fi = types.ModuleType("flashinfer")
norm = types.ModuleType("flashinfer.norm")
def _gemma(x32, weight, eps):
var = x32.pow(2).mean(-1, keepdim=True)
return x32 * torch.rsqrt(var + eps) * (1.0 + weight.float())
def gemma_rmsnorm(x, weight, eps=1e-6):
return _gemma(x.float(), weight, eps).to(x.dtype)
def gemma_fused_add_rmsnorm(x, residual, weight, eps=1e-6):
total = x.float() + residual.float()
residual.copy_(total)
x.copy_(_gemma(total, weight, eps))
norm.gemma_rmsnorm = gemma_rmsnorm
norm.gemma_fused_add_rmsnorm = gemma_fused_add_rmsnorm
fi.norm = norm
sys.modules["flashinfer"] = fi
sys.modules["flashinfer.norm"] = norm
_install_shims()
# ---------------------------------------------------------------------------
# Model loading (module scope, eager .to("cuda"))
# ---------------------------------------------------------------------------
MODEL_PATH = snapshot_download(MODEL_ID)
sys.path.insert(0, MODEL_PATH)
import xgrammar as xgr # noqa: E402
from transformers import Qwen3_5ForConditionalGeneration # noqa: E402
from clairic_model import ClairicModel # noqa: E402
from clairic_runtime import native as _native # noqa: E402
from clairic_runtime.backend import ClairicFlashModel # noqa: E402
from clairic_runtime.math import install as _install_math # noqa: E402
from clairic_runtime.readout import load_head # noqa: E402
from clairic_runtime.settings import RuntimeSettings # noqa: E402
_TOKENIZER_INFO = {}
def _zerogpu_engine_load(cls, path, tokenizer, device="cuda", dtype=None, batch_size=None,
text_batch_size=None, batch_token_budget=None, **_):
"""Same as the release loader, minus Hopper-only FA3 and CUDA-graph capture."""
class _NativeQwen3_5ForConditionalGeneration(Qwen3_5ForConditionalGeneration):
_keep_in_fp32_modules_strict = ["A_log"]
backbone = _NativeQwen3_5ForConditionalGeneration.from_pretrained(
path,
dtype=torch.bfloat16,
local_files_only=True,
attn_implementation={"text_config": "sdpa", "vision_config": "sdpa"},
)
backbone.to("cuda")
head = load_head(path, match_bfloat16=True).float().eval().to("cuda")
engine = cls(backbone, head, tokenizer, batch_size=batch_size,
text_batch_size=text_batch_size, batch_token_budget=batch_token_budget)
_TOKENIZER_INFO["info"] = xgr.TokenizerInfo.from_huggingface(
tokenizer,
vocab_size=backbone.get_output_embeddings().weight.shape[0],
stop_token_ids=[engine.eos],
)
return engine
_native.TransformersEngine.load = classmethod(_zerogpu_engine_load)
_settings = RuntimeSettings(model_path=MODEL_PATH, version="1", model_id="clairic-flash",
max_length=65_273, max_concurrency=1)
RUNTIME = ClairicFlashModel.load(_settings, device="cuda")
MODEL = ClairicModel(RUNTIME, "clairic-flash")
print("Clairic Flash loaded.", flush=True)
_WORKER_PID = None
def _prepare_worker() -> None:
"""Re-create thread pools / grammar compiler / fused math inside the GPU fork."""
global _WORKER_PID
if _WORKER_PID == os.getpid():
return
engine = RUNTIME.engine
engine._worker = concurrent.futures.ThreadPoolExecutor(max_workers=1, thread_name_prefix="clairic-model")
RUNTIME._encoder = concurrent.futures.ThreadPoolExecutor(max_workers=1, thread_name_prefix="clairic-encode")
engine.compiler = xgr.GrammarCompiler(_TOKENIZER_INFO["info"], max_threads=2)
if engine._restore_math is None:
engine._restore_math = _install_math(engine.backbone, engine.head)
_WORKER_PID = os.getpid()
# ---------------------------------------------------------------------------
# Presets (from the model card) and rendering helpers
# ---------------------------------------------------------------------------
INVOICE_STATE = (
"Invoice from Northwind Supply. Issued 2026-09-02. "
"Items: Pens; Paper. Total: $1080.00."
)
INVOICE_FIELDS = {
"vendor": {"type": "text", "instructions": "The invoice vendor."},
"total": {"type": "number", "decimals": 2},
"issued": {"type": "date"},
"items": {"type": "list", "items": "text", "instructions": "The purchased item names, in order."},
}
DEMAND_STATE = "Daily demand for the last seven days: 41, 45, 43, 47, 49, 46, 48."
DEMAND_FIELDS = {
"next_day": {"type": "estimate", "min": 0, "max": 100},
"next_three_days": {"type": "forecast", "min": 0, "max": 100, "horizon": 3, "interval": "day"},
}
RECEIPT_STATE = "Read the attached receipt."
RECEIPT_FIELDS = {
"items": {"type": "list", "items": "text", "instructions": "The purchased item names, in order."},
"total": {"type": "number", "source_only": True, "instructions": "The receipt total."},
"paid_cash": {"type": "boolean", "instructions": "Whether the customer paid in cash."},
}
TICKET_STATE = (
"Hi team, our checkout page has been returning 502 errors since about 14:20 UTC today. "
"Roughly 30% of EU customers are affected and we're losing orders. Account: ACME-4471. "
"Please escalate - Priya, Head of Ops"
)
TICKET_FIELDS = {
"category": {"type": "enum", "enum": ["billing", "outage", "feature_request", "security", "other"]},
"urgent": {"type": "boolean", "instructions": "Whether the issue needs immediate attention."},
"account_id": {"type": "text"},
"share_affected": {"type": "number", "unit": "percent", "instructions": "Share of customers affected."},
"reporter": {"type": "text", "instructions": "Name of the person reporting."},
}
def _fmt(fields: dict) -> str:
return json.dumps(fields, indent=2)
def _esc(value) -> str:
return html.escape(str(value))
def _pct(p) -> float:
try:
return max(0.0, min(1.0, float(p))) * 100.0
except (TypeError, ValueError):
return 0.0
def _num(v) -> str:
if isinstance(v, bool):
return str(v).lower()
if isinstance(v, float):
return f"{v:,.2f}".rstrip("0").rstrip(".") if abs(v) < 1e6 else f"{v:,.0f}"
if isinstance(v, int):
return f"{v:,}"
return str(v)
def _value_inline(value) -> str:
if isinstance(value, dict):
if "value" in value:
return _esc(_num(value["value"]))
return _esc(json.dumps(value, ensure_ascii=False))
return _esc(_num(value))
def _value_html(value) -> str:
if value is None:
return 'null'
if isinstance(value, bool):
return f'{str(value).lower()}'
if isinstance(value, list):
if not value:
return '[ ]'
chips = "".join(f'{_value_inline(v)}' for v in value)
return f'
{chips}
'
if isinstance(value, dict):
rows = "".join(f"
{_esc(k)} {_value_inline(v)}
" for k, v in value.items())
return f'
{rows}
'
return f'{_esc(_num(value))}'
def _floats(seq):
out = []
for v in seq or []:
try:
out.append(float(v))
except (TypeError, ValueError):
return []
return out
def _spark(vals, lows=None, highs=None) -> str:
vals = _floats(vals)
lows, highs = _floats(lows), _floats(highs)
if len(vals) < 2:
return ""
band = len(lows) == len(vals) == len(highs)
every = vals + (lows + highs if band else [])
lo, hi = min(every), max(every)
span = (hi - lo) or 1.0
w, h = 240, 70
X = lambda i: 12 + i * (w - 24) / (len(vals) - 1)
Y = lambda v: h - 10 - (v - lo) / span * (h - 20)
poly = ""
if band:
top = " ".join(f"{X(i):.1f},{Y(v):.1f}" for i, v in enumerate(highs))
bot = " ".join(f"{X(i):.1f},{Y(v):.1f}" for i, v in reversed(list(enumerate(lows))))
poly = f''
line = " ".join(f"{X(i):.1f},{Y(v):.1f}" for i, v in enumerate(vals))
dots = "".join(f'' for i, v in enumerate(vals))
return f''
def render_answers(response: dict, elapsed: float) -> str:
cards = []
for name, ans in response.get("answers", {}).items():
ans = ans if isinstance(ans, dict) else {"value": ans}
kind = ans.get("type", "")
value = ans.get("value")
body = _value_html(value)
extra = ""
if kind == "forecast" and isinstance(value, list):
extra += _spark(value, ans.get("p10"), ans.get("p90"))
if isinstance(ans.get("p10"), list):
extra += '
shaded band: 80% interval (p10–p90)
'
elif "p10" in ans and "p90" in ans and not isinstance(ans["p10"], list):
extra += (f'
')
meters = ""
if "confidence" in ans:
c = _pct(ans["confidence"])
meters += (f'
confidence
'
f'
{c:.1f}%
')
if "p_null" in ans:
p = _pct(ans["p_null"])
meters += (f'
p(null)
'
f'
{p:.1f}%
')
flags = f'{_esc(kind)}' if kind else ""
if ans.get("valid") is False:
flags += 'invalid'
if ans.get("complete") is False:
flags += 'incomplete'
cards.append(
f'
{_esc(name)}{flags}
'
f'
{body}{extra}
{meters}
'
)
usage = response.get("usage", {})
stats = "".join(
f'
{_esc(v)}{_esc(k.replace("_", " "))}
'
for k, v in usage.items()
)
trunc = ('input truncated' if response.get("truncated") else
'● complete input')
return (
f'
Structured answers'
f'{trunc}⚡ {elapsed:.1f}s
'
f'
{"".join(cards)}
{stats}
'
)
FIELD_TYPES = ["text", "number", "date", "time", "datetime", "duration", "boolean", "enum",
"list", "estimate", "forecast"]
def add_field(fields_json: str, name: str, kind: str, instructions: str, options: str) -> str:
"""Append a typed field spec to the schema JSON (UI helper)."""
name = (name or "").strip()
if not name:
raise gr.Error("Give the field a name.")
try:
fields = json.loads(fields_json or "{}")
if not isinstance(fields, dict):
raise ValueError
except ValueError:
raise gr.Error("The current schema is not a valid JSON object.")
spec = {"type": kind}
if kind == "list":
spec["items"] = "text"
elif kind == "enum":
values = [v.strip() for v in (options or "").split(",") if v.strip()]
if not values:
raise gr.Error("Enum fields need at least one option.")
spec["enum"] = values
elif kind in ("estimate", "forecast"):
spec.update({"min": 0, "max": 100})
if kind == "forecast":
spec.update({"horizon": 3, "interval": "day"})
if instructions and instructions.strip():
spec["instructions"] = instructions.strip()
fields[name] = spec
return _fmt(fields)
EMPTY_HTML = (
'
{ }
'
"
Pick a preset or describe your own fields, then hit Extract.
"
"
Each field comes back typed, with a confidence score and a null probability.
"
)
# ---------------------------------------------------------------------------
# Inference
# ---------------------------------------------------------------------------
def _gpu_duration(state, fields_json, image=None, *args, **kwargs):
# measured on this Space: 21.4s text on a cold worker (incl. Triton JIT), 4.3s warm text,
# 24.1s single image on a cold worker, 9-11s warm
return 28 if image is not None else 25
@spaces.GPU(duration=_gpu_duration)
def extract(state: str, fields_json: str, image=None, reference_date: str = "",
include_quantiles: bool = False):
"""Extract typed, scored structured answers from text and/or an image with Clairic Flash.
Args:
state: Source text (or JSON) to read from. May be empty when an image is provided.
fields_json: JSON object mapping field names to typed field specs, e.g.
{"total": {"type": "number", "decimals": 2}}. Supported types: text, number, date,
time, datetime, duration, boolean, enum, object, list, compute, estimate, forecast.
image: Optional image (e.g. a receipt or document photo).
reference_date: Optional ISO date (YYYY-MM-DD) used for relative date instructions.
include_quantiles: Return quantiles for estimate / forecast fields.
Returns:
A rendered HTML summary and the raw JSON response (answers, truncated, usage).
"""
try:
fields = json.loads(fields_json)
except json.JSONDecodeError as exc:
raise gr.Error(f"Fields must be valid JSON: {exc}")
if not isinstance(fields, dict) or not fields:
raise gr.Error("Fields must be a non-empty JSON object of field specs.")
request = {"state": state or "", "fields": fields,
"options": {"include_quantiles": bool(include_quantiles)}}
if image is not None:
request["images"] = [image]
if reference_date and reference_date.strip():
request["reference_date"] = reference_date.strip()
if not request["state"].strip() and image is None:
raise gr.Error("Provide some source text or an image.")
_prepare_worker()
t0 = time.perf_counter()
try:
response = MODEL.predict(request)
except Exception as exc: # validation / request errors → readable message
raise gr.Error(f"{type(exc).__name__}: {exc}")
elapsed = time.perf_counter() - t0
print(f"[clairic-flash] inference {elapsed:.2f}s fields={list(fields)} image={image is not None}", flush=True)
response = json.loads(json.dumps(response, default=str))
return render_answers(response, elapsed), response
# ---------------------------------------------------------------------------
# UI
# ---------------------------------------------------------------------------
CF_LOGO = """
"""
HEADER = f"""
{CF_LOGO}
CLOUDFLARE · SYSTEM ONE: EXTRACT
Clairic Flash 9B
Turn messy text and images into typed, scored structured answers. Declare a schema of fields —
text, numbers, dates, enums, lists, estimates, forecasts — and get back values with confidence and null probabilities.