#!/usr/bin/env python3 # Requirements: # pip3 install libscrc pillow """ This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to """ from argparse import ArgumentParser, FileType from importlib.machinery import SourceFileLoader from PIL import Image #from libscrc import modbus from struct import unpack from js import document, console, Uint8Array, window, File from pyodide.ffi import create_proxy import asyncio import io import time def modbusCrc(msg:str) -> int: crc = 0xFFFF for n in range(len(msg)): crc ^= msg[n] for i in range(8): if crc & 1: crc >>= 1 crc ^= 0xA001 else: crc >>= 1 return crc async def _bannergif(e): """Extracts a DS(i) ROM's icon to an image""" # Disable upload, show Loading... uploadlabel = document.getElementById("fileUploadLabel") uploadlabel.innerHTML = "Loading..." uploader = document.getElementById("fileuploadpillow") uploader.disabled = True #Get the first file from upload file_list = e.target.files romfile = file_list.item(0) if romfile == None: # Re-enable upload, hide Loading... uploader.disabled = False uploader.value = '' uploadlabel.innerHTML = "Select your DS(i) ROM!" return False else: #Get the data from the files arrayBuffer as an array of unsigned bytes array_buf = Uint8Array.new(await romfile.arrayBuffer()) #BytesIO wants a bytes-like object, so convert to bytearray first bytes_list = bytearray(array_buf) rom = io.BytesIO(bytes_list) # Seek to banner rom.seek(0x68) bannerOfs = unpack("> 4 bitmaps.append(bitmap) # Read palettes for _ in range(8): palette = [0] * 256 * 3 # Pillow wants a 256 color palette with RGB separated for i in range(0x10): color = unpack("> 5) & 0x1F) * 255 / 31) palette[i * 3 + 2] = round(((color >> 10) & 0x1F) * 255 / 31) palettes.append(palette) # Read animation sequence for i in range(0x40): value = unpack("> 11) & 7, "bitmap": (value >> 8) & 7, "duration": value & 0xFF }) else: # DS # Read bitmap rom.seek(0x20, io.SEEK_CUR) bitmap = [0] * 32 * 32 for ty in range(4): for tx in range(4): for y in range(8): for x in range(4): byte = unpack("B", rom.read(1))[0] bitmap[((ty * 8 + y) * 32) + tx * 8 + x * 2] = byte & 0xF bitmap[((ty * 8 + y) * 32) + tx * 8 + x * 2 + 1] = byte >> 4 bitmaps.append(bitmap) # Read palette palette = [0] * 256 * 3 # Pillow wants a 256 color palette with RGB separated for i in range(0x10): color = unpack("> 5) & 0x1F) * 255 / 31) palette[i * 3 + 2] = round(((color >> 10) & 0x1F) * 255 / 31) palettes.append(palette) # No animation, just show the first frame as there's only one animation = [{ "vflip": False, "hflip": False, "palette": 0, "bitmap": 0, "duration": 1 }] # Convert to Pillow image images = [] delays = [] for i, frame in enumerate(animation): # Animation ends when the animation u16 is 0, since it's split here # for ease of use checking just the duration should be fine if frame["duration"] == 0 and i > 0: break # 32x32 Paletted image img = Image.frombytes("P", (32, 32), bytes(bitmaps[frame["bitmap"]])) img.putpalette(palettes[frame["palette"]]) # Flip the image if needed if(frame["hflip"]): img = img.transpose(Image.FLIP_LEFT_RIGHT) if(frame["vflip"]): img = img.transpose(Image.FLIP_TOP_BOTTOM) conversion = document.getElementById("integer") if conversion.value != "1": img = img.resize((img.width * int(conversion.value), img.height * int(conversion.value)), resample=None, box=None, reducing_gap=None) if conversion.value == "8": result = Image.new(img.mode, (320, 320), 0) result.putpalette(palettes[frame["palette"]]) result.paste(img, (32, 32)) img = result #add transparency img.info['transparency'] = 0 img.apply_transparency() # Add it to the output list delaytime = frame["duration"] * 1000 // 60 # The 'duration' is in frames (1/60th of a second), Pillow wants # miliseconds. This should make sure that frames are never larger # than a second but it doesn't seem to work. while delaytime > 0: if delaytime > 1000: images.append(img) delays.append(1000) delaytime = delaytime - 1000 else: images.append(img) delays.append(delaytime) delaytime = 0 # Save output image imgformat = document.getElementById("filetype") my_stream = io.BytesIO() if imgformat.value == "WebP": images[0].save(my_stream, format="WEBP", lossless=True, quality=100, save_all=True, append_images=images[1:], duration=delays, loop=0) #Create a JS File object with our data and the proper mime type image_file = File.new([Uint8Array.new(my_stream.getvalue())], {type: "image/webp" }) image_file = image_file.slice(0, image_file.size, "image/webp") #Create new tag and insert into page new_image = document.createElement('img') new_image.name = str(int(time.time())) + ".webp" new_image.src = window.URL.createObjectURL(image_file) document.getElementById("output_upload_pillow").appendChild(new_image) else: images[0].save(my_stream, format="PNG", save_all=True, append_images=images[1:], duration=delays, loop=0, transparency=0) #Create a JS File object with our data and the proper mime type image_file = File.new([Uint8Array.new(my_stream.getvalue())], "output.png", {type: "image/apng" }) image_file = image_file.slice(0, image_file.size, "image/apng") #Create new tag and insert into page new_image = document.createElement('img') new_image.name = str(int(time.time())) + ".png" new_image.src = window.URL.createObjectURL(image_file) document.getElementById("output_upload_pillow").appendChild(new_image) # Re-enable upload, hide Loading... uploader.disabled = False uploader.value = '' uploadlabel.innerHTML = "Select your DS(i) ROM!" # Run image processing code above whenever file is uploaded upload_file = create_proxy(_bannergif) if upload_file != False: document.getElementById("fileuploadpillow").addEventListener("change", upload_file)