geyik1 commited on
Commit
9a35313
·
verified ·
1 Parent(s): 992f7ee

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +154 -0
app.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import os
4
+ import sys
5
+ from huggingface_hub import login
6
+ import base64
7
+ import io
8
+ from PIL import Image
9
+ import requests
10
+ import tempfile
11
+
12
+ # Force CPU usage if needed
13
+ device = "cuda" if torch.cuda.is_available() else "cpu"
14
+ print(f"Using device: {device}")
15
+
16
+ # More details about the environment
17
+ print(f"Gradio version: {gr.__version__}")
18
+ print(f"Python version: {sys.version}")
19
+
20
+ # Hugging Face API token'ı - önce environment variable olarak ara,
21
+ # sonra Hugging Face Secrets sisteminde ara
22
+ hf_token = os.environ.get("HUGGINGFACE_TOKEN")
23
+ if hf_token:
24
+ print("Found HUGGINGFACE_TOKEN in environment variables")
25
+ # Token ile giriş yap
26
+ login(token=hf_token)
27
+ print("Logged in with Hugging Face token")
28
+ else:
29
+ print("HUGGINGFACE_TOKEN not found in environment variables")
30
+ # Hugging Face Spaces bu değişkeni otomatik olarak yükleyecek
31
+ # eğer Spaces UI üzerinden secret olarak eklediyseniz
32
+
33
+ # WebP formatını PNG'ye dönüştürme yardımcı fonksiyonu
34
+ def convert_webp_to_png(input_data):
35
+ """WebP formatındaki bir görseli PNG formatına dönüştürür"""
36
+ try:
37
+ # Farklı input türlerini işle
38
+ img = None
39
+
40
+ # URL ise
41
+ if isinstance(input_data, str) and (input_data.startswith('http://') or input_data.startswith('https://')):
42
+ response = requests.get(input_data)
43
+ img = Image.open(io.BytesIO(response.content))
44
+
45
+ # Base64 kodlu ise
46
+ elif isinstance(input_data, str) and input_data.startswith('data:'):
47
+ format, imgstr = input_data.split(';base64,')
48
+ img = Image.open(io.BytesIO(base64.b64decode(imgstr)))
49
+
50
+ # Bytecode ise
51
+ elif isinstance(input_data, bytes):
52
+ img = Image.open(io.BytesIO(input_data))
53
+
54
+ # Dosya yolu ise
55
+ elif isinstance(input_data, str) and os.path.exists(input_data):
56
+ img = Image.open(input_data)
57
+
58
+ # PIL Image ise
59
+ elif isinstance(input_data, Image.Image):
60
+ img = input_data
61
+
62
+ # Görsel açılamadıysa
63
+ if img is None:
64
+ print(f"Couldn't process image data: {type(input_data)}")
65
+ return input_data
66
+
67
+ # Geçici dosya oluştur
68
+ temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
69
+ temp_filename = temp_file.name
70
+ temp_file.close()
71
+
72
+ # RGBA modundaysa RGB'ye dönüştür
73
+ if img.mode == 'RGBA':
74
+ img = img.convert('RGB')
75
+
76
+ # PNG olarak kaydet
77
+ img.save(temp_filename, format="PNG")
78
+ print(f"Converted image saved to {temp_filename}")
79
+
80
+ return temp_filename
81
+ except Exception as e:
82
+ print(f"Error converting image: {str(e)}")
83
+ return input_data
84
+
85
+ def custom_handler(model_result):
86
+ """Model sonucunu işle ve PNG'ye dönüştür"""
87
+ try:
88
+ print(f"Processing model result: {type(model_result)}")
89
+
90
+ # Liste sonucu (tipik API dönüşü)
91
+ if isinstance(model_result, list):
92
+ if len(model_result) > 0:
93
+ # İlk elemanı al
94
+ result_item = model_result[0]
95
+ return convert_webp_to_png(result_item)
96
+
97
+ # Tek sonuç
98
+ return convert_webp_to_png(model_result)
99
+ except Exception as e:
100
+ print(f"Error in custom handler: {str(e)}")
101
+ return model_result
102
+
103
+ def load_model():
104
+ try:
105
+ print("Setting up a custom interface...")
106
+
107
+ # Doğrudan bir arayüz oluştur
108
+ def generate_3d_render(prompt):
109
+ try:
110
+ print(f"Processing prompt: {prompt}")
111
+ # Doğrudan Hugging Face Spaces API'sini çağır
112
+ import gradio.external as ext
113
+ result = ext.call_space(
114
+ name="goofyai/3d_render_style_xl",
115
+ fn_index=0,
116
+ inputs=[prompt]
117
+ )
118
+ print(f"Got result from API: {type(result)}")
119
+
120
+ # Sonucu işle ve PNG'ye dönüştür
121
+ processed_result = custom_handler(result)
122
+ return processed_result
123
+ except Exception as e:
124
+ print(f"Error in generation: {str(e)}")
125
+ return None
126
+
127
+ # Arayüz oluştur
128
+ interface = gr.Interface(
129
+ fn=generate_3d_render,
130
+ inputs=gr.Textbox(label="Input", placeholder="Enter a prompt for 3D rendering"),
131
+ outputs=gr.Image(label="Output", type="filepath"),
132
+ title="3D Render Style XL",
133
+ description="Enter a prompt to generate a 3D render in game-icon style"
134
+ )
135
+ return interface
136
+ except Exception as e:
137
+ print(f"Error setting up interface: {str(e)}")
138
+ return None
139
+
140
+ # Create the interface
141
+ try:
142
+ interface = load_model()
143
+ if interface:
144
+ print("Interface set up successfully, launching...")
145
+ interface.launch(
146
+ share=False,
147
+ server_name="0.0.0.0",
148
+ server_port=7860,
149
+ show_error=True
150
+ )
151
+ else:
152
+ print("Failed to set up the interface")
153
+ except Exception as e:
154
+ print(f"Error launching interface: {str(e)}")