Spaces:
Sleeping

backendAPI / app.py
changweikoy's picture
Fix TypeError: Convert numeric classes to strings in initialize_models
75136b3
Raw History Blame Contribute Delete
64.3 kB
from flask import Flask, request, jsonify, send_from_directory from flask_cors import CORS from flask_sock import Sock import google.generativeai as genai import os import json from datetime import datetime import logging import asyncio import threading from io import BytesIO import numpy as np import pickle import re from config import GEMINI_API_KEY, SERVER_IP, SERVER_PORT from config import GCP_SERVICE_ACCOUNT_FILE, SPEECH_LANGUAGE_CODE from config import DB_CONFIG, ENABLE_FLASK_DB from text_utils import clean_text import sys # HACK: Inject clean_text into the __main__ module. # Pickled models saved in a notebook often expect to find functions in '__main__'. # When running with gunicorn, __main__ is gunicorn, so we must manually inject it. import __main__ __main__.clean_text = clean_text # Also inject into this module's name for extra safety sys.modules['app'].clean_text = clean_text # MySQL database imports try: import mysql.connector from mysql.connector import Error as MySQLError _mysql_available = True except Exception: _mysql_available = False logging.warning("MySQL connector not available") # Emotion detection imports try: import cv2 from fer import FER _emotion_detection_available = True except Exception as e: _emotion_detection_available = False logging.warning(f"Emotion detection not available: {e}") # Google Cloud Speech-to-Text try: from google.oauth2 import service_account from google.cloud import speech _speech_available = True except Exception: _speech_available = False # GCP Credentials - Support both file and environment variable (for Hugging Face Spaces) _gcp_credentials = None if _speech_available: # Try environment variable first (Hugging Face Spaces secret) gcp_json_str = os.environ.get('GCP_CREDENTIALS_JSON') if gcp_json_str: try: import json as json_module gcp_info = json_module.loads(gcp_json_str) _gcp_credentials = service_account.Credentials.from_service_account_info(gcp_info) logging.info("GCP credentials loaded from GCP_CREDENTIALS_JSON environment variable") except Exception as e: logging.warning(f"Failed to parse GCP_CREDENTIALS_JSON: {e}") # Fallback to file if env var not available elif GCP_SERVICE_ACCOUNT_FILE and os.path.exists(GCP_SERVICE_ACCOUNT_FILE): try: _gcp_credentials = service_account.Credentials.from_service_account_file(GCP_SERVICE_ACCOUNT_FILE) logging.info(f"GCP credentials loaded from file: {GCP_SERVICE_ACCOUNT_FILE}") except Exception as e: logging.warning(f"Failed to load GCP credentials from file: {e}") if _gcp_credentials is None: _speech_available = False logging.warning("Speech-to-Text: No GCP credentials available") # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) app = Flask(__name__) CORS(app) # Enable CORS for Flutter app sock = Sock(app) # Enable WebSocket support # Configure Gemini AI genai.configure(api_key=GEMINI_API_KEY) # Initialize Gemini model model = 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 detector emotion_bridge = EmotionDetectionBridge() # Sentiment analysis text cleaning is now imported from text_utils.py # ============================================================================ # 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__), 'text_model', 'best_mental_health_model_new.pkl' ) if not os.path.exists(model_path): logger.error(f"Model file not found at: {model_path}") return False model_data = None # Try joblib first (more robust for sklearn models) try: import joblib model_data = joblib.load(model_path) logger.info("Model loaded with joblib") except Exception as e: logger.warning(f"Joblib load failed: {e}, trying pickle...") # Fallback to pickle with different approaches if model_data is None: try: with open(model_path, 'rb') as f: model_data = pickle.load(f) logger.info("Model loaded with pickle") except AttributeError as e: # Handle the case where text_cleaner function can't be found logger.warning(f"Pickle AttributeError (likely function reference): {e}") # Try loading with custom unpickler that ignores missing functions import io class CustomUnpickler(pickle.Unpickler): def find_class(self, module, name): # Replace any missing function with our module-level clean_text if name == 'clean_text' or 'clean' in name.lower(): return clean_text return super().find_class(module, name) with open(model_path, 'rb') as f: model_data = CustomUnpickler(f).load() logger.info("Model loaded with custom unpickler") if model_data is None: logger.error("Failed to load model with all methods") return False # Extract components (support both old and new model key names) self.model = model_data['model'] # New model uses 'tfidf', old model uses 'tfidf_vectorizer' self.tfidf_vectorizer = model_data.get('tfidf') or model_data.get('tfidf_vectorizer') self.label_encoder = model_data.get('label_encoder') # Always use module-level clean_text to avoid pickle issues self.text_cleaner = clean_text self.model_accuracy = model_data.get('accuracy', 0.0) self.model_f1_score = model_data.get('f1_score', 0.0) # Get classes from model or label_encoder self.classes = model_data.get('classes', []) if not self.classes and hasattr(self.model, 'classes_'): self.classes = list(self.model.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)[0] # Handle numeric predictions (new model uses 0,1,2 with label_encoder) if self.label_encoder is not None and hasattr(self.label_encoder, 'inverse_transform'): try: predicted_category = self.label_encoder.inverse_transform([prediction])[0].lower() except: predicted_category = str(prediction).lower() else: predicted_category = str(prediction).lower() # Get probability scores using predict_proba probabilities = self.model.predict_proba(text_vectorized)[0] # Map probabilities to specific scores # Use label_encoder classes if available, otherwise use model classes if self.label_encoder is not None and hasattr(self.label_encoder, 'classes_'): class_labels = self.label_encoder.classes_ elif hasattr(self.model, 'classes_'): class_labels = self.model.classes_ else: class_labels = ['Anxiety', 'Normal', 'Stress'] prob_dict = { str(label).lower(): round(prob * 100, 2) for label, prob in zip(class_labels, 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 analyzer sentiment_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 # Helper function to load pkl with joblib fallback def load_pkl(path): try: import joblib return joblib.load(path) except Exception: with open(path, 'rb') as f: return pickle.load(f, encoding='bytes') # Load model components print(f" Loading stress_model.pkl...") self.model = load_pkl(model_path) print(f" Loading stress_scaler.pkl...") self.scaler = load_pkl(scaler_path) print(f" Loading feature_names.pkl...") self.feature_names = load_pkl(features_path) # 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 predictor hr_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 using pre-loaded credentials if _gcp_credentials is None: return jsonify({'error': 'GCP credentials not configured'}), 500 speech_client = speech.SpeechClient(credentials=_gcp_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 (USER MESSAGES ONLY) ===== anxiety_scores = [] stress_scores = [] normal_scores = [] for journal in journal_data: # Only count USER messages, not Gemini/AI responses role = journal.get('role', '').lower() if role == 'user': 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 (divided by number of USER messages only) 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 (user messages only): anxiety={text_anxiety:.2f}, stress={text_stress:.2f}, normal={text_normal:.2f}") logger.info(f"User message count: {len(anxiety_scores)}") # ===== 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 emotion detection (haarcascade + FER) print(">> Initializing emotion detection...") if _emotion_detection_available: if emotion_bridge.initialize(): print(">> Emotion detection ready!") print(f" Haarcascade: loaded") else: print(">> WARNING: Emotion detection initialization failed") else: print(">> WARNING: Emotion detection not available (missing dependencies)") # Initialize sentiment analysis model print("\n>> Initializing sentiment analysis model...") if sentiment_analyzer.initialize(): print(f">> Sentiment analysis ready! (Accuracy: {sentiment_analyzer.model_accuracy:.2%})") print(f" Classes: {', '.join(str(c) for c in 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() # ============================================================================ # STATIC FILE SERVING (For Flutter App to download models) # ============================================================================ @app.route('/models/<path:filename>') def serve_models(filename): """Serve model files (XML, PKL) to the Flutter app""" # Only allow specific file types for security allowed_extensions = {'.xml', '.pkl', '.json', '.txt'} file_ext = os.path.splitext(filename)[1].lower() if file_ext not in allowed_extensions: return jsonify({'error': 'File type not allowed'}), 403 return send_from_directory(os.path.dirname(os.path.abspath(__file__)), filename) @app.route('/haarcascade_frontalface_default.xml') def serve_cascade(): """Direct shortcut to serve the haarcascade file""" return send_from_directory(os.path.dirname(os.path.abspath(__file__)), 'haarcascade_frontalface_default.xml') 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)
from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
from flask_sock import Sock
import google.generativeai as genai
import os
import json
from datetime import datetime
import logging
import asyncio
import threading
from io import BytesIO
import numpy as np
import pickle
import re
from config import GEMINI_API_KEY, SERVER_IP, SERVER_PORT
from config import GCP_SERVICE_ACCOUNT_FILE, SPEECH_LANGUAGE_CODE
from config import DB_CONFIG, ENABLE_FLASK_DB
from text_utils import clean_text
import sys
# HACK: Inject clean_text into the __main__ module.
# Pickled models saved in a notebook often expect to find functions in '__main__'.
# When running with gunicorn, __main__ is gunicorn, so we must manually inject it.
import __main__
__main__.clean_text = clean_text
# Also inject into this module's name for extra safety
sys.modules['app'].clean_text = clean_text
# MySQL database imports
try:
import mysql.connector
from mysql.connector import Error as MySQLError
_mysql_available = True
except Exception:
_mysql_available = False
logging.warning("MySQL connector not available")
# Emotion detection imports
try:
import cv2
from fer import FER
_emotion_detection_available = True
except Exception as e:
_emotion_detection_available = False
logging.warning(f"Emotion detection not available: {e}")
# Google Cloud Speech-to-Text
try:
from google.oauth2 import service_account
from google.cloud import speech
_speech_available = True
except Exception:
_speech_available = False
# GCP Credentials - Support both file and environment variable (for Hugging Face Spaces)
_gcp_credentials = None
if _speech_available:
# Try environment variable first (Hugging Face Spaces secret)
gcp_json_str = os.environ.get('GCP_CREDENTIALS_JSON')
if gcp_json_str:
try:
import json as json_module
gcp_info = json_module.loads(gcp_json_str)
_gcp_credentials = service_account.Credentials.from_service_account_info(gcp_info)
logging.info("GCP credentials loaded from GCP_CREDENTIALS_JSON environment variable")
except Exception as e:
logging.warning(f"Failed to parse GCP_CREDENTIALS_JSON: {e}")
# Fallback to file if env var not available
elif GCP_SERVICE_ACCOUNT_FILE and os.path.exists(GCP_SERVICE_ACCOUNT_FILE):
try:
_gcp_credentials = service_account.Credentials.from_service_account_file(GCP_SERVICE_ACCOUNT_FILE)
logging.info(f"GCP credentials loaded from file: {GCP_SERVICE_ACCOUNT_FILE}")
except Exception as e:
logging.warning(f"Failed to load GCP credentials from file: {e}")
if _gcp_credentials is None:
_speech_available = False
logging.warning("Speech-to-Text: No GCP credentials available")
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = Flask(__name__)
CORS(app) # Enable CORS for Flutter app
sock = Sock(app) # Enable WebSocket support
# Configure Gemini AI
genai.configure(api_key=GEMINI_API_KEY)
# Initialize Gemini model
model = 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