romybeaute commited on
Commit
e65d62e
·
1 Parent(s): 036b081

Put zero-shot and condition comparison behind an 'Advanced analyses' toggle

Browse files

Off by default: the interface shows the core workflow (Main Results, Run History,
Compare Runs). On (or ?advanced=1 in the URL): adds the Zero-Shot Classification
and Condition Comparison tabs and the skip-pipeline upload mode.

Files changed (1) hide show
  1. app2.py +263 -238
app2.py CHANGED
@@ -95,7 +95,10 @@ except Exception:
95
  return _EVAL_ROOT.joinpath(*parts)
96
 
97
 
98
- # MOSAIC analysis library (Streamlit-free; the methods themselves live here)
 
 
 
99
  from mosaic_core.zeroshot import (
100
  parse_categories as _zs_parse_categories,
101
  embeddings_fingerprint as _zs_embeddings_fingerprint,
@@ -1263,6 +1266,17 @@ def generate_and_save_embeddings(
1263
  # 7. Sidebar — dataset, upload, parameters
1264
  # =====================================================================
1265
 
 
 
 
 
 
 
 
 
 
 
 
1266
  st.sidebar.header("Data Input Method")
1267
 
1268
  # Per-visitor session id. On a shared host (e.g. a Hugging Face Space) every
@@ -2486,19 +2500,26 @@ if not os.path.exists(EMBEDDINGS_FILE):
2486
  )
2487
 
2488
  st.divider()
2489
- st.markdown("**— or —**")
2490
-
2491
- _showing_tools = st.session_state.get("show_precomputed_tools", False)
2492
- _toggle_label = (
2493
- "Hide analysis tools"
2494
- if _showing_tools
2495
- else "Skip pipeline — I'll upload precomputed files from a previous run"
2496
- )
2497
- if st.button(_toggle_label, key="skip_to_tools_btn"):
2498
- st.session_state["show_precomputed_tools"] = not _showing_tools
2499
- st.rerun()
 
 
 
 
 
 
 
2500
 
2501
- if st.session_state.get("show_precomputed_tools"):
2502
  st.info(
2503
  "Upload files you exported from a previous pipeline run. "
2504
  "The embedding model selected in the sidebar will be used for any re-embedding steps."
@@ -3121,7 +3142,10 @@ else:
3121
  # =================================================================
3122
  # 9. Visualisation & History Tabs
3123
  # =================================================================
3124
- main_tab, zeroshot_tab, condition_tab, history_tab, compare_tab = st.tabs(["Main Results", "Zero-Shot Classification", "Condition Comparison", "Run History", "Compare Runs"])
 
 
 
3125
 
3126
  st.markdown(
3127
  """
@@ -4002,247 +4026,248 @@ else:
4002
  else:
4003
  st.info("Click 'Run Analysis' (scroll down left corner - after params selection -) to begin.")
4004
 
4005
- # --- ZERO-SHOT TAB ---
4006
- with zeroshot_tab:
4007
- st.subheader("Zero-Shot Topic Classification")
4008
- st.caption(
4009
- "Classify your documents into **predefined categories** using semantic similarity. "
4010
- "Uses the same preprocessed docs and embeddings as the main pipeline — no extra embedding step needed."
4011
- )
4012
-
4013
- zs_categories_raw = _zs_categories_input("zs", height=260)
4014
-
4015
- zs_col1, zs_col2 = st.columns([1, 2])
4016
- with zs_col1:
4017
- zs_min_sim = st.slider(
4018
- "Minimum similarity threshold",
4019
- min_value=0.0,
4020
- max_value=0.9,
4021
- value=0.5,
4022
- step=0.01,
4023
- help=(
4024
- "Sentences whose best category similarity is below this value are left "
4025
- "'Unclassified'.\n\n"
4026
- "**Raw cosine values are model- and corpus-dependent** — with some "
4027
- "embedding models almost all sentences score 0.40–0.55 against every "
4028
- "category, so a fixed 'good' value does not exist. After running, use "
4029
- "the similarity histogram shown with the results to place this "
4030
- "threshold; moving the slider reclassifies instantly (no re-run)."
4031
- ),
4032
- )
4033
- zs_min_margin = st.slider(
4034
- "Ambiguity margin (best vs runner-up)",
4035
- min_value=0.0,
4036
- max_value=0.2,
4037
- value=0.0,
4038
- step=0.005,
4039
- key="zs_margin",
4040
- help=(
4041
- "Require the best category to beat the runner-up by at least this much. "
4042
- "Sentences sitting between two category vectors are near coin-flips — "
4043
- "raising this leaves them 'Unclassified' instead of assigning them "
4044
- "arbitrarily. 0 disables the filter; 0.02–0.05 is a reasonable range."
4045
- ),
4046
  )
4047
 
4048
- with zs_col2:
4049
- st.info(
4050
- f"**{len(docs):,}** documents ready\n\n"
4051
- f"**Embedding model:** `{selected_embedding_model}` (set in the sidebar)\n\n"
4052
- "Zero-shot works by embedding both your documents **and** your category labels "
4053
- "into the same vector space, then assigning each sentence to the nearest category. "
4054
- f"Your documents are already embedded — only the category labels will be re-encoded "
4055
- f"using `{selected_embedding_model}` when you click Run.\n\n"
4056
- "**Tip:** bare labels like 'Anxiety' are weak anchors — add a `|` description "
4057
- "to each line (see the ? on the categories box) for noticeably better matches."
4058
- )
4059
 
4060
- if st.button("Run Zero-Shot Classification", type="primary", key="zs_run_btn"):
4061
- zs_labels, zs_line_labels, zs_line_texts = _zs_parse_categories(zs_categories_raw)
4062
- if not zs_labels:
4063
- st.error("Please enter at least one category.")
4064
- else:
4065
- with st.spinner(f"Comparing {len(docs):,} documents to {len(zs_labels)} categories…"):
4066
- try:
4067
- zs_line_sims = compute_zeroshot_similarities(
4068
- embeddings,
4069
- _zs_embeddings_fingerprint(embeddings),
4070
- tuple(zs_line_texts),
4071
- selected_embedding_model,
4072
- )
4073
- st.session_state["zs_results"] = {
4074
- "line_sims": zs_line_sims,
4075
- "labels": zs_labels,
4076
- "line_labels": zs_line_labels,
4077
- }
4078
- st.session_state["zs_results_docs_file"] = DOCS_FILE
4079
- except Exception as e:
4080
- st.error(f"Zero-shot classification failed: {e}")
 
 
 
 
 
 
 
 
 
 
 
4081
 
4082
- if "zs_results" in st.session_state and st.session_state.get("zs_results_docs_file") != DOCS_FILE:
4083
- st.warning("The dataset has changed. Re-run zero-shot classification for the current dataset.")
4084
- elif isinstance(st.session_state.get("zs_results"), dict):
4085
- _zs_state = st.session_state["zs_results"]
4086
- zs_topics, zs_topic_info, zs_per_doc = apply_zeroshot_threshold(
4087
- _zs_state["line_sims"], _zs_state["labels"], _zs_state["line_labels"],
4088
- zs_min_sim, zs_min_margin,
4089
- )
4090
- zs_categories = _zs_state["labels"]
 
 
4091
 
4092
- st.pyplot(_zs_similarity_histogram(
4093
- zs_per_doc["confidence"].to_numpy(), zs_min_sim,
4094
- zs_min_margin, zs_per_doc["margin"].to_numpy(),
4095
- ))
4096
- _zs_conf = zs_per_doc["confidence"]
4097
- st.caption(
4098
- f"Best-similarity percentiles: 25% = {_zs_conf.quantile(0.25):.2f} · "
4099
- f"median = {_zs_conf.quantile(0.5):.2f} · 75% = {_zs_conf.quantile(0.75):.2f}. "
4100
- "Move the threshold slider to reclassify instantly — a value below the 25% "
4101
- "mark classifies almost everything; above the 75% mark keeps only the tail."
4102
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4103
 
4104
- # Summary metrics
4105
- total_zs = len(zs_topics)
4106
- classified_zs = sum(1 for t in zs_topics if t != -1)
4107
- unclassified_zs = total_zs - classified_zs
4108
-
4109
- zm1, zm2, zm3 = st.columns(3)
4110
- zm1.metric("Total documents", f"{total_zs:,}")
4111
- zm2.metric("Classified", f"{classified_zs:,} ({100*classified_zs/total_zs:.1f}%)")
4112
- zm3.metric("Unclassified", f"{unclassified_zs:,} ({100*unclassified_zs/total_zs:.1f}%)")
4113
-
4114
- # Build per-doc DataFrame
4115
- zs_name_map = zs_topic_info.set_index("Topic")["Name"].to_dict()
4116
- zs_df = pd.DataFrame({"sentence": docs, "topic_id": zs_topics})
4117
- zs_df["category"] = zs_df["topic_id"].map(zs_name_map).fillna("Unclassified")
4118
- zs_df = pd.concat([zs_df, zs_per_doc.reset_index(drop=True)], axis=1)
4119
-
4120
- # Bar chart (classified topics only, sorted by count)
4121
- zs_plot_df = (
4122
- zs_topic_info[zs_topic_info["Topic"] != -1]
4123
- .sort_values("Count", ascending=True)
4124
- .reset_index(drop=True)
4125
- )
 
 
 
 
 
 
 
 
 
 
 
 
4126
 
4127
- if not zs_plot_df.empty:
4128
- st.subheader("Distribution across categories")
4129
- # Colour by rank, not by value — see _zs_rank_ramp.
4130
- _cmap = plt.get_cmap("viridis")
4131
- _bar_colors = [_cmap(x) for x in _zs_rank_ramp(len(zs_plot_df))]
4132
 
4133
- fig_zs, ax_zs = plt.subplots(figsize=(10, max(4, len(zs_plot_df) * 0.62)))
4134
- fig_zs.patch.set_facecolor("white")
4135
- ax_zs.set_facecolor("#f8f9fa")
4136
 
4137
- bars = ax_zs.barh(
4138
- zs_plot_df["Name"], zs_plot_df["Count"],
4139
- color=_bar_colors, edgecolor="white", linewidth=0.8, height=0.65,
4140
- )
4141
- _max_count = zs_plot_df["Count"].max()
4142
- for bar in bars:
4143
- w = bar.get_width()
4144
- ax_zs.text(
4145
- w + _max_count * 0.015,
4146
- bar.get_y() + bar.get_height() / 2,
4147
- str(int(w)),
4148
- va="center", ha="left", fontsize=9,
4149
- color="#333333", fontweight="bold",
4150
  )
 
 
 
 
 
 
 
 
 
 
4151
 
4152
- for spine in ("top", "right"):
4153
- ax_zs.spines[spine].set_visible(False)
4154
- ax_zs.spines["left"].set_color("#cccccc")
4155
- ax_zs.spines["bottom"].set_color("#cccccc")
4156
- ax_zs.set_xlabel("Number of sentences", fontsize=10, color="#555555")
4157
- ax_zs.tick_params(axis="y", labelsize=9, colors="#333333")
4158
- ax_zs.tick_params(axis="x", labelsize=8, colors="#777777")
4159
- ax_zs.set_xlim(0, _max_count * 1.15)
4160
- ax_zs.invert_yaxis()
4161
- ax_zs.grid(axis="x", color="#e0e0e0", linewidth=0.8, zorder=0)
4162
- ax_zs.set_axisbelow(True)
4163
- ax_zs.set_title(
4164
- f"Zero-Shot Classification · {classified_zs:,} / {total_zs:,} sentences classified",
4165
- fontsize=11, color="#333333", pad=12,
4166
- )
4167
- plt.tight_layout(pad=1.5)
4168
- st.pyplot(fig_zs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4169
 
4170
- buf_zs = BytesIO()
4171
- fig_zs.savefig(buf_zs, format="png", dpi=200, bbox_inches="tight")
4172
- st.download_button(
4173
- "Download chart as PNG",
4174
- data=buf_zs.getvalue(),
4175
- file_name=f"zeroshot_chart_{os.path.splitext(os.path.basename(CSV_PATH))[0]}.png",
4176
- mime="image/png",
4177
- )
4178
- plt.close(fig_zs)
4179
-
4180
- # ── MOSAIC topics the categories fail to capture ──────────────
4181
- _latest_zs = st.session_state.get("latest_results")
4182
- if (isinstance(_latest_zs, tuple) and len(_latest_zs) == 3
4183
- and len(_latest_zs[2]) == len(zs_df)):
4184
- _zs_uncovered_topics_ui(
4185
- _latest_zs[2], zs_df["category"], zs_min_sim, key_prefix="zs",
4186
- )
4187
- else:
4188
- st.caption(
4189
- "Run the pipeline in **Main Results** to also see which MOSAIC "
4190
- "topics these categories fail to capture."
4191
- )
 
 
4192
 
4193
- # Per-category expandable view
4194
- st.subheader("Sentences per category")
4195
- for _, row_zs in zs_plot_df.sort_values("Count", ascending=False).iterrows():
4196
- cat_name = row_zs["Name"]
4197
- count_zs = row_zs["Count"]
4198
- with st.expander(f"{cat_name} ({count_zs} sentences)"):
4199
- cat_sentences = (
4200
- zs_df[zs_df["category"] == cat_name]
4201
- [["sentence", "confidence", "margin", "runner_up"]]
4202
  .sort_values("confidence", ascending=False)
4203
  .reset_index(drop=True)
4204
  )
4205
- if len(cat_sentences) > 5:
4206
- n_show = st.slider(
4207
- "Sentences to show", 5, min(100, len(cat_sentences)),
4208
- min(10, len(cat_sentences)),
4209
- key=f"zs_show_{cat_name}"
4210
- )
4211
- else:
4212
- n_show = len(cat_sentences)
4213
- st.dataframe(
4214
- cat_sentences.head(n_show),
4215
- use_container_width=True,
4216
- )
4217
 
4218
- # Unclassified preview — sorted by confidence so near-misses surface first
4219
- with st.expander(f"Unclassified ({unclassified_zs} sentences)"):
4220
- unclass_sentences = (
4221
- zs_df[zs_df["category"] == "Unclassified"]
4222
- [["sentence", "best_category", "confidence", "margin"]]
4223
- .sort_values("confidence", ascending=False)
4224
- .reset_index(drop=True)
 
 
4225
  )
4226
- st.dataframe(unclass_sentences.head(50), use_container_width=True)
4227
 
4228
- # Download full results
4229
- zs_base = (st.session_state.get("export_label_val", "").strip()
4230
- or os.path.splitext(os.path.basename(CSV_PATH))[0])
4231
- st.download_button(
4232
- "Download full classification results (CSV)",
4233
- data=zs_df.to_csv(index=False).encode("utf-8-sig"),
4234
- file_name=f"zeroshot_{zs_base}.csv",
4235
- mime="text/csv",
4236
- use_container_width=True,
4237
- )
4238
-
4239
- # --- CONDITION COMPARISON TAB ---
4240
- with condition_tab:
4241
- st.subheader("Condition Comparison — Semantic Similarity")
4242
 
4243
- with st.expander("How to use this tab — read first", expanded=True):
4244
- st.markdown(
4245
- f"""
4246
  **This tab compares the topics found in two different conditions** by measuring the semantic
4247
  similarity between their topic vectors.
4248
 
@@ -4261,10 +4286,10 @@ similarity between their topic vectors.
4261
  - The **match threshold is calibrated from your own data** (see the *Match threshold* section) rather than fixed, because a raw number like 0.50 does not transfer between embedding models or corpora
4262
  - A greedy algorithm finds the best one-to-one pairs above the threshold, and reports roughly how many would be expected by chance — an order-of-magnitude guide, not a false-discovery rate
4263
  - Results include a heatmap, matched/unmatched topic lists, a contingency table, a chi-squared test (report **Cramér's V**, not p — see that section), and a frequency bar chart
4264
- """
4265
- )
4266
 
4267
- _condition_comparison_ui(selected_embedding_model)
4268
 
4269
  # --- HISTORY TAB ---
4270
  with history_tab:
 
95
  return _EVAL_ROOT.joinpath(*parts)
96
 
97
 
98
+ # MOSAIC analysis library (Streamlit-free; the methods themselves live here).
99
+ # `streamlit run` already puts this folder on sys.path; this covers other launchers.
100
+ if str(Path(__file__).resolve().parent) not in sys.path:
101
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
102
  from mosaic_core.zeroshot import (
103
  parse_categories as _zs_parse_categories,
104
  embeddings_fingerprint as _zs_embeddings_fingerprint,
 
1266
  # 7. Sidebar — dataset, upload, parameters
1267
  # =====================================================================
1268
 
1269
+ # Advanced analyses are opt-in so the default interface stays the core topic-modelling
1270
+ # workflow. `?advanced=1` in the URL turns them on by default (e.g. for workshops).
1271
+ ADVANCED_MODE = st.sidebar.toggle(
1272
+ "Advanced analyses",
1273
+ value=st.query_params.get("advanced") == "1",
1274
+ key="advanced_mode",
1275
+ help="Adds the **Zero-Shot Classification** and **Condition Comparison** tabs, "
1276
+ "and lets you use both on files exported from a previous run without "
1277
+ "re-running the pipeline.",
1278
+ )
1279
+
1280
  st.sidebar.header("Data Input Method")
1281
 
1282
  # Per-visitor session id. On a shared host (e.g. a Hugging Face Space) every
 
2500
  )
2501
 
2502
  st.divider()
2503
+ if ADVANCED_MODE:
2504
+ st.markdown("**— or —**")
2505
+
2506
+ _showing_tools = st.session_state.get("show_precomputed_tools", False)
2507
+ _toggle_label = (
2508
+ "Hide analysis tools"
2509
+ if _showing_tools
2510
+ else "Skip pipeline — I'll upload precomputed files from a previous run"
2511
+ )
2512
+ if st.button(_toggle_label, key="skip_to_tools_btn"):
2513
+ st.session_state["show_precomputed_tools"] = not _showing_tools
2514
+ st.rerun()
2515
+ else:
2516
+ st.caption(
2517
+ "Already have embeddings or topic summaries from a previous run? Turn on "
2518
+ "**Advanced analyses** in the sidebar to use Zero-Shot Classification and "
2519
+ "Condition Comparison on them without running the pipeline."
2520
+ )
2521
 
2522
+ if ADVANCED_MODE and st.session_state.get("show_precomputed_tools"):
2523
  st.info(
2524
  "Upload files you exported from a previous pipeline run. "
2525
  "The embedding model selected in the sidebar will be used for any re-embedding steps."
 
3142
  # =================================================================
3143
  # 9. Visualisation & History Tabs
3144
  # =================================================================
3145
+ if ADVANCED_MODE:
3146
+ main_tab, zeroshot_tab, condition_tab, history_tab, compare_tab = st.tabs(["Main Results", "Zero-Shot Classification", "Condition Comparison", "Run History", "Compare Runs"])
3147
+ else:
3148
+ main_tab, history_tab, compare_tab = st.tabs(["Main Results", "Run History", "Compare Runs"])
3149
 
3150
  st.markdown(
3151
  """
 
4026
  else:
4027
  st.info("Click 'Run Analysis' (scroll down left corner - after params selection -) to begin.")
4028
 
4029
+ if ADVANCED_MODE:
4030
+ # --- ZERO-SHOT TAB ---
4031
+ with zeroshot_tab:
4032
+ st.subheader("Zero-Shot Topic Classification")
4033
+ st.caption(
4034
+ "Classify your documents into **predefined categories** using semantic similarity. "
4035
+ "Uses the same preprocessed docs and embeddings as the main pipeline — no extra embedding step needed."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4036
  )
4037
 
4038
+ zs_categories_raw = _zs_categories_input("zs", height=260)
 
 
 
 
 
 
 
 
 
 
4039
 
4040
+ zs_col1, zs_col2 = st.columns([1, 2])
4041
+ with zs_col1:
4042
+ zs_min_sim = st.slider(
4043
+ "Minimum similarity threshold",
4044
+ min_value=0.0,
4045
+ max_value=0.9,
4046
+ value=0.5,
4047
+ step=0.01,
4048
+ help=(
4049
+ "Sentences whose best category similarity is below this value are left "
4050
+ "'Unclassified'.\n\n"
4051
+ "**Raw cosine values are model- and corpus-dependent** — with some "
4052
+ "embedding models almost all sentences score 0.40–0.55 against every "
4053
+ "category, so a fixed 'good' value does not exist. After running, use "
4054
+ "the similarity histogram shown with the results to place this "
4055
+ "threshold; moving the slider reclassifies instantly (no re-run)."
4056
+ ),
4057
+ )
4058
+ zs_min_margin = st.slider(
4059
+ "Ambiguity margin (best vs runner-up)",
4060
+ min_value=0.0,
4061
+ max_value=0.2,
4062
+ value=0.0,
4063
+ step=0.005,
4064
+ key="zs_margin",
4065
+ help=(
4066
+ "Require the best category to beat the runner-up by at least this much. "
4067
+ "Sentences sitting between two category vectors are near coin-flips — "
4068
+ "raising this leaves them 'Unclassified' instead of assigning them "
4069
+ "arbitrarily. 0 disables the filter; 0.02–0.05 is a reasonable range."
4070
+ ),
4071
+ )
4072
 
4073
+ with zs_col2:
4074
+ st.info(
4075
+ f"**{len(docs):,}** documents ready\n\n"
4076
+ f"**Embedding model:** `{selected_embedding_model}` (set in the sidebar)\n\n"
4077
+ "Zero-shot works by embedding both your documents **and** your category labels "
4078
+ "into the same vector space, then assigning each sentence to the nearest category. "
4079
+ f"Your documents are already embedded — only the category labels will be re-encoded "
4080
+ f"using `{selected_embedding_model}` when you click Run.\n\n"
4081
+ "**Tip:** bare labels like 'Anxiety' are weak anchors — add a `|` description "
4082
+ "to each line (see the ? on the categories box) for noticeably better matches."
4083
+ )
4084
 
4085
+ if st.button("Run Zero-Shot Classification", type="primary", key="zs_run_btn"):
4086
+ zs_labels, zs_line_labels, zs_line_texts = _zs_parse_categories(zs_categories_raw)
4087
+ if not zs_labels:
4088
+ st.error("Please enter at least one category.")
4089
+ else:
4090
+ with st.spinner(f"Comparing {len(docs):,} documents to {len(zs_labels)} categories…"):
4091
+ try:
4092
+ zs_line_sims = compute_zeroshot_similarities(
4093
+ embeddings,
4094
+ _zs_embeddings_fingerprint(embeddings),
4095
+ tuple(zs_line_texts),
4096
+ selected_embedding_model,
4097
+ )
4098
+ st.session_state["zs_results"] = {
4099
+ "line_sims": zs_line_sims,
4100
+ "labels": zs_labels,
4101
+ "line_labels": zs_line_labels,
4102
+ }
4103
+ st.session_state["zs_results_docs_file"] = DOCS_FILE
4104
+ except Exception as e:
4105
+ st.error(f"Zero-shot classification failed: {e}")
4106
+
4107
+ if "zs_results" in st.session_state and st.session_state.get("zs_results_docs_file") != DOCS_FILE:
4108
+ st.warning("The dataset has changed. Re-run zero-shot classification for the current dataset.")
4109
+ elif isinstance(st.session_state.get("zs_results"), dict):
4110
+ _zs_state = st.session_state["zs_results"]
4111
+ zs_topics, zs_topic_info, zs_per_doc = apply_zeroshot_threshold(
4112
+ _zs_state["line_sims"], _zs_state["labels"], _zs_state["line_labels"],
4113
+ zs_min_sim, zs_min_margin,
4114
+ )
4115
+ zs_categories = _zs_state["labels"]
4116
 
4117
+ st.pyplot(_zs_similarity_histogram(
4118
+ zs_per_doc["confidence"].to_numpy(), zs_min_sim,
4119
+ zs_min_margin, zs_per_doc["margin"].to_numpy(),
4120
+ ))
4121
+ _zs_conf = zs_per_doc["confidence"]
4122
+ st.caption(
4123
+ f"Best-similarity percentiles: 25% = {_zs_conf.quantile(0.25):.2f} · "
4124
+ f"median = {_zs_conf.quantile(0.5):.2f} · 75% = {_zs_conf.quantile(0.75):.2f}. "
4125
+ "Move the threshold slider to reclassify instantly — a value below the 25% "
4126
+ "mark classifies almost everything; above the 75% mark keeps only the tail."
4127
+ )
4128
+
4129
+ # Summary metrics
4130
+ total_zs = len(zs_topics)
4131
+ classified_zs = sum(1 for t in zs_topics if t != -1)
4132
+ unclassified_zs = total_zs - classified_zs
4133
+
4134
+ zm1, zm2, zm3 = st.columns(3)
4135
+ zm1.metric("Total documents", f"{total_zs:,}")
4136
+ zm2.metric("Classified", f"{classified_zs:,} ({100*classified_zs/total_zs:.1f}%)")
4137
+ zm3.metric("Unclassified", f"{unclassified_zs:,} ({100*unclassified_zs/total_zs:.1f}%)")
4138
+
4139
+ # Build per-doc DataFrame
4140
+ zs_name_map = zs_topic_info.set_index("Topic")["Name"].to_dict()
4141
+ zs_df = pd.DataFrame({"sentence": docs, "topic_id": zs_topics})
4142
+ zs_df["category"] = zs_df["topic_id"].map(zs_name_map).fillna("Unclassified")
4143
+ zs_df = pd.concat([zs_df, zs_per_doc.reset_index(drop=True)], axis=1)
4144
+
4145
+ # Bar chart (classified topics only, sorted by count)
4146
+ zs_plot_df = (
4147
+ zs_topic_info[zs_topic_info["Topic"] != -1]
4148
+ .sort_values("Count", ascending=True)
4149
+ .reset_index(drop=True)
4150
+ )
4151
 
4152
+ if not zs_plot_df.empty:
4153
+ st.subheader("Distribution across categories")
4154
+ # Colour by rank, not by value — see _zs_rank_ramp.
4155
+ _cmap = plt.get_cmap("viridis")
4156
+ _bar_colors = [_cmap(x) for x in _zs_rank_ramp(len(zs_plot_df))]
4157
 
4158
+ fig_zs, ax_zs = plt.subplots(figsize=(10, max(4, len(zs_plot_df) * 0.62)))
4159
+ fig_zs.patch.set_facecolor("white")
4160
+ ax_zs.set_facecolor("#f8f9fa")
4161
 
4162
+ bars = ax_zs.barh(
4163
+ zs_plot_df["Name"], zs_plot_df["Count"],
4164
+ color=_bar_colors, edgecolor="white", linewidth=0.8, height=0.65,
 
 
 
 
 
 
 
 
 
 
4165
  )
4166
+ _max_count = zs_plot_df["Count"].max()
4167
+ for bar in bars:
4168
+ w = bar.get_width()
4169
+ ax_zs.text(
4170
+ w + _max_count * 0.015,
4171
+ bar.get_y() + bar.get_height() / 2,
4172
+ str(int(w)),
4173
+ va="center", ha="left", fontsize=9,
4174
+ color="#333333", fontweight="bold",
4175
+ )
4176
 
4177
+ for spine in ("top", "right"):
4178
+ ax_zs.spines[spine].set_visible(False)
4179
+ ax_zs.spines["left"].set_color("#cccccc")
4180
+ ax_zs.spines["bottom"].set_color("#cccccc")
4181
+ ax_zs.set_xlabel("Number of sentences", fontsize=10, color="#555555")
4182
+ ax_zs.tick_params(axis="y", labelsize=9, colors="#333333")
4183
+ ax_zs.tick_params(axis="x", labelsize=8, colors="#777777")
4184
+ ax_zs.set_xlim(0, _max_count * 1.15)
4185
+ ax_zs.invert_yaxis()
4186
+ ax_zs.grid(axis="x", color="#e0e0e0", linewidth=0.8, zorder=0)
4187
+ ax_zs.set_axisbelow(True)
4188
+ ax_zs.set_title(
4189
+ f"Zero-Shot Classification · {classified_zs:,} / {total_zs:,} sentences classified",
4190
+ fontsize=11, color="#333333", pad=12,
4191
+ )
4192
+ plt.tight_layout(pad=1.5)
4193
+ st.pyplot(fig_zs)
4194
+
4195
+ buf_zs = BytesIO()
4196
+ fig_zs.savefig(buf_zs, format="png", dpi=200, bbox_inches="tight")
4197
+ st.download_button(
4198
+ "Download chart as PNG",
4199
+ data=buf_zs.getvalue(),
4200
+ file_name=f"zeroshot_chart_{os.path.splitext(os.path.basename(CSV_PATH))[0]}.png",
4201
+ mime="image/png",
4202
+ )
4203
+ plt.close(fig_zs)
4204
+
4205
+ # ── MOSAIC topics the categories fail to capture ──────────────
4206
+ _latest_zs = st.session_state.get("latest_results")
4207
+ if (isinstance(_latest_zs, tuple) and len(_latest_zs) == 3
4208
+ and len(_latest_zs[2]) == len(zs_df)):
4209
+ _zs_uncovered_topics_ui(
4210
+ _latest_zs[2], zs_df["category"], zs_min_sim, key_prefix="zs",
4211
+ )
4212
+ else:
4213
+ st.caption(
4214
+ "Run the pipeline in **Main Results** to also see which MOSAIC "
4215
+ "topics these categories fail to capture."
4216
+ )
4217
 
4218
+ # Per-category expandable view
4219
+ st.subheader("Sentences per category")
4220
+ for _, row_zs in zs_plot_df.sort_values("Count", ascending=False).iterrows():
4221
+ cat_name = row_zs["Name"]
4222
+ count_zs = row_zs["Count"]
4223
+ with st.expander(f"{cat_name} ({count_zs} sentences)"):
4224
+ cat_sentences = (
4225
+ zs_df[zs_df["category"] == cat_name]
4226
+ [["sentence", "confidence", "margin", "runner_up"]]
4227
+ .sort_values("confidence", ascending=False)
4228
+ .reset_index(drop=True)
4229
+ )
4230
+ if len(cat_sentences) > 5:
4231
+ n_show = st.slider(
4232
+ "Sentences to show", 5, min(100, len(cat_sentences)),
4233
+ min(10, len(cat_sentences)),
4234
+ key=f"zs_show_{cat_name}"
4235
+ )
4236
+ else:
4237
+ n_show = len(cat_sentences)
4238
+ st.dataframe(
4239
+ cat_sentences.head(n_show),
4240
+ use_container_width=True,
4241
+ )
4242
 
4243
+ # Unclassified preview — sorted by confidence so near-misses surface first
4244
+ with st.expander(f"Unclassified ({unclassified_zs} sentences)"):
4245
+ unclass_sentences = (
4246
+ zs_df[zs_df["category"] == "Unclassified"]
4247
+ [["sentence", "best_category", "confidence", "margin"]]
 
 
 
 
4248
  .sort_values("confidence", ascending=False)
4249
  .reset_index(drop=True)
4250
  )
4251
+ st.dataframe(unclass_sentences.head(50), use_container_width=True)
 
 
 
 
 
 
 
 
 
 
 
4252
 
4253
+ # Download full results
4254
+ zs_base = (st.session_state.get("export_label_val", "").strip()
4255
+ or os.path.splitext(os.path.basename(CSV_PATH))[0])
4256
+ st.download_button(
4257
+ "Download full classification results (CSV)",
4258
+ data=zs_df.to_csv(index=False).encode("utf-8-sig"),
4259
+ file_name=f"zeroshot_{zs_base}.csv",
4260
+ mime="text/csv",
4261
+ use_container_width=True,
4262
  )
 
4263
 
4264
+ # --- CONDITION COMPARISON TAB ---
4265
+ with condition_tab:
4266
+ st.subheader("Condition Comparison — Semantic Similarity")
 
 
 
 
 
 
 
 
 
 
 
4267
 
4268
+ with st.expander("How to use this tab — read first", expanded=True):
4269
+ st.markdown(
4270
+ f"""
4271
  **This tab compares the topics found in two different conditions** by measuring the semantic
4272
  similarity between their topic vectors.
4273
 
 
4286
  - The **match threshold is calibrated from your own data** (see the *Match threshold* section) rather than fixed, because a raw number like 0.50 does not transfer between embedding models or corpora
4287
  - A greedy algorithm finds the best one-to-one pairs above the threshold, and reports roughly how many would be expected by chance — an order-of-magnitude guide, not a false-discovery rate
4288
  - Results include a heatmap, matched/unmatched topic lists, a contingency table, a chi-squared test (report **Cramér's V**, not p — see that section), and a frequency bar chart
4289
+ """
4290
+ )
4291
 
4292
+ _condition_comparison_ui(selected_embedding_model)
4293
 
4294
  # --- HISTORY TAB ---
4295
  with history_tab: