File size: 8,842 Bytes
6391a9f
 
9d7f2c9
 
6391a9f
 
9d7f2c9
6391a9f
 
9d7f2c9
 
6391a9f
 
 
 
9d7f2c9
6391a9f
9d7f2c9
 
 
 
 
 
 
6391a9f
 
9d7f2c9
 
 
 
6391a9f
 
 
 
9d7f2c9
6391a9f
9d7f2c9
6391a9f
 
 
9d7f2c9
6391a9f
 
 
 
 
 
 
 
 
 
 
9d7f2c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6391a9f
9d7f2c9
6391a9f
 
9d7f2c9
6391a9f
 
 
 
 
9d7f2c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6391a9f
9d7f2c9
 
 
 
 
 
 
 
 
 
 
 
6391a9f
 
9d7f2c9
 
 
 
 
 
 
 
 
 
 
 
 
 
6391a9f
 
9d7f2c9
 
 
 
6391a9f
9d7f2c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6391a9f
9d7f2c9
 
6391a9f
9d7f2c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6391a9f
9d7f2c9
6391a9f
 
9d7f2c9
6391a9f
 
9d7f2c9
6391a9f
 
 
 
 
 
 
 
 
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
import torch
import gradio as gr
from diffusers import StableDiffusionPipeline, StableDiffusionImg2ImgPipeline, DPMSolverMultistepScheduler
from PIL import Image

# Model yükleme
print("Modeller yükleniyor...")
model_id = "runwayml/stable-diffusion-v1-5"

# Text-to-Image Pipeline
txt2img_pipe = StableDiffusionPipeline.from_pretrained(
    model_id,
    torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
    safety_checker=None
)
txt2img_pipe.scheduler = DPMSolverMultistepScheduler.from_config(txt2img_pipe.scheduler.config)

# Image-to-Image Pipeline
img2img_pipe = StableDiffusionImg2ImgPipeline.from_pretrained(
    model_id,
    torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
    safety_checker=None
)
img2img_pipe.scheduler = DPMSolverMultistepScheduler.from_config(img2img_pipe.scheduler.config)

if torch.cuda.is_available():
    txt2img_pipe = txt2img_pipe.to("cuda")
    txt2img_pipe.enable_attention_slicing()
    img2img_pipe = img2img_pipe.to("cuda")
    img2img_pipe.enable_attention_slicing()
    print("GPU kullanılıyor ✅")
else:
    print("CPU kullanılıyor (yavaş olabilir)")

# Text-to-Image fonksiyonu
def generate_image(prompt, negative_prompt, num_steps, guidance_scale, width, height, seed):
    """Text'ten görüntü üretir"""
    device = "cuda" if torch.cuda.is_available() else "cpu"
    generator = torch.Generator(device).manual_seed(int(seed))
    
    image = txt2img_pipe(
        prompt=prompt,
        negative_prompt=negative_prompt,
        num_inference_steps=int(num_steps),
        guidance_scale=guidance_scale,
        width=int(width),
        height=int(height),
        generator=generator
    ).images[0]
    
    return image

# Image-to-Image fonksiyonu
def transform_image(init_image, prompt, negative_prompt, num_steps, guidance_scale, strength, seed):
    """Mevcut görüntüyü dönüştürür"""
    if init_image is None:
        return None
    
    device = "cuda" if torch.cuda.is_available() else "cpu"
    generator = torch.Generator(device).manual_seed(int(seed))
    
    # Görüntüyü yeniden boyutlandır
    init_image = init_image.resize((512, 512))
    
    image = img2img_pipe(
        prompt=prompt,
        negative_prompt=negative_prompt,
        image=init_image,
        num_inference_steps=int(num_steps),
        guidance_scale=guidance_scale,
        strength=strength,
        generator=generator
    ).images[0]
    
    return image

