mminju commited on
Commit
62da546
·
verified ·
1 Parent(s): 295647a

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -0
app.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py (HF Spaces: SDK=gradio)
2
+ import io, base64, numpy as np, torch, gradio as gr
3
+ from PIL import Image
4
+ from transformers import AutoImageProcessor, DepthProForDepthEstimation
5
+
6
+ device = "cuda" if torch.cuda.is_available() else "cpu"
7
+ _proc = None
8
+ _model = None
9
+
10
+ def _lazy_init():
11
+ global _proc, _model
12
+ if _proc is None:
13
+ _proc = AutoImageProcessor.from_pretrained("apple/DepthPro-hf")
14
+ if _model is None:
15
+ _model = DepthProForDepthEstimation.from_pretrained("apple/DepthPro-hf").to(device).eval()
16
+
17
+ def _infer(pil_img: Image.Image):
18
+ _lazy_init()
19
+ H, W = pil_img.height, pil_img.width
20
+ inputs = _proc(images=pil_img.convert("RGB"), return_tensors="pt").to(device)
21
+ with torch.no_grad():
22
+ outputs = _model(**inputs)
23
+ post = _proc.post_process_depth_estimation(outputs, target_sizes=[(H, W)])[0]
24
+ depth = post["predicted_depth"].float().cpu().numpy()
25
+ fov = float(post.get("field_of_view", 0.0))
26
+ focal = float(post.get("focal_length", 0.0))
27
+ return depth, H, W, fov, focal
28
+
29
+ # (A) API 함수: JSON 반환
30
+ def depth_api(img: Image.Image):
31
+ depth, H, W, fov, focal = _infer(img)
32
+ depth_b64 = base64.b64encode(depth.astype(np.float32).tobytes()).decode("ascii")
33
+ return {
34
+ "height": int(H),
35
+ "width": int(W),
36
+ "focal_px": float(focal),
37
+ "field_of_view": float(fov),
38
+ "depth_flat": depth_b64
39
+ }
40
+
41
+ # (B) 프리뷰용 UI
42
+ def preview(img: Image.Image):
43
+ depth, *_ = _infer(img)
44
+ v = depth[np.isfinite(depth)]
45
+ lo, hi = (np.percentile(v, 1), np.percentile(v, 99)) if v.size else (0, 1)
46
+ norm = np.clip((depth - lo) / max(1e-6, hi - lo), 0, 1)
47
+ return Image.fromarray((norm * 255).astype(np.uint8))
48
+
49
+ # 🔹 Blocks(UI) 만들기
50
+ with gr.Blocks() as ui:
51
+ gr.Markdown("## DepthPro-hf (CPU, Free Space)\n- REST API: **POST /api/predict/depth** (JSON base64)")
52
+ with gr.Row():
53
+ inp = gr.Image(type="pil", label="Input")
54
+ out = gr.Image(label="Depth (preview)")
55
+ gr.Button("Run").click(preview, inp, out)
56
+
57
+ # 🔹 API 인터페이스 (REST 경로: /api/predict/depth)
58
+ api = gr.Interface(
59
+ fn=depth_api,
60
+ inputs=gr.Image(type="pil"),
61
+ outputs=gr.JSON(),
62
+ api_name="depth"
63
+ )
64
+
65
+ # ✅ 두 개를 하나의 앱으로 합치기
66
+ demo = gr.TabbedInterface([ui, api], tab_names=["UI", "api"])