File size: 3,765 Bytes
677cef0
52d69f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
677cef0
 
 
52d69f0
 
677cef0
 
52d69f0
677cef0
52d69f0
fb137fc
677cef0
 
52d69f0
677cef0
 
 
 
 
 
 
 
 
 
52d69f0
677cef0
52d69f0
677cef0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52d69f0
677cef0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52d69f0
677cef0
 
 
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
import gradio as gr
import os
import sys
import subprocess

# --- 1. StyleGAN2 Kütüphanelerini Hazırlama (En Önemli Adım) ---
# dnnlib ve legacy gibi özel kütüphaneleri bulabilmek için
# stylegan2-ada-pytorch deposunu klonlamamız gerekiyor.

# Klonlanacak repo ve hedef klasör adı
repo_url = "https://github.com/NVlabs/stylegan2-ada-pytorch.git"
repo_dir = "stylegan2-ada-pytorch"

# Eğer klasör zaten yoksa, git clone komutunu çalıştır
if not os.path.exists(repo_dir):
    print(f"'{repo_dir}' deposu indiriliyor...")
    subprocess.run(["git", "clone", repo_url])
    print("Depo başarıyla indirildi.")

# Klonlanan klasörün yolunu Python'un arama yollarına ekle
# Bu sayede `import dnnlib` ve `import legacy` komutları çalışır.
sys.path.insert(0, os.path.join(os.getcwd(), repo_dir))

# Artık import edebiliriz
import pickle
import numpy as np
import torch
import dnnlib
import legacy
from PIL import Image

# --- 2. Model Adı ve Yükleme ---
# !! DEĞİŞTİRİLECEK YER !!
# Hugging Face'e yüklediğiniz .pkl model dosyasının tam adını buraya yazın.
MODEL_FILENAME = "network-snapshot-000006.pkl" 

MODEL_PATH = MODEL_FILENAME
device = torch.device('cpu') # Ücretsiz CPU donanımı için 'cpu'

# Modelin yüklenmesi
G = None
try:
    print(f"Model yükleniyor: {MODEL_PATH}")
    with dnnlib.util.open_url(MODEL_PATH) as f:
        G = legacy.load_network_pkl(f)['G_ema'].to(device)
    print("Model başarıyla yüklendi.")
except Exception as e:
    print(f"Model yüklenemedi: {e}")
    gr.Warning(f"Model Yüklenemedi! Dosya adının ({MODEL_FILENAME}) doğru olduğundan emin olun. Hata: {e}")

# --- 3. Görüntü Üretme Fonksiyonu ---
def generate_image(seed, truncation_psi):
    if G is None:
        raise gr.Error("Model yüklenemediği için görüntü üretilemiyor. Lütfen Space loglarını kontrol edin.")
    
    if seed == -1:
        seed = np.random.randint(0, 2**32 - 1)
        
    print(f"Görüntü üretiliyor... Seed: {seed}, Truncation: {truncation_psi}")
    
    z = torch.from_numpy(np.random.RandomState(seed).randn(1, G.z_dim)).to(device)
    img = G(z, None, truncation_psi=truncation_psi, noise_mode='const')
    img = (img.permute(0, 2, 3, 1) * 127.5 + 128).clamp(0, 255).to(torch.uint8)
    
    return Image.fromarray(img[0].cpu().numpy(), 'RGB'), seed

# --- 4. Gradio Arayüzü ---
with gr.Blocks(theme=gr.themes.Soft()) as demo:
    gr.Markdown("# 🎨 StyleGAN2 ile Eğitilmiş Anime Karakter Üreticisi")
    gr.Markdown("Bu demo, özel olarak eğitilmiş bir StyleGAN2 modeli kullanarak yeni anime karakterleri üretir.")
    
    with gr.Row():
        with gr.Column(scale=1):
            seed_input = gr.Number(label="Seed Numarası (-1 = Rastgele)", value=-1, precision=0)
            truncation_input = gr.Slider(label="Truncation Psi (0.5=Daha Ortalama, 1.0=Daha Çeşitli)", minimum=0.1, maximum=1.5, step=0.05, value=0.7)
            
            with gr.Row():
                random_btn = gr.Button("Rastgele Oluştur 🎲")
                generate_btn = gr.Button("Belirtilen Seed ile Oluştur ⚙️", variant="primary")
                
        with gr.Column(scale=1):
            image_output = gr.Image(label="Sonuç", type="pil")
            used_seed_output = gr.Number(label="Kullanılan Seed", interactive=False)

    generate_btn.click(fn=generate_image, inputs=[seed_input, truncation_input], outputs=[image_output, used_seed_output])
    random_btn.click(fn=lambda: -1, inputs=None, outputs=seed_input).then(
        fn=generate_image, inputs=[seed_input, truncation_input], outputs=[image_output, used_seed_output]
    )
    
    gr.Examples(examples=[[100, 0.7], [42, 0.8]], inputs=[seed_input, truncation_input])

# Uygulamayı başlat
demo.launch()