Spaces:
Build error
Build error
Commit ·
53a8438
1
Parent(s): 9b9cd68
requirement fix
Browse filesFiles changed (9)
12 unmodified lines13141516171819180 unmodified lines20020120220320420513 unmodified lines21922022122222322433 unmodified lines25825926026126226340 unmodified lines3043053063073083093103113123133143153163173183193203213223231 unmodified line32532632732832933025 unmodified lines3563573583593603613622 unmodified lines365366367368369370371162 unmodified lines53453553653753853954012 unmodified linesimport jsonimport torchvisionimport torchfrom tools.painter import mask_painter# download checkpointsdef download_checkpoint(url, folder, filename):180 unmodified lines# tracking vosdef vos_tracking_video(video_state, interactive_state, mask_dropdown):model.xmem.clear_memory()if interactive_state["track_end_number"]:following_frames = video_state["origin_images"][video_state["select_frame_number"]:interactive_state["track_end_number"]]13 unmodified linestemplate_mask = video_state["masks"][video_state["select_frame_number"]]fps = video_state["fps"]masks, logits, painted_images = model.generator(images=following_frames, template_mask=template_mask)if interactive_state["track_end_number"]:video_state["masks"][video_state["select_frame_number"]:interactive_state["track_end_number"]] = masks33 unmodified lines# inpaintdef inpaint_video(video_state, interactive_state, mask_dropdown):frames = np.asarray(video_state["origin_images"])fps = video_state["fps"]inpaint_masks = np.asarray(video_state["masks"])40 unmodified linestorchvision.io.write_video(output_path, frames, fps=fps, video_codec="libx264")return output_path# check and download checkpoints if neededSAM_checkpoint = "sam_vit_h_4b8939.pth"sam_checkpoint_url = "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth"xmem_checkpoint = "XMem-s012.pth"xmem_checkpoint_url = "https://github.com/hkchengrex/XMem/releases/download/v1.0/XMem-s012.pth"e2fgvi_checkpoint = "E2FGVI-HQ-CVPR22.pth"e2fgvi_checkpoint_id = "10wGdKSUOie0XmCr8SQ2A2FeDe-mfn5w3"folder ="./checkpoints"SAM_checkpoint = download_checkpoint(sam_checkpoint_url, folder, SAM_checkpoint)xmem_checkpoint = download_checkpoint(xmem_checkpoint_url, folder, xmem_checkpoint)e2fgvi_checkpoint = download_checkpoint_from_google_drive(e2fgvi_checkpoint_id, folder, e2fgvi_checkpoint)# args, defined in track_anything.pyargs = parse_augment()# args.port = 12315# args.device = "cuda:2"# args.mask_save = True1 unmodified line# initialize sam, xmem, e2fgvi modelsmodel = TrackingAnything(SAM_checkpoint, xmem_checkpoint, e2fgvi_checkpoint,args)with gr.Blocks() as iface:"""state for25 unmodified lines"fps": 30})with gr.Row():# for user video input2 unmodified linesvideo_input = gr.Video(autosize=True)with gr.Column():video_info = gr.Textbox()video_info = gr.Textbox(value="Due to server restrictions, please upload a video that is no longer than 2 minutes. If you want to use the inpaint function, it is best to download and use a machine with more VRAM locally. \Alternatively, you can use the resize ratio slider to scale down the original image to around 360P resolution for faster processing.")resize_ratio_slider = gr.Slider(minimum=0.02, maximum=1, step=0.02, value=1, label="Resize ratio", visible=True)162 unmodified lines# cache_examples=True,)iface.queue(concurrency_count=1)iface.launch(debug=True, enable_queue=True)12 unmodified lines13141516171819202122232425180 unmodified lines20620720820921021121213 unmodified lines22622722822923023123223333 unmodified lines26726826927027127227340 unmodified lines3143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453461 unmodified line34834935035135235335435535635735835925 unmodified lines3853863873883893903913922 unmodified lines395396397398399400401162 unmodified lines56456556656756856957012 unmodified linesimport jsonimport torchvisionimport torchfrom tools.interact_tools import SamControlerfrom tracker.base_tracker import BaseTrackerfrom tools.painter import mask_paintertry:from mmcv.cnn import ConvModuleexcept:os.system("mim install mmcv")# download checkpointsdef download_checkpoint(url, folder, filename):180 unmodified lines# tracking vosdef vos_tracking_video(video_state, interactive_state, mask_dropdown):model.xmem.clear_memory()if interactive_state["track_end_number"]:following_frames = video_state["origin_images"][video_state["select_frame_number"]:interactive_state["track_end_number"]]13 unmodified linestemplate_mask = video_state["masks"][video_state["select_frame_number"]]fps = video_state["fps"]masks, logits, painted_images = model.generator(images=following_frames, template_mask=template_mask)# clear GPU memorymodel.xmem.clear_memory()if interactive_state["track_end_number"]:video_state["masks"][video_state["select_frame_number"]:interactive_state["track_end_number"]] = masks33 unmodified lines# inpaintdef inpaint_video(video_state, interactive_state, mask_dropdown):frames = np.asarray(video_state["origin_images"])fps = video_state["fps"]inpaint_masks = np.asarray(video_state["masks"])40 unmodified linestorchvision.io.write_video(output_path, frames, fps=fps, video_codec="libx264")return output_path# args, defined in track_anything.pyargs = parse_augment()# check and download checkpoints if neededSAM_checkpoint_dict = {'vit_h': "sam_vit_h_4b8939.pth",'vit_l': "sam_vit_l_0b3195.pth","vit_b": "sam_vit_b_01ec64.pth"}SAM_checkpoint_url_dict = {'vit_h': "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth",'vit_l': "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth",'vit_b': "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth"}sam_checkpoint = SAM_checkpoint_dict[args.sam_model_type]sam_checkpoint_url = SAM_checkpoint_url_dict[args.sam_model_type]xmem_checkpoint = "XMem-s012.pth"xmem_checkpoint_url = "https://github.com/hkchengrex/XMem/releases/download/v1.0/XMem-s012.pth"e2fgvi_checkpoint = "E2FGVI-HQ-CVPR22.pth"e2fgvi_checkpoint_id = "10wGdKSUOie0XmCr8SQ2A2FeDe-mfn5w3"folder ="./checkpoints"SAM_checkpoint = download_checkpoint(sam_checkpoint_url, folder, sam_checkpoint)xmem_checkpoint = download_checkpoint(xmem_checkpoint_url, folder, xmem_checkpoint)e2fgvi_checkpoint = download_checkpoint_from_google_drive(e2fgvi_checkpoint_id, folder, e2fgvi_checkpoint)# args.port = 12315# args.device = "cuda:2"# args.mask_save = True1 unmodified line# initialize sam, xmem, e2fgvi modelsmodel = TrackingAnything(SAM_checkpoint, xmem_checkpoint, e2fgvi_checkpoint,args)title = """<p><h1 align="center">Track-Anything</h1></p>"""description = """<p>Gradio demo for Track Anything, a flexible and interactive tool for video object tracking, segmentation, and inpainting. I To use it, simply upload your video, or click one of the examples to load them. Code: <a href="https://github.com/gaomingqi/Track-Anything">https://github.com/gaomingqi/Track-Anything</a> <a href="https://huggingface.co/spaces/watchtowerss/Track-Anything?duplicate=true"><img style="display: inline; margin-top: 0em; margin-bottom: 0em" src="https://bit.ly/3gLdBN6" alt="Duplicate Space" /></a></p>"""with gr.Blocks() as iface:"""state for25 unmodified lines"fps": 30})gr.Markdown(title)gr.Markdown(description)with gr.Row():# for user video input2 unmodified linesvideo_input = gr.Video(autosize=True)with gr.Column():video_info = gr.Textbox()resize_info = gr.Textbox(value="Due to server restrictions, please upload a video that is no longer than 2 minutes. If you want to use the inpaint function, it is best to download and use a machine with more VRAM locally. \Alternatively, you can use the resize ratio slider to scale down the original image to around 360P resolution for faster processing.")resize_ratio_slider = gr.Slider(minimum=0.02, maximum=1, step=0.02, value=1, label="Resize ratio", visible=True)162 unmodified lines# cache_examples=True,)iface.queue(concurrency_count=1)iface.launch(debug=True)
6 unmodified lines78910111253 unmodified lines6667686970717273747576777879806 unmodified lines878889909192936 unmodified linesimport cv2import importlibimport numpy as npfrom inpainter.util.tensor_util import resize_frames, resize_masks53 unmodified linesif ratio == 1:size = Noneelse:size = (int(W*ratio), int(H*ratio))if size[0] % 2 > 0:size[0] += 1if size[1] % 2 > 0:size[1] += 1masks = np.expand_dims(masks, axis=3) # expand to T, H, W, 1binary_masks = resize_masks(masks, size)frames = resize_frames(frames, size) # T, H, W, 3# frames and binary_masks are numpy arraysh, w = frames.shape[1:3]6 unmodified linesimgs, masks = imgs.to(self.device), masks.to(self.device)comp_frames = [None] * video_lengthfor f in range(0, video_length, self.neighbor_stride):neighbor_ids = [i for i in range(max(0, f - self.neighbor_stride),min(video_length, f + self.neighbor_stride + 1))6 unmodified lines789101112131453 unmodified lines6869707172737475767778798081826 unmodified lines899091929394956 unmodified linesimport cv2import importlibimport numpy as npfrom tqdm import tqdmfrom inpainter.util.tensor_util import resize_frames, resize_masks53 unmodified linesif ratio == 1:size = Noneelse:size = [int(W*ratio), int(H*ratio)]if size[0] % 2 > 0:size[0] += 1if size[1] % 2 > 0:size[1] += 1masks = np.expand_dims(masks, axis=3) # expand to T, H, W, 1binary_masks = resize_masks(masks, tuple(size))frames = resize_frames(frames, tuple(size)) # T, H, W, 3# frames and binary_masks are numpy arraysh, w = frames.shape[1:3]6 unmodified linesimgs, masks = imgs.to(self.device), masks.to(self.device)comp_frames = [None] * video_lengthfor f in tqdm(range(0, video_length, self.neighbor_stride), desc='Inpainting image'):neighbor_ids = [i for i in range(max(0, f - self.neighbor_stride),min(video_length, f + self.neighbor_stride + 1))
127 unmodified lines128129130131132133134135127 unmodified lineswindows: (B*num_windows, T*window_size*window_size, C)"""B, T, H, W, C = x.shapex = x.view(B, T, H // window_size[0], window_size[0], W // window_size[1],window_size[1], C)windows = x.permute(0, 2, 4, 1, 3, 5, 6).contiguous().view(-1, T * window_size[0] * window_size[1], C)return windows127 unmodified lines128129130131132133134135136137127 unmodified lineswindows: (B*num_windows, T*window_size*window_size, C)"""B, T, H, W, C = x.shapex = x.view(B, T, H // window_size[0], window_size[0], W // window_size[1],window_size[1], C)windows = x.permute(0, 2, 4, 1, 3, 5, 6).contiguous().view(-1, T * window_size[0] * window_size[1], C)return windows
9 unmodified lines101112131415161718199 unmodified linesopencv-pythonpycocotoolsmatplotlibonnxruntimeonnxmetaseg==0.6.1pyyamlavmmcv-fullmmengine9 unmodified lines101112131415169 unmodified linesopencv-pythonpycocotoolsmatplotlibpyyamlavopenmimtqdm
12345 unmodified lines10111213141516171820 unmodified lines394041424344455 unmodified lines51525354555657import PILfrom tools.interact_tools import SamControlerfrom tracker.base_tracker import BaseTrackerfrom inpainter.base_inpainter import BaseInpainter5 unmodified linesclass TrackingAnything():def __init__(self, sam_checkpoint, xmem_checkpoint, e2fgvi_checkpoint, args):self.args = argsself.samcontroler = SamControler(sam_checkpoint, args.sam_model_type, args.device)self.xmem = BaseTracker(xmem_checkpoint, device=args.device)self.baseinpainter = BaseInpainter(e2fgvi_checkpoint, args.device)# def inference_step(self, first_flag: bool, interact_flag: bool, image: np.ndarray,# same_image_flag: bool, points:np.ndarray, labels: np.ndarray, logits: np.ndarray=None, multimask=True):# if first_flag:20 unmodified linesmasks = []logits = []painted_images = []for i in range(len(images)):if i ==0:mask, logit, painted_image = self.xmem.track(images[i], template_mask)masks.append(mask)5 unmodified linesmasks.append(mask)logits.append(logit)painted_images.append(painted_image)print("tracking image {}".format(i))return masks, logits, painted_images1234565 unmodified lines12131415161718192021222320 unmodified lines444546474849505 unmodified lines565758596061import PILfrom tqdm import tqdmfrom tools.interact_tools import SamControlerfrom tracker.base_tracker import BaseTrackerfrom inpainter.base_inpainter import BaseInpainter5 unmodified linesclass TrackingAnything():def __init__(self, sam_checkpoint, xmem_checkpoint, e2fgvi_checkpoint, args):self.args = argsself.sam_checkpoint = sam_checkpointself.xmem_checkpoint = xmem_checkpointself.e2fgvi_checkpoint = e2fgvi_checkpointself.samcontroler = SamControler(self.sam_checkpoint, args.sam_model_type, args.device)self.xmem = BaseTracker(self.xmem_checkpoint, device=args.device)self.baseinpainter = BaseInpainter(self.e2fgvi_checkpoint, args.device)# def inference_step(self, first_flag: bool, interact_flag: bool, image: np.ndarray,# same_image_flag: bool, points:np.ndarray, labels: np.ndarray, logits: np.ndarray=None, multimask=True):# if first_flag:20 unmodified linesmasks = []logits = []painted_images = []for i in tqdm(range(len(images)), desc="Tracking image"):if i ==0:mask, logit, painted_image = self.xmem.track(images[i], template_mask)masks.append(mask)5 unmodified linesmasks.append(mask)logits.append(logit)painted_images.append(painted_image)return masks, logits, painted_images
125 unmodified lines126127128129130131125 unmodified linesdef clear_memory(self):self.tracker.clear_memory()self.mapper.clear_labels()## how to use:125 unmodified lines126127128129130131132125 unmodified linesdef clear_memory(self):self.tracker.clear_memory()self.mapper.clear_labels()torch.cuda.empty_cache()## how to use:
app.py+38-8
assets/avengers.gif

Large File Pointer Details
- SHA256: 9193a028c2e968ff7a7ee222ccc27166a5fbbe40a4d971cee13eba519134c5cf
- Pointer size: 133 Bytes
- Size of remote file: 99.2 MB

Large File Pointer Details
- SHA256: 5e07b86ee4cf002b3481c71e2038c03f4420883c3be78220dafbc4b59abfb32d
- Pointer size: 133 Bytes
- Size of remote file: 30 MB
inpainter/.DS_Store
inpainter/base_inpainter.py+6-4
inpainter/model/modules/tfocal_transformer_hq.py+2
requirements.txt+2-5
track_anything.py+10-6
tracker/.DS_Store
tracker/base_tracker.py+1