Blair Johnson commited on
Commit
5874f5d
·
1 Parent(s): 5885cbc

Add depth curves editor workflow

Browse files
Files changed (2) hide show
  1. README.md +40 -1
  2. app.py +931 -115
README.md CHANGED
@@ -9,4 +9,43 @@ license: mit
9
  short_description: Generate a 3D relief STL from an image
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  short_description: Generate a 3D relief STL from an image
10
  ---
11
 
12
+ # Image to 3D Relief
13
+
14
+ Generate an STL relief from an image using Depth Anything V2, then tune the interpreted 2D depth map before export.
15
+
16
+ ## Workflow
17
+
18
+ 1. Upload an image and click **Estimate Depth Map**.
19
+ 2. Use the **Depth histogram + curves editor** to remap the model's estimated depth values:
20
+ - drag points to reshape the curve,
21
+ - click to add a point,
22
+ - double-click or select + Delete to remove a non-endpoint,
23
+ - use presets for midtone contrast, foreground emphasis, and background compression.
24
+ 3. Review the **Adjusted depth used for STL** preview.
25
+ 4. Tune STL parameters and click **Generate STL from Adjusted Depth**.
26
+
27
+ HEIC/HEIF uploads are decoded server-side with `pillow-heif`. If a browser cannot preview HEIC directly, the file upload path should still work.
28
+
29
+ ## Resolution controls
30
+
31
+ The app defaults to a conservative `1,500,000` processing-pixel limit for Hugging Face CPU runners. Local users can raise this in the UI with **Max processing pixels**.
32
+
33
+ Environment variables are also available:
34
+
35
+ - `DEFAULT_MAX_RESOLUTION` — default value shown in the UI.
36
+ - `MAX_RESOLUTION_LIMIT` — upper clamp for the UI value.
37
+
38
+ Example:
39
+
40
+ ```bash
41
+ DEFAULT_MAX_RESOLUTION=4000000 MAX_RESOLUTION_LIMIT=30000000 python app.py
42
+ ```
43
+
44
+ ## Local run
45
+
46
+ ```bash
47
+ pip install -r requirements.txt
48
+ python app.py
49
+ ```
50
+
51
+ Once the feature is verified end-to-end, pin the package versions in `requirements.txt` for reproducible Hugging Face/Docker deployments.
app.py CHANGED
@@ -1,134 +1,781 @@
1
  import gradio as gr
2
- import torch
3
- import numpy as np
4
- import cv2
5
- from PIL import Image
6
- from transformers import AutoProcessor, AutoModelForDepthEstimation
7
  import tempfile
8
- from stl import mesh
 
 
 
 
 
9
  from sklearn.decomposition import PCA
10
- import pillow_heif
11
- pillow_heif.register_heif_opener()
 
 
 
12
 
13
- MAX_RESOLUTION = 1.5e6
 
 
 
 
 
 
 
 
 
 
 
14
  MODEL_ID = "depth-anything/Depth-Anything-V2-Large-hf"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  device = "cuda" if torch.cuda.is_available() else "cpu"
16
  processor = AutoProcessor.from_pretrained(MODEL_ID, use_fast=True)
17
  model = AutoModelForDepthEstimation.from_pretrained(MODEL_ID).to(device)
18
- print("Model loaded successfully.")
 
19
 
