Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files1234567891011121314151617181920212223242526272829301 unmodified line323334353637383940414243444546474849505115 unmodified lines676869707172737475767778798081828384858687888990919226 unmodified lines11912012112212312412558 unmodified lines1841851861871881891906 unmodified lines19719819920020120220318 unmodified lines2222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403417 unmodified lines3493503513523533543553563573583593 unmodified lines3633643653663673683693703713723733743753763773786 unmodified lines385386387388389390391"""SAM 3 — Image / Video / Panorama / Multi-Class SegmentationHugging Face Spaces app.Requires a GPU-backed Space (T4 or better) and an HF_TOKEN secret with accessto the gated facebook/sam3 checkpoint (request access athttps://huggingface.co/facebook/sam3, then add HF_TOKEN inSettings -> Variables and secrets on this Space)."""import osimport globimport hashlibfrom datetime import datetimeimport cv2import numpy as npimport torchimport gradio as grfrom PIL import Image, ImageDrawfrom huggingface_hub import loginimport spaces# ----------------------------------------------------------------------# Auth (Space secret) -- gated checkpoint download needs this at startup.# ----------------------------------------------------------------------HF_TOKEN = os.environ.get("hf_token")if HF_TOKEN:login(token=HF_TOKEN)print("Logged in to Hugging Face using HF_TOKEN secret.")1 unmodified lineprint("WARNING: HF_TOKEN secret not set. Gated checkpoint download will fail.")print("Add it in this Space's Settings -> Variables and secrets.")DEVICE = "cuda" if torch.cuda.is_available() else "cpu"print(f"Using device={DEVICE}")os.makedirs("/tmp/output", exist_ok=True)IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tif", ".tiff"}VIDEO_EXTS = {".mp4", ".mov", ".avi", ".mkv", ".webm"}MAX_CLASSES = 5# ----------------------------------------------------------------------# Lazy model loaders# ----------------------------------------------------------------------_image_model_cache = {}_video_predictor_cache = {}def _find_bpe_path():15 unmodified linesprint(f"Using bpe_path: {BPE_PATH}")def get_image_processor():if "processor" not in _image_model_cache:from sam3.model_builder import build_sam3_image_modelfrom sam3.model.sam3_image_processor import Sam3Processorprint("Loading SAM 3 image model (checkpoint auto-downloads/caches on first call)...")model = build_sam3_image_model(bpe_path=BPE_PATH, device=DEVICE)model = model.to(DEVICE)_image_model_cache["processor"] = Sam3Processor(model)print("Image model ready.")return _image_model_cache["processor"]def get_video_predictor():if "predictor" not in _video_predictor_cache:from sam3.model_builder import build_sam3_video_predictorprint("Loading SAM 3 video predictor (checkpoint auto-downloads/caches on first call)...")predictor = build_sam3_video_predictor(bpe_path=BPE_PATH, async_loading_frames=True)_video_predictor_cache["predictor"] = predictorprint("Video predictor ready.")return _video_predictor_cache["predictor"]# ----------------------------------------------------------------------26 unmodified linesfor x0 in x_starts:x1 = min(x0 + tile_w, w)tile = image.crop((x0, 0, x1, h))with torch.inference_mode(), torch.autocast(device_type=DEVICE, dtype=torch.bfloat16):state = processor.set_image(tile)out = processor.set_text_prompt(state=state, prompt=prompt)masks_np = _to_numpy_masks(out["masks"])58 unmodified linesper_class_counts = {}if not panorama:with torch.inference_mode(), torch.autocast(device_type=DEVICE, dtype=torch.bfloat16):state = processor.set_image(image)for name in class_names:6 unmodified linesoverlay[combined_mask].astype(np.float32) * (1 - alpha) + color * alpha).astype(np.uint8)else:with torch.inference_mode(), torch.autocast(device_type=DEVICE, dtype=torch.bfloat16):out = processor.set_text_prompt(state=state, prompt=name)masks_np = _to_numpy_masks(out["masks"])per_class_counts[name] = masks_np.shape[0]18 unmodified linesoutputs_per_frame[idx] = frame_output["outputs"]return outputs_per_frame# ----------------------------------------------------------------------# Main inference entrypoint# ----------------------------------------------------------------------# ----------------------------------------------------------------------# 1. Image Inference (Default Duration - Works for ALL users)# ----------------------------------------------------------------------@spaces.GPUdef run_sam3_image(file_path, class_names, timestamp, progress):progress(0.1, desc="Loading image model...")processor = get_image_processor()image = Image.open(file_path).convert("RGB")panorama = is_panorama(image)progress(0.3, desc=f"Segmenting {len(class_names)} class(es)" + (" (panorama tiling)..." if panorama else "..."))result_image, per_class_counts = segment_multiclass_image(processor, image, class_names, panorama=panorama)status = "Found: " + ", ".join(f"{k}={v}" for k, v in per_class_counts.items())progress(0.9, desc="Saving output...")out_path = f"/tmp/output/sam3_overlay_{timestamp}.png"result_image.save(out_path)progress(1.0, desc="Done!")return (gr.update(value=result_image, visible=True),gr.update(visible=False),gr.update(value=out_path, visible=True),status,)# ----------------------------------------------------------------------# 2. Video Inference (High Duration - Works for Space Owners/PRO)# ----------------------------------------------------------------------@spaces.GPU(duration=450)def run_sam3_video(file_path, class_names, timestamp, progress):progress(0.1, desc="Loading video predictor...")from sam3.visualization_utils import save_masklet_videovideo_predictor = get_video_predictor()tracked_classes_str = ", ".join(class_names)progress(0.2, desc="Reading video frames...")cap = cv2.VideoCapture(file_path)video_fps = cap.get(cv2.CAP_PROP_FPS) or 24.0video_frames = []while True:ret, frame = cap.read()if not ret:breakvideo_frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))cap.release()progress(0.3, desc="Tracking objects (multi-pass)...")master_outputs_per_frame = {i: {} for i in range(len(video_frames))}with torch.inference_mode(), torch.autocast(device_type=DEVICE, dtype=torch.bfloat16):for obj_idx, class_name in enumerate(class_names):response = video_predictor.handle_request(request=dict(type="start_session", resource_path=file_path))session_id = response["session_id"]video_predictor.handle_request(request=dict(type="add_prompt",session_id=session_id,frame_index=0,obj_id=obj_idx,text=class_name))for frame_output in video_predictor.handle_stream_request(request=dict(type="propagate_in_video", session_id=session_id, propagation_direction="both")):idx = frame_output["frame_index"]out_data = frame_output["outputs"]if isinstance(out_data, dict):for k, v in out_data.items():if k not in master_outputs_per_frame[idx]:master_outputs_per_frame[idx][k] = []if isinstance(v, list):master_outputs_per_frame[idx][k].extend(v)else:master_outputs_per_frame[idx][k].append(v)video_predictor.handle_request(request=dict(type="close_session", session_id=session_id))progress(0.85, desc="Rendering combined overlay video...")out_path = f"/tmp/output/sam3_overlay_{timestamp}.mp4"for idx in master_outputs_per_frame:for k, v_list in master_outputs_per_frame[idx].items():if isinstance(v_list, list) and len(v_list) > 0:if torch.is_tensor(v_list[0]):master_outputs_per_frame[idx][k] = torch.cat(v_list, dim=0)elif isinstance(v_list[0], np.ndarray):master_outputs_per_frame[idx][k] = np.concatenate(v_list, axis=0)save_masklet_video(video_frames, master_outputs_per_frame, out_path=out_path, alpha=0.5, fps=video_fps)progress(1.0, desc="Done!")status = f"Tracked {len(video_frames)} frames for: {tracked_classes_str}"return (gr.update(visible=False),gr.update(value=out_path, visible=True),gr.update(value=out_path, visible=True),status,)# ----------------------------------------------------------------------# 3. Main Router (Checks file type before requesting GPU)# ----------------------------------------------------------------------def run_sam3(file_path, prompt, progress=gr.Progress()):if file_path is None:raise gr.Error("Please upload an image or video first.")if not prompt or not prompt.strip():7 unmodified linesext = os.path.splitext(file_path)[1].lower()timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")# Route to the appropriate function based on file typeif ext in IMAGE_EXTS:return run_sam3_image(file_path, class_names, timestamp, progress)elif ext in VIDEO_EXTS:return run_sam3_video(file_path, class_names, timestamp, progress)else:raise gr.Error(f"Unsupported file type: {ext}")3 unmodified lines# ----------------------------------------------------------------------with gr.Blocks(title="SAM 3 Segmentation") as demo:gr.Markdown("## 🟦 SAM 3 — Image / Video / Panorama / Multi-Class Segmentation\n""Upload an image or video, type up to 5 comma-separated classes, hit Run. ""Panoramas (very wide images) are auto-tiled. Multiple classes are merged into one overlay with a legend.")with gr.Row():with gr.Column(scale=1):file_input = gr.File(label="Upload image or video", file_types=["image", "video"], type="filepath")prompt_input = gr.Textbox(label="Text prompt(s) — comma-separated, up to 5 classes exp . (person , floor , beam , column , wall)",placeholder="e.g. person, dog, red car",)run_btn = gr.Button("▶ Run Segmentation", variant="primary")6 unmodified linesrun_btn.click(fn=run_sam3,inputs=[file_input, prompt_input],outputs=[image_output, video_output, download_output, status_box],)12345678910111213141516171819202122232425262728293031321 unmodified line34353637383940414243444546474849505152535455565758596061626315 unmodified lines79808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817926 unmodified lines20620720820921021121258 unmodified lines2712722732742752762776 unmodified lines28428528628728828929018 unmodified lines3093103113123133143153163173183193203213223237 unmodified lines3313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064073 unmodified lines4114124134144154164174184194204214224234244254264274284294304314326 unmodified lines439440441442443444445"""SAM 3 / SAM 3.1 — Image / Video / Panorama / Multi-Class SegmentationHugging Face Spaces app (ZeroGPU).Requires:- ZeroGPU hardware selected under Settings -> Hardware- An HF_TOKEN secret (Settings -> Variables and secrets) with access to the gatedfacebook/sam3 and facebook/sam3.1 checkpoints (request access athttps://huggingface.co/facebook/sam3 and https://huggingface.co/facebook/sam3.1)"""import osimport globimport hashlibimport subprocessfrom datetime import datetimeimport cv2import numpy as npimport torchimport gradio as grimport spacesfrom PIL import Image, ImageDrawfrom huggingface_hub import login, list_repo_files, hf_hub_download# ----------------------------------------------------------------------# Auth (Space secret) -- gated checkpoint download needs this at startup.# ----------------------------------------------------------------------HF_TOKEN = os.environ.get("HF_TOKEN")if HF_TOKEN:login(token=HF_TOKEN)print("Logged in to Hugging Face using HF_TOKEN secret.")1 unmodified lineprint("WARNING: HF_TOKEN secret not set. Gated checkpoint download will fail.")print("Add it in this Space's Settings -> Variables and secrets.")os.makedirs("/tmp/output", exist_ok=True)IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tif", ".tiff"}VIDEO_EXTS = {".mp4", ".mov", ".avi", ".mkv", ".webm"}MAX_CLASSES = 5VERSION_REPOS = {"SAM 3.1": "facebook/sam3.1","SAM 3": "facebook/sam3",}DEFAULT_VERSION = "SAM 3.1"def get_device():"""ZeroGPU only attaches a GPU inside a @spaces.GPU-decorated call, so this mustbe evaluated at call time, never at module import time."""return "cuda" if torch.cuda.is_available() else "cpu"# ----------------------------------------------------------------------# Lazy, version-aware model loaders# ----------------------------------------------------------------------_model_cache = {} # version -> {"processor": ..., "predictor": ...}_current_version = {"value": None} # which version is currently loaded on GPUdef _find_bpe_path():15 unmodified linesprint(f"Using bpe_path: {BPE_PATH}")def _resolve_checkpoint_path(repo_id):"""Lists the repo's actual files and picks the right weight file automatically,instead of assuming a filename that may differ between repos/versions."""files = list_repo_files(repo_id)weight_files = [f for f in files if f.endswith(".pt") or f.endswith(".safetensors")]assert weight_files, f"No .pt/.safetensors checkpoint file found in {repo_id}"pt_files = [f for f in weight_files if f.endswith(".pt")]chosen = pt_files[0] if pt_files else weight_files[0]print(f"Resolved checkpoint file in {repo_id}: {chosen}")return hf_hub_download(repo_id=repo_id, filename=chosen)def _unload_current_model():"""Frees GPU memory from whichever version is currently loaded before switching."""if _current_version["value"] is not None:old = _current_version["value"]_model_cache.pop(old, None)if torch.cuda.is_available():torch.cuda.empty_cache()print(f"Unloaded {old} to free GPU memory.")def get_image_processor(version=DEFAULT_VERSION):if version not in VERSION_REPOS:raise ValueError(f"Unknown version '{version}', expected one of {list(VERSION_REPOS)}")if version not in _model_cache or "processor" not in _model_cache.get(version, {}):if _current_version["value"] is not None and _current_version["value"] != version:_unload_current_model()from sam3.model_builder import build_sam3_image_modelfrom sam3.model.sam3_image_processor import Sam3Processorrepo_id = VERSION_REPOS[version]print(f"Loading {version} image model from {repo_id} (downloads/caches on first call)...")ckpt_path = _resolve_checkpoint_path(repo_id)model = build_sam3_image_model(bpe_path=BPE_PATH, checkpoint_path=ckpt_path, device=get_device())model = model.to(get_device())_model_cache.setdefault(version, {})["processor"] = Sam3Processor(model)_current_version["value"] = versionprint(f"{version} image model ready.")return _model_cache[version]["processor"]def get_video_predictor(version=DEFAULT_VERSION):if version not in VERSION_REPOS:raise ValueError(f"Unknown version '{version}', expected one of {list(VERSION_REPOS)}")if version not in _model_cache or "predictor" not in _model_cache.get(version, {}):if _current_version["value"] is not None and _current_version["value"] != version:_unload_current_model()from sam3.model_builder import build_sam3_video_predictorrepo_id = VERSION_REPOS[version]print(f"Loading {version} video predictor from {repo_id} (downloads/caches on first call)...")ckpt_path = _resolve_checkpoint_path(repo_id)predictor = build_sam3_video_predictor(bpe_path=BPE_PATH, checkpoint_path=ckpt_path, async_loading_frames=True)_model_cache.setdefault(version, {})["predictor"] = predictor_current_version["value"] = versionprint(f"{version} video predictor ready.")return _model_cache[version]["predictor"]# ----------------------------------------------------------------------# Video repair (fixes "moov atom not found" / truncated uploads)# ----------------------------------------------------------------------def ensure_readable_video(file_path):"""cv2/SAM3 can fail on MP4s with a missing/misplaced moov atom (common with largeor truncated uploads). Remux through ffmpeg first -- this fixes most container-levelissues without re-encoding. Raises a clear gr.Error if the file is genuinely corrupted."""fixed_path = file_path + "_fixed.mp4"try:result = subprocess.run(["ffmpeg", "-y", "-v", "error", "-i", file_path,"-c", "copy", "-movflags", "+faststart", fixed_path],capture_output=True, text=True, timeout=180,)except FileNotFoundError:raise gr.Error("ffmpeg is not installed on this Space -- check packages.txt includes 'ffmpeg'.")except subprocess.TimeoutExpired:raise gr.Error("Video repair step timed out -- the file may be too large or genuinely corrupted.")if result.returncode != 0 or not os.path.exists(fixed_path) or os.path.getsize(fixed_path) == 0:stderr_tail = result.stderr[-500:] if result and result.stderr else "unknown error"raise gr.Error("This video file appears to be corrupted or incompletely uploaded ""(missing video index / moov atom). Try re-exporting or re-uploading it. "f"ffmpeg said: {stderr_tail}")return fixed_path# ----------------------------------------------------------------------26 unmodified linesfor x0 in x_starts:x1 = min(x0 + tile_w, w)tile = image.crop((x0, 0, x1, h))with torch.inference_mode(), torch.autocast(device_type=get_device(), dtype=torch.bfloat16):state = processor.set_image(tile)out = processor.set_text_prompt(state=state, prompt=prompt)masks_np = _to_numpy_masks(out["masks"])58 unmodified linesper_class_counts = {}if not panorama:with torch.inference_mode(), torch.autocast(device_type=get_device(), dtype=torch.bfloat16):state = processor.set_image(image)for name in class_names:6 unmodified linesoverlay[combined_mask].astype(np.float32) * (1 - alpha) + color * alpha).astype(np.uint8)else:with torch.inference_mode(), torch.autocast(device_type=get_device(), dtype=torch.bfloat16):out = processor.set_text_prompt(state=state, prompt=name)masks_np = _to_numpy_masks(out["masks"])per_class_counts[name] = masks_np.shape[0]18 unmodified linesoutputs_per_frame[idx] = frame_output["outputs"]return outputs_per_frame# ----------------------------------------------------------------------# Main inference entrypoint# ----------------------------------------------------------------------# ZeroGPU only grants a GPU for the duration of a decorated call. duration is the max# seconds this call is allowed to hold the GPU -- raise it if longer videos time out# (check your account's max allowed duration in the ZeroGPU docs if this errors).@spaces.GPU(duration=120)def run_sam3(file_path, prompt, model_version, progress=gr.Progress()):if file_path is None:raise gr.Error("Please upload an image or video first.")if not prompt or not prompt.strip():7 unmodified linesext = os.path.splitext(file_path)[1].lower()timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")if ext in IMAGE_EXTS:progress(0.1, desc=f"Loading {model_version} image model...")processor = get_image_processor(model_version)image = Image.open(file_path).convert("RGB")panorama = is_panorama(image)progress(0.3, desc=f"Segmenting {len(class_names)} class(es)" + (" (panorama tiling)..." if panorama else "..."))result_image, per_class_counts = segment_multiclass_image(processor, image, class_names, panorama=panorama)status = f"[{model_version}] Found: " + ", ".join(f"{k}={v}" for k, v in per_class_counts.items())progress(0.9, desc="Saving output...")out_path = f"/tmp/output/sam3_overlay_{timestamp}.png"result_image.save(out_path)progress(1.0, desc="Done!")return (gr.update(value=result_image, visible=True),gr.update(visible=False),gr.update(value=out_path, visible=True),status,)elif ext in VIDEO_EXTS:progress(0.05, desc="Checking video file...")file_path = ensure_readable_video(file_path)progress(0.15, desc=f"Loading {model_version} video predictor...")from sam3.visualization_utils import save_masklet_videovideo_predictor = get_video_predictor(model_version)video_prompt = class_names[0]note = ""if len(class_names) > 1:note = f" (only first class '{video_prompt}' is tracked for video)"progress(0.25, desc="Reading video frames...")cap = cv2.VideoCapture(file_path)video_fps = cap.get(cv2.CAP_PROP_FPS) or 24.0video_frames = []while True:ret, frame = cap.read()if not ret:breakvideo_frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))cap.release()progress(0.4, desc="Tracking object through video...")with torch.inference_mode(), torch.autocast(device_type=get_device(), dtype=torch.bfloat16):response = video_predictor.handle_request(request=dict(type="start_session", resource_path=file_path))session_id = response["session_id"]video_predictor.handle_request(request=dict(type="add_prompt", session_id=session_id, frame_index=0, text=video_prompt))outputs_per_frame = propagate_in_video(video_predictor, session_id)progress(0.85, desc="Rendering overlay video...")out_path = f"/tmp/output/sam3_overlay_{timestamp}.mp4"save_masklet_video(video_frames, outputs_per_frame, out_path=out_path, alpha=0.5, fps=video_fps)video_predictor.handle_request(request=dict(type="close_session", session_id=session_id))progress(1.0, desc="Done!")status = f"[{model_version}] Tracked {len(outputs_per_frame)} frames for '{video_prompt}'.{note}"return (gr.update(visible=False),gr.update(value=out_path, visible=True),gr.update(value=out_path, visible=True),status,)else:raise gr.Error(f"Unsupported file type: {ext}")3 unmodified lines# ----------------------------------------------------------------------with gr.Blocks(title="SAM 3 Segmentation") as demo:gr.Markdown("## 🟦 SAM 3 / SAM 3.1 — Image / Video / Panorama / Multi-Class Segmentation\n""Upload an image or video, pick a model version, type up to 5 comma-separated classes, hit Run. ""Panoramas (very wide images) are auto-tiled. Multiple classes are merged into one overlay with a legend.")with gr.Row():with gr.Column(scale=1):file_input = gr.File(label="Upload image or video", file_types=["image", "video"], type="filepath")model_toggle = gr.Radio(choices=["SAM 3.1", "SAM 3"],value=DEFAULT_VERSION,label="Model version",info="SAM 3.1 = faster multi-object video tracking (Object Multiplex). Toggle to SAM 3 for the original.",)prompt_input = gr.Textbox(label="Text prompt(s) — comma-separated, up to 5 classes",placeholder="e.g. person, dog, red car",)run_btn = gr.Button("▶ Run Segmentation", variant="primary")6 unmodified linesrun_btn.click(fn=run_sam3,inputs=[file_input, prompt_input, model_toggle],outputs=[image_output, video_output, download_output, status_box],)
app.py+206-152