Spaces:
Sleeping
Sleeping
Delete app.py
Browse files
app.py
DELETED
|
@@ -1,769 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
app.py — Topic Modelling Agentic AI | Gradio UI
|
| 3 |
-
═══════════════════════════════════════════════════
|
| 4 |
-
Version: 3.0.0 | April 2026
|
| 5 |
-
Stack: Gradio 5.x + LangGraph + Mistral + BERTopic
|
| 6 |
-
Deploy: HuggingFace Spaces (sdk: gradio)
|
| 7 |
-
Rules: Zero gr.HTML(). All UI via native Gradio components.
|
| 8 |
-
See GRADIO_UI_GUIDELINES_v2.docx for full standards.
|
| 9 |
-
|
| 10 |
-
ARCHITECTURE — 20 Blocks in 5 Sections
|
| 11 |
-
─────────────────────────────────────────
|
| 12 |
-
Section 1: Setup (B1–B3) Imports, agent, theme
|
| 13 |
-
Section 2: Helpers (B4–B10) Pure Python functions, no UI
|
| 14 |
-
Section 3: UI Layout (B11–B17) gr.Blocks with native components
|
| 15 |
-
Section 4: Event Wiring (B18–B19) Connect UI to functions
|
| 16 |
-
Section 5: Launch (B20) Start server
|
| 17 |
-
|
| 18 |
-
BLOCK COMMUNICATION MAP
|
| 19 |
-
─────────────────────────
|
| 20 |
-
B6 (respond) ←→ B2 (agent) : invokes agent for chat
|
| 21 |
-
B6 (respond) → B4 (output) : scans for download files
|
| 22 |
-
B7 (chart) → B17a (display) : loads Plotly JSON → gr.Plot
|
| 23 |
-
B8 (table) → B16 (review) : builds rows → gr.Dataframe
|
| 24 |
-
B9 (papers) ← B16 (review) : triggered by row click
|
| 25 |
-
B10 (submit) → B2 (agent) : sends review edits to agent
|
| 26 |
-
B18 (wiring) → B5,B7,B8 : refreshes progress, charts, table
|
| 27 |
-
"""
|
| 28 |
-
import os
|
| 29 |
-
import glob
|
| 30 |
-
import json
|
| 31 |
-
|
| 32 |
-
import plotly.io as pio
|
| 33 |
-
import gradio as gr
|
| 34 |
-
from langchain_mistralai import ChatMistralAI
|
| 35 |
-
from langgraph.prebuilt import create_react_agent
|
| 36 |
-
from langgraph.checkpoint.memory import MemorySaver
|
| 37 |
-
from agent import SYSTEM_PROMPT, get_local_tools
|
| 38 |
-
|
| 39 |
-
print(">>> app.py: imports complete")
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
# ╔═══════════════════════════════════════════════════════════════╗
|
| 43 |
-
# ║ SECTION 1 — SETUP ║
|
| 44 |
-
# ║ One-time initialization: agent creation and visual theme. ║
|
| 45 |
-
# ║ Nothing here renders UI — it prepares the backend brain ║
|
| 46 |
-
# ║ and the visual identity for the entire application. ║
|
| 47 |
-
# ╚═══════════════════════════════════════════════════════════════╝
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
# ── B2: Agent setup ─────────────────────────────────────────────
|
| 51 |
-
# PURPOSE: Create the LangGraph ReAct agent that powers all chat.
|
| 52 |
-
# Connects Mistral LLM to BERTopic tools with memory so
|
| 53 |
-
# the agent remembers context across conversation turns.
|
| 54 |
-
# PRODUCES: `agent` — used by B6 (respond) and B10 (_submit_review)
|
| 55 |
-
# IMPORTS: SYSTEM_PROMPT, get_local_tools from agent.py
|
| 56 |
-
# NOTE: MemorySaver keeps conversation in RAM (resets on restart).
|
| 57 |
-
# For persistent memory, swap to SQLite checkpointer.
|
| 58 |
-
# ────────────────────────────────────────────────────────────────
|
| 59 |
-
llm = ChatMistralAI(model="mistral-small-latest", temperature=0, timeout=300)
|
| 60 |
-
tools = get_local_tools()
|
| 61 |
-
agent = create_react_agent(
|
| 62 |
-
model=llm, tools=tools, prompt=SYSTEM_PROMPT, checkpointer=MemorySaver()
|
| 63 |
-
)
|
| 64 |
-
print(f">>> app.py: agent ready ({len(tools)} tools)")
|
| 65 |
-
|
| 66 |
-
_msg_count = 0 # Global message counter (shared across users)
|
| 67 |
-
_uploaded = {"path": ""} # Last uploaded CSV path (shared session)
|
| 68 |
-
# ── end B2: Agent setup ────────────────────────────────────────
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
# ── B3: Theme ───────────────────────────────────────────────────
|
| 72 |
-
# PURPOSE: Define the visual identity of the entire application.
|
| 73 |
-
# Replaces ALL custom CSS that was previously in HEADER_HTML:
|
| 74 |
-
# - DM Sans font (was @import url in <style> block)
|
| 75 |
-
# - Slate color palette (was hardcoded hex in inline styles)
|
| 76 |
-
# - Soft rounded corners and spacing
|
| 77 |
-
# USED BY: B11 (gr.Blocks constructor)
|
| 78 |
-
# REPLACES: Old HEADER_HTML lines 33-38 (<style> block with CSS)
|
| 79 |
-
# WHY SOFT: Soft theme has rounded inputs, gentle shadows, and
|
| 80 |
-
# warm neutral tones that work well for research tools.
|
| 81 |
-
# ────────────────────────────────────────────────────────────────
|
| 82 |
-
theme = gr.themes.Soft(
|
| 83 |
-
primary_hue="slate",
|
| 84 |
-
font=gr.themes.GoogleFont("DM Sans"),
|
| 85 |
-
font_mono=gr.themes.GoogleFont("JetBrains Mono"),
|
| 86 |
-
)
|
| 87 |
-
# ── end B3: Theme ──────────────────────────────────────────────
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
# ╔═══════════════════════════════════════════════════════════════╗
|
| 91 |
-
# ║ SECTION 2 — HELPER FUNCTIONS ║
|
| 92 |
-
# ║ Pure Python functions that process data and return clean ║
|
| 93 |
-
# ║ values (strings, lists, figures). NONE of these functions ║
|
| 94 |
-
# ║ return HTML strings. They feed data to UI components in ║
|
| 95 |
-
# ║ Section 3 via event handlers in Section 4. ║
|
| 96 |
-
# ╚═══════════════════════════════════════════════════════════════╝
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
# ── B4: _latest_output() ───────────────────────────────────────
|
| 100 |
-
# PURPOSE: Scan /tmp for all rq4_* output files generated by the
|
| 101 |
-
# BERTopic agent pipeline (CSVs, JSONs, chart files).
|
| 102 |
-
# Sorts them by pipeline phase order so the download
|
| 103 |
-
# component shows files in logical sequence.
|
| 104 |
-
# RETURNS: List[str] of filepaths sorted by phase, or None
|
| 105 |
-
# USED BY: B6 (respond) — attaches to download component after
|
| 106 |
-
# each agent response
|
| 107 |
-
# B10 (_submit_review) — refreshes downloads after review
|
| 108 |
-
# B19 (_auto_load_csv) — refreshes after initial upload
|
| 109 |
-
# ────────────────────────────────────────────────────────────────
|
| 110 |
-
def _latest_output():
|
| 111 |
-
"""Scan /tmp for ALL rq4_* files, sorted by phase order.
|
| 112 |
-
Returns list of filepaths for gr.File download component."""
|
| 113 |
-
phase_order = {
|
| 114 |
-
"summaries": 1, "labels": 2, "themes": 3, "taxonomy": 4,
|
| 115 |
-
"emb": 0, "intertopic": 5, "bars": 6, "hierarchy": 7,
|
| 116 |
-
"heatmap": 8, "comparison": 9, "narrative": 10,
|
| 117 |
-
}
|
| 118 |
-
files = (
|
| 119 |
-
glob.glob("/tmp/rq4_*.csv")
|
| 120 |
-
+ glob.glob("/tmp/rq4_*.json")
|
| 121 |
-
+ glob.glob("/tmp/checkpoints/rq4_*.json")
|
| 122 |
-
)
|
| 123 |
-
scored = list(map(
|
| 124 |
-
lambda f: (sum(v * (k in f) for k, v in phase_order.items()), f),
|
| 125 |
-
files,
|
| 126 |
-
))
|
| 127 |
-
scored.sort(key=lambda x: x[0])
|
| 128 |
-
return list(map(lambda x: x[1], scored)) or None
|
| 129 |
-
# ── end B4: _latest_output ─────────────────────────────────────
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
# ── B5: _build_progress() ──────────────────────────────────────
|
| 133 |
-
# PURPOSE: Check which Braun & Clarke phases are complete by
|
| 134 |
-
# scanning for checkpoint files on disk. Returns a
|
| 135 |
-
# human-readable emoji string showing pipeline status.
|
| 136 |
-
# RETURNS: str like "✅ Load → ✅ Codes → ⏳ Themes → ⬜ Report"
|
| 137 |
-
# USED BY: B14 (phase_progress initial value)
|
| 138 |
-
# B18 (respond_with_viz) — refreshes after each agent turn
|
| 139 |
-
# B10 (_submit_review) — refreshes after review submission
|
| 140 |
-
# B19 (_auto_load_csv) — refreshes after CSV upload
|
| 141 |
-
# REPLACES: Old _build_progress() which returned 24 lines of HTML
|
| 142 |
-
# with inline-styled <span> elements and color codes.
|
| 143 |
-
# Now returns pure text with emoji — gr.Markdown renders it.
|
| 144 |
-
# ────────────────────────────────────────────────────────────────
|
| 145 |
-
def _build_progress():
|
| 146 |
-
"""Return emoji progress pipeline. NO HTML — just text + emoji.
|
| 147 |
-
Displayed in gr.Markdown component (B14)."""
|
| 148 |
-
checks = [
|
| 149 |
-
("Load", bool(glob.glob("/tmp/checkpoints/rq4_*_summaries.json")
|
| 150 |
-
or glob.glob("/tmp/checkpoints/rq4_*_emb.npy"))),
|
| 151 |
-
("Codes", bool(glob.glob("/tmp/checkpoints/rq4_*_labels.json"))),
|
| 152 |
-
("Themes", bool(glob.glob("/tmp/checkpoints/rq4_*_themes.json"))),
|
| 153 |
-
("Review", bool(glob.glob("/tmp/checkpoints/rq4_*_themes.json"))),
|
| 154 |
-
("Names", bool(glob.glob("/tmp/checkpoints/rq4_*_themes.json"))),
|
| 155 |
-
("PAJAIS", bool(glob.glob("/tmp/checkpoints/rq4_*_taxonomy_map.json"))),
|
| 156 |
-
("Report", bool(glob.glob("/tmp/rq4_comparison.csv")
|
| 157 |
-
or glob.glob("/tmp/rq4_narrative.txt"))),
|
| 158 |
-
]
|
| 159 |
-
return " → ".join(f"{'✅' if done else '⬜'} {name}" for name, done in checks)
|
| 160 |
-
# ── end B5: _build_progress ────────────────────────────────────
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
# ── B6: respond() ──────────────────────────────────────────────
|
| 164 |
-
# PURPOSE: Core chat handler. This is the brain of the app.
|
| 165 |
-
# 1. Stores uploaded CSV file path (if new upload)
|
| 166 |
-
# 2. Appends file location + phase context to user message
|
| 167 |
-
# so the agent knows what data is available
|
| 168 |
-
# 3. Yields a "thinking..." bubble immediately (user sees
|
| 169 |
-
# instant feedback while agent processes)
|
| 170 |
-
# 4. Invokes the LangGraph agent (Mistral decides which
|
| 171 |
-
# BERTopic tools to call)
|
| 172 |
-
# 5. Replaces thinking bubble with actual agent response
|
| 173 |
-
# 6. Attaches latest output files to download component
|
| 174 |
-
# INPUTS: message (str), chat_history (list[dict]), uploaded_file (str|None)
|
| 175 |
-
# YIELDS: Tuple of (chat_history, empty_string, download_files)
|
| 176 |
-
# — yields TWICE: first with progress bubble, then with final response
|
| 177 |
-
# TALKS TO: B2 (agent.invoke) — sends message, gets response
|
| 178 |
-
# B4 (_latest_output) — gets download file list
|
| 179 |
-
# USED BY: B18 (respond_with_viz wraps this)
|
| 180 |
-
# B19 (_auto_load_csv wraps this)
|
| 181 |
-
# NOTE: Uses single thread_id="session" so agent remembers
|
| 182 |
-
# previous turns (loaded CSV path, current phase, etc.)
|
| 183 |
-
# ────────────────────────────────────────────────────────────────
|
| 184 |
-
def respond(message, chat_history, uploaded_file):
|
| 185 |
-
"""Handle one chat turn with the LangGraph agent.
|
| 186 |
-
Yields twice: progress bubble → final response."""
|
| 187 |
-
global _msg_count
|
| 188 |
-
_msg_count += 1
|
| 189 |
-
|
| 190 |
-
# Store file path — uses `or` short-circuit instead of if/else
|
| 191 |
-
_uploaded["path"] = uploaded_file or _uploaded.get("path", "")
|
| 192 |
-
|
| 193 |
-
# Tell agent where the CSV is (prevents hallucinated filepaths)
|
| 194 |
-
file_note = (
|
| 195 |
-
f"\n[CSV file at: {_uploaded['path']}]" * bool(_uploaded["path"])
|
| 196 |
-
) or "\n[No CSV uploaded yet — ask user to upload a file first]"
|
| 197 |
-
|
| 198 |
-
# Tell agent what phase we're in based on existing checkpoint files
|
| 199 |
-
phase_context = (
|
| 200 |
-
"\n[Phase context: labels exist]"
|
| 201 |
-
* bool(glob.glob("/tmp/checkpoints/rq4_*_labels.json"))
|
| 202 |
-
or "\n[Phase context: embeddings exist]"
|
| 203 |
-
* bool(glob.glob("/tmp/checkpoints/rq4_*_emb.npy"))
|
| 204 |
-
or "\n[Phase context: fresh start]"
|
| 205 |
-
)
|
| 206 |
-
|
| 207 |
-
text = ((message or "").strip() or "Analyze my Scopus CSV") + file_note + phase_context
|
| 208 |
-
print(f"\n{'='*60}\n>>> MSG #{_msg_count}: '{text[:120]}'\n{'='*60}")
|
| 209 |
-
|
| 210 |
-
# YIELD 1: Show "thinking" bubble immediately
|
| 211 |
-
chat_history = chat_history + [
|
| 212 |
-
{"role": "user", "content": (message or "").strip()},
|
| 213 |
-
{"role": "assistant", "content": "🔬 **Working...** _Agent is thinking..._"},
|
| 214 |
-
]
|
| 215 |
-
yield chat_history, "", _latest_output()
|
| 216 |
-
|
| 217 |
-
# Invoke agent — Mistral brain decides which tools to call
|
| 218 |
-
result = agent.invoke(
|
| 219 |
-
{"messages": [("human", text)]},
|
| 220 |
-
config={"configurable": {"thread_id": "session"}},
|
| 221 |
-
)
|
| 222 |
-
response = result["messages"][-1].content
|
| 223 |
-
print(f">>> Response ({len(response)} chars)")
|
| 224 |
-
|
| 225 |
-
# YIELD 2: Replace thinking bubble with actual response
|
| 226 |
-
chat_history[-1] = {"role": "assistant", "content": response}
|
| 227 |
-
gr.Info(f"Agent responded ({len(response)} chars)")
|
| 228 |
-
yield chat_history, "", _latest_output()
|
| 229 |
-
# ── end B6: respond ────────────────────────────────────────────
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
# ── B7: _load_chart() ──────────────────────────────────────────
|
| 233 |
-
# PURPOSE: Load a BERTopic visualization chart from a saved Plotly
|
| 234 |
-
# JSON file on disk and return the figure object.
|
| 235 |
-
# The gr.Plot component in B17a renders this directly —
|
| 236 |
-
# no iframe, no HTML escaping, no srcdoc hack.
|
| 237 |
-
# INPUT: chart_name (str) — filename like "rq4_intertopic.json"
|
| 238 |
-
# RETURNS: plotly.graph_objects.Figure or None
|
| 239 |
-
# USED BY: B17a (chart_selector.change event)
|
| 240 |
-
# B18 (respond_with_viz) — auto-shows latest chart
|
| 241 |
-
# REPLACES: Old _load_chart() which used html.escape() + iframe
|
| 242 |
-
# srcdoc to embed HTML files. That was 8 lines of hack.
|
| 243 |
-
# REQUIRES: BERTopic tools in tools.py must save charts as Plotly
|
| 244 |
-
# JSON via pio.to_json(fig) instead of fig.write_html().
|
| 245 |
-
# ────────────────────────────────────────────────────────────────
|
| 246 |
-
def _load_chart(chart_name):
|
| 247 |
-
"""Load Plotly chart from JSON file. Returns figure for gr.Plot.
|
| 248 |
-
No HTML, no iframe — just a native Plotly figure object."""
|
| 249 |
-
path = f"/tmp/{chart_name}"
|
| 250 |
-
(not os.path.exists(path)) and (not None) # guard
|
| 251 |
-
return pio.from_json(open(path).read()) * bool(os.path.exists(path)) or None
|
| 252 |
-
|
| 253 |
-
def _get_chart_choices():
|
| 254 |
-
"""Find all rq4_*.json chart files in /tmp."""
|
| 255 |
-
files = sorted(glob.glob("/tmp/rq4_*.json"))
|
| 256 |
-
return list(map(os.path.basename, files))
|
| 257 |
-
# ── end B7: _load_chart ───────────────────────────────────────
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
# ── B8: _load_review_table() ───────────────────────────────────
|
| 261 |
-
# PURPOSE: Load the latest BERTopic phase data (taxonomy, themes,
|
| 262 |
-
# labels, or summaries — whichever is most recent) and
|
| 263 |
-
# build a review table for the researcher to approve,
|
| 264 |
-
# rename, or annotate topics.
|
| 265 |
-
# RETURNS: List[List] with 8 columns matching the Dataframe schema:
|
| 266 |
-
# [#, Label, Evidence, Sentences, Papers, Approve, Rename, Reasoning]
|
| 267 |
-
# - Column 5 (Approve) is bool (True/False) → renders as checkbox
|
| 268 |
-
# - Columns 0-4 are read-only (enforced by static_columns in B16)
|
| 269 |
-
# - Columns 5-7 are editable by the researcher
|
| 270 |
-
# USED BY: B16 (initial table value)
|
| 271 |
-
# B10 (_submit_review) — reloads after agent processes review
|
| 272 |
-
# B18 (respond_with_viz) — refreshes after each agent turn
|
| 273 |
-
# REPLACES: Old version which returned "yes"/"no" strings for Approve.
|
| 274 |
-
# Now returns True/False so gr.Dataframe renders checkboxes.
|
| 275 |
-
# ────────────────────────────────────────────────────────────────
|
| 276 |
-
def _load_review_table():
|
| 277 |
-
"""Build review table from latest checkpoint JSON.
|
| 278 |
-
Approve column is bool (renders as checkbox in gr.Dataframe).
|
| 279 |
-
Priority: taxonomy_map > themes > labels > summaries."""
|
| 280 |
-
taxonomy_files = sorted(glob.glob("/tmp/checkpoints/rq4_*_taxonomy_map.json"))
|
| 281 |
-
theme_files = sorted(glob.glob("/tmp/checkpoints/rq4_*_themes.json"))
|
| 282 |
-
label_files = sorted(glob.glob("/tmp/checkpoints/rq4_*_labels.json"))
|
| 283 |
-
summary_files = sorted(glob.glob("/tmp/checkpoints/rq4_*_summaries.json"))
|
| 284 |
-
|
| 285 |
-
# Pick most advanced checkpoint available
|
| 286 |
-
path = (
|
| 287 |
-
(taxonomy_files and taxonomy_files[-1])
|
| 288 |
-
or (theme_files and theme_files[-1])
|
| 289 |
-
or (label_files and label_files[-1])
|
| 290 |
-
or (summary_files and summary_files[-1])
|
| 291 |
-
or ""
|
| 292 |
-
)
|
| 293 |
-
is_taxonomy = bool(taxonomy_files and taxonomy_files[-1] == path)
|
| 294 |
-
data = (os.path.exists(path) and json.load(open(path))) or []
|
| 295 |
-
|
| 296 |
-
# For taxonomy: merge with themes to get sentence/paper counts
|
| 297 |
-
theme_lookup = {}
|
| 298 |
-
(is_taxonomy and theme_files) and theme_lookup.update(
|
| 299 |
-
{t.get("label", ""): t for t in json.load(open(theme_files[-1]))}
|
| 300 |
-
)
|
| 301 |
-
|
| 302 |
-
rows = list(map(
|
| 303 |
-
lambda pair: [
|
| 304 |
-
pair[0], # #
|
| 305 |
-
pair[1].get("label", pair[1].get("top_words", ""))[:60], # Label
|
| 306 |
-
# Evidence: PAJAIS mapping for taxonomy, nearest sentence otherwise
|
| 307 |
-
(
|
| 308 |
-
is_taxonomy
|
| 309 |
-
and f"→ {pair[1].get('pajais_match', '?')} | {pair[1].get('reasoning', '')}"[:120]
|
| 310 |
-
) or (
|
| 311 |
-
(pair[1].get("nearest", [{}])[0].get("sentence", "")[:120] + "...")
|
| 312 |
-
* bool(pair[1].get("nearest"))
|
| 313 |
-
),
|
| 314 |
-
# Sentence/paper counts
|
| 315 |
-
theme_lookup.get(pair[1].get("label", ""), pair[1]).get(
|
| 316 |
-
"sentence_count", pair[1].get("sentence_count", 0)),
|
| 317 |
-
theme_lookup.get(pair[1].get("label", ""), pair[1]).get(
|
| 318 |
-
"paper_count", pair[1].get("paper_count", 0)),
|
| 319 |
-
True, # Approve (bool → checkbox)
|
| 320 |
-
"", # Rename To
|
| 321 |
-
"", # Reasoning
|
| 322 |
-
],
|
| 323 |
-
enumerate(data),
|
| 324 |
-
))
|
| 325 |
-
return rows or [[0, "No data yet", "", 0, 0, False, "", ""]]
|
| 326 |
-
# ── end B8: _load_review_table ─────────────────────────────────
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
# ── B9: _show_papers_by_select() ───────────────────────────────
|
| 330 |
-
# PURPOSE: When the researcher clicks any row in the review table,
|
| 331 |
-
# this function fires and shows the papers belonging to
|
| 332 |
-
# that topic. Eliminates the old workflow of typing a
|
| 333 |
-
# Topic # into a separate input and clicking "Show Papers".
|
| 334 |
-
# INPUT: gr.SelectData event — contains .index (row, col) and .value
|
| 335 |
-
# RETURNS: str — formatted paper list for gr.Textbox (paper_list)
|
| 336 |
-
# TRIGGERED BY: review_table.select() event in B16
|
| 337 |
-
# REPLACES: Old _show_papers(topic_id) + topic_num (gr.Number) +
|
| 338 |
-
# view_papers_btn (gr.Button) — all three components removed.
|
| 339 |
-
# NOTE: Uses column 0 value (the # column) as topic_id, NOT the
|
| 340 |
-
# row index, because filtering/sorting may reorder rows.
|
| 341 |
-
# ────────────────────────────────────────────────────────────────
|
| 342 |
-
def _show_papers_by_select(table_data, evt: gr.SelectData):
|
| 343 |
-
"""Show papers for clicked row. Uses column 0 as topic_id.
|
| 344 |
-
Triggered by review_table.select() — no separate Topic # input needed."""
|
| 345 |
-
row_idx = evt.index[0]
|
| 346 |
-
|
| 347 |
-
# Get topic_id from column 0 of the clicked row (not row index)
|
| 348 |
-
topic_id = int(table_data.iloc[row_idx, 0]) if hasattr(table_data, 'iloc') else int(table_data[row_idx][0])
|
| 349 |
-
|
| 350 |
-
# Load paper data from checkpoint files
|
| 351 |
-
label_files = sorted(glob.glob("/tmp/checkpoints/rq4_*_labels.json"))
|
| 352 |
-
summary_files = sorted(glob.glob("/tmp/checkpoints/rq4_*_summaries.json"))
|
| 353 |
-
all_files = label_files or summary_files
|
| 354 |
-
|
| 355 |
-
lines = []
|
| 356 |
-
for f in all_files:
|
| 357 |
-
source = os.path.basename(f).split("_")[1]
|
| 358 |
-
data = json.load(open(f))
|
| 359 |
-
for t in data:
|
| 360 |
-
(t.get("topic_id") == topic_id) and lines.append(
|
| 361 |
-
f"═══ {source.upper()} — Topic {topic_id}: "
|
| 362 |
-
f"{t.get('label', t.get('top_words', '')[:50])} ═══\n"
|
| 363 |
-
f"{t.get('sentence_count', 0)} sentences from {t.get('paper_count', 0)} papers\n"
|
| 364 |
-
f"AI Reasoning: {t.get('reasoning', 'not yet labeled')}\n\n"
|
| 365 |
-
f"── 5 NEAREST CENTROID SENTENCES (evidence) ──\n"
|
| 366 |
-
+ "\n".join(
|
| 367 |
-
f" {i+1}. \"{t['nearest'][i]['sentence'][:200]}\"\n"
|
| 368 |
-
f" Paper: {t['nearest'][i].get('title', '')[:100]}"
|
| 369 |
-
for i in range(min(5, len(t.get('nearest', []))))
|
| 370 |
-
)
|
| 371 |
-
+ "\n\n── ALL PAPER TITLES ──\n"
|
| 372 |
-
+ "\n".join(
|
| 373 |
-
f" {i+1}. {title}"
|
| 374 |
-
for i, title in enumerate(t.get('paper_titles', []))
|
| 375 |
-
)
|
| 376 |
-
)
|
| 377 |
-
return "\n\n".join(lines) or f"Topic {topic_id} not found."
|
| 378 |
-
# ── end B9: _show_papers_by_select ─────────────────────────────
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
# ── B10: _submit_review() ──────────────────────────────────────
|
| 382 |
-
# PURPOSE: When the researcher finishes editing the review table
|
| 383 |
-
# (checking Approve boxes, typing Rename values, adding
|
| 384 |
-
# Reasoning notes) and clicks "Submit Review", this
|
| 385 |
-
# function converts those edits into a natural language
|
| 386 |
-
# message and sends it to the agent for processing.
|
| 387 |
-
# INPUTS: table_data (DataFrame from gr.Dataframe), chat_history (list)
|
| 388 |
-
# YIELDS: Tuple of (chat, download, chart_choices, chart_fig,
|
| 389 |
-
# review_rows, progress_str) — yields twice (progress → final)
|
| 390 |
-
# TALKS TO: B2 (agent.invoke) — sends review decisions
|
| 391 |
-
# B4 (_latest_output) — refreshes downloads
|
| 392 |
-
# B5 (_build_progress) — refreshes pipeline status
|
| 393 |
-
# B7 (_get_chart_choices) — refreshes chart dropdown
|
| 394 |
-
# B8 (_load_review_table) — reloads table with updated data
|
| 395 |
-
# NOTE: Column 5 (Approve) is now bool. True = approve, False = reject.
|
| 396 |
-
# ────────────────────────────────────────────────────────────────
|
| 397 |
-
def _submit_review(table_data, chat_history):
|
| 398 |
-
"""Convert review table edits into agent message.
|
| 399 |
-
Approve column is bool (checkbox), not string."""
|
| 400 |
-
rows = table_data.values.tolist()
|
| 401 |
-
lines = list(map(
|
| 402 |
-
lambda r: (
|
| 403 |
-
f"Topic {int(r[0])}: "
|
| 404 |
-
+ (f"RENAME to '{r[6]}'" * bool(str(r[6]).strip()))
|
| 405 |
-
+ (f"APPROVE '{r[1]}'" * (not bool(str(r[6]).strip())) * bool(r[5]))
|
| 406 |
-
+ (f"REJECT" * (not r[5]))
|
| 407 |
-
+ (f" — reason: {r[7]}" * bool(str(r[7]).strip()))
|
| 408 |
-
),
|
| 409 |
-
rows,
|
| 410 |
-
))
|
| 411 |
-
review_msg = "Review decisions:\n" + "\n".join(lines)
|
| 412 |
-
print(f">>> Review submitted: {review_msg[:200]}")
|
| 413 |
-
|
| 414 |
-
# YIELD 1: Show processing bubble
|
| 415 |
-
chat_history = chat_history + [
|
| 416 |
-
{"role": "user", "content": review_msg},
|
| 417 |
-
{"role": "assistant", "content": "🔬 **Processing review decisions...**"},
|
| 418 |
-
]
|
| 419 |
-
gr.Info("Review submitted to agent")
|
| 420 |
-
yield (chat_history, _latest_output(), gr.update(),
|
| 421 |
-
gr.update(), gr.update(), _build_progress())
|
| 422 |
-
|
| 423 |
-
# Invoke agent with review decisions
|
| 424 |
-
result = agent.invoke(
|
| 425 |
-
{"messages": [("human", review_msg)]},
|
| 426 |
-
config={"configurable": {"thread_id": "session"}},
|
| 427 |
-
)
|
| 428 |
-
response = result["messages"][-1].content
|
| 429 |
-
|
| 430 |
-
# YIELD 2: Final response + refreshed table/charts
|
| 431 |
-
chat_history[-1] = {"role": "assistant", "content": response}
|
| 432 |
-
gr.Info("Review processed — table updated")
|
| 433 |
-
yield (
|
| 434 |
-
chat_history,
|
| 435 |
-
_latest_output(),
|
| 436 |
-
gr.update(choices=_get_chart_choices()),
|
| 437 |
-
gr.update(),
|
| 438 |
-
gr.update(value=_load_review_table()),
|
| 439 |
-
_build_progress(),
|
| 440 |
-
)
|
| 441 |
-
# ── end B10: _submit_review ────────────────────────────────────
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
# ╔═══════════════════════════════════════════════════════════════╗
|
| 445 |
-
# ║ SECTION 3 — UI LAYOUT ║
|
| 446 |
-
# ║ All visual components defined here using ONLY native Gradio ║
|
| 447 |
-
# ║ widgets. Zero gr.HTML() calls. Theming via B3. ║
|
| 448 |
-
# ║ Layout: Header → Upload → Progress → Chat → Results tabs ║
|
| 449 |
-
# ╚═══════════════════════════════════════════════════════════════╝
|
| 450 |
-
|
| 451 |
-
print(">>> Building UI...")
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
# ── B11: gr.Blocks container ───────────────────────────────────
|
| 455 |
-
# PURPOSE: Root container for the entire application UI.
|
| 456 |
-
# Sets the visual theme (B3), enables full browser width,
|
| 457 |
-
# and hides the default Gradio footer NATIVELY using
|
| 458 |
-
# footer_links=[] (no CSS hack needed).
|
| 459 |
-
# CONTAINS: All UI blocks B12 through B17b
|
| 460 |
-
# CONFIG: title — browser tab title
|
| 461 |
-
# theme — from B3 (Soft + DM Sans + slate)
|
| 462 |
-
# fill_width — removes side padding, uses full browser width
|
| 463 |
-
# footer_links — empty list hides footer without CSS
|
| 464 |
-
# ────────────────────────────────────────────────────────────────
|
| 465 |
-
with gr.Blocks(
|
| 466 |
-
title="Topic Modelling — Agentic AI",
|
| 467 |
-
theme=theme,
|
| 468 |
-
fill_width=True,
|
| 469 |
-
footer_links=[],
|
| 470 |
-
) as demo:
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
# ── B12: Header ────────────────────────────────────────────
|
| 474 |
-
# PURPOSE: Application title and subtitle. Single gr.Markdown
|
| 475 |
-
# call replaces 15 lines of HEADER_HTML that included
|
| 476 |
-
# a gradient background div, font imports, and inline CSS.
|
| 477 |
-
# REPLACES: Old HEADER_HTML constant (lines 32-47 of old app.py)
|
| 478 |
-
# ───────────────────────────────────────────────────────────
|
| 479 |
-
gr.Markdown(
|
| 480 |
-
"# 🔬 Topic Modelling — Agentic AI\n"
|
| 481 |
-
"*Mistral · Cosine Clustering · 384d · B&C Thematic Analysis*"
|
| 482 |
-
)
|
| 483 |
-
# ── end B12: Header ────────────────────────────────────────
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
# ── B13: Data input ────────────────────────────────────────
|
| 487 |
-
# PURPOSE: CSV file upload area with inline instructions.
|
| 488 |
-
# Researcher uploads their Scopus CSV export here.
|
| 489 |
-
# On upload, B19 auto-triggers the first analysis.
|
| 490 |
-
# COMPONENTS: gr.File (upload) + gr.Markdown (instructions)
|
| 491 |
-
# EVENTS: upload.change → B19 (_auto_load_csv)
|
| 492 |
-
# ───────────────────────────────────────────────────────────
|
| 493 |
-
gr.Markdown("**① Data input**")
|
| 494 |
-
with gr.Row():
|
| 495 |
-
upload = gr.File(label="📂 Upload Scopus CSV", file_types=[".csv"])
|
| 496 |
-
gr.Markdown("**Upload your CSV** then type `run abstract only` in chat below")
|
| 497 |
-
# ── end B13: Data input ────────────────────────────────────
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
# ── B14: Progress pipeline ─────────────────────────────────
|
| 501 |
-
# PURPOSE: Visual indicator of which Braun & Clarke analysis
|
| 502 |
-
# phases are complete. Updated after every agent action.
|
| 503 |
-
# Now uses gr.Markdown with emoji text (was gr.HTML
|
| 504 |
-
# with inline-styled colored <span> elements).
|
| 505 |
-
# COMPONENT: gr.Markdown — displays emoji string from B5
|
| 506 |
-
# UPDATED BY: B18 (after chat), B10 (after review), B19 (after upload)
|
| 507 |
-
# REPLACES: Old gr.HTML(value=_build_progress()) with 24 lines of HTML
|
| 508 |
-
# ───────────────────────────────────────────────────────────
|
| 509 |
-
phase_progress = gr.Markdown(value=_build_progress())
|
| 510 |
-
# ── end B14: Progress pipeline ─────────────────────────────
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
# ── B15: Chatbot + input ───────────────────────────────────
|
| 514 |
-
# PURPOSE: Main conversation interface between researcher and
|
| 515 |
-
# the LangGraph agent. The chatbot displays message
|
| 516 |
-
# history with markdown rendering. The textbox + button
|
| 517 |
-
# below it capture user input.
|
| 518 |
-
# COMPONENTS: gr.Chatbot (display), gr.Textbox (input), gr.Button (send)
|
| 519 |
-
# EVENTS: msg.submit → B18, send.click → B18
|
| 520 |
-
# NOTE: placeholder text guides the researcher on available commands.
|
| 521 |
-
# height=300 keeps chat visible while showing results below.
|
| 522 |
-
# ───────────────────────────────────────────────────────────
|
| 523 |
-
gr.Markdown("**② Agent conversation** — follow the prompts below")
|
| 524 |
-
with gr.Group():
|
| 525 |
-
chatbot = gr.Chatbot(
|
| 526 |
-
height=300,
|
| 527 |
-
show_label=False,
|
| 528 |
-
placeholder="Upload your Scopus CSV above, then type: run abstract only",
|
| 529 |
-
)
|
| 530 |
-
with gr.Row():
|
| 531 |
-
msg = gr.Textbox(
|
| 532 |
-
placeholder="run · approve · show topic 4 papers · group 0 1 5 · done",
|
| 533 |
-
show_label=False, scale=9, lines=1, max_lines=1, container=False,
|
| 534 |
-
)
|
| 535 |
-
send = gr.Button("Send", variant="primary", scale=1, min_width=70)
|
| 536 |
-
# ── end B15: Chatbot + input ───────────────────────────────
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
# ── B16: Review table tab ──────────────────────────────────
|
| 540 |
-
# PURPOSE: Interactive topic review table where the researcher
|
| 541 |
-
# approves, renames, or annotates BERTopic-discovered
|
| 542 |
-
# topics. This is the core human-in-the-loop interface.
|
| 543 |
-
#
|
| 544 |
-
# KEY FEATURES (all native Gradio, no HTML):
|
| 545 |
-
# - static_columns=[0,1,2,3,4] — first 5 columns (#, Label,
|
| 546 |
-
# Evidence, Sentences, Papers) are READ-ONLY. Prevents
|
| 547 |
-
# accidental edits to agent-generated data.
|
| 548 |
-
# - datatype "bool" on column 5 — Approve renders as a native
|
| 549 |
-
# CHECKBOX. Researcher clicks to toggle, no typing needed.
|
| 550 |
-
# - pinned_columns=2 — # and Label columns stay visible when
|
| 551 |
-
# scrolling horizontally through wider columns.
|
| 552 |
-
# - show_search="filter" — built-in column filtering. Researcher
|
| 553 |
-
# can filter by paper count, sentence count, etc.
|
| 554 |
-
# - .select() event — clicking any row auto-loads that topic's
|
| 555 |
-
# papers in the textbox below. REPLACES the old workflow of
|
| 556 |
-
# Topic # input + Show Papers button (both removed).
|
| 557 |
-
#
|
| 558 |
-
# COMPONENTS: gr.Dataframe, gr.Button (submit), gr.Textbox (papers)
|
| 559 |
-
# EVENTS: review_table.select → B9 (_show_papers_by_select)
|
| 560 |
-
# submit_review.click → B10 (_submit_review)
|
| 561 |
-
# DATA: Loaded by B8 (_load_review_table)
|
| 562 |
-
# REPLACES: Old gr.Dataframe (no static_columns, string Approve,
|
| 563 |
-
# no search) + topic_num + view_papers_btn
|
| 564 |
-
# ───────────────────────────────────────────────────────────
|
| 565 |
-
gr.Markdown("**③ Results** — review table, charts, downloads")
|
| 566 |
-
with gr.Tabs():
|
| 567 |
-
with gr.Tab("📋 Review Table"):
|
| 568 |
-
gr.Markdown(
|
| 569 |
-
"*Edit Approve / Rename To / Reasoning → click Submit. "
|
| 570 |
-
"Click any row to see its papers below.*"
|
| 571 |
-
)
|
| 572 |
-
review_table = gr.Dataframe(
|
| 573 |
-
headers=[
|
| 574 |
-
"#", "Topic Label", "Top Evidence Sentence",
|
| 575 |
-
"Sentences", "Papers", "Approve", "Rename To", "Your Reasoning",
|
| 576 |
-
],
|
| 577 |
-
datatype=[
|
| 578 |
-
"number", "str", "str", "number", "number",
|
| 579 |
-
"bool", "str", "str",
|
| 580 |
-
],
|
| 581 |
-
interactive=True,
|
| 582 |
-
static_columns=[0, 1, 2, 3, 4],
|
| 583 |
-
pinned_columns=2,
|
| 584 |
-
show_search="filter",
|
| 585 |
-
show_row_numbers=True,
|
| 586 |
-
show_fullscreen_button=True,
|
| 587 |
-
show_copy_button=True,
|
| 588 |
-
column_widths=["60px", "200px", "250px", "80px", "70px",
|
| 589 |
-
"70px", "150px", "200px"],
|
| 590 |
-
row_count=(1, "dynamic"),
|
| 591 |
-
)
|
| 592 |
-
submit_review = gr.Button("✅ Submit Review to Agent", variant="primary")
|
| 593 |
-
|
| 594 |
-
# Paper viewer — triggered by clicking any row (replaces Topic # + button)
|
| 595 |
-
gr.Markdown("---")
|
| 596 |
-
gr.Markdown("**📄 Papers in selected topic** *(click any row above)*")
|
| 597 |
-
paper_list = gr.Textbox(
|
| 598 |
-
label="Papers in selected topic",
|
| 599 |
-
lines=8, interactive=False,
|
| 600 |
-
)
|
| 601 |
-
# ── end B16: Review table tab ──────────────────────────────
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
# ── B17a: Charts tab ───────────────────────────────────
|
| 605 |
-
# PURPOSE: Display BERTopic visualization charts (intertopic
|
| 606 |
-
# distance map, bar chart, hierarchy, heatmap).
|
| 607 |
-
# Charts are loaded as Plotly figure objects from
|
| 608 |
-
# JSON files and rendered natively in gr.Plot.
|
| 609 |
-
# COMPONENTS: gr.Dropdown (selector), gr.Plot (display)
|
| 610 |
-
# EVENTS: chart_selector.change → B7 (_load_chart)
|
| 611 |
-
# REPLACES: Old iframe + srcdoc hack that used html.escape()
|
| 612 |
-
# to embed HTML files. Now uses gr.Plot directly.
|
| 613 |
-
# ───────────────────────────────────────────────────────
|
| 614 |
-
with gr.Tab("📊 Charts"):
|
| 615 |
-
chart_selector = gr.Dropdown(
|
| 616 |
-
choices=[], label="Select Chart", interactive=True,
|
| 617 |
-
)
|
| 618 |
-
chart_display = gr.Plot(label="BERTopic Visualization")
|
| 619 |
-
# ── end B17a: Charts tab ───────────────────────────────
|
| 620 |
-
|
| 621 |
-
|
| 622 |
-
# ── B17b: Download tab ─────────────────────────────────
|
| 623 |
-
# PURPOSE: Multi-file download for all pipeline outputs.
|
| 624 |
-
# Shows file descriptions by phase and a gr.File
|
| 625 |
-
# component with all generated files.
|
| 626 |
-
# COMPONENTS: gr.Markdown (descriptions), gr.File (download)
|
| 627 |
-
# UPDATED BY: B18, B10, B19 — refreshed after each action
|
| 628 |
-
# ───────────────────────────────────────────────────────
|
| 629 |
-
with gr.Tab("📥 Download"):
|
| 630 |
-
gr.Markdown(
|
| 631 |
-
"**Files by Phase (per run: abstract / title):**\n\n"
|
| 632 |
-
"**Phase 2 — Discovery:** `summaries.json` · `emb.npy`\n\n"
|
| 633 |
-
"**Phase 2 — Labeling:** `labels.json`\n\n"
|
| 634 |
-
"**Phase 2 — Charts:** `intertopic.json` · `bars.json` · "
|
| 635 |
-
"`hierarchy.json` · `heatmap.json`\n\n"
|
| 636 |
-
"**Phase 3 — Themes:** `themes.json`\n\n"
|
| 637 |
-
"**Phase 5.5 — Taxonomy:** `taxonomy_map.json`\n\n"
|
| 638 |
-
"**Phase 6 — Report:** `comparison.csv` · `narrative.txt`"
|
| 639 |
-
)
|
| 640 |
-
download = gr.File(label="All output files", file_count="multiple")
|
| 641 |
-
# ── end B17b: Download tab ─────────────────────────────
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
# ╔═══════════════════════════════════════════════════════════╗
|
| 645 |
-
# ║ SECTION 4 — EVENT WIRING ║
|
| 646 |
-
# ║ Connect UI components to helper functions. This is ║
|
| 647 |
-
# ║ where data flows are defined: which function runs when ║
|
| 648 |
-
# ║ a button is clicked, a file is uploaded, or a row is ║
|
| 649 |
-
# ║ selected. No HTML, no CSS — just Python event binding. ║
|
| 650 |
-
# ╚═══════════════════════════════════════════════════════════╝
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
# ── B18: respond_with_viz() + event bindings ───────────────
|
| 654 |
-
# PURPOSE: Wrapper around B6 (respond) that also refreshes
|
| 655 |
-
# the chart dropdown, chart display, review table,
|
| 656 |
-
# and progress pipeline after each agent response.
|
| 657 |
-
# This is the main "after every chat turn, update
|
| 658 |
-
# everything" orchestrator.
|
| 659 |
-
# CALLS: B6 (respond), B5 (_build_progress), B7 (_load_chart,
|
| 660 |
-
# _get_chart_choices), B8 (_load_review_table)
|
| 661 |
-
# BINDINGS: msg.submit → this function
|
| 662 |
-
# send.click → this function
|
| 663 |
-
# OUTPUTS: chatbot, msg, download, chart_selector, chart_display,
|
| 664 |
-
# review_table, phase_progress (7 components updated)
|
| 665 |
-
# ───────────────────────────────────────────────────────────
|
| 666 |
-
chart_selector.change(_load_chart, [chart_selector], [chart_display])
|
| 667 |
-
|
| 668 |
-
review_table.select(
|
| 669 |
-
_show_papers_by_select, [review_table], [paper_list],
|
| 670 |
-
)
|
| 671 |
-
|
| 672 |
-
submit_review.click(
|
| 673 |
-
_submit_review, [review_table, chatbot],
|
| 674 |
-
[chatbot, download, chart_selector, chart_display,
|
| 675 |
-
review_table, phase_progress],
|
| 676 |
-
)
|
| 677 |
-
|
| 678 |
-
def respond_with_viz(message, chat_history, uploaded_file):
|
| 679 |
-
"""Wrap respond() and update charts + table + progress after each turn."""
|
| 680 |
-
gen = respond(message, chat_history, uploaded_file)
|
| 681 |
-
|
| 682 |
-
# First yield (progress bubble)
|
| 683 |
-
hist, txt, dl = next(gen)
|
| 684 |
-
yield (hist, txt, dl, gr.update(choices=_get_chart_choices()),
|
| 685 |
-
gr.update(), gr.update(), _build_progress())
|
| 686 |
-
|
| 687 |
-
# Second yield (final response + populate table + charts)
|
| 688 |
-
hist, txt, dl = next(gen)
|
| 689 |
-
choices = _get_chart_choices()
|
| 690 |
-
first_chart = (choices and _load_chart(choices[-1])) or gr.update()
|
| 691 |
-
table_data = _load_review_table()
|
| 692 |
-
yield (
|
| 693 |
-
hist, txt, dl,
|
| 694 |
-
gr.update(choices=choices, value=(choices and choices[-1]) or None),
|
| 695 |
-
first_chart,
|
| 696 |
-
gr.update(value=table_data),
|
| 697 |
-
_build_progress(),
|
| 698 |
-
)
|
| 699 |
-
|
| 700 |
-
msg.submit(
|
| 701 |
-
respond_with_viz, [msg, chatbot, upload],
|
| 702 |
-
[chatbot, msg, download, chart_selector, chart_display,
|
| 703 |
-
review_table, phase_progress],
|
| 704 |
-
)
|
| 705 |
-
send.click(
|
| 706 |
-
respond_with_viz, [msg, chatbot, upload],
|
| 707 |
-
[chatbot, msg, download, chart_selector, chart_display,
|
| 708 |
-
review_table, phase_progress],
|
| 709 |
-
)
|
| 710 |
-
# ── end B18: respond_with_viz + event bindings ─────────────
|
| 711 |
-
|
| 712 |
-
|
| 713 |
-
# ── B19: _auto_load_csv() ──────────────────────────────────
|
| 714 |
-
# PURPOSE: Automatically triggers analysis when a CSV file is
|
| 715 |
-
# uploaded. The researcher doesn't need to type anything —
|
| 716 |
-
# just uploading the file starts the pipeline.
|
| 717 |
-
# Sends "Analyze my Scopus CSV" as the initial message.
|
| 718 |
-
# TRIGGERED BY: upload.change event
|
| 719 |
-
# CALLS: B6 (respond) with auto-message
|
| 720 |
-
# OUTPUTS: chatbot, download, chart_selector, chart_display,
|
| 721 |
-
# review_table, phase_progress
|
| 722 |
-
# ───────────────────────────────────────────────────────────
|
| 723 |
-
def _auto_load_csv(uploaded_file, chat_history):
|
| 724 |
-
"""Auto-trigger analysis when CSV is uploaded — no typing needed."""
|
| 725 |
-
gen = respond("Analyze my Scopus CSV", chat_history, uploaded_file)
|
| 726 |
-
|
| 727 |
-
# First yield (progress)
|
| 728 |
-
hist, txt, dl = next(gen)
|
| 729 |
-
yield (hist, dl, gr.update(), gr.update(),
|
| 730 |
-
gr.update(), _build_progress())
|
| 731 |
-
|
| 732 |
-
# Second yield (final + populate everything)
|
| 733 |
-
hist, txt, dl = next(gen)
|
| 734 |
-
choices = _get_chart_choices()
|
| 735 |
-
first_chart = (choices and _load_chart(choices[-1])) or gr.update()
|
| 736 |
-
table_data = _load_review_table()
|
| 737 |
-
yield (
|
| 738 |
-
hist, dl,
|
| 739 |
-
gr.update(choices=choices, value=(choices and choices[-1]) or None),
|
| 740 |
-
first_chart,
|
| 741 |
-
gr.update(value=table_data),
|
| 742 |
-
_build_progress(),
|
| 743 |
-
)
|
| 744 |
-
|
| 745 |
-
upload.change(
|
| 746 |
-
_auto_load_csv, [upload, chatbot],
|
| 747 |
-
[chatbot, download, chart_selector, chart_display,
|
| 748 |
-
review_table, phase_progress],
|
| 749 |
-
)
|
| 750 |
-
# ── end B19: _auto_load_csv ────────────────────────────────
|
| 751 |
-
|
| 752 |
-
|
| 753 |
-
# ╔═══════════════════════════════════════════════════════════════╗
|
| 754 |
-
# ║ SECTION 5 — LAUNCH ║
|
| 755 |
-
# ║ Start the Gradio server. On HuggingFace Spaces this runs ║
|
| 756 |
-
# ║ automatically. Locally, access at http://localhost:7860 ║
|
| 757 |
-
# ╚═══════════════════════════════════════════════════════════════╝
|
| 758 |
-
|
| 759 |
-
|
| 760 |
-
# ── B20: Launch ────────────────────────────────────────────────
|
| 761 |
-
# PURPOSE: Start the web server. ssr_mode=False for compatibility
|
| 762 |
-
# with HuggingFace Spaces free tier (SSR needs more RAM).
|
| 763 |
-
# server_name="0.0.0.0" makes it accessible on the network.
|
| 764 |
-
# NOTE: On Spaces, port 7860 is auto-exposed to the internet.
|
| 765 |
-
# Locally, open http://localhost:7860 in your browser.
|
| 766 |
-
# ────────────────────────────────────────────────────────────────
|
| 767 |
-
print(">>> Launching...")
|
| 768 |
-
demo.launch(server_name="0.0.0.0", server_port=7860, ssr_mode=False)
|
| 769 |
-
# ── end B20: Launch ────────────────────────────────────────────
|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