Zaiiida commited on
Commit
c38ae1d
·
verified ·
1 Parent(s): 77706c8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +144 -118
app.py CHANGED
@@ -1,5 +1,5 @@
1
  import gradio as gr
2
- import time # For simulating loading times
3
  import tempfile
4
  import numpy as np
5
  import torch
@@ -7,10 +7,10 @@ from PIL import Image
7
  from tsr.system import TSR
8
  from tsr.utils import remove_background, resize_foreground, to_gradio_3d_orientation
9
 
10
- # Check for GPU availability
11
  device = "cuda:0" if torch.cuda.is_available() else "cpu"
12
 
13
- # Load the model
14
  model = TSR.from_pretrained(
15
  "stabilityai/TripoSR",
16
  config_name="config.yaml",
@@ -19,12 +19,14 @@ model = TSR.from_pretrained(
19
  model.renderer.set_chunk_size(131072)
20
  model.to(device)
21
 
22
- # Function to check image input
 
23
  def check_input_image(input_image):
24
  if input_image is None:
25
  raise gr.Error("No image uploaded!")
26
 
27
- # Image preprocessing
 
28
  def preprocess(input_image, do_remove_background, foreground_ratio):
29
  def fill_background(image):
30
  image = np.array(image).astype(np.float32) / 255.0
@@ -43,9 +45,10 @@ def preprocess(input_image, do_remove_background, foreground_ratio):
43
  image = fill_background(image)
44
  return image
45
 
46
- # 3D model generation
 
47
  def generate(image):
48
- time.sleep(3) # Simulate processing time
49
  scene_codes = model(image, device=device)
50
  mesh = model.extract_mesh(scene_codes)[0]
51
  mesh = to_gradio_3d_orientation(mesh)
@@ -53,71 +56,120 @@ def generate(image):
53
  mesh.export(mesh_path2.name)
54
  return mesh_path2.name
55
 
56
- def start_loading_image():
57
- return "<div id='loading-image' style='display: block;'></div>"
58
 
59
- def start_loading_processed():
60
- return "<div id='loading-processed' style='display: block;'></div>"
 
 
 
61
 
62
- def start_loading_model():
63
- return "<div id='loading-model' style='display: block;'></div>"
64
- def stop_loading_image():
65
- return "<div id='loading-image' style='display: none;'></div>"
66
 
67
- def stop_loading_processed():
68
- return "<div id='loading-processed' style='display: none;'></div>"
 
 
 
 
 
 
 
 
 
 
 
69
 
70
- def stop_loading_model():
71
- return "<div id='loading-model' style='display: none;'></div>"
72
 
73
- # Custom CSS and theme
74
  css = """
75
- .custom-loader {
76
- display: none; /* По умолчанию скрыто */
77
- position: absolute;
78
- top: 50%;
79
- left: 50%;
80
- transform: translate(-50%, -50%);
81
- width: 40px;
82
- height: 40px;
83
- border: 4px solid #f3f3f3;
84
- border-top: 4px solid #5271FF;
85
- border-radius: 50%;
86
- animation: spin 1s linear infinite;
87
  }
88
-
89
- @keyframes spin {
90
- 0% { transform: rotate(0deg); }
91
- 100% { transform: rotate(360deg); }
 
 
92
  }
93
-
94
- /* Включение лоадеров внутри контейнеров */
95
- #loading-image {
96
- z-index: 10; /* Вверху */
 
97
  }
98
-
99
- #loading-processed {
100
- z-index: 10;
 
 
101
  }
102
-
103
- #loading-model {
104
- z-index: 10;
 
105
  }
106
-
107
- /* Button styling remains as original */
 
 
 
 
 
 
 
 
 
 
 
108
  .generate-button {
109
  background-color: #5271FF !important;
110
  color: #FFFFFF !important;
111
  border: none;
112
  font-weight: bold;
113
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  """
115
 
116
- # Gradio Interface
117
- with gr.Blocks(css=css) as demo:
118
  with gr.Column():
119
- # Row 1: Image upload
120
- with gr.Row(elem_id="image-container"):
121
  input_image = gr.Image(
122
  label="Upload Image",
123
  image_mode="RGBA",
@@ -132,75 +184,49 @@ with gr.Blocks(css=css) as demo:
132
  width=400,
133
  height=300,
134
  )
135
- loading_image = gr.HTML("<div id='loading-image' class='custom-loader'></div>")
136
- loading_processed = gr.HTML("<div id='loading-processed' class='custom-loader'></div>")
137
- loading_model = gr.HTML("<div id='loading-model' class='custom-loader'></div>")
138
-
139
-
140
- # Row 2: Processing options
141
- with gr.Row(elem_id="process-container"):
142
- foreground_ratio = gr.Slider(
143
- label="Foreground Ratio",
144
- minimum=0.5,
145
- maximum=1.0,
146
- value=0.85,
147
- step=0.05,
148
- )
149
- do_remove_background = gr.Checkbox(label="Remove Background", value=True)
150
- loading_bar_process = gr.HTML("<div class='loader' id='process-loader'></div>")
151
-
152
- # Row 3: Generate button and 3D model
153
- with gr.Row(elem_id="generate-container"):
154
- submit = gr.Button("Generate", elem_classes="generate-button")
155
- output_model = gr.Model3D(
156
- label="Generated GLB Model",
157
- interactive=False,
158
- elem_classes="gr-model3d-container",
159
- )
160
- loading_bar_generate = gr.HTML("<div class='loader' id='generate-loader'></div>")
161
-
162
- # Submit button functionality
163
- submit.click(
164
- fn=lambda: start_loading("image-loader"),
165
- inputs=[],
166
- outputs=[loading_bar_image],
167
- ).then(
168
- fn=check_input_image,
169
- inputs=[input_image],
170
- outputs=[]
171
- ).then(
172
- fn=lambda: stop_loading("image-loader"),
173
- inputs=[],
174
- outputs=[loading_bar_image],
175
- ).then(
176
- fn=lambda: start_loading("process-loader"),
177
- inputs=[],
178
- outputs=[loading_bar_process],
179
- ).then(
180
- fn=preprocess,
181
- inputs=[input_image, do_remove_background, foreground_ratio],
182
- outputs=[processed_image],
183
- ).then(
184
- fn=lambda: stop_loading("process-loader"),
185
- inputs=[],
186
- outputs=[loading_bar_process],
187
- ).then(
188
- fn=lambda: start_loading("generate-loader"),
189
- inputs=[],
190
- outputs=[loading_bar_generate],
191
- ).then(
192
- fn=generate,
193
- inputs=[processed_image],
194
- outputs=[output_model],
195
- ).then(
196
- fn=lambda: stop_loading("generate-loader"),
197
- inputs=[],
198
- outputs=[loading_bar_generate],
199
  )
200
 
201
- # Launch app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
  demo.launch(
203
  server_name="0.0.0.0",
204
  server_port=7860,
205
  share=True,
206
- )
 
1
  import gradio as gr
2
+ import time # Для эмуляции времени загрузки
3
  import tempfile
4
  import numpy as np
5
  import torch
 
7
  from tsr.system import TSR
8
  from tsr.utils import remove_background, resize_foreground, to_gradio_3d_orientation
9
 
10
+ # Проверяем наличие GPU
11
  device = "cuda:0" if torch.cuda.is_available() else "cpu"
12
 
13
+ # Загружаем модель
14
  model = TSR.from_pretrained(
15
  "stabilityai/TripoSR",
16
  config_name="config.yaml",
 
19
  model.renderer.set_chunk_size(131072)
20
  model.to(device)
21
 
22
+
23
+ # Функция для проверки изображения
24
  def check_input_image(input_image):
25
  if input_image is None:
26
  raise gr.Error("No image uploaded!")
27
 
28
+
29
+ # Функция обработки изображения
30
  def preprocess(input_image, do_remove_background, foreground_ratio):
31
  def fill_background(image):
32
  image = np.array(image).astype(np.float32) / 255.0
 
45
  image = fill_background(image)
46
  return image
47
 
48
+
49
+ # Функция генерации 3D модели
50
  def generate(image):
51
+ time.sleep(3) # Эмуляция времени обработки
52
  scene_codes = model(image, device=device)
53
  mesh = model.extract_mesh(scene_codes)[0]
54
  mesh = to_gradio_3d_orientation(mesh)
 
56
  mesh.export(mesh_path2.name)
57
  return mesh_path2.name
58
 
 
 
59
 
60
+ def start_loading():
61
+ return gr.HTML.update(visible=True)
62
+
63
+ def stop_loading():
64
+ return gr.HTML.update(visible=False)
65
 
 
 
 
 
66
 
67
+ # Настройка темы и CSS
68
+ class CustomTheme(gr.themes.Base):
69
+ def __init__(self):
70
+ super().__init__()
71
+ self.primary_hue = "#191a1e"
72
+ self.background_fill_primary = "#191a1e"
73
+ self.background_fill_secondary = "#191a1e"
74
+ self.background_fill_tertiary = "#191a1e"
75
+ self.text_color_primary = "#FFFFFF"
76
+ self.text_color_secondary = "#FFFFFF"
77
+ self.text_color_tertiary = "#FFFFFF"
78
+ self.input_background_fill = "#191a1e"
79
+ self.input_text_color = "#FFFFFF"
80
 
 
 
81
 
 
82
  css = """
83
+ /* Скрываем нижний колонтитул */
84
+ footer {
85
+ visibility: hidden;
86
+ height: 0;
87
+ margin: 0;
88
+ padding: 0;
89
+ overflow: hidden;
 
 
 
 
 
90
  }
91
+ /* Применяем шрифты */
92
+ @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;700&display=swap');
93
+ body, input, button, textarea, select, .gr-button {
94
+ font-family: 'Poppins', sans-serif;
95
+ background-color: #191a1e !important;
96
+ color: #FFFFFF;
97
  }
98
+ /* Настройки заголовков */
99
+ h1, h2, h3, h4, h5, h6 {
100
+ font-family: 'Poppins', sans-serif;
101
+ font-weight: 700;
102
+ color: #FFFFFF;
103
  }
104
+ /* Стиль для текстовых полей и кнопок */
105
+ input[type="text"], textarea {
106
+ background-color: #191a1e !important;
107
+ color: #FFFFFF;
108
+ border: 1px solid #FFFFFF;
109
  }
110
+ /* Слайдер */
111
+ .gr-slider {
112
+ height: 40px !important; /* Увеличение высоты слайдера */
113
+ transition: all 0.3s ease !important; /* Плавные переходы */
114
  }
115
+ .gr-slider .slider-value {
116
+ display: none !important; /* Прячем текст значения */
117
+ }
118
+ .gr-slider .slider::-webkit-slider-thumb {
119
+ height: 15px !important;
120
+ width: 15px !important;
121
+ background-color: #5271FF !important; /* Цвет совпадает с кнопкой */
122
+ border-radius: 50%;
123
+ }
124
+ .gr-slider .slider::-webkit-slider-runnable-track {
125
+ background: #5271FF !important; /* Цвет заполнения слайдера */
126
+ }
127
+ /* Кнопка Generate */
128
  .generate-button {
129
  background-color: #5271FF !important;
130
  color: #FFFFFF !important;
131
  border: none;
132
  font-weight: bold;
133
  }
134
+ .generate-button:hover {
135
+ background-color: #405BBF !important; /* Цвет при наведении */
136
+ }
137
+ .generate-button {
138
+ position: relative; /* Кнопка становится родительским контейнером */
139
+ }
140
+ /* Выделяем текст для Prompt */
141
+ .prompt-text {
142
+ font-weight: bold;
143
+ color: #FFFFFF;
144
+ }
145
+ /* Лоадер (анимация) */
146
+ #loading-bar {
147
+ display: none; /* Скрыт по умолчанию */
148
+ position: relative; /* Изменено на relative для использования в кнопке */
149
+ margin: 0 auto; /* Центрируем внутри родительского элемента */
150
+ width: 30px; /* Уменьшен размер для кнопки */
151
+ height: 30px;
152
+ border: 4px solid #f3f3f3;
153
+ border-top: 4px solid #5271FF; /* Цвет лоадера */
154
+ border-radius: 50%;
155
+ animation: spin 1s linear infinite;
156
+ }
157
+ /* Анимация вращения */
158
+ @keyframes spin {
159
+ 0% { transform: translate(-50%, -50%) rotate(0deg); }
160
+ 100% { transform: translate(-50%, -50%) rotate(360deg); }
161
+ }
162
+ /* Текст CheckBox в белый */
163
+ .gr-checkbox label {
164
+ color: #FFFFFF !important;
165
+ }
166
  """
167
 
168
+ # Интерфейс
169
+ with gr.Blocks(theme=CustomTheme(), css=css) as demo:
170
  with gr.Column():
171
+ gr.Markdown("<span style='color: white; font-weight: bold;'>Upload and Process Your Image</span>")
172
+ with gr.Row():
173
  input_image = gr.Image(
174
  label="Upload Image",
175
  image_mode="RGBA",
 
184
  width=400,
185
  height=300,
186
  )
187
+ foreground_ratio = gr.Slider(
188
+ label="Foreground Ratio",
189
+ minimum=0.5,
190
+ maximum=1.0,
191
+ value=0.85,
192
+ step=0.05,
193
+ )
194
+ do_remove_background = gr.Checkbox(
195
+ label="Remove Background", # Текст перекрашен в белый через CSS
196
+ value=True,
197
+ )
198
+ submit = gr.Button("Generate", elem_classes="generate-button")
199
+ loading_bar = gr.HTML("<div id='loading-bar'></div>")
200
+ output_model = gr.Model3D(
201
+ label="Generated GLB Model",
202
+ interactive=False,
203
+ elem_classes="gr-model3d-container",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
  )
205
 
206
+ submit.click(
207
+ fn=start_loading, # Включить прогресс-бар
208
+ inputs=[],
209
+ outputs=[loading_bar]
210
+ ).then(
211
+ fn=check_input_image,
212
+ inputs=[input_image],
213
+ outputs=[]
214
+ ).then(
215
+ fn=preprocess,
216
+ inputs=[input_image, do_remove_background, foreground_ratio],
217
+ outputs=[processed_image]
218
+ ).then(
219
+ fn=generate,
220
+ inputs=[processed_image],
221
+ outputs=[output_model]
222
+ ).then(
223
+ fn=stop_loading, # Отключаем прогресс-бар после завершения генерации
224
+ inputs=[],
225
+ outputs=[loading_bar]
226
+ )
227
+ # Запуск приложения
228
  demo.launch(
229
  server_name="0.0.0.0",
230
  server_port=7860,
231
  share=True,
232
+ )