bokula commited on
Commit
1863a65
·
verified ·
1 Parent(s): 58b1e11

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -164
app.py CHANGED
@@ -11,53 +11,34 @@ import gradio as gr
11
  import numpy as np
12
  from PIL import Image
13
 
14
- from relief_workshop import (
15
- build_heightmap, heightmap_to_stl,
16
- blobs_to_stl, blob_preview,
17
- )
18
 
19
 
20
- # ─────────────────────────────────────────────
21
- # CORE
22
- # ─────────────────────────────────────────────
23
-
24
- def preview_depthmap(image, invert, quantize_levels, tileable, blur,
25
- no_base, separate_blobs, threshold):
26
  if image is None:
27
  return None, "⚠️ Carica un'immagine."
28
  try:
29
  with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:
30
  tmp = f.name
31
  Image.fromarray(image).save(tmp)
32
-
33
- if no_base and separate_blobs:
34
- # Blob preview: mostra i contorni trovati
35
- prev, n = blob_preview(tmp, threshold=int(threshold))
36
- Path(tmp).unlink(missing_ok=True)
37
- msg = f"{n} blob trovati — ognuno diventerà un cilindretto separato"
38
- if n == 0:
39
- msg = "Nessun blob trovato. Prova ad abbassare la soglia o usare un'immagine con forme bianche su nero."
40
- return prev, msg
41
- else:
42
- # Heightmap preview normale
43
- quantize = int(quantize_levels) if quantize_levels >= 2 else 0
44
- height_map, px_w, px_h = build_heightmap(
45
- tmp, max_px=300, invert=invert, blur=blur, gamma=1.1,
46
- quantize=quantize, tileable=tileable, fade_px=12,
47
- )
48
- Path(tmp).unlink(missing_ok=True)
49
- preview = (height_map * 255).astype(np.uint8)
50
- msg = f"Depth map {px_w}×{px_h}px — bianco=alto, nero=basso"
51
- if invert:
52
- msg += " (invertita)"
53
- return preview, msg
54
  except Exception as e:
55
  return None, f"❌ {e}"
56
 
57
 
58
  def generate_stl(
59
  image, tile_w, tile_h_mode, tile_h_custom,
60
- relief_mm, base_mm, no_base, separate_blobs, threshold,
61
  invert, quantize_levels, tileable, blur, resolution,
62
  ):
63
  if image is None:
