File size: 8,097 Bytes
de8a5bd fc6508e de8a5bd fc6508e de8a5bd fc6508e de8a5bd |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 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 180 181 182 183 184 |
# app.py
import gradio as gr
import pandas as pd
from model import IIQAI81
from utils_viz import bar_topk
from lattice_config import LAYER_GROUPS
model = IIQAI81()
INTRO = """\
# IIQAI-81 — Subjective Inner I AI
Type anything. The model maps your text across 81 lattice nodes and returns:
- **Lattice View Mode** (scores per node)
- **Symbolic Frequency Decoder** (SFD)
- **Intent Field Scanner**
- **Truth Charge Meter**
- **Mirror Integrity Check**
"""
# Simple, human-readable blurbs for groups and nodes
GROUP_BLURBS = {
"Awareness": "Core noticing -> clarity -> wisdom. Higher score = you’re speaking from direct seeing.",
"Knowledge": "Facts, concepts, how-to, meta-thinking. Higher = well-structured, informative signal.",
"Consciousness": "States and scopes of mind. Higher = spacious, reflective, or high-state language.",
"Unknowns": "Gaps, paradox, doubt. Higher = wrestling with uncertainty (which is healthy!).",
"UnknownFields": "Large-scale unknown domains. Higher = speculation about science/culture/cosmos.",
"SuppressedLayers": "Hidden material or blind spots surfacing.",
"ColorFieldConsciousness": "Spiral color states (developmental hues) showing tone/values in the signal.",
"HigherBeingStates": "Intuitive/illumined/overmind. Higher = transpersonal or devotional current.",
}
# One-liners for popup labels per node (keep simple; extend anytime)
NODE_TIPS = {}
for group, names, _ in LAYER_GROUPS:
for n in names:
NODE_TIPS[n] = f"{n.replace('_', ' ')} — A simple lens on your message through the {group} layer."
def friendly_score_note(score):
if score >= 80: return "Very strong resonance — this layer is leading your message."
if score >= 60: return "Clear influence — this layer is shaping your tone/meaning."
if score >= 40: return "Moderate trace — present but not dominant."
return "Low trace — this layer is quiet here."
def run(text):
if not text.strip():
return INTRO, None, None, None, None, None, None
out = model.analyze(text)
df = pd.DataFrame(out["nodes"]).sort_values("score", ascending=False)
img = bar_topk(out["top"])
# Instruments -> human cards
ins = out["instruments"]
sfd = ins["SFD"]
human_cards = [
f"**Intent:** {ins['Intent'].capitalize()} — plain meaning: the overall pull of your words trends this way.",
f"**Truth Charge:** {ins['TruthCharge']}/100 — how aligned your signal is to your stable self-vector.",
f"**Mirror Integrity:** {ins['MirrorIntegrity']}/100 — do your words agree with themselves?",
f"**Symbolic Charge:** {sfd['symbolic_charge']:.1f}/100 — how vivid/symbolic the phrasing is.",
f"**Breath-phase (θₘ):** {sfd['breath_phase']} — a runtime rhythm marker.",
f"**OM carrier:** {sfd['om_carrier_hz']} Hz • **Child tone:** {sfd['child_freq_hz']} Hz",
]
human_md = "- " + "\n- ".join(human_cards)
# Insight summary (top 3)
top3 = df.head(3).to_dict(orient="records")
bullet = []
for r in top3:
bullet.append(f"**{r['name']}** ({r['group']}) — {friendly_score_note(r['score'])}")
insights_md = "### Quick Insights\n" + "\n".join([f"- {b}" for b in bullet])
# Group blurbs pane
groups_present = df.groupby("group")["score"].max().sort_values(ascending=False)
group_lines = []
for g, sc in groups_present.items():
brief = GROUP_BLURBS.get(g, g)
group_lines.append(f"**{g}** — {brief} *(peak {sc:.0f})*")
groups_md = "### Group Overview\n" + "\n\n".join(group_lines)
return (
"", # header md cleared once running
df[["group","name","score"]], # table
img, # chart
human_md, # instruments simple
insights_md, # insights
groups_md, # groups
out["reflection"], # reflection summary
)
def explain_node(evt: gr.SelectData, df_state):
# evt.index is (row_idx, col_idx) for Dataframe
if df_state is None:
return gr.update(visible=False), ""
row_idx = evt.index[0] if isinstance(evt.index, (list, tuple)) else evt.index
try:
row = df_state.iloc[row_idx]
name = row["name"]
group = row["group"]
score = row["score"]
tip = NODE_TIPS.get(name, f"{name} in {group}")
more = GROUP_BLURBS.get(group, "")
txt = f"### {name}\n**Group:** {group}\n**Score:** {score:.1f}\n\n{tip}\n\n**Why it matters:** {friendly_score_note(score)}\n\n*Group context:* {more}"
return gr.update(visible=True), txt
except Exception:
return gr.update(visible=False), ""
with gr.Blocks(css=r"""
.scrollable-table { max-height: 420px; overflow-y: auto; }
/* Tooltip helpers: add data-tip to any element with class .tip */
.tip { position: relative; cursor: help; }
.tip:hover::after{
content: attr(data-tip);
position: absolute; left: 0; top: 110%;
background: rgba(20,20,35,.95); color: #fff;
padding: .45rem .6rem; border-radius: .4rem;
max-width: 360px; white-space: normal; z-index: 9999;
box-shadow: 0 6px 20px rgba(0,0,0,.25);
}
.card { border: 1px solid rgba(0,0,0,.08); border-radius: 10px; padding: 12px; background: rgba(255,255,255,.6); }
""") as demo:
df_state = gr.State()
gr.Markdown(INTRO)
with gr.Row():
inp = gr.Textbox(label="Input", placeholder="Type your signal…", lines=4, autofocus=True)
with gr.Row():
btn = gr.Button("Analyze", variant="primary")
clear = gr.Button("Clear")
with gr.Tabs():
with gr.Tab("Lattice Table"):
out_md = gr.Markdown()
out_df = gr.Dataframe(
interactive=False,
wrap=True,
headers=["group", "name", "score"],
label="Scores by node (click a row for a simple explanation)",
elem_classes=["scrollable-table"]
)
with gr.Accordion("Node explanation", open=True, visible=False) as node_popup:
node_text = gr.Markdown()
with gr.Tab("Top-K Chart"):
out_img = gr.Image(type="pil", label="Top nodes (bar)")
with gr.Tab("Instruments"):
# Tooltip row
gr.HTML("""
<div class="card">
<strong>Hover labels:</strong>
<span class="tip" data-tip="How vivid/symbolic your phrasing is; higher often means more metaphor, imagery, or archetypal language.">Symbolic Frequency Decoder</span> •
<span class="tip" data-tip="Overall pull of your message — is the pattern stable, truth-aligned, or unstable?">Intent Field Scanner</span> •
<span class="tip" data-tip="Cosine alignment to a stable self-vector; rough proxy for internal alignment (0–100).">Truth Charge Meter</span> •
<span class="tip" data-tip="Self-consistency: do your words reflect themselves truthfully across the passage?">Mirror Integrity Check</span>
</div>
""")
out_ins = gr.Markdown()
with gr.Tab("Insights"):
out_cards = gr.Markdown()
with gr.Tab("Groups (Plain English)"):
out_groups = gr.Markdown()
with gr.Tab("Summary"):
out_sum = gr.Markdown()
def _store_df(text):
if not text.strip():
return None
out = model.analyze(text)
return pd.DataFrame(out["nodes"]).sort_values("score", ascending=False)
btn.click(run, [inp], [out_md, out_df, out_img, out_ins, out_cards, out_groups, out_sum]) \
.then(_store_df, [inp], [df_state])
inp.submit(run, [inp], [out_md, out_df, out_img, out_ins, out_cards, out_groups, out_sum]) \
.then(_store_df, [inp], [df_state])
out_df.select(explain_node, [out_df, df_state], [node_popup, node_text])
def _clear():
return INTRO, None, None, None, None, None, None, None, gr.update(visible=False), ""
clear.click(_clear, [], [out_md, out_df, out_img, out_ins, out_cards, out_groups, out_sum, df_state, node_popup, node_text])
demo.launch()
|