Lara Monteagudo Tubau commited on
Commit Β·
e605ae7
1
Parent(s): 02a1c61
Refine transcript episode review UI
Browse files693 unmodified lines694695696697698699452 unmodified lines115211531154115511561157115811591160116111621163116411651166116710 unmodified lines117811791180118111821183118411851186118711881189119042 unmodified lines12331234123512361237123812391240124112421243124438 unmodified lines12831284128512861287128839 unmodified lines13281329133013311332133313341335133613371338133913401341134213431344147 unmodified lines14921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251 unmodified line152715281529153015311532660 unmodified lines21932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218243 unmodified lines24622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499693 unmodified linesreturn agent_card + grid + warn_html + instrdef _agent_log_html(logs: list[dict]) -> str:if not logs:return (452 unmodified lines# ββ Confirm sections ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef fn_confirm_sections(labels_text: str, state: dict):sections = state.get("sections", [])if not sections:raise gr.Error("No sections to confirm β process a transcript first.")labels = [l.strip() for l in labels_text.strip().splitlines() if l.strip()]confirmed = [dict(s, label=labels[i] if i < len(labels) else s["label"])for i, s in enumerate(sections)]if len(labels) != len(sections):gr.Warning(f"Label count mismatch ({len(labels)} vs {len(sections)}) β using AI labels for extras.")new_state = dict(state)new_state.update({10 unmodified lines)_persist(new_state)gr.Info(f"{len(confirmed)} sections confirmed. Detect episode boundaries next.")# Navigate to pipeline page; reset subcolumn visibility for clean statereturn (new_state,*_show("pipeline"),_section_cards_html(confirmed, new_state["section_stages"], 0),gr.update(visible=True), # col_run_all_boundariesgr.update(visible=False), # col_boundary_reviewgr.update(visible=False), # col_coding42 unmodified linesstate,f"β³ Running Agent 1a on {n} section(s) (max 3 concurrent)β¦","",gr.update(visible=False), # col_boundary_reviewgr.update(visible=False, value=""), # boundary_display_htmlgr.update(visible=False, value=""), # boundary_ids_box"",_agent_log_html(state.get("agent_logs", [])),_a1a_banner(0, n, "running"),)pstats = PipelineStats(agent_name="Agent 1a β Boundary Detector", n_sections=n)38 unmodified lines"",_agent_log_html(state.get("agent_logs", [])),_a1a_banner(processed, n, "running"),)except Exception as e:39 unmodified linesstatus_final += f"\n\nβ {n_error} section(s) failed β enter boundary turn IDs manually."gr.Info(f"Parallel analysis complete: {n_success}/{n} sections OK.")yield (state,status_final,pipeline_stats_html,gr.update(visible=True), # col_boundary_review β now visiblegr.update(visible=True, value=_episode_table_html(turns, bounds)),gr.update(visible=True, value=ids_txt),f"### Reviewing: {sec['label']} ({sec['section_id']})",_agent_log_html(state["agent_logs"]),_a1a_banner(n_success, n, "done" if n_error == 0 else "error"),)147 unmodified lines_write_coding_file(new_state)_persist(new_state)gr.Info("All sections coded! Download your coding file.")return (new_state,*_show("done"),_section_cards_html(sections, new_state["section_stages"], sec_idx),"",gr.update(visible=False), # col_boundary_reviewgr.update(visible=False), # col_coding)# More sections remain β stay on pipeline page, show next section's boundary reviewnew_state["section_idx"] = next_idxnew_state["coding_idx"] = 0next_sec = sections[next_idx]n = next_sec["end_turn_id"] - next_sec["start_turn_id"] + 1hdr = (f"### Section {next_idx+1} of {len(sections)}: {next_sec['label']}\n"f"*{next_sec.get('summary','')}* Β· "f"turns {next_sec['start_turn_id']}β{next_sec['end_turn_id']} ({n} turns)")_persist(new_state)# Load boundary review for next sectionresult = new_state.get("section_a1a_results", {}).get(next_sec["section_id"], {})bounds = result.get("boundaries", [])turns = _turns_for_section(new_state["turns"], next_sec)ids_txt = ", ".join(str(b["after_turn_id"]) for b in bounds)gr.Info(f"Section {next_idx+1}: {next_sec['label']}")return (new_state,*_show("pipeline"),1 unmodified linehdr,gr.update(visible=True), # col_boundary_reviewgr.update(visible=False), # col_coding)660 unmodified lines# Sub-step B: Per-section boundary reviewwith gr.Column(visible=False) as col_boundary_review:gr.HTML('<div style="background:#f8fafc;border:1px solid #e2e8f0;''border-radius:10px;padding:14px 16px;margin:8px 0">''<div style="font-size:0.75em;font-weight:700;text-transform:uppercase;''letter-spacing:0.08em;color:#94a3b8;margin-bottom:8px">Episode Structure</div>')boundary_display_html = gr.HTML()gr.HTML('</div>')gr.Markdown("**Review boundaries above.** Edit the turn IDs below to adjust. ""Leave empty for a single undivided episode.")with gr.Row():boundary_ids_box = gr.Textbox(label="Boundary turn IDs (comma-separated) β turn after which each new episode begins",placeholder="e.g. 12, 28, 35",lines=1, scale=3,)confirm_boundaries_btn = gr.Button("Confirm & Code β", variant="primary", scale=1)code_status = gr.Markdown()# Sub-step C: Coding canvas243 unmodified linesPROCESS_OUTPUTS = [state, process_status, *ALL_PAGES,sections_display_html, sections_labels_box, process_log, process_btn]# fn_confirm_sections outputs (12 total)CONFIRM_SECTIONS_OUTPUTS = [state, *ALL_PAGES,sections_overview_html,col_run_all_boundaries, # reset to visiblecol_boundary_review, # reset to hiddencol_coding, # reset to hidden]# fn_run_all_boundaries outputs (9 total β includes agent_activity_html)RUN_ALL_OUTPUTS = [state,parallel_status_md,parallel_stats_html,col_boundary_review, # show/hideboundary_display_html,boundary_ids_box,section_header_md,pipeline_log,agent_activity_html,]# fn_confirm_and_code outputs (14 total)CONFIRM_CODE_OUTPUTS = [state, code_status, col_coding] + CODING_OUTPUTS + [pipeline_log]# fn_next_section outputs (12 total)NEXT_SECTION_OUTPUTS = [state, *ALL_PAGES,sections_overview_html,section_header_md,col_boundary_review,col_coding,]# =====================================================================693 unmodified lines694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820452 unmodified lines1273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131910 unmodified lines13301331133213331334133513361337133813391340134113421343134442 unmodified lines138713881389139013911392139313941395139613971398139938 unmodified lines143814391440144114421443144439 unmodified lines1484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508147 unmodified lines16561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951 unmodified line169716981699170017011702170317041705660 unmodified lines2366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411243 unmodified lines2655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697693 unmodified linesreturn agent_card + grid + warn_html + instrdef _episode_dialogue_html(segments: list[dict], boundaries: list[dict],speaker_map: dict) -> str:"""Render each proposed episode with its actual dialogue turns + boundary markers.Design goal: the researcher must be able to READ the transcript beforedeciding whether to accept the AI's proposed boundary positions.Showing only turn-ID tables (the old approach) is opaque.Rules:- Up to 5 turns shown per episode; truncation indicated clearly- Speaker avatars + timestamps match the coding canvas- Boundary markers show signal type, confidence, and AI rationale- Entire view is scrollable so the page does not grow unbounded"""if not segments:return ('<p style="color:#94a3b8;font-style:italic;padding:12px">''No episode data yet.</p>')bmap: dict[int, dict] = {}for b in boundaries:bmap[b.get("after_turn_id", -1)] = bconf_colors = {"high": ("#065f46", "#f0fdf4", "#86efac"),"medium": ("#92400e", "#fffbeb", "#fde68a"),"low": ("#991b1b", "#fef2f2", "#fca5a5"),}parts: list[str] = []for i, seg in enumerate(segments):turns = seg.get("turns", [])ep_id = seg.get("segment_id", f"ep{i+1:02d}")ep_num = ep_id.split("_ep")[-1] if "_ep" in ep_id else str(i + 1)n_turns = len(turns)# Episode header stripparts.append(f'<div style="background:#f1f5f9;border-left:4px solid #4338ca;'f'padding:7px 14px;display:flex;align-items:center;gap:10px;'f'font-family:system-ui,sans-serif">'f'<span style="font-size:0.72em;font-weight:800;color:#4338ca;'f'text-transform:uppercase;letter-spacing:0.08em">Episode {ep_num}</span>'f'<span style="font-size:0.75em;color:#64748b">{n_turns} turns</span>'+ (f'<span style="font-size:0.75em;color:#94a3b8;font-style:italic">'f'{_h(seg.get("rationale","")[:80])}{"β¦" if len(seg.get("rationale",""))>80 else ""}'f'</span>' if seg.get("rationale") else '')+ '</div>')# Show up to 5 turnsshown = turns[:5]for t in shown:sp = t.get("speaker", "?")entry = speaker_map.get(sp, {"color": "#64748b", "bg": "#f8fafc", "initials_bg": "#e2e8f0"})avatar = _speaker_avatar(sp, entry)text = t.get("text", "")if len(text) > 220:text = text[:220] + "β¦"ts = _h(t.get("start_time", ""))parts.append(f'<div style="display:flex;gap:9px;padding:8px 14px;'f'background:white;border-bottom:1px solid #f1f5f9;'f'align-items:flex-start;font-family:system-ui,sans-serif">'f'{avatar}'f'<div style="flex:1;min-width:0">'f'<div style="display:flex;gap:8px;margin-bottom:2px;align-items:baseline">'f'<span style="font-weight:700;font-size:0.82em;color:{entry["color"]}">'f'{_h(sp)}</span>'f'<span style="font-size:0.7em;color:#94a3b8;font-family:monospace">{ts}</span>'f'<span style="font-size:0.68em;color:#cbd5e1;font-family:monospace">'f'#{t.get("turn_id","")}</span>'f'</div>'f'<div style="font-size:0.88em;color:#1e293b;line-height:1.6">{_h(text)}</div>'f'</div></div>')if n_turns > 5:parts.append(f'<div style="padding:5px 14px;font-size:0.75em;color:#94a3b8;'f'background:#fafafa;border-bottom:1px solid #f1f5f9;font-style:italic">'f'β― {n_turns - 5} more turn{"s" if n_turns-5>1 else ""} in this episode</div>')# Boundary marker before the next episodeif i < len(segments) - 1 and turns:last_tid = turns[-1].get("turn_id", -1)b = bmap.get(last_tid, {})sig = b.get("boundary_signal", "boundary")conf = b.get("confidence", "medium")rat = b.get("rationale", "")tc, bg, bc = conf_colors.get(conf, conf_colors["medium"])parts.append(f'<div style="background:{bg};border-top:1px dashed {bc};'f'border-bottom:1px dashed {bc};padding:6px 14px;'f'display:flex;align-items:center;gap:8px;flex-wrap:wrap;'f'font-family:system-ui,sans-serif">'f'<span style="font-size:0.72em;font-weight:800;color:{tc};'f'text-transform:uppercase;letter-spacing:0.06em">β boundary</span>'f'<span style="background:{tc}18;color:{tc};padding:1px 7px;'f'border-radius:4px;font-size:0.75em;font-weight:700">{_h(sig)}</span>'f'<span style="font-size:0.72em;color:{tc};font-weight:600">{conf} confidence</span>'+ (f'<span style="font-size:0.72em;color:#64748b;font-style:italic">'f'β {_h(rat[:100])}{"β¦" if len(rat)>100 else ""}</span>' if rat else '')+ f'<span style="margin-left:auto;font-size:0.68em;color:#94a3b8;'f'font-family:monospace">after #{last_tid}</span>'f'</div>')return (f'<div style="border:1px solid #e2e8f0;border-radius:10px;overflow:hidden;'f'max-height:55vh;overflow-y:auto;font-family:system-ui,sans-serif">'+ "".join(parts)+ '</div>')def _agent_log_html(logs: list[dict]) -> str:if not logs:return (452 unmodified lines# ββ Confirm sections ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef fn_confirm_sections(labels_text: str, state: dict):"""Generator: immediately shows a 'confirming' state (so the user knowstheir click registered), then navigates to the pipeline page."""sections = state.get("sections", [])if not sections:raise gr.Error("No sections to confirm β process a transcript first.")_BUSY_HTML = ('<div style="background:#eff6ff;border:2px solid #93c5fd;border-radius:10px;''padding:14px 18px;font-family:system-ui,sans-serif">''<div style="display:flex;align-items:center;gap:10px">''<span style="font-size:1.2em">β</span>''<strong style="color:#1e3a8a">Saving section labels and loading pipelineβ¦</strong>''</div>''<div style="margin-top:8px;font-size:0.82em;color:#4b5563">''Please wait β this takes only a moment.''</div></div>')# ββ Yield 1: immediate feedback, stay on sections page ββββββββββββββββββββyield (state,*_show("sections"),gr.update(value=_BUSY_HTML), # sections_display_htmlgr.update(interactive=False, value="β³ Savingβ¦"), # confirm_sections_btngr.update(interactive=False), # col_run_all_boundaries (not visible, ignored)gr.update(visible=False), # col_boundary_reviewgr.update(visible=False), # col_coding)# ββ Process (fast: no LLM, just in-memory + disk) βββββββββββββββββββββββββlabels = [l.strip() for l in labels_text.strip().splitlines() if l.strip()]confirmed = [dict(s, label=labels[i] if i < len(labels) else s["label"])for i, s in enumerate(sections)]if len(labels) != len(sections):gr.Warning(f"Label count mismatch ({len(labels)} labels for {len(sections)} sections) β "f"AI labels used for any extras.")new_state = dict(state)new_state.update({10 unmodified lines)_persist(new_state)gr.Info(f"{len(confirmed)} sections confirmed. Click 'Detect Episode Boundaries' to continue.")print(f"[Confirm Sections] {len(confirmed)} sections saved for session {new_state['session_id']}")# ββ Yield 2: navigate to pipeline page ββββββββββββββββββββββββββββββββββββyield (new_state,*_show("pipeline"),gr.update(value=""), # sections_display_html (leaving)gr.update(interactive=True, value="Confirm Sections β"), # reset button for if user navigates backgr.update(visible=True), # col_run_all_boundariesgr.update(visible=False), # col_boundary_reviewgr.update(visible=False), # col_coding42 unmodified linesstate,f"β³ Running Agent 1a on {n} section(s) (max 3 concurrent)β¦","",gr.update(visible=False),gr.update(visible=False, value=""),gr.update(visible=False, value=""),"",_agent_log_html(state.get("agent_logs", [])),_a1a_banner(0, n, "running"),gr.update(value=""), # episode_dialogue_html β clear while processing)pstats = PipelineStats(agent_name="Agent 1a β Boundary Detector", n_sections=n)38 unmodified lines"",_agent_log_html(state.get("agent_logs", [])),_a1a_banner(processed, n, "running"),gr.update(value=""), # episode_dialogue_html β still processing)except Exception as e:39 unmodified linesstatus_final += f"\n\nβ {n_error} section(s) failed β enter boundary turn IDs manually."gr.Info(f"Parallel analysis complete: {n_success}/{n} sections OK.")print(f"[Agent 1a] Complete: {n_success}/{n} OK in {pstats.parallel_wall_s:.1f}s "f"({pstats.speedup:.1f}Γ speedup)")# Build dialogue view for the first section to reviewfirst_result = collected.get(sec["section_id"], {})first_segs = first_result.get("segments", [])ep_dial_html = _episode_dialogue_html(first_segs, bounds, state["speakers"])yield (state,status_final,pipeline_stats_html,gr.update(visible=True),gr.update(visible=True, value=_episode_table_html(turns, bounds)),gr.update(visible=True, value=ids_txt),f"### Reviewing: {sec['label']} ({sec['section_id']})",_agent_log_html(state["agent_logs"]),_a1a_banner(n_success, n, "done" if n_error == 0 else "error"),ep_dial_html, # full dialogue view β researcher reads this before confirming)147 unmodified lines_write_coding_file(new_state)_persist(new_state)gr.Info("All sections coded! Download your coding file.")print(f"[Done] All {len(sections)} sections coded for session {new_state['session_id']}")return (new_state,*_show("done"),_section_cards_html(sections, new_state["section_stages"], sec_idx),"", # section_header_mdgr.update(visible=False), # col_boundary_reviewgr.update(visible=False), # col_codinggr.update(value=""), # boundary_display_htmlgr.update(value=""), # boundary_ids_boxgr.update(value=""), # episode_dialogue_html)# More sections remain β populate boundary review for the next sectionnew_state["section_idx"] = next_idxnew_state["coding_idx"] = 0next_sec = sections[next_idx]n = next_sec["end_turn_id"] - next_sec["start_turn_id"] + 1hdr = (f"### Section {next_idx+1} of {len(sections)}: {next_sec['label']}\n"f"*{next_sec.get('summary','')}* Β· "f"turns {next_sec['start_turn_id']}β{next_sec['end_turn_id']} ({n} turns)")_persist(new_state)result = new_state.get("section_a1a_results", {}).get(next_sec["section_id"], {})bounds = result.get("boundaries", [])next_segs = result.get("segments", [])turns = _turns_for_section(new_state["turns"], next_sec)ids_txt = ", ".join(str(b["after_turn_id"]) for b in bounds)ep_html = _episode_dialogue_html(next_segs, bounds, new_state["speakers"])gr.Info(f"Section {next_idx+1} of {len(sections)}: {next_sec['label']}")print(f"[Next Section] Moving to section {next_idx+1}: {next_sec['label']}")return (new_state,*_show("pipeline"),1 unmodified linehdr,gr.update(visible=True), # col_boundary_reviewgr.update(visible=False), # col_codinggr.update(value=_episode_table_html(turns, bounds)), # boundary_display_htmlgr.update(value=ids_txt), # boundary_ids_boxep_html, # episode_dialogue_html)660 unmodified lines# Sub-step B: Per-section boundary reviewwith gr.Column(visible=False) as col_boundary_review:# Agent 1b will run here β show what principles it usesgr.HTML('<div style="background:#f0fdf4;border:1px solid #86efac;border-radius:10px;''padding:10px 16px;margin-bottom:8px;font-size:0.83em;color:#166534">''<strong>Agent 1b β Dimension Coder</strong> will run after you confirm these boundaries. ''It uses: D1βD9 framework (Meier, Spada & Rummel 2007) Β· ''Tier 1 hard rules (R01βR08) Β· Tier 2 learned rules Β· ''Uncertainty sampling (Settles 2012) to flag hard cases for your review.''</div>')# Episode count summary (compact table)boundary_display_html = gr.HTML()# Full dialogue view β the key UX improvementgr.HTML('<div style="font-size:0.8em;font-weight:700;color:#475569;''text-transform:uppercase;letter-spacing:0.06em;margin:10px 0 6px">''Read the dialogue β verify each episode boundary</div>')episode_dialogue_html = gr.HTML()# Edit controlsgr.HTML('<div style="font-size:0.82em;color:#334155;margin:10px 0 4px;''padding:8px 12px;background:#f8fafc;border:1px solid #e2e8f0;''border-radius:8px">''<strong>Adjust if needed:</strong> enter the turn ID <em>after which</em> ''each new episode begins. Leave empty for a single undivided episode. ''The AI proposal is pre-filled β edit only where you disagree.''</div>')with gr.Row():boundary_ids_box = gr.Textbox(label="Boundary turn IDs (comma-separated)",placeholder="e.g. 12, 28, 35",lines=1, scale=3,)confirm_boundaries_btn = gr.Button("Confirm & Run Agent 1b β",variant="primary", scale=1)code_status = gr.Markdown()# Sub-step C: Coding canvas243 unmodified linesPROCESS_OUTPUTS = [state, process_status, *ALL_PAGES,sections_display_html, sections_labels_box, process_log, process_btn]# fn_confirm_sections outputs (13 total β generator; includes button + sections_display)CONFIRM_SECTIONS_OUTPUTS = [state, *ALL_PAGES,sections_display_html, # show busy state on yield-1; clear on yield-2confirm_sections_btn, # disable on yield-1; re-enable on yield-2col_run_all_boundaries,col_boundary_review,col_coding,]# fn_run_all_boundaries outputs (10 total)RUN_ALL_OUTPUTS = [state,parallel_status_md,parallel_stats_html,col_boundary_review,boundary_display_html,boundary_ids_box,section_header_md,pipeline_log,agent_activity_html,episode_dialogue_html, # NEW β full dialogue view per episode]# fn_confirm_and_code outputs (14 total)CONFIRM_CODE_OUTPUTS = [state, code_status, col_coding] + CODING_OUTPUTS + [pipeline_log]# fn_next_section outputs (15 total β includes boundary + dialogue update for next section)NEXT_SECTION_OUTPUTS = [state, *ALL_PAGES,sections_overview_html,section_header_md,col_boundary_review,col_coding,boundary_display_html, # re-populate for next sectionboundary_ids_box, # re-populate for next sectionepisode_dialogue_html, # re-populate for next section]# =====================================================================
app.py+236-38