Spaces:
Sleeping
Sleeping
Commit ·
2fe683b
1
Parent(s): f235090
Deploy app.py with ML models and dependencies
Browse filesFiles changed (11)
- .gitignoreAdded+61
- DockerfileAdded+48
- README.md+113-6
- app.pyAdded+1505
- best_mental_health_model.pklAdded+3
- config.pyAdded+36
- haarcascade_frontalface_default.xmlAdded
- heartPredictionModel/feature_names.pklAdded+3
- heartPredictionModel/stress_model.pklAdded+3
- heartPredictionModel/stress_scaler.pklAdded+3
- requirements.txtAdded+27
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061# Environment files.env.env.local.env.production
# GCP credentials (add these as HF Secrets instead)gcp_key.jsongcp_key_2.json
# Python__pycache__/*.py[cod]*$py.class*.so.Pythonbuild/develop-eggs/dist/downloads/eggs/.eggs/lib/lib64/parts/sdist/var/wheels/*.egg-info/.installed.cfg*.egg
# Virtual environmentsvenv/ENV/env/.venv/
# IDE.idea/.vscode/*.swp*.swo
# Test filestest_*.py*_test.pycheck_*.pyinspect_*.pyregenerate_*.py
# Logs*.loglogs/
# OS.DS_StoreThumbs.db
# Batch/Shell scripts (not needed in deployment)*.bat*.sh123456789101112131415161718192021222324252627282930313233343536373839404142434445464748# Dockerfile for Hugging Face Spaces deployment# AikoDiary Backend - Mental Health Journaling API
FROM python:3.10-slim
# Install system dependencies for OpenCV and other packagesRUN apt-get update && apt-get install -y \ libgl1-mesa-glx \ libglib2.0-0 \ libsm6 \ libxext6 \ libxrender-dev \ libgomp1 \ && rm -rf /var/lib/apt/lists/*
# Set working directoryWORKDIR /app
# Create a non-root user for security (required by HF Spaces)RUN useradd -m -u 1000 userUSER userENV HOME=/home/user \ PATH=/home/user/.local/bin:$PATH
# Copy requirements first for better cachingCOPY --chown=user:user requirements.txt .
# Install Python dependenciesRUN pip install --no-cache-dir --upgrade pip && \ pip install --no-cache-dir -r requirements.txt
# Copy application codeCOPY --chown=user:user . .
# Hugging Face Spaces uses port 7860ENV PORT=7860EXPOSE 7860
# Set environment variables for productionENV PYTHONUNBUFFERED=1ENV FLASK_ENV=production
# Health checkHEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \ CMD python -c "import requests; requests.get('http://localhost:7860/health')" || exit 1
# Run the application with gunicorn for productionCMD ["gunicorn", "--bind", "0.0.0.0:7860", "--workers", "2", "--timeout", "120", "app:app"]1234567891011---title: BackendAPIemoji: 🔥colorFrom: redcolorTo: indigosdk: dockerpinned: falselicense: apache-2.0---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118---title: AikoDiary Backendemoji: 📔colorFrom: purplecolorTo: pinksdk: dockerpinned: falselicense: mitapp_port: 7860---# AikoDiary Backend APIA mental health journaling companion powered by Gemini AI, providing:- 🤖 **AI Chat** - Empathetic conversation sessions using Gemini AI- 🎤 **Speech-to-Text** - Voice input using Google Cloud Speech API- 🔍 **Sentiment Analysis** - Anxiety, stress, and normal state detection- 😊 **Emotion Detection** - Facial emotion recognition from camera frames- 📊 **Utility Fusion** - Combined mental health score calculation## API Endpoints### Conversation| Endpoint | Method | Description ||----------|--------|-------------|| `/start_conversation` | POST | Start new AI chat session || `/send_message` | POST | Send message, get AI response with sentiment || `/get_conversation` | GET | Get conversation history || `/end_conversation` | POST | End conversation session |### Speech-to-Text| Endpoint | Method | Description ||----------|--------|-------------|| `/stt_start` | POST | Start STT recording session || `/stt_send_chunk` | POST | Send audio chunk || `/stt_stop` | POST | Stop recording, get transcript || `/stt_cancel` | POST | Cancel recording session || `/stt` | POST | Simple file upload STT |### Sentiment Analysis| Endpoint | Method | Description ||----------|--------|-------------|| `/sentiment_initialize` | POST | Initialize sentiment model || `/sentiment_predict` | POST | Predict sentiment for text || `/sentiment_status` | GET | Get model status |### Emotion Detection| Endpoint | Method | Description ||----------|--------|-------------|| `/emotion_initialize` | POST | Initialize emotion detector || `/emotion_detect` | POST | Detect emotion from image || `/emotion_status` | GET | Get detector status |### System| Endpoint | Method | Description ||----------|--------|-------------|| `/health` | GET | Health check || `/calculate_utility_scores` | POST | Calculate fused mental health scores |## Environment Variables (Secrets)Set these in Hugging Face Space Settings > Repository secrets:| Variable | Required | Description ||----------|----------|-------------|| `GEMINI_API_KEY` | ✅ Yes | Google Gemini API key || `GCP_SERVICE_ACCOUNT_FILE` | Optional | Path to GCP credentials JSON || `SPEECH_LANGUAGE_CODE` | Optional | Speech recognition language (default: en-US) |## Usage Example```pythonimport requests# Start conversationresponse = requests.post("https://your-space.hf.space/start_conversation",json={"session_id": "user_123"})print(response.json())# Send messageresponse = requests.post("https://your-space.hf.space/send_message",json={"session_id": "user_123","message": "I'm feeling stressed today"})print(response.json())```## Local Development```bash# Install dependenciespip install -r requirements.txt# Set environment variablesexport GEMINI_API_KEY=your_api_key# Run locallypython app.py# Or with gunicorngunicorn --bind 0.0.0.0:7860 app:app```## Tech Stack- **Framework**: Flask + Gunicorn- **AI**: Google Gemini API- **Speech**: Google Cloud Speech-to-Text- **ML**: scikit-learn (SVM sentiment classifier)- **Emotion**: FER (Facial Emotion Recognition)---*Built with ❤️ for mental health awareness*
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505from flask import Flask, request, jsonifyfrom flask_cors import CORSfrom flask_sock import Sockimport google.generativeai as genaiimport osimport jsonfrom datetime import datetimeimport loggingimport asyncioimport threadingfrom io import BytesIOimport numpy as npimport pickleimport refrom config import GEMINI_API_KEY, SERVER_IP, SERVER_PORTfrom config import GCP_SERVICE_ACCOUNT_FILE, SPEECH_LANGUAGE_CODEfrom config import DB_CONFIG, ENABLE_FLASK_DB
# MySQL database importstry: import mysql.connector from mysql.connector import Error as MySQLError _mysql_available = Trueexcept Exception: _mysql_available = False logging.warning("MySQL connector not available")
# Emotion detection importstry: import cv2 from fer import FER _emotion_detection_available = Trueexcept Exception as e: _emotion_detection_available = False logging.warning(f"Emotion detection not available: {e}")
# Google Cloud Speech-to-Texttry: from google.oauth2 import service_account from google.cloud import speech _speech_available = Trueexcept Exception: _speech_available = False
# Configure logginglogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)
app = Flask(__name__)CORS(app) # Enable CORS for Flutter appsock = Sock(app) # Enable WebSocket support
# Configure Gemini AIgenai.configure(api_key=GEMINI_API_KEY)
# Initialize Gemini modelmodel = genai.GenerativeModel('gemini-2.5-flash')
# Store conversation sessions in memory (in production, use a database)conversation_sessions = {}stt_sessions = {}
class ConversationSession: def __init__(self, session_id): self.session_id = session_id self.messages = [] self.question_count = 0 self.user_emotions = [] self.conversation_complete = False self.created_at = datetime.now() def add_message(self, message, is_user=True, emotion=None): self.messages.append({ 'text': message, 'is_user': is_user, 'timestamp': datetime.now().isoformat(), 'emotion': emotion }) if is_user and emotion: self.user_emotions.append(emotion) def get_conversation_context(self): context = "You are an empathetic AI companion helping someone journal their feelings and daily experiences. " context += "Your goal is to help the user express their feelings and understand what they did today through gentle, follow-up questions. " context += "Be supportive, understanding, and ask one thoughtful question at a time. " context += "Keep responses concise (2-3 sentences max). " context += "Continue the conversation naturally based on what the user shares - don't impose artificial limits. " context += "Let the user guide when they're ready to finish by listening for closing cues in their responses. " # Add recent conversation history if self.messages: context += "\n\nConversation so far:\n" for msg in self.messages[-8:]: # Last 8 messages for context role = "User" if msg['is_user'] else "AI" context += f"{role}: {msg['text']}\n" return context
class STTSession: def __init__(self, session_id): self.session_id = session_id self.audio_buffer = BytesIO() self.is_recording = False self.created_at = datetime.now()
# ============================================================================# EMOTION DETECTION CLASS# ============================================================================
class EmotionDetectionBridge: """Emotion detection using FER (Facial Emotion Recognition)"""
def __init__(self): self.emotion_detector = None self.face_cascade = None self.is_initialized = False self.current_emotion_data = { 'dominant_emotion': 'neutral', 'confidence': 0.0, 'all_emotions': {}, 'timestamp': datetime.now().isoformat(), 'face_detected': False }
def initialize(self): """Initialize emotion detection system""" try: if not _emotion_detection_available: logger.warning("Emotion detection dependencies not available") return False
# Initialize FER emotion detector without MTCNN (use OpenCV instead) # MTCNN has TorchVision issues, so we use OpenCV's haarcascade self.emotion_detector = FER(mtcnn=False)
# Load face cascade classifier from backend folder cascade_path = os.path.join( os.path.dirname(__file__), 'haarcascade_frontalface_default.xml' )
if os.path.exists(cascade_path): self.face_cascade = cv2.CascadeClassifier(cascade_path) logger.info(f"Loaded cascade from: {cascade_path}") else: # Fallback to OpenCV's built-in cascade logger.warning(f"Cascade not found at {cascade_path}, using built-in") self.face_cascade = cv2.CascadeClassifier( cv2.data.haarcascades + 'haarcascade_frontalface_default.xml' )
self.is_initialized = True logger.info("Emotion detection system initialized successfully") return True
except Exception as e: logger.error(f"Error initializing emotion detection: {e}") return False
def detect_emotion_from_frame(self, frame_data): """Detect emotion from camera frame using cascade + FER""" try: if not self.is_initialized: return self.get_neutral_emotion()
# Convert frame_data to numpy array if needed if isinstance(frame_data, bytes): nparr = np.frombuffer(frame_data, np.uint8) frame = cv2.imdecode(nparr, cv2.IMREAD_COLOR) else: frame = frame_data
if frame is None: return self.get_neutral_emotion()
# Convert to grayscale for cascade detection gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Detect faces using Haar Cascade faces = self.face_cascade.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30) )
# Only proceed if cascade detected at least one face if len(faces) == 0: # No face detected by cascade logger.info(">> [FER] Cascade: NO FACE DETECTED") self.current_emotion_data = self.get_neutral_emotion() self.current_emotion_data['face_detected'] = False self.current_emotion_data['face_box'] = None return self.current_emotion_data
# Get the first (largest) face detected by cascade (x, y, w, h) = faces[0] logger.info(f">> [FER] Cascade: FACE DETECTED at ({x}, {y}) size {w}x{h}")
# Now detect emotions using FER on the frame emotions = self.emotion_detector.detect_emotions(frame) logger.info(f">> [FER] FER returned: {len(emotions) if emotions else 0} emotion(s)")
if emotions and len(emotions) > 0: # Get the first (most prominent) face emotion emotion_data = emotions[0] all_emotions_raw = emotion_data["emotions"] logger.info(f">> [FER] RAW emotions: {all_emotions_raw}")
# Filter to only include angry, sad, fear, neutral target_emotions = ['angry', 'sad', 'fear', 'neutral'] filtered_emotions = { emotion: all_emotions_raw.get(emotion, 0.0) for emotion in target_emotions } logger.info(f">> [FER] FILTERED emotions (before normalize): {filtered_emotions}")
# Normalize the filtered emotions to sum to 1.0 total = sum(filtered_emotions.values()) if total > 0: filtered_emotions = { k: v / total for k, v in filtered_emotions.items() } logger.info(f">> [FER] NORMALIZED emotions: {filtered_emotions}")
# Find dominant emotion from filtered set dominant_emotion = max(filtered_emotions, key=filtered_emotions.get) confidence = filtered_emotions[dominant_emotion] logger.info(f">> [FER] DOMINANT: {dominant_emotion} ({confidence*100:.1f}%)")
self.current_emotion_data = { 'dominant_emotion': dominant_emotion, 'confidence': float(confidence), 'all_emotions': {k: float(v) for k, v in filtered_emotions.items()}, 'timestamp': datetime.now().isoformat(), 'face_detected': True, 'face_box': { 'x': int(x), 'y': int(y), 'width': int(w), 'height': int(h) } } else: # Cascade detected face but FER didn't - still return face box self.current_emotion_data = self.get_neutral_emotion() self.current_emotion_data['face_detected'] = True self.current_emotion_data['face_box'] = { 'x': int(x), 'y': int(y), 'width': int(w), 'height': int(h) }
return self.current_emotion_data
except Exception as e: logger.error(f"Error detecting emotion: {e}") return self.get_neutral_emotion()
def get_neutral_emotion(self): """Return neutral emotion data""" return { 'dominant_emotion': 'neutral', 'confidence': 1.0, 'all_emotions': { 'angry': 0.0, 'sad': 0.0, 'fear': 0.0, 'neutral': 1.0 }, 'timestamp': datetime.now().isoformat(), 'face_detected': False, 'face_box': None }
# Initialize global emotion detectoremotion_bridge = EmotionDetectionBridge()
# ============================================================================# SENTIMENT ANALYSIS - TEXT CLEANING FUNCTION# ============================================================================
# IMPORTANT: This function must be at module level for pickle to workdef clean_text(text): """Clean and preprocess text for sentiment analysis (module-level function for pickle)""" if not isinstance(text, str): return ""
# Convert to lowercase text = text.lower()
# Remove URLs text = re.sub(r'http\S+|www\S+|https\S+', '', text, flags=re.MULTILINE)
# Remove email addresses text = re.sub(r'\S+@\S+', '', text)
# Remove special characters and digits, keep only letters and basic punctuation text = re.sub(r'[^a-zA-Z\s\.\,\!\?]', '', text)
# Remove extra whitespaces text = re.sub(r'\s+', ' ', text).strip()
return text
# ============================================================================# SENTIMENT ANALYSIS CLASS# ============================================================================
class SentimentAnalysisBridge: """Sentiment analysis for mental health detection (Anxiety, Stress, Normal)"""
def __init__(self): self.model = None self.tfidf_vectorizer = None self.label_encoder = None self.text_cleaner = None self.is_initialized = False self.model_accuracy = 0.0 self.model_f1_score = 0.0 self.classes = []
def initialize(self): """Initialize sentiment analysis model""" try: model_path = os.path.join( os.path.dirname(__file__), 'best_mental_health_model.pkl' )
if not os.path.exists(model_path): logger.error(f"Model file not found at: {model_path}") return False
# Load the model with open(model_path, 'rb') as f: model_data = pickle.load(f)
# Extract components self.model = model_data['model'] self.tfidf_vectorizer = model_data['tfidf_vectorizer'] self.label_encoder = model_data['label_encoder'] self.text_cleaner = model_data.get('text_cleaner', clean_text) # Use module-level function self.model_accuracy = model_data.get('accuracy', 0.0) self.model_f1_score = model_data.get('f1_score', 0.0) self.classes = model_data.get('classes', [])
self.is_initialized = True logger.info("Sentiment analysis model initialized successfully") logger.info(f"Model accuracy: {self.model_accuracy:.4f}, F1-score: {self.model_f1_score:.4f}") logger.info(f"Model classes: {self.classes}")
return True
except Exception as e: logger.error(f"Error initializing sentiment analysis: {e}") import traceback traceback.print_exc() return False
def predict_sentiment(self, text): """ Predict sentiment and return all three probability scores Returns: dict with anxiety_score, stress_score, normal_score (all 0-100%) """ try: if not self.is_initialized: logger.warning("Sentiment model not initialized, attempting to initialize...") if not self.initialize(): return { 'category': 'normal', 'anxiety_score': 0.0, 'stress_score': 0.0, 'normal_score': 0.0, 'error': 'Model not initialized' }
# Clean the text (use module-level clean_text as fallback) cleaned_text = self.text_cleaner(text) if callable(self.text_cleaner) else clean_text(text)
if not cleaned_text or len(cleaned_text.strip()) == 0: return { 'category': 'normal', 'anxiety_score': 0.0, 'stress_score': 0.0, 'normal_score': 0.0, 'error': 'Empty text after cleaning' }
# Transform using TF-IDF vectorizer text_vectorized = self.tfidf_vectorizer.transform([cleaned_text])
# Make prediction prediction = self.model.predict(text_vectorized) predicted_category = prediction[0].lower() # Convert to lowercase for consistency
# Get probability scores using predict_proba (SVM has probability=True) probabilities = self.model.predict_proba(text_vectorized)[0]
# Map probabilities to specific scores # Model classes are: ['Anxiety', 'Normal', 'Stress'] prob_dict = { label.lower(): round(prob * 100, 2) for label, prob in zip(self.model.classes_, probabilities) }
anxiety_score = prob_dict.get('anxiety', 0.0) stress_score = prob_dict.get('stress', 0.0) normal_score = prob_dict.get('normal', 0.0)
logger.info(f"Sentiment prediction: {predicted_category}") logger.info(f" Anxiety: {anxiety_score}%, Stress: {stress_score}%, Normal: {normal_score}%")
return { 'category': predicted_category, 'anxiety_score': anxiety_score, 'stress_score': stress_score, 'normal_score': normal_score, 'all_probabilities': prob_dict }
except Exception as e: logger.error(f"Error predicting sentiment: {e}") import traceback traceback.print_exc() return { 'category': 'normal', 'anxiety_score': 0.0, 'stress_score': 0.0, 'normal_score': 0.0, 'error': str(e) }
# Initialize global sentiment analyzersentiment_analyzer = SentimentAnalysisBridge()
# ============================================================================# HEART RATE STRESS PREDICTION CLASS# ============================================================================
class HeartRateStressPrediction: """Heart rate stress prediction using RR intervals"""
def __init__(self): self.model = None self.scaler = None self.feature_names = None self.is_initialized = False
def initialize(self): """Initialize heart rate stress prediction model""" try: # Get absolute path to the model directory # Use __file__ to get the directory where app.py is located backend_dir = os.path.dirname(os.path.abspath(__file__)) model_dir = os.path.join(backend_dir, 'heartPredictionModel')
print(f"\n>> HR Model Initialization:") print(f" Backend dir: {backend_dir}") print(f" Model dir: {model_dir}") print(f" Model dir exists: {os.path.exists(model_dir)}")
model_path = os.path.join(model_dir, 'stress_model.pkl') scaler_path = os.path.join(model_dir, 'stress_scaler.pkl') features_path = os.path.join(model_dir, 'feature_names.pkl')
# Check each file individually print(f" stress_model.pkl: {os.path.exists(model_path)}") print(f" stress_scaler.pkl: {os.path.exists(scaler_path)}") print(f" feature_names.pkl: {os.path.exists(features_path)}")
if not all([os.path.exists(p) for p in [model_path, scaler_path, features_path]]): logger.error(f"Heart rate model files not found in: {model_dir}") logger.error(f"Missing files:") if not os.path.exists(model_path): logger.error(f" - {model_path}") if not os.path.exists(scaler_path): logger.error(f" - {scaler_path}") if not os.path.exists(features_path): logger.error(f" - {features_path}") return False
# Load model components with explicit binary mode and protocol print(f" Loading stress_model.pkl...") with open(model_path, 'rb') as f: self.model = pickle.load(f, encoding='bytes')
print(f" Loading stress_scaler.pkl...") with open(scaler_path, 'rb') as f: self.scaler = pickle.load(f, encoding='bytes')
print(f" Loading feature_names.pkl...") with open(features_path, 'rb') as f: self.feature_names = pickle.load(f, encoding='bytes') # Convert bytes to string if needed if self.feature_names and isinstance(self.feature_names[0], bytes): self.feature_names = [f.decode('utf-8') for f in self.feature_names]
self.is_initialized = True print(f" ✅ Model loaded successfully!") print(f" Model type: {type(self.model)}") print(f" Scaler type: {type(self.scaler)}") print(f" Features: {self.feature_names}") logger.info("Heart rate stress prediction model initialized successfully") logger.info(f"Feature names: {self.feature_names}")
return True
except pickle.UnpicklingError as e: logger.error(f"Pickle error loading HR stress model: {e}") logger.error(f"This usually means the pickle file is corrupted or incompatible") logger.error(f"Try regenerating the model files") import traceback traceback.print_exc() return False
except Exception as e: logger.error(f"Error initializing HR stress model: {e}") import traceback traceback.print_exc() return False
def predict_stress(self, rr_intervals): """ Predict stress from RR intervals Args: rr_intervals: List of RR interval values in milliseconds Returns: dict with stress prediction (1=stress, 0=no stress) and score """ try: if not self.is_initialized: logger.warning("HR stress model not initialized, attempting to initialize...") if not self.initialize(): return { 'stress': 0, 'score': 0, 'error': 'Model not initialized' }
if not rr_intervals or len(rr_intervals) == 0: return { 'stress': 0, 'score': 0, 'error': 'No RR intervals provided' }
# Calculate HRV features from RR intervals features = self._calculate_hrv_features(rr_intervals)
# Scale features features_scaled = self.scaler.transform([features])
# Predict (1 = stress, 0 = no stress) prediction = self.model.predict(features_scaled)[0]
# Get probability if available if hasattr(self.model, 'predict_proba'): probabilities = self.model.predict_proba(features_scaled)[0] stress_prob = probabilities[1] if len(probabilities) > 1 else probabilities[0] else: stress_prob = float(prediction)
logger.info(f"HR Stress Prediction: stress={prediction}, probability={stress_prob:.2%}")
return { 'stress': int(prediction), 'score': 100 if prediction == 1 else 0, 'probability': float(stress_prob), 'features': features }
except Exception as e: logger.error(f"Error predicting HR stress: {e}") import traceback traceback.print_exc() return { 'stress': 0, 'score': 0, 'error': str(e) }
def _calculate_hrv_features(self, rr_intervals): """Calculate HRV features from RR intervals""" try: rr_array = np.array(rr_intervals, dtype=float)
# Time-domain features mean_rr = np.mean(rr_array) std_rr = np.std(rr_array) rmssd = np.sqrt(np.mean(np.square(np.diff(rr_array))))
# Frequency-domain features would go here # For now, using basic time-domain features
# Return features in expected order (matching feature_names) features = [mean_rr, std_rr, rmssd]
logger.info(f"Calculated HRV features: mean={mean_rr:.2f}, std={std_rr:.2f}, rmssd={rmssd:.2f}")
return features
except Exception as e: logger.error(f"Error calculating HRV features: {e}") # Return default features if calculation fails return [0.0, 0.0, 0.0]
# Initialize global HR stress predictorhr_stress_predictor = HeartRateStressPrediction()
# ============================================================================# MYSQL DATABASE CONFIGURATION# ============================================================================
# Database configuration imported from config.py (uses environment variables)# NOTE: Database operations are handled by PHP backend, not Flask# Flask is only responsible for sentiment analysis# DB_CONFIG and ENABLE_FLASK_DB imported from config.py
def get_db_connection(): """Get MySQL database connection""" try: if not _mysql_available: logger.error("MySQL connector not available") return None
connection = mysql.connector.connect(**DB_CONFIG) if connection.is_connected(): return connection return None except Exception as e: logger.error(f"Error connecting to database: {e}") return None
def save_journal_to_db(session_code, role, journal_text, anxiety_score=None, depression_score=None, neutral_score=None): """ Save journal entry to MySQL database with all three sentiment scores
Args: session_code: Unique session identifier role: 'user' or 'assistant' journal_text: The journal text content anxiety_score: Anxiety probability score (0-100 percentage) depression_score: Depression probability score (0-100 percentage) neutral_score: Neutral/Normal probability score (0-100 percentage)
Returns: dict with success status and data """ # Check if database operations are enabled if not ENABLE_FLASK_DB: logger.info("Database operations disabled in Flask (handled by PHP backend)") return { 'success': True, 'message': 'Database operations handled by PHP backend', 'skipped': True }
connection = None cursor = None try: connection = get_db_connection() if not connection: return {'success': False, 'error': 'Database connection failed'}
cursor = connection.cursor(dictionary=True)
# Insert journal entry with all three sentiment scores sql = """ INSERT INTO journal_tbl (session_code, role, journal_text, anxiety_score, depression_score, neutral_score, journal_timestamp) VALUES (%s, %s, %s, %s, %s, %s, NOW()) """
cursor.execute(sql, (session_code, role, journal_text, anxiety_score, depression_score, neutral_score)) connection.commit()
session_id = cursor.lastrowid
logger.info(f"Journal saved to DB: session_code={session_code}, role={role}") logger.info(f" Scores - Anxiety: {anxiety_score}%, Depression: {depression_score}%, Neutral: {neutral_score}%")
return { 'success': True, 'session_id': session_id, 'session_code': session_code, 'role': role, 'anxiety_score': anxiety_score, 'depression_score': depression_score, 'neutral_score': neutral_score }
except Exception as e: logger.error(f"Error saving journal to database: {e}") if connection: connection.rollback() return {'success': False, 'error': str(e)}
finally: if cursor: cursor.close() if connection and connection.is_connected(): connection.close()
@app.route('/health', methods=['GET'])def health_check(): """Health check endpoint""" return jsonify({'status': 'healthy', 'timestamp': datetime.now().isoformat()})
@app.route('/start_conversation', methods=['POST'])def start_conversation(): """Start a new conversation session""" try: data = request.get_json() session_id = data.get('session_id', f"session_{datetime.now().timestamp()}") # Create new conversation session session = ConversationSession(session_id) conversation_sessions[session_id] = session # Generate initial greeting initial_prompt = """You are an empathetic AI companion for a journaling app. Start a conversation to help the user express their feelings and share about their day. Begin with a warm, welcoming greeting and ask an open-ended question about how they're feeling right now. Keep it concise (2-3 sentences max).""" response = model.generate_content(initial_prompt) ai_message = response.text.strip()
session.add_message(ai_message, is_user=False) session.question_count = 1
logger.info(f"Started conversation session: {session_id}")
return jsonify({ 'session_id': session_id, 'message': ai_message, 'question_count': session.question_count, 'conversation_complete': False }) except Exception as e: logger.error(f"Error starting conversation: {str(e)}") return jsonify({'error': 'Failed to start conversation'}), 500
@app.route('/send_message', methods=['POST'])def send_message(): """Send a message and get AI response with sentiment analysis""" try: data = request.get_json() session_id = data.get('session_id') user_message = data.get('message', '').strip() user_emotion = data.get('emotion', '') session_code = data.get('session_code', session_id) # For database saving
if not session_id or not user_message: return jsonify({'error': 'Session ID and message are required'}), 400
# Get or create session if session_id not in conversation_sessions: return jsonify({'error': 'Session not found'}), 404
session = conversation_sessions[session_id]
# Check if conversation is already complete if session.conversation_complete: return jsonify({ 'session_id': session_id, 'message': "Thank you for sharing with me today. I hope our conversation was helpful!", 'question_count': session.question_count, 'conversation_complete': True })
# ===== SENTIMENT ANALYSIS FOR USER MESSAGE ===== sentiment_result = sentiment_analyzer.predict_sentiment(user_message) category = sentiment_result.get('category', 'normal') anxiety_score = sentiment_result.get('anxiety_score', 0.0) depression_score = sentiment_result.get('depression_score', 0.0) neutral_score = sentiment_result.get('neutral_score', 0.0)
logger.info(f"User message sentiment: category={category}") logger.info(f" Anxiety: {anxiety_score}%, Depression: {depression_score}%, Neutral: {neutral_score}%")
# Save user message to database with all three sentiment scores db_result = save_journal_to_db( session_code=session_code, role='user', journal_text=user_message, anxiety_score=anxiety_score, depression_score=depression_score, neutral_score=neutral_score )
if not db_result.get('success'): logger.warning(f"Failed to save user message to DB: {db_result.get('error')}")
# Add user message to session session.add_message(user_message, is_user=True, emotion=user_emotion)
# Generate follow-up question - no artificial limit context = session.get_conversation_context() context += f"\n\nUser just said: {user_message}" if user_emotion: context += f"\nDetected emotion: {user_emotion}" if category and category != 'normal': max_score = max(anxiety_score, depression_score, neutral_score) context += f"\nDetected sentiment: {category} (confidence: {max_score}%)" context += "\n\nGenerate a thoughtful follow-up question or supportive response to help them continue exploring their feelings or share more about their day. " context += "If the user seems satisfied or gives closing cues (like 'that's all', 'nothing else', 'I'm done'), provide a warm closing statement instead of another question."
response = model.generate_content(context) ai_message = response.text.strip() session.question_count += 1
# Add AI response to session session.add_message(ai_message, is_user=False)
# ===== SAVE AI MESSAGE TO DATABASE ===== # AI messages have all scores set to 0 ai_db_result = save_journal_to_db( session_code=session_code, role='assistant', journal_text=ai_message, anxiety_score=0.0, depression_score=0.0, neutral_score=0.0 )
if not ai_db_result.get('success'): logger.warning(f"Failed to save AI message to DB: {ai_db_result.get('error')}")
logger.info(f"Session {session_id}: Message count: {session.question_count}")
return jsonify({ 'session_id': session_id, 'message': ai_message, 'question_count': session.question_count, 'conversation_complete': session.conversation_complete, 'sentiment': { 'category': category, 'anxiety_score': anxiety_score, 'depression_score': depression_score, 'neutral_score': neutral_score, 'all_probabilities': sentiment_result.get('all_probabilities', {}) } })
except Exception as e: logger.error(f"Error processing message: {str(e)}") import traceback traceback.print_exc() return jsonify({'error': 'Failed to process message'}), 500
@app.route('/get_conversation', methods=['GET'])def get_conversation(): """Get conversation history""" try: session_id = request.args.get('session_id') if not session_id or session_id not in conversation_sessions: return jsonify({'error': 'Session not found'}), 404 session = conversation_sessions[session_id] return jsonify({ 'session_id': session_id, 'messages': session.messages, 'question_count': session.question_count, 'conversation_complete': session.conversation_complete, 'user_emotions': session.user_emotions }) except Exception as e: logger.error(f"Error getting conversation: {str(e)}") return jsonify({'error': 'Failed to get conversation'}), 500
@app.route('/end_conversation', methods=['POST'])def end_conversation(): """End a conversation session""" try: data = request.get_json() session_id = data.get('session_id') if session_id in conversation_sessions: session = conversation_sessions[session_id] session.conversation_complete = True return jsonify({ 'session_id': session_id, 'message': 'Conversation ended successfully', 'summary': { 'total_messages': len(session.messages), 'questions_asked': session.question_count, 'emotions_detected': session.user_emotions, 'duration': str(datetime.now() - session.created_at) } }) return jsonify({'error': 'Session not found'}), 404 except Exception as e: logger.error(f"Error ending conversation: {str(e)}") return jsonify({'error': 'Failed to end conversation'}), 500
# ============================================================================# IMPROVED STT ENDPOINTS (HTTP-based, no WebSocket)# ============================================================================
@app.route('/stt_start', methods=['POST'])def stt_start(): """Start a new STT recording session""" try: data = request.get_json() session_id = data.get('session_id', f"stt_{datetime.now().timestamp()}") # Create new STT session session = STTSession(session_id) session.is_recording = True stt_sessions[session_id] = session logger.info(f"Started STT session: {session_id}") return jsonify({ 'success': True, 'session_id': session_id, 'message': 'Recording started' }) except Exception as e: logger.error(f"STT start error: {str(e)}") return jsonify({'error': 'Failed to start STT session'}), 500
@app.route('/stt_send_chunk', methods=['POST'])def stt_send_chunk(): """Receive audio chunks during recording""" try: if not _speech_available: return jsonify({'error': 'Speech-to-Text not available'}), 500 session_id = request.form.get('session_id') if not session_id or session_id not in stt_sessions: return jsonify({'error': 'Invalid session_id'}), 400 session = stt_sessions[session_id] if 'chunk' not in request.files: return jsonify({'error': 'No audio chunk provided'}), 400 # Append chunk to buffer chunk_data = request.files['chunk'].read() session.audio_buffer.write(chunk_data) return jsonify({ 'success': True, 'session_id': session_id, 'bytes_received': len(chunk_data), 'total_bytes': session.audio_buffer.tell() }) except Exception as e: logger.error(f"STT chunk error: {str(e)}") return jsonify({'error': 'Failed to process audio chunk'}), 500
@app.route('/stt_stop', methods=['POST'])def stt_stop(): """Stop recording and get final transcription""" try: if not _speech_available: return jsonify({'error': 'Speech-to-Text not available'}), 500 data = request.get_json() session_id = data.get('session_id') language_code = data.get('language_code', SPEECH_LANGUAGE_CODE or 'en-US') if not session_id or session_id not in stt_sessions: return jsonify({'error': 'Invalid session_id'}), 400 session = stt_sessions[session_id] session.is_recording = False # Get all audio data audio_data = session.audio_buffer.getvalue() if not audio_data: # Cleanup and return empty del stt_sessions[session_id] return jsonify({ 'success': True, 'session_id': session_id, 'transcript': '', 'message': 'No audio recorded' }) # Transcribe using Google Cloud Speech-to-Text credentials = service_account.Credentials.from_service_account_file( GCP_SERVICE_ACCOUNT_FILE ) speech_client = speech.SpeechClient(credentials=credentials) audio = speech.RecognitionAudio(content=audio_data) config = speech.RecognitionConfig( encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16, sample_rate_hertz=16000, language_code=language_code, enable_automatic_punctuation=True, model='default' ) response = speech_client.recognize(config=config, audio=audio) # Combine all transcripts transcripts = [] confidence_scores = [] for result in response.results: if result.alternatives: transcripts.append(result.alternatives[0].transcript) if result.alternatives[0].confidence: confidence_scores.append(result.alternatives[0].confidence) final_transcript = ' '.join(transcripts).strip() avg_confidence = sum(confidence_scores) / len(confidence_scores) if confidence_scores else 0.0 # Cleanup session del stt_sessions[session_id] logger.info(f"STT session {session_id} completed: {len(final_transcript)} chars") return jsonify({ 'success': True, 'session_id': session_id, 'transcript': final_transcript, 'confidence': avg_confidence, 'has_text': bool(final_transcript), 'duration': str(datetime.now() - session.created_at) }) except Exception as e: logger.error(f"STT stop error: {str(e)}") # Cleanup on error if session_id in stt_sessions: del stt_sessions[session_id] return jsonify({'error': f'Failed to transcribe: {str(e)}'}), 500
@app.route('/stt_cancel', methods=['POST'])def stt_cancel(): """Cancel an ongoing STT session""" try: data = request.get_json() session_id = data.get('session_id') if session_id in stt_sessions: del stt_sessions[session_id] return jsonify({ 'success': True, 'message': 'STT session cancelled' }) return jsonify({'error': 'Session not found'}), 404 except Exception as e: logger.error(f"STT cancel error: {str(e)}") return jsonify({'error': 'Failed to cancel session'}), 500
@app.route('/stt', methods=['POST'])def speech_to_text(): """Transcribe uploaded audio file using Google Cloud Speech-to-Text. Expected form-data: - file: audio file (e.g., .wav, .mp3, .raw) - language_code (optional): override default language """ try: if not _speech_available: return jsonify({'error': 'Speech-to-Text dependencies not installed'}), 500
if 'file' not in request.files: return jsonify({'error': 'No file provided'}), 400
uploaded = request.files['file'] if uploaded.filename == '': return jsonify({'error': 'Empty filename'}), 400
language_code = request.form.get('language_code', SPEECH_LANGUAGE_CODE or 'en-US')
# Read file content into memory content = uploaded.read() if not content: return jsonify({'error': 'Empty file content'}), 400
logger.info(f"Received audio file: {len(content)} bytes")
# Create Speech client credentials = service_account.Credentials.from_service_account_file(GCP_SERVICE_ACCOUNT_FILE) speech_client = speech.SpeechClient(credentials=credentials)
# Configure audio for LINEAR16 format (raw PCM) audio = speech.RecognitionAudio(content=content) config = speech.RecognitionConfig( encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16, sample_rate_hertz=16000, language_code=language_code, enable_automatic_punctuation=True, model='default' )
response = speech_client.recognize(config=config, audio=audio)
transcripts = [] for result in response.results: if result.alternatives: transcripts.append(result.alternatives[0].transcript)
transcript_text = ' '.join(transcripts).strip() logger.info(f"Transcription complete: {len(transcript_text)} characters") return jsonify({ 'transcript': transcript_text, 'language_code': language_code, 'has_text': bool(transcript_text) }) except Exception as e: logger.error(f"STT error: {str(e)}") return jsonify({'error': f'Failed to transcribe audio: {str(e)}'}), 500
# ============================================================================# EMOTION DETECTION ENDPOINTS# ============================================================================
@app.route('/emotion_initialize', methods=['POST'])def emotion_initialize(): """Initialize emotion detection system""" try: if not _emotion_detection_available: return jsonify({ 'success': False, 'error': 'Emotion detection dependencies not available', 'message': 'Install opencv-python and fer packages' }), 500
success = emotion_bridge.initialize()
return jsonify({ 'success': success, 'initialized': emotion_bridge.is_initialized, 'message': 'Emotion detection initialized' if success else 'Failed to initialize' })
except Exception as e: logger.error(f"Emotion initialization error: {str(e)}") return jsonify({'error': f'Failed to initialize emotion detection: {str(e)}'}), 500
@app.route('/emotion_detect', methods=['POST'])def emotion_detect(): """Detect emotion from uploaded image frame""" try: if not _emotion_detection_available: return jsonify({ 'error': 'Emotion detection not available' }), 500
if not emotion_bridge.is_initialized: # Try to initialize emotion_bridge.initialize()
if 'frame' not in request.files: return jsonify({'error': 'No frame image provided'}), 400
# Read the uploaded frame frame_file = request.files['frame'] frame_bytes = frame_file.read()
if not frame_bytes: return jsonify({'error': 'Empty frame data'}), 400
# Detect emotion emotion_data = emotion_bridge.detect_emotion_from_frame(frame_bytes)
logger.info(f"Emotion detected: {emotion_data['dominant_emotion']} ({emotion_data['confidence']:.2f})")
return jsonify({ 'success': True, 'emotion': emotion_data['dominant_emotion'], 'confidence': emotion_data['confidence'], 'all_emotions': emotion_data['all_emotions'], 'face_detected': emotion_data['face_detected'], 'timestamp': emotion_data['timestamp'] })
except Exception as e: logger.error(f"Emotion detection error: {str(e)}") return jsonify({'error': f'Failed to detect emotion: {str(e)}'}), 500
@app.route('/emotion_status', methods=['GET'])def emotion_status(): """Get current emotion detection status""" try: return jsonify({ 'available': _emotion_detection_available, 'initialized': emotion_bridge.is_initialized, 'current_emotion': emotion_bridge.current_emotion_data })
except Exception as e: logger.error(f"Emotion status error: {str(e)}") return jsonify({'error': f'Failed to get emotion status: {str(e)}'}), 500
# ============================================================================# SENTIMENT ANALYSIS ENDPOINTS# ============================================================================
@app.route('/sentiment_initialize', methods=['POST'])def sentiment_initialize(): """Initialize sentiment analysis model""" try: success = sentiment_analyzer.initialize()
return jsonify({ 'success': success, 'initialized': sentiment_analyzer.is_initialized, 'accuracy': sentiment_analyzer.model_accuracy, 'f1_score': sentiment_analyzer.model_f1_score, 'classes': sentiment_analyzer.classes, 'message': 'Sentiment analysis initialized' if success else 'Failed to initialize' })
except Exception as e: logger.error(f"Sentiment initialization error: {str(e)}") return jsonify({'error': f'Failed to initialize sentiment analysis: {str(e)}'}), 500
@app.route('/sentiment_predict', methods=['POST'])def sentiment_predict(): """Predict sentiment for given text""" try: data = request.get_json() text = data.get('text', '').strip()
if not text: return jsonify({'error': 'Text is required'}), 400
# Make prediction result = sentiment_analyzer.predict_sentiment(text)
return jsonify({ 'success': True, 'text': text, 'category': result.get('category'), 'anxiety_score': result.get('anxiety_score'), 'stress_score': result.get('stress_score'), 'normal_score': result.get('normal_score'), 'all_probabilities': result.get('all_probabilities', {}), 'error': result.get('error') })
except Exception as e: logger.error(f"Sentiment prediction error: {str(e)}") return jsonify({'error': f'Failed to predict sentiment: {str(e)}'}), 500
@app.route('/sentiment_status', methods=['GET'])def sentiment_status(): """Get sentiment analysis status""" try: return jsonify({ 'initialized': sentiment_analyzer.is_initialized, 'accuracy': sentiment_analyzer.model_accuracy, 'f1_score': sentiment_analyzer.model_f1_score, 'classes': sentiment_analyzer.classes })
except Exception as e: logger.error(f"Sentiment status error: {str(e)}") return jsonify({'error': f'Failed to get sentiment status: {str(e)}'}), 500
# ============================================================================# UTILITY FUSION CALCULATION ENDPOINT# ============================================================================
@app.route('/calculate_utility_scores', methods=['POST'])def calculate_utility_scores(): """ Calculate utility fusion scores from heartbeat, emotion, and journal data Expects JSON with: user_id, session_code Returns: anxiety, stress, and normal scores (normalized to 100%) """ try: data = request.get_json() user_id = data.get('user_id') session_code = data.get('session_code')
# Heartbeat data from request (retrieved from PHP by Flutter) heartbeat_data = data.get('heartbeat_data', []) emotion_data = data.get('emotion_data', []) journal_data = data.get('journal_data', [])
if not user_id or not session_code: return jsonify({'error': 'user_id and session_code are required'}), 400
logger.info(f"Calculating utility scores for user={user_id}, session={session_code}") logger.info(f"Received {len(heartbeat_data)} heartbeat records, {len(emotion_data)} emotion records, {len(journal_data)} journal records")
# ===== 1. PROCESS HEARTBEAT DATA ===== hr_stress_score = 0 valid_rr_intervals = []
for hb in heartbeat_data: quality = float(hb.get('quality_score', 0)) rr_interval = float(hb.get('rr_interval', 0))
# Filter: quality >= 50 if quality >= 50 and rr_interval > 0: valid_rr_intervals.append(rr_interval)
logger.info(f"Valid RR intervals (quality >= 50): {len(valid_rr_intervals)}")
# Predict stress using HR model if len(valid_rr_intervals) > 0: hr_prediction = hr_stress_predictor.predict_stress(valid_rr_intervals) hr_stress_score = hr_prediction.get('score', 0) # 100 if stress, 0 if not logger.info(f"HR Stress Prediction: {hr_stress_score} (stress={hr_prediction.get('stress')})") else: logger.warning("No valid RR intervals, using HR stress score = 0")
# ===== 2. PROCESS EMOTION DATA ===== fear_scores = [] angry_scores = [] sad_scores = [] neutral_scores = []
for emotion in emotion_data: face_exist = emotion.get('face_exist', 'no')
# Filter: face_exist = 'yes' if face_exist.lower() == 'yes': fear_scores.append(float(emotion.get('fear_score', 0))) angry_scores.append(float(emotion.get('angry_score', 0))) sad_scores.append(float(emotion.get('sad_score', 0))) neutral_scores.append(float(emotion.get('neutral_score', 0)))
# Calculate averages avg_fear = np.mean(fear_scores) if fear_scores else 0.0 avg_angry = np.mean(angry_scores) if angry_scores else 0.0 avg_sad = np.mean(sad_scores) if sad_scores else 0.0 avg_neutral = np.mean(neutral_scores) if neutral_scores else 0.0
logger.info(f"Emotion averages: fear={avg_fear:.2f}%, angry={avg_angry:.2f}%, sad={avg_sad:.2f}%, neutral={avg_neutral:.2f}%")
# ===== 3. PROCESS JOURNAL DATA ===== anxiety_scores = [] stress_scores = [] normal_scores = []
for journal in journal_data: anxiety_scores.append(float(journal.get('anxiety_score', 0))) stress_scores.append(float(journal.get('stress_score', 0))) normal_scores.append(float(journal.get('normal_score', 0)))
# Calculate averages text_anxiety = np.mean(anxiety_scores) if anxiety_scores else 0.0 text_stress = np.mean(stress_scores) if stress_scores else 0.0 text_normal = np.mean(normal_scores) if normal_scores else 0.0
logger.info(f"Journal averages: anxiety={text_anxiety:.2f}, stress={text_stress:.2f}, normal={text_normal:.2f}")
# ===== 4. UTILITY FUSION CALCULATION ===== # Updated weightage: Text Sentiment = 60%, Emotion = 25%, HR = 15%
# Anxiety score calculation anxiety_raw = ( 0.60 * text_anxiety + 0.25 * (0.45 * avg_fear + 0.25 * avg_sad + 0.20 * avg_angry) + 0.15 * hr_stress_score )
# Stress score calculation stress_raw = ( 0.60 * text_stress + 0.25 * (0.35 * avg_angry + 0.30 * avg_fear + 0.20 * avg_sad) + 0.15 * hr_stress_score )
# Normal score calculation - USE NEUTRAL EMOTION DIRECTLY normal_raw = ( 0.60 * text_normal + 0.25 * avg_neutral + # Use neutral emotion score directly 0.15 * (100 - hr_stress_score) # Inverse of HR stress )
logger.info(f"Raw scores: anxiety={anxiety_raw:.2f}, stress={stress_raw:.2f}, normal={normal_raw:.2f}")
# ===== 5. SOFTMAX NORMALIZATION ===== scores = np.array([anxiety_raw, stress_raw, normal_raw]) exp_scores = np.exp(scores / 10) normalized = (exp_scores / np.sum(exp_scores)) * 100
final_anxiety = float(normalized[0]) final_stress = float(normalized[1]) final_normal = float(normalized[2])
logger.info(f"Normalized scores: anxiety={final_anxiety:.2f}%, stress={final_stress:.2f}%, normal={final_normal:.2f}%") logger.info(f"Sum check: {final_anxiety + final_stress + final_normal:.2f}% (should be 100%)")
return jsonify({ 'success': True, 'user_id': user_id, 'session_code': session_code, 'anxiety_score': round(final_anxiety, 2), 'stress_score': round(final_stress, 2), 'normal_score': round(final_normal, 2), 'raw_scores': { 'anxiety': round(anxiety_raw, 2), 'stress': round(stress_raw, 2), 'normal': round(normal_raw, 2) }, 'input_stats': { 'hr_stress': hr_stress_score, 'valid_rr_intervals': len(valid_rr_intervals), 'emotion_records': len(fear_scores), 'journal_records': len(anxiety_scores), 'avg_fear': round(avg_fear, 2), 'avg_angry': round(avg_angry, 2), 'avg_sad': round(avg_sad, 2), 'avg_neutral': round(avg_neutral, 2), 'text_anxiety': round(text_anxiety, 2), 'text_stress': round(text_stress, 2), 'text_normal': round(text_normal, 2) } })
except Exception as e: logger.error(f"Error calculating utility scores: {str(e)}") import traceback traceback.print_exc() return jsonify({'error': f'Failed to calculate utility scores: {str(e)}'}), 500
# ============================================================================# MODEL INITIALIZATION ON STARTUP (for both direct run and gunicorn)# ============================================================================
def initialize_models(): """Initialize all ML models on startup""" print("\n>> Initializing ML models...") # Initialize sentiment analysis model print(">> Initializing sentiment analysis model...") if sentiment_analyzer.initialize(): print(f">> Sentiment analysis ready! (Accuracy: {sentiment_analyzer.model_accuracy:.2%})") print(f" Classes: {', '.join(sentiment_analyzer.classes)}") else: print(">> WARNING: Sentiment analysis initialization failed") # Initialize HR stress prediction model print("\n>> Initializing HR stress prediction model...") if hr_stress_predictor.initialize(): print(f">> HR stress prediction ready!") print(f" Features: {', '.join(hr_stress_predictor.feature_names) if hr_stress_predictor.feature_names else 'Unknown'}") else: print(">> WARNING: HR stress prediction initialization failed") print("\n>> Model initialization complete!")
# Initialize models when module is loaded (works with gunicorn)initialize_models()
if __name__ == '__main__': print(">> Starting Gemini AI Journaling Backend...") print(f">> API Key configured: {'YES' if GEMINI_API_KEY else 'NO'}") print(f">> Server will be available at: http://{SERVER_IP}:{SERVER_PORT}") print(f">> Also accessible via: http://localhost:{SERVER_PORT}") print("\n>> Available endpoints:") print("\n Conversation:") print(" - POST /start_conversation - Start new conversation") print(" - POST /send_message - Send message and get response (with sentiment analysis)") print(" - GET /get_conversation - Get conversation history") print(" - POST /end_conversation - End conversation")
print("\n Speech-to-Text:") print(" - POST /stt_start - Start STT recording session") print(" - POST /stt_send_chunk - Send audio chunk (optional)") print(" - POST /stt_stop - Stop recording and get transcript") print(" - POST /stt_cancel - Cancel recording session") print(" - POST /stt - Simple file upload STT") print("\n Emotion Detection:") print(" - POST /emotion_initialize - Initialize emotion detection") print(" - POST /emotion_detect - Detect emotion from image frame") print(" - GET /emotion_status - Get emotion detection status") print("\n Sentiment Analysis:") print(" - POST /sentiment_initialize - Initialize sentiment analysis model") print(" - POST /sentiment_predict - Predict sentiment for text") print(" - GET /sentiment_status - Get sentiment analysis status") print("\n Utility Fusion:") print(" - POST /calculate_utility_scores - Calculate fused mental health scores") print("\n System:") print(" - GET /health - Health check")
print("\n" + "="*60) print("Server starting...") print("="*60 + "\n")
# Run without debug mode to prevent constant restarts app.run(debug=False, host='0.0.0.0', port=SERVER_PORT)123version https://git-lfs.github.com/spec/v1oid sha256:f8cf20b4f8be9db6a5c606db783262894e99c8d481984b85fe3bcdaabe4ffbb2size 3233186123456789101112131415161718192021222324252627282930313233343536import osfrom dotenv import load_dotenv
# Load environment variables from .env file (if exists)load_dotenv()
# Configuration file for backend server
# Server IP address - 0.0.0.0 to listen on all network interfaces# This allows the Android emulator to connect via 10.0.2.2SERVER_IP = os.getenv("SERVER_IP", "0.0.0.0")
# Server port - 7860 for Hugging Face Spaces, 5000 for local developmentSERVER_PORT = int(os.getenv("PORT", os.getenv("SERVER_PORT", "7860")))
# Gemini API Key - REQUIRED for AI chat functionality# For Hugging Face Spaces: Add as a Secret named GEMINI_API_KEYGEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "")
# Get full server URLdef get_server_url(): return f"http://{SERVER_IP}:{SERVER_PORT}"
# Google Cloud Speech-to-Text configuration# For Hugging Face Spaces: Upload gcp_key.json or set as base64 encoded SecretGCP_SERVICE_ACCOUNT_FILE = os.getenv("GCP_SERVICE_ACCOUNT_FILE", "gcp_key.json")SPEECH_LANGUAGE_CODE = os.getenv("SPEECH_LANGUAGE_CODE", "en-US")
# Database configuration (Optional - handled by PHP backend in production)ENABLE_FLASK_DB = os.getenv("ENABLE_FLASK_DB", "false").lower() == "true"DB_CONFIG = { 'host': os.getenv("DB_HOST", "localhost"), 'user': os.getenv("DB_USER", ""), 'password': os.getenv("DB_PASSWORD", ""), 'database': os.getenv("DB_NAME", "")}123version https://git-lfs.github.com/spec/v1oid sha256:05922a84469dce5360c098c27dcc4fe0cf13e4a475e02f83dcaa96f1fce3ccb8size 43123version https://git-lfs.github.com/spec/v1oid sha256:08828dfc12b6e13be214bedd40f7b3ec91f7797256bc20b3153a2204a7962d74size 53136123version https://git-lfs.github.com/spec/v1oid sha256:5345c74ea752530af23032ede0742c45a86e24e678c0ed68daf3cedb2e6bfc79size 512123456789101112131415161718192021222324252627# Core Flask dependenciesFlask==2.3.3Flask-CORS==4.0.0flask-sock==0.6.0gunicorn==21.2.0
# Google AI and Cloud Servicesgoogle-generativeai==0.3.2google-cloud-speech==2.26.0google-auth==2.35.0
# Environment configurationpython-dotenv==1.0.0
# Sentiment Analysis & ML Dependenciesscikit-learn==1.3.2numpy==1.26.2
# Optional: Database (only if ENABLE_FLASK_DB=true)mysql-connector-python==8.2.0
# Emotion Detection (Optional - for /emotion_detect endpoint)opencv-python-headless==4.8.1.78fer==22.5.1
# Joblib for loading pkl modelsjoblib==1.3.2.gitignoreAdded+61
DockerfileAdded+48
README.md+113-6
app.pyAdded+1505
best_mental_health_model.pklAdded+3
config.pyAdded+36
haarcascade_frontalface_default.xmlAdded
heartPredictionModel/feature_names.pklAdded+3
heartPredictionModel/stress_model.pklAdded+3
heartPredictionModel/stress_scaler.pklAdded+3
requirements.txtAdded+27