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 lines195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225887 unmodified lines1113111411151116111711181119112011211122112311241125112611271128112929 unmodified lines115911601161116211631164116511661167116811691170117111721173117411751176308 unmodified lines148514861487148814891490217 unmodified lines170817091710171117121713184 unmodified lines18981899190019011902190387 unmodified lines19911992199319941995199619971318 unmodified lines33163317331833193320332122 unmodified lines33443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375247 unmodified lines362336243625362636273628157 unmodified lines3786378737883789379037913792194 unmodified lines)def _format_turns_html(seg: dict, speaker_map: dict) -> str:turns = seg.get("turns", [])if not turns:return '<p style="color:#94a3b8;font-style:italic">No turns in this segment.</p>'parts = []for t in turns:sp = t.get("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", "")parts.append(f'<div style="display:flex;gap:10px;padding:10px 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'<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'</div>'f'<div style="line-height:1.65;color:#1e293b;font-size:0.95em">{text}</div>'f'</div></div>')return f'<div style="font-family:system-ui,sans-serif">{"".join(parts)}</div>'887 unmodified linesCODING_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),)29 unmodified lines)labels = [_segment_label(s, codings) for s in segs]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),)308 unmodified linesif not turns:raise gr.Error("No transcript loaded β process a file first.")session_id = state.get("session_id", "")n_t = len(turns)if n_t > 600:217 unmodified linesif not state.get("turns"):raise gr.Error("No parsed turns β parse the transcript first.")n = len(sections)session_overview = state.get("_agent0_overview", "")collected = {}184 unmodified linesif not segments:raise gr.Error("No segments produced β check your boundary turn IDs.")state["section_boundaries"][sec["section_id"]] = boundariesstate["section_segments"][sec["section_id"]] = segments87 unmodified linesdef fn_dim_desc(choice: str):return _dim_desc_html(choice or "")# ββ Next section / finish βββββββββββββββββββββββββββββββββββββββββββββββββββββ1318 unmodified lineswith gr.Column(visible=False) as col_coding:coding_progress_comp = gr.HTML()with gr.Row(equal_height=False):# Left: transcriptwith gr.Column(scale=3, elem_classes=["cc-coding-transcript"]):22 unmodified linesinteractive=True,)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.",)comment_box = gr.Textbox(label="Note (optional)", lines=2,placeholder="Ambiguity, competing codesβ¦")with gr.Row():prev_btn = gr.Button("β Previous", size="sm")next_btn = gr.Button("Next β", variant="primary", size="sm")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 linescomment_box, # 8next_section_btn, # 9ssrl_radio, # 10 β SSRL phase tag]# fn_parse_transcript / fn_process_with_source outputs157 unmodified linesoutputs=[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])# Finish section / go to done (now includes ssrl_radio)next_section_btn.click(194 unmodified lines195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253887 unmodified lines11411142114311441145114611471148114911501151115211531154115511561157115829 unmodified lines1188118911901191119211931194119511961197119811991200120112021203120412051206120712081209308 unmodified lines15181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540217 unmodified lines175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787184 unmodified lines1972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200387 unmodified lines2091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621171318 unmodified lines34363437343834393440344134423443344434453446344722 unmodified lines347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505247 unmodified lines3753375437553756375737583759157 unmodified lines3917391839193920392139223923392439253926392739283929393039313932393339343935194 unmodified lines)_TURN_MERGE_GAP_S = 5 # merge same-speaker turns with gap < this many secondsdef _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>'# ββ Group consecutive same-speaker turns with gap < _TURN_MERGE_GAP_S ββββgroups: list[dict] = []for t in turns:sp = t.get("speaker", "?")cur = t.get("start_seconds", 0)if (groupsand groups[-1]["speaker"] == spand (cur - groups[-1]["last_seconds"]) < _TURN_MERGE_GAP_S):groups[-1]["texts"].append(t.get("text", ""))groups[-1]["last_seconds"] = curgroups[-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(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 readabilitysentences = [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: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: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.65em;color:#cbd5e1">{id_label}</span>'f'</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 linesCODING_EMPTY = ("", # 0 coding_progress_compgr.update(choices=[], value=None), # 1 segment_jump"", # 2 turns_html_comp"", # 3 uncertainty_compgr.update(value="", visible=False), # 4 proposal_compgr.update(choices=DIM_CHOICES, value=None), # 5 dim_radio"", # 6 dim_desc_compgr.update(choices=SEC_DIM_CHOICES, value=SEC_NONE), # 7 secondary_dim_drop"", # 8 comment_boxgr.update(visible=False), # 9 next_section_btngr.update(choices=SSRL_CHOICES, value=SSRL_NONE), # 10 ssrl_radiogr.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), # 0gr.update(choices=labels, value=labels[min(cidx, len(segs) - 1)]), # 1_format_turns_html(seg, speaker_map), # 2_uncertainty_html(seg), # 3gr.update(value=_proposal_md(seg), visible=False), # 4gr.update(choices=DIM_CHOICES, value=choice), # 5_dim_desc_html(choice or ""), # 6gr.update(choices=SEC_DIM_CHOICES, value=sec_choice), # 7existing.get("comment", ""), # 8gr.update(visible=all_done), # 9gr.update(choices=SSRL_CHOICES, value=ssrl_choice), # 10gr.update(visible=show_ssrl), # 11 ssrl_col)308 unmodified linesif 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"),)returnsession_id = state.get("session_id", "")n_t = len(turns)if n_t > 600:217 unmodified linesif 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 reviewsec = 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)),)returnn = len(sections)session_overview = state.get("_agent0_overview", "")collected = {}184 unmodified linesif 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 = 2merged: list[dict] = []pending_turns: list = []for seg in segments:seg_turns = seg.get("turns", [])combined = pending_turns + seg_turnspending_turns = []if len(combined) < _MIN_TURNS:pending_turns = combined # carry forward, merge into nextelse:if merged:seg["turns"] = combinedelse:seg["turns"] = combinedmerged.append(seg)# Any remaining tiny tail β append to last segmentif pending_turns and merged:merged[-1]["turns"] = merged[-1].get("turns", []) + pending_turnselif pending_turns:merged = [{"turns": pending_turns, "segment_id": "s_merged","label": "Merged", "section_id": sec["section_id"]}]segments = merged if merged else segmentsif not segments:raise gr.Error("No segments produced after merging short episodes.")state["section_boundaries"][sec["section_id"]] = boundariesstate["section_segments"][sec["section_id"]] = segments87 unmodified linesdef fn_dim_desc(choice: str):"""Return dim description HTML + SSRL visibility update."""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 lineswith 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: transcriptwith gr.Column(scale=3, elem_classes=["cc-coding-transcript"]):22 unmodified linesinteractive=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) β 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("β 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>')next_section_btn = gr.Button("β Finish Section & Continue", variant="secondary", visible=False)247 unmodified linescomment_box, # 8next_section_btn, # 9ssrl_radio, # 10 β SSRL phase tagssrl_col, # 11 β SSRL section visibility (show only for D1-D9)]# fn_parse_transcript / fn_process_with_source outputs157 unmodified linesoutputs=[state] + CODING_OUTPUTS,)reveal_btn.click(fn=fn_reveal, inputs=[state], outputs=[proposal_comp])# dim_radio controls description AND shows/hides SSRL sectiondim_radio.change(fn=fn_dim_desc,inputs=[dim_radio],outputs=[dim_desc_comp, ssrl_col],)# Skip episode β mark as not codeable and advanceskip_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