20
- def create_3d_model(
21
- input_filepath: str,
22
- texture_strength: float,
23
- max_z: float,
24
- min_z: float,
25
- x_length: float,
26
- do_pca_correction: bool,
27
- depth_map_smoothing: int,
28
- texture_smoothing: int,
29
- close_body: int
30
- ):
31
- if input_filepath is None: raise gr.Error("Please upload an image.")
32
- if max_z <= min_z: raise gr.Error("Max Z-height must be greater than Min Z-height.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
  try:
35
- image_pil = Image.open(input_filepath)
36
- input_image = np.array(image_pil.convert("RGB"))
37
- except Exception as e:
38
- raise gr.Error(f"Could not open image file. Error: {e}")
39
-
40
- # resize large images
41
- h, w, _ = input_image.shape
42
- if h * w > MAX_RESOLUTION:
43
- gr.Info("Image is large, downsampling to improve performance...")
44
- ratio = (MAX_RESOLUTION / (h * w)) ** 0.5
45
- new_w, new_h = int(w * ratio), int(h * ratio)
46
- input_image = cv2.resize(input_image, (new_w, new_h), interpolation=cv2.INTER_AREA)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
 
 
48
  image = Image.fromarray(input_image).convert("RGB")
49
  with torch.no_grad():
50
  inputs = processor(images=image, return_tensors="pt").to(device)
51
  outputs = model(**inputs)
52
  predicted_depth = outputs.predicted_depth
53
  depth = torch.nn.functional.interpolate(
54
- predicted_depth.unsqueeze(1), size=(image.height, image.width),
55
- mode="bicubic", align_corners=False,
 
 
56
  ).squeeze().cpu().numpy()
57
- depth_normalized = (depth - depth.min()) / (depth.max() - depth.min())
58
-
59
- # smoothing base depthmap
60
- if depth_map_smoothing > 1:
61
- ksize = int(depth_map_smoothing)
62
- if ksize % 2 == 0: ksize += 1
63
- depth_normalized = cv2.GaussianBlur(depth_normalized, (ksize, ksize), 0)
64
-
65
- gray_image = cv2.cvtColor(input_image, cv2.COLOR_RGB2GRAY)
66
- brightness_normalized = gray_image.astype(float) / 255.0
67
-
68
- # smoothing brightness
69
- if texture_smoothing > 1:
70
- ksize = int(texture_smoothing)
71
- if ksize % 2 == 0: ksize += 1
72
- brightness_normalized = cv2.GaussianBlur(brightness_normalized, (ksize, ksize), 0)
73
-
74
- if brightness_normalized.shape != depth_normalized.shape:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  brightness_normalized = cv2.resize(
76
- brightness_normalized, (depth_normalized.shape[1], depth_normalized.shape[0]),
77
- interpolation=cv2.INTER_LINEAR
 
78
  )
79
 
80
- combined_map = depth_normalized + (brightness_normalized * texture_strength)
81
- c_min, c_max = combined_map.min(), combined_map.max()
82
- if c_max > c_min:
83
- combined_map_rescaled = (combined_map - c_min) / (c_max - c_min)
84
- else:
85
- combined_map_rescaled = np.zeros_like(combined_map)
86
 
87
- z_data = min_z + combined_map_rescaled * (max_z - min_z)
88
 
89
- # Planar correction with PCA
90
- if do_pca_correction:
91
- height, width = z_data.shape
92
- y_length = x_length * (height / width)
93
- x_coords_1d, y_coords_1d = np.linspace(0, x_length, width), np.linspace(y_length, 0, height)
94
- x_grid, y_grid = np.meshgrid(x_coords_1d, y_coords_1d)
95
- points = np.stack([x_grid.flatten(), y_grid.flatten(), z_data.flatten()], axis=1)
96
- n_points, n_samples = points.shape[0], min(points.shape[0], 50000)
97
- sample_indices = np.random.choice(n_points, n_samples, replace=False)
98
- pca = PCA(n_components=3)
99
- pca.fit(points[sample_indices])
100
- normal = pca.components_[2]
101
- if normal[2] < 0:
102
- normal *= -1
103
- p0 = pca.mean_
104
- z_plane = p0[2] - (normal[0] * (x_grid - p0[0]) + normal[1] * (y_grid - p0[1])) / normal[2]
105
- corrected_z = z_data - z_plane
106
- cz_min, cz_max = corrected_z.min(), corrected_z.max()
107
- if cz_max > cz_min:
108
- z_data = min_z + (corrected_z - cz_min) / (cz_max - cz_min) * (max_z - min_z)
109
-
110
- # STL mesh
111
  height, width = z_data.shape
112
  y_length = x_length * (height / width)
113
- vertices = np.zeros((height, width, 3))
114
- x_coords, y_coords = np.linspace(0, x_length, width), np.linspace(y_length, 0, height)
115
- vertices[:, :, 0], vertices[:, :, 1], vertices[:, :, 2] = x_coords[np.newaxis, :], y_coords[:, np.newaxis], z_data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  faces = []
117
- for i in range(height-1):
118
- for j in range(width-1):
119
- v1,v2,v3,v4 = vertices[i,j], vertices[i+1,j], vertices[i+1,j+1], vertices[i,j+1]
120
  faces.extend([[v1, v2, v3], [v1, v3, v4]])
121
 
122
  if close_body:
123
- v_tl, v_tr, v_bl, v_br = vertices[0,0], vertices[0,width-1], vertices[height-1,0], vertices[height-1,width-1]
124
- b_tl,b_tr,b_bl,b_br = np.array([v_tl[0],v_tl[1],0]), np.array([v_tr[0],v_tr[1],0]), np.array([v_bl[0],v_bl[1],0]), np.array([v_br[0],v_br[1],0])
125
-
 
 
 
 
 
 
126
  faces.extend([
127
- [v_tl, b_tl, b_tr], [v_tl, b_tr, v_tr], #top wall
128
- [v_br, b_br, b_bl], [v_br, b_bl, v_bl], #bottom wall
129
- [v_bl, b_bl, b_tl], [v_bl, b_tl, v_tl], #left
130
- [v_tr, b_tr, b_br], [v_tr, b_br, v_br], #right
131
- [b_tl, b_br, b_bl], [b_tl, b_tr, b_br] #base
132
  ])
133
 
134
  surface = mesh.Mesh(np.zeros(len(faces), dtype=mesh.Mesh.dtype))
@@ -136,39 +783,208 @@ def create_3d_model(
136
 
137
  with tempfile.NamedTemporaryFile(delete=False, suffix=".stl") as tmpfile:
138
  surface.save(tmpfile.name)
139
- return tmpfile.name, tmpfile.name
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
 
141
- with gr.Blocks(theme='base') as demo:
142
  gr.Markdown("# Image to 3D Relief Generator")
 
 
 
 
 
143
  with gr.Row():
144
  with gr.Column(scale=1):
145
- input_image = gr.Image(type="filepath", label="Upload Image")
146
- gr.Markdown("### Model Parameters")
147
- texture_strength = gr.Slider(minimum=0.0, maximum=1.0, value=0.1, step=0.001, label="Brightness Texture Strength")
148
- depth_map_smoothing = gr.Slider(minimum=0, maximum=51, value=0, step=1, label="Depth Map Smoothing", info="Smooths the base geometry. 0 = none.")
149
- texture_smoothing = gr.Slider(minimum=0, maximum=51, value=0, step=1, label="Texture Smoothing", info="Smooths the brightness texture. 0 = none.")
150
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  x_length = gr.Number(value=100, label="X Length (units)")
152
  min_z = gr.Number(value=0.5, label="Min Z-Height (units)")
153
  max_z = gr.Number(value=5.0, label="Max Z-Height (units)")
154
  do_pca = gr.Checkbox(value=True, label="Enable PCA Planar Correction")
155
  close_body = gr.Checkbox(value=False, label="Close Body")
156
-
157
- generate_btn = gr.Button("Generate STL", variant="primary")
158
 
159
  with gr.Column(scale=1):
 
 
 
 
 
160
  gr.Markdown("### 3D Model Output")
161
  output_model = gr.Model3D(label="Generated 3D Model")
162
  output_file = gr.File(label="Download STL File")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
 
164
  generate_btn.click(
165
- fn=create_3d_model,
166
  inputs=[
167
- input_image, texture_strength, max_z, min_z, x_length, do_pca,
168
- depth_map_smoothing, texture_smoothing, close_body
 
 
 
 
 
 
 
 
 
169
  ],
170
- outputs=[output_model, output_file]
171
  )
172
 
173
  if __name__ == "__main__":
174
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import json
3
+ import os
 
 
 
4
  import tempfile
5
+ from typing import Any
6
+
7
+ import cv2
8
+ import numpy as np
9
+ import torch
10
+ from PIL import Image, ImageOps
11
  from sklearn.decomposition import PCA
12
+ from stl import mesh
13
+ from transformers import AutoModelForDepthEstimation, AutoProcessor
14
+
15
+ try:
16
+ import pillow_heif
17
 
18
+ pillow_heif.register_heif_opener()
19
+ HEIF_SUPPORT = True
20
+ except Exception as heif_error: # pragma: no cover - surfaced in UI if HEIC open fails
21
+ pillow_heif = None
22
+ HEIF_SUPPORT = False
23
+ HEIF_IMPORT_ERROR = heif_error
24
+ else:
25
+ HEIF_IMPORT_ERROR = None
26
+
27
+ DEFAULT_MAX_RESOLUTION = int(os.getenv("DEFAULT_MAX_RESOLUTION", "1500000"))
28
+ MAX_RESOLUTION_LIMIT = int(os.getenv("MAX_RESOLUTION_LIMIT", "20000000"))
29
+ MIN_RESOLUTION_LIMIT = 10_000
30
  MODEL_ID = "depth-anything/Depth-Anything-V2-Large-hf"
31
+ DEFAULT_CURVE_POINTS = [
32
+ {"x": 0.0, "y": 0.0},
33
+ {"x": 1.0, "y": 1.0},
34
+ ]
35
+ ACCEPTED_IMAGE_TYPES = [
36
+ ".png",
37
+ ".jpg",
38
+ ".jpeg",
39
+ ".webp",
40
+ ".bmp",
41
+ ".tif",
42
+ ".tiff",
43
+ ".heic",
44
+ ".heif",
45
+ ]
46
+
47
+
48
  device = "cuda" if torch.cuda.is_available() else "cpu"
49
  processor = AutoProcessor.from_pretrained(MODEL_ID, use_fast=True)
50
  model = AutoModelForDepthEstimation.from_pretrained(MODEL_ID).to(device)
51
+ model.eval()
52
+ print(f"Model loaded successfully on {device}.")
53
 
54
+
55
+ APP_CSS = """
56
+ #curve-points-json, #depth-histogram-json, #auto-preview-depth-btn {
57
+ display: none !important;
58
+ }
59
+ .depth-editor-card {
60
+ border: 1px solid var(--border-color-primary);
61
+ border-radius: 12px;
62
+ padding: 14px;
63
+ background: var(--background-fill-secondary);
64
+ }
65
+ .depth-editor-toolbar {
66
+ display: flex;
67
+ flex-wrap: wrap;
68
+ gap: 8px;
69
+ margin: 8px 0 10px;
70
+ }
71
+ .depth-editor-toolbar button {
72
+ border: 1px solid var(--border-color-primary);
73
+ border-radius: 8px;
74
+ padding: 6px 10px;
75
+ background: var(--button-secondary-background-fill);
76
+ color: var(--body-text-color);
77
+ cursor: pointer;
78
+ }
79
+ .depth-editor-toolbar button:hover {
80
+ background: var(--button-secondary-background-fill-hover);
81
+ }
82
+ #depth-curve-canvas {
83
+ width: 100%;
84
+ max-width: 720px;
85
+ height: 360px;
86
+ display: block;
87
+ touch-action: none;
88
+ border: 1px solid var(--border-color-primary);
89
+ border-radius: 8px;
90
+ background: #111827;
91
+ }
92
+ .depth-editor-help {
93
+ margin-top: 8px;
94
+ color: var(--body-text-color-subdued);
95
+ font-size: 0.9rem;
96
+ line-height: 1.35;
97
+ }
98
+ .depth-editor-readout {
99
+ min-height: 1.2rem;
100
+ margin-top: 6px;
101
+ color: var(--body-text-color-subdued);
102
+ font-family: var(--font-mono);
103
+ font-size: 0.85rem;
104
+ }
105
+ """
106
+
107
+
108
+ CURVE_EDITOR_HEAD = """
109
+ <script>
110
+ (() => {
111
+ const DEFAULT_POINTS = [{x: 0, y: 0}, {x: 1, y: 1}];
112
+ const PRESETS = {
113
+ linear: DEFAULT_POINTS,
114
+ subject: [{x: 0, y: 0}, {x: 0.22, y: 0.13}, {x: 0.50, y: 0.50}, {x: 0.78, y: 0.88}, {x: 1, y: 1}],
115
+ compressHigh: [{x: 0, y: 0}, {x: 0.45, y: 0.52}, {x: 0.75, y: 0.74}, {x: 1, y: 0.86}],
116
+ compressLow: [{x: 0, y: 0.14}, {x: 0.25, y: 0.26}, {x: 0.55, y: 0.50}, {x: 1, y: 1}],
117
+ foregroundPop: [{x: 0, y: 0}, {x: 0.35, y: 0.22}, {x: 0.62, y: 0.70}, {x: 1, y: 1}],
118
+ invert: [{x: 0, y: 1}, {x: 1, y: 0}]
119
+ };
120
+
121
+ const clamp = (v, lo = 0, hi = 1) => Math.max(lo, Math.min(hi, v));
122
+
123
+ function getTextarea(elemId) {
124
+ const root = document.getElementById(elemId);
125
+ if (!root) return null;
126
+ return root.querySelector('textarea, input');
127
+ }
128
+
129
+ function setTextareaValue(elemId, value) {
130
+ const el = getTextarea(elemId);
131
+ if (!el) return false;
132
+ const proto = el.tagName === 'TEXTAREA' ? window.HTMLTextAreaElement.prototype : window.HTMLInputElement.prototype;
133
+ const setter = Object.getOwnPropertyDescriptor(proto, 'value')?.set;
134
+ if (setter) setter.call(el, value);
135
+ else el.value = value;
136
+ el.dispatchEvent(new Event('input', { bubbles: true }));
137
+ el.dispatchEvent(new Event('change', { bubbles: true }));
138
+ return true;
139
+ }
140
+
141
+ function readTextareaValue(elemId) {
142
+ const el = getTextarea(elemId);
143
+ return el ? el.value : '';
144
+ }
145
+
146
+ function clickGradioButton(elemId) {
147
+ const root = document.getElementById(elemId);
148
+ const button = root?.querySelector('button');
149
+ if (button) button.click();
150
+ }
151
+
152
+ function normalizePoints(points) {
153
+ if (!Array.isArray(points)) return [...DEFAULT_POINTS];
154
+ const normalized = [];
155
+ for (const point of points) {
156
+ const x = typeof point?.x === 'number' ? point.x : Array.isArray(point) ? point[0] : NaN;
157
+ const y = typeof point?.y === 'number' ? point.y : Array.isArray(point) ? point[1] : NaN;
158
+ if (Number.isFinite(x) && Number.isFinite(y)) normalized.push({ x: clamp(x), y: clamp(y) });
159
+ }
160
+ if (!normalized.length) normalized.push(...DEFAULT_POINTS);
161
+ normalized.sort((a, b) => a.x - b.x);
162
+ normalized[0].x = 0;
163
+ normalized[normalized.length - 1].x = 1;
164
+ return normalized;
165
+ }
166
+
167
+ function parseJson(value, fallback) {
168
+ try { return JSON.parse(value); } catch (_) { return fallback; }
169
+ }
170
+
171
+ function initCurveEditor() {
172
+ const canvas = document.getElementById('depth-curve-canvas');
173
+ if (!canvas || canvas.dataset.depthCurveReady === '1') return;
174
+ canvas.dataset.depthCurveReady = '1';
175
+ const ctx = canvas.getContext('2d');
176
+ const readout = document.getElementById('depth-curve-readout');
177
+ const state = {
178
+ points: [...DEFAULT_POINTS],
179
+ histogram: [],
180
+ dragging: -1,
181
+ selected: -1,
182
+ lastCurveJson: '',
183
+ lastHistogramJson: '',
184
+ hasDepth: false,
185
+ refreshTimer: null
186
+ };
187
+
188
+ function resizeCanvas() {
189
+ const rect = canvas.getBoundingClientRect();
190
+ const dpr = window.devicePixelRatio || 1;
191
+ const width = Math.max(320, Math.round(rect.width * dpr));
192
+ const height = Math.max(240, Math.round(rect.height * dpr));
193
+ if (canvas.width !== width || canvas.height !== height) {
194
+ canvas.width = width;
195
+ canvas.height = height;
196
+ return true;
197
+ }
198
+ return false;
199
+ }
200
+
201
+ function graphRect() {
202
+ const pad = 34 * (window.devicePixelRatio || 1);
203
+ return { x: pad, y: pad * 0.65, w: canvas.width - pad * 1.45, h: canvas.height - pad * 1.5 };
204
+ }
205
+
206
+ function toCanvas(point) {
207
+ const r = graphRect();
208
+ return { x: r.x + point.x * r.w, y: r.y + (1 - point.y) * r.h };
209
+ }
210
+
211
+ function fromCanvas(x, y) {
212
+ const r = graphRect();
213
+ return { x: clamp((x - r.x) / r.w), y: clamp(1 - ((y - r.y) / r.h)) };
214
+ }
215
+
216
+ function drawGrid(r) {
217
+ ctx.save();
218
+ ctx.strokeStyle = 'rgba(255,255,255,0.13)';
219
+ ctx.lineWidth = 1;
220
+ for (let i = 0; i <= 4; i++) {
221
+ const x = r.x + (r.w * i / 4);
222
+ const y = r.y + (r.h * i / 4);
223
+ ctx.beginPath(); ctx.moveTo(x, r.y); ctx.lineTo(x, r.y + r.h); ctx.stroke();
224
+ ctx.beginPath(); ctx.moveTo(r.x, y); ctx.lineTo(r.x + r.w, y); ctx.stroke();
225
+ }
226
+ ctx.strokeStyle = 'rgba(255,255,255,0.5)';
227
+ ctx.strokeRect(r.x, r.y, r.w, r.h);
228
+ ctx.fillStyle = 'rgba(255,255,255,0.72)';
229
+ ctx.font = `${12 * (window.devicePixelRatio || 1)}px ui-monospace, SFMono-Regular, Menlo, monospace`;
230
+ ctx.fillText('input model depth →', r.x + r.w - 150 * (window.devicePixelRatio || 1), r.y + r.h + 24 * (window.devicePixelRatio || 1));
231
+ ctx.save();
232
+ ctx.translate(r.x - 24 * (window.devicePixelRatio || 1), r.y + 95 * (window.devicePixelRatio || 1));
233
+ ctx.rotate(-Math.PI / 2);
234
+ ctx.fillText('output height', 0, 0);
235
+ ctx.restore();
236
+ ctx.restore();
237
+ }
238
+
239
+ function drawHistogram(r) {
240
+ if (!state.histogram?.length) return;
241
+ const maxBin = Math.max(...state.histogram, 1);
242
+ const binW = r.w / state.histogram.length;
243
+ ctx.save();
244
+ ctx.fillStyle = 'rgba(96, 165, 250, 0.35)';
245
+ state.histogram.forEach((count, i) => {
246
+ const h = (count / maxBin) * r.h;
247
+ ctx.fillRect(r.x + i * binW, r.y + r.h - h, Math.max(1, binW), h);
248
+ });
249
+ ctx.restore();
250
+ }
251
+
252
+ function drawCurve() {
253
+ ctx.save();
254
+ ctx.strokeStyle = '#f8fafc';
255
+ ctx.lineWidth = 3 * (window.devicePixelRatio || 1);
256
+ ctx.beginPath();
257
+ state.points.forEach((point, index) => {
258
+ const c = toCanvas(point);
259
+ if (index === 0) ctx.moveTo(c.x, c.y);
260
+ else ctx.lineTo(c.x, c.y);
261
+ });
262
+ ctx.stroke();
263
+ state.points.forEach((point, index) => {
264
+ const c = toCanvas(point);
265
+ ctx.beginPath();
266
+ ctx.fillStyle = index === state.selected ? '#fb923c' : '#38bdf8';
267
+ ctx.strokeStyle = '#0f172a';
268
+ ctx.lineWidth = 2 * (window.devicePixelRatio || 1);
269
+ ctx.arc(c.x, c.y, 7 * (window.devicePixelRatio || 1), 0, Math.PI * 2);
270
+ ctx.fill();
271
+ ctx.stroke();
272
+ });
273
+ ctx.restore();
274
+ }
275
+
276
+ function draw() {
277
+ resizeCanvas();
278
+ const r = graphRect();
279
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
280
+ ctx.fillStyle = '#111827';
281
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
282
+ drawHistogram(r);
283
+ drawGrid(r);
284
+ drawCurve();
285
+ if (readout) {
286
+ const selected = state.selected >= 0 ? state.points[state.selected] : null;
287
+ readout.textContent = selected
288
+ ? `Selected point: input ${selected.x.toFixed(3)} → output ${selected.y.toFixed(3)}`
289
+ : `${state.points.length} curve points`;
290
+ }
291
+ }
292
+
293
+ function pushCurve(autoPreview = true) {
294
+ state.points = normalizePoints(state.points);
295
+ const payload = JSON.stringify(state.points.map(p => ({ x: +p.x.toFixed(5), y: +p.y.toFixed(5) })));
296
+ state.lastCurveJson = payload;
297
+ setTextareaValue('curve-points-json', payload);
298
+ draw();
299
+ if (autoPreview && state.hasDepth) {
300
+ window.clearTimeout(state.refreshTimer);
301
+ state.refreshTimer = window.setTimeout(() => clickGradioButton('auto-preview-depth-btn'), 350);
302
+ }
303
+ }
304
+
305
+ function nearestPoint(x, y) {
306
+ const threshold = 15 * (window.devicePixelRatio || 1);
307
+ let best = -1;
308
+ let bestDistance = Infinity;
309
+ state.points.forEach((point, index) => {
310
+ const c = toCanvas(point);
311
+ const distance = Math.hypot(c.x - x, c.y - y);
312
+ if (distance < threshold && distance < bestDistance) {
313
+ best = index;
314
+ bestDistance = distance;
315
+ }
316
+ });
317
+ return best;
318
+ }
319
+
320
+ function pointerPosition(event) {
321
+ const rect = canvas.getBoundingClientRect();
322
+ const dpr = window.devicePixelRatio || 1;
323
+ return { x: (event.clientX - rect.left) * dpr, y: (event.clientY - rect.top) * dpr };
324
+ }
325
+
326
+ canvas.addEventListener('pointerdown', (event) => {
327
+ event.preventDefault();
328
+ canvas.setPointerCapture(event.pointerId);
329
+ const pos = pointerPosition(event);
330
+ const nearest = nearestPoint(pos.x, pos.y);
331
+ if (nearest >= 0) {
332
+ state.dragging = nearest;
333
+ state.selected = nearest;
334
+ } else {
335
+ const point = fromCanvas(pos.x, pos.y);
336
+ state.points.push(point);
337
+ state.points.sort((a, b) => a.x - b.x);
338
+ state.selected = state.points.findIndex(p => p === point);
339
+ state.dragging = state.selected;
340
+ pushCurve(false);
341
+ }
342
+ draw();
343
+ });
344
+
345
+ canvas.addEventListener('pointermove', (event) => {
346
+ if (state.dragging < 0) return;
347
+ event.preventDefault();
348
+ const pos = pointerPosition(event);
349
+ const point = fromCanvas(pos.x, pos.y);
350
+ const i = state.dragging;
351
+ const left = i === 0 ? 0 : state.points[i - 1].x + 0.002;
352
+ const right = i === state.points.length - 1 ? 1 : state.points[i + 1].x - 0.002;
353
+ state.points[i].x = i === 0 ? 0 : i === state.points.length - 1 ? 1 : clamp(point.x, left, right);
354
+ state.points[i].y = point.y;
355
+ pushCurve(true);
356
+ });
357
+
358
+ canvas.addEventListener('pointerup', (event) => {
359
+ if (state.dragging >= 0) pushCurve(true);
360
+ state.dragging = -1;
361
+ try { canvas.releasePointerCapture(event.pointerId); } catch (_) {}
362
+ });
363
+
364
+ canvas.addEventListener('dblclick', (event) => {
365
+ event.preventDefault();
366
+ const pos = pointerPosition(event);
367
+ const nearest = nearestPoint(pos.x, pos.y);
368
+ if (nearest > 0 && nearest < state.points.length - 1) {
369
+ state.points.splice(nearest, 1);
370
+ state.selected = -1;
371
+ pushCurve(true);
372
+ }
373
+ });
374
+
375
+ window.addEventListener('keydown', (event) => {
376
+ if ((event.key === 'Delete' || event.key === 'Backspace') && state.selected > 0 && state.selected < state.points.length - 1) {
377
+ state.points.splice(state.selected, 1);
378
+ state.selected = -1;
379
+ pushCurve(true);
380
+ }
381
+ });
382
+
383
+ document.addEventListener('click', (event) => {
384
+ const button = event.target.closest('[data-depth-preset]');
385
+ if (!button) return;
386
+ const preset = button.dataset.depthPreset;
387
+ state.points = normalizePoints(PRESETS[preset] || DEFAULT_POINTS);
388
+ state.selected = -1;
389
+ pushCurve(true);
390
+ });
391
+
392
+ window.addEventListener('resize', draw);
393
+
394
+ window.setInterval(() => {
395
+ const curveJson = readTextareaValue('curve-points-json');
396
+ if (curveJson && curveJson !== state.lastCurveJson) {
397
+ state.points = normalizePoints(parseJson(curveJson, DEFAULT_POINTS));
398
+ state.lastCurveJson = curveJson;
399
+ draw();
400
+ }
401
+ const histogramJson = readTextareaValue('depth-histogram-json');
402
+ if (histogramJson && histogramJson !== state.lastHistogramJson) {
403
+ const parsed = parseJson(histogramJson, []);
404
+ state.histogram = Array.isArray(parsed) ? parsed : [];
405
+ state.hasDepth = state.histogram.some(count => Number(count) > 0);
406
+ state.lastHistogramJson = histogramJson;
407
+ draw();
408
+ }
409
+ }, 500);
410
+
411
+ pushCurve(false);
412
+ draw();
413
+ }
414
+
415
+ function startCurveEditorWatcher() {
416
+ initCurveEditor();
417
+ window.setInterval(initCurveEditor, 500);
418
+ }
419
+
420
+ if (document.readyState === 'loading') {
421
+ document.addEventListener('DOMContentLoaded', startCurveEditorWatcher);
422
+ } else {
423
+ startCurveEditorWatcher();
424
+ }
425
+ window.addEventListener('load', initCurveEditor);
426
+ })();
427
+ </script>
428
+ """
429
+
430
+
431
+ CURVE_EDITOR_HTML = """
432
+ <div class="depth-editor-card">
433
+ <strong>Depth histogram + curves editor</strong>
434
+ <div class="depth-editor-toolbar">
435
+ <button type="button" data-depth-preset="linear">Linear</button>
436
+ <button type="button" data-depth-preset="subject">Midtone contrast</button>
437
+ <button type="button" data-depth-preset="compressHigh">Compress high values</button>
438
+ <button type="button" data-depth-preset="compressLow">Compress low values</button>
439
+ <button type="button" data-depth-preset="foregroundPop">Foreground pop</button>
440
+ <button type="button" data-depth-preset="invert">Invert curve</button>
441
+ </div>
442
+ <canvas id="depth-curve-canvas" width="720" height="360"></canvas>
443
+ <div id="depth-curve-readout" class="depth-editor-readout"></div>
444
+ <div class="depth-editor-help">
445
+ Drag points to remap estimated model depth before STL export. Click the curve to add a point.
446
+ Double-click a non-endpoint, or select it and press Delete, to remove it. The blue histogram shows the current smoothed base-depth distribution.
447
+ </div>
448
+ </div>
449
+ """
450
+
451
+
452
+ def clamp(value: float, minimum: float, maximum: float) -> float:
453
+ return max(minimum, min(maximum, value))
454
+
455
+
456
+ def normalize_array(values: np.ndarray) -> np.ndarray:
457
+ values = values.astype(np.float32, copy=False)
458
+ v_min = float(np.nanmin(values))
459
+ v_max = float(np.nanmax(values))
460
+ if not np.isfinite(v_min) or not np.isfinite(v_max) or v_max <= v_min:
461
+ return np.zeros_like(values, dtype=np.float32)
462
+ return ((values - v_min) / (v_max - v_min)).astype(np.float32)
463
+
464
+
465
+ def sanitize_max_pixels(max_pixels: Any) -> int:
466
+ try:
467
+ requested = int(float(max_pixels))
468
+ except (TypeError, ValueError):
469
+ requested = DEFAULT_MAX_RESOLUTION
470
+ return int(clamp(requested, MIN_RESOLUTION_LIMIT, MAX_RESOLUTION_LIMIT))
471
+
472
+ def get_lanczos_resample_filter() -> int:
473
+ return getattr(getattr(Image, "Resampling", Image), "LANCZOS")
474
+
475
+
476
+ def load_and_resize_image(input_filepath: str, max_pixels: int) -> tuple[np.ndarray, str]:
477
+ if input_filepath is None:
478
+ raise gr.Error("Please upload an image.")
479
+
480
+ filepath = str(input_filepath)
481
+ filepath_lower = filepath.lower()
482
 
483
  try:
484
+ image_pil = Image.open(filepath)
485
+ image_pil = ImageOps.exif_transpose(image_pil).convert("RGB")
486
+ except Exception as exc:
487
+ heif_hint = ""
488
+ if filepath_lower.endswith((".heic", ".heif")):
489
+ if HEIF_SUPPORT:
490
+ heif_hint = " The file looks like HEIC/HEIF; pillow-heif is installed but could not decode this file."
491
+ else:
492
+ heif_hint = f" HEIC/HEIF support is unavailable because pillow-heif failed to load: {HEIF_IMPORT_ERROR}"
493
+ raise gr.Error(f"Could not open image file.{heif_hint} Error: {exc}") from exc
494
+
495
+ original_w, original_h = image_pil.size
496
+ original_pixels = original_w * original_h
497
+ max_pixels = sanitize_max_pixels(max_pixels)
498
+ resized = False
499
+
500
+ if original_pixels > max_pixels:
501
+ ratio = (max_pixels / original_pixels) ** 0.5
502
+ new_w = max(1, int(original_w * ratio))
503
+ new_h = max(1, int(original_h * ratio))
504
+ image_pil = image_pil.resize((new_w, new_h), get_lanczos_resample_filter())
505
+ resized = True
506
+
507
+ input_image = np.array(image_pil, dtype=np.uint8)
508
+ current_h, current_w = input_image.shape[:2]
509
+ status = (
510
+ f"Loaded {original_w}×{original_h} image. "
511
+ f"Processing at {current_w}×{current_h} ({current_w * current_h:,} pixels)."
512
+ )
513
+ if resized:
514
+ status += f" Downsampled to stay under the {max_pixels:,}-pixel limit."
515
+ if filepath_lower.endswith((".heic", ".heif")):
516
+ status += " HEIC/HEIF decoded server-side."
517
+ return input_image, status
518
 
519
+
520
+ def estimate_depth_map(input_image: np.ndarray) -> np.ndarray:
521
  image = Image.fromarray(input_image).convert("RGB")
522
  with torch.no_grad():
523
  inputs = processor(images=image, return_tensors="pt").to(device)
524
  outputs = model(**inputs)
525
  predicted_depth = outputs.predicted_depth
526
  depth = torch.nn.functional.interpolate(
527
+ predicted_depth.unsqueeze(1),
528
+ size=(image.height, image.width),
529
+ mode="bicubic",
530
+ align_corners=False,
531
  ).squeeze().cpu().numpy()
532
+ return normalize_array(depth)
533
+
534
+
535
+ def apply_smoothing(values: np.ndarray, smoothing: int) -> np.ndarray:
536
+ try:
537
+ ksize = int(smoothing)
538
+ except (TypeError, ValueError):
539
+ ksize = 0
540
+ if ksize <= 1:
541
+ return values.astype(np.float32, copy=True)
542
+ if ksize % 2 == 0:
543
+ ksize += 1
544
+ return cv2.GaussianBlur(values.astype(np.float32), (ksize, ksize), 0).astype(np.float32)
545
+
546
+
547
+ def sanitize_curve_points(curve_points_json: str | None) -> list[dict[str, float]]:
548
+ try:
549
+ raw_points = json.loads(curve_points_json or "")
550
+ except (TypeError, json.JSONDecodeError):
551
+ raw_points = DEFAULT_CURVE_POINTS
552
+
553
+ points: list[dict[str, float]] = []
554
+ if isinstance(raw_points, list):
555
+ for point in raw_points:
556
+ if isinstance(point, dict):
557
+ x, y = point.get("x"), point.get("y")
558
+ elif isinstance(point, (list, tuple)) and len(point) >= 2:
559
+ x, y = point[0], point[1]
560
+ else:
561
+ continue
562
+ try:
563
+ x_f = clamp(float(x), 0.0, 1.0)
564
+ y_f = clamp(float(y), 0.0, 1.0)
565
+ except (TypeError, ValueError):
566
+ continue
567
+ points.append({"x": x_f, "y": y_f})
568
+
569
+ if len(points) < 2:
570
+ points = [dict(point) for point in DEFAULT_CURVE_POINTS]
571
+
572
+ points.sort(key=lambda point: point["x"])
573
+ deduped: list[dict[str, float]] = []
574
+ for point in points:
575
+ if deduped and abs(point["x"] - deduped[-1]["x"]) < 1e-5:
576
+ deduped[-1] = point
577
+ else:
578
+ deduped.append(point)
579
+
580
+ if len(deduped) < 2:
581
+ deduped = [dict(point) for point in DEFAULT_CURVE_POINTS]
582
+
583
+ deduped[0]["x"] = 0.0
584
+ deduped[-1]["x"] = 1.0
585
+ return deduped
586
+
587
+
588
+ def curve_points_to_json(points: list[dict[str, float]]) -> str:
589
+ return json.dumps([
590
+ {"x": round(float(point["x"]), 5), "y": round(float(point["y"]), 5)}
591
+ for point in points
592
+ ])
593
+
594
+
595
+ def apply_depth_curve(depth_map: np.ndarray, curve_points_json: str | None, invert_depth: bool) -> np.ndarray:
596
+ working = depth_map.astype(np.float32, copy=True)
597
+ if invert_depth:
598
+ working = 1.0 - working
599
+ points = sanitize_curve_points(curve_points_json)
600
+ x_values = np.array([point["x"] for point in points], dtype=np.float32)
601
+ y_values = np.array([point["y"] for point in points], dtype=np.float32)
602
+ adjusted = np.interp(working, x_values, y_values).astype(np.float32)
603
+ return np.clip(adjusted, 0.0, 1.0)
604
+
605
+
606
+ def depth_to_preview_image(depth_map: np.ndarray) -> Image.Image:
607
+ preview = np.clip(depth_map, 0.0, 1.0)
608
+ preview_uint8 = (preview * 255).astype(np.uint8)
609
+ colored = cv2.applyColorMap(preview_uint8, cv2.COLORMAP_INFERNO)
610
+ colored = cv2.cvtColor(colored, cv2.COLOR_BGR2RGB)
611
+ return Image.fromarray(colored)
612
+
613
+
614
+ def histogram_json(depth_map: np.ndarray, bins: int = 96) -> str:
615
+ counts, _ = np.histogram(np.clip(depth_map, 0.0, 1.0), bins=bins, range=(0.0, 1.0))
616
+ return json.dumps(counts.astype(int).tolist())
617
+
618
+
619
+ def prepare_depth(input_filepath: str, max_processing_pixels: float):
620
+ input_image, load_status = load_and_resize_image(input_filepath, sanitize_max_pixels(max_processing_pixels))
621
+ depth_normalized = estimate_depth_map(input_image)
622
+ curve_json = curve_points_to_json(DEFAULT_CURVE_POINTS)
623
+ adjusted = apply_depth_curve(depth_normalized, curve_json, invert_depth=False)
624
+ state = {
625
+ "image_rgb": input_image,
626
+ "raw_depth": depth_normalized,
627
+ "adjusted_depth": adjusted,
628
+ "curve_points_json": curve_json,
629
+ "depth_map_smoothing": 0,
630
+ "invert_depth": False,
631
+ "load_status": load_status,
632
+ }
633
+ status = (
634
+ f"{load_status}\nDepth estimation complete. Use the curve editor to remap the 2D depth map before generating the STL."
635
+ )
636
+ return (
637
+ state,
638
+ Image.fromarray(input_image),
639
+ depth_to_preview_image(depth_normalized),
640
+ depth_to_preview_image(adjusted),
641
+ histogram_json(depth_normalized),
642
+ curve_json,
643
+ status,
644
+ "Preview is using the linear curve.",
645
+ )
646
+
647
+
648
+ def get_smoothed_depth_from_state(depth_state: dict[str, Any] | None, depth_map_smoothing: int) -> np.ndarray:
649
+ if not depth_state or "raw_depth" not in depth_state:
650
+ raise gr.Error("Please upload an image and estimate its depth first.")
651
+ return normalize_array(apply_smoothing(depth_state["raw_depth"], depth_map_smoothing))
652
+
653
+
654
+ def update_depth_preview(
655
+ depth_state: dict[str, Any] | None,
656
+ curve_points_json: str | None,
657
+ depth_map_smoothing: int,
658
+ invert_depth: bool,
659
+ ):
660
+ smoothed_depth = get_smoothed_depth_from_state(depth_state, depth_map_smoothing)
661
+ adjusted_depth = apply_depth_curve(smoothed_depth, curve_points_json, invert_depth)
662
+ points = sanitize_curve_points(curve_points_json)
663
+ normalized_curve_json = curve_points_to_json(points)
664
+ if depth_state is not None:
665
+ depth_state["adjusted_depth"] = adjusted_depth
666
+ depth_state["curve_points_json"] = normalized_curve_json
667
+ depth_state["depth_map_smoothing"] = int(depth_map_smoothing)
668
+ depth_state["invert_depth"] = bool(invert_depth)
669
+ status = f"Preview updated with {len(points)} curve points."
670
+ return (
671
+ depth_state,
672
+ depth_to_preview_image(adjusted_depth),
673
+ histogram_json(smoothed_depth),
674
+ normalized_curve_json,
675
+ status,
676
+ )
677
+
678
+
679
+ def get_adjusted_depth_for_settings(
680
+ depth_state: dict[str, Any],
681
+ curve_points_json: str | None,
682
+ depth_map_smoothing: int,
683
+ invert_depth: bool,
684
+ ) -> np.ndarray:
685
+ normalized_curve_json = curve_points_to_json(sanitize_curve_points(curve_points_json))
686
+ cached_depth = depth_state.get("adjusted_depth")
687
+ cache_matches = (
688
+ cached_depth is not None
689
+ and depth_state.get("curve_points_json") == normalized_curve_json
690
+ and int(depth_state.get("depth_map_smoothing", -1)) == int(depth_map_smoothing)
691
+ and bool(depth_state.get("invert_depth", False)) == bool(invert_depth)
692
+ )
693
+ if cache_matches:
694
+ return cached_depth
695
+
696
+ smoothed_depth = get_smoothed_depth_from_state(depth_state, depth_map_smoothing)
697
+ adjusted_depth = apply_depth_curve(smoothed_depth, normalized_curve_json, invert_depth)
698
+ depth_state["adjusted_depth"] = adjusted_depth
699
+ depth_state["curve_points_json"] = normalized_curve_json
700
+ depth_state["depth_map_smoothing"] = int(depth_map_smoothing)
701
+ depth_state["invert_depth"] = bool(invert_depth)
702
+ return adjusted_depth
703
+
704
+ def combine_depth_and_texture(
705
+ image_rgb: np.ndarray,
706
+ adjusted_depth: np.ndarray,
707
+ texture_strength: float,
708
+ texture_smoothing: int,
709
+ ) -> np.ndarray:
710
+ gray_image = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2GRAY)
711
+ brightness_normalized = gray_image.astype(np.float32) / 255.0
712
+ brightness_normalized = apply_smoothing(brightness_normalized, texture_smoothing)
713
+
714
+ if brightness_normalized.shape != adjusted_depth.shape:
715
  brightness_normalized = cv2.resize(
716
+ brightness_normalized,
717
+ (adjusted_depth.shape[1], adjusted_depth.shape[0]),
718
+ interpolation=cv2.INTER_LINEAR,
719
  )
720
 
721
+ combined_map = adjusted_depth + (brightness_normalized * float(texture_strength))
722
+ return normalize_array(combined_map)
 
 
 
 
723
 
 
724
 
725
+ def apply_pca_correction_to_z(z_data: np.ndarray, x_length: float, min_z: float, max_z: float) -> np.ndarray:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
726
  height, width = z_data.shape
727
  y_length = x_length * (height / width)
728
+ x_coords_1d = np.linspace(0, x_length, width)
729
+ y_coords_1d = np.linspace(y_length, 0, height)
730
+ x_grid, y_grid = np.meshgrid(x_coords_1d, y_coords_1d)
731
+ points = np.stack([x_grid.flatten(), y_grid.flatten(), z_data.flatten()], axis=1)
732
+ n_points = points.shape[0]
733
+ n_samples = min(n_points, 50_000)
734
+ sample_indices = np.random.choice(n_points, n_samples, replace=False)
735
+ pca = PCA(n_components=3)
736
+ pca.fit(points[sample_indices])
737
+ normal = pca.components_[2]
738
+ if normal[2] < 0:
739
+ normal *= -1
740
+ p0 = pca.mean_
741
+ z_plane = p0[2] - (normal[0] * (x_grid - p0[0]) + normal[1] * (y_grid - p0[1])) / normal[2]
742
+ corrected_z = z_data - z_plane
743
+ corrected_normalized = normalize_array(corrected_z)
744
+ return min_z + corrected_normalized * (max_z - min_z)
745
+
746
+
747
+ def build_stl_mesh(z_data: np.ndarray, x_length: float, close_body: bool) -> str:
748
+ height, width = z_data.shape
749
+ y_length = x_length * (height / width)
750
+ vertices = np.zeros((height, width, 3), dtype=np.float32)
751
+ x_coords = np.linspace(0, x_length, width, dtype=np.float32)
752
+ y_coords = np.linspace(y_length, 0, height, dtype=np.float32)
753
+ vertices[:, :, 0] = x_coords[np.newaxis, :]
754
+ vertices[:, :, 1] = y_coords[:, np.newaxis]
755
+ vertices[:, :, 2] = z_data.astype(np.float32)
756
+
757
  faces = []
758
+ for i in range(height - 1):
759
+ for j in range(width - 1):
760
+ v1, v2, v3, v4 = vertices[i, j], vertices[i + 1, j], vertices[i + 1, j + 1], vertices[i, j + 1]
761
  faces.extend([[v1, v2, v3], [v1, v3, v4]])
762
 
763
  if close_body:
764
+ v_tl = vertices[0, 0]
765
+ v_tr = vertices[0, width - 1]
766
+ v_bl = vertices[height - 1, 0]
767
+ v_br = vertices[height - 1, width - 1]
768
+ b_tl = np.array([v_tl[0], v_tl[1], 0], dtype=np.float32)
769
+ b_tr = np.array([v_tr[0], v_tr[1], 0], dtype=np.float32)
770
+ b_bl = np.array([v_bl[0], v_bl[1], 0], dtype=np.float32)
771
+ b_br = np.array([v_br[0], v_br[1], 0], dtype=np.float32)
772
+
773
  faces.extend([
774
+ [v_tl, b_tl, b_tr], [v_tl, b_tr, v_tr],
775
+ [v_br, b_br, b_bl], [v_br, b_bl, v_bl],
776
+ [v_bl, b_bl, b_tl], [v_bl, b_tl, v_tl],
777
+ [v_tr, b_tr, b_br], [v_tr, b_br, v_br],
778
+ [b_tl, b_br, b_bl], [b_tl, b_tr, b_br],
779
  ])
780
 
781
  surface = mesh.Mesh(np.zeros(len(faces), dtype=mesh.Mesh.dtype))
 
783
 
784
  with tempfile.NamedTemporaryFile(delete=False, suffix=".stl") as tmpfile:
785
  surface.save(tmpfile.name)
786
+ return tmpfile.name
787
+
788
+
789
+ def generate_3d_model_from_adjusted_depth(
790
+ depth_state: dict[str, Any] | None,
791
+ curve_points_json: str | None,
792
+ depth_map_smoothing: int,
793
+ invert_depth: bool,
794
+ texture_strength: float,
795
+ texture_smoothing: int,
796
+ max_z: float,
797
+ min_z: float,
798
+ x_length: float,
799
+ do_pca_correction: bool,
800
+ close_body: bool,
801
+ ):
802
+ if max_z <= min_z:
803
+ raise gr.Error("Max Z-height must be greater than Min Z-height.")
804
+ if x_length <= 0:
805
+ raise gr.Error("X Length must be positive.")
806
+ if not depth_state or "image_rgb" not in depth_state:
807
+ raise gr.Error("Please estimate a depth map before generating an STL.")
808
+
809
+ adjusted_depth = get_adjusted_depth_for_settings(
810
+ depth_state,
811
+ curve_points_json,
812
+ depth_map_smoothing,
813
+ invert_depth,
814
+ )
815
+ combined_map = combine_depth_and_texture(
816
+ depth_state["image_rgb"],
817
+ adjusted_depth,
818
+ texture_strength,
819
+ texture_smoothing,
820
+ )
821
+ z_data = min_z + combined_map * (max_z - min_z)
822
+
823
+ if do_pca_correction:
824
+ z_data = apply_pca_correction_to_z(z_data, x_length, min_z, max_z)
825
+
826
+ stl_path = build_stl_mesh(z_data, x_length, close_body)
827
+ point_count = len(sanitize_curve_points(curve_points_json))
828
+ status = f"Generated STL from adjusted depth map using {point_count} curve points."
829
+ return stl_path, stl_path, status
830
+
831
+
832
+ with gr.Blocks(title="Image to 3D Relief Generator") as demo:
833
+ depth_state = gr.State()
834
 
 
835
  gr.Markdown("# Image to 3D Relief Generator")
836
+ gr.Markdown(
837
+ "Estimate a depth map from an image, tune the 2D depth interpretation with a histogram + curves editor, "
838
+ "then export the adjusted relief as an STL."
839
+ )
840
+
841
  with gr.Row():
842
  with gr.Column(scale=1):
843
+ gr.Markdown("## 1. Upload and estimate depth")
844
+ input_file = gr.File(
845
+ type="filepath",
846
+ label="Upload image (PNG, JPG, WebP, TIFF, HEIC/HEIF)",
847
+ file_types=ACCEPTED_IMAGE_TYPES,
848
+ )
849
+ max_processing_pixels = gr.Number(
850
+ value=DEFAULT_MAX_RESOLUTION,
851
+ label="Max processing pixels",
852
+ precision=0,
853
+ info=(
854
+ "Default is conservative for Hugging Face CPU runners. "
855
+ "Raise it locally for more detail; very high values can be slow or memory-intensive."
856
+ ),
857
+ )
858
+ estimate_btn = gr.Button("Estimate Depth Map", variant="primary")
859
+ analysis_status = gr.Textbox(label="Depth estimation status", lines=4, interactive=False)
860
+
861
+ gr.Markdown("## 2. Tune depth before export")
862
+ depth_map_smoothing = gr.Slider(
863
+ minimum=0,
864
+ maximum=51,
865
+ value=0,
866
+ step=1,
867
+ label="Base Depth Map Smoothing",
868
+ info="Smooths the estimated base depth map before the curve. 0 = none.",
869
+ )
870
+ invert_depth = gr.Checkbox(
871
+ value=False,
872
+ label="Invert estimated depth before curve",
873
+ info="Use if the preview has foreground/background relief direction reversed.",
874
+ )
875
+ gr.HTML(CURVE_EDITOR_HTML)
876
+ curve_points_json = gr.Textbox(
877
+ value=curve_points_to_json(DEFAULT_CURVE_POINTS),
878
+ label="Curve Points JSON",
879
+ elem_id="curve-points-json",
880
+ )
881
+ depth_histogram_json = gr.Textbox(
882
+ value="[]",
883
+ label="Depth Histogram JSON",
884
+ elem_id="depth-histogram-json",
885
+ )
886
+ auto_preview_btn = gr.Button("Auto Preview", elem_id="auto-preview-depth-btn")
887
+ update_preview_btn = gr.Button("Update Adjusted Depth Preview")
888
+ preview_status = gr.Textbox(label="Curve preview status", interactive=False)
889
+
890
+ gr.Markdown("## 3. STL parameters")
891
+ texture_strength = gr.Slider(
892
+ minimum=0.0,
893
+ maximum=1.0,
894
+ value=0.1,
895
+ step=0.001,
896
+ label="Brightness Texture Strength",
897
+ )
898
+ texture_smoothing = gr.Slider(
899
+ minimum=0,
900
+ maximum=51,
901
+ value=0,
902
+ step=1,
903
+ label="Texture Smoothing",
904
+ info="Smooths the brightness texture before it is mixed into the adjusted depth map. 0 = none.",
905
+ )
906
  x_length = gr.Number(value=100, label="X Length (units)")
907
  min_z = gr.Number(value=0.5, label="Min Z-Height (units)")
908
  max_z = gr.Number(value=5.0, label="Max Z-Height (units)")
909
  do_pca = gr.Checkbox(value=True, label="Enable PCA Planar Correction")
910
  close_body = gr.Checkbox(value=False, label="Close Body")
911
+ generate_btn = gr.Button("Generate STL from Adjusted Depth", variant="primary")
 
912
 
913
  with gr.Column(scale=1):
914
+ gr.Markdown("### Image and depth previews")
915
+ original_preview = gr.Image(label="Processed input image", interactive=False)
916
+ raw_depth_preview = gr.Image(label="Estimated base depth", interactive=False)
917
+ adjusted_depth_preview = gr.Image(label="Adjusted depth used for STL", interactive=False)
918
+
919
  gr.Markdown("### 3D Model Output")
920
  output_model = gr.Model3D(label="Generated 3D Model")
921
  output_file = gr.File(label="Download STL File")
922
+ generation_status = gr.Textbox(label="Generation status", interactive=False)
923
+
924
+ estimate_btn.click(
925
+ fn=prepare_depth,
926
+ inputs=[input_file, max_processing_pixels],
927
+ outputs=[
928
+ depth_state,
929
+ original_preview,
930
+ raw_depth_preview,
931
+ adjusted_depth_preview,
932
+ depth_histogram_json,
933
+ curve_points_json,
934
+ analysis_status,
935
+ preview_status,
936
+ ],
937
+ )
938
+
939
+ preview_inputs = [depth_state, curve_points_json, depth_map_smoothing, invert_depth]
940
+ preview_outputs = [depth_state, adjusted_depth_preview, depth_histogram_json, curve_points_json, preview_status]
941
+ update_preview_btn.click(
942
+ fn=update_depth_preview,
943
+ inputs=preview_inputs,
944
+ outputs=preview_outputs,
945
+ )
946
+ auto_preview_btn.click(
947
+ fn=update_depth_preview,
948
+ inputs=preview_inputs,
949
+ outputs=preview_outputs,
950
+ show_progress=False,
951
+ )
952
+ depth_map_smoothing.change(
953
+ fn=update_depth_preview,
954
+ inputs=preview_inputs,
955
+ outputs=preview_outputs,
956
+ show_progress=False,
957
+ )
958
+ invert_depth.change(
959
+ fn=update_depth_preview,
960
+ inputs=preview_inputs,
961
+ outputs=preview_outputs,
962
+ show_progress=False,
963
+ )
964
 
965
  generate_btn.click(
966
+ fn=generate_3d_model_from_adjusted_depth,
967
  inputs=[
968
+ depth_state,
969
+ curve_points_json,
970
+ depth_map_smoothing,
971
+ invert_depth,
972
+ texture_strength,
973
+ texture_smoothing,
974
+ max_z,
975
+ min_z,
976
+ x_length,
977
+ do_pca,
978
+ close_body,
979
  ],
980
+ outputs=[output_model, output_file, generation_status],
981
  )
982
 
983
  if __name__ == "__main__":
984
+ demo.queue().launch(
985
+ server_name="0.0.0.0",
986
+ server_port=7860,
987
+ theme="base",
988
+ css=APP_CSS,
989
+ head=CURVE_EDITOR_HEAD,
990
+ )