# help_system.py """ Help System for Enhanced Verification Modes. Provides tooltips, guidance text, format examples, and troubleshooting information for all verification modes. Requirements: 8.5, 12.5 """ from typing import Dict, List, Optional from dataclasses import dataclass @dataclass class HelpContent: """Container for help content.""" title: str description: str tips: List[str] examples: Optional[List[str]] = None class HelpSystem: """ Centralized help system for enhanced verification modes. Provides consistent help content, tooltips, and guidance across all modes. """ # ========================================================================== # MODE DESCRIPTIONS # ========================================================================== MODE_DESCRIPTIONS = { "enhanced_dataset": HelpContent( title="📊 Enhanced Dataset Mode", description="Work with existing test datasets with full editing capabilities. " "Perfect for systematic testing with prepared data.", tips=[ "Select a dataset to view its details and message breakdown", "Edit datasets to add, modify, or remove test cases", "Create new datasets from templates for quick setup", "All changes are saved automatically with version history" ], examples=[ "Testing classifier accuracy on curated spiritual distress examples", "Building custom datasets for specific patient populations", "Iterating on test cases based on verification results" ] ), "manual_input": HelpContent( title="✏️ Manual Input Mode", description="Enter individual messages for immediate classification and verification. " "Ideal for quick testing of specific scenarios or edge cases.", tips=[ "Enter any patient message to see instant classification", "Verify each result as correct or incorrect", "Build up a session of results for export", "Great for exploring edge cases and unusual messages" ], examples=[ "Testing specific phrases that might indicate distress", "Exploring how the classifier handles ambiguous messages", "Quick verification of suspected misclassifications" ] ), "file_upload": HelpContent( title="📁 File Upload Mode", description="Upload CSV or XLSX files for batch processing and verification. " "Best for large-scale testing with pre-prepared test cases.", tips=[ "Download templates to see the required format", "Files are validated before processing begins", "Pause and resume batch processing at any time", "Export comprehensive results when complete" ], examples=[ "Processing hundreds of test cases from research data", "Validating classifier against external datasets", "Batch verification of historical patient messages" ] ) } # ========================================================================== # TOOLTIPS # ========================================================================== TOOLTIPS = { # Session controls "start_session": "Begin a new verification session. Your name is required for tracking.", "complete_session": "Mark this session as complete. No further changes will be allowed.", "pause_session": "Pause the current session. Progress is saved automatically.", "resume_session": "Continue from where you left off.", # Classification "classify_message": "Send the message to the AI classifier for analysis.", "correct_button": "The classifier's decision matches the expected result.", "incorrect_button": "The classifier made an error. Select the correct classification.", "confidence_score": "How confident the classifier is in its decision (0-100%).", "indicators": "Specific phrases or patterns that influenced the classification.", # Dataset operations "edit_dataset": "Modify test cases in this dataset.", "add_test_case": "Add a new message with expected classification.", "delete_test_case": "Remove this test case. This action requires confirmation.", "save_dataset": "Save all changes to the dataset.", "create_dataset": "Create a new empty dataset or from a template.", # File upload "upload_file": "Select a CSV or XLSX file with test messages.", "process_file": "Validate and parse the uploaded file.", "download_template": "Get a sample file showing the required format.", "start_batch": "Begin processing all messages in the file.", # Export "export_csv": "Download results as a comma-separated values file.", "export_xlsx": "Download results as an Excel workbook with multiple sheets.", "export_json": "Download results as structured JSON data.", # Progress "progress_bar": "Shows how many messages have been processed.", "accuracy_display": "Running accuracy based on verified results.", "processing_speed": "Average messages processed per minute." } # ========================================================================== # FILE FORMAT HELP # ========================================================================== FILE_FORMAT_HELP = { "csv": HelpContent( title="CSV File Format", description="Comma-separated values file with test messages and expected classifications.", tips=[ "First row must contain column headers", "Supported delimiters: comma (,), semicolon (;), tab", "Use UTF-8 encoding for special characters", "Wrap text with commas in double quotes" ], examples=[ 'message,expected_classification', '"I feel hopeless about my situation",RED', '"Thank you for your help today",GREEN', '"I\'m not sure what to believe anymore",YELLOW' ] ), "xlsx": HelpContent( title="XLSX File Format", description="Excel workbook with test messages on the first worksheet.", tips=[ "Data must be on the first worksheet", "First row must contain column headers", "No merged cells in the data area", "Avoid formulas - use plain text values" ], examples=[ "Column A: message (patient message text)", "Column B: expected_classification (GREEN/YELLOW/RED)" ] ) } REQUIRED_COLUMNS = { "message": ["message", "text", "patient_message", "content"], "classification": ["expected_classification", "classification", "label", "expected_label"] } VALID_CLASSIFICATIONS = ["GREEN", "YELLOW", "RED", "green", "yellow", "red"] # ========================================================================== # ERROR MESSAGES # ========================================================================== ERROR_MESSAGES = { # File errors "file_not_found": { "message": "File not found", "suggestion": "Please select a file and try again." }, "invalid_format": { "message": "Invalid file format", "suggestion": "Only CSV and XLSX files are supported. Please check your file type." }, "missing_columns": { "message": "Required columns not found", "suggestion": "Your file must have 'message' and 'expected_classification' columns. " "Download a template to see the correct format." }, "invalid_classification": { "message": "Invalid classification value", "suggestion": "Classification must be GREEN, YELLOW, or RED (case-insensitive)." }, "empty_message": { "message": "Empty message found", "suggestion": "All messages must contain text. Remove or fill in empty rows." }, "file_too_large": { "message": "File is too large", "suggestion": "Maximum file size is 10MB. Split your data into smaller files." }, # Session errors "no_session": { "message": "No active session", "suggestion": "Please start a new session by entering your name and clicking 'Start Session'." }, "session_complete": { "message": "Session is already complete", "suggestion": "Start a new session to continue verification." }, "name_required": { "message": "Name is required", "suggestion": "Please enter your name to start a session." }, # Classification errors "classification_failed": { "message": "Classification service error", "suggestion": "The AI service is temporarily unavailable. Click 'Retry' or try again later." }, "network_error": { "message": "Network connection error", "suggestion": "Check your internet connection and try again." }, # Export errors "export_failed": { "message": "Export failed", "suggestion": "Try a different format or check if there are results to export." }, "no_results": { "message": "No results to export", "suggestion": "Complete at least one verification before exporting." } } # ========================================================================== # WORKFLOW GUIDES # ========================================================================== WORKFLOW_GUIDES = { "enhanced_dataset": [ ("1. Select Dataset", "Choose a dataset from the dropdown list"), ("2. Review Details", "Check message count and classification breakdown"), ("3. Edit (Optional)", "Add, modify, or remove test cases as needed"), ("4. Start Verification", "Enter your name and begin the verification process"), ("5. Verify Messages", "Mark each classification as correct or incorrect"), ("6. Export Results", "Download your results in CSV, XLSX, or JSON format") ], "manual_input": [ ("1. Start Session", "Enter your name and click 'Start Session'"), ("2. Enter Message", "Type or paste a patient message"), ("3. Classify", "Click 'Classify Message' to get AI classification"), ("4. Verify", "Mark the result as correct or incorrect"), ("5. Repeat", "Continue with more messages as needed"), ("6. Complete & Export", "Finish the session and download results") ], "file_upload": [ ("1. Prepare File", "Create a CSV/XLSX with messages and expected classifications"), ("2. Upload", "Select your file and click 'Process File'"), ("3. Review Preview", "Check the validation results and data preview"), ("4. Start Processing", "Enter your name and begin batch processing"), ("5. Verify Batch", "Review and verify each message in sequence"), ("6. Export Results", "Download comprehensive results when complete") ] } # ========================================================================== # CLASSIFICATION EXPLANATIONS # ========================================================================== CLASSIFICATION_EXPLANATIONS = { "green": { "label": "🟢 GREEN - No Distress", "description": "No indicators of spiritual distress detected.", "examples": [ "General health inquiries", "Positive or neutral statements", "Routine communication" ] }, "yellow": { "label": "🟡 YELLOW - Potential Distress", "description": "Some indicators suggest possible spiritual concerns that warrant follow-up.", "examples": [ "Mild expressions of uncertainty", "Questions about meaning or purpose", "Subtle signs of spiritual struggle" ] }, "red": { "label": "🔴 RED - Severe Distress", "description": "Clear indicators of significant spiritual distress requiring attention.", "examples": [ "Expressions of hopelessness", "Existential crisis indicators", "Severe spiritual pain or guilt" ] } } # ========================================================================== # PUBLIC METHODS # ========================================================================== @classmethod def get_mode_description(cls, mode: str) -> HelpContent: """Get description for a verification mode.""" return cls.MODE_DESCRIPTIONS.get(mode, HelpContent( title="Unknown Mode", description="Mode not recognized.", tips=[] )) @classmethod def get_tooltip(cls, element: str) -> str: """Get tooltip text for a UI element.""" return cls.TOOLTIPS.get(element, "") @classmethod def get_file_format_help(cls, format_type: str) -> HelpContent: """Get help content for a file format.""" return cls.FILE_FORMAT_HELP.get(format_type, HelpContent( title="Unknown Format", description="Format not recognized.", tips=[] )) @classmethod def get_error_help(cls, error_type: str) -> Dict[str, str]: """Get error message and suggestion for an error type.""" return cls.ERROR_MESSAGES.get(error_type, { "message": "An error occurred", "suggestion": "Please try again or contact support." }) @classmethod def get_workflow_guide(cls, mode: str) -> List[tuple]: """Get workflow steps for a mode.""" return cls.WORKFLOW_GUIDES.get(mode, []) @classmethod def get_classification_explanation(cls, classification: str) -> Dict[str, any]: """Get explanation for a classification level.""" return cls.CLASSIFICATION_EXPLANATIONS.get( classification.lower(), {"label": "Unknown", "description": "Classification not recognized.", "examples": []} ) @classmethod def format_mode_help_html(cls, mode: str) -> str: """Generate HTML help content for a mode.""" content = cls.get_mode_description(mode) workflow = cls.get_workflow_guide(mode) html = f"""

