Lukeetah commited on
Commit
162286c
·
verified ·
1 Parent(s): 8f846af

Create optimization.py

Browse files
Files changed (1) hide show
  1. optimization.py +64 -0
optimization.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # optimization.py
2
+ import zlib
3
+ import base64
4
+ from PIL import Image
5
+ import io
6
+ import json
7
+
8
+ class SpaceOptimizer:
9
+ """Clase para optimizar recursos en HuggingFace Spaces"""
10
+ def __init__(self):
11
+ self.asset_cache = {}
12
+ self.compression_level = 6
13
+
14
+ def compress_assets(self, asset_data: bytes) -> str:
15
+ """Comprime assets usando zlib y base64"""
16
+ compressed = zlib.compress(asset_data, level=self.compression_level)
17
+ return base64.b64encode(compressed).decode('utf-8')
18
+
19
+ def decompress_assets(self, compressed_str: str) -> bytes:
20
+ """Descomprime assets previamente comprimidos"""
21
+ compressed_data = base64.b64decode(compressed_str)
22
+ return zlib.decompress(compressed_data)
23
+
24
+ def image_to_webp(self, image_path: str, quality: int = 80) -> bytes:
25
+ """Convierte imágenes a formato WebP optimizado"""
26
+ with Image.open(image_path) as img:
27
+ byte_io = io.BytesIO()
28
+ img.save(byte_io, format='WEBP', quality=quality, method=6)
29
+ return byte_io.getvalue()
30
+
31
+ def generate_sprite_atlas(self, image_paths: list, tile_size: int = 64) -> dict:
32
+ """Crea atlas de sprites optimizados para el juego"""
33
+ atlas = {}
34
+ total_width = tile_size * len(image_paths)
35
+ composite = Image.new('RGBA', (total_width, tile_size))
36
+
37
+ for idx, path in enumerate(image_paths):
38
+ img = Image.open(path).resize((tile_size, tile_size))
39
+ composite.paste(img, (idx * tile_size, 0))
40
+ atlas[path.stem] = {
41
+ 'x': idx * tile_size,
42
+ 'y': 0,
43
+ 'width': tile_size,
44
+ 'height': tile_size
45
+ }
46
+
47
+ byte_io = io.BytesIO()
48
+ composite.save(byte_io, format='WEBP')
49
+ return {
50
+ 'atlas': byte_io.getvalue(),
51
+ 'mapping': atlas
52
+ }
53
+
54
+ def save_state_optimized(self, game_state: dict) -> str:
55
+ """Guarda el estado del juego en formato optimizado para Spaces"""
56
+ compressed = self.compress_assets(json.dumps(game_state).encode('utf-8'))
57
+ return f"GAUCHO_SAVE::{compressed}"
58
+
59
+ def load_state_optimized(self, save_str: str) -> dict:
60
+ """Carga el estado del juego desde formato optimizado"""
61
+ if save_str.startswith("GAUCHO_SAVE::"):
62
+ compressed = save_str.split("::", 1)[1]
63
+ return json.loads(self.decompress_assets(compressed))
64
+ return {}