Lemontropia-Suite/modules/auto_screenshot.py

132 lines
4.5 KiB
Python

"""
Lemontropia Suite - Auto Screenshot
Automatically capture screenshots on important events.
"""
import cv2
import logging
from pathlib import Path
from datetime import datetime
from typing import Optional, List
import mss
import numpy as np
logger = logging.getLogger(__name__)
class AutoScreenshot:
"""
Auto-screenshot capture system.
Captures screen on globals, HoFs, or user-defined events.
"""
def __init__(self, screenshot_dir: Optional[Path] = None):
# Default to Documents/Entropia Universe/Screenshots
if screenshot_dir is None:
screenshot_dir = Path.home() / "Documents" / "Entropia Universe" / "Screenshots"
self.screenshot_dir = screenshot_dir
self.screenshot_dir.mkdir(parents=True, exist_ok=True)
self.session_screenshots: List[Path] = []
# Settings
self.on_global = True
self.on_hof = True
self.on_profit_threshold = False
self.profit_threshold = 50 # PED
def capture_full_screen(self, filename: Optional[str] = None) -> Path:
"""Capture full screen."""
if filename is None:
filename = f"screenshot_{datetime.now():%Y%m%d_%H%M%S}.png"
filepath = self.screenshot_dir / filename
try:
# Create fresh mss context for thread safety
with mss.mss() as sct:
monitor = sct.monitors[1] # Primary monitor
screenshot = sct.grab(monitor)
img = np.array(screenshot)
img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
cv2.imwrite(str(filepath), img)
self.session_screenshots.append(filepath)
logger.info(f"Screenshot saved: {filepath}")
return filepath
except Exception as e:
logger.error(f"Failed to capture screenshot: {e}")
return None
def capture_region(self, x: int, y: int, w: int, h: int,
filename: Optional[str] = None) -> Path:
"""Capture specific region."""
if filename is None:
filename = f"region_{datetime.now():%Y%m%d_%H%M%S}.png"
filepath = self.screenshot_dir / filename
try:
# Create fresh mss context for thread safety
with mss.mss() as sct:
monitor = {"left": x, "top": y, "width": w, "height": h}
screenshot = sct.grab(monitor)
img = np.array(screenshot)
img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
cv2.imwrite(str(filepath), img)
self.session_screenshots.append(filepath)
logger.info(f"Region screenshot saved: {filepath}")
return filepath
except Exception as e:
logger.error(f"Failed to capture region: {e}")
return None
def on_global(self, item_name: str, value: float):
"""Handle global event."""
if not self.on_global:
return
filename = f"global_{datetime.now():%Y%m%d_%H%M%S}_{item_name[:20]}.png"
self.capture_full_screen(filename)
def on_hof(self, item_name: str, value: float):
"""Handle HoF event."""
if not self.on_hof:
return
filename = f"hof_{datetime.now():%Y%m%d_%H%M%S}_{item_name[:20]}.png"
self.capture_full_screen(filename)
def get_session_summary(self) -> dict:
"""Get summary of screenshots taken this session."""
return {
'total_screenshots': len(self.session_screenshots),
'directory': str(self.screenshot_dir),
'screenshots': [str(p) for p in self.session_screenshots]
}
class ScreenshotViewer:
"""
Simple viewer for browsing screenshots.
"""
def __init__(self, screenshot_dir: Optional[Path] = None):
self.screenshot_dir = screenshot_dir or Path.home() / ".lemontropia" / "screenshots"
def list_screenshots(self, pattern: str = "*.png") -> List[Path]:
"""List all screenshots."""
return sorted(self.screenshot_dir.glob(pattern), key=lambda x: x.stat().st_mtime, reverse=True)
def view_latest(self, n: int = 5):
"""View latest N screenshots."""
screenshots = self.list_screenshots()[:n]
for i, path in enumerate(screenshots, 1):
print(f"{i}. {path.name} ({path.stat().st_size / 1024:.1f} KB)")
# Export main classes
__all__ = ['AutoScreenshot', 'ScreenshotViewer']