Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,37 +1,40 @@
|
|
| 1 |
-
"""
|
|
|
|
| 2 |
import importlib.util
|
| 3 |
import json
|
|
|
|
| 4 |
import os
|
|
|
|
| 5 |
import sys
|
|
|
|
| 6 |
|
| 7 |
import gradio as gr
|
| 8 |
-
|
|
|
|
| 9 |
|
| 10 |
MODEL_REPO = os.environ.get("MODEL_REPO", "siyah1/jev-fin-0.8b")
|
| 11 |
-
TOKEN = os.environ.get("HF_TOKEN") #
|
| 12 |
|
| 13 |
-
try: # ZeroGPU
|
| 14 |
import spaces
|
| 15 |
gpu = spaces.GPU(duration=60)
|
| 16 |
except Exception: # noqa: BLE001
|
| 17 |
def gpu(fn):
|
| 18 |
return fn
|
| 19 |
|
|
|
|
| 20 |
_clf = None
|
| 21 |
|
| 22 |
|
| 23 |
def get_clf():
|
| 24 |
-
"""Load jev_common.py from the model repo, then the classifier (once)."""
|
| 25 |
global _clf
|
| 26 |
if _clf is None:
|
| 27 |
-
|
| 28 |
-
spec = importlib.util.spec_from_file_location("jev_common",
|
| 29 |
mod = importlib.util.module_from_spec(spec)
|
| 30 |
sys.modules["jev_common"] = mod
|
| 31 |
spec.loader.exec_module(mod)
|
| 32 |
-
|
| 33 |
-
local = snapshot_download(MODEL_REPO, token=TOKEN)
|
| 34 |
-
_clf = mod.JevClassifier(local)
|
| 35 |
print("model loaded on", _clf.device, flush=True)
|
| 36 |
return _clf
|
| 37 |
|
|
@@ -40,140 +43,562 @@ if not os.environ.get("SKIP_LOAD"):
|
|
| 40 |
try:
|
| 41 |
get_clf()
|
| 42 |
except Exception as e: # noqa: BLE001
|
| 43 |
-
print("startup load failed (
|
| 44 |
|
| 45 |
|
| 46 |
-
|
| 47 |
-
def
|
| 48 |
-
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
out = []
|
| 54 |
-
for
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
head = f"**{v['choice']}**" if t == "choice" else f"**{v['level']}** (score {v['score']:.2f}, 0 = lowest, 1 = highest)"
|
| 60 |
-
rows = "\n".join(f"- {n}: {p:.1%} `{bar(p)}`" for n, p in sorted(v["probabilities"].items(), key=lambda x: -x[1]))
|
| 61 |
-
out.append(f"### {key} _({t})_\n{head}, confidence {v['confidence']:.1%}\n{rows}")
|
| 62 |
-
return "\n\n".join(out)
|
| 63 |
|
| 64 |
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
|
| 71 |
-
def
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
try:
|
| 82 |
-
res = _decide(state,
|
| 83 |
except Exception as e: # noqa: BLE001
|
| 84 |
raise gr.Error(f"Inference failed: {e!r}")
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
continue
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
|
| 99 |
-
def
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
try:
|
| 114 |
-
res = _decide(state,
|
| 115 |
except Exception as e: # noqa: BLE001
|
| 116 |
raise gr.Error(f"Inference failed: {e!r}")
|
| 117 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
DEFAULT_SPEC = json.dumps({
|
| 127 |
"negative": {"type": "noul", "instructions": "Is this news negative for the stock?"},
|
| 128 |
"topic": {"type": "choice", "instructions": "Which topic does this belong to?",
|
| 129 |
"criteria": {"earnings": "results or guidance", "personnel": "executive changes", "m&a": "mergers and deals"}},
|
| 130 |
"severity": {"type": "score", "instructions": "How negative is this news?", "levels": ["mild", "moderate", "severe"]},
|
| 131 |
}, indent=2)
|
| 132 |
-
PF_SPEC = json.dumps({
|
| 133 |
-
"one_name_over_30": {"type": "noul", "instructions": "Is any single holding larger than 30% of the portfolio (weight_pct)?"},
|
| 134 |
-
"drift": {"type": "noul", "instructions": "Has any holding drifted more than 5 percentage points away from its target_pct?"},
|
| 135 |
-
}, indent=2)
|
| 136 |
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
with gr.Tabs():
|
| 145 |
-
|
| 146 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
with gr.Row():
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
)
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""jev-fin-0.8b: interactive demo (Gradio 6). Typed decisions with calibrated probabilities."""
|
| 2 |
+
import html
|
| 3 |
import importlib.util
|
| 4 |
import json
|
| 5 |
+
import math
|
| 6 |
import os
|
| 7 |
+
import random
|
| 8 |
import sys
|
| 9 |
+
import time
|
| 10 |
|
| 11 |
import gradio as gr
|
| 12 |
+
import pandas as pd
|
| 13 |
+
from huggingface_hub import hf_hub_download, snapshot_download
|
| 14 |
|
| 15 |
MODEL_REPO = os.environ.get("MODEL_REPO", "siyah1/jev-fin-0.8b")
|
| 16 |
+
TOKEN = os.environ.get("HF_TOKEN") # only needed if the model repo is private
|
| 17 |
|
| 18 |
+
try: # ZeroGPU when available, plain no-op otherwise
|
| 19 |
import spaces
|
| 20 |
gpu = spaces.GPU(duration=60)
|
| 21 |
except Exception: # noqa: BLE001
|
| 22 |
def gpu(fn):
|
| 23 |
return fn
|
| 24 |
|
| 25 |
+
# ----------------------------------------------------------------------------- model
|
| 26 |
_clf = None
|
| 27 |
|
| 28 |
|
| 29 |
def get_clf():
|
|
|
|
| 30 |
global _clf
|
| 31 |
if _clf is None:
|
| 32 |
+
p = hf_hub_download(MODEL_REPO, "jev_common.py", token=TOKEN)
|
| 33 |
+
spec = importlib.util.spec_from_file_location("jev_common", p)
|
| 34 |
mod = importlib.util.module_from_spec(spec)
|
| 35 |
sys.modules["jev_common"] = mod
|
| 36 |
spec.loader.exec_module(mod)
|
| 37 |
+
_clf = mod.JevClassifier(snapshot_download(MODEL_REPO, token=TOKEN))
|
|
|
|
|
|
|
| 38 |
print("model loaded on", _clf.device, flush=True)
|
| 39 |
return _clf
|
| 40 |
|
|
|
|
| 43 |
try:
|
| 44 |
get_clf()
|
| 45 |
except Exception as e: # noqa: BLE001
|
| 46 |
+
print("startup load failed (retry on first request):", repr(e), flush=True)
|
| 47 |
|
| 48 |
|
| 49 |
+
@gpu
|
| 50 |
+
def _decide(state, questions, debias):
|
| 51 |
+
return get_clf().decide(state, questions, debias=debias)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def device_name():
|
| 55 |
+
return _clf.device if _clf is not None else "?"
|
| 56 |
+
|
| 57 |
|
| 58 |
+
# ----------------------------------------------------------------------------- helpers
|
| 59 |
+
LETTERS = [chr(65 + i) for i in range(26)]
|
| 60 |
+
esc = lambda s: html.escape(str(s)) # noqa: E731
|
| 61 |
|
| 62 |
+
|
| 63 |
+
def build_prompt(state, question, options, qtype): # same template as training (for the "what the model sees" box)
|
| 64 |
+
opts = "\n".join(f"{LETTERS[i]}. {o}" for i, o in enumerate(options))
|
| 65 |
+
return (f"<state>\n{state}\n</state>\n<question type=\"{qtype}\">\n{question}\n</question>\n"
|
| 66 |
+
f"<options>\n{opts}\n</options>\nAnswer:")
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def parse_lines(text):
|
| 70 |
+
items = {}
|
| 71 |
+
for line in (text or "").splitlines():
|
| 72 |
+
line = line.strip()
|
| 73 |
+
if line:
|
| 74 |
+
k, _, v = line.partition(":")
|
| 75 |
+
items[k.strip()] = v.strip() or k.strip()
|
| 76 |
+
return items
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def make_spec(qtype, question, opts_text):
|
| 80 |
+
"""-> (spec for decide(), option names, question text as the model will see it)"""
|
| 81 |
+
q = question.strip()
|
| 82 |
+
spec = {"type": qtype, "instructions": q}
|
| 83 |
+
if qtype == "noul":
|
| 84 |
+
return spec, ["No", "Yes"], q
|
| 85 |
+
items = parse_lines(opts_text)
|
| 86 |
+
if not 2 <= len(items) <= 26:
|
| 87 |
+
raise ValueError("needs 2-26 options, one per line")
|
| 88 |
+
desc = any(k != v for k, v in items.items())
|
| 89 |
+
if qtype == "choice":
|
| 90 |
+
spec["criteria"] = items
|
| 91 |
+
return spec, list(items), q + "\n" + "\n".join(f"- {k}: {v}" for k, v in items.items())
|
| 92 |
+
spec["levels"] = items if desc else list(items)
|
| 93 |
+
return spec, list(items), q + ("\n" + "\n".join(f"- {k}: {v}" for k, v in items.items()) if desc else "")
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
# ----------------------------------------------------------------------------- styling + cards
|
| 97 |
+
CSS = """
|
| 98 |
+
.jv{--jv-card:var(--background-fill-secondary,#f8fafc);--jv-bd:var(--border-color-primary,#e2e8f0);--jv-tx:var(--body-text-color,#0f172a);--jv-mut:var(--body-text-color-subdued,#64748b);color:var(--jv-tx)}
|
| 99 |
+
.jv *{box-sizing:border-box}
|
| 100 |
+
.jv-hero{padding:26px 28px;border-radius:20px;background:linear-gradient(135deg,#4f46e5 0%,#0ea5e9 55%,#14b8a6 100%);color:#fff}
|
| 101 |
+
.jv-hero h1{margin:0 0 6px;font-size:1.9rem;font-weight:800;letter-spacing:-.02em;color:#fff}
|
| 102 |
+
.jv-hero p{margin:0;opacity:.95;max-width:780px;line-height:1.55;color:#fff}
|
| 103 |
+
.jv-steps{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:10px;margin-top:16px}
|
| 104 |
+
.jv-step{background:rgba(255,255,255,.15);border:1px solid rgba(255,255,255,.28);border-radius:12px;padding:10px 12px;font-size:.86rem;color:#fff}
|
| 105 |
+
.jv-step b{display:block;font-size:.95rem;margin-bottom:2px;color:#fff}
|
| 106 |
+
.jv-card{background:var(--jv-card);border:1px solid var(--jv-bd);border-radius:16px;padding:16px 18px;margin:0 0 12px;animation:jv-in .35s ease-out}
|
| 107 |
+
@keyframes jv-in{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}
|
| 108 |
+
@keyframes jv-grow{from{width:0}}
|
| 109 |
+
.jv-head{display:flex;align-items:center;gap:10px;margin-bottom:12px;flex-wrap:wrap}
|
| 110 |
+
.jv-tag{font-size:.68rem;font-weight:700;letter-spacing:.06em;text-transform:uppercase;padding:3px 9px;border-radius:999px;color:#fff;white-space:nowrap}
|
| 111 |
+
.jv-q{font-weight:600;line-height:1.35}
|
| 112 |
+
.jv-flex{display:flex;gap:18px;align-items:center;flex-wrap:wrap}
|
| 113 |
+
.jv-grow{flex:1;min-width:220px}
|
| 114 |
+
.jv-ring{width:104px;height:104px;border-radius:50%;background:conic-gradient(var(--c) calc(var(--p)*1%),var(--jv-bd) 0);display:grid;place-items:center;position:relative;flex:none}
|
| 115 |
+
.jv-ring::before{content:"";position:absolute;inset:10px;border-radius:50%;background:var(--jv-card)}
|
| 116 |
+
.jv-ring span{position:relative;font-weight:800;font-size:1.25rem}
|
| 117 |
+
.jv-pill{display:inline-block;color:#fff;font-weight:700;font-size:.85rem;padding:3px 12px;border-radius:999px;margin:0 8px 6px 0}
|
| 118 |
+
.jv-chip{display:inline-block;font-size:.76rem;padding:2px 9px;border-radius:999px;border:1px solid var(--jv-bd);color:var(--jv-mut);margin:0 6px 6px 0}
|
| 119 |
+
.jv-chip.up{color:#059669;border-color:#10b98177}.jv-chip.down{color:#e11d48;border-color:#f43f5e77}.jv-chip.warn{color:#b45309;border-color:#f59e0b88}
|
| 120 |
+
.jv-row{display:grid;grid-template-columns:minmax(80px,180px) 1fr 56px;gap:10px;align-items:center;margin:6px 0;font-size:.92rem}
|
| 121 |
+
.jv-row.top{font-weight:700}
|
| 122 |
+
.jv-track{height:12px;border-radius:99px;background:var(--jv-bd);overflow:hidden}
|
| 123 |
+
.jv-fill{height:100%;border-radius:99px;animation:jv-grow .8s ease-out}
|
| 124 |
+
.jv-pc{text-align:right;font-variant-numeric:tabular-nums;color:var(--jv-mut)}
|
| 125 |
+
.jv-ans{font-size:1.08rem;margin-bottom:10px}
|
| 126 |
+
.jv-ans b{font-size:1.2rem}
|
| 127 |
+
.jv-scale{position:relative;height:10px;border-radius:99px;background:linear-gradient(90deg,#6366f1,#14b8a6);margin:14px 4px 6px}
|
| 128 |
+
.jv-marker{position:absolute;top:-6px;width:4px;height:22px;border-radius:3px;background:var(--jv-tx);transform:translateX(-2px);box-shadow:0 0 0 3px var(--jv-card)}
|
| 129 |
+
.jv-cols{display:grid;gap:8px;align-items:end;margin-top:10px}
|
| 130 |
+
.jv-col{display:flex;flex-direction:column;align-items:stretch;text-align:center;font-size:.82rem}
|
| 131 |
+
.jv-colwrap{height:84px;display:flex;align-items:flex-end}
|
| 132 |
+
.jv-colbar{width:100%;border-radius:8px 8px 3px 3px;min-height:3px;animation:jv-grow .8s ease-out}
|
| 133 |
+
.jv-col .l{margin-top:4px;color:var(--jv-mut)}.jv-col .p{font-variant-numeric:tabular-nums;font-weight:600;margin-top:3px}
|
| 134 |
+
.jv-check{margin-top:10px;font-size:.86rem;padding:7px 11px;border-radius:10px}
|
| 135 |
+
.jv-check.ok{background:#10b98122;color:#047857}.jv-check.bad{background:#f59e0b22;color:#b45309}
|
| 136 |
+
.jv-note{margin-top:8px;font-size:.84rem;color:var(--jv-mut)}
|
| 137 |
+
.jv-summary{display:flex;gap:8px;flex-wrap:wrap;margin:2px 0 12px;color:var(--jv-mut);font-size:.84rem}
|
| 138 |
+
.jv-hold{display:grid;grid-template-columns:64px 1fr 120px;gap:10px;align-items:center;margin:7px 0;font-size:.88rem}
|
| 139 |
+
.jv-htrack{position:relative;height:14px;border-radius:99px;background:var(--jv-bd)}
|
| 140 |
+
.jv-hfill{height:100%;border-radius:99px;animation:jv-grow .8s ease-out}
|
| 141 |
+
.jv-targ{position:absolute;top:-4px;bottom:-4px;width:3px;border-radius:2px;background:var(--jv-tx)}
|
| 142 |
+
.jv-flow{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:12px}
|
| 143 |
+
.jv-flow>div{border:1px solid var(--jv-bd);background:var(--jv-card);border-radius:14px;padding:12px 14px;font-size:.88rem}
|
| 144 |
+
.jv-flow b{display:block;margin-bottom:3px}
|
| 145 |
+
.jv-empty{padding:28px;text-align:center;color:var(--jv-mut);border:1px dashed var(--jv-bd);border-radius:16px}
|
| 146 |
+
"""
|
| 147 |
+
TYPE_COL = {"noul": "#6366f1", "choice": "#0ea5e9", "score": "#14b8a6"}
|
| 148 |
+
TYPE_TAG = {"noul": "Yes / No", "choice": "Pick one", "score": "Ordered scale"}
|
| 149 |
+
GOOD, BAD, WARN, MUTED = "#10b981", "#f43f5e", "#f59e0b", "#94a3b8"
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def wrap(inner):
|
| 153 |
+
return f"<style>{CSS}</style><div class='jv'>{inner}</div>"
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def bars(items, top_color):
|
| 157 |
+
mx = max((p for _, p, _ in items), default=0)
|
| 158 |
out = []
|
| 159 |
+
for lab, p, col in items:
|
| 160 |
+
top = " top" if p == mx else ""
|
| 161 |
+
out.append(f"<div class='jv-row{top}'><span>{esc(lab)}</span><div class='jv-track'><div class='jv-fill' "
|
| 162 |
+
f"style='width:{p*100:.1f}%;background:{col}'></div></div><span class='jv-pc'>{p:.1%}</span></div>")
|
| 163 |
+
return "".join(out)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
|
| 165 |
|
| 166 |
+
def delta_chip(r, prev):
|
| 167 |
+
if not prev or prev["type"] != r["type"]:
|
| 168 |
+
return ""
|
| 169 |
+
if r["type"] == "noul":
|
| 170 |
+
d = (r["noul"] - prev["p"]) * 100
|
| 171 |
+
if abs(d) < 0.05:
|
| 172 |
+
return "<span class='jv-chip'>no change vs previous run</span>"
|
| 173 |
+
return f"<span class='jv-chip {'up' if d > 0 else 'down'}'>{'▲' if d > 0 else '▼'} {d:+.1f} pp vs previous run</span>"
|
| 174 |
+
label = r["choice"] if r["type"] == "choice" else r["level"]
|
| 175 |
+
if label != prev["label"]:
|
| 176 |
+
return f"<span class='jv-chip warn'>answer changed: {esc(prev['label'])} → {esc(label)}</span>"
|
| 177 |
+
d = (r["confidence"] - prev["conf"]) * 100
|
| 178 |
+
return f"<span class='jv-chip'>same answer, confidence {d:+.1f} pp</span>"
|
| 179 |
|
| 180 |
|
| 181 |
+
def card(title, r, prev=None, note="", check=None):
|
| 182 |
+
t = r["type"]
|
| 183 |
+
head = (f"<div class='jv-head'><span class='jv-tag' style='background:{TYPE_COL[t]}'>{TYPE_TAG[t]}</span>"
|
| 184 |
+
f"<span class='jv-q'>{esc(title)}</span></div>")
|
| 185 |
+
dl = delta_chip(r, prev)
|
| 186 |
+
if t == "noul":
|
| 187 |
+
p = r["noul"]
|
| 188 |
+
verdict, vc = ("Likely YES", GOOD) if p >= .65 else ("Likely NO", BAD) if p <= .35 else ("Uncertain", WARN)
|
| 189 |
+
body = (f"<div class='jv-flex'><div class='jv-ring' style='--p:{p*100:.1f};--c:{vc}'><span>{p:.0%}</span></div>"
|
| 190 |
+
f"<div class='jv-grow'><span class='jv-pill' style='background:{vc}'>{verdict}</span>{dl}"
|
| 191 |
+
f"{bars([('Yes', p, GOOD), ('No', 1 - p, BAD)], GOOD)}</div></div>")
|
| 192 |
+
elif t == "choice":
|
| 193 |
+
probs = sorted(r["probabilities"].items(), key=lambda x: -x[1])
|
| 194 |
+
low = "<span class='jv-chip warn'>low confidence</span>" if r["confidence"] < .5 else ""
|
| 195 |
+
body = (f"<div class='jv-ans'>Answer: <b>{esc(r['choice'])}</b> <span class='jv-chip'>confidence {r['confidence']:.0%}</span>{low}{dl}</div>"
|
| 196 |
+
+ bars([(n, p, TYPE_COL["choice"] if i == 0 else MUTED) for i, (n, p) in enumerate(probs)], TYPE_COL["choice"]))
|
| 197 |
+
else:
|
| 198 |
+
levels = list(r["probabilities"].items())
|
| 199 |
+
mx = max(p for _, p in levels)
|
| 200 |
+
cols = "".join(
|
| 201 |
+
f"<div class='jv-col'><div class='jv-colwrap'><div class='jv-colbar' style='height:{max(p, .02)*100:.0f}%;"
|
| 202 |
+
f"background:{TYPE_COL['score'] if p == mx else MUTED}'></div></div><div class='p'>{p:.0%}</div><div class='l'>{esc(n)}</div></div>"
|
| 203 |
+
for n, p in levels)
|
| 204 |
+
low = "<span class='jv-chip warn'>low confidence</span>" if r["confidence"] < .5 else ""
|
| 205 |
+
body = (f"<div class='jv-ans'>Level: <b>{esc(r['level'])}</b> <span class='jv-chip'>score {r['score']:.2f} (0 = lowest, 1 = highest)</span>{low}{dl}</div>"
|
| 206 |
+
f"<div class='jv-scale'><div class='jv-marker' style='left:{r['score']*100:.1f}%'></div></div>"
|
| 207 |
+
f"<div class='jv-cols' style='grid-template-columns:repeat({len(levels)},1fr)'>{cols}</div>")
|
| 208 |
+
extra = f"<div class='jv-note'>{note}</div>" if note else ""
|
| 209 |
+
if check:
|
| 210 |
+
truth, ok = check
|
| 211 |
+
extra += (f"<div class='jv-check ok'>✅ Matches the exact calculation ({esc(truth)})</div>" if ok else
|
| 212 |
+
f"<div class='jv-check bad'>⚠️ Exact calculation says <b>{esc(truth)}</b>. Check arithmetic-heavy answers with code.</div>")
|
| 213 |
+
return f"<div class='jv-card'>{head}{body}{extra}</div>"
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def snapshot(r):
|
| 217 |
+
if r["type"] == "noul":
|
| 218 |
+
return {"type": "noul", "p": r["noul"]}
|
| 219 |
+
return {"type": r["type"], "label": r.get("choice") or r.get("level"), "conf": r["confidence"]}
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def summary(dt, n):
|
| 223 |
+
return (f"<div class='jv-summary'><span>⏱ {dt:.1f}s</span><span>🖥 {esc(device_name())}</span>"
|
| 224 |
+
f"<span>{n} question{'s' if n != 1 else ''}</span><span>calibrated probabilities</span></div>")
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
# ----------------------------------------------------------------------------- presets + playground
|
| 228 |
+
N_SLOTS = 3
|
| 229 |
+
NEWS = "Acme Corp cut full-year guidance and the CFO resigned effective immediately."
|
| 230 |
+
j = json.dumps
|
| 231 |
+
PRESETS = {
|
| 232 |
+
"📰 News shock": dict(state=NEWS, qs=[
|
| 233 |
+
("noul", "Is this news negative for the stock?", ""),
|
| 234 |
+
("choice", "Which topic does this belong to?", "earnings: results or guidance\npersonnel: executive changes\nm&a: mergers and deals"),
|
| 235 |
+
("score", "How negative is this news?", "mild\nmoderate\nsevere")]),
|
| 236 |
+
"🏦 Fed statement": dict(state="The Committee decided to raise the target range for the federal funds rate by 75 basis points and anticipates that ongoing increases will be appropriate to bring inflation back to 2 percent.", qs=[
|
| 237 |
+
("score", "What is the monetary-policy stance of this FOMC statement?", "dovish\nneutral\nhawkish"),
|
| 238 |
+
("noul", "Does this statement signal tighter (hawkish) monetary policy?", ""),
|
| 239 |
+
("noul", "Does this statement signal easier (dovish) monetary policy?", "")]),
|
| 240 |
+
"🐦 Finance tweet": dict(state="$AMZN - Morgan Stanley upgrades to Overweight, raises price target to $210 ahead of Q3 earnings", qs=[
|
| 241 |
+
("score", "What is the market sentiment of this finance tweet?", "Bearish\nNeutral\nBullish"),
|
| 242 |
+
("choice", "Which topic does this financial news tweet belong to?", "Analyst Update\nEarnings\nCompany | Product News\nStock Movement\nM&A | Investments"),
|
| 243 |
+
("noul", "Does this text express a positive (bullish) outlook?", "")]),
|
| 244 |
+
"🏢 Company health": dict(state=j({"company": {"revenue_musd": 820.0, "ebit_musd": 96.0, "interest_expense_musd": 41.0, "net_income_musd": 38.5,
|
| 245 |
+
"total_assets_musd": 1100.0, "total_liabilities_musd": 780.0, "equity_musd": 320.0,
|
| 246 |
+
"current_assets_musd": 210.0, "current_liabilities_musd": 260.0}}), qs=[
|
| 247 |
+
("noul", "Is the current ratio (current_assets_musd / current_liabilities_musd) below 1.0?", ""),
|
| 248 |
+
("score", "Rate liquidity by current ratio = current_assets_musd / current_liabilities_musd (weak: below 1.0, adequate: 1.0 to below 1.5, strong: 1.5 to below 2.5, very strong: 2.5 or above).", "weak\nadequate\nstrong\nvery strong"),
|
| 249 |
+
("choice", "Classify leverage by debt-to-equity = total_liabilities_musd / equity_musd (conservative: below 0.5, moderate: 0.5 to below 1.5, aggressive: 1.5 or above).", "conservative\nmoderate\naggressive")]),
|
| 250 |
+
"🏠 Loan application": dict(state=j({"loan_application": {"annual_income": 72000, "monthly_debt_payments": 1450, "requested_monthly_payment": 1300,
|
| 251 |
+
"credit_score": 655, "loan_to_value_pct": 88.0}}), qs=[
|
| 252 |
+
("noul", "Is the back-end debt-to-income ratio, (monthly_debt_payments + requested_monthly_payment) / (annual_income / 12), above 43%?", ""),
|
| 253 |
+
("score", "Rate the credit tier by credit_score (poor: below 580, fair: 580 to 669, good: 670 to 739, very good: 740 to 799, exceptional: 800 or above).", "poor\nfair\ngood\nvery good\nexceptional"),
|
| 254 |
+
("choice", "Apply in order: decline if back-end DTI (as above) is over 50%; otherwise manual review if credit_score < 620 or loan_to_value_pct > 95; otherwise approve.", "approve\nmanual review\ndecline")]),
|
| 255 |
+
"📉 Macro snapshot": dict(state=j({"macro": {"fed_funds_pct": 5.25, "cpi_yoy_pct": 4.8, "unemployment_pct": 4.1,
|
| 256 |
+
"yield_3m_pct": 5.3, "yield_2y_pct": 4.9, "yield_10y_pct": 4.2}}), qs=[
|
| 257 |
+
("noul", "Is the 2y/10y yield curve inverted (yield_2y_pct above yield_10y_pct)?", ""),
|
| 258 |
+
("score", "Rate the real policy rate = fed_funds_pct - cpi_yoy_pct (deeply negative: below -2, negative: -2 to below 0, mildly positive: 0 to below 2, restrictive: 2 or above).", "deeply negative\nnegative\nmildly positive\nrestrictive"),
|
| 259 |
+
("choice", "Which regime fits? stagflation: cpi_yoy_pct >= 4 and unemployment_pct >= 6; overheating: cpi_yoy_pct >= 4 and unemployment_pct < 6; slack: cpi_yoy_pct < 4 and unemployment_pct >= 6; goldilocks: cpi_yoy_pct < 4 and unemployment_pct < 6.", "stagflation\noverheating\nslack\ngoldilocks")]),
|
| 260 |
+
}
|
| 261 |
+
OPT_HELP = {
|
| 262 |
+
"noul": dict(visible=False),
|
| 263 |
+
"choice": dict(visible=True, label="Choices (one per line)", info="Optional description after a colon, e.g. `personnel: executive changes`", placeholder="earnings: results or guidance\npersonnel: executive changes"),
|
| 264 |
+
"score": dict(visible=True, label="Levels, lowest to highest (one per line)", info="Order matters: the first line is the lowest level.", placeholder="mild\nmoderate\nsevere"),
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def opt_update(t):
|
| 269 |
+
return gr.update(**OPT_HELP[t])
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def load_preset(name):
|
| 273 |
+
p = PRESETS[name]
|
| 274 |
+
out = [p["state"]]
|
| 275 |
+
for i in range(N_SLOTS):
|
| 276 |
+
if i < len(p["qs"]):
|
| 277 |
+
t, q, o = p["qs"][i]
|
| 278 |
+
out += [True, t, q, gr.update(value=o, **OPT_HELP[t])]
|
| 279 |
+
else:
|
| 280 |
+
out += [False, "noul", "", gr.update(value="", **OPT_HELP["noul"])]
|
| 281 |
+
return out
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def run_playground(state, prev, debias, *vals):
|
| 285 |
+
if not str(state).strip():
|
| 286 |
+
raise gr.Error("Enter a state: some text or JSON for the model to read.")
|
| 287 |
+
qs, info, prompts = {}, {}, []
|
| 288 |
+
for i in range(N_SLOTS):
|
| 289 |
+
en, t, q, o = vals[4 * i: 4 * i + 4]
|
| 290 |
+
if not en or not str(q).strip():
|
| 291 |
+
continue
|
| 292 |
+
try:
|
| 293 |
+
spec, base, text = make_spec(t, q, o)
|
| 294 |
+
except ValueError as e:
|
| 295 |
+
raise gr.Error(f"Question {i + 1}: {e}")
|
| 296 |
+
qs[f"q{i + 1}"] = spec
|
| 297 |
+
info[f"q{i + 1}"] = q.strip()
|
| 298 |
+
st = state if len(state) <= 1600 else state[:1600] + " ..."
|
| 299 |
+
prompts.append(f"# ---- question {i + 1} ----\n" + build_prompt(st, text, base, t))
|
| 300 |
+
if not qs:
|
| 301 |
+
raise gr.Error("Switch on at least one question and fill in its text.")
|
| 302 |
+
t0 = time.time()
|
| 303 |
try:
|
| 304 |
+
res = _decide(state, qs, bool(debias))
|
| 305 |
except Exception as e: # noqa: BLE001
|
| 306 |
raise gr.Error(f"Inference failed: {e!r}")
|
| 307 |
+
dt = time.time() - t0
|
| 308 |
+
prev = prev or {}
|
| 309 |
+
cards = "".join(card(info[k], res[k], prev.get(info[k])) for k in qs)
|
| 310 |
+
new_prev = {info[k]: snapshot(res[k]) for k in qs}
|
| 311 |
+
return wrap(summary(dt, len(qs)) + cards), new_prev, res, "\n\n".join(prompts)
|
| 312 |
|
| 313 |
|
| 314 |
+
EMPTY = wrap("<div class='jv-empty'>Pick a scenario above, or write your own state and questions, then press <b>Analyze</b>.</div>")
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
# ----------------------------------------------------------------------------- portfolio lab
|
| 318 |
+
UNIV = {"AAPL": "Technology", "MSFT": "Technology", "NVDA": "Technology", "GOOGL": "Communication", "META": "Communication",
|
| 319 |
+
"AMZN": "Consumer Discretionary", "TSLA": "Consumer Discretionary", "JPM": "Financials", "BAC": "Financials",
|
| 320 |
+
"V": "Financials", "JNJ": "Health Care", "PFE": "Health Care", "LLY": "Health Care", "XOM": "Energy", "CVX": "Energy",
|
| 321 |
+
"KO": "Consumer Staples", "PG": "Consumer Staples", "WMT": "Consumer Staples", "CAT": "Industrials", "BA": "Industrials",
|
| 322 |
+
"NEE": "Utilities", "AMT": "Real Estate", "LIN": "Materials", "TLT": "Bonds", "AGG": "Bonds", "GLD": "Commodities",
|
| 323 |
+
"SPY": "Broad Market ETF", "QQQ": "Broad Market ETF"}
|
| 324 |
+
VOL = {"Technology": (22, 45), "Communication": (20, 38), "Consumer Discretionary": (20, 50), "Financials": (18, 35),
|
| 325 |
+
"Health Care": (14, 30), "Energy": (22, 40), "Consumer Staples": (10, 20), "Industrials": (16, 32), "Utilities": (12, 22),
|
| 326 |
+
"Real Estate": (16, 30), "Materials": (18, 36), "Bonds": (5, 15), "Commodities": (12, 22), "Broad Market ETF": (13, 24)}
|
| 327 |
+
PF_COLS = ["ticker", "sector", "weight_pct", "target_pct", "annual_vol_pct"]
|
| 328 |
+
PF_DEFAULT = pd.DataFrame([
|
| 329 |
+
["NVDA", "Technology", 38.0, 30.0, 40.0], ["AAPL", "Technology", 22.0, 25.0, 28.0], ["JPM", "Financials", 15.0, 15.0, 24.0],
|
| 330 |
+
["XOM", "Energy", 10.0, 12.0, 28.0], ["AGG", "Bonds", 15.0, 18.0, 6.0]], columns=PF_COLS)
|
| 331 |
+
PF_Q = [
|
| 332 |
+
("noul", "Is any single holding larger than 30% of the portfolio (weight_pct)?", None),
|
| 333 |
+
("noul", "Does any single sector account for more than 50% of total portfolio weight?", None),
|
| 334 |
+
("noul", "Has any holding drifted more than 5 percentage points away from its target_pct?", None),
|
| 335 |
+
("score", "Rate the portfolio risk using the weight-averaged annual_vol_pct (low: below 12, medium: 12-20, high: 20-30, very high: above 30).",
|
| 336 |
+
["low", "medium", "high", "very high"]),
|
| 337 |
+
("choice", "How diversified is this portfolio by the Herfindahl index, i.e. sum of squared weights (below 0.15 well diversified, 0.15-0.30 moderately concentrated, above 0.30 highly concentrated)?",
|
| 338 |
+
{"well diversified": "HHI below 0.15", "moderately concentrated": "HHI 0.15 to 0.30", "highly concentrated": "HHI above 0.30"}),
|
| 339 |
+
]
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def df_to_holdings(df):
|
| 343 |
+
rows = []
|
| 344 |
+
for _, r in pd.DataFrame(df).iterrows():
|
| 345 |
+
tk = str(r["ticker"]).strip()
|
| 346 |
+
if not tk or tk.lower() in ("nan", "none"):
|
| 347 |
continue
|
| 348 |
+
try:
|
| 349 |
+
w, tg, v = float(r["weight_pct"]), float(r["target_pct"]), float(r["annual_vol_pct"])
|
| 350 |
+
assert not any(math.isnan(x) for x in (w, tg, v))
|
| 351 |
+
except Exception: # noqa: BLE001
|
| 352 |
+
raise gr.Error(f"Row '{tk}': weight_pct, target_pct and annual_vol_pct must be numbers.")
|
| 353 |
+
sec = str(r["sector"]).strip()
|
| 354 |
+
rows.append({"ticker": tk, "sector": sec if sec and sec.lower() != "nan" else "Unknown",
|
| 355 |
+
"weight_pct": round(w, 1), "target_pct": round(max(tg, 0.0), 1), "annual_vol_pct": round(v, 1)})
|
| 356 |
+
if not rows:
|
| 357 |
+
raise gr.Error("Add at least one holding.")
|
| 358 |
+
return rows
|
| 359 |
|
| 360 |
|
| 361 |
+
def exact_portfolio(h):
|
| 362 |
+
W = [x["weight_pct"] for x in h]
|
| 363 |
+
tw = sum(W) or 1.0
|
| 364 |
+
sec = {}
|
| 365 |
+
for x in h:
|
| 366 |
+
sec[x["sector"]] = sec.get(x["sector"], 0) + x["weight_pct"]
|
| 367 |
+
wavol = sum(x["weight_pct"] * x["annual_vol_pct"] for x in h) / tw
|
| 368 |
+
hhi = sum((w / tw) ** 2 for w in W)
|
| 369 |
+
top_sec = max(sec, key=sec.get)
|
| 370 |
+
drift = max(abs(x["weight_pct"] - x["target_pct"]) for x in h)
|
| 371 |
+
risk = "low" if wavol < 12 else "medium" if wavol < 20 else "high" if wavol < 30 else "very high"
|
| 372 |
+
div = "well diversified" if hhi < .15 else "moderately concentrated" if hhi < .30 else "highly concentrated"
|
| 373 |
+
big = max(h, key=lambda x: x["weight_pct"])
|
| 374 |
+
return [
|
| 375 |
+
("Yes" if max(W) > 30 else "No", f"largest holding: {big['ticker']} at {big['weight_pct']}%"),
|
| 376 |
+
("Yes" if sec[top_sec] > 50 else "No", f"largest sector: {top_sec} at {sec[top_sec]:.1f}%"),
|
| 377 |
+
("Yes" if drift > 5 else "No", f"max drift: {drift:.1f} percentage points"),
|
| 378 |
+
(risk, f"weighted volatility: {wavol:.1f}%"),
|
| 379 |
+
(div, f"HHI: {hhi:.3f}"),
|
| 380 |
+
]
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
PALETTE = ["#6366f1", "#14b8a6", "#f59e0b", "#ec4899", "#0ea5e9", "#84cc16", "#a855f7", "#f97316", "#64748b", "#22c55e"]
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def holdings_chart(h):
|
| 387 |
+
secs = sorted({x["sector"] for x in h})
|
| 388 |
+
col = {s: PALETTE[i % len(PALETTE)] for i, s in enumerate(secs)}
|
| 389 |
+
sc = max(max(x["weight_pct"], x["target_pct"]) for x in h) or 1
|
| 390 |
+
rows = "".join(
|
| 391 |
+
f"<div class='jv-hold'><b>{esc(x['ticker'])}</b><div class='jv-htrack'><div class='jv-hfill' style='width:{x['weight_pct']/sc*100:.1f}%;background:{col[x['sector']]}'></div>"
|
| 392 |
+
f"<div class='jv-targ' style='left:{x['target_pct']/sc*100:.1f}%'></div></div>"
|
| 393 |
+
f"<span class='jv-pc'>{x['weight_pct']}% <span style='opacity:.7'>(target {x['target_pct']}%)</span></span></div>" for x in h)
|
| 394 |
+
legend = "".join(f"<span class='jv-chip'><span style='color:{col[s]}'>●</span> {esc(s)}</span>" for s in secs)
|
| 395 |
+
return (f"<div class='jv-card'><div class='jv-head'><span class='jv-q'>Holdings: bar = weight, black marker = target</span></div>{rows}"
|
| 396 |
+
f"<div style='margin-top:8px'>{legend}</div></div>")
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def run_portfolio(df, prev, debias):
|
| 400 |
+
h = df_to_holdings(df)
|
| 401 |
+
note = ""
|
| 402 |
+
tw = sum(x["weight_pct"] for x in h)
|
| 403 |
+
warns = []
|
| 404 |
+
if abs(tw - 100) > 1:
|
| 405 |
+
warns.append(f"weights sum to {tw:.1f}% (the model saw portfolios that sum to about 100%)")
|
| 406 |
+
if not 3 <= len(h) <= 12:
|
| 407 |
+
warns.append(f"{len(h)} holdings (training used 3 to 12)")
|
| 408 |
+
if warns:
|
| 409 |
+
note = "<div class='jv-card'><span class='jv-chip warn'>heads-up</span> " + "; ".join(warns) + ". Answers may be less reliable.</div>"
|
| 410 |
+
state = json.dumps({"portfolio": h})
|
| 411 |
+
qs = {f"q{i}": ({"type": t, "instructions": q, **({"levels": o} if t == "score" else {"criteria": o} if t == "choice" else {})})
|
| 412 |
+
for i, (t, q, o) in enumerate(PF_Q)}
|
| 413 |
+
t0 = time.time()
|
| 414 |
try:
|
| 415 |
+
res = _decide(state, qs, bool(debias))
|
| 416 |
except Exception as e: # noqa: BLE001
|
| 417 |
raise gr.Error(f"Inference failed: {e!r}")
|
| 418 |
+
dt = time.time() - t0
|
| 419 |
+
truth = exact_portfolio(h)
|
| 420 |
+
prev = prev or {}
|
| 421 |
+
out, new_prev = [], {}
|
| 422 |
+
for i, (t, q, o) in enumerate(PF_Q):
|
| 423 |
+
r = res[f"q{i}"]
|
| 424 |
+
ans = ("Yes" if r["noul"] >= .5 else "No") if t == "noul" else (r["choice"] if t == "choice" else r["level"])
|
| 425 |
+
short = q.split(" (")[0].split(", i.e.")[0]
|
| 426 |
+
out.append(card(short, r, prev.get(short), note=esc(truth[i][1]), check=(truth[i][0], ans == truth[i][0])))
|
| 427 |
+
new_prev[short] = snapshot(r)
|
| 428 |
+
return wrap(summary(dt, len(PF_Q)) + note + holdings_chart(h) + "".join(out)), new_prev
|
| 429 |
|
| 430 |
|
| 431 |
+
def random_portfolio():
|
| 432 |
+
n = random.randint(4, 9)
|
| 433 |
+
tk = random.sample(list(UNIV), n)
|
| 434 |
+
a = random.choice([0.7, 1.5, 4.0])
|
| 435 |
+
w = [random.gammavariate(a, 1) + 1e-6 for _ in tk]
|
| 436 |
+
s = sum(w)
|
| 437 |
+
w = [round(100 * x / s, 1) for x in w]
|
| 438 |
+
rows = []
|
| 439 |
+
for t_, w_ in zip(tk, w):
|
| 440 |
+
lo, hi = VOL[UNIV[t_]]
|
| 441 |
+
rows.append([t_, UNIV[t_], w_, round(max(0.0, w_ + random.gauss(0, 4)), 1), round(random.uniform(lo, hi), 1)])
|
| 442 |
+
return pd.DataFrame(rows, columns=PF_COLS)
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def normalise(df):
|
| 446 |
+
d = pd.DataFrame(df).copy()
|
| 447 |
+
d["weight_pct"] = pd.to_numeric(d["weight_pct"], errors="coerce")
|
| 448 |
+
tot = d["weight_pct"].sum()
|
| 449 |
+
if tot and not math.isnan(tot):
|
| 450 |
+
d["weight_pct"] = (d["weight_pct"] / tot * 100).round(1)
|
| 451 |
+
return d
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
# ----------------------------------------------------------------------------- JSON / API tab
|
| 455 |
DEFAULT_SPEC = json.dumps({
|
| 456 |
"negative": {"type": "noul", "instructions": "Is this news negative for the stock?"},
|
| 457 |
"topic": {"type": "choice", "instructions": "Which topic does this belong to?",
|
| 458 |
"criteria": {"earnings": "results or guidance", "personnel": "executive changes", "m&a": "mergers and deals"}},
|
| 459 |
"severity": {"type": "score", "instructions": "How negative is this news?", "levels": ["mild", "moderate", "severe"]},
|
| 460 |
}, indent=2)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 461 |
|
| 462 |
+
|
| 463 |
+
def run_json(state, spec_text, debias):
|
| 464 |
+
if not str(state).strip():
|
| 465 |
+
raise gr.Error("Enter a state.")
|
| 466 |
+
try:
|
| 467 |
+
qs = json.loads(spec_text)
|
| 468 |
+
assert isinstance(qs, dict) and qs
|
| 469 |
+
for q in qs.values():
|
| 470 |
+
assert q["type"].lower() in ("noul", "choice", "score")
|
| 471 |
+
except Exception as e: # noqa: BLE001
|
| 472 |
+
raise gr.Error(f"Questions JSON is invalid: {e!r}")
|
| 473 |
+
try:
|
| 474 |
+
res = _decide(state, qs, bool(debias))
|
| 475 |
+
except Exception as e: # noqa: BLE001
|
| 476 |
+
raise gr.Error(f"Inference failed: {e!r}")
|
| 477 |
+
return wrap("".join(card(k, r) for k, r in res.items())), res
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
# ----------------------------------------------------------------------------- about tab
|
| 481 |
+
def load_metrics():
|
| 482 |
+
try:
|
| 483 |
+
p = hf_hub_download(MODEL_REPO, "metrics.json", token=TOKEN)
|
| 484 |
+
df = pd.DataFrame(json.load(open(p)))
|
| 485 |
+
df = df[["slice", "n", "acc", "ece_raw", "ece_cal", "brier_cal"]]
|
| 486 |
+
df.columns = ["slice", "test rows", "accuracy", "ECE (raw)", "ECE (calibrated)", "Brier (calibrated)"]
|
| 487 |
+
return df
|
| 488 |
+
except Exception: # noqa: BLE001
|
| 489 |
+
return pd.DataFrame({"info": ["metrics.json not available (model repo private or not reachable)"]})
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
HERO = wrap("""
|
| 493 |
+
<div class='jv-hero'>
|
| 494 |
+
<h1>📊 jev-fin-0.8b</h1>
|
| 495 |
+
<p>A small finance model that <b>doesn't write text</b>. You give it some text or JSON and a typed question, and it answers
|
| 496 |
+
with a <b>calibrated probability</b> in a single forward pass. Fast, checkable, and easy to plug into agents and pipelines.</p>
|
| 497 |
+
<div class='jv-steps'>
|
| 498 |
+
<div class='jv-step'><b>1 · Pick a scenario</b>news, Fed text, tweets, financials, loans, macro</div>
|
| 499 |
+
<div class='jv-step'><b>2 · Shape the questions</b>yes/no, pick one, or an ordered scale</div>
|
| 500 |
+
<div class='jv-step'><b>3 · Read the odds</b>rings, bars and a scale, with change vs your last run</div>
|
| 501 |
+
</div>
|
| 502 |
+
</div>""")
|
| 503 |
+
|
| 504 |
+
FLOW = wrap("""
|
| 505 |
+
<div class='jv-flow'>
|
| 506 |
+
<div><b>1 · State + question</b>Your text or JSON, plus a typed question with options.</div>
|
| 507 |
+
<div><b>2 · Lettered prompt</b>Options become A, B, C… (shuffled and averaged in debias mode).</div>
|
| 508 |
+
<div><b>3 · One forward pass</b>Only the logits of the letter tokens are read. No text generation.</div>
|
| 509 |
+
<div><b>4 · Calibrated odds</b>Softmax with a temperature fitted on held-out data.</div>
|
| 510 |
+
</div>""")
|
| 511 |
+
|
| 512 |
+
TIPS = """
|
| 513 |
+
**Writing good questions**
|
| 514 |
+
- **Yes / No** gives the probability of *Yes*. Phrase it so that "Yes" is meaningful, e.g. *"Is this news negative for the stock?"*.
|
| 515 |
+
- **Pick one** works best with a short description per choice (`name: description`).
|
| 516 |
+
- **Ordered scale**: list levels from lowest to highest. You also get an expected score between 0 and 1.
|
| 517 |
+
- Put thresholds in the question text for numeric JSON states, like the examples do.
|
| 518 |
+
- **Debias** asks twice with the options reversed and averages the two. It is slower but removes position bias.
|
| 519 |
+
|
| 520 |
+
**Limits**
|
| 521 |
+
- It classifies the text or state you give it. It does **not** predict returns.
|
| 522 |
+
- Arithmetic-heavy answers (the Portfolio lab) are learned from rule-labelled synthetic data. The lab shows the exact calculation next to the model's answer.
|
| 523 |
+
- Calibration is measured in-distribution. Expect it to be worse on questions unlike the training tasks.
|
| 524 |
+
- Not financial advice. Part of the training data is non-commercial, so use is **non-commercial only**.
|
| 525 |
+
"""
|
| 526 |
+
|
| 527 |
+
# ----------------------------------------------------------------------------- UI
|
| 528 |
+
with gr.Blocks(title="jev-fin-0.8b: typed finance decisions") as demo:
|
| 529 |
+
gr.HTML(HERO)
|
| 530 |
with gr.Tabs():
|
| 531 |
+
# ---------------- playground
|
| 532 |
+
with gr.Tab("🧪 Playground"):
|
| 533 |
+
gr.Markdown("**Start from a scenario** (it loads the text and questions and runs them), then edit anything and press **Analyze** to see what-if changes.")
|
| 534 |
+
with gr.Row():
|
| 535 |
+
pbtns = [gr.Button(n, size="sm") for n in PRESETS]
|
| 536 |
+
state = gr.Textbox(label="State: text or JSON the model reads", lines=5, value=PRESETS["📰 News shock"]["state"])
|
| 537 |
+
slot_inputs = []
|
| 538 |
+
for i in range(N_SLOTS):
|
| 539 |
+
t0_, q0_, o0_ = PRESETS["📰 News shock"]["qs"][i]
|
| 540 |
+
with gr.Accordion(f"Question {i + 1}", open=True):
|
| 541 |
+
with gr.Row():
|
| 542 |
+
en = gr.Checkbox(value=True, label="Use this question", scale=1, min_width=120)
|
| 543 |
+
typ = gr.Radio(choices=[("Yes / No", "noul"), ("Pick one", "choice"), ("Ordered scale", "score")],
|
| 544 |
+
value=t0_, label="Type", scale=3)
|
| 545 |
+
q = gr.Textbox(label="Question", value=q0_)
|
| 546 |
+
o = gr.Textbox(**{"label": "Options", "lines": 3, "value": o0_, **OPT_HELP[t0_]})
|
| 547 |
+
typ.change(opt_update, typ, o)
|
| 548 |
+
slot_inputs += [en, typ, q, o]
|
| 549 |
with gr.Row():
|
| 550 |
+
debias = gr.Checkbox(value=True, label="Debias (average over reversed option order)")
|
| 551 |
+
go = gr.Button("▶ Analyze", variant="primary", scale=2)
|
| 552 |
+
prev = gr.State({})
|
| 553 |
+
out = gr.HTML(EMPTY)
|
| 554 |
+
with gr.Accordion("🔍 What the model actually sees", open=False):
|
| 555 |
+
prompt_box = gr.Textbox(label="Prompts (one per question)", lines=14, interactive=False)
|
| 556 |
+
with gr.Accordion("{ } Raw output", open=False):
|
| 557 |
+
raw = gr.JSON()
|
| 558 |
+
run_ins = [state, prev, debias, *slot_inputs]
|
| 559 |
+
run_outs = [out, prev, raw, prompt_box]
|
| 560 |
+
go.click(run_playground, run_ins, run_outs)
|
| 561 |
+
for b, name in zip(pbtns, PRESETS):
|
| 562 |
+
b.click(lambda n=name: (load_preset(n)), None, [state, *slot_inputs]).then(run_playground, run_ins, run_outs)
|
| 563 |
+
|
| 564 |
+
# ---------------- portfolio lab
|
| 565 |
+
with gr.Tab("💼 Portfolio lab"):
|
| 566 |
+
gr.Markdown("Edit the table (add rows, change weights or targets) and press **Analyze**. "
|
| 567 |
+
"The model answers five risk questions, and each answer is **checked against the exact calculation**.")
|
| 568 |
+
pf = gr.Dataframe(value=PF_DEFAULT, headers=PF_COLS, datatype=["str", "str", "number", "number", "number"],
|
| 569 |
+
row_count=(5, "dynamic"), column_count=(5, "fixed"), interactive=True, label="Holdings")
|
| 570 |
+
with gr.Row():
|
| 571 |
+
rnd = gr.Button("🎲 Random portfolio", size="sm")
|
| 572 |
+
nrm = gr.Button("⚖️ Normalise weights to 100%", size="sm")
|
| 573 |
+
pf_debias = gr.Checkbox(value=True, label="Debias")
|
| 574 |
+
pgo = gr.Button("▶ Analyze portfolio", variant="primary", scale=2)
|
| 575 |
+
pf_prev = gr.State({})
|
| 576 |
+
pf_out = gr.HTML(wrap("<div class='jv-empty'>Press <b>Analyze portfolio</b>. Then change a weight and run again to see the odds move.</div>"))
|
| 577 |
+
rnd.click(random_portfolio, None, pf)
|
| 578 |
+
nrm.click(normalise, pf, pf)
|
| 579 |
+
pgo.click(run_portfolio, [pf, pf_prev, pf_debias], [pf_out, pf_prev])
|
| 580 |
+
|
| 581 |
+
# ---------------- JSON
|
| 582 |
+
with gr.Tab("🧩 API / JSON"):
|
| 583 |
+
gr.Markdown("Same format as `JevClassifier.decide(state, questions)`: handy for copying into your own code.")
|
| 584 |
+
j_state = gr.Textbox(label="State", lines=4, value=NEWS)
|
| 585 |
+
j_spec = gr.Code(label="Questions (JSON)", language="json", value=DEFAULT_SPEC, lines=16)
|
| 586 |
+
j_debias = gr.Checkbox(value=True, label="Debias")
|
| 587 |
+
j_go = gr.Button("▶ Run", variant="primary")
|
| 588 |
+
j_out = gr.HTML()
|
| 589 |
+
with gr.Accordion("{ } Raw output", open=False):
|
| 590 |
+
j_raw = gr.JSON()
|
| 591 |
+
j_go.click(run_json, [j_state, j_spec, j_debias], [j_out, j_raw])
|
| 592 |
+
|
| 593 |
+
# ---------------- about
|
| 594 |
+
with gr.Tab("ℹ️ About"):
|
| 595 |
+
gr.HTML(FLOW)
|
| 596 |
+
gr.Markdown(TIPS)
|
| 597 |
+
gr.Markdown("### Held-out test metrics (read live from the model repo)\nECE = expected calibration error (lower is better). "
|
| 598 |
+
"Compare *accuracy* with the majority-class baseline of each source before trusting a slice.")
|
| 599 |
+
gr.Dataframe(value=load_metrics, interactive=False, wrap=True)
|
| 600 |
+
|
| 601 |
+
try:
|
| 602 |
+
demo.queue(max_size=16).launch(theme=gr.themes.Soft(primary_hue="indigo", secondary_hue="teal"))
|
| 603 |
+
except TypeError: # older Gradio keeps theme on Blocks()
|
| 604 |
+
demo.queue(max_size=16).launch()
|