Spaces:
Sleeping
Sleeping
File size: 21,829 Bytes
7bbd836 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 |
# 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"""
<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
@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 = """
<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
@classmethod
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)
|