cdda-cataclysm-gameplay / cdda_logger.py
Xnsviel's picture
revert update
0e466d8 verified
import os
import time
import json
import datetime
import sys
import mss
import mss.tools
import pygetwindow as gw
import keyboard
import numpy as np
from PIL import Image
# ================= CONFIGURATION =================
WINDOW_TITLE = "Cataclysm" # Window title to search for
CHECK_FREQ = 0.1 # Check interval (seconds)
MAX_RES = 1024 # Max resolution (longest side)
# Standard US Layout Shift Map
SHIFT_MAP = {
'1': '!', '2': '@', '3': '#', '4': '$', '5': '%', '6': '^', '7': '&', '8': '*', '9': '(', '0': ')',
'-': '_', '=': '+',
'[': '{', ']': '}', '\\': '|',
';': ':', "'": '"',
',': '<', '.': '>', '/': '?',
'`': '~'
}
# =================================================
class CDDALogger:
def __init__(self):
self.run_id = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
self.base_dir = os.path.join(os.getcwd(), f"run_{self.run_id}")
self.img_dir = os.path.join(self.base_dir, "images")
self.jsonl_path = os.path.join(self.base_dir, "data.jsonl")
self.turn_count = 0
self.last_key = None
self.prev_image_array = None
self.running = True
os.makedirs(self.img_dir, exist_ok=True)
print(f"[*] Initialized. Saving to: {self.base_dir}")
def get_window_region(self):
"""Finds the game window geometry."""
try:
windows = gw.getWindowsWithTitle(WINDOW_TITLE)
if not windows:
return None
win = windows[0]
if win.isActive:
return {
"top": int(win.top),
"left": int(win.left),
"width": int(win.width),
"height": int(win.height)
}
return None
except Exception:
return None
def process_screenshot(self, sct_img):
"""Converts MSS raw bytes to PIL Image and resizes."""
img = Image.frombytes("RGB", sct_img.size, sct_img.bgra, "raw", "BGRX")
w, h = img.size
longest = max(w, h)
if longest > MAX_RES:
scale = MAX_RES / longest
new_size = (int(w * scale), int(h * scale))
img = img.resize(new_size, Image.Resampling.LANCZOS)
return img
def log_data(self, img, key_pressed):
"""Saves image and appends JSONL entry."""
filename = f"screenshot_{self.turn_count}.webp"
filepath = os.path.join(self.img_dir, filename)
img.save(filepath, "WEBP")
if self.turn_count == 0:
entry = {"image": filename}
else:
k = key_pressed if key_pressed else "None"
entry = {"keypress": k, "image": filename}
with open(self.jsonl_path, 'a') as f:
f.write(json.dumps(entry) + "\n")
def on_key_event(self, event):
"""
Callback for key presses.
Handles Shift logic:
- Shift + 'v' -> 'V'
- Shift + '1' -> '!'
- Shift + 'tab' -> 'shift+tab'
"""
if event.event_type == keyboard.KEY_DOWN:
name = event.name
# Detect modifiers
is_shift = keyboard.is_pressed('shift') or keyboard.is_pressed('right shift')
is_ctrl = keyboard.is_pressed('ctrl') or keyboard.is_pressed('right ctrl')
is_alt = keyboard.is_pressed('alt') or keyboard.is_pressed('right alt')
# Ignore modifier keys themselves (don't log "shift" when shift is pressed)
if name in ['ctrl', 'right ctrl', 'alt', 'right alt', 'shift', 'right shift']:
return
# Logic:
# 1. If Ctrl or Alt is held, we want the combo string (e.g., "ctrl+s", "alt+tab")
if is_ctrl or is_alt:
mods = []
if is_ctrl: mods.append('ctrl')
if is_alt: mods.append('alt')
if is_shift: mods.append('shift')
self.last_key = "+".join(mods + [name])
return
# 2. If ONLY Shift is held (or no modifiers)
if is_shift:
# Case A: Letters (a -> A)
if len(name) == 1 and name.isalpha():
self.last_key = name.upper()
# Case B: Symbols (1 -> !, ' -> ")
elif name in SHIFT_MAP:
self.last_key = SHIFT_MAP[name]
# Case C: Functional Keys (tab -> shift+tab, enter -> shift+enter)
else:
self.last_key = f"shift+{name}"
else:
# 3. No Modifiers
self.last_key = name
def print_status(self):
sys.stdout.write(f"\r[REC] Turns: {self.turn_count} | Last Key: {self.last_key} ")
sys.stdout.flush()
def start(self):
# Hook global keyboard events
keyboard.hook(self.on_key_event)
print(f"[*] Waiting for window containing '{WINDOW_TITLE}'...")
with mss.mss() as sct:
while self.running:
try:
# 1. Locate Window
region = self.get_window_region()
if not region:
time.sleep(1)
continue
# 2. Capture Screenshot
sct_img = sct.grab(region)
current_img = self.process_screenshot(sct_img)
current_array = np.array(current_img)
# 3. Detect Visual Change
has_changed = False
if self.prev_image_array is None:
# Always capture the very first frame immediately
has_changed = True
else:
if current_array.shape == self.prev_image_array.shape:
# Fast pixel comparison
if np.sum(current_array - self.prev_image_array) != 0:
has_changed = True
else:
# Resolution changed
has_changed = True
# 4. Save & Log
if has_changed:
# For the first frame (turn 0), key is irrelevant in the log function
self.log_data(current_img, self.last_key)
self.prev_image_array = current_array
self.print_status()
self.turn_count += 1
# Reset key so we don't log the same key for purely visual animations later
self.last_key = None
time.sleep(CHECK_FREQ)
except KeyboardInterrupt:
print("\n[*] Stopping...")
self.running = False
except Exception as e:
print(f"\n[!] Error: {e}")
time.sleep(1)
if __name__ == "__main__":
# Admin check for Windows (required for keyboard hook)
if os.name == 'nt':
import ctypes
if not ctypes.windll.shell32.IsUserAnAdmin():
print("[!] Warning: Run as Administrator to detect keypresses reliably.")
logger = CDDALogger()
logger.start()