geyik1 commited on
Commit
5e3f873
·
verified ·
1 Parent(s): bb89d71

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -232
app.py DELETED
@@ -1,232 +0,0 @@
1
- import torch
2
- import gradio as gr
3
- from diffusers import ShapEPipeline, ShapEImg2ImgPipeline
4
- from diffusers.utils import export_to_gif
5
- import os
6
- from huggingface_hub import HfApi, login
7
- from PIL import Image
8
- import numpy as np
9
- import gc
10
-
11
- # Zorla CPU kullanımı
12
- device = "cpu"
13
- torch.set_num_threads(4) # CPU thread sayısını sınırla
14
- print(f"Kullanılan cihaz: {device}")
15
-
16
- def validate_token(token):
17
- try:
18
- login(token=token)
19
- return True
20
- except Exception as e:
21
- print(f"Token doğrulama hatası: {str(e)}")
22
- return False
23
-
24
- def generate_3d_from_text(prompt, token, guidance_scale=7.0, export_format="obj", progress=gr.Progress()):
25
- try:
26
- if not validate_token(token):
27
- return "Geçersiz Hugging Face token'ı", None, None
28
-
29
- print(f"Üretim başlıyor: {prompt}")
30
- progress(0.1, "Model yükleniyor...")
31
-
32
- # Model yükleme (token ile)
33
- pipe = ShapEPipeline.from_pretrained(
34
- "openai/shap-e",
35
- torch_dtype=torch.float32,
36
- token=token,
37
- revision="main",
38
- low_cpu_mem_usage=True
39
- )
40
-
41
- # Çıktı klasörü kontrolü
42
- os.makedirs("outputs", exist_ok=True)
43
-
44
- # Dosya adı oluşturma
45
- safe_prompt = "".join(x for x in prompt if x.isalnum() or x in (" ", "-", "_"))
46
- base_filename = f"outputs/{safe_prompt}"
47
-
48
- try:
49
- progress(0.3, "3D model oluşturuluyor...")
50
- with torch.no_grad(): # Bellek kullanımını azalt
51
- # 3D model oluşturma
52
- output = pipe(
53
- prompt,
54
- guidance_scale=min(guidance_scale, 10.0), # Guidance scale'i sınırla
55
- num_inference_steps=16 # Sabit düşük adım sayısı
56
- )
57
-
58
- progress(0.5, "GIF oluşturuluyor...")
59
- # GIF kaydetme
60
- gif_path = export_to_gif(output.images, f"{base_filename}.gif")
61
-
62
- progress(0.7, "3D mesh oluşturuluyor...")
63
- # 3D mesh oluşturma
64
- mesh_output = pipe(
65
- prompt,
66
- guidance_scale=min(guidance_scale, 10.0),
67
- num_inference_steps=16,
68
- output_type="mesh"
69
- )
70
-
71
- progress(0.9, "Dosyalar kaydediliyor...")
72
- # Mesh'i kaydetme
73
- output_path = f"{base_filename}.{export_format}"
74
- mesh_output.meshes[0].export(output_path)
75
-
76
- # Belleği temizle
77
- del pipe
78
- del output
79
- del mesh_output
80
- gc.collect()
81
-
82
- print(f"Üretim tamamlandı: {output_path}")
83
- progress(1.0, "Tamamlandı!")
84
- return "Üretim başarılı!", gif_path, output_path
85
-
86
- except Exception as model_error:
87
- error_msg = f"Model çalıştırma hatası: {str(model_error)}"
88
- print(error_msg)
89
- return error_msg, None, None
90
-
91
- except Exception as e:
92
- error_msg = f"Genel hata: {str(e)}"
93
- print(error_msg)
94
- return error_msg, None, None
95
-
96
- def generate_3d_from_image(image, token, guidance_scale=7.0, export_format="obj", progress=gr.Progress()):
97
- try:
98
- if not validate_token(token):
99
- return "Geçersiz Hugging Face token'ı", None, None
100
-
101
- print("Görüntüden 3D model üretimi başlıyor")
102
- progress(0.1, "Model yükleniyor...")
103
-
104
- # Model yükleme (token ile)
105
- pipe = ShapEImg2ImgPipeline.from_pretrained(
106
- "openai/shap-e-img2img",
107
- torch_dtype=torch.float32,
108
- token=token,
109
- revision="main",
110
- low_cpu_mem_usage=True
111
- )
112
-
113
- # Çıktı klasörü kontrolü
114
- os.makedirs("outputs", exist_ok=True)
115
-
116
- # Dosya adı oluşturma
117
- import time
118
- timestamp = int(time.time())
119
- base_filename = f"outputs/image_to_3d_{timestamp}"
120
-
121
- try:
122
- progress(0.3, "Görüntü hazırlanıyor...")
123
- # Görüntüyü hazırla
124
- if isinstance(image, str):
125
- image = Image.open(image)
126
- elif isinstance(image, np.ndarray):
127
- image = Image.fromarray(image)
128
-
129
- # Görüntüyü yeniden boyutlandır
130
- image = image.resize((128, 128)) # Daha küçük boyut
131
-
132
- progress(0.5, "3D model oluşturuluyor...")
133
- with torch.no_grad(): # Bellek kullanımını azalt
134
- # 3D model oluşturma
135
- output = pipe(
136
- image=image,
137
- guidance_scale=min(guidance_scale, 10.0),
138
- num_inference_steps=16
139
- )
140
-
141
- progress(0.7, "GIF oluşturuluyor...")
142
- # GIF kaydetme
143
- gif_path = export_to_gif(output.images, f"{base_filename}.gif")
144
-
145
- progress(0.8, "3D mesh oluşturuluyor...")
146
- # 3D mesh oluşturma
147
- mesh_output = pipe(
148
- image=image,
149
- guidance_scale=min(guidance_scale, 10.0),
150
- num_inference_steps=16,
151
- output_type="mesh"
152
- )
153
-
154
- progress(0.9, "Dosyalar kaydediliyor...")
155
- # Mesh'i kaydetme
156
- output_path = f"{base_filename}.{export_format}"
157
- mesh_output.meshes[0].export(output_path)
158
-
159
- # Belleği temizle
160
- del pipe
161
- del output
162
- del mesh_output
163
- gc.collect()
164
-
165
- print(f"Üretim tamamlandı: {output_path}")
166
- progress(1.0, "Tamamlandı!")
167
- return "Üretim başarılı!", gif_path, output_path
168
-
169
- except Exception as model_error:
170
- error_msg = f"Model çalıştırma hatası: {str(model_error)}"
171
- print(error_msg)
172
- return error_msg, None, None
173
-
174
- except Exception as e:
175
- error_msg = f"Genel hata: {str(e)}"
176
- print(error_msg)
177
- return error_msg, None, None
178
-
179
- # Gradio arayüzü
180
- with gr.Blocks() as interface:
181
- gr.Markdown("# DNM3D - 3D Model Üretici")
182
- gr.Markdown("Metin veya görüntü girişiyle 3D model oluşturun. Kullanmak için Hugging Face token'ınızı girmeniz gerekiyor.")
183
- gr.Markdown("""
184
- > **Önemli Not**:
185
- > - İşlem süresi CPU'da uzun sürebilir
186
- > - Daha hızlı sonuç için guidance scale'i 10'un altında tutun
187
- > - Adım sayısı 16 olarak sabitlenmiştir
188
- > - Kalite/hız optimizasyonu için görüntü boyutu küçültülmüştür
189
- """)
190
-
191
- with gr.Tab("Metin → 3D"):
192
- with gr.Row():
193
- with gr.Column():
194
- text_input = gr.Textbox(label="3D Model için açıklama giriniz (İngilizce)")
195
- text_token = gr.Textbox(label="Hugging Face Token", type="password")
196
- text_guidance = gr.Slider(minimum=1, maximum=10, value=7, label="Guidance Scale")
197
- text_format = gr.Radio(["obj", "glb"], label="Export Formatı", value="obj")
198
- text_button = gr.Button("Oluştur")
199
-
200
- with gr.Column():
201
- text_status = gr.Textbox(label="Durum")
202
- text_preview = gr.Image(label="3D Önizleme (GIF)")
203
- text_file = gr.File(label="3D Model Dosyası")
204
-
205
- with gr.Tab("Görüntü → 3D"):
206
- with gr.Row():
207
- with gr.Column():
208
- image_input = gr.Image(label="3D Modele dönüştürülecek görüntü", type="pil")
209
- image_token = gr.Textbox(label="Hugging Face Token", type="password")
210
- image_guidance = gr.Slider(minimum=1, maximum=10, value=7, label="Guidance Scale")
211
- image_format = gr.Radio(["obj", "glb"], label="Export Formatı", value="obj")
212
- image_button = gr.Button("Oluştur")
213
-
214
- with gr.Column():
215
- image_status = gr.Textbox(label="Durum")
216
- image_preview = gr.Image(label="3D Önizleme (GIF)")
217
- image_file = gr.File(label="3D Model Dosyası")
218
-
219
- text_button.click(
220
- generate_3d_from_text,
221
- inputs=[text_input, text_token, text_guidance, text_format],
222
- outputs=[text_status, text_preview, text_file]
223
- )
224
-
225
- image_button.click(
226
- generate_3d_from_image,
227
- inputs=[image_input, image_token, image_guidance, image_format],
228
- outputs=[image_status, image_preview, image_file]
229
- )
230
-
231
- if __name__ == "__main__":
232
- interface.launch()