File size: 11,942 Bytes
76810fa |
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 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 |
# sjt_answers_viewer.py
# Gradio viewer for case_study_answers.json
# - Shows one question at a time
# - Dropdown 1: filter by **Name**
# - Dropdown 2: filter by **Selected Trait** (HEXACO slice)
# - Underlines & highlights the actually selected option + trait name
# - Always orders options consistently (HEXACO)
# - Top "Summary" bar shows proportion of selections by trait (under current Name filter)
import json
from pathlib import Path
from typing import List, Dict, Any, Optional, Tuple
import random
import gradio as gr
import matplotlib.pyplot as plt
# ---------- Constants ----------
DATA_PATH = Path("case_study_answers.json")
HEXACO_ORDER = [
"hh",
"emotionality",
"extraversion",
"agreeableness",
"conscientiousness",
"openness",
]
TRAIT_LABELS = {
"hh": "HonestyβHumility",
"emotionality": "Emotionality",
"extraversion": "Extraversion",
"agreeableness": "Agreeableness",
"conscientiousness": "Conscientiousness",
"openness": "Openness",
}
# ---------- Icons ----------
ICONS = {
"header": "π",
"question": "β",
"options": "β
",
"summary": "π",
"progress": "βοΈ",
"metadata": "π",
"filters": "ποΈ",
}
# ---------- Data Loading & Normalization ----------
def load_json(path: Path) -> Any:
if not path.exists():
return []
with path.open("r", encoding="utf-8") as f:
return json.load(f)
def _safe_get_question_block(item: Dict[str, Any]) -> Tuple[str, Dict[str, str], Optional[str]]:
"""
Extract (question_text, options_map, selected_trait) from a raw item.
Heuristics:
- Selected trait is at top-level key 'option'.
- Question text/options may be under item['question'] with nested 'corrected_sjt' or 'original_sjt'.
- Options are expected as keys like '<trait>_option' where trait β HEXACO_ORDER.
"""
selected = item.get("option")
q = item.get("question", {}) or {}
block = q.get("corrected_sjt") or q.get("original_sjt") or {}
question_text = ""
options: Dict[str, str] = {}
if isinstance(block, dict):
question_text = block.get("question") or q.get("question") or ""
for trait in HEXACO_ORDER:
k = f"{trait}_option"
if k in block:
options[trait] = str(block[k]).strip()
elif k in q:
options[trait] = str(q[k]).strip()
else:
# sometimes block is a plain string
question_text = str(block) if block else str(q.get("question", ""))
# Fallback: look for options directly on item if missing
if not options and isinstance(q, dict):
for trait in HEXACO_ORDER:
k = f"{trait}_option"
if k in q:
options[trait] = str(q[k]).strip()
return question_text.strip(), options, selected
def flatten_entries(raw: Any) -> List[Dict[str, Any]]:
"""
Returns a list of entries with keys:
- name (str)
- question (str)
- options (dict[trait->text])
- selected (trait str)
"""
out: List[Dict[str, Any]] = []
def handle_item(obj: Dict[str, Any], default_name: str):
q_text, opts, sel = _safe_get_question_block(obj)
# Prefer name from object if present; else inherit from container
nm = (obj.get("name") or default_name or "Unknown").strip() or "Unknown"
if q_text and opts and sel:
out.append({"name": nm, "question": q_text, "options": opts, "selected": sel})
if isinstance(raw, list):
for x in raw:
if isinstance(x, dict):
handle_item(x, "Unknown")
elif isinstance(raw, dict):
# Could be {persona_name: [items]} or {persona_name: {...}} etc.
for k, v in raw.items():
default_name = str(k)
if isinstance(v, list):
for x in v:
if isinstance(x, dict):
handle_item(x, default_name)
elif isinstance(v, dict):
handle_item(v, default_name)
return out
DATA_RAW = load_json(DATA_PATH)
DATA: List[Dict[str, Any]] = flatten_entries(DATA_RAW)
# Unique names for dropdown
def all_names(entries: List[Dict[str, Any]]) -> List[str]:
seen = []
for e in entries:
nm = e.get("name", "Unknown") or "Unknown"
if nm not in seen:
seen.append(nm)
return sorted(seen)
NAME_FILTERS = ["All"] + all_names(DATA)
TRAIT_FILTERS = ["All"] + HEXACO_ORDER
# ---------- Filtering & Navigation ----------
def get_filtered_indices(entries: List[Dict[str, Any]], name_filt: str, trait_filt: str) -> List[int]:
idxs = list(range(len(entries)))
if name_filt != "All":
idxs = [i for i in idxs if entries[i].get("name") == name_filt]
if trait_filt != "All":
idxs = [i for i in idxs if entries[i].get("selected") == trait_filt]
return idxs
def clamp_index(i: int, n: int) -> int:
return 0 if n == 0 else (i % n)
# ---------- Summary ----------
def compute_summary(entries: List[Dict[str, Any]]):
total = len(entries)
counts = {t: 0 for t in HEXACO_ORDER}
for e in entries:
sel = e.get("selected")
if sel in counts:
counts[sel] += 1
labels = [TRAIT_LABELS[t] for t in HEXACO_ORDER]
props = [counts[t] / total if total else 0.0 for t in HEXACO_ORDER]
return labels, props, counts, total
def summary_plot(entries: List[Dict[str, Any]]):
# Returns Markdown with proportions per trait under the current Name filter
labels, props, counts, total = compute_summary(entries)
lines = ["## π Summary (Name filter)", f"**Total:** {total}"]
for label, p in zip(labels, props):
lines.append(f"- {label}: {p:.2f}")
return "\n".join(lines)
# ---------- Rendering ----------
def md_question(entry: Dict[str, Any]) -> str:
q = entry.get("question", "")
name = entry.get("name", "β")
return f"## {ICONS['question']} Question\n**Name:** {name}\n\n{q if q else 'β'}"
def md_options(entry: Dict[str, Any]) -> str:
opts: Dict[str, str] = entry.get("options", {})
selected = entry.get("selected")
lines = []
for i, trait in enumerate(HEXACO_ORDER, start=1):
if trait not in opts:
continue
label = TRAIT_LABELS[trait]
text = opts[trait]
if trait == selected:
# underline + highlight both the label and the text
line = (
f"{i}. <u><mark><strong>{label}</strong>:</mark></u> "
f"<u><mark>{text}</mark></u>"
)
else:
line = f"{i}. **{label}:** {text}"
lines.append(line)
body = "\n\n".join(lines) if lines else "β"
return f"## {ICONS['options']} Options (HEXACO order)\n{body}"
def md_metadata(entry: Dict[str, Any], idx: int, total_in_filter: int) -> str:
sel = entry.get("selected", "β")
sel_disp = TRAIT_LABELS.get(sel, sel)
nm = entry.get("name", "β")
return (
f"## {ICONS['metadata']} Metadata\n"
f"**Name:** {nm} \n"
f"**Selected Option (Trait):** {sel_disp} \n"
f"**Position in Filter:** {idx + 1} / {total_in_filter}"
)
def md_progress(idx: int, total: int) -> str:
return f"## {ICONS['progress']} Progress\n**{idx + 1} / {total}**"
def render(entries: List[Dict[str, Any]], name_filt: str, trait_filt: str, pos: int):
# For summary, use "name-only" filter to show that persona's distribution
name_only_indices = [i for i, e in enumerate(entries) if (name_filt == "All" or e.get("name") == name_filt)]
name_only_slice = [entries[i] for i in name_only_indices]
# For the main view selection, apply both filters
indices = get_filtered_indices(entries, name_filt, trait_filt)
n = len(indices)
if n == 0:
return (
summary_plot(name_only_slice),
f"## {ICONS['question']} Question\n_No questions for filters **Name={name_filt}**, **Trait={trait_filt}**._",
f"## {ICONS['options']} Options\nβ",
f"## {ICONS['metadata']} Metadata\nβ",
f"## {ICONS['progress']} Progress\n0 / 0",
0, # expose pos back
)
pos = clamp_index(pos, n)
entry = entries[indices[pos]]
return (
summary_plot(name_only_slice),
md_question(entry),
md_options(entry),
md_metadata(entry, pos, n),
md_progress(pos, n),
pos, # expose pos back
)
# ---------- Gradio App ----------
with gr.Blocks(title="SJT Answers Viewer") as demo:
gr.Markdown("# SJT Answers Viewer")
gr.Markdown(
f"{ICONS['filters']} **Filters:** Choose a Name and a HEXACO Selected-Trait slice.\n\n"
f"{ICONS['summary']} **Summary:** Bar shows the trait-selection proportions under the current **Name** filter.\n\n"
"Options are consistently ordered by HEXACO. The actual selected option is underlined and highlighted."
)
with gr.Row():
name_dd = gr.Dropdown(choices=NAME_FILTERS, value="All", label="Filter by Name", interactive=True)
trait_dd = gr.Dropdown(choices=TRAIT_FILTERS, value="All", label="Filter by Selected Trait", interactive=True)
st_pos = gr.State(0)
with gr.Row():
prev_btn = gr.Button("Previous")
next_btn = gr.Button("Next")
rand_btn = gr.Button("Random")
# Outputs
summary_out = gr.Markdown(label="Selections Summary (Name filter)")
question_out = gr.Markdown()
options_out = gr.Markdown()
metadata_out = gr.Markdown()
progress_out = gr.Markdown()
# ----- Callbacks -----
def on_filters_change(name_filt: str, trait_filt: str):
return [*render(DATA, name_filt, trait_filt, 0), 0]
def on_prev(name_filt: str, trait_filt: str, pos: int):
indices = get_filtered_indices(DATA, name_filt, trait_filt)
if not indices:
return [*render(DATA, name_filt, trait_filt, pos), pos]
pos = clamp_index(pos - 1, len(indices))
return [*render(DATA, name_filt, trait_filt, pos), pos]
def on_next(name_filt: str, trait_filt: str, pos: int):
indices = get_filtered_indices(DATA, name_filt, trait_filt)
if not indices:
return [*render(DATA, name_filt, trait_filt, pos), pos]
pos = clamp_index(pos + 1, len(indices))
return [*render(DATA, name_filt, trait_filt, pos), pos]
def on_rand(name_filt: str, trait_filt: str, pos: int):
indices = get_filtered_indices(DATA, name_filt, trait_filt)
if not indices:
return [*render(DATA, name_filt, trait_filt, pos), pos]
pos = random.randrange(len(indices))
return [*render(DATA, name_filt, trait_filt, pos), pos]
name_dd.change(
on_filters_change,
inputs=[name_dd, trait_dd],
outputs=[summary_out, question_out, options_out, metadata_out, progress_out, st_pos, st_pos],
)
trait_dd.change(
on_filters_change,
inputs=[name_dd, trait_dd],
outputs=[summary_out, question_out, options_out, metadata_out, progress_out, st_pos, st_pos],
)
prev_btn.click(
on_prev,
inputs=[name_dd, trait_dd, st_pos],
outputs=[summary_out, question_out, options_out, metadata_out, progress_out, st_pos, st_pos],
)
next_btn.click(
on_next,
inputs=[name_dd, trait_dd, st_pos],
outputs=[summary_out, question_out, options_out, metadata_out, progress_out, st_pos, st_pos],
)
rand_btn.click(
on_rand,
inputs=[name_dd, trait_dd, st_pos],
outputs=[summary_out, question_out, options_out, metadata_out, progress_out, st_pos, st_pos],
)
# initial load
demo.load(
lambda: [*render(DATA, "All", "All", 0), 0],
inputs=None,
outputs=[summary_out, question_out, options_out, metadata_out, progress_out, st_pos, st_pos],
)
if __name__ == "__main__":
demo.launch()
|