Spaces:
Running
Running
Upload app.py
Browse files10 unmodified lines1112131415161714151620212223241725181920212223323334353637383940414243444546474849505152532425262728293031323334353637383940604142434411 unmodified lines565758787959606162636465668283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221236768125126697071727374757612812913013113213313413513613713813914014114214314414514614714814915077787980818283848586878889909192939495969715615715815916098991001631641651661671681691701711721731741751761771781011021038 unmodified lines1121131141931151161171183 unmodified lines12212312420312512612711 unmodified lines13914014122122222322414214314414514617 unmodified lines16416516624824925025125225325425525625725825926026126226326416716816917017117218 unmodified lines19119219328919419519629229319729429529629729829930030130230330419830630719920020131031120220320420510 unmodified linesimport numpy as npfrom PIL import Image
from relief_workshop import ( build_heightmap, heightmap_to_stl, blobs_to_stl, blob_preview,)from relief_workshop import build_heightmap, heightmap_to_stl
# ─────────────────────────────────────────────# CORE# ─────────────────────────────────────────────
def preview_depthmap(image, invert, quantize_levels, tileable, blur,def preview_depthmap(image, invert, quantize_levels, tileable, blur): no_base, separate_blobs, threshold): if image is None: return None, "⚠️ Carica un'immagine." try: with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f: tmp = f.name Image.fromarray(image).save(tmp)
if no_base and separate_blobs: # Blob preview: mostra i contorni trovati prev, n = blob_preview(tmp, threshold=int(threshold)) Path(tmp).unlink(missing_ok=True) msg = f"{n} blob trovati — ognuno diventerà un cilindretto separato" if n == 0: msg = "Nessun blob trovato. Prova ad abbassare la soglia o usare un'immagine con forme bianche su nero." return prev, msg else: # Heightmap preview normale quantize = int(quantize_levels) if quantize_levels >= 2 else 0 height_map, px_w, px_h = build_heightmap( tmp, max_px=300, invert=invert, blur=blur, gamma=1.1, quantize=quantize, tileable=tileable, fade_px=12, ) Path(tmp).unlink(missing_ok=True) preview = (height_map * 255).astype(np.uint8) msg = f"Depth map {px_w}×{px_h}px — bianco=alto, nero=basso" if invert: msg += " (invertita)" return preview, msg quantize = int(quantize_levels) if quantize_levels >= 2 else 0 height_map, px_w, px_h = build_heightmap( tmp, max_px=300, invert=invert, blur=blur, gamma=1.1, quantize=quantize, tileable=tileable, fade_px=12, ) Path(tmp).unlink(missing_ok=True) preview = (height_map * 255).astype(np.uint8) msg = f"Depth map {px_w}×{px_h}px — bianco=alto, nero=basso" if invert: msg += " (invertita)" return preview, msg except Exception as e: return None, f"❌ {e}"
def generate_stl( image, tile_w, tile_h_mode, tile_h_custom, relief_mm, base_mm, no_base, separate_blobs, threshold, relief_mm, base_mm, invert, quantize_levels, tileable, blur, resolution,): if image is None:11 unmodified lines else: tile_h = tile_h_custom
stl_tmp = tempfile.NamedTemporaryFile( suffix=".stl", delete=False, prefix="tile_" quantize = int(quantize_levels) if quantize_levels >= 2 else 0 height_map, px_w, px_h = build_heightmap( tmp_in, max_px=int(resolution), invert=invert, blur=blur, gamma=1.1, quantize=quantize, tileable=tileable, fade_px=12, ) Path(tmp_in).unlink(missing_ok=True)
if no_base and separate_blobs: # ── Pipeline blob ── stl_bytes, n_blobs = blobs_to_stl( tmp_in, tile_w_mm=float(tile_w), tile_h_mm=float(tile_h), height_mm=float(relief_mm), threshold=int(threshold), ) stl_tmp.write(stl_bytes) stl_tmp.close() Path(tmp_in).unlink(missing_ok=True)
# Preview: contorni dei blob sull'immagine originale with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f2: tmp2 = f2.name Image.fromarray(image).save(tmp2) preview, n_found = blob_preview(tmp2, threshold=int(threshold)) Path(tmp2).unlink(missing_ok=True)
n_tri = (len(stl_bytes) - 84) // 50 size_kb = len(stl_bytes) / 1024 info = ( f"✓ {n_blobs} cilindretti separati\n\n" f"Dimensioni tile: {tile_w:.0f} × {tile_h:.0f} mm\n" f"Altezza: {relief_mm:.1f} mm + base piatta\n" f"Soglia blob: {threshold}\n" f"Mesh: {n_tri:,} triangoli totali\n" f"File: {size_kb:.0f} KB\n\n" f"Slicer: layer 0.15 mm · infill 15% · no supports" ) return preview, stl_tmp.name, info
else: # ── Pipeline heightmap ── quantize = int(quantize_levels) if quantize_levels >= 2 else 0 height_map, px_w, px_h = build_heightmap( tmp_in, max_px=int(resolution), invert=invert, blur=blur, gamma=1.1, quantize=quantize, tileable=tileable, fade_px=12, ) Path(tmp_in).unlink(missing_ok=True) preview = (height_map * 255).astype(np.uint8)
preview = (height_map * 255).astype(np.uint8) effective_base = 0.0 if no_base else float(base_mm) stl_bytes = heightmap_to_stl( height_map, px_w, px_h, tile_w_mm=float(tile_w), tile_h_mm=float(tile_h), relief_mm=float(relief_mm), base_mm=float(base_mm), )
stl_bytes = heightmap_to_stl( height_map, px_w, px_h, tile_w_mm=float(tile_w), tile_h_mm=float(tile_h), relief_mm=float(relief_mm), base_mm=effective_base, ) stl_tmp.write(stl_bytes) stl_tmp.close()
n_tri = (len(stl_bytes) - 84) // 50 size_kb = len(stl_bytes) / 1024 base_info = "nessuna (guscio aperto)" if no_base else f"{effective_base:.1f} mm" info = ( f"✓ Tile generata\n\n" f"Dimensioni: {tile_w:.0f} × {tile_h:.0f} mm\n" f"Rilievo: {relief_mm:.1f} mm\n" f"Base: {base_info}\n" f"Mesh: {px_w}×{px_h}px — {n_tri:,} triangoli\n" f"File: {size_kb:.0f} KB\n\n" f"Slicer: layer 0.15 mm · infill 15% · no supports" ) return preview, stl_tmp.name, info stl_tmp = tempfile.NamedTemporaryFile(suffix=".stl", delete=False, prefix="tile_") stl_tmp.write(stl_bytes) stl_tmp.close()
n_tri = (len(stl_bytes) - 84) // 50 size_kb = len(stl_bytes) / 1024 info = ( f"✓ Tile generata\n\n" f"Dimensioni: {tile_w:.0f} × {tile_h:.0f} mm\n" f"Rilievo: {relief_mm:.1f} mm\n" f"Base: {base_mm:.1f} mm\n" f"Mesh: {px_w}×{px_h}px — {n_tri:,} triangoli\n" f"File: {size_kb:.0f} KB\n\n" f"Slicer: layer 0.15 mm · infill 15% · no supports" ) return preview, stl_tmp.name, info
except Exception as e: return None, None, f"❌ {e}"
# ─────────────────────────────────────────────# UI CALLBACKS# ─────────────────────────────────────────────
def toggle_custom_height(mode):def toggle_custom(mode): return gr.update(visible=(mode == "Personalizzata"))
def toggle_base_options(no_base): """Quando si spunta 'Senza base', mostra slider base (se non separato) e opzione blob.""" return ( gr.update(visible=not no_base), # base_mm slider gr.update(visible=no_base), # separate_blobs checkbox )
def toggle_blob_options(no_base, separate_blobs): """Mostra il threshold solo se entrambe le opzioni sono attive.""" show = no_base and separate_blobs return gr.update(visible=show)
# ─────────────────────────────────────────────# UI# ─────────────────────────────────────────────
CSS = """@import url('https://fonts.googleapis.com/css2?family=Bebas+Neue&family=DM+Mono:ital,wght@0,400;0,500;1,400&display=swap');8 unmodified lines.pg-num { font-family: 'DM Mono', monospace; font-size: 10px; letter-spacing: 0.2em; color: #333; margin-bottom: 6px; display: block; }.pg-logo { font-family: 'Bebas Neue', sans-serif; font-size: 56px; letter-spacing: 0.1em; color: #f2efe8; line-height: 1; display: block; }.pg-logo .accent { color: #d4a912; }.pg-sub { font-family: 'DM Mono', monospace; font-size: 9px; letter-spacing: 0.22em; color: #444; text-transform: uppercase; margin-top: 8px; display: block; }.pg-sub { font-family: 'DM Mono', monospace; font-size: 9px; letter-spacing: 0.22em; color: #f2efe8; text-transform: uppercase; margin-top: 8px; display: block; }.pg-rule { width: 100%; height: 1px; background: #1e1e1e; margin-top: 20px; }.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; }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; }3 unmodified linesinput[type=range] { accent-color: #d4a912 !important; }input[type=checkbox] { accent-color: #d4a912 !important; }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; }.blob-box { border: 1px solid #2a1a00; background: #0f0900; border-radius: 0; padding: 10px 12px; margin-top: 4px; }.guide { font-family: 'DM Mono', monospace; font-size: 11px; line-height: 1.9; color: #555; margin-top: 16px; }.guide strong { color: #888; font-weight: 500; }"""11 unmodified lines<div class="guide"><strong>bianco = alto, nero = basso</strong> — controlla la depth map prima di generare.<br><br><strong>Quantize</strong> — livelli netti invece di gradiente continuo.<br><strong>Tileable</strong> — bordi sfumati per affiancamento senza giunti.<br><strong>Senza base</strong> — guscio aperto (utile su supporto esterno).<br><strong>Separa i blob</strong> — ogni forma bianca diventa un cilindretto<br> fisicamente separato. Ideal per pois, lettere, pattern binari.<br><br>Ottimo per pattern urbani: sanpietrini, griglia, muratura.<br><br><strong>Tileable</strong> — bordi sfumati per affiancamento senza giunti.<br><br><strong>Slicer:</strong> layer 0.15 mm · infill 15% · no supports · ironing top</div>"""17 unmodified lines label="Altezza personalizzata (mm)", visible=False)
gr.Markdown("## Rilievo") relief_mm = gr.Slider(1, 10, value=4, step=0.5, label="Altezza rilievo (mm)")
gr.Markdown("## Base") no_base = gr.Checkbox(label="Senza base (guscio aperto)", value=False) base_mm = gr.Slider(0.5, 5, value=2, step=0.5, label="Spessore base (mm)")
# Opzioni blob — visibili solo con "Senza base" attivo with gr.Group(visible=False, elem_classes=["blob-box"]) as blob_group: separate_blobs = gr.Checkbox( label="Separa i blob bianchi (ogni forma = cilindretto separato)", value=False, ) threshold = gr.Slider( 0, 255, value=127, step=1, label="Soglia binaria (0–255, default 127)", visible=False, ) with gr.Row(): relief_mm = gr.Slider(1, 10, value=4, step=0.5, label="Altezza rilievo (mm)") base_mm = gr.Slider(0.5, 5, value=2, step=0.5, label="Spessore base (mm)")
gr.Markdown("## Processing") quantize = gr.Slider(0, 12, value=0, step=1,18 unmodified lines gr.Markdown("## Download") stl_out = gr.File(label="STL file") gr.Markdown("## Info") info_out = gr.Textbox(label="", lines=8, interactive=False) info_out = gr.Textbox(label="", lines=7, interactive=False) gr.HTML(GUIDE_HTML)
# ── Events ── tile_h_mode.change(toggle_custom_height, tile_h_mode, tile_h_custom) tile_h_mode.change(toggle_custom, tile_h_mode, tile_h_custom)
def on_no_base(val): base_vis, blob_vis = toggle_base_options(val) return base_vis, blob_vis
no_base.change(on_no_base, no_base, [base_mm, blob_group])
def on_blob_toggle(no_base_val, sep_val): return toggle_blob_options(no_base_val, sep_val)
separate_blobs.change(on_blob_toggle, [no_base, separate_blobs], threshold)
preview_inputs = [image_in, invert, quantize, tileable, blur, no_base, separate_blobs, threshold] preview_inputs = [image_in, invert, quantize, tileable, blur] gen_inputs = [ image_in, tile_w, tile_h_mode, tile_h_custom, relief_mm, base_mm, no_base, separate_blobs, threshold, invert, quantize, tileable, blur, resolution, relief_mm, base_mm, invert, quantize, tileable, blur, resolution, ]
preview_btn.click(preview_depthmap, preview_inputs, [depth_out, info_out])app.py+55-164