Spaces:
Sleeping
Sleeping
| # 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 | |
| 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 | |
| # ========================================================================== | |
| 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=[] | |
| )) | |
| def get_tooltip(cls, element: str) -> str: | |
| """Get tooltip text for a UI element.""" | |
| return cls.TOOLTIPS.get(element, "") | |
| 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=[] | |
| )) | |
| 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." | |
| }) | |
| def get_workflow_guide(cls, mode: str) -> List[tuple]: | |
| """Get workflow steps for a mode.""" | |
| return cls.WORKFLOW_GUIDES.get(mode, []) | |
| 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": []} | |
| ) | |
| 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""" | |
| <div style="font-family: system-ui; padding: 1em; background-color: #f8fafc; border-radius: 8px;"> | |
| <h3 style="margin-top: 0; color: #1e293b;">{content.title}</h3> | |
| <p style="color: #475569;">{content.description}</p> | |
| <h4 style="color: #334155;">π‘ Tips</h4> | |
| <ul style="color: #475569; padding-left: 1.5em;"> | |
| """ | |
| for tip in content.tips: | |
| html += f"<li>{tip}</li>" | |
| html += """ | |
| </ul> | |
| <h4 style="color: #334155;">π Workflow</h4> | |
| <ol style="color: #475569; padding-left: 1.5em;"> | |
| """ | |
| for step, description in workflow: | |
| html += f"<li><strong>{step}:</strong> {description}</li>" | |
| html += """ | |
| </ol> | |
| </div> | |
| """ | |
| return html | |
| 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 = """ | |
| <div style="font-family: system-ui; padding: 1em; background-color: #f0f9ff; border-radius: 8px; border-left: 4px solid #3b82f6;"> | |
| <h3 style="margin-top: 0; color: #1e40af;">π File Format Requirements</h3> | |
| <h4 style="color: #1e40af;">Required Columns</h4> | |
| <table style="width: 100%; border-collapse: collapse; margin-bottom: 1em;"> | |
| <tr style="background-color: #dbeafe;"> | |
| <th style="padding: 0.5em; text-align: left; border: 1px solid #93c5fd;">Column</th> | |
| <th style="padding: 0.5em; text-align: left; border: 1px solid #93c5fd;">Alternative Names</th> | |
| <th style="padding: 0.5em; text-align: left; border: 1px solid #93c5fd;">Description</th> | |
| </tr> | |
| <tr> | |
| <td style="padding: 0.5em; border: 1px solid #93c5fd;"><code>message</code></td> | |
| <td style="padding: 0.5em; border: 1px solid #93c5fd;">text, patient_message, content</td> | |
| <td style="padding: 0.5em; border: 1px solid #93c5fd;">Patient message text</td> | |
| </tr> | |
| <tr> | |
| <td style="padding: 0.5em; border: 1px solid #93c5fd;"><code>expected_classification</code></td> | |
| <td style="padding: 0.5em; border: 1px solid #93c5fd;">classification, label</td> | |
| <td style="padding: 0.5em; border: 1px solid #93c5fd;">Expected result (GREEN/YELLOW/RED)</td> | |
| </tr> | |
| </table> | |
| <h4 style="color: #1e40af;">Valid Classification Values</h4> | |
| <p style="color: #1e3a8a;"> | |
| <span style="background-color: #dcfce7; padding: 0.25em 0.5em; border-radius: 4px; margin-right: 0.5em;">GREEN</span> | |
| <span style="background-color: #fef3c7; padding: 0.25em 0.5em; border-radius: 4px; margin-right: 0.5em;">YELLOW</span> | |
| <span style="background-color: #fee2e2; padding: 0.25em 0.5em; border-radius: 4px;">RED</span> | |
| <br><small>(case-insensitive)</small> | |
| </p> | |
| <h4 style="color: #1e40af;">CSV Example</h4> | |
| <pre style="background-color: #1e293b; color: #e2e8f0; padding: 1em; border-radius: 4px; overflow-x: auto;"> | |
| 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</pre> | |
| <h4 style="color: #1e40af;">Tips</h4> | |
| <ul style="color: #1e3a8a;"> | |
| <li>Download a template file to see the exact format</li> | |
| <li>CSV files can use comma, semicolon, or tab as delimiter</li> | |
| <li>XLSX files must have data on the first worksheet</li> | |
| <li>Use UTF-8 encoding for special characters</li> | |
| </ul> | |
| </div> | |
| """ | |
| return html | |
| def format_troubleshooting_html(cls) -> str: | |
| """Generate HTML troubleshooting guide.""" | |
| html = """ | |
| <div style="font-family: system-ui; padding: 1em; background-color: #fef2f2; border-radius: 8px; border-left: 4px solid #dc2626;"> | |
| <h3 style="margin-top: 0; color: #991b1b;">π§ Troubleshooting Guide</h3> | |
| """ | |
| 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""" | |
| <h4 style="color: #991b1b; margin-top: 1em;">{category}</h4> | |
| <dl style="margin: 0;"> | |
| """ | |
| for error_type in error_types: | |
| error = cls.get_error_help(error_type) | |
| html += f""" | |
| <dt style="font-weight: bold; color: #7f1d1d;">β {error['message']}</dt> | |
| <dd style="margin-left: 1em; margin-bottom: 0.5em; color: #991b1b;"> | |
| π‘ {error['suggestion']} | |
| </dd> | |
| """ | |
| html += "</dl>" | |
| html += """ | |
| </div> | |
| """ | |
| 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) | |