fix(backend): lazy-load PersonaAnalysisService in podcast mode, preserve PORT from Render
This commit is contained in:
@@ -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',
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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}")
|
||||
|
||||
|
||||
@@ -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()
|
||||
|
||||
Reference in New Issue
Block a user