KPRSpaceAPI/spacer.py

53 lines
1.7 KiB
Python
Raw Normal View History

2023-12-02 22:04:46 +00:00
import os
import glob
2025-10-20 05:14:50 +00:00
from PIL import Image
2023-12-02 22:04:46 +00:00
2025-10-20 05:14:50 +00:00
def get_latest_screenshot(directory, ext='jpg'):
"""Return the latest file path with the given extension in directory or None if none found."""
if not directory:
return None
if not os.path.isdir(directory):
return None
pattern = os.path.join(directory, f'*.{ext}')
files = glob.glob(pattern)
if not files:
return None
return max(files, key=os.path.getctime)
2023-12-02 22:04:46 +00:00
2025-10-20 05:14:50 +00:00
def process_image(image_path):
"""Return 'open', 'closed' or 'unknown' based on average brightness of an image.
2023-12-02 22:04:46 +00:00
2025-10-20 05:14:50 +00:00
The function is defensive and returns 'unknown' if the path is missing or an error occurs.
"""
if not image_path or not os.path.isfile(image_path):
return 'unknown'
try:
with Image.open(image_path) as img:
img = img.convert('RGB')
img = img.resize((2, 2))
pixels = list(img.getdata())
if not pixels:
return 'unknown'
avg = [sum(ch) / len(pixels) for ch in zip(*pixels)]
luminance = sum(avg) / 3.0
return 'closed' if luminance < 128 else 'open'
except Exception:
return 'unknown'
2023-12-02 22:04:46 +00:00
2025-10-20 05:14:50 +00:00
def get_brightness(image_path):
"""Return average brightness (0-255) as float, or None on error."""
if not image_path or not os.path.isfile(image_path):
return None
try:
with Image.open(image_path) as img:
img = img.convert('L')
img = img.resize((16, 16))
pixels = list(img.getdata())
if not pixels:
return None
return float(sum(pixels) / len(pixels))
except Exception:
return None