"""
Help Dialog
Displays usage instructions and help information for the DuDONG application.
"""
from PyQt5.QtWidgets import (QDialog, QVBoxLayout, QLabel, QPushButton,
QScrollArea, QWidget, QTabWidget)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont
from resources.styles import STANDARD_BUTTON_STYLE, TAB_WIDGET_STYLE
class HelpDialog(QDialog):
"""
Help dialog window showing usage instructions.
Displays:
- Getting started guide
- Feature descriptions
- Usage instructions for each tool
- Troubleshooting tips
- Keyboard shortcuts
"""
def __init__(self, parent=None):
"""
Initialize the help dialog.
Args:
parent: Parent widget
"""
super().__init__(parent)
self.setWindowTitle("DuDONG Help")
self.setMinimumSize(950, 650)
self.init_ui()
def init_ui(self):
"""Initialize the UI components."""
layout = QVBoxLayout()
layout.setContentsMargins(10, 10, 10, 10)
layout.setSpacing(10)
# Title
title = QLabel("DuDONG Help & Documentation")
title.setFont(QFont("Arial", 16, QFont.Bold))
title.setAlignment(Qt.AlignCenter)
title.setStyleSheet("color: #2c3e50; margin: 5px;")
layout.addWidget(title)
# Tab widget for different help sections
tabs = QTabWidget()
tabs.setStyleSheet(TAB_WIDGET_STYLE)
tabs.setTabPosition(QTabWidget.North)
tabs.setMovable(False)
tabs.setDocumentMode(False)
# Getting Started Tab
tabs.addTab(self._create_getting_started(), "Getting Started")
# Comprehensive Analysis Tab (NEW - Primary workflow)
tabs.addTab(self._create_comprehensive_analysis(), "Analyze Durian")
# System Info Tab
tabs.addTab(self._create_system_info(), "System Requirements")
# Troubleshooting Tab
tabs.addTab(self._create_troubleshooting(), "Troubleshooting")
layout.addWidget(tabs, 1)
# Close button
close_btn = QPushButton("Close")
close_btn.setStyleSheet(STANDARD_BUTTON_STYLE)
close_btn.clicked.connect(self.accept)
layout.addWidget(close_btn, alignment=Qt.AlignRight)
self.setLayout(layout)
def _create_scrollable_content(self, content_text: str) -> QScrollArea:
"""
Create a scrollable text area.
Args:
content_text: HTML formatted text content
Returns:
QScrollArea with content
"""
scroll = QScrollArea()
scroll.setWidgetResizable(True)
scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
label = QLabel(content_text)
label.setWordWrap(True)
label.setTextFormat(Qt.RichText)
label.setStyleSheet("padding: 20px; color: #2c3e50; line-height: 1.6;")
scroll.setWidget(label)
return scroll
def _create_comprehensive_analysis(self) -> QWidget:
"""Create the comprehensive analysis (Analyze Durian) help tab."""
content = """
Comprehensive Durian Analysis
Overview
The "Analyze Durian" feature is DuDONG's primary workflow for comprehensive fruit grading. It combines multiple AI models to analyze different aspects of durian quality, ripeness, and maturity in a single analysis session.
Two Analysis Modes
1. Manual Entry Mode (Current)
Select data files from different camera and sensor sources:
- DSLR Side View (JPG/PNG/BMP) - Plain durian image for defect detection
- DSLR Top View (JPG/PNG/BMP) - Cross-section or top view for locule counting
- Multispectral TIFF (TIF/TIFF) - 12-band multispectral image for maturity analysis
- Thermal CSV (CSV) - Thermal imaging data (future integration)
- Audio WAV (WAV) - Audio recording of knock sound for ripeness classification
At least one input is required. All other inputs are optional.
2. Auto Mode (Future)
Automatically detects and captures data from running camera applications:
- EOS Utility - Canon DSLR capture
- 2nd Look - Multispectral camera capture
- AnalyzIR - Thermal imaging capture
Available Analysis Models
1. Ripeness Classification (Audio)
- Input: Audio WAV file of knock sound
- Processing: Detects individual knocks and averages predictions
- Output: Unripe, Ripe, or Overripe (with confidence %)
2. Defect Detection (RGB Side View)
- Input: Image of durian side view
- Processing: YOLOv8-based defect detection
- Output: No Defects, Minor Defects, or Reject classification
3. Locule Counting (RGB Top View)
- Input: Cross-section or top view image
- Processing: YOLOv8 segmentation to identify and count locules
- Output: Total locule count with color-coded visualization
4. Maturity Classification (Multispectral)
- Input: 12-band multispectral TIFF image
- Processing: Deep learning model analyzes spectral signatures
- Output: Immature, Mature, or Overmature classification
5. Shape Classification (RGB)
- Input: Image of durian
- Processing: YOLO classification model
- Output: Regular or Irregular shape classification
Workflow Steps
- Click "Manual Entry" button on the Dashboard
- In the dialog that opens, select files for desired analyses (at least one required)
- Click "Confirm" to start processing
- System automatically navigates to Reports tab
- Models process inputs in parallel using available GPU
- View comprehensive results with:
- Overall grade (A/B/C)
- Individual model results with confidence scores
- Annotated images and visualizations
- Click "Export PDF" to save detailed report
Understanding the Report
- Overall Grade - Combined assessment: A (best), B (good), C (acceptable)
- Analysis ID - Unique identifier stored in database for future reference
- Individual Results - Each model's prediction with confidence percentage
- Visualizations - Annotated images, spectrograms, and Grad-CAM explanations
- Processing Time - Total time to complete all analyses
Grade Calculation
Overall grade is determined by combining results from all available analyses:
- Grade A: Premium quality - optimal ripeness, no defects, ideal maturity, regular shape
- Grade B: Good quality - acceptable ripeness, minor defects, good maturity
- Grade C: Standard quality - mixed indicators, some defects, acceptable maturity
Tips for Best Results
- Use high-quality images (1920x1080 or higher resolution)
- Ensure good lighting and avoid shadows on durian
- Record audio in a quiet environment with consistent knocking force
- Position durian clearly in the center of images
- Use proper file formats: JPG/PNG for images, WAV for audio, TIFF for multispectral
"""
return self._create_scrollable_content(content)
def _create_getting_started(self) -> QWidget:
"""Create the getting started help tab."""
content = """
Getting Started with DuDONG
Dashboard Overview
The main dashboard is your control center for all durian analysis:
- System Status Panel - View status of all AI models (Ripeness, Quality, Defect, Maturity)
- Quick Actions Panel - Two main buttons:
- Auto Analyze Durian - Automatically detects and captures from camera applications
- Manual Entry - Manually select files from different camera sources
- Recent Results Panel - View and reload your last 5 analyses
- System Information Panel - Monitor performance: uptime, throughput, processing time, and model accuracy
- Live Feeds Panel - Placeholder for future camera integration
Quick Start Workflow
- Click "Manual Entry" on the Dashboard (Auto mode requires running camera apps)
- Select data from available camera sources in the dialog:
- DSLR Side View (optional) - Image for defect detection
- DSLR Top View (optional) - Image for locule counting
- Multispectral TIFF (optional) - For maturity classification
- Audio WAV (optional) - For ripeness classification
- At least one input is required. All other inputs are optional.
- Click Confirm to start analysis
- View comprehensive results in the Reports tab
Navigation
The application has two main tabs:
- Dashboard - Main overview and quick action buttons
- Reports - Detailed analysis results and PDF export
Note: Ripeness, Quality, and Maturity tabs are available for individual model testing.
Understanding Results
- Overall Grade - A/B/C classification based on all analysis results
- Ripeness - Audio-based classification: Unripe, Ripe, or Overripe
- Quality - Defect detection: No Defects, Minor Defects, or Reject
- Maturity - Multispectral-based classification: Immature, Mature, or Overmature
- Shape - Shape classification: Regular or Irregular
- Locule Count - Number of segments detected in top view
"""
return self._create_scrollable_content(content)
def _create_system_info(self) -> QWidget:
"""Create the system requirements tab."""
content = """
System Requirements
Minimum Requirements
- Operating System: Windows 10/11, Linux, or macOS
- Python: 3.9 or higher
- RAM: 8GB minimum, 16GB recommended
- Storage: 10GB free space (includes models and database)
- Display: 1920x1080 resolution or higher for optimal UI
Recommended Configuration
- GPU: NVIDIA GPU with CUDA 12.8 support (highly recommended)
- VRAM: 4GB VRAM or more for fast processing
- RAM: 32GB for batch processing multiple analyses
- CPU: Multi-core processor (8+ cores) for parallel processing
- SSD: NVMe SSD for faster model loading
GPU Acceleration Setup
For optimal performance with NVIDIA GPU:
- Install latest NVIDIA GPU drivers
- Install CUDA Toolkit 12.8
- Install cuDNN 9.x for CUDA 12.x
- Verify installation: Check System Info panel shows GPU status as "Active"
Required Dependencies
- PyQt5 - GUI framework
- TensorFlow 2.17+ - Deep learning (audio model)
- PyTorch - Deep learning (YOLO models)
- Ultralytics YOLO - Object detection and segmentation
- OpenCV 4.10+ - Image processing
- NumPy - Numerical computations
- SciPy - Signal processing
- Matplotlib - Visualization
- Librosa - Audio analysis
- Pillow - Image handling
Model Files Required
All model files must be present in the project directory:
- models/audio/best_model_mel_spec_grouped.keras - Ripeness audio model
- best.pt - Defect detection model (YOLOv8)
- locule.pt - Locule segmentation model (YOLOv8)
- models/multispectral/maturity/final_model.pt - Maturity classification model
- shape.pt - Shape classification model (YOLOv8)
Database Setup
- Location: data/database.db
- Automatic: Database is created automatically on first run
- Storage: Stores all analysis results, input files, and visualizations
- Size: Grows with number of analyses (typically 100MB per 1000 analyses)
Disk Space Estimates
- Model files: ~2GB
- Application: ~500MB
- Database: Grows with analyses (~100MB per 1000 analyses)
- Temporary files: ~100MB
- Total: Plan for 10GB+ free space for safe operation
Performance Tips
- GPU: Use GPU for 5-10x faster processing (if available)
- Memory: Close other applications to free RAM
- SSD: Install on SSD for faster model loading
- Cooling: Ensure adequate ventilation for GPU during batch processing
- Batch: Process multiple analyses sequentially, not simultaneously
Troubleshooting System Issues
- GPU Not Detected: Check CUDA installation and PyTorch GPU support
- Out of Memory: Close other applications or process smaller batches
- Slow Processing: Enable GPU acceleration or reduce image resolution
- Models Not Loading: Verify model files exist and have correct permissions
- Database Errors: Check disk space and file system permissions
Checking System Status
In the Dashboard, the System Info Panel displays:
- Application uptime
- Daily analysis count
- Average processing time
- Model accuracy statistics
- GPU status (in status bar)
- Number of loaded models
"""
return self._create_scrollable_content(content)
def _create_troubleshooting(self) -> QWidget:
"""Create the troubleshooting tab."""
content = """
Troubleshooting
Common Issues
1. Models Not Loading at Startup
Problem: System Status shows models as "offline" or displays error messages
Solutions:
- Verify all model files exist in correct locations
- Check file permissions (models should be readable)
- Ensure sufficient disk space (at least 10GB free)
- Try deleting and re-downloading model files
- Check console output for specific error messages
2. GPU Not Detected
Problem: Status bar shows "GPU: N/A" instead of "GPU: Active"
Solutions:
- Install/update NVIDIA GPU drivers to latest version
- Install CUDA Toolkit 12.8 (matching TensorFlow/PyTorch versions)
- Reinstall PyTorch with CUDA support: pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu128
- Verify CUDA availability in Python:
import torch; print(torch.cuda.is_available())
- Check GPU memory usage with nvidia-smi command
3. "Manual Entry" Dialog Won't Open
Problem: Clicking Manual Entry button has no effect
Solutions:
- Ensure no processing is currently active
- Try clicking the button again (sometimes needs 2 clicks)
- Restart the application
- Check console for error messages
4. Processing Hangs or Freezes
Problem: Application becomes unresponsive during analysis
Solutions:
- Wait longer (first run can take 30+ seconds for model loading)
- Close other memory-heavy applications
- Reduce image resolution or use smaller files
- Check available RAM (needs at least 4GB free)
- If truly frozen, force close and restart
5. Reports Tab Shows "No Analysis Yet"
Problem: After clicking Confirm, Reports tab doesn't update with results
Solutions:
- Wait for processing to complete (check status bar)
- Verify at least one input file was selected
- Check console for model processing errors
- Try with a different input file
- Ensure input files are valid and uncorrupted
6. Inaccurate Predictions
Problem: Results don't match expected output
Solutions:
- Verify input quality (good lighting, clear images, quality audio)
- Follow input guidelines (resolution, format, positioning)
- Use consistent data format and preprocessing
- Try multiple samples to verify consistency
- Report systematic errors to development team with examples
7. PDF Export Fails
Problem: "Export PDF" button doesn't work or file doesn't save
Solutions:
- Ensure reportlab library is installed:
pip install reportlab
- Check disk space for output file
- Verify write permissions in destination folder
- Try saving to a different location (e.g., Documents folder)
- Close any open PDF files that might have the same name
8. "Processing" Status Won't Clear
Problem: Status bar shows "Processing" but nothing is happening
Solutions:
- Wait a full minute (models can take time)
- Check if only one model failed to respond
- Try restarting the application
- Check console for worker thread errors
9. Audio File Won't Process
Problem: Selected WAV file causes error or crash
Solutions:
- Verify file is valid WAV format (not corrupted)
- Ensure sample rate is 44.1kHz or higher
- Try re-exporting the file from audio software
- Use ffmpeg to convert:
ffmpeg -i input.wav -acodec pcm_s16le -ar 44100 output.wav
- Check file size (should be under 100MB)
10. Image Processing Errors
Problem: Image file causes crash or error message
Solutions:
- Verify image format (JPG, PNG, or BMP only)
- Check image resolution (should be 1920x1080 or higher)
- Try re-saving image with image editor
- Ensure image is not corrupted: open in viewer first
- Convert format if needed:
ffmpeg -i input.png -q:v 5 output.jpg
Advanced Troubleshooting
Checking Logs
- Console output shows real-time processing logs
- Look for "[Error]" or "[Exception]" messages
- Save console output for debugging
- Report with full error stack trace to development team
Database Issues
- Problem: "Database error" when loading analyses
- Solution: Database corrupted - back up data/database.db and delete it
- Application will recreate fresh database on next run
- Previous analyses will be lost (unless backup exists)
Memory Issues
- Monitor RAM usage in System Info panel
- If approaching maximum, close other applications
- Reduce batch size or process one analysis at a time
- Consider upgrading system RAM
Getting Help
If problems persist:
- Check the full documentation in each help tab
- Review system requirements and verify compliance
- Try reproducing the issue with sample data
- Collect console output and error messages
- Contact AIDurian development team with:
- Detailed description of the problem
- Steps to reproduce
- Console output/error messages
- System information (OS, Python version, GPU info)
- Input files if possible
Performance Optimization
- First Run: Models are cached after first load, subsequent runs are faster
- GPU Warmup: First GPU inference can be slow, later ones are faster
- Batch Processing: Process multiple files sequentially for best performance
- Resource Monitoring: Watch System Info for bottlenecks
"""
return self._create_scrollable_content(content)