@@ -75,107 +56,48 @@ def generate_stl(
75
  else:
76
  tile_h = tile_h_custom
77
 
78
- stl_tmp = tempfile.NamedTemporaryFile(
79
- suffix=".stl", delete=False, prefix="tile_"
 
 
 
80
  )
 
81
 
82
- if no_base and separate_blobs:
83
- # ── Pipeline blob ──
84
- stl_bytes, n_blobs = blobs_to_stl(
85
- tmp_in,
86
- tile_w_mm=float(tile_w),
87
- tile_h_mm=float(tile_h),
88
- height_mm=float(relief_mm),
89
- threshold=int(threshold),
90
- )
91
- stl_tmp.write(stl_bytes)
92
- stl_tmp.close()
93
- Path(tmp_in).unlink(missing_ok=True)
94
-
95
- # Preview: contorni dei blob sull'immagine originale
96
- with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f2:
97
- tmp2 = f2.name
98
- Image.fromarray(image).save(tmp2)
99
- preview, n_found = blob_preview(tmp2, threshold=int(threshold))
100
- Path(tmp2).unlink(missing_ok=True)
101
-
102
- n_tri = (len(stl_bytes) - 84) // 50
103
- size_kb = len(stl_bytes) / 1024
104
- info = (
105
- f"✓ {n_blobs} cilindretti separati\n\n"
106
- f"Dimensioni tile: {tile_w:.0f} × {tile_h:.0f} mm\n"
107
- f"Altezza: {relief_mm:.1f} mm + base piatta\n"
108
- f"Soglia blob: {threshold}\n"
109
- f"Mesh: {n_tri:,} triangoli totali\n"
110
- f"File: {size_kb:.0f} KB\n\n"
111
- f"Slicer: layer 0.15 mm · infill 15% · no supports"
112
- )
113
- return preview, stl_tmp.name, info
114
-
115
- else:
116
- # ── Pipeline heightmap ──
117
- quantize = int(quantize_levels) if quantize_levels >= 2 else 0
118
- height_map, px_w, px_h = build_heightmap(
119
- tmp_in, max_px=int(resolution),
120
- invert=invert, blur=blur, gamma=1.1,
121
- quantize=quantize, tileable=tileable, fade_px=12,
122
- )
123
- Path(tmp_in).unlink(missing_ok=True)
124
 
125
- preview = (height_map * 255).astype(np.uint8)
126
- effective_base = 0.0 if no_base else float(base_mm)
 
 
 
 
 
127
 
128
- stl_bytes = heightmap_to_stl(
129
- height_map, px_w, px_h,
130
- tile_w_mm=float(tile_w),
131
- tile_h_mm=float(tile_h),
132
- relief_mm=float(relief_mm),
133
- base_mm=effective_base,
134
- )
135
- stl_tmp.write(stl_bytes)
136
- stl_tmp.close()
137
-
138
- n_tri = (len(stl_bytes) - 84) // 50
139
- size_kb = len(stl_bytes) / 1024
140
- base_info = "nessuna (guscio aperto)" if no_base else f"{effective_base:.1f} mm"
141
- info = (
142
- f"✓ Tile generata\n\n"
143
- f"Dimensioni: {tile_w:.0f} × {tile_h:.0f} mm\n"
144
- f"Rilievo: {relief_mm:.1f} mm\n"
145
- f"Base: {base_info}\n"
146
- f"Mesh: {px_w}×{px_h}px — {n_tri:,} triangoli\n"
147
- f"File: {size_kb:.0f} KB\n\n"
148
- f"Slicer: layer 0.15 mm · infill 15% · no supports"
149
- )
150
- return preview, stl_tmp.name, info
151
 
152
  except Exception as e:
153
  return None, None, f"❌ {e}"
154
 
155
 
156
- # ─────────────────────────────────────────────
157
- # UI CALLBACKS
158
- # ─────────────────────────────────────────────
159
-
160
- def toggle_custom_height(mode):
161
  return gr.update(visible=(mode == "Personalizzata"))
162
 
163
- def toggle_base_options(no_base):
164
- """Quando si spunta 'Senza base', mostra slider base (se non separato) e opzione blob."""
165
- return (
166
- gr.update(visible=not no_base), # base_mm slider
167
- gr.update(visible=no_base), # separate_blobs checkbox
168
- )
169
-
170
- def toggle_blob_options(no_base, separate_blobs):
171
- """Mostra il threshold solo se entrambe le opzioni sono attive."""
172
- show = no_base and separate_blobs
173
- return gr.update(visible=show)
174
-
175
-
176
- # ─────────────────────────────────────────────
177
- # UI
178
- # ─────────────────────────────────────────────
179
 
180
  CSS = """
181
  @import url('https://fonts.googleapis.com/css2?family=Bebas+Neue&family=DM+Mono:ital,wght@0,400;0,500;1,400&display=swap');
@@ -190,7 +112,7 @@ body { background: #0a0a0a !important; }
190
  .pg-num { font-family: 'DM Mono', monospace; font-size: 10px; letter-spacing: 0.2em; color: #333; margin-bottom: 6px; display: block; }
191
  .pg-logo { font-family: 'Bebas Neue', sans-serif; font-size: 56px; letter-spacing: 0.1em; color: #f2efe8; line-height: 1; display: block; }
192
  .pg-logo .accent { color: #d4a912; }
193
- .pg-sub { font-family: 'DM Mono', monospace; font-size: 9px; letter-spacing: 0.22em; color: #444; text-transform: uppercase; margin-top: 8px; display: block; }
194
  .pg-rule { width: 100%; height: 1px; background: #1e1e1e; margin-top: 20px; }
195
  .gradio-container h2 { font-family: 'DM Mono', monospace !important; font-size: 9px !important; letter-spacing: 0.2em !important; color: #d4a912 !important; text-transform: uppercase !important; border-bottom: 1px solid #1e1e1e !important; padding-bottom: 6px !important; margin-top: 20px !important; font-weight: 400 !important; }
196
  button.primary { background: #d4a912 !important; color: #0a0a0a !important; border: none !important; border-radius: 0 !important; font-family: 'DM Mono', monospace !important; text-transform: uppercase !important; letter-spacing: 0.1em !important; font-size: 0.7rem !important; font-weight: 500 !important; }
@@ -200,7 +122,6 @@ label span { font-family: 'DM Mono', monospace !important; font-size: 10px !impo
200
  input[type=range] { accent-color: #d4a912 !important; }
201
  input[type=checkbox] { accent-color: #d4a912 !important; }
202
  textarea { background: #0d0d0d !important; border: 1px solid #1e1e1e !important; color: #888 !important; font-family: 'DM Mono', monospace !important; font-size: 12px !important; border-radius: 0 !important; }
203
- .blob-box { border: 1px solid #2a1a00; background: #0f0900; border-radius: 0; padding: 10px 12px; margin-top: 4px; }
204
  .guide { font-family: 'DM Mono', monospace; font-size: 11px; line-height: 1.9; color: #555; margin-top: 16px; }
205
  .guide strong { color: #888; font-weight: 500; }
206
  """
@@ -218,10 +139,8 @@ GUIDE_HTML = """
218
  <div class="guide">
219
  <strong>bianco = alto, nero = basso</strong> — controlla la depth map prima di generare.<br><br>
220
  <strong>Quantize</strong> — livelli netti invece di gradiente continuo.<br>
221
- <strong>Tileable</strong> bordi sfumati per affiancamento senza giunti.<br>
222
- <strong>Senza base</strong> — guscio aperto (utile su supporto esterno).<br>
223
- <strong>Separa i blob</strong> — ogni forma bianca diventa un cilindretto<br>
224
- &nbsp;&nbsp;fisicamente separato. Ideal per pois, lettere, pattern binari.<br><br>
225
  <strong>Slicer:</strong> layer 0.15 mm · infill 15% · no supports · ironing top
226
  </div>
227
  """
@@ -245,23 +164,9 @@ with gr.Blocks(css=CSS, title="Pattern Ground") as demo:
245
  label="Altezza personalizzata (mm)", visible=False)
