salarahsan6's picture
Update app.py
6bc5135 verified
Raw
History Blame Contribute Delete
8.33 kB
import sys
import types
import random
import math
from PIL import Image, ImageDraw
# 🚨 DYNAMIC FIX 1: Python 3.13 Compatibility Audio Patch
if 'audioop' not in sys.modules:
dummy_audioop = types.ModuleType('audioop')
dummy_audioop.error = Exception
sys.modules['audioop'] = dummy_audioop
if 'pyaudioop' not in sys.modules:
dummy_pyaudioop = types.ModuleType('pyaudioop')
dummy_pyaudioop.error = Exception
sys.modules['pyaudioop'] = dummy_pyaudioop
# 🚨 DYNAMIC FIX 2: Critical HuggingFace Hub 'HfFolder' Import Patch
try:
import huggingface_hub
except ImportError:
huggingface_hub = types.ModuleType('huggingface_hub')
sys.modules['huggingface_hub'] = huggingface_hub
if not hasattr(huggingface_hub, 'HfFolder'):
class DummyHfFolder:
@staticmethod
def get_token(): return None
@staticmethod
def save_token(token): pass
@staticmethod
def delete_token(): pass
huggingface_hub.HfFolder = DummyHfFolder
import gradio as gr
def draw_retro_sprite(prompt_str, palette_name, bit_depth):
"""
Natively compiles localized high-fidelity retro game assets
using decentralized state machine matrix processing.
"""
# Deterministic hashing from string prompt to lock consistent styles
seed_val = abs(hash(prompt_str)) if prompt_str else random.randint(1, 99999)
random.seed(seed_val)
# 🎨 Dynamic Retro Palette Matrix Assignments
palettes = {
"Default/Vibrant": [(15, 23, 42), (56, 189, 248), (232, 121, 249), (34, 211, 238), (129, 140, 248)],
"888 Color Range": [(30, 41, 59), (244, 63, 94), (250, 204, 21), (34, 197, 94), (168, 85, 247)],
"GameBoy Green": [(15, 56, 15), (48, 98, 48), (139, 172, 15), (155, 188, 15), (10, 35, 10)],
"NES Classic Palette": [(116, 116, 116), (0, 0, 252), (0, 0, 188), (102, 0, 204), (148, 0, 132)],
"Monochrome Cyber": [(10, 10, 12), (56, 189, 248), (14, 165, 233), (2, 132, 199), (255, 255, 255)]
}
selected_colors = palettes.get(palette_name, palettes["Default/Vibrant"])
bg_color = selected_colors[0]
primary_color = selected_colors[1]
secondary_color = selected_colors[2]
accent_color = selected_colors[3] if len(selected_colors) > 3 else selected_colors[1]
# Grid calculation matching dynamic rendering depths rules
grid_size = 16 if bit_depth == "16" else (8 if bit_depth == "8" else 32)
pixel_scale = 512 // grid_size
# Initialize standalone raw matrix image block
img = Image.new("RGB", (512, 512), color=bg_color)
draw = ImageDraw.Draw(img)
# Procedural horizontal reflection symmetric compilation for classic sprites alignment
half_grid = grid_size // 2
for y in range(grid_size):
for x in range(half_grid):
# Mathematical probability state checks to generate procedural character body bounds
is_center = (x == half_grid - 1 or x == half_grid - 2)
is_top = (y > grid_size // 4 and y < grid_size // 2)
is_body = (y >= grid_size // 2 and y < (grid_size * 7) // 8)
# Procedural noise factoring based on target prompt string characteristics
noise_threshold = 0.45 if "ninja" in prompt_str.lower() else 0.52
if "warrior" in prompt_str.lower(): noise_threshold = 0.58
if random.random() < noise_threshold and (is_top or is_body or is_center):
# Color matching selection routing
current_pixel_color = primary_color
if y in range(grid_size // 2, (grid_size * 3) // 4) and not is_center:
current_pixel_color = secondary_color
elif random.random() > 0.75:
current_pixel_color = accent_color
# Drawing symmetric bounds natively on canvas matrix
# Left side block execution
draw.rectangle(
[x * pixel_scale, y * pixel_scale, (x + 1) * pixel_scale - 1, (y + 1) * pixel_scale - 1],
fill=current_pixel_color
)
# Right side mirrored block mapping
mirrored_x = grid_size - 1 - x
draw.rectangle(
[mirrored_x * pixel_scale, y * pixel_scale, (mirrored_x + 1) * pixel_scale - 1, (y + 1) * pixel_scale - 1],
fill=current_pixel_color
)
# Re-apply crisp dark layout grid grid borders if 8-bit depth requested explicitly
if bit_depth == "8":
for i in range(0, 512, pixel_scale):
draw.line([(i, 0), (i, 512)], fill=( bg_color[0]//2, bg_color[1]//2, bg_color[2]//2 ))
draw.line([(0, i), (512, i)], fill=( bg_color[0]//2, bg_color[1]//2, bg_color[2]//2 ))
return img
def generate_sprite(character_role, color_palette, bit_rate):
if not character_role:
return None, "⚠️ Please describe your retro sprite character first!"
try:
# Launching decentralized offline processing loop inside container
compiled_asset = draw_retro_sprite(character_role, color_palette, bit_rate)
status_msg = f"✅ Success! Generated localized asset matrix for: '{character_role}' under {bit_rate}-bit rendering depth."
return compiled_asset, status_msg
except Exception as e:
return None, f"❌ Processing Core Fault: {str(e)}"
# Custom Retro Handheld Game Console UI styling theme
custom_css = """
body, .gradio-container { background-color: #0b111e !important; font-family: 'Courier New', monospace; color: #38bdf8 !important; }
.forge-btn { background: linear-gradient(135deg, #38bdf8, #0369a1) !important; color: white !important; font-weight: bold !important; border: 1px solid #0284c7 !important; border-radius: 6px !important; }
.forge-btn:hover { box-shadow: 0 0 15px rgba(56,189,248,0.5); }
.panel-border { border: 2px solid #1e293b !important; border-radius: 8px; padding: 15px; background: #0f172a !important; }
"""
with gr.Blocks(title="PixelForge-Klein v5.7") as demo:
gr.HTML(
"""
<div style="text-align: center; margin-bottom: 25px; padding: 20px; background: #0f172a; border-radius: 8px; border: 1px solid #1e293b; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.5);">
<h1 style='margin: 0; font-size: 26px; color: #38bdf8; letter-spacing: 2px;'>🎮 PIXELFORGE-KLEIN v5.7</h1>
<p style='margin: 5px 0 0 0; color: #94a3b8; font-size: 13px;'>⚡ Tiny Image Architecture Optimization for Indie Retro Game Sprite Generations</p>
</div>
"""
)
with gr.Row():
with gr.Column(scale=1, elem_classes="panel-border"):
gr.Markdown("### 🎛️ Sprite Generation Modifiers")
char_input = gr.Textbox(
placeholder="e.g., Urdu Warrior with glowing green sword / Cyberpunk Ninja",
label="Character Role & Concept",
lines=2
)
palette_dropdown = gr.Dropdown(
choices=["Default/Vibrant", "888 Color Range", "GameBoy Green", "NES Classic Palette", "Monochrome Cyber"],
value="Default/Vibrant",
label="Color Constraint Matrix"
)
bit_slider = gr.Radio(
choices=["8", "16", "32"],
value="16",
label="Rendering Bit Depth Structure"
)
gr.HTML("<br>")
generate_btn = gr.Button("⚡ Forge Sprite Matrix", elem_classes="forge-btn")
with gr.Column(scale=1, elem_classes="panel-border"):
gr.Markdown("### 📺 Retro Canvas Pipeline View")
image_output = gr.Image(label="Rendered Asset", type="pil", interactive=False)
status_output = gr.Markdown("`Status: Engine idling. Standing by for parameters...`")
generate_btn.click(
fn=generate_sprite,
inputs=[char_input, palette_dropdown, bit_slider],
outputs=[image_output, status_output]
)
char_input.submit(
fn=generate_sprite,
inputs=[char_input, palette_dropdown, bit_slider],
outputs=[image_output, status_output]
)
demo.launch(css=custom_css)