Lara Monteagudo Tubau commited on
Commit Β·
6dc4dd3
1
Parent(s): f5ce139
UX: turn merging, conditional SSRL, skip button, caching, min-episode guard
Browse files194 unmodified lines195196197198199200201202203204202205206207208204209210211212213214215216217218219220221222223224225226227228229230231207208209210232233234235236237238239240212241242243244216217218245246247220248249222250251252253887 unmodified lines1141114211431116111711181119112011211122112311241125112611441145114611471148114911501151115211531154115511561157115829 unmodified lines118811891190119111921193119411631164116511661167116811691170117111721173119511961197119811991200120112021203120412051206120712081209308 unmodified lines15181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540217 unmodified lines175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787184 unmodified lines1972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200387 unmodified lines20912092209320941994209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621171318 unmodified lines34363437343834393440344134423443344434453446344722 unmodified lines347034713472347334743347334833493350335133523353335433553356335733583359336034753476347734783479348034813482348334843485348634873488348934903491349234933494336734953496349734983499350035013502337033713372350335043505247 unmodified lines3753375437553756375737583759157 unmodified lines39173918391937893920392139223923392439253926392739283929393039313932393339343935194 unmodified lines )
_TURN_MERGE_GAP_S = 5 # merge same-speaker turns with gap < this many seconds
def _format_turns_html(seg: dict, speaker_map: dict) -> str: """Render episode turns, grouping consecutive same-speaker turns with small gaps.""" turns = seg.get("turns", []) if not turns: return '<p style="color:#94a3b8;font-style:italic">No turns in this segment.</p>' parts = []
# ββ Group consecutive same-speaker turns with gap < _TURN_MERGE_GAP_S ββββ groups: list[dict] = [] for t in turns: sp = t.get("speaker", "?") sp = t.get("speaker", "?") cur = t.get("start_seconds", 0) if (groups and groups[-1]["speaker"] == sp and (cur - groups[-1]["last_seconds"]) < _TURN_MERGE_GAP_S): groups[-1]["texts"].append(t.get("text", "")) groups[-1]["last_seconds"] = cur groups[-1]["last_id"] = t.get("turn_id", "") else: groups.append({ "speaker": sp, "texts": [t.get("text", "")], "start_time": t.get("start_time", ""), "last_seconds": cur, "first_id": t.get("turn_id", ""), "last_id": t.get("turn_id", ""), })
parts = [] for g in groups: sp = g["speaker"] entry = speaker_map.get(sp, {"color": "#64748b", "bg": "#f8fafc", "initials_bg": "#e2e8f0", "emoji": "β"}) avatar = _speaker_avatar(sp, entry) ts = _h(t.get("start_time", "")) text = _h(t.get("text", "")) turn_id = t.get("turn_id", "") avatar = _speaker_avatar(sp, entry) ts = _h(g["start_time"]) merged = " ".join(g["texts"]) fid, lid = g["first_id"], g["last_id"] id_label = f"#{fid}β#{lid}" if fid != lid else f"#{fid}" # Wrap separate sentences for readability sentences = [s.strip() for s in merged.replace("β¦", "β¦ ").split(" ") if s.strip()] body = " ".join(f'<span style="opacity:0.9">{_h(s)}</span>' for s in sentences) or _h(merged) parts.append( f'<div style="display:flex;gap:10px;padding:10px 0;' f'<div style="display:flex;gap:10px;padding:11px 0;' f'border-bottom:1px solid #f1f5f9;align-items:flex-start">' f'{avatar}' f'<div style="flex:1;min-width:0">' f'<div style="display:flex;align-items:baseline;gap:8px;margin-bottom:3px">' f'<span style="font-weight:700;color:{entry["color"]};font-size:0.85em">' f'{_h(sp)}</span>' f'<div style="display:flex;align-items:baseline;gap:8px;margin-bottom:4px">' f'<span style="font-weight:700;color:{entry["color"]};font-size:0.85em">{_h(sp)}</span>' f'<span style="font-family:monospace;font-size:0.72em;color:#94a3b8">{ts}</span>' f'<span style="font-family:monospace;font-size:0.68em;color:#cbd5e1">#{turn_id}</span>' f'<span style="font-family:monospace;font-size:0.65em;color:#cbd5e1">{id_label}</span>' f'</div>' f'<div style="line-height:1.65;color:#1e293b;font-size:0.95em">{text}</div>' f'<div style="line-height:1.7;color:#1e293b;font-size:0.95em">{body}</div>' f'</div></div>' ) return f'<div style="font-family:system-ui,sans-serif">{"".join(parts)}</div>'887 unmodified lines
CODING_EMPTY = ( "", gr.update(choices=[], value=None), "", "", gr.update(value="", visible=False), gr.update(choices=DIM_CHOICES, value=None), "", gr.update(choices=SEC_DIM_CHOICES, value=SEC_NONE), "", gr.update(visible=False), gr.update(choices=SSRL_CHOICES, value=SSRL_NONE), "", # 0 coding_progress_comp gr.update(choices=[], value=None), # 1 segment_jump "", # 2 turns_html_comp "", # 3 uncertainty_comp gr.update(value="", visible=False), # 4 proposal_comp gr.update(choices=DIM_CHOICES, value=None), # 5 dim_radio "", # 6 dim_desc_comp gr.update(choices=SEC_DIM_CHOICES, value=SEC_NONE), # 7 secondary_dim_drop "", # 8 comment_box gr.update(visible=False), # 9 next_section_btn gr.update(choices=SSRL_CHOICES, value=SSRL_NONE), # 10 ssrl_radio gr.update(visible=False), # 11 ssrl_col β hidden when no D1-D9)
29 unmodified lines ) labels = [_segment_label(s, codings) for s in segs]
_skip_prefixes = ("NS", "NA", "None", "") show_ssrl = bool(choice) and not any(choice.startswith(p) for p in _skip_prefixes)
return ( _coding_progress_html(state), gr.update(choices=labels, value=labels[min(cidx, len(segs) - 1)]), _format_turns_html(seg, speaker_map), _uncertainty_html(seg), gr.update(value=_proposal_md(seg), visible=False), gr.update(choices=DIM_CHOICES, value=choice), _dim_desc_html(choice or ""), gr.update(choices=SEC_DIM_CHOICES, value=sec_choice), existing.get("comment", ""), gr.update(visible=all_done), gr.update(choices=SSRL_CHOICES, value=ssrl_choice), _coding_progress_html(state), # 0 gr.update(choices=labels, value=labels[min(cidx, len(segs) - 1)]), # 1 _format_turns_html(seg, speaker_map), # 2 _uncertainty_html(seg), # 3 gr.update(value=_proposal_md(seg), visible=False), # 4 gr.update(choices=DIM_CHOICES, value=choice), # 5 _dim_desc_html(choice or ""), # 6 gr.update(choices=SEC_DIM_CHOICES, value=sec_choice), # 7 existing.get("comment", ""), # 8 gr.update(visible=all_done), # 9 gr.update(choices=SSRL_CHOICES, value=ssrl_choice), # 10 gr.update(visible=show_ssrl), # 11 ssrl_col )
308 unmodified lines if not turns: raise gr.Error("No transcript loaded β process a file first.")
# ββ Sections cache: if Agent 0 already ran, skip LLM and go to sections β existing_sections = state.get("sections", []) if existing_sections: n_t = len(turns) speakers = list(state.get("speakers", {}).keys()) sec_html = _sections_html(existing_sections, n_t, 0, len(speakers), all_turns=turns) labels_txt = "\n".join(f"{s['section_id']}: {s['label']}" for s in existing_sections) gr.Info(f"Using cached sections ({len(existing_sections)} detected). Re-run via Back if you need fresh detection.") yield ( state, _pipeline_bar_html(state), sec_html, labels_txt, *_show("sections"), ) return
session_id = state.get("session_id", "") n_t = len(turns) if n_t > 600:217 unmodified lines if not state.get("turns"): raise gr.Error("No parsed turns β parse the transcript first.")
# ββ Cache check: if all sections already have boundaries, skip LLM βββββββ existing = state.get("section_a1a_results", {}) if existing and all(s["section_id"] in existing for s in sections): collected = {sid: r for sid, r in existing.items()} # Jump straight to showing first section review sec = sections[0] turns = _turns_for_section(state["turns"], sec) result = collected.get(sec["section_id"], {}) bounds = result.get("boundaries", []) ids_txt = ", ".join(str(b["after_turn_id"]) for b in bounds) yield ( state, "β Episode boundaries already detected β showing cached results.", "", gr.update(visible=False), gr.update(visible=True, value=_episode_table_html(turns, bounds)), gr.update(visible=True, value=ids_txt), _section_header_md(sec), _agent_log_html(state.get("agent_logs", [])), "", gr.update(value=_episode_dialogue_html(turns, bounds)), ) return
n = len(sections) session_overview = state.get("_agent0_overview", "") collected = {}184 unmodified lines if not segments: raise gr.Error("No segments produced β check your boundary turn IDs.")
# ββ Min-episode guard: merge segments with < 2 turns into the next one βββ _MIN_TURNS = 2 merged: list[dict] = [] pending_turns: list = [] for seg in segments: seg_turns = seg.get("turns", []) combined = pending_turns + seg_turns pending_turns = [] if len(combined) < _MIN_TURNS: pending_turns = combined # carry forward, merge into next else: if merged: seg["turns"] = combined else: seg["turns"] = combined merged.append(seg) # Any remaining tiny tail β append to last segment if pending_turns and merged: merged[-1]["turns"] = merged[-1].get("turns", []) + pending_turns elif pending_turns: merged = [{"turns": pending_turns, "segment_id": "s_merged", "label": "Merged", "section_id": sec["section_id"]}] segments = merged if merged else segments if not segments: raise gr.Error("No segments produced after merging short episodes.")
state["section_boundaries"][sec["section_id"]] = boundaries state["section_segments"][sec["section_id"]] = segments
87 unmodified lines
def fn_dim_desc(choice: str): """Return dim description HTML + SSRL visibility update.""" return _dim_desc_html(choice or "") desc = _dim_desc_html(choice or "") # Show SSRL only when a substantive D1-D9 code is selected (not NS / NA / None) _skip_prefixes = ("NS", "NA", "None", "") show_ssrl = bool(choice) and not any(choice.startswith(p) for p in _skip_prefixes) return desc, gr.update(visible=show_ssrl)
def fn_skip_episode(state: dict): """Mark current episode as non-codeable and advance to next.""" idx = state.get("current_index", 0) segs = state.get("segments", []) if 0 <= idx < len(segs): sid = segs[idx].get("segment_id") state.setdefault("codings", {})[sid] = { "dimension_id": "SKIP", "secondary_dim": None, "ssrl_phase": None, "comment": "Not codeable β skipped", } return fn_navigate(+1, "SKIP", SEC_NONE, "", SSRL_NONE, state)
# ββ Next section / finish βββββββββββββββββββββββββββββββββββββββββββββββββββββ1318 unmodified lines with gr.Column(visible=False) as col_coding: coding_progress_comp = gr.HTML()
# ββ Jump to segment β at the TOP before the transcript ββββββββββ segment_jump = gr.Dropdown( label="Jump to segment", choices=[], value=None, interactive=True, info="Quickly navigate to any episode by ID." )
with gr.Row(equal_height=False): # Left: transcript with gr.Column(scale=3, elem_classes=["cc-coding-transcript"]):22 unmodified lines interactive=True, )
# ββ SSRL section β hidden until a D1-D9 code is chosen ββ with gr.Column(visible=False) as ssrl_col: gr.HTML( '<div style="border-top:1px solid var(--cc-border);' 'margin:12px 0 8px;padding-top:10px">' '<div style="font-weight:700;font-size:0.85em;color:var(--cc-ink);' 'text-transform:uppercase;letter-spacing:.05em;margin-bottom:4px">SSRL Phase</div>' '<div style="font-size:0.72em;color:var(--cc-muted)">Iiskala (2011) Β· ' 'JΓ€rvelΓ€ & Hadwin (2013)</div></div>' ) ssrl_radio = gr.Radio( choices=SSRL_CHOICES, label="Metacognitive phase", value=SSRL_NONE, info="Tag the dominant SSRL phase if metacognition is present.", ) gr.HTML( '<div style="border-top:1px solid var(--cc-border);' 'margin:12px 0 8px;padding-top:10px">' '<div style="font-weight:700;font-size:0.85em;color:var(--cc-ink);' 'text-transform:uppercase;letter-spacing:.05em;margin-bottom:4px">SSRL Phase</div>' '<div style="font-size:0.72em;color:var(--cc-muted)">Iiskala (2011) Β· ' 'JΓ€rvelΓ€ & Hadwin (2013) β only shown when a D1-D9 code is selected</div></div>' ) ssrl_radio = gr.Radio( choices=SSRL_CHOICES, label="Metacognitive phase", value=SSRL_NONE, info="Tag the dominant SSRL phase if metacognition is present.", )
comment_box = gr.Textbox( label="Note (optional)", lines=2, placeholder="Ambiguity, competing codesβ¦" ) with gr.Row(): prev_btn = gr.Button("β Previous", size="sm") prev_btn = gr.Button("β Prev", size="sm") next_btn = gr.Button("Next β", variant="primary", size="sm") skip_btn = gr.Button("β Skip", size="sm", variant="secondary") gr.HTML( '<p style="font-size:0.72em;color:#94a3b8;margin-top:4px;line-height:1.4">' 'Skip marks the episode as <em>not codeable</em> (small talk, off-topic) and moves on.</p>' )
segment_jump = gr.Dropdown( label="Jump to segment", choices=[], value=None, interactive=True ) next_section_btn = gr.Button( "β Finish Section & Continue", variant="secondary", visible=False )247 unmodified lines comment_box, # 8 next_section_btn, # 9 ssrl_radio, # 10 β SSRL phase tag ssrl_col, # 11 β SSRL section visibility (show only for D1-D9) ]
# fn_parse_transcript / fn_process_with_source outputs157 unmodified lines outputs=[state] + CODING_OUTPUTS, ) reveal_btn.click(fn=fn_reveal, inputs=[state], outputs=[proposal_comp]) dim_radio.change(fn=fn_dim_desc, inputs=[dim_radio], outputs=[dim_desc_comp]) # dim_radio controls description AND shows/hides SSRL section dim_radio.change( fn=fn_dim_desc, inputs=[dim_radio], outputs=[dim_desc_comp, ssrl_col], )
# Skip episode β mark as not codeable and advance skip_btn.click( fn=fn_skip_episode, inputs=[state], outputs=[state] + CODING_OUTPUTS, )
# Finish section / go to done (now includes ssrl_radio) next_section_btn.click(app.py+197-54