File size: 5,280 Bytes
9a35313
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import torch
import os
import sys
from huggingface_hub import login
import base64
import io
from PIL import Image
import requests
import tempfile

# Force CPU usage if needed
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Using device: {device}")

# More details about the environment
print(f"Gradio version: {gr.__version__}")
print(f"Python version: {sys.version}")

# Hugging Face API token'ı - önce environment variable olarak ara, 
# sonra Hugging Face Secrets sisteminde ara
hf_token = os.environ.get("HUGGINGFACE_TOKEN")
if hf_token:
    print("Found HUGGINGFACE_TOKEN in environment variables")
    # Token ile giriş yap
    login(token=hf_token)
    print("Logged in with Hugging Face token")
else:
    print("HUGGINGFACE_TOKEN not found in environment variables")
    # Hugging Face Spaces bu değişkeni otomatik olarak yükleyecek
    # eğer Spaces UI üzerinden secret olarak eklediyseniz

# WebP formatını PNG'ye dönüştürme yardımcı fonksiyonu
def convert_webp_to_png(input_data):
    """WebP formatındaki bir görseli PNG formatına dönüştürür"""
    try:
        # Farklı input türlerini işle
        img = None
        
        # URL ise
        if isinstance(input_data, str) and (input_data.startswith('http://') or input_data.startswith('https://')):
            response = requests.get(input_data)
            img = Image.open(io.BytesIO(response.content))
        
        # Base64 kodlu ise
        elif isinstance(input_data, str) and input_data.startswith('data:'):
            format, imgstr = input_data.split(';base64,')
            img = Image.open(io.BytesIO(base64.b64decode(imgstr)))
        
        # Bytecode ise
        elif isinstance(input_data, bytes):
            img = Image.open(io.BytesIO(input_data))
        
        # Dosya yolu ise
        elif isinstance(input_data, str) and os.path.exists(input_data):
            img = Image.open(input_data)
        
        # PIL Image ise
        elif isinstance(input_data, Image.Image):
            img = input_data
            
        # Görsel açılamadıysa
        if img is None:
            print(f"Couldn't process image data: {type(input_data)}")
            return input_data
            
        # Geçici dosya oluştur
        temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
        temp_filename = temp_file.name
        temp_file.close()
        
        # RGBA modundaysa RGB'ye dönüştür
        if img.mode == 'RGBA':
            img = img.convert('RGB')
            
        # PNG olarak kaydet
        img.save(temp_filename, format="PNG")
        print(f"Converted image saved to {temp_filename}")
        
        return temp_filename
    except Exception as e:
        print(f"Error converting image: {str(e)}")
        return input_data

def custom_handler(model_result):
    """Model sonucunu işle ve PNG'ye dönüştür"""
    try:
        print(f"Processing model result: {type(model_result)}")
        
        # Liste sonucu (tipik API dönüşü)
        if isinstance(model_result, list):
            if len(model_result) > 0:
                # İlk elemanı al
                result_item = model_result[0]
                return convert_webp_to_png(result_item)
        
        # Tek sonuç
        return convert_webp_to_png(model_result)
    except Exception as e:
        print(f"Error in custom handler: {str(e)}")
        return model_result

def load_model():
    try:
        print("Setting up a custom interface...")
        
        # Doğrudan bir arayüz oluştur
        def generate_3d_render(prompt):
            try:
                print(f"Processing prompt: {prompt}")
                # Doğrudan Hugging Face Spaces API'sini çağır
                import gradio.external as ext
                result = ext.call_space(
                    name="goofyai/3d_render_style_xl",
                    fn_index=0,
                    inputs=[prompt]
                )
                print(f"Got result from API: {type(result)}")
                
                # Sonucu işle ve PNG'ye dönüştür
                processed_result = custom_handler(result)
                return processed_result
            except Exception as e:
                print(f"Error in generation: {str(e)}")
                return None
        
        # Arayüz oluştur
        interface = gr.Interface(
            fn=generate_3d_render,
            inputs=gr.Textbox(label="Input", placeholder="Enter a prompt for 3D rendering"),
            outputs=gr.Image(label="Output", type="filepath"),
            title="3D Render Style XL",
            description="Enter a prompt to generate a 3D render in game-icon style"
        )
        return interface
    except Exception as e:
        print(f"Error setting up interface: {str(e)}")
        return None

# Create the interface
try:
    interface = load_model()
    if interface:
        print("Interface set up successfully, launching...")
        interface.launch(
            share=False,
            server_name="0.0.0.0",
            server_port=7860,
            show_error=True
        )
    else:
        print("Failed to set up the interface")
except Exception as e:
    print(f"Error launching interface: {str(e)}")