jasonod888 commited on
Commit ·
8d718f3
1
Parent(s): 46af2ea
Robust Marigold output unwrap + deps compatible with HF toolkit
Browse filesFiles changed (2)
- handler.py+82-46
- requirements.txt+1-2
1234564 unmodified lines11121314151617181925 unmodified lines454647484950515253545556575 unmodified lines63646566676869707172737475767 unmodified lines8485868788899091928 unmodified lines1011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531544 unmodified lines1591601611621631641651 unmodified line16716816917017117217314 unmodified lines1881891901911921931941 unmodified line19619719819920020120220320420520620720820921021121221315 unmodified lines229230231232233234235236237238239240import ioimport base64import inspectfrom typing import Any, Dict, List, Optional, Unionimport numpy as np4 unmodified linesfrom diffusers import MarigoldIntrinsicsPipeline, MarigoldNormalsPipeline# -------------------------# Image IO helpers# -------------------------def _is_data_url(s: str) -> bool:return isinstance(s, str) and s.startswith("data:image/") and ";base64," in s25 unmodified linesraise ValueError("inputs must be a string (url/data-url/base64) or a dict with image_url/image_b64")s = payload_inputs.strip()if s.startswith("http://") or s.startswith("https://"):return _url_to_pil(s)if _is_data_url(s):s = _strip_data_url_header(s)return _b64_to_pil(s)# raw base64try:return _b64_to_pil(s)except Exception as e:5 unmodified linesreturn "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode("utf-8")# -------------------------# Tensor helpers# -------------------------def _to_float_tensor(img: Any) -> torch.Tensor:"""Accept PIL / numpy / torch; return float32 tensor with last dim=3 when possible.Scales from [0,255] to [0,1] if needed."""if isinstance(img, torch.Tensor):t = img7 unmodified linesraise TypeError(f"Unexpected prediction type: {type(img)}")t = t.float()if t.max() > 1.5: # likely uint8 0..255t = t / 255.0# If channels-first, move to HWCif t.ndim == 3 and t.shape[0] in (1, 3) and t.shape[-1] not in (1, 3):t = t.permute(1, 2, 0).contiguous()return t8 unmodified linesreturn _png_b64_from_float_img01((img + 1.0) * 0.5)# -------------------------# Output unwrapping# -------------------------def _unwrap_field(obj: Any, names: List[str]) -> Optional[Any]:"""Try to extract a named field from:- dataclass-like (attributes)- dict-like- tuple-like via known order- diffusers outputs exposing .imagesReturns first match or None."""# Attribute accessfor n in names:if hasattr(obj, n):return getattr(obj, n)# Dict-likeif isinstance(obj, dict):for n in names:if n in obj:return obj[n]# Diffusers common: images listif hasattr(obj, "images"):imgs = getattr(obj, "images")if isinstance(imgs, (list, tuple)) and len(imgs) > 0:# If caller asked for 'normals'/'albedo' etc but only .images is present,# best effort is to return images[0].return imgs[0]# Tuple/list fallback for known ordersif isinstance(obj, (list, tuple)):# Intrinsics often: [albedo, diffuse, residual] (or similar)if len(obj) >= 3 and names == ["albedo"]:return obj[0]if len(obj) >= 2 and names == ["diffuse_shading", "shading"]:return obj[1]if len(obj) >= 3 and names == ["residual"]:return obj[2]return None# -------------------------# Endpoint# -------------------------class EndpointHandler:def __init__(self, path: Optional[str] = None):4 unmodified linesself.normals_pipe: Optional[MarigoldNormalsPipeline] = Noneself.intrin_pipe: Optional[MarigoldIntrinsicsPipeline] = None# Config per our discussionself.fixed_processing_res = 768self.default_intr_steps = 41 unmodified lineself.model_id_intrin = "prs-eth/marigold-iid-lighting-v1-1"def initialize(self, context: Optional[Dict[str, Any]] = None) -> None:# Lazy load on first usepass# -------- loaders --------14 unmodified linesdef _run_normals(self, pil_img: Image.Image, processing_res: int) -> Dict[str, Any]:self._ensure_normals_loaded()# Only pass processing_res if supportedsig = inspect.signature(self.normals_pipe.__call__)kwargs = {"image": pil_img}if "processing_res" in sig.parameters:1 unmodified lineout = self.normals_pipe(**kwargs)# Robust extractionnormals = _unwrap_field(out, ["normals"])if normals is None:# Some builds expose a single image via .images[0]normals = _unwrap_field(out, ["images"]) # will give images[0] in our helperif normals is None:# Last resort: maybe it's a raw tensor/ndarray/PIL alreadynormals = outnormals_t = _to_float_tensor(normals) # expect [-1,1] or [0,1]# Heuristic: if range looks 0..1, map to [-1,1] visualization anywaymaxv, minv = float(normals_t.max().item()), float(normals_t.min().item())if maxv <= 1.01 and minv >= -0.01:vis_b64 = _png_b64_from_float_img01(normals_t)15 unmodified linesout = self.intrin_pipe(image=pil_img, num_inference_steps=int(steps))# Try attributes/dict/tuple/tensor in a robust wayalbedo = _unwrap_field(out, ["albedo"])diffuse = _unwrap_field(out, ["diffuse_shading", "shading"])residual = _unwrap_field(out, ["residual"])# Tensor stack fallback (e.g., [3,H,W,3] or similar)if any(v is None for v in (albedo, diffuse, residual)):try:t = _to_float_tensor(out)12345674 unmodified lines12131415161718192025 unmodified lines4647484950515253545556575 unmodified lines636465666768697071727374757 unmodified lines838485868788899091928 unmodified lines1011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751764 unmodified lines1811821831841851861871 unmodified line18919019119219319419514 unmodified lines2102112122132142151 unmodified line21721821922022122222322422522622722822923023123223323423523623723823924024115 unmodified lines257258259260261262263264265266267268269270271272273274275276import ioimport base64import inspectimport dataclassesfrom typing import Any, Dict, List, Optional, Unionimport numpy as np4 unmodified linesfrom diffusers import MarigoldIntrinsicsPipeline, MarigoldNormalsPipeline# =======================# Image IO helpers# =======================def _is_data_url(s: str) -> bool:return isinstance(s, str) and s.startswith("data:image/") and ";base64," in s25 unmodified linesraise ValueError("inputs must be a string (url/data-url/base64) or a dict with image_url/image_b64")s = payload_inputs.strip()if s.startswith(("http://", "https://")):return _url_to_pil(s)if _is_data_url(s):s = _strip_data_url_header(s)return _b64_to_pil(s)try:return _b64_to_pil(s)except Exception as e:5 unmodified linesreturn "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode("utf-8")# =======================# Tensor helpers# =======================def _to_float_tensor(img: Any) -> torch.Tensor:"""Accept PIL / numpy / torch; return float32 tensor HxWxC in [0,1] when possible."""if isinstance(img, torch.Tensor):t = img7 unmodified linesraise TypeError(f"Unexpected prediction type: {type(img)}")t = t.float()if t.max() > 1.5: # likely 0..255t = t / 255.0# channels-first -> HWCif t.ndim == 3 and t.shape[0] in (1, 3) and t.shape[-1] not in (1, 3):t = t.permute(1, 2, 0).contiguous()return t8 unmodified linesreturn _png_b64_from_float_img01((img + 1.0) * 0.5)# =======================# Output unwrapping# =======================def _maybe_dataclass_to_dict(obj: Any) -> Optional[Dict[str, Any]]:try:if dataclasses.is_dataclass(obj):return dataclasses.asdict(obj)except Exception:pass# diffusers outputs often have .to_dict()if hasattr(obj, "to_dict") and callable(getattr(obj, "to_dict")):try:return obj.to_dict()except Exception:pass# last resort: use __dict__if hasattr(obj, "__dict__") and isinstance(obj.__dict__, dict):return dict(obj.__dict__)return Nonedef _unwrap_field(obj: Any, names: List[str]) -> Optional[Any]:"""Extract a named field from:- dataclass-like (converted to dict)- dict-like- attribute access- diffusers common: .images (first)- tuple/list fallbacks by known order"""# dataclass / to_dict / __dict__asd = _maybe_dataclass_to_dict(obj)if isinstance(asd, dict):for n in names:if n in asd:return asd[n]# attribute accessfor n in names:if hasattr(obj, n):return getattr(obj, n)# dict-likeif isinstance(obj, dict):for n in names:if n in obj:return obj[n]# diffusers: images listif hasattr(obj, "images"):imgs = getattr(obj, "images")if isinstance(imgs, (list, tuple)) and len(imgs) > 0:return imgs[0]# list/tuple positional guessesif isinstance(obj, (list, tuple)):# Intrinsics often 3 outputsif len(obj) >= 3 and names == ["albedo", "pred_albedo", "albedo_img"]:return obj[0]if len(obj) >= 2 and names == ["diffuse_shading", "shading", "pred_shading", "shading_diffuse"]:return obj[1]if len(obj) >= 3 and names == ["residual", "pred_residual", "specular_residual"]:return obj[2]return None# =======================# Endpoint# =======================class EndpointHandler:def __init__(self, path: Optional[str] = None):4 unmodified linesself.normals_pipe: Optional[MarigoldNormalsPipeline] = Noneself.intrin_pipe: Optional[MarigoldIntrinsicsPipeline] = None# Configself.fixed_processing_res = 768self.default_intr_steps = 41 unmodified lineself.model_id_intrin = "prs-eth/marigold-iid-lighting-v1-1"def initialize(self, context: Optional[Dict[str, Any]] = None) -> None:# Lazy load at first callpass# -------- loaders --------14 unmodified linesdef _run_normals(self, pil_img: Image.Image, processing_res: int) -> Dict[str, Any]:self._ensure_normals_loaded()sig = inspect.signature(self.normals_pipe.__call__)kwargs = {"image": pil_img}if "processing_res" in sig.parameters:1 unmodified lineout = self.normals_pipe(**kwargs)# Try common field names used across versionsnormals = _unwrap_field(out, ["normals", "pred_normals", "normal_map"])if normals is None:# if still not found, see if the object itself is an image/tensorasd = _maybe_dataclass_to_dict(out)if isinstance(asd, dict):# pick first image-like thing from the dictfor v in asd.values():try:_ = _to_float_tensor(v)normals = vbreakexcept Exception:continueif normals is None:# Last resort: the entire object is not directly convertible; fail clearlyraise TypeError(f"Unexpected prediction type: {type(out)}")normals_t = _to_float_tensor(normals)maxv, minv = float(normals_t.max().item()), float(normals_t.min().item())if maxv <= 1.01 and minv >= -0.01:vis_b64 = _png_b64_from_float_img01(normals_t)15 unmodified linesout = self.intrin_pipe(image=pil_img, num_inference_steps=int(steps))# Keys that show up across versionsalbedo = _unwrap_field(out, ["albedo", "pred_albedo", "albedo_img"])diffuse = _unwrap_field(out, ["diffuse_shading", "shading", "pred_shading", "shading_diffuse"])residual = _unwrap_field(out, ["residual", "pred_residual", "specular_residual"])# If .images[0..2] only:if any(v is None for v in (albedo, diffuse, residual)) and hasattr(out, "images"):imgs = getattr(out, "images")if isinstance(imgs, (list, tuple)) and len(imgs) >= 3:albedo = imgs[0] if albedo is None else albedodiffuse = imgs[1] if diffuse is None else diffuseresidual = imgs[2] if residual is None else residual# Tensor stack fallbackif any(v is None for v in (albedo, diffuse, residual)):try:t = _to_float_tensor(out)
123456789torch>=2.1accelerate>=0.28diffusers==0.35.2transformers>=4.44peft>=0.17.0huggingface_hub[hf_transfer]==0.30.2Pillow>=10.3safetensors>=0.4.2numpy>=1.2612345678torch>=2.1accelerate>=0.28diffusers==0.33.1transformers>=4.44peft>=0.17.0Pillow>=10.3safetensors>=0.4.2numpy>=1.26
handler.py+82-46
requirements.txt+1-2