| 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 |
|
|
| |
| WINDOW_TITLE = "Cataclysm" |
| CHECK_FREQ = 0.1 |
| MAX_RES = 1024 |
|
|
| |
| 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 |
| |
| |
| 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') |
|
|
| |
| if name in ['ctrl', 'right ctrl', 'alt', 'right alt', 'shift', 'right shift']: |
| return |
|
|
| |
| |
| 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 |
|
|
| |
| if is_shift: |
| |
| if len(name) == 1 and name.isalpha(): |
| self.last_key = name.upper() |
| |
| |
| elif name in SHIFT_MAP: |
| self.last_key = SHIFT_MAP[name] |
| |
| |
| else: |
| self.last_key = f"shift+{name}" |
| else: |
| |
| 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): |
| |
| keyboard.hook(self.on_key_event) |
| |
| print(f"[*] Waiting for window containing '{WINDOW_TITLE}'...") |
| |
| with mss.mss() as sct: |
| while self.running: |
| try: |
| |
| region = self.get_window_region() |
| if not region: |
| time.sleep(1) |
| continue |
|
|
| |
| sct_img = sct.grab(region) |
| current_img = self.process_screenshot(sct_img) |
| current_array = np.array(current_img) |
|
|
| |
| has_changed = False |
| |
| if self.prev_image_array is None: |
| |
| has_changed = True |
| else: |
| if current_array.shape == self.prev_image_array.shape: |
| |
| if np.sum(current_array - self.prev_image_array) != 0: |
| has_changed = True |
| else: |
| |
| has_changed = True |
|
|
| |
| if has_changed: |
| |
| self.log_data(current_img, self.last_key) |
| |
| self.prev_image_array = current_array |
| self.print_status() |
| self.turn_count += 1 |
| |
| |
| 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__": |
| |
| 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() |