Spaces:
Runtime error
Runtime error
| # optimization.py | |
| import zlib | |
| import base64 | |
| from PIL import Image | |
| import io | |
| import json | |
| class SpaceOptimizer: | |
| """Clase para optimizar recursos en HuggingFace Spaces""" | |
| def __init__(self): | |
| self.asset_cache = {} | |
| self.compression_level = 6 | |
| def compress_assets(self, asset_data: bytes) -> str: | |
| """Comprime assets usando zlib y base64""" | |
| compressed = zlib.compress(asset_data, level=self.compression_level) | |
| return base64.b64encode(compressed).decode('utf-8') | |
| def decompress_assets(self, compressed_str: str) -> bytes: | |
| """Descomprime assets previamente comprimidos""" | |
| compressed_data = base64.b64decode(compressed_str) | |
| return zlib.decompress(compressed_data) | |
| def image_to_webp(self, image_path: str, quality: int = 80) -> bytes: | |
| """Convierte imágenes a formato WebP optimizado""" | |
| with Image.open(image_path) as img: | |
| byte_io = io.BytesIO() | |
| img.save(byte_io, format='WEBP', quality=quality, method=6) | |
| return byte_io.getvalue() | |
| def generate_sprite_atlas(self, image_paths: list, tile_size: int = 64) -> dict: | |
| """Crea atlas de sprites optimizados para el juego""" | |
| atlas = {} | |
| total_width = tile_size * len(image_paths) | |
| composite = Image.new('RGBA', (total_width, tile_size)) | |
| for idx, path in enumerate(image_paths): | |
| img = Image.open(path).resize((tile_size, tile_size)) | |
| composite.paste(img, (idx * tile_size, 0)) | |
| atlas[path.stem] = { | |
| 'x': idx * tile_size, | |
| 'y': 0, | |
| 'width': tile_size, | |
| 'height': tile_size | |
| } | |
| byte_io = io.BytesIO() | |
| composite.save(byte_io, format='WEBP') | |
| return { | |
| 'atlas': byte_io.getvalue(), | |
| 'mapping': atlas | |
| } | |
| def save_state_optimized(self, game_state: dict) -> str: | |
| """Guarda el estado del juego en formato optimizado para Spaces""" | |
| compressed = self.compress_assets(json.dumps(game_state).encode('utf-8')) | |
| return f"GAUCHO_SAVE::{compressed}" | |
| def load_state_optimized(self, save_str: str) -> dict: | |
| """Carga el estado del juego desde formato optimizado""" | |
| if save_str.startswith("GAUCHO_SAVE::"): | |
| compressed = save_str.split("::", 1)[1] | |
| return json.loads(self.decompress_assets(compressed)) | |
| return {} | |