Improve NHL logo rendering and logging - Add logo caching to prevent redundant loading - Change logo-related logging to DEBUG level - Reduce update intervals for non-live games - Add proper RGB/RGBA image handling - Improve error handling and logging format - Set dedicated NHL logger with appropriate level

This commit is contained in:
ChuckBuilds
2025-04-18 11:06:00 -05:00
parent 2c8bae462b
commit d5edc2c07f
2 changed files with 187 additions and 158 deletions

View File

@@ -10,7 +10,15 @@ from src.stock_news_manager import StockNewsManager
from src.nhl_managers import NHLLiveManager, NHLRecentManager, NHLUpcomingManager from src.nhl_managers import NHLLiveManager, NHLRecentManager, NHLUpcomingManager
# Configure logging # Configure logging
logging.basicConfig(level=logging.INFO) logging.basicConfig(
level=logging.INFO,
format='%(levelname)s:%(name)s:%(message)s'
)
# Set NHL logger to INFO level to reduce spam
nhl_logger = logging.getLogger('NHL')
nhl_logger.setLevel(logging.INFO)
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class DisplayController: class DisplayController:

View File

@@ -13,18 +13,19 @@ ESPN_NHL_SCOREBOARD_URL = "https://site.api.espn.com/apis/site/v2/sports/hockey/
class BaseNHLManager: class BaseNHLManager:
"""Base class for NHL managers with common functionality.""" """Base class for NHL managers with common functionality."""
def __init__(self, config: dict, display_manager): def __init__(self, config: Dict[str, Any], display_manager: DisplayManager):
self.display_manager = display_manager self.display_manager = display_manager
self.config = config self.config = config
self.nhl_config = config.get("nhl_scoreboard", {}) self.nhl_config = config.get("nhl_scoreboard", {})
self.is_enabled = self.nhl_config.get("enabled", False) self.is_enabled = self.nhl_config.get("enabled", False)
self.test_mode = self.nhl_config.get("test_mode", False) self.test_mode = self.nhl_config.get("test_mode", False)
self.logo_dir = Path(config.get("nhl_scoreboard", {}).get("logo_dir", "assets/sports/nhl_logos")) self.logo_dir = self.nhl_config.get("logo_dir", "assets/sports/nhl_logos")
self.update_interval = self.nhl_config.get("update_interval_seconds", 60) self.update_interval = self.nhl_config.get("update_interval_seconds", 60)
self.last_update = 0 self.last_update = 0
self.current_game = None self.current_game = None
self.fonts = self._load_fonts() self.fonts = self._load_fonts()
self.favorite_teams = self.nhl_config.get("favorite_teams", []) self.favorite_teams = self.nhl_config.get("favorite_teams", [])
self.logger = logging.getLogger('NHL')
# Get display dimensions from config # Get display dimensions from config
display_config = config.get("display", {}) display_config = config.get("display", {})
@@ -34,9 +35,16 @@ class BaseNHLManager:
self.display_width = int(cols * chain) self.display_width = int(cols * chain)
self.display_height = hardware_config.get("rows", 32) self.display_height = hardware_config.get("rows", 32)
# Load fonts
self.font = ImageFont.truetype("assets/fonts/4x6.bdf", 6)
self.small_font = ImageFont.truetype("assets/fonts/3x5.bdf", 5)
# Cache for loaded logos
self._logo_cache = {}
self.logger.info(f"Initialized NHL manager with display dimensions: {self.display_width}x{self.display_height}")
logging.info(f"[NHL] Test mode: {'enabled' if self.test_mode else 'disabled'}") logging.info(f"[NHL] Test mode: {'enabled' if self.test_mode else 'disabled'}")
logging.info(f"[NHL] Favorite teams: {self.favorite_teams}") logging.info(f"[NHL] Favorite teams: {self.favorite_teams}")
logging.info(f"[NHL] Display dimensions: {self.display_width}x{self.display_height}")
def _load_fonts(self): def _load_fonts(self):
"""Load fonts used by the scoreboard.""" """Load fonts used by the scoreboard."""
@@ -54,24 +62,37 @@ class BaseNHLManager:
fonts['status'] = ImageFont.load_default() fonts['status'] = ImageFont.load_default()
return fonts return fonts
def _load_and_resize_logo(self, logo_path: Path, max_size: tuple) -> Optional[Image.Image]: def _load_and_resize_logo(self, team_abbrev: str) -> Optional[Image.Image]:
"""Load and resize a logo image.""" """Load and resize a team logo, with caching."""
if not logo_path or not logo_path.is_file(): if team_abbrev in self._logo_cache:
logging.warning(f"[NHL] Logo file not found: {logo_path}") return self._logo_cache[team_abbrev]
return None
logo_path = os.path.join(self.logo_dir, f"{team_abbrev}.png")
self.logger.debug(f"Loading logo from: {logo_path}")
try: try:
logging.info(f"[NHL] Loading logo from: {logo_path}")
logo = Image.open(logo_path) logo = Image.open(logo_path)
original_size = logo.size
self.logger.debug(f"Original logo size: {original_size}")
# Convert to RGBA if not already
if logo.mode != 'RGBA': if logo.mode != 'RGBA':
logging.info(f"[NHL] Converting logo from {logo.mode} to RGBA")
logo = logo.convert('RGBA') logo = logo.convert('RGBA')
logging.info(f"[NHL] Original logo size: {logo.size}")
logo.thumbnail(max_size, Image.Resampling.LANCZOS) # Calculate max size based on display dimensions
logging.info(f"[NHL] Resized logo size: {logo.size}") max_width = self.display_width // 4 # Quarter of display width
max_height = self.display_height // 2 # Half of display height
# Resize maintaining aspect ratio
logo.thumbnail((max_width, max_height), Image.Resampling.LANCZOS)
self.logger.debug(f"Resized logo size: {logo.size}")
# Cache the resized logo
self._logo_cache[team_abbrev] = logo
return logo return logo
except Exception as e: except Exception as e:
logging.error(f"[NHL] Error loading logo {logo_path}: {e}") self.logger.error(f"Error loading logo for {team_abbrev}: {e}")
return None return None
def _fetch_data(self, date_str: str = None) -> Optional[Dict]: def _fetch_data(self, date_str: str = None) -> Optional[Dict]:
@@ -162,8 +183,8 @@ class BaseNHLManager:
max_size = (self.display_width // 3, self.display_height // 2) max_size = (self.display_width // 3, self.display_height // 2)
# Load and resize logos # Load and resize logos
home_logo = self._load_and_resize_logo(self.current_game["home_logo_path"], max_size) home_logo = self._load_and_resize_logo(self.current_game["home_abbr"])
away_logo = self._load_and_resize_logo(self.current_game["away_logo_path"], max_size) away_logo = self._load_and_resize_logo(self.current_game["away_abbr"])
# Draw home team logo # Draw home team logo
if home_logo: if home_logo:
@@ -210,9 +231,11 @@ class BaseNHLManager:
class NHLLiveManager(BaseNHLManager): class NHLLiveManager(BaseNHLManager):
"""Manager for live NHL games.""" """Manager for live NHL games."""
def __init__(self, config: dict, display_manager): def __init__(self, config: Dict[str, Any], display_manager: DisplayManager):
super().__init__(config, display_manager) super().__init__(config, display_manager)
self.update_interval = self.nhl_config.get("live_update_interval", 30) # More frequent updates for live games self.update_interval = self.nhl_config.get("live_update_interval", 30)
self.last_update = 0
self.logger.info("Initialized NHL Live Manager")
# Initialize with test game only if test mode is enabled # Initialize with test game only if test mode is enabled
if self.test_mode: if self.test_mode:
@@ -233,9 +256,9 @@ class NHLLiveManager(BaseNHLManager):
def update(self): def update(self):
"""Update live game data.""" """Update live game data."""
current_time = time.time() current_time = time.time()
if current_time - self.last_update < self.update_interval: if current_time - self.last_update >= self.update_interval:
return self.logger.debug("Updating live game data")
self.last_update = current_time
if self.test_mode: if self.test_mode:
# For testing, we'll just update the clock to show it's working # For testing, we'll just update the clock to show it's working
if self.current_game: if self.current_game:
@@ -273,8 +296,6 @@ class NHLLiveManager(BaseNHLManager):
self.current_game = None self.current_game = None
logging.info("[NHL] No live games found") logging.info("[NHL] No live games found")
self.last_update = current_time
def display(self, force_clear: bool = False): def display(self, force_clear: bool = False):
"""Display live game information.""" """Display live game information."""
if not self.current_game: if not self.current_game:
@@ -291,8 +312,8 @@ class NHLLiveManager(BaseNHLManager):
logging.info(f"[NHL] Logo max size: {max_size}") logging.info(f"[NHL] Logo max size: {max_size}")
# Load and resize logos # Load and resize logos
home_logo = self._load_and_resize_logo(self.current_game["home_logo_path"], max_size) home_logo = self._load_and_resize_logo(self.current_game["home_abbr"])
away_logo = self._load_and_resize_logo(self.current_game["away_logo_path"], max_size) away_logo = self._load_and_resize_logo(self.current_game["away_abbr"])
logging.info(f"[NHL] Home logo loaded: {home_logo is not None}, path: {self.current_game['home_logo_path']}") logging.info(f"[NHL] Home logo loaded: {home_logo is not None}, path: {self.current_game['home_logo_path']}")
logging.info(f"[NHL] Away logo loaded: {away_logo is not None}, path: {self.current_game['away_logo_path']}") logging.info(f"[NHL] Away logo loaded: {away_logo is not None}, path: {self.current_game['away_logo_path']}")
@@ -348,9 +369,11 @@ class NHLLiveManager(BaseNHLManager):
class NHLRecentManager(BaseNHLManager): class NHLRecentManager(BaseNHLManager):
"""Manager for recently completed NHL games.""" """Manager for recently completed NHL games."""
def __init__(self, config: dict, display_manager): def __init__(self, config: Dict[str, Any], display_manager: DisplayManager):
super().__init__(config, display_manager) super().__init__(config, display_manager)
self.update_interval = self.nhl_config.get("recent_update_interval", 3600) # 1 hour self.update_interval = self.nhl_config.get("recent_update_interval", 300) # 5 minutes
self.last_update = 0
self.logger.info("Initialized NHL Recent Manager")
self.recent_hours = self.nhl_config.get("recent_game_hours", 48) # Default 48 hours self.recent_hours = self.nhl_config.get("recent_game_hours", 48) # Default 48 hours
self.current_game = None self.current_game = None
@@ -372,9 +395,9 @@ class NHLRecentManager(BaseNHLManager):
def update(self): def update(self):
"""Update recent game data.""" """Update recent game data."""
current_time = time.time() current_time = time.time()
if current_time - self.last_update < self.update_interval: if current_time - self.last_update >= self.update_interval:
return self.logger.debug("Updating recent game data")
self.last_update = current_time
if self.test_mode: if self.test_mode:
# In test mode, just keep the test game # In test mode, just keep the test game
pass pass
@@ -409,8 +432,6 @@ class NHLRecentManager(BaseNHLManager):
else: else:
logging.info("[NHL] No recent games found") logging.info("[NHL] No recent games found")
self.last_update = current_time
def display(self, force_clear: bool = False): def display(self, force_clear: bool = False):
"""Display recent game information.""" """Display recent game information."""
if not self.current_game: if not self.current_game:
@@ -427,8 +448,8 @@ class NHLRecentManager(BaseNHLManager):
logging.info(f"[NHL] Logo max size: {max_size}") logging.info(f"[NHL] Logo max size: {max_size}")
# Load and resize logos # Load and resize logos
home_logo = self._load_and_resize_logo(self.current_game["home_logo_path"], max_size) home_logo = self._load_and_resize_logo(self.current_game["home_abbr"])
away_logo = self._load_and_resize_logo(self.current_game["away_logo_path"], max_size) away_logo = self._load_and_resize_logo(self.current_game["away_abbr"])
logging.info(f"[NHL] Home logo loaded: {home_logo is not None}, path: {self.current_game['home_logo_path']}") logging.info(f"[NHL] Home logo loaded: {home_logo is not None}, path: {self.current_game['home_logo_path']}")
logging.info(f"[NHL] Away logo loaded: {away_logo is not None}, path: {self.current_game['away_logo_path']}") logging.info(f"[NHL] Away logo loaded: {away_logo is not None}, path: {self.current_game['away_logo_path']}")
@@ -481,9 +502,11 @@ class NHLRecentManager(BaseNHLManager):
class NHLUpcomingManager(BaseNHLManager): class NHLUpcomingManager(BaseNHLManager):
"""Manager for upcoming NHL games.""" """Manager for upcoming NHL games."""
def __init__(self, config: dict, display_manager): def __init__(self, config: Dict[str, Any], display_manager: DisplayManager):
super().__init__(config, display_manager) super().__init__(config, display_manager)
self.update_interval = self.nhl_config.get("upcoming_update_interval", 3600) # 1 hour self.update_interval = self.nhl_config.get("upcoming_update_interval", 300) # 5 minutes
self.last_update = 0
self.logger.info("Initialized NHL Upcoming Manager")
self.current_game = None self.current_game = None
if self.test_mode: if self.test_mode:
@@ -502,9 +525,9 @@ class NHLUpcomingManager(BaseNHLManager):
def update(self): def update(self):
"""Update upcoming game data.""" """Update upcoming game data."""
current_time = time.time() current_time = time.time()
if current_time - self.last_update < self.update_interval: if current_time - self.last_update >= self.update_interval:
return self.logger.debug("Updating upcoming game data")
self.last_update = current_time
if self.test_mode: if self.test_mode:
# In test mode, just keep the test game # In test mode, just keep the test game
pass pass
@@ -551,8 +574,6 @@ class NHLUpcomingManager(BaseNHLManager):
else: else:
logging.info("[NHL] No upcoming games found") logging.info("[NHL] No upcoming games found")
self.last_update = current_time
def display(self, force_clear: bool = False): def display(self, force_clear: bool = False):
"""Display upcoming game information.""" """Display upcoming game information."""
if not self.current_game: if not self.current_game:
@@ -569,8 +590,8 @@ class NHLUpcomingManager(BaseNHLManager):
logging.info(f"[NHL] Logo max size: {max_size}") logging.info(f"[NHL] Logo max size: {max_size}")
# Load and resize logos # Load and resize logos
home_logo = self._load_and_resize_logo(self.current_game["home_logo_path"], max_size) home_logo = self._load_and_resize_logo(self.current_game["home_abbr"])
away_logo = self._load_and_resize_logo(self.current_game["away_logo_path"], max_size) away_logo = self._load_and_resize_logo(self.current_game["away_abbr"])
logging.info(f"[NHL] Home logo loaded: {home_logo is not None}, path: {self.current_game['home_logo_path']}") logging.info(f"[NHL] Home logo loaded: {home_logo is not None}, path: {self.current_game['home_logo_path']}")
logging.info(f"[NHL] Away logo loaded: {away_logo is not None}, path: {self.current_game['away_logo_path']}") logging.info(f"[NHL] Away logo loaded: {away_logo is not None}, path: {self.current_game['away_logo_path']}")