246
 
247
  gr.Markdown("## Rilievo")
248
- relief_mm = gr.Slider(1, 10, value=4, step=0.5, label="Altezza rilievo (mm)")
249
-
250
- gr.Markdown("## Base")
251
- no_base = gr.Checkbox(label="Senza base (guscio aperto)", value=False)
252
- base_mm = gr.Slider(0.5, 5, value=2, step=0.5, label="Spessore base (mm)")
253
-
254
- # Opzioni blob — visibili solo con "Senza base" attivo
255
- with gr.Group(visible=False, elem_classes=["blob-box"]) as blob_group:
256
- separate_blobs = gr.Checkbox(
257
- label="Separa i blob bianchi (ogni forma = cilindretto separato)",
258
- value=False,
259
- )
260
- threshold = gr.Slider(
261
- 0, 255, value=127, step=1,
262
- label="Soglia binaria (0–255, default 127)",
263
- visible=False,
264
- )
265
 
266
  gr.Markdown("## Processing")
267
  quantize = gr.Slider(0, 12, value=0, step=1,
@@ -286,29 +191,15 @@ with gr.Blocks(css=CSS, title="Pattern Ground") as demo:
286
  gr.Markdown("## Download")
287
  stl_out = gr.File(label="STL file")
288
  gr.Markdown("## Info")
289
- info_out = gr.Textbox(label="", lines=8, interactive=False)
290
  gr.HTML(GUIDE_HTML)
291
 
292
- # ── Events ──
293
- tile_h_mode.change(toggle_custom_height, tile_h_mode, tile_h_custom)
294
-
295
- def on_no_base(val):
296
- base_vis, blob_vis = toggle_base_options(val)
297
- return base_vis, blob_vis
298
-
299
- no_base.change(on_no_base, no_base, [base_mm, blob_group])
300
-
301
- def on_blob_toggle(no_base_val, sep_val):
302
- return toggle_blob_options(no_base_val, sep_val)
303
-
304
- separate_blobs.change(on_blob_toggle, [no_base, separate_blobs], threshold)
305
 
306
- preview_inputs = [image_in, invert, quantize, tileable, blur,
307
- no_base, separate_blobs, threshold]
308
  gen_inputs = [
309
  image_in, tile_w, tile_h_mode, tile_h_custom,
310
- relief_mm, base_mm, no_base, separate_blobs, threshold,
311
- invert, quantize, tileable, blur, resolution,
312
  ]
313
 
314
  preview_btn.click(preview_depthmap, preview_inputs, [depth_out, info_out])
 
11
  import numpy as np
12
  from PIL import Image
13
 
14
+ from relief_workshop import build_heightmap, heightmap_to_stl
 
 
 
15
 
16
 
17
+ def preview_depthmap(image, invert, quantize_levels, tileable, blur):
 
 
 
 
 
18
  if image is None:
19
  return None, "⚠️ Carica un'immagine."
20
  try:
21
  with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:
22
  tmp = f.name
23
  Image.fromarray(image).save(tmp)
24
+ quantize = int(quantize_levels) if quantize_levels >= 2 else 0
25
+ height_map, px_w, px_h = build_heightmap(
26
+ tmp, max_px=300, invert=invert, blur=blur, gamma=1.1,
27
+ quantize=quantize, tileable=tileable, fade_px=12,
28
+ )
29
+ Path(tmp).unlink(missing_ok=True)
30
+ preview = (height_map * 255).astype(np.uint8)
31
+ msg = f"Depth map {px_w}×{px_h}px bianco=alto, nero=basso"
32
+ if invert:
33
+ msg += " (invertita)"
34
+ return preview, msg
 
 
 
 
 
 
 
 
 
 
 
35
  except Exception as e:
36
  return None, f"❌ {e}"
37
 
38
 
39
  def generate_stl(
40
  image, tile_w, tile_h_mode, tile_h_custom,
41
+ relief_mm, base_mm,
42
  invert, quantize_levels, tileable, blur, resolution,
43
  ):
44
  if image is None:
 
56
  else:
57
  tile_h = tile_h_custom
58
 
59
+ quantize = int(quantize_levels) if quantize_levels >= 2 else 0
60
+ height_map, px_w, px_h = build_heightmap(
61
+ tmp_in, max_px=int(resolution),
62
+ invert=invert, blur=blur, gamma=1.1,
63
+ quantize=quantize, tileable=tileable, fade_px=12,
64
  )
65
+ Path(tmp_in).unlink(missing_ok=True)
66
 
67
+ preview = (height_map * 255).astype(np.uint8)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
+ stl_bytes = heightmap_to_stl(
70
+ height_map, px_w, px_h,
71
+ tile_w_mm=float(tile_w),
72
+ tile_h_mm=float(tile_h),
73
+ relief_mm=float(relief_mm),
74
+ base_mm=float(base_mm),
75
+ )
76
 
77
+ stl_tmp = tempfile.NamedTemporaryFile(suffix=".stl", delete=False, prefix="tile_")
78
+ stl_tmp.write(stl_bytes)
79
+ stl_tmp.close()
80
+
81
+ n_tri = (len(stl_bytes) - 84) // 50
82
+ size_kb = len(stl_bytes) / 1024
83
+ info = (
84
+ f"✓ Tile generata\n\n"
85
+ f"Dimensioni: {tile_w:.0f} × {tile_h:.0f} mm\n"
86
+ f"Rilievo: {relief_mm:.1f} mm\n"
87
+ f"Base: {base_mm:.1f} mm\n"
88
+ f"Mesh: {px_w}×{px_h}px {n_tri:,} triangoli\n"
89
+ f"File: {size_kb:.0f} KB\n\n"
90
+ f"Slicer: layer 0.15 mm · infill 15% · no supports"
91
+ )
92
+ return preview, stl_tmp.name, info
 
 
 
 
 
 
 
93
 
94
  except Exception as e:
95
  return None, None, f"❌ {e}"
96
 
97
 
98
+ def toggle_custom(mode):
 
 
 
 
99
  return gr.update(visible=(mode == "Personalizzata"))
100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
 
102
  CSS = """
103
  @import url('https://fonts.googleapis.com/css2?family=Bebas+Neue&family=DM+Mono:ital,wght@0,400;0,500;1,400&display=swap');
 
112
  .pg-num { font-family: 'DM Mono', monospace; font-size: 10px; letter-spacing: 0.2em; color: #333; margin-bottom: 6px; display: block; }
113
  .pg-logo { font-family: 'Bebas Neue', sans-serif; font-size: 56px; letter-spacing: 0.1em; color: #f2efe8; line-height: 1; display: block; }
114
  .pg-logo .accent { color: #d4a912; }
115
+ .pg-sub { font-family: 'DM Mono', monospace; font-size: 9px; letter-spacing: 0.22em; color: #f2efe8; text-transform: uppercase; margin-top: 8px; display: block; }
116
  .pg-rule { width: 100%; height: 1px; background: #1e1e1e; margin-top: 20px; }
117
  .gradio-container h2 { font-family: 'DM Mono', monospace !important; font-size: 9px !important; letter-spacing: 0.2em !important; color: #d4a912 !important; text-transform: uppercase !important; border-bottom: 1px solid #1e1e1e !important; padding-bottom: 6px !important; margin-top: 20px !important; font-weight: 400 !important; }
118
  button.primary { background: #d4a912 !important; color: #0a0a0a !important; border: none !important; border-radius: 0 !important; font-family: 'DM Mono', monospace !important; text-transform: uppercase !important; letter-spacing: 0.1em !important; font-size: 0.7rem !important; font-weight: 500 !important; }
 
122
  input[type=range] { accent-color: #d4a912 !important; }
123
  input[type=checkbox] { accent-color: #d4a912 !important; }
124
  textarea { background: #0d0d0d !important; border: 1px solid #1e1e1e !important; color: #888 !important; font-family: 'DM Mono', monospace !important; font-size: 12px !important; border-radius: 0 !important; }
 
125
  .guide { font-family: 'DM Mono', monospace; font-size: 11px; line-height: 1.9; color: #555; margin-top: 16px; }
126
  .guide strong { color: #888; font-weight: 500; }
127
  """
 
139
  <div class="guide">
140
  <strong>bianco = alto, nero = basso</strong> — controlla la depth map prima di generare.<br><br>
141
  <strong>Quantize</strong> — livelli netti invece di gradiente continuo.<br>
142
+ Ottimo per pattern urbani: sanpietrini, griglia, muratura.<br><br>
143
+ <strong>Tileable</strong> — bordi sfumati per affiancamento senza giunti.<br><br>
 
 
144
  <strong>Slicer:</strong> layer 0.15 mm · infill 15% · no supports · ironing top
145
  </div>
146
  """
 
164
  label="Altezza personalizzata (mm)", visible=False)
165
 
166
  gr.Markdown("## Rilievo")
167
+ with gr.Row():
168
+ relief_mm = gr.Slider(1, 10, value=4, step=0.5, label="Altezza rilievo (mm)")
169
+ base_mm = gr.Slider(0.5, 5, value=2, step=0.5, label="Spessore base (mm)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
 
171
  gr.Markdown("## Processing")
172
  quantize = gr.Slider(0, 12, value=0, step=1,
 
191
  gr.Markdown("## Download")
192
  stl_out = gr.File(label="STL file")
193
  gr.Markdown("## Info")
194
+ info_out = gr.Textbox(label="", lines=7, interactive=False)
195
  gr.HTML(GUIDE_HTML)
196
 
197
+ tile_h_mode.change(toggle_custom, tile_h_mode, tile_h_custom)
 
 
 
 
 
 
 
 
 
 
 
 
198
 
199
+ preview_inputs = [image_in, invert, quantize, tileable, blur]
 
200
  gen_inputs = [
201
  image_in, tile_w, tile_h_mode, tile_h_custom,
202
+ relief_mm, base_mm, invert, quantize, tileable, blur, resolution,
 
203
  ]
204
 
205
  preview_btn.click(preview_depthmap, preview_inputs, [depth_out, info_out])