Spaces:
Sleeping
fix: Or_6 feedback — consent questions, unrecorded verdicts, feedback types
Browse filesFindings from Alex's first reviewed test case (review/Or_6.txt).
Fixed:
- A question about the spiritual care team was scored as a refusal.
"I don't know, who are they" contains "don't"/"not", so _check_consent's
negative keyword scan matched first, _process_consent_declined closed the
topic and moved the session back to GREEN while the patient was still in an
unresolved RED. _is_consent_question now runs before _check_consent, explains
what the chaplains do, re-asks for consent and stays in AWAITING_CONSENT.
- Saving from the always-visible verification panel never set is_correct, so a
fully reviewed session exported as "0 reviewed". Picking a classification is
now the verdict itself (PROVIDER_SUMMARY step excluded, its radio is hidden).
The panel also stays open after Save so a note left on an exchange whose
classification was correct doesn't disappear.
Added:
- "Type of feedback" multi-select (wrong classification / tone / missing
information / conversation flow) in both interfaces, exported as a
feedback_types column with stable codes. An exchange can carry more than one,
which splits reviewer notes into classifier-prompt vs response-prompt fixes
without re-reading free text.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Files changed (4)
421 unmodified lines4224234244254264274284294304314324334344354364374384394404411 unmodified line443444445446447448449450451452421 unmodified linesdef _handle_consent_response(self, message: str) -> str:"""Handle patient's response to consent request.If patient agrees → generate referralIf patient declines → return to medical dialog without referralRequirement: Or_review.md section 4.A.3"""logger.info(f"Handling consent response: {message[:50]}...")# Detect languagepatient_language = self._detect_language(message)# Check if patient consentsconsent_given = self._check_consent(message)if consent_given:logger.info("Patient consented to spiritual care referral")return self._process_consent_accepted(patient_language)1 unmodified linelogger.info("Patient declined spiritual care referral")return self._process_consent_declined(patient_language)def _check_consent(self, message: str) -> bool:"""Check if patient's response indicates consent.Returns True if patient agrees, False if declines or unclear."""message_lower = message.lower()421 unmodified lines4224234244254264274284294304314324334344354364374384394404414424434444454464474481 unmodified line450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506421 unmodified linesdef _handle_consent_response(self, message: str) -> str:"""Handle patient's response to consent request.If patient asks about the service → explain it and keep awaiting consentIf patient agrees → generate referralIf patient declines → return to medical dialog without referralRequirement: Or_review.md section 4.A.3"""logger.info(f"Handling consent response: {message[:50]}...")# Detect languagepatient_language = self._detect_language(message)# A question about the spiritual care team is not a refusal - answer it and# stay in AWAITING_CONSENT so the patient can still decide (Or_6.txt).if self._is_consent_question(message):logger.info("Patient asked about the spiritual care team - explaining service")return self._explain_spiritual_care_service(patient_language)# Check if patient consentsconsent_given = self._check_consent(message)if consent_given:logger.info("Patient consented to spiritual care referral")return self._process_consent_accepted(patient_language)1 unmodified linelogger.info("Patient declined spiritual care referral")return self._process_consent_declined(patient_language)def _is_consent_question(self, message: str) -> bool:"""Check whether the patient is asking about the spiritual care team ratherthan accepting or refusing the referral.This must be checked before _check_consent: phrases like "I don't know,who are they" contain negative keywords ("don't", "not") and wouldotherwise be scored as a refusal."""message_lower = message.lower()question_en = ["who are they", "who is", "who are", "what is", "what are","what do they", "what would", "what does", "what's that","how does", "how do they", "how would", "tell me more","more information", "more about", "what kind of","i don't know", "i dont know", "not sure", "like what"]question_uk = ["хто це", "хто вони", "хто такі", "що це", "що вони","що саме", "як це", "як вони", "розкажіть більше","більше інформації", "не знаю", "не впевнен", "що це означає"]return any(q in message_lower for q in question_en + question_uk)def _explain_spiritual_care_service(self, language: str) -> str:"""Explain what the spiritual care team does and re-ask for consent.The session stays in AWAITING_CONSENT, so the patient's next message isrouted back through _handle_consent_response."""if language == "Ukrainian":return """Звісно, поясню. Команда духовної підтримки — це капелани нашої лікарні. Вони не є медичним персоналом і не змінюють ваше лікування.Вони просто вислухають вас і побудуть поруч — можна говорити про те, що вас турбує, про сенс, страх чи втрату. Це конфіденційно, безкоштовно, не залежить від вашої релігії чи її відсутності, і ви можете припинити будь-якої миті.Якщо ви погодитесь, я передам їм ваше ім'я та контакт, і хтось із них зв'яжеться з вами. Чи хотіли б ви, щоб я це зробив?"""else:return """Of course, let me explain. The spiritual care team are the chaplains here at the hospital. They are not medical staff, and they don't change anything about your treatment.They're simply there to listen and sit with you — you can talk about whatever is weighing on you, about meaning, fear, or loss. It's confidential, there's no cost, it doesn't depend on your religion or having one, and you can stop at any point.If you'd like, I can share your name and contact details so someone from the team can reach out to you. Would you like me to do that?"""def _check_consent(self, message: str) -> bool:"""Check if patient's response indicates consent.Returns True if patient agrees, False if declines or unclear."""message_lower = message.lower()
259 unmodified lines260261262263264265399 unmodified lines66566666766866967022 unmodified lines69369469569669769810 unmodified lines7097107117127137147157167177187197204 unmodified lines725726727728729730731732733734735736737738739740741742743259 unmodified lineslabel="Correct Classification",interactive=True)conv_incorrect_comment = gr.Textbox(label="Comment (why incorrect / what to fix)",placeholder="Add a short note for this exchange...",399 unmodified linesconv_verify_status, conv_verify_exchange, conv_position, conv_stats,# Show the classification/comment panel for the first exchange tooconv_incorrect_comment_row, conv_incorrect_comment, conv_correct_classification,])22 unmodified linesconv_incorrect_comment_row,conv_incorrect_comment,conv_correct_classification,])10 unmodified linesconv_incorrect_comment_row,conv_incorrect_comment,conv_correct_classification,])conv_save_comment_btn.click(verification_handlers._save_incorrect_comment,inputs=[conv_verify_records, conv_verify_index, conv_incorrect_comment, conv_correct_classification],outputs=[conv_verify_records,conv_verify_index,4 unmodified linesconv_incorrect_comment_row,conv_incorrect_comment,conv_correct_classification,])conv_prev_btn.click(lambda records, idx: verification_handlers._nav_conv(records, idx, -1),inputs=[conv_verify_records, conv_verify_index],outputs=[conv_verify_index, conv_verify_exchange, conv_position, conv_stats, conv_incorrect_comment_row, conv_incorrect_comment, conv_correct_classification])conv_next_btn.click(lambda records, idx: verification_handlers._nav_conv(records, idx, 1),inputs=[conv_verify_records, conv_verify_index],outputs=[conv_verify_index, conv_verify_exchange, conv_position, conv_stats, conv_incorrect_comment_row, conv_incorrect_comment, conv_correct_classification])259 unmodified lines260261262263264265266267268269270399 unmodified lines67067167267367467567622 unmodified lines69970070170270370470510 unmodified lines7167177187197207217227237247257267277284 unmodified lines733734735736737738739740741742743744745746747748749750751752259 unmodified lineslabel="Correct Classification",interactive=True)conv_feedback_type = gr.CheckboxGroup(choices=verification_handlers._FEEDBACK_TYPE_CHOICES,label="Type of feedback (select all that apply)",interactive=True,)conv_incorrect_comment = gr.Textbox(label="Comment (why incorrect / what to fix)",placeholder="Add a short note for this exchange...",399 unmodified linesconv_verify_status, conv_verify_exchange, conv_position, conv_stats,# Show the classification/comment panel for the first exchange tooconv_incorrect_comment_row, conv_incorrect_comment, conv_correct_classification,conv_feedback_type,])22 unmodified linesconv_incorrect_comment_row,conv_incorrect_comment,conv_correct_classification,conv_feedback_type,])10 unmodified linesconv_incorrect_comment_row,conv_incorrect_comment,conv_correct_classification,conv_feedback_type,])conv_save_comment_btn.click(verification_handlers._save_incorrect_comment,inputs=[conv_verify_records, conv_verify_index, conv_incorrect_comment, conv_correct_classification, conv_feedback_type],outputs=[conv_verify_records,conv_verify_index,4 unmodified linesconv_incorrect_comment_row,conv_incorrect_comment,conv_correct_classification,conv_feedback_type,])conv_prev_btn.click(lambda records, idx: verification_handlers._nav_conv(records, idx, -1),inputs=[conv_verify_records, conv_verify_index],outputs=[conv_verify_index, conv_verify_exchange, conv_position, conv_stats, conv_incorrect_comment_row, conv_incorrect_comment, conv_correct_classification, conv_feedback_type])conv_next_btn.click(lambda records, idx: verification_handlers._nav_conv(records, idx, 1),inputs=[conv_verify_records, conv_verify_index],outputs=[conv_verify_index, conv_verify_exchange, conv_position, conv_stats, conv_incorrect_comment_row, conv_incorrect_comment, conv_correct_classification, conv_feedback_type])
176 unmodified lines177178179180181182357 unmodified lines54054154254354454516 unmodified lines56256356456556656710 unmodified lines5785795805815825835845855865875885894 unmodified lines594595596597598599600601602603604605606607608609610611612176 unmodified lineslabel="Select Correct Classification",interactive=True)conv_incorrect_comment = gr.Textbox(label="Comment (why incorrect / what to fix)",placeholder="Add your feedback here...",357 unmodified linesconv_verify_status, conv_verify_exchange, conv_position, conv_stats,# Show the classification/comment panel for the first exchange tooconv_incorrect_comment_row, conv_incorrect_comment, conv_correct_classification,])16 unmodified linesconv_incorrect_comment_row,conv_incorrect_comment,conv_correct_classification,])10 unmodified linesconv_incorrect_comment_row,conv_incorrect_comment,conv_correct_classification,])conv_save_comment_btn.click(verification_handlers._save_incorrect_comment,inputs=[conv_verify_records, conv_verify_index, conv_incorrect_comment, conv_correct_classification],outputs=[conv_verify_records,conv_verify_index,4 unmodified linesconv_incorrect_comment_row,conv_incorrect_comment,conv_correct_classification,])conv_prev_btn.click(lambda records, idx: verification_handlers._nav_conv(records, idx, -1),inputs=[conv_verify_records, conv_verify_index],outputs=[conv_verify_index, conv_verify_exchange, conv_position, conv_stats, conv_incorrect_comment_row, conv_incorrect_comment, conv_correct_classification])conv_next_btn.click(lambda records, idx: verification_handlers._nav_conv(records, idx, 1),inputs=[conv_verify_records, conv_verify_index],outputs=[conv_verify_index, conv_verify_exchange, conv_position, conv_stats, conv_incorrect_comment_row, conv_incorrect_comment, conv_correct_classification])# Prompt editing events176 unmodified lines177178179180181182183184185186187357 unmodified lines54554654754854955055116 unmodified lines56856957057157257357410 unmodified lines5855865875885895905915925935945955965974 unmodified lines602603604605606607608609610611612613614615616617618619620621176 unmodified lineslabel="Select Correct Classification",interactive=True)conv_feedback_type = gr.CheckboxGroup(choices=verification_handlers._FEEDBACK_TYPE_CHOICES,label="Type of feedback (select all that apply)",interactive=True,)conv_incorrect_comment = gr.Textbox(label="Comment (why incorrect / what to fix)",placeholder="Add your feedback here...",357 unmodified linesconv_verify_status, conv_verify_exchange, conv_position, conv_stats,# Show the classification/comment panel for the first exchange tooconv_incorrect_comment_row, conv_incorrect_comment, conv_correct_classification,conv_feedback_type,])16 unmodified linesconv_incorrect_comment_row,conv_incorrect_comment,conv_correct_classification,conv_feedback_type,])10 unmodified linesconv_incorrect_comment_row,conv_incorrect_comment,conv_correct_classification,conv_feedback_type,])conv_save_comment_btn.click(verification_handlers._save_incorrect_comment,inputs=[conv_verify_records, conv_verify_index, conv_incorrect_comment, conv_correct_classification, conv_feedback_type],outputs=[conv_verify_records,conv_verify_index,4 unmodified linesconv_incorrect_comment_row,conv_incorrect_comment,conv_correct_classification,conv_feedback_type,])conv_prev_btn.click(lambda records, idx: verification_handlers._nav_conv(records, idx, -1),inputs=[conv_verify_records, conv_verify_index],outputs=[conv_verify_index, conv_verify_exchange, conv_position, conv_stats, conv_incorrect_comment_row, conv_incorrect_comment, conv_correct_classification, conv_feedback_type])conv_next_btn.click(lambda records, idx: verification_handlers._nav_conv(records, idx, 1),inputs=[conv_verify_records, conv_verify_index],outputs=[conv_verify_index, conv_verify_exchange, conv_position, conv_stats, conv_incorrect_comment_row, conv_incorrect_comment, conv_correct_classification, conv_feedback_type])# Prompt editing events
923 unmodified lines92492592692792892921 unmodified lines9519529539549559564 unmodified lines96196296396496596696796896934 unmodified lines1004100510061007100810091 unmodified line1011101210131014101510161017101810193 unmodified lines10231024102510261027102812 unmodified lines104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781 unmodified line108010811082108310841085108610871088108910903 unmodified lines109410951096109710981099110011011102110311048 unmodified lines11131114111511161117111811191120112160 unmodified lines11821183118411851186118716 unmodified lines1204120512061207120812092 unmodified lines1212121312141215121612171218121912201221923 unmodified lines"original_confidence","is_correct","correct_classification","verifier_notes","user_message","assistant_response",21 unmodified lines"original_confidence": r.get("original_confidence"),"is_correct": r.get("is_correct"),"correct_classification": r.get("correct_classification") or "","verifier_notes": r.get("verifier_notes") or "","user_message": r.get("user_message"),"assistant_response": r.get("assistant_response"),4 unmodified linesdef _generate_conv_verification(session: SimplifiedSessionData):if session is None or not hasattr(session.app_instance, "conversation_logger"):return None, [], 0, "❌ No session/conversation found", "", "", "", gr.update(visible=False), "", gr.update(value=None)if not session.app_instance.conversation_logger.entries:return None, [], 0, "⚠️ No exchanges to verify yet", "", "", "", gr.update(visible=False), "", gr.update(value=None)manager = ConversationVerificationManager()vs = manager.create_verification_session(session.app_instance.conversation_logger, "Medical Professional")34 unmodified lines"correct_classification": r.correct_classification,"correction_reason": r.correction_reason,"verifier_notes": r.verifier_notes,"provider_summary": provider_summary_text if r.original_classification.upper() == "RED" else "",}for r in vs.verification_records1 unmodified linehtml, pos, stats = _render_conv_exchange(records_as_dicts, 0)row_upd, note_val = _comment_ui_state(records_as_dicts, 0)radio_upd = _classification_update(records_as_dicts, 0)return (meta, records_as_dicts, 0, f"✅ Generated session `{vs.session_id}`",html, pos, stats, row_upd, note_val, radio_upd,)# Display text for each classification flag (shared by the verification handlers).3 unmodified lines"RED": "🔴 Should be RED - Spiritual distress",}def _classification_update(records: list, idx: int):"""Build the gr.update for the 'Correct Classification' Radio.12 unmodified linesdef _mark_conv_correct(records: list, idx: int):if not records:return records, idx, "", "", "", "", gr.update(visible=False), "", gr.update(value=None)idx = max(0, min(idx, len(records) - 1))if isinstance(records[idx], dict):records[idx]["is_correct"] = True# clear comment and correct_classification when marked correct (avoid stale data)records[idx]["verifier_notes"] = ""records[idx]["correct_classification"] = Nonehtml, pos, stats = _render_conv_exchange(records, idx)row_upd, note_val = _comment_ui_state(records, idx)return records, idx, "✅ Marked correct", html, pos, stats, row_upd, note_val, _classification_update(records, idx)def _mark_conv_incorrect(records: list, idx: int):if not records:return records, idx, "", "", "", "", gr.update(visible=False), "", gr.update(value=None)idx = max(0, min(idx, len(records) - 1))if isinstance(records[idx], dict):records[idx]["is_correct"] = Falsehtml, pos, stats = _render_conv_exchange(records, idx)row_upd, note_val = _comment_ui_state(records, idx)return records, idx, "❌ Marked incorrect", html, pos, stats, row_upd, note_val, _classification_update(records, idx)def _show_incorrect_comment_ui(records: list, idx: int):"""Mark incorrect and open the comment row, pre-filling any existing note."""records, idx, status, html, pos, stats, _row, note, existing_classification = _mark_conv_incorrect(records, idx)return records, idx, status, html, pos, stats, gr.update(visible=True), note, existing_classificationdef _save_incorrect_comment(records: list, idx: int, note: str, correct_classification: str):if not records:return records, idx, "", "", "", "", gr.update(visible=False), "", gr.update(value=None)idx = max(0, min(idx, len(records) - 1))if isinstance(records[idx], dict):records[idx]["verifier_notes"] = (note or "").strip()# Map display text to classification codeclassification_map = {"🟢 Should be GREEN - No distress": "GREEN",1 unmodified line"🔴 Should be RED - Spiritual distress": "RED"}if correct_classification and correct_classification in classification_map:records[idx]["correct_classification"] = classification_map[correct_classification]html, pos, stats = _render_conv_exchange(records, idx)row_upd, note_val = _comment_ui_state(records, idx)# keep row visible after save (since still incorrect)return records, idx, "💾 Comment saved", html, pos, stats, row_upd, note_val, _classification_update(records, idx)def _download_reviewed_json(meta: dict, records: list):return _export_conv_records_to_json(meta, records)3 unmodified linesdef _nav_conv(records: list, idx: int, delta: int):if not records:return idx, "", "", "", gr.update(visible=False), "", gr.update(value=None)idx = max(0, min(idx + delta, len(records) - 1))html, pos, stats = _render_conv_exchange(records, idx)row_upd, note_val = _comment_ui_state(records, idx)return idx, html, pos, stats, row_upd, note_val, _classification_update(records, idx)# ============================================================================8 unmodified lines"Provider Summary to be the final exchange presented in that tab""""if session is None or not hasattr(session.app_instance, "conversation_logger"):return None, [], 0, "❌ No session/conversation found", "", "", "", gr.update(visible=False), "", gr.update(value=None)if not session.app_instance.conversation_logger.entries:return None, [], 0, "⚠️ No exchanges to verify yet", "", "", "", gr.update(visible=False), "", gr.update(value=None)manager = ConversationVerificationManager()vs = manager.create_verification_session(session.app_instance.conversation_logger, "Medical Professional")60 unmodified lines"correct_classification": r.correct_classification,"correction_reason": r.correction_reason,"verifier_notes": r.verifier_notes,"provider_summary": "", # Not shown in regular exchanges}for r in vs.verification_records16 unmodified lines"correct_classification": None,"correction_reason": "","verifier_notes": "","provider_summary": provider_summary_text,"provider_summary_html": provider_summary_html,}2 unmodified lineshtml, pos, stats = _render_conv_exchange(records_as_dicts, 0)row_upd, note_val = _comment_ui_state(records_as_dicts, 0)radio_upd = _classification_update(records_as_dicts, 0)return (meta, records_as_dicts, 0,f"✅ Generated session with {len(records_as_dicts)} exchanges (Provider Summary as final step)",html, pos, stats, row_upd, note_val, radio_upd,)923 unmodified lines92492592692792892993021 unmodified lines9529539549559569579584 unmodified lines96396496596696796896997097134 unmodified lines10061007100810091010101110121 unmodified line10141015101610171018101910201021102210233 unmodified lines102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105712 unmodified lines1070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111 unmodified line11131114111511161117111811191120112111221123112411251126112711281129113011313 unmodified lines113511361137113811391140114111421143114411458 unmodified lines11541155115611571158115911601161116260 unmodified lines122312241225122612271228122916 unmodified lines12461247124812491250125112522 unmodified lines12551256125712581259126012611262126312641265923 unmodified lines"original_confidence","is_correct","correct_classification","feedback_types","verifier_notes","user_message","assistant_response",21 unmodified lines"original_confidence": r.get("original_confidence"),"is_correct": r.get("is_correct"),"correct_classification": r.get("correct_classification") or "","feedback_types": "; ".join(r.get("feedback_types") or []),"verifier_notes": r.get("verifier_notes") or "","user_message": r.get("user_message"),"assistant_response": r.get("assistant_response"),4 unmodified linesdef _generate_conv_verification(session: SimplifiedSessionData):if session is None or not hasattr(session.app_instance, "conversation_logger"):return None, [], 0, "❌ No session/conversation found", "", "", "", gr.update(visible=False), "", gr.update(value=None), gr.update(value=[])if not session.app_instance.conversation_logger.entries:return None, [], 0, "⚠️ No exchanges to verify yet", "", "", "", gr.update(visible=False), "", gr.update(value=None), gr.update(value=[])manager = ConversationVerificationManager()vs = manager.create_verification_session(session.app_instance.conversation_logger, "Medical Professional")34 unmodified lines"correct_classification": r.correct_classification,"correction_reason": r.correction_reason,"verifier_notes": r.verifier_notes,"feedback_types": [],"provider_summary": provider_summary_text if r.original_classification.upper() == "RED" else "",}for r in vs.verification_records1 unmodified linehtml, pos, stats = _render_conv_exchange(records_as_dicts, 0)row_upd, note_val = _comment_ui_state(records_as_dicts, 0)radio_upd = _classification_update(records_as_dicts, 0)types_upd = _feedback_type_update(records_as_dicts, 0)return (meta, records_as_dicts, 0, f"✅ Generated session `{vs.session_id}`",html, pos, stats, row_upd, note_val, radio_upd, types_upd,)# Display text for each classification flag (shared by the verification handlers).3 unmodified lines"RED": "🔴 Should be RED - Spiritual distress",}# What kind of problem the reviewer is reporting. A single exchange can have more# than one (e.g. wrong flag AND a missing explanation), hence a multi-select.# Stored as stable codes so the export can be split into "fix the classifier# prompt" vs "fix the response prompt" without re-reading free text (Or_6.txt)._FEEDBACK_TYPE_DISPLAY = {"CLASSIFICATION": "🏷 Wrong classification","TONE": "💬 Tone / wording","MISSING_CONTENT": "📋 Missing information","FLOW": "🔀 Conversation flow",}_FEEDBACK_TYPE_CHOICES = list(_FEEDBACK_TYPE_DISPLAY.values())_FEEDBACK_TYPE_CODES = {v: k for k, v in _FEEDBACK_TYPE_DISPLAY.items()}def _feedback_type_update(records: list, idx: int):"""Build the gr.update for the 'Type of feedback' CheckboxGroup."""value = []if records and 0 <= idx < len(records) and isinstance(records[idx], dict):value = [_FEEDBACK_TYPE_DISPLAY[c]for c in (records[idx].get("feedback_types") or [])if c in _FEEDBACK_TYPE_DISPLAY]return gr.update(value=value)def _classification_update(records: list, idx: int):"""Build the gr.update for the 'Correct Classification' Radio.12 unmodified linesdef _mark_conv_correct(records: list, idx: int):if not records:return records, idx, "", "", "", "", gr.update(visible=False), "", gr.update(value=None), gr.update(value=[])idx = max(0, min(idx, len(records) - 1))if isinstance(records[idx], dict):records[idx]["is_correct"] = True# clear comment and correct_classification when marked correct (avoid stale data)records[idx]["verifier_notes"] = ""records[idx]["correct_classification"] = Nonerecords[idx]["feedback_types"] = []html, pos, stats = _render_conv_exchange(records, idx)row_upd, note_val = _comment_ui_state(records, idx)return records, idx, "✅ Marked correct", html, pos, stats, row_upd, note_val, _classification_update(records, idx), _feedback_type_update(records, idx)def _mark_conv_incorrect(records: list, idx: int):if not records:return records, idx, "", "", "", "", gr.update(visible=False), "", gr.update(value=None), gr.update(value=[])idx = max(0, min(idx, len(records) - 1))if isinstance(records[idx], dict):records[idx]["is_correct"] = Falsehtml, pos, stats = _render_conv_exchange(records, idx)row_upd, note_val = _comment_ui_state(records, idx)return records, idx, "❌ Marked incorrect", html, pos, stats, row_upd, note_val, _classification_update(records, idx), _feedback_type_update(records, idx)def _show_incorrect_comment_ui(records: list, idx: int):"""Mark incorrect and open the comment row, pre-filling any existing note."""records, idx, status, html, pos, stats, _row, note, existing_classification, existing_types = _mark_conv_incorrect(records, idx)return records, idx, status, html, pos, stats, gr.update(visible=True), note, existing_classification, existing_typesdef _save_incorrect_comment(records: list, idx: int, note: str, correct_classification: str, feedback_types: list = None):if not records:return records, idx, "", "", "", "", gr.update(visible=False), "", gr.update(value=None), gr.update(value=[])idx = max(0, min(idx, len(records) - 1))if isinstance(records[idx], dict):records[idx]["verifier_notes"] = (note or "").strip()records[idx]["feedback_types"] = [_FEEDBACK_TYPE_CODES[t] for t in (feedback_types or []) if t in _FEEDBACK_TYPE_CODES]# Map display text to classification codeclassification_map = {"🟢 Should be GREEN - No distress": "GREEN",1 unmodified line"🔴 Should be RED - Spiritual distress": "RED"}if correct_classification and correct_classification in classification_map:code = classification_map[correct_classification]records[idx]["correct_classification"] = code# Picking a classification IS the review verdict. Without this, a# reviewer who uses the always-visible panel (pick + comment + Save)# never sets is_correct, and the exchange exports as "not reviewed"# even though it was reviewed (Or_6.txt).if records[idx].get("original_classification") != "PROVIDER_SUMMARY":records[idx]["is_correct"] = (code == records[idx].get("original_classification"))html, pos, stats = _render_conv_exchange(records, idx)saved_note = records[idx].get("verifier_notes", "") if isinstance(records[idx], dict) else ""# Keep the panel open with the saved note visible, even when the reviewer# agreed with the classification and only commented on the wording.return records, idx, "💾 Comment saved", html, pos, stats, gr.update(visible=True), str(saved_note), _classification_update(records, idx), _feedback_type_update(records, idx)def _download_reviewed_json(meta: dict, records: list):return _export_conv_records_to_json(meta, records)3 unmodified linesdef _nav_conv(records: list, idx: int, delta: int):if not records:return idx, "", "", "", gr.update(visible=False), "", gr.update(value=None), gr.update(value=[])idx = max(0, min(idx + delta, len(records) - 1))html, pos, stats = _render_conv_exchange(records, idx)row_upd, note_val = _comment_ui_state(records, idx)return idx, html, pos, stats, row_upd, note_val, _classification_update(records, idx), _feedback_type_update(records, idx)# ============================================================================8 unmodified lines"Provider Summary to be the final exchange presented in that tab""""if session is None or not hasattr(session.app_instance, "conversation_logger"):return None, [], 0, "❌ No session/conversation found", "", "", "", gr.update(visible=False), "", gr.update(value=None), gr.update(value=[])if not session.app_instance.conversation_logger.entries:return None, [], 0, "⚠️ No exchanges to verify yet", "", "", "", gr.update(visible=False), "", gr.update(value=None), gr.update(value=[])manager = ConversationVerificationManager()vs = manager.create_verification_session(session.app_instance.conversation_logger, "Medical Professional")60 unmodified lines"correct_classification": r.correct_classification,"correction_reason": r.correction_reason,"verifier_notes": r.verifier_notes,"feedback_types": [],"provider_summary": "", # Not shown in regular exchanges}for r in vs.verification_records16 unmodified lines"correct_classification": None,"correction_reason": "","verifier_notes": "","feedback_types": [],"provider_summary": provider_summary_text,"provider_summary_html": provider_summary_html,}2 unmodified lineshtml, pos, stats = _render_conv_exchange(records_as_dicts, 0)row_upd, note_val = _comment_ui_state(records_as_dicts, 0)radio_upd = _classification_update(records_as_dicts, 0)types_upd = _feedback_type_update(records_as_dicts, 0)return (meta, records_as_dicts, 0,f"✅ Generated session with {len(records_as_dicts)} exchanges (Provider Summary as final step)",html, pos, stats, row_upd, note_val, radio_upd, types_upd,)