# AI Composition Analysis Module - Setup Guide ## Overview The AI Composition Analysis Module is an advanced addon to the Photo Critique Tool that provides automated composition analysis using computer vision techniques. It analyzes photos for: - **Rule of Thirds** alignment - **Leading Lines** detection - **Symmetry & Balance** analysis - **Natural Framing** identification - **Depth & Layers** assessment - **Negative Space** evaluation - **Background Cleanliness** scoring ## Features ### 🤖 AI-Powered Analysis - Real-time composition scoring using OpenCV - Confidence levels for each detection - Visual overlay with rule of thirds grid - Detailed technical analysis data ### 🎯 Interactive Scoring - AI-suggested scores that users can adjust - Visual sliders for each composition element - Checkbox indicators for detected elements - Real-time overall score calculation ### 📊 Comprehensive Reporting - PDF generation with detailed analysis - Downloadable reports with scores and insights - Analysis history tracking - Progress monitoring for logged-in users ### 🔗 Full Integration - Works with existing authentication system - Database storage for analysis history - User progress tracking - Seamless navigation with main tool ## Installation ### Prerequisites 1. **PHP 8.0+** with the following extensions: - `php-gd` (for image processing) - `php-json` (for JSON handling) - `php-mysqli` (for database) 2. **Python 3.8+** with pip 3. **MySQL/MariaDB** database ### Step 1: Database Setup Run the updated database schema to add AI analysis tables: ```sql -- Add these tables to your existing database CREATE TABLE ai_analyses ( id INT PRIMARY KEY AUTO_INCREMENT, user_id INT, image_name VARCHAR(255) NOT NULL, width INT NOT NULL, height INT NOT NULL, analysis_data JSON NOT NULL, overall_score DECIMAL(3,1), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, INDEX idx_user_id (user_id), INDEX idx_created_at (created_at), FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ); CREATE TABLE analysis_history ( id INT PRIMARY KEY AUTO_INCREMENT, user_id INT, analysis_id INT, manual_adjustments JSON, final_score DECIMAL(3,1), user_notes TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, INDEX idx_user_analysis (user_id, analysis_id), FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, FOREIGN KEY (analysis_id) REFERENCES ai_analyses(id) ON DELETE CASCADE ); ``` ### Step 2: Python Environment Setup Create a virtual environment for Python dependencies: ```bash # Navigate to your project directory cd /path/to/PhotoCritique # Create virtual environment python3 -m venv ai_env # Activate virtual environment source ai_env/bin/activate # Linux/Mac # OR ai_env\Scripts\activate # Windows # Install dependencies pip install -r ai/requirements.txt ``` ### Step 3: Python Dependencies Install the required Python packages: ```bash pip install opencv-python==4.8.1.78 pip install opencv-contrib-python==4.8.1.78 pip install numpy==1.24.3 pip install Pillow==10.0.1 pip install scikit-image==0.21.0 pip install matplotlib==3.7.2 ``` ### Step 4: File Permissions Ensure the Python script is executable: ```bash chmod +x ai/analyze_composition.py ``` ### Step 5: Test Installation Test the Python analysis script: ```bash # Test with a sample image python3 ai/analyze_composition.py path/to/test/image.jpg --output detailed ``` Expected output should be a JSON response with composition analysis. ## Configuration ### PHP Configuration Update your `config/database.php` if needed to ensure JSON column support is enabled. ### Python Path Configuration In `api/ai-analyze.php`, update the Python command path if needed: ```php // Update this line if your Python installation is in a different location $command = "python3 ../ai/analyze_composition.py " . escapeshellarg($imagePath); ``` ### Environment Variables (Optional) For production deployment, consider setting environment variables: ```bash export PYTHON_PATH="/path/to/python3" export AI_SCRIPT_PATH="/path/to/ai/analyze_composition.py" ``` ## Usage ### For Students 1. **Upload Photo**: Drag & drop or select a photo (JPG, PNG, WebP) 2. **AI Analysis**: Wait for automated composition analysis 3. **Review Results**: Check AI-suggested scores and insights 4. **Manual Adjustment**: Modify scores based on your own assessment 5. **Download Report**: Generate PDF report with analysis 6. **Save Progress**: Logged-in users can save analyses to their profile ## API Endpoints ### POST `/api/ai-analyze.php` Performs AI composition analysis on uploaded image. **Parameters:** - `image` (file): Image file for analysis - `user_id` (optional): User ID for saving analysis **Response:** ```json { "success": true, "analysis": { "scores": { "rule_of_thirds": 8, "leading_lines": 5, "symmetry": 7, ... }, "confidence_levels": { "rule_of_thirds": "high", "leading_lines": "medium", ... }, "insights": [ "Excellent use of the rule of thirds...", "Consider strengthening leading lines..." ], "overall_score": 7.2 } } ``` ## Troubleshooting ### Common Issues #### 1. Python Script Not Found ```bash # Error: python3: command not found # Solution: Install Python 3 or update PATH which python3 # or try which python ``` #### 2. OpenCV Installation Issues ```bash # Error: ImportError: No module named 'cv2' # Solution: Reinstall OpenCV pip uninstall opencv-python opencv-contrib-python pip install opencv-python opencv-contrib-python ``` #### 3. Permission Denied ```bash # Error: Permission denied: python script # Solution: Make script executable chmod +x ai/analyze_composition.py ``` #### 4. JSON Column Not Supported ```sql -- Error with JSON columns -- Solution: Ensure MySQL 5.7+ or MariaDB 10.2+ SELECT VERSION(); ``` ### Debug Mode Enable debug mode in the Python script: ```python # In ai/analyze_composition.py, add debug prints print(f"Debug: Analyzing image {args.image_path}", file=sys.stderr) ``` Check PHP error logs for API issues: ```bash tail -f /var/log/apache2/error.log # or tail -f /var/log/nginx/error.log ``` ## Performance Optimization ### 1. Image Processing - Resize large images before analysis - Cache analysis results - Use image thumbnails for preview ### 2. Database Optimization - Index frequently queried columns - Archive old analysis data - Use connection pooling ### 3. Python Performance - Use compiled OpenCV (not built from source) - Consider GPU acceleration for heavy processing - Implement analysis result caching ## Advanced Features ### Real-time Analysis Enable real-time analysis as users adjust crop/composition: ```javascript // Add to ai-composition-analyzer.html function enableRealTimeAnalysis() { // Monitor image adjustments // Trigger analysis on changes } ``` ### Batch Processing Process multiple images simultaneously: ```bash # Batch analysis script python3 ai/batch_analyze.py /path/to/images/ ``` ### Machine Learning Integration For advanced AI features, integrate with: - **TensorFlow** for deep learning models - **MediaPipe** for advanced object detection - **YOLO** for subject identification ## Security Considerations 1. **File Upload Validation**: Ensure only valid image files are processed 2. **Path Sanitization**: Prevent directory traversal attacks 3. **Resource Limits**: Set timeouts for Python script execution 4. **User Authentication**: Verify user permissions before saving analyses ## Support For issues with the AI Composition Analysis Module: 1. Check the troubleshooting section above 2. Review server error logs 3. Test Python script independently 4. Verify database schema updates 5. Check file permissions and paths ## Future Enhancements - **Advanced AI Models**: Integration with pre-trained composition models - **Video Analysis**: Extend to video composition analysis - **Style Analysis**: Detect photography styles and genres - **Collaborative Learning**: Share analyses between users - **Mobile App**: Native mobile application with AI analysis