Spaces:
Running
Running
Upload app.py
Browse files10 unmodified lines111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626311 unmodified lines757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801818 unmodified lines1901911921931941951963 unmodified lines20020120220320420520611 unmodified lines21821922022122222322422522622717 unmodified lines24524624724824925025125225325425525625725825926026126226326426526626718 unmodified lines28628728828929029129229329429529629729829930030130230330430530630730830931031131231331410 unmodified linesimport numpy as npfrom PIL import Imagefrom relief_workshop import (build_heightmap, heightmap_to_stl,blobs_to_stl, blob_preview,)# ─────────────────────────────────────────────# CORE# ─────────────────────────────────────────────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.nameImage.fromarray(image).save(tmp)if no_base and separate_blobs:# Blob preview: mostra i contorni trovatiprev, 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, msgelse:# Heightmap preview normalequantize = int(quantize_levels) if quantize_levels >= 2 else 0height_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, msgexcept 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,invert, quantize_levels, tileable, blur, resolution,):if image is None:11 unmodified lineselse:tile_h = tile_h_customstl_tmp = tempfile.NamedTemporaryFile(suffix=".stl", delete=False, prefix="tile_")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 originalewith tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f2:tmp2 = f2.nameImage.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) // 50size_kb = len(stl_bytes) / 1024info = (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, infoelse:# ── Pipeline heightmap ──quantize = int(quantize_levels) if quantize_levels >= 2 else 0height_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)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=effective_base,)stl_tmp.write(stl_bytes)stl_tmp.close()n_tri = (len(stl_bytes) - 84) // 50size_kb = len(stl_bytes) / 1024base_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, infoexcept Exception as e:return None, None, f"❌ {e}"# ─────────────────────────────────────────────# UI CALLBACKS# ─────────────────────────────────────────────def toggle_custom_height(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 slidergr.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_blobsreturn 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-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><strong>Slicer:</strong> layer 0.15 mm · infill 15% · no supports · ironing top</div>"""17 unmodified lineslabel="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" attivowith 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,)gr.Markdown("## Processing")quantize = gr.Slider(0, 12, value=0, step=1,18 unmodified linesgr.Markdown("## Download")stl_out = gr.File(label="STL file")gr.Markdown("## Info")info_out = gr.Textbox(label="", lines=8, interactive=False)gr.HTML(GUIDE_HTML)# ── Events ──tile_h_mode.change(toggle_custom_height, tile_h_mode, tile_h_custom)def on_no_base(val):base_vis, blob_vis = toggle_base_options(val)return base_vis, blob_visno_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]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,]preview_btn.click(preview_depthmap, preview_inputs, [depth_out, info_out])10 unmodified lines1112131415161718192021222324252627282930313233343536373839404142434411 unmodified lines56575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021038 unmodified lines1121131141151161171183 unmodified lines12212312412512612711 unmodified lines13914014114214314414514617 unmodified lines16416516616716816917017117218 unmodified lines19119219319419519619719819920020120220320420510 unmodified linesimport numpy as npfrom PIL import Imagefrom relief_workshop import build_heightmap, heightmap_to_stldef preview_depthmap(image, invert, quantize_levels, tileable, blur):if image is None:return None, "⚠️ Carica un'immagine."try:with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:tmp = f.nameImage.fromarray(image).save(tmp)quantize = int(quantize_levels) if quantize_levels >= 2 else 0height_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, msgexcept Exception as e:return None, f"❌ {e}"def generate_stl(image, tile_w, tile_h_mode, tile_h_custom,relief_mm, base_mm,invert, quantize_levels, tileable, blur, resolution,):if image is None:11 unmodified lineselse:tile_h = tile_h_customquantize = int(quantize_levels) if quantize_levels >= 2 else 0height_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)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_tmp = tempfile.NamedTemporaryFile(suffix=".stl", delete=False, prefix="tile_")stl_tmp.write(stl_bytes)stl_tmp.close()n_tri = (len(stl_bytes) - 84) // 50size_kb = len(stl_bytes) / 1024info = (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, infoexcept Exception as e:return None, None, f"❌ {e}"def toggle_custom(mode):return gr.update(visible=(mode == "Personalizzata"))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: #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; }.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>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 lineslabel="Altezza personalizzata (mm)", visible=False)gr.Markdown("## Rilievo")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 linesgr.Markdown("## Download")stl_out = gr.File(label="STL file")gr.Markdown("## Info")info_out = gr.Textbox(label="", lines=7, interactive=False)gr.HTML(GUIDE_HTML)tile_h_mode.change(toggle_custom, tile_h_mode, tile_h_custom)preview_inputs = [image_in, invert, quantize, tileable, blur]gen_inputs = [image_in, tile_w, tile_h_mode, tile_h_custom,relief_mm, base_mm, invert, quantize, tileable, blur, resolution,]preview_btn.click(preview_depthmap, preview_inputs, [depth_out, info_out])
app.py+55-164