{content.title}

{content.description}

💡 Tips

📋 Workflow

    """ for step, description in workflow: html += f"
  1. {step}: {description}
  2. " html += """
""" return html @classmethod def format_file_format_help_html(cls) -> str: """Generate HTML help for file formats.""" csv_help = cls.get_file_format_help("csv") xlsx_help = cls.get_file_format_help("xlsx") html = """

📄 File Format Requirements

Required Columns

Column Alternative Names Description
message text, patient_message, content Patient message text
expected_classification classification, label Expected result (GREEN/YELLOW/RED)

Valid Classification Values

GREEN YELLOW RED
(case-insensitive)

CSV Example

message,expected_classification
"I feel hopeless about my situation",RED
"Thank you for your help today",GREEN
"I'm not sure what to believe anymore",YELLOW

Tips

""" return html @classmethod def format_troubleshooting_html(cls) -> str: """Generate HTML troubleshooting guide.""" html = """

🔧 Troubleshooting Guide

""" categories = { "File Upload Issues": ["file_not_found", "invalid_format", "missing_columns", "invalid_classification", "empty_message"], "Session Issues": ["no_session", "session_complete", "name_required"], "Classification Issues": ["classification_failed", "network_error"], "Export Issues": ["export_failed", "no_results"] } for category, error_types in categories.items(): html += f"""

{category}

""" for error_type in error_types: error = cls.get_error_help(error_type) html += f"""
❌ {error['message']}
💡 {error['suggestion']}
""" html += "
" html += """
""" return html # ========================================================================== # GRADIO INTEGRATION HELPERS # ========================================================================== def create_help_accordion(mode: str) -> str: """Create help content for Gradio accordion.""" return HelpSystem.format_mode_help_html(mode) def create_format_help_accordion() -> str: """Create file format help for Gradio accordion.""" return HelpSystem.format_file_format_help_html() def create_troubleshooting_accordion() -> str: """Create troubleshooting guide for Gradio accordion.""" return HelpSystem.format_troubleshooting_html() def get_tooltip_for_element(element_id: str) -> str: """Get tooltip text for a specific UI element.""" return HelpSystem.get_tooltip(element_id)