RamaManna's picture
Create app.py
6405f1a verified
raw
history blame
2.7 kB
import gradio as gr
import torch
from diffusers import StableDiffusionPipeline
from PIL import Image
# Tiny model that fits in free tier memory
MODEL_NAME = "OFA-Sys/small-stable-diffusion-v0"
# Load model (will cache after first run)
@gr.cache()
def load_model():
return StableDiffusionPipeline.from_pretrained(
MODEL_NAME,
torch_dtype=torch.float16,
safety_checker=None
).to("cpu")
def generate_character(description, seed=42):
try:
pipe = load_model()
# Reduce memory usage
torch.manual_seed(seed)
with torch.inference_mode():
image = pipe(
prompt=f"pixel art character, {description}",
num_inference_steps=15, # Fewer steps = less memory
guidance_scale=7.0,
width=256, # Smaller resolution
height=256
).images[0]
return image
except Exception as e:
return f"Error: {str(e)}\nTry a simpler description or different words."
# Create simple animation effect by generating variations
def generate_animation(description, frames=3):
images = []
for i in range(frames):
img = generate_character(description, seed=i)
if isinstance(img, str): # If error returned
return img
images.append(img)
# Create simple animation (GIF)
images[0].save(
"animation.gif",
save_all=True,
append_images=images[1:],
duration=500,
loop=0
)
return "animation.gif"
# Minimal interface
with gr.Blocks(title="Tiny Character Animator") as demo:
gr.Markdown("""
# ๐ŸŽฎ Tiny Character Animator
*Free-tier optimized for Hugging Face Spaces*
""")
with gr.Row():
desc = gr.Textbox(
label="Describe your character",
placeholder="e.g., 'blue robot with antennae'",
max_lines=2
)
with gr.Row():
btn_still = gr.Button("Generate Still", variant="secondary")
btn_animate = gr.Button("Generate Animation", variant="primary")
with gr.Row():
output_still = gr.Image(label="Character", shape=(256, 256))
output_anim = gr.Image(label="Animation", format="gif", visible=False)
# Button actions
btn_still.click(
generate_character,
inputs=desc,
outputs=output_still
)
btn_animate.click(
lambda: (gr.Image(visible=False), gr.Image(visible=True)), # Toggle visibility
None,
[output_still, output_anim]
).then(
generate_animation,
inputs=desc,
outputs=output_anim
)
demo.launch(debug=False)