File size: 3,547 Bytes
543e4c2
39655de
543e4c2
39655de
543e4c2
 
 
 
9647f3e
 
543e4c2
39655de
543e4c2
39655de
9647f3e
39655de
 
543e4c2
 
 
 
39655de
543e4c2
 
 
 
 
 
39655de
 
543e4c2
 
39655de
543e4c2
 
 
39655de
 
 
543e4c2
 
39655de
 
 
 
 
 
543e4c2
39655de
543e4c2
 
39655de
 
 
 
 
543e4c2
 
39655de
 
543e4c2
39655de
543e4c2
 
 
 
 
 
 
 
 
 
 
39655de
543e4c2
 
39655de
 
543e4c2
 
 
 
 
 
 
 
 
 
 
 
 
39655de
 
543e4c2
39655de
543e4c2
39655de
 
 
 
 
543e4c2
 
39655de
 
543e4c2
39655de
543e4c2
39655de
 
543e4c2
39655de
543e4c2
 
39655de
543e4c2
 
 
39655de
543e4c2
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# =========================
# 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()