# Gradio UI
with gr.Blocks(title="🎨 Stable Diffusion Generator", theme=gr.themes.Soft()) as demo:
    gr.Markdown("""
    # 🎨 Stable Diffusion Görüntü Üretici
    Text-to-Image ve Image-to-Image modelleri ile hayal gücünüzü görüntüye dönüştürün!
    
    **Model:** Stable Diffusion v1.5  
    **Geliştirici:** Mehmet Tuğrul Kaya
    """)
    
    # TAB YAPISI
    with gr.Tabs():
        # TAB 1: TEXT-TO-IMAGE
        with gr.Tab("📝 Text-to-Image"):
            with gr.Row():
                with gr.Column(scale=1):
                    t2i_prompt = gr.Textbox(
                        label="✍️ Prompt",
                        placeholder="A beautiful sunset over mountains, digital art, highly detailed",
                        lines=3
                    )
                    
                    t2i_negative = gr.Textbox(
                        label="🚫 Negative Prompt",
                        placeholder="blurry, low quality, distorted",
                        lines=2,
                        value="blurry, low quality, ugly, distorted, deformed"
                    )
                    
                    with gr.Accordion("⚙️ Gelişmiş Ayarlar", open=False):
                        t2i_steps = gr.Slider(10, 50, value=25, step=1, label="🔄 Steps")
                        t2i_guidance = gr.Slider(1, 20, value=7.5, step=0.5, label="🎯 Guidance Scale")
                        
                        with gr.Row():
                            t2i_width = gr.Slider(256, 768, value=512, step=64, label="📐 Width")
                            t2i_height = gr.Slider(256, 768, value=512, step=64, label="📏 Height")
                        
                        t2i_seed = gr.Number(label="🌱 Seed", value=42, precision=0)
                    
                    t2i_btn = gr.Button("🎨 Görüntü Üret", variant="primary", size="lg")
                
                with gr.Column(scale=1):
                    t2i_output = gr.Image(label="🖼️ Üretilen Görüntü", type="pil")
            
            gr.Markdown("### 💡 Örnek Promptlar:")
            gr.Examples(
                examples=[
                    ["A majestic lion in savanna at sunset, photorealistic, 8k", "blurry", 25, 7.5, 512, 512, 42],
                    ["Futuristic cyberpunk city, neon lights, night", "blurry, dark", 30, 8.0, 512, 512, 123],
                    ["Cute cat wearing wizard hat, digital art, kawaii", "scary, ugly", 25, 7.5, 512, 512, 456],
                    ["Beautiful Turkish tea glass, Istanbul Bosphorus view, sunset", "blurry", 25, 7.5, 512, 512, 789],
                ],
                inputs=[t2i_prompt, t2i_negative, t2i_steps, t2i_guidance, t2i_width, t2i_height, t2i_seed],
                outputs=t2i_output,
                fn=generate_image,
                cache_examples=False
            )
            
            t2i_btn.click(
                fn=generate_image,
                inputs=[t2i_prompt, t2i_negative, t2i_steps, t2i_guidance, t2i_width, t2i_height, t2i_seed],
                outputs=t2i_output
            )
        
        # TAB 2: IMAGE-TO-IMAGE
        with gr.Tab("🖼️ Image-to-Image"):
            with gr.Row():
                with gr.Column(scale=1):
                    i2i_input = gr.Image(
                        label="📤 Başlangıç Görüntüsü Yükle",
                        type="pil",
                        sources=["upload", "clipboard"]
                    )
                    
                    i2i_prompt = gr.Textbox(
                        label="✍️ Dönüşüm Prompt'u",
                        placeholder="Turn this into a watercolor painting",
                        lines=3
                    )
                    
                    i2i_negative = gr.Textbox(
                        label="🚫 Negative Prompt",
                        placeholder="blurry, low quality",
                        lines=2,
                        value="blurry, low quality, distorted"
                    )
                    
                    with gr.Accordion("⚙️ Gelişmiş Ayarlar", open=False):
                        i2i_steps = gr.Slider(10, 50, value=30, step=1, label="🔄 Steps")
                        i2i_guidance = gr.Slider(1, 20, value=7.5, step=0.5, label="🎯 Guidance Scale")
                        i2i_strength = gr.Slider(
                            0.0, 1.0, value=0.75, step=0.05,
                            label="💪 Strength (Ne kadar değişsin?)"
                        )
                        i2i_seed = gr.Number(label="🌱 Seed", value=42, precision=0)
                    
                    i2i_btn = gr.Button("🔄 Görüntüyü Dönüştür", variant="primary", size="lg")
                
                with gr.Column(scale=1):
                    i2i_output = gr.Image(label="✨ Dönüştürülmüş Görüntü", type="pil")
            
            gr.Markdown("""
            ### 💡 Image-to-Image İpuçları:
            - **Strength 0.3-0.5**: Küçük değişiklikler, orijinale yakın
            - **Strength 0.6-0.8**: Orta seviye değişiklik (önerilen)
            - **Strength 0.9-1.0**: Büyük değişiklikler, orijinalden uzak
            
            ### 🎨 Örnek Kullanımlar:
            - Fotoğrafı resme dönüştür: "oil painting style"
            - Stil değiştir: "anime style", "cyberpunk style"
            - Renklendirme: "colorful, vibrant colors"
            - Sezon değiştir: "winter scene with snow"
            """)
            
            i2i_btn.click(
                fn=transform_image,
                inputs=[i2i_input, i2i_prompt, i2i_negative, i2i_steps, i2i_guidance, i2i_strength, i2i_seed],
                outputs=i2i_output
            )
    
    # GENEL BİLGİLER
    gr.Markdown("""
    ---
    ### 📝 Genel İpuçları:
    - **Prompt**: Detaylı ve açıklayıcı olun (örn: "photorealistic", "8k", "detailed" ekleyin)
    - **Negative Prompt**: İstemediğiniz özellikleri ekleyin
    - **Steps**: 25-30 arası optimal
    - **Guidance Scale**: 7-8 arası genelde en iyi sonuçları verir
    
    ### 🔗 Bağlantılar:
    - [GitHub](https://github.com/mtkaya)
    - [Hugging Face](https://huggingface.co/tugrulkaya)
    """)

if __name__ == "__main__":
    demo.launch()