Spaces:
Sleeping
Sleeping
File size: 7,509 Bytes
765c205 | 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 | # 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.
|