Spaces:
Sleeping
after comments from Or:
Browse filesfeat: Enhance spiritual care classification and consent messaging
- Updated the YELLOW category definition in spiritual_monitor.py to clarify ambiguity in distress indicators.
- Added follow-up purpose guidelines for YELLOW classifications.
- Introduced consent-based messaging requirements for RED classifications, ensuring patient autonomy.
- Created a new consent_message_generator.py to handle consent message generation and validation.
- Developed a provider_summary_generator.py to generate structured summaries for RED flag cases, including patient information and distress indicators.
- Modified the simplified_gradio_app.py to include patient phone number and correct classification options during conversation verification.
- Enhanced UI elements to support new classification and consent features.
Files changed (6)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184#!/usr/bin/env python3"""Consent Message Generator.
Generates consent-based messages for RED category cases, ensuring patient autonomy and avoiding assumptive language."""
import refrom typing import List, Optional
class ConsentMessageGenerator: """Generator for consent-based messages for RED category cases.""" # Approved consent-based template CONSENT_TEMPLATE = ( "Some patients who feel this way find it helpful to talk with " "someone from our spiritual care team. Would you be open to me " "sharing your information so they can reach out to you?" ) # Alternative consent templates for variety CONSENT_TEMPLATES = [ "Some patients who feel this way find it helpful to talk with someone from our spiritual care team. Would you be open to me sharing your information so they can reach out to you?", "Many people in similar situations have found it beneficial to speak with someone from our spiritual care team. Would you be comfortable with me sharing your information so they can contact you?", "Our spiritual care team has experience supporting patients who are going through similar experiences. Would you like me to share your information so someone can reach out to offer support?", "Some patients find it meaningful to connect with our spiritual care team during challenging times like this. Would you be interested in having someone reach out to you?", ] # Forbidden assumptive phrases that must not appear in messages FORBIDDEN_PHRASES = [ "I'm connecting you with", "You're not alone in this", "I'm referring you to", "Someone will reach out", "I will contact", "I'm arranging", "I'll make sure", "I'll have someone", "I'm scheduling", "I'm setting up", "You will receive", "Someone is coming", "Help is on the way", "I've notified", "I've contacted", "I've arranged", "We're sending", "We will contact", "We're connecting", "We're referring", ] # Required consent language patterns REQUIRED_CONSENT_PATTERNS = [ r"would you be (?:open to|comfortable with|interested in)", r"would you like", r"are you (?:open to|comfortable with|interested in)", r"do you want", r"would it be (?:okay|alright|helpful)", ] def generate_consent_request(self, context: str = "") -> str: """ Generate consent request message for RED case. Args: context: Optional context about the patient's situation Returns: Consent-based message asking for patient permission """ # For now, use the primary template # In the future, this could be enhanced to select based on context return self.CONSENT_TEMPLATE def validate_message(self, message: str) -> bool: """ Ensure message doesn't contain forbidden assumptive phrases. Args: message: Message to validate Returns: True if message is valid (no forbidden phrases), False otherwise """ if not message or not isinstance(message, str): return False message_lower = message.lower() # Check for forbidden phrases for forbidden_phrase in self.FORBIDDEN_PHRASES: if forbidden_phrase.lower() in message_lower: return False return True def contains_consent_language(self, message: str) -> bool: """ Check if message contains proper consent-asking language. Args: message: Message to check Returns: True if message contains consent language, False otherwise """ if not message or not isinstance(message, str): return False message_lower = message.lower() # Check for required consent patterns for pattern in self.REQUIRED_CONSENT_PATTERNS: if re.search(pattern, message_lower): return True return False def get_validation_errors(self, message: str) -> List[str]: """ Get list of validation errors for a message. Args: message: Message to validate Returns: List of validation error messages """ errors = [] if not message or not isinstance(message, str): errors.append("Message is empty or not a string") return errors # Check for forbidden phrases message_lower = message.lower() for forbidden_phrase in self.FORBIDDEN_PHRASES: if forbidden_phrase.lower() in message_lower: errors.append(f"Contains forbidden assumptive phrase: '{forbidden_phrase}'") # Check for consent language if not self.contains_consent_language(message): errors.append("Missing consent-asking language (e.g., 'Would you be open to...', 'Would you like...')") return errors def fix_message(self, message: str) -> str: """ Attempt to fix a message by replacing forbidden phrases. Args: message: Message to fix Returns: Fixed message (or original if no fixes needed) """ if not message or not isinstance(message, str): return self.CONSENT_TEMPLATE fixed_message = message # Replace common assumptive phrases with consent-based alternatives replacements = { "I'm connecting you with": "Would you be open to connecting with", "You're not alone in this": "Some patients find it helpful to know they're not alone. Would you like to connect with", "I'm referring you to": "Would you be interested in speaking with", "Someone will reach out": "Would you like someone to reach out", "I will contact": "Would you be comfortable if I contact", "I'm arranging": "Would you like me to arrange", "I'll make sure": "Would you like me to make sure", "I'll have someone": "Would you be open to having someone", } for forbidden, replacement in replacements.items(): fixed_message = re.sub(re.escape(forbidden), replacement, fixed_message, flags=re.IGNORECASE) # If still not valid, return the template if not self.validate_message(fixed_message) or not self.contains_consent_language(fixed_message): return self.CONSENT_TEMPLATE return fixed_message123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242#!/usr/bin/env python3"""Provider Summary Generator.
Generates provider-facing summaries for RED flag cases, including patientsituation, indicators, context from clarifying questions, and contact info.
Requirements: 6.1, 6.2, 6.3, 6.4, 6.5"""
from dataclasses import dataclass, fieldfrom datetime import datetimefrom typing import List, Optional
@dataclassclass ProviderSummary: """ Provider-facing summary for RED flag cases. Contains all information needed for spiritual care team follow-up. """ patient_name: str = "[Patient Name]" patient_phone: str = "[Phone Number]" situation_description: str = "" indicators: List[str] = field(default_factory=list) classification: str = "RED" confidence: float = 0.0 reasoning: str = "" triage_context: List[dict] = field(default_factory=list) conversation_context: str = "" generated_at: str = field(default_factory=lambda: datetime.now().isoformat()) def to_dict(self) -> dict: """Convert to dictionary for export.""" return { "patient_name": self.patient_name, "patient_phone": self.patient_phone, "situation_description": self.situation_description, "indicators": self.indicators, "classification": self.classification, "confidence": self.confidence, "reasoning": self.reasoning, "triage_context": self.triage_context, "conversation_context": self.conversation_context, "generated_at": self.generated_at }
class ProviderSummaryGenerator: """ Generator for provider-facing summaries in RED flag cases. Creates structured summaries for spiritual care team with patient information, distress indicators, and relevant context. Requirements: 6.1, 6.2, 6.3, 6.4 """ def generate_summary( self, indicators: List[str], reasoning: str, confidence: float = 0.0, patient_name: Optional[str] = None, patient_phone: Optional[str] = None, triage_questions: Optional[List[str]] = None, triage_responses: Optional[List[str]] = None, conversation_context: Optional[str] = None ) -> ProviderSummary: """ Generate provider-facing summary for RED flag case. Args: indicators: List of distress indicators detected reasoning: Reasoning for RED classification confidence: Confidence level (0.0-1.0) patient_name: Patient name (optional, uses placeholder if not provided) patient_phone: Patient phone (optional, uses placeholder if not provided) triage_questions: List of triage questions asked (if any) triage_responses: List of patient responses to triage (if any) conversation_context: Recent conversation context Returns: ProviderSummary with all relevant information Requirements: 6.1, 6.2, 6.4 """ # Build triage context triage_context = [] if triage_questions and triage_responses: for q, r in zip(triage_questions, triage_responses): triage_context.append({ "question": q, "response": r }) # Generate situation description from indicators and reasoning situation_description = self._generate_situation_description( indicators, reasoning, triage_context ) return ProviderSummary( patient_name=patient_name or "[Patient Name]", patient_phone=patient_phone or "[Phone Number]", situation_description=situation_description, indicators=indicators, classification="RED", confidence=confidence, reasoning=reasoning, triage_context=triage_context, conversation_context=conversation_context or "" ) def _generate_situation_description( self, indicators: List[str], reasoning: str, triage_context: List[dict] ) -> str: """Generate brief description of patient's situation.""" parts = [] # Add indicator summary if indicators: indicator_text = ", ".join(indicators) parts.append(f"Patient showing signs of: {indicator_text}.") # Add reasoning if reasoning: parts.append(f"Assessment: {reasoning}") # Add triage summary if available if triage_context: parts.append(f"Clarifying questions asked: {len(triage_context)}") return " ".join(parts) if parts else "RED flag detected - spiritual care support recommended." def format_for_display(self, summary: ProviderSummary) -> str: """ Format provider summary for display in UI. Args: summary: ProviderSummary to format Returns: Formatted string for display Requirements: 6.3 """ lines = [ "β" * 50, "π PROVIDER SUMMARY - SPIRITUAL CARE REFERRAL", "β" * 50, "", f"π
Generated: {summary.generated_at}", "", "π€ PATIENT INFORMATION", "β" * 30, f" Name: {summary.patient_name}", f" Phone: {summary.patient_phone}", "", "π΄ CLASSIFICATION: RED FLAG", f" Confidence: {summary.confidence:.0%}", "", "π SITUATION", "β" * 30, f" {summary.situation_description}", "", "β οΈ DISTRESS INDICATORS", "β" * 30, ] if summary.indicators: for indicator in summary.indicators: lines.append(f" β’ {indicator}") else: lines.append(" β’ No specific indicators recorded") lines.append("") lines.append("π REASONING") lines.append("β" * 30) lines.append(f" {summary.reasoning}") if summary.triage_context: lines.append("") lines.append("π TRIAGE EXCHANGES") lines.append("β" * 30) for i, exchange in enumerate(summary.triage_context, 1): lines.append(f" Q{i}: {exchange.get('question', 'N/A')}") lines.append(f" A{i}: {exchange.get('response', 'N/A')}") lines.append("") if summary.conversation_context: lines.append("") lines.append("π¬ RECENT CONVERSATION") lines.append("β" * 30) # Truncate if too long context = summary.conversation_context if len(context) > 500: context = context[:500] + "..." lines.append(f" {context}") lines.append("") lines.append("β" * 50) lines.append("RECOMMENDED ACTION: Immediate spiritual care outreach") lines.append("β" * 50) return "\n".join(lines) def format_for_export(self, summary: ProviderSummary) -> str: """ Format provider summary for export (CSV/JSON). Args: summary: ProviderSummary to format Returns: Compact string suitable for export Requirements: 6.5 """ parts = [ f"Patient: {summary.patient_name} ({summary.patient_phone})", f"Classification: RED ({summary.confidence:.0%})", f"Indicators: {', '.join(summary.indicators) if summary.indicators else 'None'}", f"Reasoning: {summary.reasoning}", ] if summary.triage_context: triage_summary = "; ".join([ f"Q: {ex.get('question', '')} A: {ex.get('response', '')}" for ex in summary.triage_context ]) parts.append(f"Triage: {triage_summary}") return " | ".join(parts)
def create_provider_summary_generator() -> ProviderSummaryGenerator: """Factory function to create ProviderSummaryGenerator.""" return ProviderSummaryGenerator()27 unmodified lines28293031323344 unmodified lines787980818283255 unmodified lines33934034134234334434534634784 unmodified lines43243343443543643743843944038 unmodified lines47948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253327 unmodified linesClinicalBackground, ChatMessage, SessionState,PatientDataLoader, MedicalAssistant, SoftMedicalTriage)# Configure logginglogging.basicConfig(level=logging.INFO)44 unmodified lines# Spiritual monitoring componentsself.spiritual_monitor = SpiritualMonitor(self.api)self.soft_triage_manager = SoftTriageManager(self.api)# Load patient datalogger.info("π Loading patient data...")255 unmodified linesreturn self._escalate_to_red("Max triage questions reached - conservative escalation")else:# Update assessment for continuing triagecontinue_assessment = SpiritualAssessment(state=SpiritualState.YELLOW,indicators=["ongoing_triage"],confidence=0.7,reasoning=f"Continuing triage assessment - {reasoning}")84 unmodified linespatient_language = self._detect_language(last_response)# Create assessment from triage contextassessment = SpiritualAssessment(state=SpiritualState.RED,indicators=["triage_escalation"],confidence=0.8,reasoning=reasoning)38 unmodified lineslanguage: str,assessment: SpiritualAssessment) -> str:"""Generate compassionate crisis support response."""if language == "Ukrainian":return """Π― ΡΡΡ Π²Π°Ρ, Ρ ΠΌΠ΅Π½Ρ Π²Π°ΠΆΠ»ΠΈΠ²ΠΎ, ΡΠΎ Π²ΠΈ ΠΏΠΎΠ΄ΡΠ»ΠΈΠ»ΠΈΡΡ ΡΠΈΠΌ Π·Ρ ΠΌΠ½ΠΎΡ. Π’Π΅, ΡΠΎ Π²ΠΈ Π²ΡΠ΄ΡΡΠ²Π°ΡΡΠ΅, ΡΠ΅ΡΠΉΠΎΠ·Π½Π΅, Ρ Π²ΠΈ Π·Π°ΡΠ»ΡΠ³ΠΎΠ²ΡΡΡΠ΅ Π½Π° ΠΏΡΠ΄ΡΡΠΈΠΌΠΊΡ.π **ΠΠ°ΠΆΠ»ΠΈΠ²ΠΎ:** Π―ΠΊΡΠΎ Π²ΠΈ ΠΌΠ°ΡΡΠ΅ Π΄ΡΠΌΠΊΠΈ ΠΏΡΠΎ ΡΠ°ΠΌΠΎΡΡΠΊΠΎΠ΄ΠΆΠ΅Π½Π½Ρ, Π±ΡΠ΄Ρ Π»Π°ΡΠΊΠ°, Π·Π²Π΅ΡΠ½ΡΡΡΡΡ Π·Π° Π΄ΠΎΠΏΠΎΠΌΠΎΠ³ΠΎΡ:β’ ΠΡΠ½ΡΡ Π΄ΠΎΠ²ΡΡΠΈ: 7333 (Π±Π΅Π·ΠΊΠΎΡΡΠΎΠ²Π½ΠΎ Π· ΠΌΠΎΠ±ΡΠ»ΡΠ½ΠΎΠ³ΠΎ)β’ ΠΠ°ΠΉΡΠ»Π°ΠΉΠ½ Π£ΠΊΡΠ°ΡΠ½Π°: 0 800 500 335Π― ΠΏΠ΅ΡΠ΅Π΄Π°ΠΌ ΡΠ½ΡΠΎΡΠΌΠ°ΡΡΡ Π½Π°ΡΡΠΉ ΠΊΠΎΠΌΠ°Π½Π΄Ρ Π΄ΡΡ ΠΎΠ²Π½ΠΎΡ ΠΏΡΠ΄ΡΡΠΈΠΌΠΊΠΈ, ΡΠΎΠ± Ρ ΡΠΎΡΡ ΠΌΡΠ³ Π·Π²'ΡΠ·Π°ΡΠΈΡΡ Π· Π²Π°ΠΌΠΈ ΠΎΡΠΎΠ±ΠΈΡΡΠΎ. ΠΠΈ Π½Π΅ ΡΠ°ΠΌΠΎΡΠ½Ρ Π² ΡΡΠΎΠΌΡ."""else:return """I hear you, and I'm glad you shared this with me. What you're feeling is serious, and you deserve support.π **Important:** If you're having thoughts of self-harm, please reach out for help:β’ National Suicide Prevention Lifeline: 988β’ Crisis Text Line: Text HOME to 741741I'm connecting you with our spiritual care team so someone can reach out to you personally. You're not alone in this."""def _generate_referral(self, assessment: SpiritualAssessment) -> str:"""Generate referral message for chaplain team."""# Get triage context if availabletriage_context = ""if self.spiritual_state.triage_session:triage_context = "\n\nTriage exchanges:\n"for q, r in zip(self.spiritual_state.triage_session.questions_asked,self.spiritual_state.triage_session.patient_responses):triage_context += f"Q: {q}\nA: {r}\n"referral = f"""=== SPIRITUAL CARE REFERRAL ===Generated: {datetime.now().isoformat()}Patient: {self.clinical_background.patient_name}DISTRESS INDICATORS:{chr(10).join(f'β’ {ind}' for ind in assessment.indicators)}CLASSIFICATION: {assessment.state.value.upper()}CONFIDENCE: {assessment.confidence:.0%}REASONING: {assessment.reasoning}{triage_context}RECENT CONVERSATION:{self._get_conversation_context_str()}RECOMMENDED ACTION: Immediate spiritual care outreach================================"""return referraldef _detect_language(self, text: str) -> str:"""Simple language detection based on character analysis."""27 unmodified lines282930313233343544 unmodified lines8081828384858687888990919293255 unmodified lines34935035135235335435535635735835936036136284 unmodified lines44744844945045145245345445545645745845946038 unmodified lines49950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159227 unmodified linesClinicalBackground, ChatMessage, SessionState,PatientDataLoader, MedicalAssistant, SoftMedicalTriage)from src.core.consent_message_generator import ConsentMessageGeneratorfrom src.core.provider_summary_generator import ProviderSummaryGenerator, ProviderSummary# Configure logginglogging.basicConfig(level=logging.INFO)44 unmodified lines# Spiritual monitoring componentsself.spiritual_monitor = SpiritualMonitor(self.api)self.soft_triage_manager = SoftTriageManager(self.api)self.consent_generator = ConsentMessageGenerator()self.provider_summary_generator = ProviderSummaryGenerator()# Patient information (can be set via UI)self.patient_info = {"name": None,"phone": None}# Load patient datalogger.info("π Loading patient data...")255 unmodified linesreturn self._escalate_to_red("Max triage questions reached - conservative escalation")else:# Update assessment for continuing triage# Preserve original spiritual indicators from initial assessmentoriginal_indicators = []if self.spiritual_state.last_assessment and self.spiritual_state.last_assessment.indicators:original_indicators = self.spiritual_state.last_assessment.indicatorscontinue_assessment = SpiritualAssessment(state=SpiritualState.YELLOW,indicators=original_indicators if original_indicators else ["potential_distress"],confidence=0.7,reasoning=f"Continuing triage assessment - {reasoning}")84 unmodified linespatient_language = self._detect_language(last_response)# Create assessment from triage context# Preserve original spiritual indicators from triage sessionoriginal_indicators = []if self.spiritual_state.last_assessment and self.spiritual_state.last_assessment.indicators:original_indicators = self.spiritual_state.last_assessment.indicatorsassessment = SpiritualAssessment(state=SpiritualState.RED,indicators=original_indicators if original_indicators else ["spiritual_distress"],confidence=0.8,reasoning=reasoning)38 unmodified lineslanguage: str,assessment: SpiritualAssessment) -> str:"""Generate compassionate crisis support response with consent-based messaging.Uses ConsentMessageGenerator to ensure patient autonomy - asks for permissionbefore connecting with spiritual care team instead of assuming consent.Requirements: 2.1, 2.2, 2.3, 2.5"""# Get consent request from generatorconsent_request = self.consent_generator.generate_consent_request()if language == "Ukrainian":return f"""Π― ΡΡΡ Π²Π°Ρ, Ρ ΠΌΠ΅Π½Ρ Π²Π°ΠΆΠ»ΠΈΠ²ΠΎ, ΡΠΎ Π²ΠΈ ΠΏΠΎΠ΄ΡΠ»ΠΈΠ»ΠΈΡΡ ΡΠΈΠΌ Π·Ρ ΠΌΠ½ΠΎΡ. Π’Π΅, ΡΠΎ Π²ΠΈ Π²ΡΠ΄ΡΡΠ²Π°ΡΡΠ΅, ΡΠ΅ΡΠΉΠΎΠ·Π½Π΅, Ρ Π²ΠΈ Π·Π°ΡΠ»ΡΠ³ΠΎΠ²ΡΡΡΠ΅ Π½Π° ΠΏΡΠ΄ΡΡΠΈΠΌΠΊΡ.π **ΠΠ°ΠΆΠ»ΠΈΠ²ΠΎ:** Π―ΠΊΡΠΎ Π²ΠΈ ΠΌΠ°ΡΡΠ΅ Π΄ΡΠΌΠΊΠΈ ΠΏΡΠΎ ΡΠ°ΠΌΠΎΡΡΠΊΠΎΠ΄ΠΆΠ΅Π½Π½Ρ, Π±ΡΠ΄Ρ Π»Π°ΡΠΊΠ°, Π·Π²Π΅ΡΠ½ΡΡΡΡΡ Π·Π° Π΄ΠΎΠΏΠΎΠΌΠΎΠ³ΠΎΡ:β’ ΠΡΠ½ΡΡ Π΄ΠΎΠ²ΡΡΠΈ: 7333 (Π±Π΅Π·ΠΊΠΎΡΡΠΎΠ²Π½ΠΎ Π· ΠΌΠΎΠ±ΡΠ»ΡΠ½ΠΎΠ³ΠΎ)β’ ΠΠ°ΠΉΡΠ»Π°ΠΉΠ½ Π£ΠΊΡΠ°ΡΠ½Π°: 0 800 500 335ΠΠ΅ΡΠΊΡ ΠΏΠ°ΡΡΡΠ½ΡΠΈ, ΡΠΊΡ Π²ΡΠ΄ΡΡΠ²Π°ΡΡΡ ΠΏΠΎΠ΄ΡΠ±Π½Π΅, Π²Π²Π°ΠΆΠ°ΡΡΡ ΠΊΠΎΡΠΈΡΠ½ΠΈΠΌ ΠΏΠΎΠ³ΠΎΠ²ΠΎΡΠΈΡΠΈ Π· ΠΊΠΈΠΌΠΎΡΡ ΡΠ· Π½Π°ΡΠΎΡ ΠΊΠΎΠΌΠ°Π½Π΄ΠΈ Π΄ΡΡ ΠΎΠ²Π½ΠΎΡ ΠΏΡΠ΄ΡΡΠΈΠΌΠΊΠΈ. Π§ΠΈ Π±ΡΠ»ΠΈ Π± Π²ΠΈ Π²ΡΠ΄ΠΊΡΠΈΡΡ Π΄ΠΎ ΡΠΎΠ³ΠΎ, ΡΠΎΠ± Ρ ΠΏΠΎΠ΄ΡΠ»ΠΈΠ²ΡΡ Π²Π°ΡΠΎΡ ΡΠ½ΡΠΎΡΠΌΠ°ΡΡΡΡ, ΡΠΎΠ± Π²ΠΎΠ½ΠΈ ΠΌΠΎΠ³Π»ΠΈ Π·Π²'ΡΠ·Π°ΡΠΈΡΡ Π· Π²Π°ΠΌΠΈ?"""else:return f"""I hear you, and I'm glad you shared this with me. What you're feeling is serious, and you deserve support.π **Important:** If you're having thoughts of self-harm, please reach out for help:β’ National Suicide Prevention Lifeline: 988β’ Crisis Text Line: Text HOME to 741741{consent_request}"""def _generate_referral(self, assessment: SpiritualAssessment) -> str:"""Generate referral message for chaplain team using ProviderSummaryGenerator.Requirements: 6.1, 6.2, 6.3"""# Get triage context if availabletriage_questions = []triage_responses = []if self.spiritual_state.triage_session:triage_questions = self.spiritual_state.triage_session.questions_askedtriage_responses = self.spiritual_state.triage_session.patient_responses# Get patient name - prefer patient_info, fall back to clinical_backgroundpatient_name = self.patient_info.get("name") or self.clinical_background.patient_namepatient_phone = self.patient_info.get("phone")# Generate provider summarysummary = self.provider_summary_generator.generate_summary(indicators=assessment.indicators,reasoning=assessment.reasoning,confidence=assessment.confidence,patient_name=patient_name,patient_phone=patient_phone,triage_questions=triage_questions,triage_responses=triage_responses,conversation_context=self._get_conversation_context_str())# Store the summary for later accessself._last_provider_summary = summary# Return formatted summary for displayreturn self.provider_summary_generator.format_for_display(summary)def set_patient_info(self, name: Optional[str] = None, phone: Optional[str] = None) -> None:"""Set patient information for provider summaries.Args:name: Patient name (optional)phone: Patient phone number (optional)Requirements: 7.1, 7.2"""if name:self.patient_info["name"] = nameif phone:self.patient_info["phone"] = phonedef get_last_provider_summary(self) -> Optional[ProviderSummary]:"""Get the last generated provider summary.Returns:ProviderSummary if one was generated, None otherwiseRequirements: 6.3"""return getattr(self, '_last_provider_summary', None)def _detect_language(self, text: str) -> str:"""Simple language detection based on character analysis."""
70 unmodified lines71727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221 unmodified line12412512612712812913070 unmodified lines# System prompt for evaluating triage responsesSYSTEM_PROMPT_TRIAGE_EVALUATE = """<system_role>You are evaluating a patient's response during a gentle wellness check. Based on the patient's response, determine the appropriate outcome to guide next steps.</system_role><outcome_categories><outcome name="RESOLVED_GREEN" action="return_to_medical"><description>Patient is coping well, has support systems, or the concern was minor</description><indicators>- Mentions coping strategies or support from others- Describes temporary stress that is manageable- Reports feeling better or having resources- Shows resilience or positive outlook</indicators><example>"I'm just having a bad day, but I have my family to talk to"</example><example>"It's been tough, but I'm managing with my therapist's help"</example></outcome><outcome name="ESCALATE_RED" action="generate_referral"><description>Patient shows significant distress that needs professional support</description><indicators>- Persistent hopelessness without relief- Complete isolation with no support system- Inability to cope or function- Worsening symptoms or deterioration- Continued crisis language</indicators><example>"I feel completely alone and nothing helps anymore"</example><example>"Every day is worse, I can't see a way forward"</example></outcome><outcome name="CONTINUE" action="ask_another_question"><description>Need more information to make a determination</description><indicators>- Vague or unclear response- Patient deflecting or avoiding- Ambiguous situation requiring clarification- Mixed signals that need exploration</indicators><example>"I don't know, it's complicated"</example><example>"Maybe, I'm not sure"</example></outcome></outcome_categories><evaluation_process><step>Review the patient's response carefully</step><step>Identify specific indicators present in their words</step><step>Match indicators to outcome categories</step><step>Consider the overall tone and context</step><step>Assess confidence in your determination</step></evaluation_process>1 unmodified lineRespond ONLY with valid JSON in this exact format:{"outcome": "resolved_green" | "escalate_red" | "continue","reasoning": "Brief explanation of why you chose this outcome","confidence": 0.0-1.0}70 unmodified lines71727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841 unmodified line18618718818919019119219370 unmodified lines# System prompt for evaluating triage responsesSYSTEM_PROMPT_TRIAGE_EVALUATE = """<system_role>You are evaluating a patient's response during a gentle wellness check. Based on the patient's response, determine the appropriate outcome to guide next steps.IMPORTANT: You have access to the full classification definitions to make accurate decisions.</system_role><classification_definitions><category name="GREEN" description="No spiritual/emotional distress">The patient's situation is NOT caused by and is NOT causing emotional/spiritual distress. The concern is:- Due to external factors (time constraints, routine changes, logistics)- Medical symptoms without emotional distress component- Temporary circumstances that patient is managing well- Patient has adequate support and coping mechanisms</category><category name="RED" description="Clear spiritual/emotional distress requiring support">The patient shows clear indicators of emotional or spiritual distress:- Loss of meaning, purpose, or hope- Sadness, despair, grief that is affecting functioning- Spiritual questioning with distress (anger at God, loss of faith)- Identity disruption ("I don't know who I am anymore")- Isolation combined with distress- Guilt, shame, or remorse causing suffering- Crisis language (hopelessness, wanting to give up)- Patient with mental health condition expressing distress- Anticipatory emotional response causing distress</category><category name="YELLOW" description="Ambiguous - need more information">It remains UNCLEAR whether the patient's situation is caused by or is causing emotional/spiritual distress. Use this only when you genuinely cannot determine if distress is present.</category></classification_definitions><outcome_categories><outcome name="RESOLVED_GREEN" action="return_to_medical"><description>Patient's response indicates NO spiritual/emotional distress - situation is due to external factors</description><indicators>- External causes identified: time constraints, routine changes, medical symptoms without emotional component- Patient mentions coping strategies or support from others- Describes temporary stress that is manageable- Reports feeling better or having resources- Shows resilience or positive outlook- Concern is logistical/practical, not emotional/spiritual</indicators><examples>"I'm just having a bad day, but I have my family to talk to""It's been tough, but I'm managing with my therapist's help""I haven't been sleeping well because of my medication schedule""I'm just busy with appointments, that's why I'm stressed""My routine changed because of the treatment, but I'm adjusting"</examples></outcome><outcome name="ESCALATE_RED" action="generate_referral"><description>Patient's response indicates clear emotional/spiritual distress requiring support</description><indicators>- Loss of meaning, purpose, or hope expressed- Sadness, despair, grief affecting daily life- Spiritual distress (anger at God, questioning faith with pain)- Identity disruption or loss of self- Persistent hopelessness without relief- Complete isolation with no support system- Inability to cope or function- Worsening symptoms or deterioration- Continued crisis language- Patient with mental health condition expressing distress- Anticipatory emotional response causing suffering</indicators><examples>"I feel completely alone and nothing helps anymore""Every day is worse, I can't see a way forward""I don't know who I am anymore since the diagnosis""What's the point of any of this?""I feel like God has abandoned me""I'm so sad all the time, I can't enjoy anything""I'm terrified about what's going to happen and can't stop thinking about it"</examples></outcome><outcome name="CONTINUE" action="ask_another_question"><description>Response is still ambiguous - need more information to determine if distress is present</description><indicators>- Vague or unclear response that doesn't clarify cause- Patient deflecting or avoiding the question- Mixed signals that need exploration- Cannot determine if external factors or emotional distress</indicators><examples>"I don't know, it's complicated""Maybe, I'm not sure""Things are just different now"</examples></outcome></outcome_categories><yellow_flow_logic>CRITICAL: The purpose of triage is to CLARIFY ambiguity. Apply these rules:1. If patient's response indicates EXTERNAL CAUSES (time, routine, medical symptoms, logistics) β RESOLVED_GREEN2. If patient's response indicates EMOTIONAL/SPIRITUAL DISTRESS (loss of meaning, sadness, despair, grief, spiritual pain) β ESCALATE_RED3. If patient with known mental health condition expresses emotional distress β ESCALATE_RED4. If patient expresses anticipatory emotional response causing distress β ESCALATE_RED5. If response is still ambiguous and you cannot determine cause β CONTINUE (if questions remain)</yellow_flow_logic><evaluation_process><step>Review the patient's response carefully</step><step>Identify if response indicates EXTERNAL causes (β GREEN) or EMOTIONAL/SPIRITUAL distress (β RED)</step><step>Apply the yellow_flow_logic rules</step><step>If still ambiguous and questions remain, choose CONTINUE</step><step>Assess confidence in your determination</step></evaluation_process>1 unmodified lineRespond ONLY with valid JSON in this exact format:{"outcome": "resolved_green" | "escalate_red" | "continue","indicators": ["indicator1", "indicator2"],"reasoning": "Brief explanation of why you chose this outcome based on the classification definitions","confidence": 0.0-1.0}
72 unmodified lines737475767778798043 unmodified lines12412512612712812913013113213313413513613713813968 unmodified lines20820921021121221324 unmodified lines23823924024124224324472 unmodified linesThe message contains only medical symptoms, routine questions, appointment scheduling, medication inquiries, or other standard healthcare topics. There are no indicators of emotional or spiritual distress.</category><category name="YELLOW" severity="potential_distress">The message contains indicators of mild to moderate distress, including:<emotional_expressions>- Sleep difficulties, insomnia (Dysomnias/Difficulty sleeping)43 unmodified lines</spiritual_practices><examples>"I can't sleep at night, my mind won't stop racing""I used to love gardening, but now I can't and it breaks my heart""Why is God letting this happen to me?""I feel so alone, nobody understands""I'm worried about being a burden to my family""I don't know who I am anymore without my work""I'm exhausted all the time, emotionally drained""I can't do the things I used to enjoy""What's the meaning of all this suffering?"</examples></category><category name="RED" severity="severe_distress">68 unmodified lines4. Spiritual questions alone (without crisis indicators) are YELLOW, not RED5. Multiple YELLOW indicators together still remain YELLOW unless crisis language is present6. Physical pain or medical symptoms alone are GREEN unless accompanied by emotional/spiritual distress language</critical_rules><analysis_process>24 unmodified lines}Do not include any text before or after the JSON object.</output_format>"""class SpiritualMonitor:72 unmodified lines73747576777879808182838485868788899043 unmodified lines13413513613713813914014114214314414514614714814915015115215315415568 unmodified lines22422522622722822923023123223324 unmodified lines25825926026126226326426526626726826927027127227327427527627727827928028128228328428572 unmodified linesThe message contains only medical symptoms, routine questions, appointment scheduling, medication inquiries, or other standard healthcare topics. There are no indicators of emotional or spiritual distress.</category><category name="YELLOW" severity="ambiguous_distress">The message contains indicators where it is UNCLEAR whether the patient's situation is caused by or is causing emotional/spiritual distress, or if it is due to something else (medical symptoms, pain, temporary circumstances, external factors).YELLOW is NOT about severity level - it is about AMBIGUITY. Use YELLOW when you need more information to determine if the situation warrants spiritual care support.Common YELLOW scenarios:- Patient mentions potentially distressing circumstances without expressing emotional distress- Patient reports loss of loved one but hasn't expressed how they're coping emotionally- Patient mentions having no help but hasn't indicated if this is causing distress- Patient describes difficult situation but cause of any distress is unclearIndicators that may warrant YELLOW classification:<emotional_expressions>- Sleep difficulties, insomnia (Dysomnias/Difficulty sleeping)43 unmodified lines</spiritual_practices><examples>"I can't sleep at night, my mind won't stop racing" (unclear if medical or emotional cause)"I used to love gardening, but now I can't" (unclear if causing distress or just factual)"My mother passed away last month" (unclear how patient is coping emotionally)"I don't have anyone to help me at home" (unclear if this is causing distress)"I've been feeling tired lately" (could be medical or emotional)"Things have been difficult since my diagnosis" (unclear extent of emotional impact)"I'm worried about my upcoming surgery" (normal concern vs spiritual distress unclear)"I haven't been able to go to church lately" (unclear if causing spiritual distress)</examples><yellow_follow_up_purpose>When classifying as YELLOW, the purpose of follow-up questions is to CLARIFY:- Is the situation CAUSING emotional/spiritual distress? β Escalate to RED- Is the distress due to external factors (time, routine, medical symptoms)? β Downgrade to GREEN- Does the patient express loss of meaning, sadness, despair, grief? β Escalate to RED</yellow_follow_up_purpose></category><category name="RED" severity="severe_distress">68 unmodified lines4. Spiritual questions alone (without crisis indicators) are YELLOW, not RED5. Multiple YELLOW indicators together still remain YELLOW unless crisis language is present6. Physical pain or medical symptoms alone are GREEN unless accompanied by emotional/spiritual distress language7. Patient with known mental health condition who expresses emotional or spiritual distress β RED (regardless of diagnosis)8. Patient expressing anticipatory emotional response causing distress β RED9. YELLOW is about AMBIGUITY, not severity - use YELLOW when you need clarification about whether distress is present10. If patient clearly expresses emotional/spiritual distress (loss of meaning, sadness, despair, grief) β RED, not YELLOW</critical_rules><analysis_process>24 unmodified lines}Do not include any text before or after the JSON object.</output_format><consent_based_messaging>CRITICAL FOR RED CLASSIFICATIONS:When a message is classified as RED, the system will generate a response that asks for patient CONSENT before connecting them with spiritual care support. This is essential for patient autonomy.The response MUST:- Ask for permission before sharing patient information- Use phrases like "Would you be open to..." or "Would you like..."- Respect patient's right to declineThe response MUST NOT:- Assume the patient wants to be connected with support- Use assumptive language like "I'm connecting you with..." or "Someone will reach out..."- Make decisions on behalf of the patientExample of CORRECT consent-based language:"Some patients who feel this way find it helpful to talk with someone from our spiritual care team. Would you be open to me sharing your information so they can reach out to you?"Example of INCORRECT assumptive language (DO NOT USE):"I'm connecting you with our spiritual care team so someone can reach out to you personally."</consent_based_messaging>"""class SpiritualMonitor:
214 unmodified lines215216217218219220221222223224225226227202 unmodified lines4304314324334344351498 unmodified lines19341935193619371938193913 unmodified lines1953195419551956195719586 unmodified lines196519661967196819691970197119721973197419751976197748 unmodified lines2026202720282029203020311 unmodified line2033203420352036203720382039204020412042204320442045204620472048204920501 unmodified line2052205320542055205620572058205920608 unmodified lines206920702071207220732074207520762077207820792080208110 unmodified lines2092209320942095209620972 unmodified lines210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921403 unmodified lines2144214521462147214821492150215121522153215425 unmodified lines2180218121822183218421859 unmodified lines2195219621972198219922002201220222032204220522063 unmodified lines2210221122122213221422152216221722182219222022212222222322242225222622272228105 unmodified lines2334233523362337233823392 unmodified lines2342234323442345234623472 unmodified lines2350235123522353235423552 unmodified lines2358235923602361236223632 unmodified lines2366236723682369237023712 unmodified lines2374237523762377237823792 unmodified lines2382238323842385238623872 unmodified lines2390239123922393239423952 unmodified lines2398239924002401240224032 unmodified lines2406240724082409241024112 unmodified lines2414241524162417241824192 unmodified lines2422242324242425242624272 unmodified lines2430243124322433243424352 unmodified lines2438243924402441244224432 unmodified lines2446244724482449245024517 unmodified lines2459246024612462246324642465246624672468246924702 unmodified lines247324742475247624772478247924802481248224832484248524862487248824893 unmodified lines249324942495249624972498249925002501250225032504250525066 unmodified lines251325142515251625172518251925202521252225232524252525262527252825292530214 unmodified lines# Shown only when marking Incorrectwith gr.Row(visible=False) as conv_incorrect_comment_row:conv_incorrect_comment = gr.Textbox(label="Comment (why incorrect / what to fix)",placeholder="Add a short note for this exchange...",lines=3,scale=4,)conv_save_comment_btn = gr.Button("πΎ Save comment", variant="secondary", scale=1)with gr.Row():with gr.Column(scale=1):202 unmodified linesvalue="Serhii",interactive=True)patient_age = gr.Number(label="Age",value=52,1498 unmodified linesoriginal_indicators=r.get("original_indicators", []),original_reasoning=r.get("original_reasoning", ""),timestamp=r.get("timestamp"),)else:rec = r13 unmodified linescorrect = 0incorrect = 0incorrect_with_comment = 0for x in records:v = (x.get("is_correct") if isinstance(x, dict) else getattr(x, "is_correct", None))if v is None:6 unmodified linesnote = (x.get("verifier_notes") if isinstance(x, dict) else getattr(x, "verifier_notes", None))if note and str(note).strip():incorrect_with_comment += 1stats = ("<div style='display:flex; gap:12px; flex-wrap:wrap;'>"f"<div><strong>Reviewed:</strong> {reviewed}/{len(records)}</div>"f"<div><strong>β Correct:</strong> {correct}</div>"f"<div><strong>β Incorrect:</strong> {incorrect}</div>"f"<div><strong>π Incorrect w/ comment:</strong> {incorrect_with_comment}</div>""</div>")return html, pos, stats48 unmodified linesfieldnames = ["session_id","patient_name","verifier_name","start_time","exchange_number",1 unmodified line"original_classification","original_confidence","is_correct","verifier_notes","user_message","assistant_response",]with open(export_path, "w", encoding="utf-8", newline="") as f:w = csv.DictWriter(f, fieldnames=fieldnames)w.writeheader()for r in records or []:row = {"session_id": (meta or {}).get("session_id"),"patient_name": (meta or {}).get("patient_name"),"verifier_name": (meta or {}).get("verifier_name"),"start_time": (meta or {}).get("start_time"),"exchange_number": r.get("exchange_number"),1 unmodified line"original_classification": r.get("original_classification"),"original_confidence": r.get("original_confidence"),"is_correct": r.get("is_correct"),"verifier_notes": r.get("verifier_notes") or "","user_message": r.get("user_message"),"assistant_response": r.get("assistant_response"),}w.writerow(row)return export_path8 unmodified linesmanager = ConversationVerificationManager()vs = manager.create_verification_session(session.app_instance.conversation_logger, "Medical Professional")meta = {"session_id": vs.session_id,"patient_name": vs.patient_name,"verifier_name": vs.verifier_name,"start_time": vs.start_time.isoformat() if hasattr(vs, "start_time") else None,}records_as_dicts = [{"exchange_id": r.exchange_id,10 unmodified lines"correct_classification": r.correct_classification,"correction_reason": r.correction_reason,"verifier_notes": r.verifier_notes,}for r in vs.verification_records]2 unmodified linesdef _mark_conv_correct(records: list, idx: int):if not records:return records, idx, "", "", "", gr.update(visible=False), ""idx = max(0, min(idx, len(records) - 1))if isinstance(records[idx], dict):records[idx]["is_correct"] = True# clear comment when marked correct (avoid stale notes)records[idx]["verifier_notes"] = ""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_valdef _mark_conv_incorrect(records: list, idx: int):if not records:return records, idx, "", "", "", gr.update(visible=False), ""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_valdef _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 = _mark_conv_incorrect(records, idx)return records, idx, status, html, pos, stats, gr.update(visible=True), notedef _save_incorrect_comment(records: list, idx: int, note: str):if not records:return records, idx, "", "", "", "", gr.update(visible=False), ""idx = max(0, min(idx, len(records) - 1))if isinstance(records[idx], dict):records[idx]["verifier_notes"] = (note or "").strip()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_valdef _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), ""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_valgenerate_conv_verification_btn.click(_generate_conv_verification,25 unmodified linesconv_stats,conv_incorrect_comment_row,conv_incorrect_comment,])9 unmodified linesconv_stats,conv_incorrect_comment_row,conv_incorrect_comment,])conv_save_comment_btn.click(_save_incorrect_comment,inputs=[conv_verify_records, conv_verify_index, conv_incorrect_comment],outputs=[conv_verify_records,conv_verify_index,3 unmodified linesconv_stats,conv_incorrect_comment_row,conv_incorrect_comment,])conv_prev_btn.click(lambda records, idx: _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_next_btn.click(lambda records, idx: _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])# Refresh conversation stats105 unmodified linesprofiles = {"Default (Serhii)": {"name": "Serhii","age": 52,"conditions": "Atrial fibrillation, Deep vein thrombosis, Obesity, Hypertension","goal": "Weight reduction and cardiovascular fitness improvement",2 unmodified lines},"π’ GREEN - Healthy": {"name": "James","age": 40,"conditions": "No chronic conditions, Excellent health","goal": "Maintain fitness and wellness",2 unmodified lines},"π‘ YELLOW - Mild Distress": {"name": "Lisa","age": 45,"conditions": "Hypertension, Mild anxiety, Sleep issues","goal": "Manage stress and improve sleep quality",2 unmodified lines},"π‘ YELLOW - Grief & Loss": {"name": "Michael","age": 58,"conditions": "Recent loss of spouse, Mild depression","goal": "Process grief and rebuild routine",2 unmodified lines},"π‘ YELLOW - Existential Questions": {"name": "Patricia","age": 62,"conditions": "Chronic pain, Questioning life purpose","goal": "Find meaning and manage chronic pain",2 unmodified lines},"π‘ YELLOW - Spiritual Disconnection": {"name": "David","age": 55,"conditions": "Loss of faith, Isolation from community","goal": "Reconnect with spiritual community",2 unmodified lines},"π΄ RED - Crisis (Suicidal)": {"name": "Thomas","age": 35,"conditions": "Severe depression, Suicidal ideation","goal": "Immediate crisis intervention and support",2 unmodified lines},"π΄ RED - Severe Hopelessness": {"name": "Jennifer","age": 48,"conditions": "Major depression, Complete hopelessness","goal": "Crisis stabilization and professional support",2 unmodified lines},"π΄ RED - Spiritual Crisis": {"name": "Christopher","age": 52,"conditions": "Moral injury, Spiritual crisis, Anger at God","goal": "Spiritual crisis intervention and healing",2 unmodified lines},"Cardiac Patient": {"name": "John","age": 65,"conditions": "Coronary artery disease, Hypertension, Hyperlipidemia","goal": "Cardiac rehabilitation and risk factor management",2 unmodified lines},"Diabetic Patient": {"name": "Maria","age": 58,"conditions": "Type 2 Diabetes, Obesity, Hypertension","goal": "Blood sugar control and weight management",2 unmodified lines},"Post-Surgery Recovery": {"name": "Alex","age": 45,"conditions": "Post-surgical recovery, Pain management","goal": "Safe return to normal activities",2 unmodified lines},"Mental Health Focus": {"name": "Emma","age": 35,"conditions": "Depression, Anxiety, Sedentary lifestyle","goal": "Mood improvement through activity",2 unmodified lines},"Elderly Patient": {"name": "Robert","age": 78,"conditions": "Arthritis, Osteoporosis, Hypertension","goal": "Maintain independence and mobility",2 unmodified lines},"Athletic Patient": {"name": "Sarah","age": 32,"conditions": "Mild hypertension, Overtraining syndrome","goal": "Optimize performance and prevent injury",7 unmodified linesstatus = f"""<div style="padding: 1em; background-color: #ecfdf5; border-left: 4px solid #10b981; border-radius: 4px;"><h4 style="color: #059669; margin-top: 0;">β Profile Loaded</h4><p><strong>Patient:</strong> {profile['name']}, {profile['age']} years old</p><p><strong>Profile:</strong> {profile_name}</p><p style="margin-bottom: 0;">Profile data loaded into settings. Review and save if needed.</p></div>"""return (profile['name'],profile['age'],profile['conditions'],profile['goal'],2 unmodified linesstatus)def save_profile(name: str, age: float, conditions: str, goal: str, exercise: str, limitations: str):"""Save current profile settings."""if not name.strip():return """<div style="padding: 1em; background-color: #fef2f2; border-left: 4px solid #dc2626; border-radius: 4px;"><h4 style="color: #dc2626; margin-top: 0;">β Error</h4><p style="margin-bottom: 0;">Patient name cannot be empty</p></div>"""status = f"""<div style="padding: 1em; background-color: #ecfdf5; border-left: 4px solid #10b981; border-radius: 4px;"><h4 style="color: #059669; margin-top: 0;">πΎ Profile Saved</h4><p><strong>Patient:</strong> {name}, {int(age)} years old</p><p><strong>Conditions:</strong> {conditions}</p><p><strong>Primary Goal:</strong> {goal}</p><p style="margin-bottom: 0;">Profile settings have been updated for this session.</p>3 unmodified linesdef reset_profile():"""Reset profile to default."""status = """<div style="padding: 1em; background-color: #eff6ff; border-left: 4px solid #3b82f6; border-radius: 4px;"><h4 style="color: #2563eb; margin-top: 0;">π Profile Reset</h4><p><strong>Patient:</strong> Serhii, 52 years old</p><p style="margin-bottom: 0;">Default profile has been restored.</p></div>"""return ("Serhii",52,"Atrial fibrillation, Deep vein thrombosis, Obesity, Hypertension","Weight reduction and cardiovascular fitness improvement",6 unmodified linesload_profile_btn.click(load_profile,inputs=[profile_selector],outputs=[patient_name, patient_age, conditions, primary_goal, exercise_prefs, exercise_limits, profile_status])save_profile_btn.click(save_profile,inputs=[patient_name, patient_age, conditions, primary_goal, exercise_prefs, exercise_limits],outputs=[profile_save_status])reset_profile_btn.click(reset_profile,outputs=[patient_name, patient_age, conditions, primary_goal, exercise_prefs, exercise_limits, profile_save_status])return demo214 unmodified lines215216217218219220221222223224225226227228229230231232233234235236237238202 unmodified lines4414424434444454464474484494504514521498 unmodified lines195119521953195419551956195719581959196013 unmodified lines197419751976197719781979198019816 unmodified lines1988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201648 unmodified lines20652066206720682069207020711 unmodified line207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720981 unmodified line210021012102210321042105210621072108210921108 unmodified lines2119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214410 unmodified lines21552156215721582159216021612 unmodified lines216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422253 unmodified lines2229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225125 unmodified lines22772278227922802281228222839 unmodified lines22932294229522962297229822992300230123022303230423053 unmodified lines23092310231123122313231423152316231723182319232023212322232323242325232623272328105 unmodified lines24342435243624372438243924402 unmodified lines24432444244524462447244824492 unmodified lines24522453245424552456245724582 unmodified lines24612462246324642465246624672 unmodified lines24702471247224732474247524762 unmodified lines24792480248124822483248424852 unmodified lines24882489249024912492249324942 unmodified lines24972498249925002501250225032 unmodified lines25062507250825092510251125122 unmodified lines25152516251725182519252025212 unmodified lines25242525252625272528252925302 unmodified lines25332534253525362537253825392 unmodified lines25422543254425452546254725482 unmodified lines25512552255325542555255625572 unmodified lines25602561256225632564256525667 unmodified lines257425752576257725782579258025812582258325842585258625872 unmodified lines25902591259225932594259525962597259825992600260126022603260426052606260726082609261026113 unmodified lines261526162617261826192620262126222623262426252626262726282629263026312632263326346 unmodified lines264126422643264426452646264726482649265026512652265326542655265626572658214 unmodified lines# Shown only when marking Incorrectwith gr.Row(visible=False) as conv_incorrect_comment_row:with gr.Column(scale=3):gr.Markdown("### Select Correct Classification:")conv_correct_classification = gr.Radio(choices=["π’ Should be GREEN - No distress","π‘ Should be YELLOW - Needs clarification","π΄ Should be RED - Spiritual distress"],label="Correct Classification",interactive=True)conv_incorrect_comment = gr.Textbox(label="Comment (why incorrect / what to fix)",placeholder="Add a short note for this exchange...",lines=3,)with gr.Column(scale=1):conv_save_comment_btn = gr.Button("πΎ Save comment", variant="secondary")with gr.Row():with gr.Column(scale=1):202 unmodified linesvalue="Serhii",interactive=True)patient_phone = gr.Textbox(label="Phone Number",value="",placeholder="(555) 123-4567",interactive=True)patient_age = gr.Number(label="Age",value=52,1498 unmodified linesoriginal_indicators=r.get("original_indicators", []),original_reasoning=r.get("original_reasoning", ""),timestamp=r.get("timestamp"),is_correct=r.get("is_correct"),correct_classification=r.get("correct_classification"),correction_reason=r.get("correction_reason"),verifier_notes=r.get("verifier_notes"),)else:rec = r13 unmodified linescorrect = 0incorrect = 0incorrect_with_comment = 0corrections = {} # Track classification correctionsfor x in records:v = (x.get("is_correct") if isinstance(x, dict) else getattr(x, "is_correct", None))if v is None:6 unmodified linesnote = (x.get("verifier_notes") if isinstance(x, dict) else getattr(x, "verifier_notes", None))if note and str(note).strip():incorrect_with_comment += 1# Track classification correctionsoriginal_class = (x.get("original_classification") if isinstance(x, dict) else getattr(x, "original_classification", ""))correct_class = (x.get("correct_classification") if isinstance(x, dict) else getattr(x, "correct_classification", None))if original_class and correct_class:correction_key = f"{original_class}β{correct_class}"corrections[correction_key] = corrections.get(correction_key, 0) + 1stats_parts = [f"<div><strong>Reviewed:</strong> {reviewed}/{len(records)}</div>",f"<div><strong>β Correct:</strong> {correct}</div>",f"<div><strong>β Incorrect:</strong> {incorrect}</div>",f"<div><strong>π Incorrect w/ comment:</strong> {incorrect_with_comment}</div>"]# Add correction breakdown if any corrections existif corrections:correction_text = ", ".join([f"{k}: {v}" for k, v in corrections.items()])stats_parts.append(f"<div><strong>π Corrections:</strong> {correction_text}</div>")stats = ("<div style='display:flex; gap:12px; flex-wrap:wrap;'>"+ "".join(stats_parts) +"</div>")return html, pos, stats48 unmodified linesfieldnames = ["session_id","patient_name","patient_phone","verifier_name","start_time","exchange_number",1 unmodified line"original_classification","original_confidence","is_correct","correct_classification","verifier_notes","user_message","assistant_response","provider_summary",]with open(export_path, "w", encoding="utf-8", newline="") as f:w = csv.DictWriter(f, fieldnames=fieldnames)w.writeheader()for r in records or []:# Include provider_summary only for RED casesprovider_summary = ""if r.get("original_classification", "").upper() == "RED":provider_summary = r.get("provider_summary") or ""row = {"session_id": (meta or {}).get("session_id"),"patient_name": (meta or {}).get("patient_name"),"patient_phone": (meta or {}).get("patient_phone") or "","verifier_name": (meta or {}).get("verifier_name"),"start_time": (meta or {}).get("start_time"),"exchange_number": r.get("exchange_number"),1 unmodified line"original_classification": r.get("original_classification"),"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"),"provider_summary": provider_summary,}w.writerow(row)return export_path8 unmodified linesmanager = ConversationVerificationManager()vs = manager.create_verification_session(session.app_instance.conversation_logger, "Medical Professional")# Get patient phone from app if availablepatient_phone = ""if hasattr(session.app_instance, 'patient_info'):patient_phone = session.app_instance.patient_info.get("phone") or ""meta = {"session_id": vs.session_id,"patient_name": vs.patient_name,"patient_phone": patient_phone,"verifier_name": vs.verifier_name,"start_time": vs.start_time.isoformat() if hasattr(vs, "start_time") else None,}# Get provider summary if available (for RED cases)provider_summary_text = ""if hasattr(session.app_instance, 'get_last_provider_summary'):summary = session.app_instance.get_last_provider_summary()if summary and hasattr(session.app_instance, 'provider_summary_generator'):provider_summary_text = session.app_instance.provider_summary_generator.format_for_export(summary)records_as_dicts = [{"exchange_id": r.exchange_id,10 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_records]2 unmodified linesdef _mark_conv_correct(records: list, idx: int):if not records:return records, idx, "", "", "", gr.update(visible=False), "", ""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, ""def _mark_conv_incorrect(records: list, idx: int):if not records:return records, idx, "", "", "", gr.update(visible=False), "", ""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)# Get existing correct_classification if anyexisting_classification = ""if isinstance(records[idx], dict):correct_class = records[idx].get("correct_classification")if correct_class:# Map back to display textreverse_map = {"GREEN": "π’ Should be GREEN - No distress","YELLOW": "π‘ Should be YELLOW - Needs clarification","RED": "π΄ Should be RED - Spiritual distress"}existing_classification = reverse_map.get(correct_class, "")return records, idx, "β Marked incorrect", html, pos, stats, row_upd, note_val, existing_classificationdef _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), "", ""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","π‘ Should be YELLOW - Needs clarification": "YELLOW","π΄ 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, ""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), "", ""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)# Get existing correct_classification if anyexisting_classification = ""if isinstance(records[idx], dict):correct_class = records[idx].get("correct_classification")if correct_class:# Map back to display textreverse_map = {"GREEN": "π’ Should be GREEN - No distress","YELLOW": "π‘ Should be YELLOW - Needs clarification","RED": "π΄ Should be RED - Spiritual distress"}existing_classification = reverse_map.get(correct_class, "")return idx, html, pos, stats, row_upd, note_val, existing_classificationgenerate_conv_verification_btn.click(_generate_conv_verification,25 unmodified linesconv_stats,conv_incorrect_comment_row,conv_incorrect_comment,conv_correct_classification,])9 unmodified linesconv_stats,conv_incorrect_comment_row,conv_incorrect_comment,conv_correct_classification,])conv_save_comment_btn.click(_save_incorrect_comment,inputs=[conv_verify_records, conv_verify_index, conv_incorrect_comment, conv_correct_classification],outputs=[conv_verify_records,conv_verify_index,3 unmodified linesconv_stats,conv_incorrect_comment_row,conv_incorrect_comment,conv_correct_classification,])conv_prev_btn.click(lambda records, idx: _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: _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])# Refresh conversation stats105 unmodified linesprofiles = {"Default (Serhii)": {"name": "Serhii","phone": "(555) 123-4567","age": 52,"conditions": "Atrial fibrillation, Deep vein thrombosis, Obesity, Hypertension","goal": "Weight reduction and cardiovascular fitness improvement",2 unmodified lines},"π’ GREEN - Healthy": {"name": "James","phone": "(555) 234-5678","age": 40,"conditions": "No chronic conditions, Excellent health","goal": "Maintain fitness and wellness",2 unmodified lines},"π‘ YELLOW - Mild Distress": {"name": "Lisa","phone": "(555) 345-6789","age": 45,"conditions": "Hypertension, Mild anxiety, Sleep issues","goal": "Manage stress and improve sleep quality",2 unmodified lines},"π‘ YELLOW - Grief & Loss": {"name": "Michael","phone": "(555) 456-7890","age": 58,"conditions": "Recent loss of spouse, Mild depression","goal": "Process grief and rebuild routine",2 unmodified lines},"π‘ YELLOW - Existential Questions": {"name": "Patricia","phone": "(555) 567-8901","age": 62,"conditions": "Chronic pain, Questioning life purpose","goal": "Find meaning and manage chronic pain",2 unmodified lines},"π‘ YELLOW - Spiritual Disconnection": {"name": "David","phone": "(555) 678-9012","age": 55,"conditions": "Loss of faith, Isolation from community","goal": "Reconnect with spiritual community",2 unmodified lines},"π΄ RED - Crisis (Suicidal)": {"name": "Thomas","phone": "(555) 789-0123","age": 35,"conditions": "Severe depression, Suicidal ideation","goal": "Immediate crisis intervention and support",2 unmodified lines},"π΄ RED - Severe Hopelessness": {"name": "Jennifer","phone": "(555) 890-1234","age": 48,"conditions": "Major depression, Complete hopelessness","goal": "Crisis stabilization and professional support",2 unmodified lines},"π΄ RED - Spiritual Crisis": {"name": "Christopher","phone": "(555) 901-2345","age": 52,"conditions": "Moral injury, Spiritual crisis, Anger at God","goal": "Spiritual crisis intervention and healing",2 unmodified lines},"Cardiac Patient": {"name": "John","phone": "(555) 012-3456","age": 65,"conditions": "Coronary artery disease, Hypertension, Hyperlipidemia","goal": "Cardiac rehabilitation and risk factor management",2 unmodified lines},"Diabetic Patient": {"name": "Maria","phone": "(555) 111-2222","age": 58,"conditions": "Type 2 Diabetes, Obesity, Hypertension","goal": "Blood sugar control and weight management",2 unmodified lines},"Post-Surgery Recovery": {"name": "Alex","phone": "(555) 222-3333","age": 45,"conditions": "Post-surgical recovery, Pain management","goal": "Safe return to normal activities",2 unmodified lines},"Mental Health Focus": {"name": "Emma","phone": "(555) 333-4444","age": 35,"conditions": "Depression, Anxiety, Sedentary lifestyle","goal": "Mood improvement through activity",2 unmodified lines},"Elderly Patient": {"name": "Robert","phone": "(555) 444-5555","age": 78,"conditions": "Arthritis, Osteoporosis, Hypertension","goal": "Maintain independence and mobility",2 unmodified lines},"Athletic Patient": {"name": "Sarah","phone": "(555) 555-6666","age": 32,"conditions": "Mild hypertension, Overtraining syndrome","goal": "Optimize performance and prevent injury",7 unmodified linesstatus = f"""<div style="padding: 1em; background-color: #ecfdf5; border-left: 4px solid #10b981; border-radius: 4px;"><h4 style="color: #059669; margin-top: 0;">β Profile Loaded</h4><p><strong>Patient:</strong> {profile['name']}, {profile['age']} years old</p><p><strong>Phone:</strong> {profile.get('phone', 'Not provided')}</p><p><strong>Profile:</strong> {profile_name}</p><p style="margin-bottom: 0;">Profile data loaded into settings. Review and save if needed.</p></div>"""return (profile['name'],profile.get('phone', ''),profile['age'],profile['conditions'],profile['goal'],2 unmodified linesstatus)def save_profile(name: str, phone: str, age: float, conditions: str, goal: str, exercise: str, limitations: str):"""Save current profile settings and update app patient info."""if not name.strip():return """<div style="padding: 1em; background-color: #fef2f2; border-left: 4px solid #dc2626; border-radius: 4px;"><h4 style="color: #dc2626; margin-top: 0;">β Error</h4><p style="margin-bottom: 0;">Patient name cannot be empty</p></div>"""# Update app's patient info for provider summariesif hasattr(app, 'set_patient_info'):app.set_patient_info(name=name.strip(), phone=phone.strip() if phone else None)status = f"""<div style="padding: 1em; background-color: #ecfdf5; border-left: 4px solid #10b981; border-radius: 4px;"><h4 style="color: #059669; margin-top: 0;">πΎ Profile Saved</h4><p><strong>Patient:</strong> {name}, {int(age)} years old</p><p><strong>Phone:</strong> {phone if phone else 'Not provided'}</p><p><strong>Conditions:</strong> {conditions}</p><p><strong>Primary Goal:</strong> {goal}</p><p style="margin-bottom: 0;">Profile settings have been updated for this session.</p>3 unmodified linesdef reset_profile():"""Reset profile to default."""# Reset app's patient infoif hasattr(app, 'set_patient_info'):app.set_patient_info(name="Serhii", phone="(555) 123-4567")status = """<div style="padding: 1em; background-color: #eff6ff; border-left: 4px solid #3b82f6; border-radius: 4px;"><h4 style="color: #2563eb; margin-top: 0;">π Profile Reset</h4><p><strong>Patient:</strong> Serhii, 52 years old</p><p><strong>Phone:</strong> (555) 123-4567</p><p style="margin-bottom: 0;">Default profile has been restored.</p></div>"""return ("Serhii","(555) 123-4567",52,"Atrial fibrillation, Deep vein thrombosis, Obesity, Hypertension","Weight reduction and cardiovascular fitness improvement",6 unmodified linesload_profile_btn.click(load_profile,inputs=[profile_selector],outputs=[patient_name, patient_phone, patient_age, conditions, primary_goal, exercise_prefs, exercise_limits, profile_status])save_profile_btn.click(save_profile,inputs=[patient_name, patient_phone, patient_age, conditions, primary_goal, exercise_prefs, exercise_limits],outputs=[profile_save_status])reset_profile_btn.click(reset_profile,outputs=[patient_name, patient_phone, patient_age, conditions, primary_goal, exercise_prefs, exercise_limits, profile_save_status])return demo