Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,200 +1,209 @@
|
|
| 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 DPTForDepthEstimation, DPTImageProcessor
|
| 7 |
-
from huggingface_hub import hf_hub_download
|
| 8 |
-
import os
|
| 9 |
-
|
| 10 |
-
# === DEVICE ===
|
| 11 |
-
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 12 |
-
print(f"Running on device: {device}")
|
| 13 |
-
|
| 14 |
-
# === LOAD MODELS ===
|
| 15 |
-
def load_models():
|
| 16 |
-
print("Loading Depth Model...")
|
| 17 |
-
# 1. Depth Model
|
| 18 |
-
depth_model = DPTForDepthEstimation.from_pretrained("Intel/dpt-hybrid-midas").to(device)
|
| 19 |
-
depth_processor = DPTImageProcessor.from_pretrained("Intel/dpt-hybrid-midas")
|
| 20 |
-
|
| 21 |
-
print("Loading LaMa Inpainting Model...")
|
| 22 |
-
# 2. LaMa Inpainting Model (TorchScript)
|
| 23 |
-
# We download the
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
#
|
| 71 |
-
mask
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
#
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
img_t =
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
#
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
return
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
#
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
#
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
#
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
demo.launch()
|
|
|
|
| 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 DPTForDepthEstimation, DPTImageProcessor
|
| 7 |
+
from huggingface_hub import hf_hub_download
|
| 8 |
+
import os
|
| 9 |
+
|
| 10 |
+
# === DEVICE ===
|
| 11 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 12 |
+
print(f"Running on device: {device}")
|
| 13 |
+
|
| 14 |
+
# === LOAD MODELS ===
|
| 15 |
+
def load_models():
|
| 16 |
+
print("Loading Depth Model...")
|
| 17 |
+
# 1. Depth Model
|
| 18 |
+
depth_model = DPTForDepthEstimation.from_pretrained("Intel/dpt-hybrid-midas").to(device)
|
| 19 |
+
depth_processor = DPTImageProcessor.from_pretrained("Intel/dpt-hybrid-midas")
|
| 20 |
+
|
| 21 |
+
print("Loading LaMa Inpainting Model...")
|
| 22 |
+
# 2. LaMa Inpainting Model (TorchScript)
|
| 23 |
+
# We download the .pt file directly from a repository that hosts the compiled JIT version.
|
| 24 |
+
# This avoids dealing with .ckpt files and source code dependencies.
|
| 25 |
+
try:
|
| 26 |
+
model_path = hf_hub_download(repo_id="fashn-ai/LaMa", filename="big-lama.pt")
|
| 27 |
+
|
| 28 |
+
print(f"Loading LaMa from: {model_path}")
|
| 29 |
+
# Load the TorchScript model
|
| 30 |
+
lama_model = torch.jit.load(model_path, map_location=device)
|
| 31 |
+
lama_model.eval()
|
| 32 |
+
|
| 33 |
+
except Exception as e:
|
| 34 |
+
print(f"Error loading LaMa model: {e}")
|
| 35 |
+
raise e
|
| 36 |
+
|
| 37 |
+
return depth_model, depth_processor, lama_model
|
| 38 |
+
|
| 39 |
+
# Load models once at startup
|
| 40 |
+
depth_model, depth_processor, lama_model = load_models()
|
| 41 |
+
|
| 42 |
+
# === DEPTH ESTIMATION ===
|
| 43 |
+
@torch.no_grad()
|
| 44 |
+
def estimate_depth(image_pil, model, processor):
|
| 45 |
+
original_size = image_pil.size
|
| 46 |
+
inputs = processor(images=image_pil, return_tensors="pt").to(device)
|
| 47 |
+
depth = model(**inputs).predicted_depth
|
| 48 |
+
|
| 49 |
+
depth = torch.nn.functional.interpolate(
|
| 50 |
+
depth.unsqueeze(1),
|
| 51 |
+
size=(original_size[1], original_size[0]),
|
| 52 |
+
mode="bicubic",
|
| 53 |
+
align_corners=False,
|
| 54 |
+
).squeeze().detach().cpu().numpy()
|
| 55 |
+
|
| 56 |
+
depth_min, depth_max = depth.min(), depth.max()
|
| 57 |
+
if depth_max - depth_min > 0:
|
| 58 |
+
return (depth - depth_min) / (depth_max - depth_min)
|
| 59 |
+
return depth
|
| 60 |
+
|
| 61 |
+
# === STEREO GENERATION LOGIC ===
|
| 62 |
+
def generate_right_and_mask(image, shift_map):
|
| 63 |
+
height, width = image.shape[:2]
|
| 64 |
+
x_coords, y_coords = np.meshgrid(np.arange(width), np.arange(height))
|
| 65 |
+
shift = shift_map.astype(int)
|
| 66 |
+
target_x = x_coords - shift
|
| 67 |
+
|
| 68 |
+
right = np.zeros_like(image)
|
| 69 |
+
# Mask: 1 (or 255) means HOLE/MISSING info.
|
| 70 |
+
# Initialize as all holes (255)
|
| 71 |
+
mask = np.ones((height, width), dtype=np.float32)
|
| 72 |
+
|
| 73 |
+
valid_mask = (target_x >= 0) & (target_x < width)
|
| 74 |
+
flat_y = y_coords[valid_mask]
|
| 75 |
+
flat_x_target = target_x[valid_mask]
|
| 76 |
+
flat_x_source = x_coords[valid_mask]
|
| 77 |
+
|
| 78 |
+
right[flat_y, flat_x_target] = image[flat_y, flat_x_source]
|
| 79 |
+
# Mark written pixels as valid (0)
|
| 80 |
+
mask[flat_y, flat_x_target] = 0.0
|
| 81 |
+
|
| 82 |
+
return right, mask
|
| 83 |
+
|
| 84 |
+
# === LOCAL INPAINTING ===
|
| 85 |
+
@torch.no_grad()
|
| 86 |
+
def run_local_lama(image_bgr, mask_float):
|
| 87 |
+
"""
|
| 88 |
+
Runs LaMa locally.
|
| 89 |
+
image_bgr: HxWx3 uint8 numpy array
|
| 90 |
+
mask_float: HxW float32 numpy array (1.0 = hole, 0.0 = valid)
|
| 91 |
+
"""
|
| 92 |
+
# 1. Resize to be divisible by 8 (LaMa requirement)
|
| 93 |
+
h, w = image_bgr.shape[:2]
|
| 94 |
+
new_h = (h // 8) * 8
|
| 95 |
+
new_w = (w // 8) * 8
|
| 96 |
+
|
| 97 |
+
img_resized = cv2.resize(image_bgr, (new_w, new_h))
|
| 98 |
+
mask_resized = cv2.resize(mask_float, (new_w, new_h), interpolation=cv2.INTER_NEAREST)
|
| 99 |
+
|
| 100 |
+
# 2. Convert to Torch Tensors
|
| 101 |
+
# Image: (1, 3, H, W), RGB, 0-1
|
| 102 |
+
img_t = torch.from_numpy(img_resized).float().permute(2, 0, 1).unsqueeze(0) / 255.0
|
| 103 |
+
# Swap BGR to RGB
|
| 104 |
+
img_t = img_t[:, [2, 1, 0], :, :]
|
| 105 |
+
|
| 106 |
+
# Mask: (1, 1, H, W), 0-1
|
| 107 |
+
mask_t = torch.from_numpy(mask_resized).float().unsqueeze(0).unsqueeze(0)
|
| 108 |
+
# Binary threshold just in case
|
| 109 |
+
mask_t = (mask_t > 0.5).float()
|
| 110 |
+
|
| 111 |
+
img_t = img_t.to(device)
|
| 112 |
+
mask_t = mask_t.to(device)
|
| 113 |
+
|
| 114 |
+
# 3. Inference
|
| 115 |
+
inpainted_t = lama_model(img_t, mask_t)
|
| 116 |
+
|
| 117 |
+
# 4. Post-process
|
| 118 |
+
inpainted = inpainted_t[0].permute(1, 2, 0).cpu().numpy()
|
| 119 |
+
inpainted = np.clip(inpainted * 255, 0, 255).astype(np.uint8)
|
| 120 |
+
|
| 121 |
+
# Swap back RGB to BGR
|
| 122 |
+
inpainted = cv2.cvtColor(inpainted, cv2.COLOR_RGB2BGR)
|
| 123 |
+
|
| 124 |
+
# Resize back to original if needed
|
| 125 |
+
if new_h != h or new_w != w:
|
| 126 |
+
inpainted = cv2.resize(inpainted, (w, h))
|
| 127 |
+
|
| 128 |
+
return inpainted
|
| 129 |
+
|
| 130 |
+
def make_anaglyph(left, right):
|
| 131 |
+
l_arr = np.array(left)
|
| 132 |
+
r_arr = np.array(right)
|
| 133 |
+
anaglyph = np.zeros_like(l_arr)
|
| 134 |
+
anaglyph[:, :, 0] = l_arr[:, :, 0]
|
| 135 |
+
anaglyph[:, :, 1] = r_arr[:, :, 1]
|
| 136 |
+
anaglyph[:, :, 2] = r_arr[:, :, 2]
|
| 137 |
+
return Image.fromarray(anaglyph)
|
| 138 |
+
|
| 139 |
+
# === PIPELINE ===
|
| 140 |
+
def stereo_pipeline(image_pil, divergence, convergence):
|
| 141 |
+
if image_pil is None:
|
| 142 |
+
return None, None
|
| 143 |
+
|
| 144 |
+
# Convert to BGR for OpenCV processing
|
| 145 |
+
image_cv = cv2.cvtColor(np.array(image_pil), cv2.COLOR_RGB2BGR)
|
| 146 |
+
|
| 147 |
+
# 1. Depth
|
| 148 |
+
depth = estimate_depth(image_pil, depth_model, depth_processor)
|
| 149 |
+
|
| 150 |
+
# 2. Shift Map
|
| 151 |
+
shift = (depth - convergence) * divergence
|
| 152 |
+
|
| 153 |
+
# 3. Warping
|
| 154 |
+
right_img, mask = generate_right_and_mask(image_cv, shift)
|
| 155 |
+
|
| 156 |
+
# 4. Inpainting (Local)
|
| 157 |
+
right_filled = run_local_lama(right_img, mask)
|
| 158 |
+
|
| 159 |
+
left = image_pil
|
| 160 |
+
right = Image.fromarray(cv2.cvtColor(right_filled, cv2.COLOR_BGR2RGB))
|
| 161 |
+
|
| 162 |
+
# 5. Composition
|
| 163 |
+
width, height = left.size
|
| 164 |
+
combined_image = Image.new('RGB', (width * 2, height))
|
| 165 |
+
combined_image.paste(left, (0, 0))
|
| 166 |
+
combined_image.paste(right, (width, 0))
|
| 167 |
+
|
| 168 |
+
anaglyph_image = make_anaglyph(left, right)
|
| 169 |
+
|
| 170 |
+
return combined_image, anaglyph_image
|
| 171 |
+
|
| 172 |
+
# === GRADIO UI ===
|
| 173 |
+
with gr.Blocks(title="2D to 3D Stereo") as demo:
|
| 174 |
+
gr.Markdown("## 2D to 3D Stereo Generator (Fully Local)")
|
| 175 |
+
gr.Markdown("Generates stereo pairs using Depth Estimation and **Local LaMa Inpainting**. No external APIs required.")
|
| 176 |
+
|
| 177 |
+
with gr.Row():
|
| 178 |
+
with gr.Column(scale=1):
|
| 179 |
+
input_img = gr.Image(type="pil", label="Input Image", height=480)
|
| 180 |
+
|
| 181 |
+
with gr.Group():
|
| 182 |
+
gr.Markdown("### 3D Controls")
|
| 183 |
+
divergence_slider = gr.Slider(
|
| 184 |
+
minimum=0, maximum=100, value=30, step=1,
|
| 185 |
+
label="3D Strength (Divergence)",
|
| 186 |
+
info="Max pixel separation."
|
| 187 |
+
)
|
| 188 |
+
convergence_slider = gr.Slider(
|
| 189 |
+
minimum=0.0, maximum=1.0, value=0.1, step=0.05,
|
| 190 |
+
label="Focus Plane (Convergence)",
|
| 191 |
+
info="0.0 = Background at screen. 1.0 = Foreground at screen."
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
btn = gr.Button("Generate 3D", variant="primary")
|
| 195 |
+
|
| 196 |
+
with gr.Column(scale=1):
|
| 197 |
+
out_anaglyph = gr.Image(label="Anaglyph (Red/Cyan)", height=480)
|
| 198 |
+
|
| 199 |
+
with gr.Row():
|
| 200 |
+
out_stereo = gr.Image(label="Side-by-Side Stereo Pair", height=400)
|
| 201 |
+
|
| 202 |
+
btn.click(
|
| 203 |
+
fn=stereo_pipeline,
|
| 204 |
+
inputs=[input_img, divergence_slider, convergence_slider],
|
| 205 |
+
outputs=[out_stereo, out_anaglyph]
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
if __name__ == "__main__":
|
| 209 |
demo.launch()
|