Dynamic splatoon screen

This commit is contained in:
oitsjustjose 2022-11-06 15:42:44 -06:00
commit c760d7d6ff
11 changed files with 327 additions and 311 deletions

View file

@ -1,15 +1,16 @@
"""General image magiks"""
import base64
import os
from typing import List, Tuple
from typing import List
import requests
from PIL import Image
from webptools import cwebp, dwebp, webpmux_animate
from webptools import dwebp
from util import rel_to_abspath
def download_image(link: str) -> Tuple[bool, str]:
def download_image(link: str) -> str:
"""Downloads an image via url only if it doesn't exist locally"""
out_dir = rel_to_abspath("../weapons").replace("\\", os.sep).replace("/", os.sep)
file_name = link.split("/")[-1]
@ -18,14 +19,12 @@ def download_image(link: str) -> Tuple[bool, str]:
if not os.path.exists(out_dir):
os.mkdir(out_dir)
existed = True
if not os.path.exists(full_path):
existed = False
img_data = requests.get(link).content
with open(full_path, "wb") as handler:
handler.write(img_data)
return (existed, full_path)
return full_path
def loadout_to_b64(loadout: List[str]) -> str:
@ -35,40 +34,25 @@ def loadout_to_b64(loadout: List[str]) -> str:
Arguments:
loadout (List[str]): a list of URLs for each weapon
"""
inputs: List[str] = []
frames: List[Image.Image] = []
for img_url in loadout:
existed, path = download_image(img_url)
if not existed: # Only resize if the image didn't already exist
dwebp(input_image=path, output_image=f"{path}.png", option="-o")
Image.open(f"{path}.png").resize((24, 24)).save(f"{path}.png")
cwebp(input_image=f"{path}.png", output_image=path, option="-q 100")
os.unlink(f"{path}.png")
inputs.append(f"{path} +1000+0+0+1")
path = download_image(img_url)
# Convert webp to png
dwebp(input_image=path, output_image=f"{path}.png", option="-o")
frames.append(Image.open(path).resize((24, 24)))
webpmux_animate(
input_images=inputs,
output_image=rel_to_abspath("../temp.webp"),
loop="10",
bgcolor="0,0,0,0",
gif_path = rel_to_abspath("../temp.gif")
frames[0].save(
gif_path,
format="GIF",
append_images=frames[1:],
save_all=True,
duration=5000,
disposal=2,
loop=0,
)
img = Image.open(rel_to_abspath("../temp.webp"))
img.info.pop("background", None)
img.save(rel_to_abspath("../temp.gif"), "gif", save_all=True)
with open(rel_to_abspath("../temp.gif"), "rb") as file_handle:
b64 = base64.b64encode(file_handle.read())
# os.unlink(rel_to_abspath("../temp.webp"))
return b64
print(
loadout_to_b64(
[
"https://splatoon.oatmealdome.me/img/weapon/thunder/Shooter_Short_00.webp",
"https://splatoon.oatmealdome.me/img/weapon/thunder/Blaster_Short_00.webp",
"https://splatoon.oatmealdome.me/img/weapon/thunder/Shelter_Compact_00.webp",
"https://splatoon.oatmealdome.me/img/weapon/thunder/Charger_Normal_00.webp",
]
)
)
with open(gif_path, "rb") as fh:
b64 = base64.b64encode(fh.read())
os.unlink(gif_path)
return b64.decode("utf-8")

147
src/main.py Normal file
View file

@ -0,0 +1,147 @@
import json
from dataclasses import dataclass
from datetime import datetime
from time import sleep
from typing import List
import dateutil.parser
from bs4 import BeautifulSoup
from pywinauto import Desktop
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
import pixlet
from images import loadout_to_b64
from util import rel_to_abspath
@dataclass
class SalmonRunEvent:
"""Represents a GrizzCo Job"""
start: datetime
end: datetime
stage_name: str
loadout: List[str]
@dataclass
class Cache:
"""Caching System"""
last_update: datetime
event: List[SalmonRunEvent]
CACHED: Cache = None
def get_salmon_run_data() -> List[SalmonRunEvent]:
"""Scrapes salmon run data"""
global CACHED
if CACHED and CACHED.last_update.date == datetime.now().date:
return CACHED.event
options = Options()
options.add_argument("--headless")
driver = webdriver.Firefox(options=options)
driver.get("https://splatoon.oatmealdome.me/three/salmon-run")
main_el = driver.page_source
main_el = BeautifulSoup(main_el, features="html.parser")
main_el = main_el.body.find("main", attrs={"role": "main"}).find(
"div", attrs={"class": "d-grid gap-3"}
)
# The row where the datetime is shown when the evt. will occur
times: List[str] = [
x.text.strip()
for x in main_el.find_all("div", attrs={"class": "d-flex flex-row"})
]
# The row where the actual Salmon Run loadout & reward is
events: List[BeautifulSoup] = main_el.find_all(
"div", attrs={"class": "bg-salmon-run"}
)
data: List[SalmonRunEvent] = []
for idx, evt in enumerate(events):
start, end = times[idx].split(" - ")
start = dateutil.parser.parse(start)
end = dateutil.parser.parse(end)
stage_name = evt.find("span", attrs={"class": "text-stage-name"}).text
event_root = evt.find("div", attrs={"class": "col d-flex flex-column"})
# Get the photos of the loadout, then lean on the `title` attr
loadout = [
f"https://splatoon.oatmealdome.me/{x.find('img').attrs['src']}"
for x in event_root.find("div", attrs={"class": "row gx-2"}).find_all(
"picture"
)
]
data.append(SalmonRunEvent(start, end, stage_name, loadout))
driver.close()
CACHED = Cache(last_update=datetime.now(), event=data)
return data
def main():
"""The main run function of the application"""
desktop = Desktop()
showing_sploon = False
rotation_time = 15 # the amount of time between tidbyt app rotations
while True:
try:
windows = list(
filter(lambda x: x, [w.window_text() for w in desktop.windows()])
)
if "Zoom Meeting" in windows:
showing_sploon = False
pixlet.display(rel_to_abspath("../zoom/meeting.webp"))
sleep(rotation_time)
elif "obs64" in windows:
showing_sploon = False
with open(
rel_to_abspath("../status"), "r", encoding="utf-8"
) as file_handle:
data = json.loads(file_handle.read())
if data["STREAMING"]:
pixlet.display(rel_to_abspath("../streaming/active.webp"))
elif data["RECORDING"]:
pixlet.display(rel_to_abspath("../recording/active.webp"))
else:
pixlet.display(rel_to_abspath("../recording/paused.webp"))
sleep(rotation_time)
else:
if not showing_sploon: # prevents overworking
salmon_run = get_salmon_run_data()[0]
render_file = rel_to_abspath("../templates/rendered.star")
pixlet.update_template(
rel_to_abspath("../templates/splatoon.star"),
render_file,
{
"<IMAGE>": loadout_to_b64(salmon_run.loadout),
"<START_DATE>": f"{salmon_run.start.month}/{salmon_run.start.day} {salmon_run.start.hour%12}:{str(salmon_run.start.minute).zfill(2)} {'AM' if salmon_run.start.hour < 12 else 'PM'}",
"<END_DATE>": f"{salmon_run.end.month}/{salmon_run.end.day} {salmon_run.end.hour%12}:{str(salmon_run.end.minute).zfill(2)} {'AM' if salmon_run.end.hour < 12 else 'PM'}",
"<STAGE>": salmon_run.stage_name,
},
)
pixlet.render(render_file)
pixlet.display(
render_file.replace(".star", ".webp"),
installation_id="SalmonRun",
)
showing_sploon = True
sleep(5)
except KeyboardInterrupt:
break
if __name__ == "__main__":
main()

71
src/pixlet.py Normal file
View file

@ -0,0 +1,71 @@
"""
Python wrapper for Pixlet Operations
"""
import subprocess
import os
from util import rel_to_abspath
STARTUP_INFO = subprocess.STARTUPINFO()
STARTUP_INFO.dwFlags |= subprocess.STARTF_USESHOWWINDOW
def update_template(template_path: str, out_path: str, replacers: dict):
"""
Opens the template up at template_path, reads it in,
replaces all keys in replacers with their values
then writes it out with the same name in `./out`
Arguments:
template_path (str): the path of the template.star to load
out_path (str): where the output should be saved
replacers (dict): a Dict[str,str] whose keys are in the template,
and whose values will replace their keys in the template
"""
if not os.path.exists("../out"):
os.mkdir("../out")
with open(template_path, "r", encoding="utf-8") as file_handle:
data = file_handle.read()
for key in replacers:
data = data.replace(key, replacers[key])
with open(out_path, "w", encoding="utf-8") as file_handle:
file_handle.write(data)
def display(file_path: str, installation_id: str = None):
"""
Displays a file (by name) to the Tidbyt, reading the device id from `device_id`
"""
with open(rel_to_abspath("../device_id"), "r", encoding="utf-8") as file_handle:
device_id = file_handle.read()
if installation_id:
args = [
rel_to_abspath("../pixlet.exe"),
"push",
"--installation-id",
installation_id,
device_id,
file_path,
]
else:
args = [
rel_to_abspath("../pixlet.exe"),
"push",
device_id,
file_path,
]
with subprocess.Popen(args, startupinfo=STARTUP_INFO) as process:
process.wait()
def render(file_path: str):
"""
Uses Pixlet to render a `.star` file to webp so that it can be pushed
Args:
file_path (str): the path (relative) to the file you want rendered
"""
with subprocess.Popen(
[rel_to_abspath("../pixlet.exe"), "render", file_path],
startupinfo=STARTUP_INFO,
) as process:
process.wait()

14
src/util.py Normal file
View file

@ -0,0 +1,14 @@
"""
General utils for things - mostly file path resolution
"""
import os
path_root = os.path.realpath(__file__).replace("util.py", "")
def rel_to_abspath(path: str) -> str:
"""
Converts a local path (like '../thing' to the absolute path)
"""
return f"{path_root}{path}".replace("\\", os.sep).replace("/", os.sep)