# Sentiment Score Database Issue - Diagnosis and Fix ## Problem Summary The anxiety, stress, and normal scores are not being saved correctly to the database. All scores appear as 0 in the `journal_tbl`. ## Test Results ### 1. PKL Model Test ✅ PASSED **File:** `test_pkl_probabilities.py` The PKL model (best_mental_health_model.pkl) is working correctly: - Model loads successfully - Returns three probability scores that sum to 100% - Classes: ['Anxiety', 'Normal', 'Stress'] - Model accuracy: 89.3% **Example output:** ``` Test: "I am sad, my mother not believe on me" Anxiety: 0.35% Normal: 97.85% Stress: 1.8% Total: 100.0% ✓ ``` ### 2. Data Flow Analysis ✅ CORRECT The data flow is correctly structured: ``` Flutter App ↓ 1. User sends message ↓ 2. Call SentimentAnalysisService.analyzeSentiment(text) → POST to Flask: http://IP:5001/sentiment_predict → Expects: anxiety_score, stress_score, normal_score ↓ 3. Call JournalDatabaseService.saveJournalEntry() → POST to PHP: save_journal.php → Sends: anxiety_score, stress_score, normal_score ↓ 4. PHP saves to MySQL database → Table: journal_tbl → Columns: anxiety_score, stress_score, normal_score ``` **Flutter code (journaling_screen.dart) is CORRECT:** - Calls sentiment analysis for user messages - Gets three scores - Passes them to database service **Flask endpoint (/sentiment_predict) is CORRECT:** - Returns anxiety_score, stress_score, normal_score - Calls predict_sentiment() which works correctly ## Potential Issues ### Issue 1: Flask Server Not Running ⚠️ The Flask server might not be running when the app tries to analyze sentiment. **How to check:** 1. Is the Flask server running on port 5001? 2. Run: `python test_flask_endpoint.py` to verify **How to fix:** ```bash cd backend python app.py ``` The server should start and show: ``` 🚀 Starting Gemini AI Journaling Backend... 📡 API Key configured: ✅ 🌐 Server will be available at: http://YOUR_IP:5001 ``` ### Issue 2: Sentiment Analyzer Not Initialized ⚠️ The sentiment analyzer might not be initialized when the Flask server starts. **How to check:** ```bash curl http://localhost:5001/sentiment_status ``` Should return: ```json { "initialized": true, "accuracy": 0.893, "classes": ["Anxiety", "Normal", "Stress"] } ``` **How to fix:** Add this to app.py (around line 1240, in the `if __name__ == '__main__'` block): ```python if __name__ == '__main__': print("🚀 Starting Gemini AI Journaling Backend...") # Initialize sentiment analyzer on startup print("\n🧠 Initializing sentiment analysis model...") if sentiment_analyzer.initialize(): print(" ✓ Sentiment analyzer initialized successfully") else: print(" ✗ Failed to initialize sentiment analyzer") # Start server app.run(host=SERVER_IP, port=SERVER_PORT, debug=False, threaded=True) ``` ### Issue 3: Error Handling Returns 0 ⚠️ If sentiment analysis fails, the Flutter app falls back to neutral scores: ```dart // In sentiment_analysis_service.dart factory SentimentResult.neutral() { return SentimentResult( category: 'normal', anxietyScore: 0.0, stressScore: 0.0, normalScore: 100.0, // Should be 100! success: false, ); } ``` If the sentiment analysis fails (network error, timeout, etc.), it returns all zeros except normal=100. **How to check:** - Look at Flutter console logs when sending a message - Should see: "Sentiment analysis complete: Anxiety: X, Stress: Y, Normal: Z" - If you see: "Sentiment analysis failed", the Flask endpoint isn't responding ### Issue 4: Network Configuration ⚠️ The Flutter app might not be able to reach the Flask server. **How to check:** 1. Check `myconfig.dart` for the Flask server URL 2. Make sure the IP and port are correct 3. Make sure the server is accessible from the emulator/device **Common issues:** - Using `localhost` or `127.0.0.1` won't work from Android emulator - Use `10.0.2.2` for Android emulator - Use your computer's IP address for physical device ## Testing Steps ### Step 1: Test PKL Model Directly ```bash cd backend python test_pkl_probabilities.py ``` Expected: All tests pass with three scores summing to 100% ### Step 2: Start Flask Server ```bash cd backend python app.py ``` Expected: Server starts on port 5001 ### Step 3: Test Flask Endpoint ```bash cd backend python test_flask_endpoint.py ``` Expected: - Server is running ✓ - Model initialized ✓ - All tests return three scores summing to 100% ✓ ### Step 4: Test from Flutter App 1. Start Flask server 2. Start Flutter app 3. Send a journal message 4. Check Flutter console for sentiment analysis logs 5. Check database for saved scores ## Quick Fix Checklist - [ ] Flask server is running (`python app.py`) - [ ] Sentiment analyzer is initialized (check `/sentiment_status`) - [ ] Flask server is accessible from Flutter app (check IP/port) - [ ] Flutter app can reach Flask server (no network errors) - [ ] Database columns match: `anxiety_score`, `stress_score`, `normal_score` - [ ] PHP save_journal.php is receiving the scores (check PHP logs) ## Database Check Run this SQL query to check current scores: ```sql SELECT session_id, session_code, role, LEFT(journal_text, 50) as text_preview, anxiety_score, stress_score, normal_score, journal_timestamp FROM journal_tbl ORDER BY journal_timestamp DESC LIMIT 10; ``` Expected: - User messages should have non-zero scores - Assistant messages should have all zeros - Scores should sum to approximately 100 ## Files to Check 1. **Flask Backend:** - `backend/app.py` (lines 354-425: predict_sentiment) - `backend/app.py` (lines 1195-1221: /sentiment_predict endpoint) 2. **Flutter Frontend:** - `lib/services/sentiment_analysis_service.dart` - `lib/screens/journaling/journaling_screen.dart` (lines 305-337) 3. **PHP Backend:** - `database/save_journal.php` 4. **Database:** - Table: `journal_tbl` - Columns: `anxiety_score`, `stress_score`, `normal_score` (DOUBLE/FLOAT) ## Common Reasons for Zero Scores 1. **Flask server not running** → All scores default to 0, 0, 100 (neutral) 2. **Sentiment analyzer not initialized** → Returns default 0, 0, 0 3. **Network timeout** → Falls back to neutral 0, 0, 100 4. **Error in predict_sentiment** → Returns 0, 0, 0 with error message 5. **Text is empty after cleaning** → Returns 0, 0, 0 ## Recommended Solution Create an initialization script for Flask: ```python # In app.py, at the bottom: if __name__ == '__main__': print("🚀 Starting Gemini AI Journaling Backend...") print(f"📡 API Key configured: {'✅' if GEMINI_API_KEY else '❌'}") print(f"🌐 Server will be available at: http://{SERVER_IP}:{SERVER_PORT}") # Initialize sentiment analyzer print("\n🧠 Initializing sentiment analysis model...") if sentiment_analyzer.initialize(): print("✅ Sentiment analyzer ready!") print(f" Model: {sentiment_analyzer.classes}") print(f" Accuracy: {sentiment_analyzer.model_accuracy:.2%}") else: print("❌ Sentiment analyzer failed to initialize") print(" Sentiment analysis will not be available") # Start Flask server print(f"\n🚀 Starting server...") app.run(host=SERVER_IP, port=SERVER_PORT, debug=False, threaded=True) ``` This ensures the sentiment analyzer is initialized before handling requests.