Spaces:
Paused
Paused
Upload folder using huggingface_hub
Browse files- README.md +8 -6
- app.py +116 -0
- requirements.txt +11 -0
README.md
CHANGED
|
@@ -1,13 +1,15 @@
|
|
| 1 |
---
|
| 2 |
title: SAM3 Video
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version: 6.
|
| 8 |
-
python_version: '3.12'
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
title: SAM3 Video
|
| 3 |
+
emoji: 🎬
|
| 4 |
+
colorFrom: indigo
|
| 5 |
+
colorTo: blue
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 6.6.0
|
|
|
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
+
short_description: SAM 3 concept tracking across video frames (API)
|
| 11 |
---
|
| 12 |
|
| 13 |
+
`api_track(video, concepts, conf, max_frames)` -> JSON tracks (stable object ids
|
| 14 |
+
across frames) with base64-PNG masks. Backed by the transformers `Sam3VideoModel`
|
| 15 |
+
(facebook/sam3). Requires the `HF_TOKEN` secret with gated access to facebook/sam3.
|
app.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""SAM 3 video concept-tracking API (ZeroGPU), transformers Sam3VideoModel route.
|
| 2 |
+
|
| 3 |
+
Tracks every instance of the given concept(s) across video frames with stable
|
| 4 |
+
object ids. Output schema matches the local video_client parser:
|
| 5 |
+
{version, model, fps, width, height, n_frames, tracks:[{label, object_id,
|
| 6 |
+
frames:[{frame, score, box, mask_png_b64}]}]}
|
| 7 |
+
"""
|
| 8 |
+
import base64
|
| 9 |
+
import io
|
| 10 |
+
import os
|
| 11 |
+
|
| 12 |
+
import gradio as gr
|
| 13 |
+
import numpy as np
|
| 14 |
+
import spaces
|
| 15 |
+
from PIL import Image
|
| 16 |
+
from transformers import Sam3VideoModel, Sam3VideoProcessor
|
| 17 |
+
|
| 18 |
+
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 19 |
+
MODEL_ID = "facebook/sam3"
|
| 20 |
+
|
| 21 |
+
# Built at import on CPU; moved to CUDA inside the @spaces.GPU function.
|
| 22 |
+
processor = Sam3VideoProcessor.from_pretrained(MODEL_ID, token=HF_TOKEN)
|
| 23 |
+
model = Sam3VideoModel.from_pretrained(MODEL_ID, token=HF_TOKEN)
|
| 24 |
+
model.eval()
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _enc(mask_bool: np.ndarray, maxside: int = 512) -> str:
|
| 28 |
+
h, w = mask_bool.shape
|
| 29 |
+
img = Image.fromarray((mask_bool.astype(np.uint8) * 255), "L")
|
| 30 |
+
scale = min(1.0, maxside / max(h, w))
|
| 31 |
+
if scale < 1.0:
|
| 32 |
+
img = img.resize((max(1, int(w * scale)), max(1, int(h * scale))))
|
| 33 |
+
buf = io.BytesIO(); img.save(buf, "PNG")
|
| 34 |
+
return base64.b64encode(buf.getvalue()).decode("ascii")
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _np(x):
|
| 38 |
+
return x.detach().cpu().numpy() if hasattr(x, "detach") else np.asarray(x)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _read_frames(path, max_frames):
|
| 42 |
+
import imageio
|
| 43 |
+
reader = imageio.get_reader(path)
|
| 44 |
+
frames = []
|
| 45 |
+
try:
|
| 46 |
+
for i, fr in enumerate(reader):
|
| 47 |
+
if i >= max_frames:
|
| 48 |
+
break
|
| 49 |
+
frames.append(np.asarray(fr))
|
| 50 |
+
finally:
|
| 51 |
+
reader.close()
|
| 52 |
+
return frames
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@spaces.GPU(duration=300)
|
| 56 |
+
def api_track(video, concepts, conf, max_frames):
|
| 57 |
+
device = "cuda"
|
| 58 |
+
model.to(device)
|
| 59 |
+
concept_list = [c.strip() for c in (concepts or "").split(",") if c.strip()] or ["person"]
|
| 60 |
+
frames = _read_frames(video, int(max_frames))
|
| 61 |
+
if not frames:
|
| 62 |
+
return {"error": "no frames read from video"}
|
| 63 |
+
H, W = frames[0].shape[:2]
|
| 64 |
+
session = processor.init_video_session(
|
| 65 |
+
video=frames, inference_device=device,
|
| 66 |
+
processing_device="cpu", video_storage_device="cpu",
|
| 67 |
+
)
|
| 68 |
+
processor.add_text_prompt(session, concept_list)
|
| 69 |
+
|
| 70 |
+
tracks, obj_label, n_frames = {}, {}, 0
|
| 71 |
+
for mo in model.propagate_in_video_iterator(inference_session=session,
|
| 72 |
+
max_frame_num_to_track=int(max_frames)):
|
| 73 |
+
proc = processor.postprocess_outputs(session, mo)
|
| 74 |
+
fi = int(mo.frame_idx); n_frames = max(n_frames, fi + 1)
|
| 75 |
+
for prompt, oids in (proc.get("prompt_to_obj_ids") or {}).items():
|
| 76 |
+
for oid in oids:
|
| 77 |
+
obj_label.setdefault(int(oid), prompt)
|
| 78 |
+
oids = _np(proc["object_ids"]).tolist()
|
| 79 |
+
scores = _np(proc["scores"]).tolist()
|
| 80 |
+
masks = proc["masks"]
|
| 81 |
+
boxes = _np(proc["boxes"])
|
| 82 |
+
for k, oid in enumerate(oids):
|
| 83 |
+
oid = int(oid)
|
| 84 |
+
m = _np(masks[k])
|
| 85 |
+
if m.ndim == 3:
|
| 86 |
+
m = m[0]
|
| 87 |
+
m = m > 0.5 if m.dtype != bool else m
|
| 88 |
+
tr = tracks.get(oid)
|
| 89 |
+
if tr is None:
|
| 90 |
+
tr = {"label": obj_label.get(oid, concept_list[0]), "object_id": oid, "frames": []}
|
| 91 |
+
tracks[oid] = tr
|
| 92 |
+
tr["frames"].append({"frame": fi, "score": float(scores[k]),
|
| 93 |
+
"box": [float(v) for v in boxes[k]],
|
| 94 |
+
"mask_png_b64": _enc(m)})
|
| 95 |
+
|
| 96 |
+
out_tracks = []
|
| 97 |
+
for oid, tr in tracks.items():
|
| 98 |
+
tr["label"] = obj_label.get(oid, tr["label"])
|
| 99 |
+
if tr["frames"] and max(f["score"] for f in tr["frames"]) >= float(conf):
|
| 100 |
+
out_tracks.append(tr)
|
| 101 |
+
return {"version": "3", "model": MODEL_ID, "fps": 0.0,
|
| 102 |
+
"width": W, "height": H, "n_frames": n_frames, "tracks": out_tracks}
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
with gr.Blocks(title="SAM3 Video") as demo:
|
| 106 |
+
gr.Markdown("# SAM 3 Video Tracking API\nUpload a video, enter comma-separated concepts.")
|
| 107 |
+
with gr.Row():
|
| 108 |
+
vid = gr.File(file_count="single", type="filepath", label="Video (mp4)")
|
| 109 |
+
out = gr.JSON(label="Tracks")
|
| 110 |
+
txt = gr.Textbox(label="Concepts (comma-separated)", value="person")
|
| 111 |
+
conf = gr.Slider(0.0, 1.0, value=0.4, step=0.05, label="Confidence")
|
| 112 |
+
mf = gr.Slider(8, 96, value=48, step=8, label="Max frames")
|
| 113 |
+
gr.Button("Track").click(api_track, [vid, txt, conf, mf], out, api_name="api_track")
|
| 114 |
+
|
| 115 |
+
if __name__ == "__main__":
|
| 116 |
+
demo.queue().launch(show_error=True)
|
requirements.txt
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
transformers==5.9.0
|
| 2 |
+
torch==2.11.0
|
| 3 |
+
torchvision
|
| 4 |
+
gradio==6.6.0
|
| 5 |
+
spaces
|
| 6 |
+
accelerate
|
| 7 |
+
sentencepiece
|
| 8 |
+
pillow
|
| 9 |
+
numpy
|
| 10 |
+
imageio
|
| 11 |
+
imageio-ffmpeg
|