Qasim742's picture
Update app.py
39655de verified
Raw History Blame Contribute Delete
3.55 kB
# =========================
# INSTALL (only for Colab)
# =========================
# !pip install diffusers transformers accelerate safetensors gradio torch torchvision xformers
import torch
import gradio as gr
from diffusers import StableDiffusionPipeline
import os
# =========================
# LOAD HF TOKEN (for Hugging Face Spaces)
# =========================
HF_TOKEN = os.getenv("HF_TOKEN")
if not HF_TOKEN:
raise ValueError("❌ HF_TOKEN not found in Hugging Face Secrets")
print("βœ… HF Token Loaded Successfully")
# =========================
# MODEL CONFIG
# =========================
model_id = "runwayml/stable-diffusion-v1-5"
device = "cuda" if torch.cuda.is_available() else "cpu"
dtype = torch.float16 if device == "cuda" else torch.float32
print(f"πŸš€ Running on: {device}")
pipe = StableDiffusionPipeline.from_pretrained(
model_id,
use_auth_token=HF_TOKEN,
torch_dtype=dtype
).to(device)
# =========================
# PERFORMANCE OPTIMIZATION
# =========================
pipe.enable_attention_slicing()
try:
pipe.enable_xformers_memory_efficient_attention()
print("⚑ xFormers enabled (faster generation)")
except:
print("⚠️ xFormers not available")
# =========================
# STYLE PRESETS
# =========================
STYLE_PRESETS = {
"Realistic": "realistic, ultra detailed, 8k, highly detailed, sharp focus",
"Anime": "anime style, studio ghibli, manga art, vibrant colors",
"Digital Art": "digital art, concept art, trending on artstation",
"Oil Painting": "oil painting, classical art, textured brush strokes",
"Cyberpunk": "cyberpunk, neon lights, futuristic city, dark atmosphere"
}
NEGATIVE_PROMPT = "blurry, low quality, distorted, bad anatomy, ugly, deformed"
# =========================
# IMAGE GENERATION FUNCTION
# =========================
def generate_image(prompt, style, steps, guidance):
try:
prompt = prompt.strip()
if not prompt:
return None, "⚠️ Please enter a prompt"
if len(prompt) > 300:
return None, "⚠️ Prompt too long (max 300 characters)"
styled_prompt = f"{prompt}, {STYLE_PRESETS[style]}"
image = pipe(
styled_prompt,
negative_prompt=NEGATIVE_PROMPT,
num_inference_steps=int(steps),
guidance_scale=float(guidance)
).images[0]
return image, "βœ… Image generated successfully"
except Exception as e:
return None, f"❌ Error: {str(e)}"
# =========================
# GRADIO UI
# =========================
with gr.Blocks() as app:
gr.Markdown("# 🎨 AI Text β†’ Image Generator")
gr.Markdown("Generate high-quality images using Stable Diffusion πŸš€")
prompt = gr.Textbox(label="πŸ“ Enter Prompt", placeholder="e.g. A futuristic city at night")
style = gr.Radio(
choices=list(STYLE_PRESETS.keys()),
value="Realistic",
label="🎭 Select Style"
)
with gr.Row():
steps = gr.Slider(10, 40, value=20, step=1, label="βš™οΈ Steps (Speed vs Quality)")
guidance = gr.Slider(1, 12, value=7.5, step=0.5, label="🎯 Guidance Scale")
generate_btn = gr.Button("πŸš€ Generate Image")
image_output = gr.Image(label="πŸ–ΌοΈ Output Image")
status = gr.Textbox(label="πŸ“’ Status")
generate_btn.click(
fn=generate_image,
inputs=[prompt, style, steps, guidance],
outputs=[image_output, status]
)
# =========================
# LAUNCH
# =========================
app.launch()