diff --git a/backend/alwrity_utils/production_optimizer.py b/backend/alwrity_utils/production_optimizer.py index 6ea87a2f..5fc3b9a3 100644 --- a/backend/alwrity_utils/production_optimizer.py +++ b/backend/alwrity_utils/production_optimizer.py @@ -39,9 +39,10 @@ class ProductionOptimizer: def _set_production_env_vars(self) -> None: """Set production-specific environment variables.""" production_vars = { + # Note: PORT is NOT set here - it's provided by the deployment platform (e.g., Render) + # Don't override PORT as it must come from the environment # Note: HOST is not set here - it's auto-detected by start_backend() # Based on deployment environment (cloud vs local) - 'PORT': '8000', 'RELOAD': 'false', 'LOG_LEVEL': 'INFO', 'DEBUG': 'false', diff --git a/backend/app.py b/backend/app.py index 88d5a68a..3ee7b05b 100644 --- a/backend/app.py +++ b/backend/app.py @@ -14,9 +14,12 @@ from pathlib import Path from dotenv import load_dotenv backend_dir = Path(__file__).parent project_root = backend_dir.parent -load_dotenv(backend_dir / '.env') -load_dotenv(project_root / '.env') -load_dotenv() + +# Load .env but DON'T override existing environment variables (especially PORT from Render) +# Use override=False to preserve Render-provided PORT +load_dotenv(backend_dir / '.env', override=False) +load_dotenv(project_root / '.env', override=False) +load_dotenv(override=False) # Set LOG_LEVEL early to WARNING to suppress DEBUG persona logs in podcast mode import os diff --git a/backend/services/persona_analysis_service.py b/backend/services/persona_analysis_service.py index a8082ad8..b6832588 100644 --- a/backend/services/persona_analysis_service.py +++ b/backend/services/persona_analysis_service.py @@ -18,9 +18,12 @@ import json from services.database import get_db_session from models.onboarding import OnboardingSession, WebsiteAnalysis, ResearchPreferences from models.persona_models import WritingPersona, PlatformPersona, PersonaAnalysisResult -from services.persona.core_persona import CorePersonaService, OnboardingDataCollector -from services.persona.linkedin.linkedin_persona_service import LinkedInPersonaService -from services.persona.facebook.facebook_persona_service import FacebookPersonaService + +def _get_podcast_mode(): + """Check if running in podcast-only mode to skip heavy initialization.""" + import os + env_val = os.getenv("ALWRITY_ENABLED_FEATURES", "").strip().lower() + return env_val == "podcast" class PersonaAnalysisService: """Service for analyzing onboarding data and generating writing personas using Gemini AI.""" @@ -37,12 +40,40 @@ class PersonaAnalysisService: def __init__(self): """Initialize the persona analysis service (only once).""" if not self._initialized: + # Skip heavy initialization in podcast-only mode + if _get_podcast_mode(): + logger.debug("PersonaAnalysisService: Skipping heavy init in podcast mode") + self._initialized = True + return + + # Only initialize heavy services when needed (not at import time) + self._heavy_init_done = False + + def _ensure_heavy_init(self): + """Lazily initialize heavy services only when first used.""" + if self._heavy_init_done: + return + + # Check again in case mode changed + if _get_podcast_mode(): + logger.debug("PersonaAnalysisService: Skipping heavy init in podcast mode") + self._heavy_init_done = True + return + + try: + from services.persona.core_persona import CorePersonaService, OnboardingDataCollector + from services.persona.linkedin.linkedin_persona_service import LinkedInPersonaService + from services.persona.facebook.facebook_persona_service import FacebookPersonaService + self.core_persona_service = CorePersonaService() self.data_collector = OnboardingDataCollector() self.linkedin_service = LinkedInPersonaService() self.facebook_service = FacebookPersonaService() - logger.debug("PersonaAnalysisService initialized") - self._initialized = True + self._heavy_init_done = True + logger.debug("PersonaAnalysisService initialized (lazy)") + except Exception as e: + logger.warning(f"PersonaAnalysisService: Failed to initialize heavy services: {e}") + self._heavy_init_done = True def generate_persona_from_onboarding(self, user_id: str, onboarding_session_id: int = None) -> Dict[str, Any]: """ @@ -55,6 +86,13 @@ class PersonaAnalysisService: Returns: Generated persona data with platform adaptations """ + # Ensure heavy services are initialized + self._ensure_heavy_init() + + # Check if heavy init failed (podcast mode) + if not getattr(self, '_heavy_init_done', False): + return {"error": "Persona service unavailable in podcast-only mode"} + try: logger.info(f"Generating persona for user {user_id}") diff --git a/backend/start_alwrity_backend.py b/backend/start_alwrity_backend.py index 6efae468..97254bcf 100644 --- a/backend/start_alwrity_backend.py +++ b/backend/start_alwrity_backend.py @@ -225,11 +225,12 @@ from pathlib import Path backend_dir = Path(__file__).parent load_dotenv(backend_dir / '.env') -# Debug: Print what PORT is set to +# Debug: Print what PORT is set to - IMMEDIATELY at startup import os -print(f"[DEBUG] PORT env: {os.getenv('PORT')}") -print(f"[DEBUG] RENDER env: {os.getenv('RENDER')}") -print(f"[DEBUG] ALWRITY_ENABLED_FEATURES: {os.getenv('ALWRITY_ENABLED_FEATURES')}") +print(f"[STARTUP] PORT env: {os.getenv('PORT')}", flush=True) +print(f"[STARTUP] RENDER env: {os.getenv('RENDER')}", flush=True) +print(f"[STARTUP] ALWRITY_ENABLED_FEATURES: {os.getenv('ALWRITY_ENABLED_FEATURES')}", flush=True) +print(f"[STARTUP] HOST env: {os.getenv('HOST')}", flush=True) if __name__ == "__main__": enabled_features = get_enabled_features()