geyik1 commited on
Commit
e9c688b
·
verified ·
1 Parent(s): 7e6910a

Delete app.py

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