Spaces:
Running on Zero
Running on Zero
load selected variant inside gpu calls, fix get_cmap removal
Browse files3 unmodified lines45678910336 unmodified lines347348349350351352353354355108 unmodified lines464465466467468469470102 unmodified lines57357457557657757857963 unmodified lines6436446456466476486496506516526537 unmodified lines66166266366466566666766866967010 unmodified lines68168268368468568668768868969069114 unmodified lines70670770870971071171271371471571623 unmodified lines74074174274374474574674774874975010 unmodified lines761762763764765766767768769770771226 unmodified lines998999100010011002100310041005100610071008100911 unmodified lines10211022102310241025102610273 unmodified linesimport osimport gradio as grimport matplotlib.cm as cmimport matplotlib.pyplot as pltimport numpy as npimport spaces336 unmodified linesprint("Pascal Context text embeddings computed.")def _init_model():"""Load model + move to GPU + compute text embeddings."""load_variant(_model["name"] or DEFAULT_VARIANT)_move_models_to_device()_ensure_ade20k_embs()108 unmodified linesh, w = spatial.shape[0], spatial.shape[1]depth = PCA(n_components=1).fit_transform(feat).reshape(h, w)depth = (depth - depth.min()) / (depth.max() - depth.min() + 1e-8)colored = cm.get_cmap("inferno")(depth)[:, :, :3].astype(np.float32)return to_uint8(colored)102 unmodified lines"""Colour a depth map with the turbo colormap β PIL Image."""d = depth_map.squeeze()d = (d - d.min()) / (d.max() - d.min() + 1e-8)colored = cm.get_cmap("turbo")(d)[:, :, :3].astype(np.float32)return to_uint8(upsample(colored, h, w))63 unmodified lines# ββ Gradio callbacks ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@spaces.GPUdef on_variant_change(variant_name):load_variant(variant_name)_move_models_to_device()_ensure_ade20k_embs()return (None,None,7 unmodified lines@spaces.GPUdef on_pca_extract(image, resolution, _pca_state):if image is None:return None, None, None, None_init_model()resolution = int(resolution)spatial = extract_features(image, resolution)h, w = image.shape[:2]10 unmodified lines@spaces.GPUdef on_recluster(image, resolution, n_clusters, pca_state):if image is None:gr.Warning("Upload an image first.")return None, pca_state_init_model()resolution = int(resolution)if (pca_state is not None14 unmodified lines@spaces.GPUdef on_zeroseg_custom(image, resolution, class_names_str):if image is None or not class_names_str or not class_names_str.strip():gr.Warning("Upload an image and enter at least one class name.")return None, None, "", ""_init_model()resolution = int(resolution)classes = [c.strip() for c in class_names_str.split(",") if c.strip()]if not classes:23 unmodified lines@spaces.GPUdef on_depth_normals_predict(image, dpt_variant, resolution): # noqa: ARG001"""Run DPT depth and normals prediction."""if image is None:return None, None_init_model()dev = _device()h, w = image.shape[:2]10 unmodified lines@spaces.GPUdef on_segmentation_predict(image, dpt_variant, resolution): # noqa: ARG001"""Run DPT segmentation prediction."""if image is None:return None_init_model()dev = _device()img = Image.fromarray(image).convert("RGB")226 unmodified linespca_btn.click(fn=on_pca_extract,inputs=[pca_input, resolution_dd, pca_state],outputs=[pca_out, depth_out, kmeans_out, pca_state],)recluster_btn.click(fn=on_recluster,inputs=[pca_input, resolution_dd, n_clusters, pca_state],outputs=[kmeans_out, pca_state],)11 unmodified linescustom_btn.click(fn=on_zeroseg_custom,inputs=[custom_input, resolution_dd, custom_classes],outputs=[custom_overlay, custom_mask, custom_detected, custom_undetected],)3 unmodified lines456789336 unmodified lines346347348349350351352353354355356357358359108 unmodified lines468469470471472473474102 unmodified lines57757857958058158258363 unmodified lines6476486496506516526536546556567 unmodified lines66466566666766866967067167267310 unmodified lines68468568668768868969069169269369414 unmodified lines70971071171271371471571671771871923 unmodified lines74374474574674774874975075175275310 unmodified lines764765766767768769770771772773774226 unmodified lines10011002100310041005100610071008100910101011101211 unmodified lines10241025102610271028102910303 unmodified linesimport osimport gradio as grimport matplotlib.pyplot as pltimport numpy as npimport spaces336 unmodified linesprint("Pascal Context text embeddings computed.")def _init_model(name=None):"""Load model + move to GPU + compute text embeddings.Must be called with the requested variant inside each @spaces.GPU function:on ZeroGPU those run in a forked worker, so global state mutated in one call(e.g. by a dropdown handler) does not survive into the next."""load_variant(name or _model["name"] or DEFAULT_VARIANT)_move_models_to_device()_ensure_ade20k_embs()108 unmodified linesh, w = spatial.shape[0], spatial.shape[1]depth = PCA(n_components=1).fit_transform(feat).reshape(h, w)depth = (depth - depth.min()) / (depth.max() - depth.min() + 1e-8)colored = plt.get_cmap("inferno")(depth)[:, :, :3].astype(np.float32)return to_uint8(colored)102 unmodified lines"""Colour a depth map with the turbo colormap β PIL Image."""d = depth_map.squeeze()d = (d - d.min()) / (d.max() - d.min() + 1e-8)colored = plt.get_cmap("turbo")(d)[:, :, :3].astype(np.float32)return to_uint8(upsample(colored, h, w))63 unmodified lines# ββ Gradio callbacks ββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef on_variant_change(variant_name): # noqa: ARG001# Only clears stale outputs. The variant is loaded inside the inference# handlers themselves β loading it here would happen in a ZeroGPU worker# whose state is thrown away when the call returns.return (None,None,7 unmodified lines@spaces.GPUdef on_pca_extract(image, variant, resolution, _pca_state):if image is None:return None, None, None, None_init_model(variant)resolution = int(resolution)spatial = extract_features(image, resolution)h, w = image.shape[:2]10 unmodified lines@spaces.GPUdef on_recluster(image, variant, resolution, n_clusters, pca_state):if image is None:gr.Warning("Upload an image first.")return None, pca_state_init_model(variant)resolution = int(resolution)if (pca_state is not None14 unmodified lines@spaces.GPUdef on_zeroseg_custom(image, variant, resolution, class_names_str):if image is None or not class_names_str or not class_names_str.strip():gr.Warning("Upload an image and enter at least one class name.")return None, None, "", ""_init_model(variant)resolution = int(resolution)classes = [c.strip() for c in class_names_str.split(",") if c.strip()]if not classes:23 unmodified lines@spaces.GPUdef on_depth_normals_predict(image, dpt_variant, resolution):"""Run DPT depth and normals prediction."""if image is None:return None, None_init_model(dpt_variant)dev = _device()h, w = image.shape[:2]10 unmodified lines@spaces.GPUdef on_segmentation_predict(image, dpt_variant, resolution):"""Run DPT segmentation prediction."""if image is None:return None_init_model(dpt_variant)dev = _device()img = Image.fromarray(image).convert("RGB")226 unmodified linespca_btn.click(fn=on_pca_extract,inputs=[pca_input, variant_dd, resolution_dd, pca_state],outputs=[pca_out, depth_out, kmeans_out, pca_state],)recluster_btn.click(fn=on_recluster,inputs=[pca_input, variant_dd, resolution_dd, n_clusters, pca_state],outputs=[kmeans_out, pca_state],)11 unmodified linescustom_btn.click(fn=on_zeroseg_custom,inputs=[custom_input, variant_dd, resolution_dd, custom_classes],outputs=[custom_overlay, custom_mask, custom_detected, custom_undetected],)
app.py+27-24