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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# pip install google-genai gradio pillow
|
2 |
+
|
3 |
+
import base64
|
4 |
+
import mimetypes
|
5 |
+
import os
|
6 |
+
import io
|
7 |
+
import gradio as gr
|
8 |
+
from google import genai
|
9 |
+
from google.genai import types
|
10 |
+
from PIL import Image
|
11 |
+
import tempfile
|
12 |
+
|
13 |
+
class GeminiImageGenerator:
|
14 |
+
def __init__(self):
|
15 |
+
self.client = None
|
16 |
+
self.model = "gemini-2.5-flash-image-preview"
|
17 |
+
|
18 |
+
def set_api_key(self, api_key):
|
19 |
+
"""API anahtarını ayarla"""
|
20 |
+
try:
|
21 |
+
os.environ["GEMINI_API_KEY"] = api_key
|
22 |
+
self.client = genai.Client(api_key=api_key)
|
23 |
+
return "✅ API anahtarı başarıyla ayarlandı!"
|
24 |
+
except Exception as e:
|
25 |
+
return f"❌ API anahtarı ayarlanırken hata: {str(e)}"
|
26 |
+
|
27 |
+
def generate_image(self, prompt, api_key):
|
28 |
+
"""Görsel oluştur"""
|
29 |
+
if not api_key:
|
30 |
+
return None, "❌ Lütfen önce API anahtarınızı girin!"
|
31 |
+
|
32 |
+
if not prompt.strip():
|
33 |
+
return None, "❌ Lütfen bir görsel açıklaması girin!"
|
34 |
+
|
35 |
+
try:
|
36 |
+
# API anahtarını ayarla
|
37 |
+
if not self.client or os.environ.get("GEMINI_API_KEY") != api_key:
|
38 |
+
self.client = genai.Client(api_key=api_key)
|
39 |
+
os.environ["GEMINI_API_KEY"] = api_key
|
40 |
+
|
41 |
+
# İçerik oluştur
|
42 |
+
contents = [
|
43 |
+
types.Content(
|
44 |
+
role="user",
|
45 |
+
parts=[
|
46 |
+
types.Part.from_text(text=f"Generate an image of: {prompt}"),
|
47 |
+
],
|
48 |
+
),
|
49 |
+
]
|
50 |
+
|
51 |
+
generate_content_config = types.GenerateContentConfig(
|
52 |
+
response_modalities=[
|
53 |
+
"IMAGE",
|
54 |
+
"TEXT",
|
55 |
+
],
|
56 |
+
)
|
57 |
+
|
58 |
+
# Stream'den veri al
|
59 |
+
image_data = None
|
60 |
+
text_response = ""
|
61 |
+
|
62 |
+
for chunk in self.client.models.generate_content_stream(
|
63 |
+
model=self.model,
|
64 |
+
contents=contents,
|
65 |
+
config=generate_content_config,
|
66 |
+
):
|
67 |
+
if (
|
68 |
+
chunk.candidates is None
|
69 |
+
or chunk.candidates[0].content is None
|
70 |
+
or chunk.candidates[0].content.parts is None
|
71 |
+
):
|
72 |
+
continue
|
73 |
+
|
74 |
+
# Görsel verisi varsa al
|
75 |
+
if (chunk.candidates[0].content.parts[0].inline_data and
|
76 |
+
chunk.candidates[0].content.parts[0].inline_data.data):
|
77 |
+
inline_data = chunk.candidates[0].content.parts[0].inline_data
|
78 |
+
image_data = inline_data.data
|
79 |
+
|
80 |
+
# Metin yanıtı varsa al
|
81 |
+
if hasattr(chunk, 'text') and chunk.text:
|
82 |
+
text_response += chunk.text
|
83 |
+
|
84 |
+
if image_data:
|
85 |
+
# Görsel verisini PIL Image'e çevir
|
86 |
+
image = Image.open(io.BytesIO(image_data))
|
87 |
+
success_msg = f"✅ Görsel başarıyla oluşturuldu!\n\nAçıklama: {prompt}"
|
88 |
+
if text_response:
|
89 |
+
success_msg += f"\n\nGemini'nin yorumu: {text_response}"
|
90 |
+
return image, success_msg
|
91 |
+
else:
|
92 |
+
return None, f"❌ Görsel oluşturulamadı. Yanıt: {text_response}"
|
93 |
+
|
94 |
+
except Exception as e:
|
95 |
+
return None, f"❌ Hata oluştu: {str(e)}"
|
96 |
+
|
97 |
+
def save_image(self, image, filename):
|
98 |
+
"""Görseli kaydet"""
|
99 |
+
if image is None:
|
100 |
+
return "❌ Kaydedilecek görsel yok!"
|
101 |
+
|
102 |
+
try:
|
103 |
+
if not filename.strip():
|
104 |
+
filename = "generated_image.png"
|
105 |
+
|
106 |
+
if not filename.endswith(('.png', '.jpg', '.jpeg')):
|
107 |
+
filename += '.png'
|
108 |
+
|
109 |
+
image.save(filename)
|
110 |
+
return f"✅ Görsel '{filename}' olarak kaydedildi!"
|
111 |
+
except Exception as e:
|
112 |
+
return f"❌ Kaydetme hatası: {str(e)}"
|
113 |
+
|
114 |
+
# Generator instance
|
115 |
+
generator = GeminiImageGenerator()
|
116 |
+
|
117 |
+
def generate_and_display(prompt, api_key):
|
118 |
+
"""Görsel oluştur ve göster"""
|
119 |
+
return generator.generate_image(prompt, api_key)
|
120 |
+
|
121 |
+
def save_current_image(image, filename):
|
122 |
+
"""Mevcut görseli kaydet"""
|
123 |
+
return generator.save_image(image, filename)
|
124 |
+
|
125 |
+
# Gradio arayüzü
|
126 |
+
with gr.Blocks(
|
127 |
+
theme=gr.themes.Soft(),
|
128 |
+
title="Gemini Görsel Oluşturucu",
|
129 |
+
css="""
|
130 |
+
.main-container {
|
131 |
+
max-width: 1200px;
|
132 |
+
margin: 0 auto;
|
133 |
+
}
|
134 |
+
.header {
|
135 |
+
text-align: center;
|
136 |
+
padding: 20px 0;
|
137 |
+
background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
|
138 |
+
color: white;
|
139 |
+
border-radius: 10px;
|
140 |
+
margin-bottom: 20px;
|
141 |
+
}
|
142 |
+
.generate-btn {
|
143 |
+
background: linear-gradient(45deg, #667eea 0%, #764ba2 100%) !important;
|
144 |
+
border: none !important;
|
145 |
+
color: white !important;
|
146 |
+
}
|
147 |
+
"""
|
148 |
+
) as demo:
|
149 |
+
|
150 |
+
gr.HTML("""
|
151 |
+
<div class="header">
|
152 |
+
<h1>🎨 Gemini Görsel Oluşturucu</h1>
|
153 |
+
<p>Google Gemini AI ile yaratıcı görseller oluşturun</p>
|
154 |
+
</div>
|
155 |
+
""")
|
156 |
+
|
157 |
+
with gr.Row():
|
158 |
+
with gr.Column(scale=1):
|
159 |
+
# API Key girişi
|
160 |
+
api_key_input = gr.Textbox(
|
161 |
+
label="🔑 Gemini API Anahtarı",
|
162 |
+
placeholder="API anahtarınızı buraya girin...",
|
163 |
+
type="password",
|
164 |
+
info="Google AI Studio'dan alacağınız API anahtarını girin"
|
165 |
+
)
|
166 |
+
|
167 |
+
# Prompt girişi
|
168 |
+
prompt_input = gr.Textbox(
|
169 |
+
label="📝 Görsel Açıklaması",
|
170 |
+
placeholder="Örnek: Bir kedi astronot uzayda yüzüyor",
|
171 |
+
lines=3,
|
172 |
+
info="Oluşturmak istediğiniz görseli detaylı olarak açıklayın"
|
173 |
+
)
|
174 |
+
|
175 |
+
# Örnek promptlar
|
176 |
+
gr.Examples(
|
177 |
+
examples=[
|
178 |
+
["Bir kedi astronot uzayda yüzüyor"],
|
179 |
+
["Cyberpunk tarzında neon şehir manzarası"],
|
180 |
+
["Sihirli orman içinde parlayan mantarlar"],
|
181 |
+
["Vintage tarzda robot kahve içiyor"],
|
182 |
+
["Underwater saray balıklar arasında"],
|
183 |
+
["Steampunk tarzında uçan makine"],
|
184 |
+
],
|
185 |
+
inputs=prompt_input,
|
186 |
+
label="💡 Örnek Promptlar"
|
187 |
+
)
|
188 |
+
|
189 |
+
# Oluştur butonu
|
190 |
+
generate_btn = gr.Button(
|
191 |
+
"🎨 Görsel Oluştur",
|
192 |
+
variant="primary",
|
193 |
+
elem_classes=["generate-btn"],
|
194 |
+
scale=1
|
195 |
+
)
|
196 |
+
|
197 |
+
# Kaydetme bölümü
|
198 |
+
gr.Markdown("### 💾 Görseli Kaydet")
|
199 |
+
filename_input = gr.Textbox(
|
200 |
+
label="Dosya Adı",
|
201 |
+
placeholder="ornek_gorsel.png",
|
202 |
+
value="generated_image.png"
|
203 |
+
)
|
204 |
+
save_btn = gr.Button("💾 Kaydet", variant="secondary")
|
205 |
+
|
206 |
+
with gr.Column(scale=2):
|
207 |
+
# Görsel çıktısı
|
208 |
+
image_output = gr.Image(
|
209 |
+
label="🖼️ Oluşturulan Görsel",
|
210 |
+
type="pil",
|
211 |
+
height=500
|
212 |
+
)
|
213 |
+
|
214 |
+
# Durum mesajı
|
215 |
+
status_output = gr.Textbox(
|
216 |
+
label="📊 Durum",
|
217 |
+
lines=4,
|
218 |
+
interactive=False
|
219 |
+
)
|
220 |
+
|
221 |
+
# Kaydetme durumu
|
222 |
+
save_status = gr.Textbox(
|
223 |
+
label="💾 Kaydetme Durumu",
|
224 |
+
lines=2,
|
225 |
+
interactive=False
|
226 |
+
)
|
227 |
+
|
228 |
+
# Event handlers
|
229 |
+
generate_btn.click(
|
230 |
+
fn=generate_and_display,
|
231 |
+
inputs=[prompt_input, api_key_input],
|
232 |
+
outputs=[image_output, status_output]
|
233 |
+
)
|
234 |
+
|
235 |
+
save_btn.click(
|
236 |
+
fn=save_current_image,
|
237 |
+
inputs=[image_output, filename_input],
|
238 |
+
outputs=[save_status]
|
239 |
+
)
|
240 |
+
|
241 |
+
# Enter tuşu ile oluşturma
|
242 |
+
prompt_input.submit(
|
243 |
+
fn=generate_and_display,
|
244 |
+
inputs=[prompt_input, api_key_input],
|
245 |
+
outputs=[image_output, status_output]
|
246 |
+
)
|
247 |
+
|
248 |
+
# Kullanım talimatları
|
249 |
+
gr.Markdown("""
|
250 |
+
## 📖 Kullanım Talimatları
|
251 |
+
|
252 |
+
1. **API Anahtarı**: Google AI Studio'dan Gemini API anahtarınızı alın ve yukarıdaki alana girin
|
253 |
+
2. **Prompt**: Oluşturmak istediğiniz görseli detaylı olarak açıklayın
|
254 |
+
3. **Oluştur**: "Görsel Oluştur" butonuna tıklayın veya Enter'a basın
|
255 |
+
4. **Kaydet**: Beğendiğiniz görseli bilgisayarınıza kaydedin
|
256 |
+
|
257 |
+
### 💡 İpuçları
|
258 |
+
- Detaylı açıklamalar daha iyi sonuçlar verir
|
259 |
+
- Sanat tarzı belirtin (cyberpunk, vintage, anime, vb.)
|
260 |
+
- Renk paletini ve atmosferi tanımlayın
|
261 |
+
- Örnek promptları deneyerek başlayabilirsiniz
|
262 |
+
|
263 |
+
### 🔗 Faydalı Linkler
|
264 |
+
- [Google AI Studio](https://makersuite.google.com/app/apikey) - API anahtarı almak için
|
265 |
+
- [Gemini API Dökümantasyonu](https://ai.google.dev/docs)
|
266 |
+
""")
|
267 |
+
|
268 |
+
if __name__ == "__main__":
|
269 |
+
demo.launch(
|
270 |
+
server_name="0.0.0.0",
|
271 |
+
server_port=7860,
|
272 |
+
share=True,
|
273 |
+
debug=True
|
274 |
+
)
|