Spaces:
Build error
Build error
Commit ·
3c7c9f9
1
Parent(s): 6738b38
operation prompt version
Browse filesFiles changed (2)
- app.py+59-36
- inpainter/base_inpainter.py+10-10
102 unmodified lines1031041051061071081091 unmodified line11111211311411511611712 unmodified lines13013113213313413513613713813914014114214314430 unmodified lines1751761771781791801811821831841851861871881891901911921931941951961971981993 unmodified lines20320420520620720820921021121221321412 unmodified lines22722822923023123226 unmodified lines2592602612622632642653 unmodified lines26927027127227327411 unmodified lines28628728828929029129229329429547 unmodified lines34334434534634734834946 unmodified lines39639739839940040140240340427 unmodified lines4324334344354364374384394404414424433 unmodified lines4474484494504514524534544554564574584594604614622 unmodified lines46546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450525 unmodified lines5315325335345355365374 unmodified lines5425435445455465475482 unmodified lines5515525535545555565578 unmodified lines566567568569570571572102 unmodified lines"fps": fps}video_info = "Video Name: {}, FPS: {}, Total Frames: {}, Image Size:{}".format(video_state["video_name"], video_state["fps"], len(frames), image_size)model.samcontroler.sam_controler.reset_image()model.samcontroler.sam_controler.set_image(video_state["origin_images"][0])return video_state, video_info, video_state["origin_images"][0], gr.update(visible=True, maximum=len(frames), value=1), gr.update(visible=True, maximum=len(frames), value=len(frames)), \1 unmodified linegr.update(visible=True), gr.update(visible=True), \gr.update(visible=True), gr.update(visible=True), \gr.update(visible=True), gr.update(visible=True), \gr.update(visible=True), gr.update(visible=True)def run_example(example):return video_input12 unmodified lines# update the masks when select a new template frame# if video_state["masks"][image_selection_slider] is not None:# video_state["painted_images"][image_selection_slider] = mask_painter(video_state["origin_images"][image_selection_slider], video_state["masks"][image_selection_slider])return video_state["painted_images"][image_selection_slider], video_state, interactive_state# set the tracking end framedef get_end_number(track_pause_number_slider, video_state, interactive_state):interactive_state["track_end_number"] = track_pause_number_sliderreturn video_state["painted_images"][track_pause_number_slider],interactive_statedef get_resize_ratio(resize_ratio_slider, interactive_state):interactive_state["resize_ratio"] = resize_ratio_slider30 unmodified linesvideo_state["logits"][video_state["select_frame_number"]] = logitvideo_state["painted_images"][video_state["select_frame_number"]] = painted_imagereturn painted_image, video_state, interactive_statedef add_multi_mask(video_state, interactive_state, mask_dropdown):mask = video_state["masks"][video_state["select_frame_number"]]interactive_state["multi_mask"]["masks"].append(mask)interactive_state["multi_mask"]["mask_names"].append("mask_{:03d}".format(len(interactive_state["multi_mask"]["masks"])))mask_dropdown.append("mask_{:03d}".format(len(interactive_state["multi_mask"]["masks"])))select_frame = show_mask(video_state, interactive_state, mask_dropdown)return interactive_state, gr.update(choices=interactive_state["multi_mask"]["mask_names"], value=mask_dropdown), select_frame, [[],[]]def clear_click(video_state, click_state):click_state = [[],[]]template_frame = video_state["origin_images"][video_state["select_frame_number"]]return template_frame, click_statedef remove_multi_mask(interactive_state):interactive_state["multi_mask"]["mask_names"]= []interactive_state["multi_mask"]["masks"] = []return interactive_statedef show_mask(video_state, interactive_state, mask_dropdown):mask_dropdown.sort()3 unmodified linesmask_number = int(mask_dropdown[i].split("_")[1]) - 1mask = interactive_state["multi_mask"]["masks"][mask_number]select_frame = mask_painter(select_frame, mask.astype('uint8'), mask_color=mask_number+2)return select_frame# 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"]]12 unmodified lineselse:template_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()26 unmodified linesi+=1# save_mask(video_state["masks"], video_state["video_name"])#### shanggao code for mask savereturn video_output, video_state, interactive_state# extracting masks from mask_dropdown# def extract_sole_mask(video_state, mask_dropdown):3 unmodified lines# inpaintdef inpaint_video(video_state, interactive_state, mask_dropdown):frames = np.asarray(video_state["origin_images"])fps = video_state["fps"]11 unmodified linescontinueinpaint_masks[inpaint_masks==i] = 0# inpaint for videosinpainted_frames = model.baseinpainter.inpaint(frames, inpaint_masks, ratio=interactive_state["resize_ratio"]) # numpy array, T, H, W, 3video_output = generate_video_from_frames(inpainted_frames, output_path="./result/inpaint/{}".format(video_state["video_name"]), fps=fps) # import video_input to name the output videoreturn video_output# generate video after vos inference47 unmodified linesSAM_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 = True46 unmodified lineswith gr.Row(scale=0.4):video_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)27 unmodified linestrack_pause_number_slider = gr.Slider(minimum=1, maximum=100, step=1, value=1, label="Track end frames", visible=False)with gr.Column():mask_dropdown = gr.Dropdown(multiselect=True, value=[], label="Mask_select", info=".", visible=False)remove_mask_button = gr.Button(value="Remove mask", interactive=True, visible=False)video_output = gr.Video(autosize=True, visible=False).style(height=360)with gr.Row():tracking_video_predict_button = gr.Button(value="Tracking", visible=False)inpaint_video_predict_button = gr.Button(value="Inpaint", visible=False)# first step: get the video informationextract_frames_button.click(3 unmodified lines],outputs=[video_state, video_info, template_frame,image_selection_slider, track_pause_number_slider,point_prompt, click_mode, clear_button_click, Add_mask_button, template_frame,tracking_video_predict_button, video_output, mask_dropdown, remove_mask_button, inpaint_video_predict_button])# second step: select images from sliderimage_selection_slider.release(fn=select_template,inputs=[image_selection_slider, video_state, interactive_state],outputs=[template_frame, video_state, interactive_state], api_name="select_image")track_pause_number_slider.release(fn=get_end_number,inputs=[track_pause_number_slider, video_state, interactive_state],outputs=[template_frame, interactive_state], api_name="end_image")resize_ratio_slider.release(fn=get_resize_ratio,inputs=[resize_ratio_slider, interactive_state],outputs=[interactive_state], api_name="resize_ratio")2 unmodified linestemplate_frame.select(fn=sam_refine,inputs=[video_state, point_prompt, click_state, interactive_state],outputs=[template_frame, video_state, interactive_state])# add different maskAdd_mask_button.click(fn=add_multi_mask,inputs=[video_state, interactive_state, mask_dropdown],outputs=[interactive_state, mask_dropdown, template_frame, click_state])remove_mask_button.click(fn=remove_multi_mask,inputs=[interactive_state],outputs=[interactive_state])# tracking video from select image and masktracking_video_predict_button.click(fn=vos_tracking_video,inputs=[video_state, interactive_state, mask_dropdown],outputs=[video_output, video_state, interactive_state])# inpaint video from select image and maskinpaint_video_predict_button.click(fn=inpaint_video,inputs=[video_state, interactive_state, mask_dropdown],outputs=[video_output])# click to get maskmask_dropdown.change(fn=show_mask,inputs=[video_state, interactive_state, mask_dropdown],outputs=[template_frame])# clear input25 unmodified linesNone,gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), \gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), \gr.update(visible=False), gr.update(visible=False), gr.update(visible=False, value=[]), gr.update(visible=False), gr.update(visible=False) \),[],4 unmodified linesvideo_output,template_frame,tracking_video_predict_button, image_selection_slider , track_pause_number_slider,point_prompt, click_mode, clear_button_click,Add_mask_button, template_frame, tracking_video_predict_button, video_output, mask_dropdown, remove_mask_button,inpaint_video_predict_button],queue=False,show_progress=False)2 unmodified linesclear_button_click.click(fn = clear_click,inputs = [video_state, click_state,],outputs = [template_frame,click_state],)# set examplegr.Markdown("## Examples")8 unmodified lines# cache_examples=True,)iface.queue(concurrency_count=1)iface.launch(debug=True)102 unmodified lines1031041051061071081091 unmodified line11111211311411511611711812 unmodified lines13113213313413513613713813914014114214314414514630 unmodified lines1771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062073 unmodified lines21121221321421521621721821922022122222312 unmodified lines23623723823924024124224324424524624726 unmodified lines2742752762772782792803 unmodified lines28428528628728828929011 unmodified lines30230330430530630730830931031131231331431531647 unmodified lines36436536636736836937046 unmodified lines41741841942042142242342442527 unmodified lines4534544554564574584594604614624634644653 unmodified lines4694704714724734744754764774784794804814824834842 unmodified lines48748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652725 unmodified lines5535545555565575585595604 unmodified lines5655665675685695705712 unmodified lines5745755765775785795808 unmodified lines589590591592593594595102 unmodified lines"fps": fps}video_info = "Video Name: {}, FPS: {}, Total Frames: {}, Image Size:{}".format(video_state["video_name"], video_state["fps"], len(frames), image_size)operation_log = "Upload video already. Try click the image for adding targets to track and inpaint."model.samcontroler.sam_controler.reset_image()model.samcontroler.sam_controler.set_image(video_state["origin_images"][0])return video_state, video_info, video_state["origin_images"][0], gr.update(visible=True, maximum=len(frames), value=1), gr.update(visible=True, maximum=len(frames), value=len(frames)), \1 unmodified linegr.update(visible=True), gr.update(visible=True), \gr.update(visible=True), gr.update(visible=True), \gr.update(visible=True), gr.update(visible=True), \gr.update(visible=True), gr.update(visible=True), \gr.update(visible=True, value=operation_log)def run_example(example):return video_input12 unmodified lines# update the masks when select a new template frame# if video_state["masks"][image_selection_slider] is not None:# video_state["painted_images"][image_selection_slider] = mask_painter(video_state["origin_images"][image_selection_slider], video_state["masks"][image_selection_slider])operation_log = "Select frame {}. Try click image and add mask for tracking.".format(image_selection_slider)return video_state["painted_images"][image_selection_slider], video_state, interactive_state, operation_log# set the tracking end framedef get_end_number(track_pause_number_slider, video_state, interactive_state):interactive_state["track_end_number"] = track_pause_number_slideroperation_log = "Set the tracking finish at frame {}".format(track_pause_number_slider)return video_state["painted_images"][track_pause_number_slider],interactive_state, operation_logdef get_resize_ratio(resize_ratio_slider, interactive_state):interactive_state["resize_ratio"] = resize_ratio_slider30 unmodified linesvideo_state["logits"][video_state["select_frame_number"]] = logitvideo_state["painted_images"][video_state["select_frame_number"]] = painted_imageoperation_log = "Use SAM for segment. You can try add positive and negative points by clicking. Or press Clear clicks button to refresh the image. Press Add mask button when you are satisfied with the segment"return painted_image, video_state, interactive_state, operation_logdef add_multi_mask(video_state, interactive_state, mask_dropdown):mask = video_state["masks"][video_state["select_frame_number"]]interactive_state["multi_mask"]["masks"].append(mask)interactive_state["multi_mask"]["mask_names"].append("mask_{:03d}".format(len(interactive_state["multi_mask"]["masks"])))mask_dropdown.append("mask_{:03d}".format(len(interactive_state["multi_mask"]["masks"])))select_frame, run_status = show_mask(video_state, interactive_state, mask_dropdown)operation_log = "Added a mask, use the mask select for target tracking or inpainting."return interactive_state, gr.update(choices=interactive_state["multi_mask"]["mask_names"], value=mask_dropdown), select_frame, [[],[]], operation_logdef clear_click(video_state, click_state):click_state = [[],[]]template_frame = video_state["origin_images"][video_state["select_frame_number"]]operation_log = "Clear points history and refresh the image."return template_frame, click_state, operation_logdef remove_multi_mask(interactive_state, mask_dropdown):interactive_state["multi_mask"]["mask_names"]= []interactive_state["multi_mask"]["masks"] = []operation_log = "Remove all mask, please add new masks"return interactive_state, gr.update(choices=[],value=[]), operation_logdef show_mask(video_state, interactive_state, mask_dropdown):mask_dropdown.sort()3 unmodified linesmask_number = int(mask_dropdown[i].split("_")[1]) - 1mask = interactive_state["multi_mask"]["masks"][mask_number]select_frame = mask_painter(select_frame, mask.astype('uint8'), mask_color=mask_number+2)operation_log = "Select {} for tracking or inpainting".format(mask_dropdown)return select_frame, operation_log# tracking vosdef vos_tracking_video(video_state, interactive_state, mask_dropdown):operation_log = "Track the selected masks, and then you can select the masks for inpainting."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"]]12 unmodified lineselse:template_mask = video_state["masks"][video_state["select_frame_number"]]fps = video_state["fps"]# operation errorif len(np.unique(template_mask))==1:template_mask[0][0]=1operation_log = "Error! Please add at least one mask to track by clicking the left image."# return video_output, video_state, interactive_state, operation_errormasks, logits, painted_images = model.generator(images=following_frames, template_mask=template_mask)# clear GPU memorymodel.xmem.clear_memory()26 unmodified linesi+=1# save_mask(video_state["masks"], video_state["video_name"])#### shanggao code for mask savereturn video_output, video_state, interactive_state, operation_log# extracting masks from mask_dropdown# def extract_sole_mask(video_state, mask_dropdown):3 unmodified lines# inpaintdef inpaint_video(video_state, interactive_state, mask_dropdown):operation_log = "Removed the selected masks."frames = np.asarray(video_state["origin_images"])fps = video_state["fps"]11 unmodified linescontinueinpaint_masks[inpaint_masks==i] = 0# inpaint for videostry:inpainted_frames = model.baseinpainter.inpaint(frames, inpaint_masks, ratio=interactive_state["resize_ratio"]) # numpy array, T, H, W, 3except:operation_log = "Error! You are trying to inpaint without masks input. Please track the selected mask first, and then press inpaint. If VRAM exceeded, please use the resize ratio to scaling down the image size."inpainted_frames = video_state["origin_images"]video_output = generate_video_from_frames(inpainted_frames, output_path="./result/inpaint/{}".format(video_state["video_name"]), fps=fps) # import video_input to name the output videoreturn video_output, operation_log# generate video after vos inference47 unmodified linesSAM_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 = 12212# args.device = "cuda:2"# args.mask_save = True46 unmodified lineswith gr.Row(scale=0.4):video_input = gr.Video(autosize=True)with gr.Column():video_info = gr.Textbox(label="Video Info")resize_info = gr.Textbox(value="If you want to use the inpaint function, it is best to git clone the repo 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.", label="Tips for running this demo.")resize_ratio_slider = gr.Slider(minimum=0.02, maximum=1, step=0.02, value=1, label="Resize ratio", visible=True)27 unmodified linestrack_pause_number_slider = gr.Slider(minimum=1, maximum=100, step=1, value=1, label="Track end frames", visible=False)with gr.Column():mask_dropdown = gr.Dropdown(multiselect=True, value=[], label="Mask selection", info=".", visible=False)remove_mask_button = gr.Button(value="Remove mask", interactive=True, visible=False)video_output = gr.Video(autosize=True, visible=False).style(height=360)with gr.Row():tracking_video_predict_button = gr.Button(value="Tracking", visible=False)inpaint_video_predict_button = gr.Button(value="Inpaint", visible=False)run_status = gr.Textbox(label="Operation log", visible=False)# first step: get the video informationextract_frames_button.click(3 unmodified lines],outputs=[video_state, video_info, template_frame,image_selection_slider, track_pause_number_slider,point_prompt, click_mode, clear_button_click, Add_mask_button, template_frame,tracking_video_predict_button, video_output, mask_dropdown, remove_mask_button, inpaint_video_predict_button, run_status])# second step: select images from sliderimage_selection_slider.release(fn=select_template,inputs=[image_selection_slider, video_state, interactive_state],outputs=[template_frame, video_state, interactive_state, run_status], api_name="select_image")track_pause_number_slider.release(fn=get_end_number,inputs=[track_pause_number_slider, video_state, interactive_state],outputs=[template_frame, interactive_state, run_status], api_name="end_image")resize_ratio_slider.release(fn=get_resize_ratio,inputs=[resize_ratio_slider, interactive_state],outputs=[interactive_state], api_name="resize_ratio")2 unmodified linestemplate_frame.select(fn=sam_refine,inputs=[video_state, point_prompt, click_state, interactive_state],outputs=[template_frame, video_state, interactive_state, run_status])# add different maskAdd_mask_button.click(fn=add_multi_mask,inputs=[video_state, interactive_state, mask_dropdown],outputs=[interactive_state, mask_dropdown, template_frame, click_state, run_status])remove_mask_button.click(fn=remove_multi_mask,inputs=[interactive_state, mask_dropdown],outputs=[interactive_state, mask_dropdown, run_status])# tracking video from select image and masktracking_video_predict_button.click(fn=vos_tracking_video,inputs=[video_state, interactive_state, mask_dropdown],outputs=[video_output, video_state, interactive_state, run_status])# inpaint video from select image and maskinpaint_video_predict_button.click(fn=inpaint_video,inputs=[video_state, interactive_state, mask_dropdown],outputs=[video_output, run_status])# click to get maskmask_dropdown.change(fn=show_mask,inputs=[video_state, interactive_state, mask_dropdown],outputs=[template_frame, run_status])# clear input25 unmodified linesNone,gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), \gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), \gr.update(visible=False), gr.update(visible=False), gr.update(visible=False, value=[]), gr.update(visible=False), \gr.update(visible=False), gr.update(visible=False)),[],4 unmodified linesvideo_output,template_frame,tracking_video_predict_button, image_selection_slider , track_pause_number_slider,point_prompt, click_mode, clear_button_click,Add_mask_button, template_frame, tracking_video_predict_button, video_output, mask_dropdown, remove_mask_button,inpaint_video_predict_button, run_status],queue=False,show_progress=False)2 unmodified linesclear_button_click.click(fn = clear_click,inputs = [video_state, click_state,],outputs = [template_frame,click_state, run_status],)# set examplegr.Markdown("## Examples")8 unmodified lines# cache_examples=True,)iface.queue(concurrency_count=1)iface.launch(debug=True, enable_queue=True, server_port=args.port, server_name="0.0.0.0")
63 unmodified lines64656667686970717273747576777879808182838471 unmodified lines15615715815916016116263 unmodified linesmasks = np.stack([cv2.dilate(mask, kernel) for mask in masks], 0)T, H, W = masks.shape# size: (w, h)if 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]video_length = T71 unmodified linesbase_inpainter = BaseInpainter(checkpoint, device)# 3/3: inpainting (frames: numpy array, T, H, W, 3; masks: numpy array, T, H, W)# ratio: (0, 1], ratio for down sample, default value is 1inpainted_frames = base_inpainter.inpaint(frames, masks, ratio=1) # numpy array, T, H, W, 3# ----------------------------------------------# end# ----------------------------------------------63 unmodified lines64656667686970717273747576777879808182838471 unmodified lines15615715815916016116263 unmodified linesmasks = np.stack([cv2.dilate(mask, kernel) for mask in masks], 0)T, H, W = masks.shapemasks = np.expand_dims(masks, axis=3) # expand to T, H, W, 1# size: (w, h)if ratio == 1:size = Nonebinary_masks = maskselse:size = [int(W*ratio), int(H*ratio)]size = [si+1 if si%2>0 else si for si in size] # only consider even values# shortest side should be larger than 50if min(size) < 50:ratio = 50. / min(H, W)size = [int(W*ratio), int(H*ratio)]binary_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]video_length = T71 unmodified linesbase_inpainter = BaseInpainter(checkpoint, device)# 3/3: inpainting (frames: numpy array, T, H, W, 3; masks: numpy array, T, H, W)# ratio: (0, 1], ratio for down sample, default value is 1inpainted_frames = base_inpainter.inpaint(frames, masks, ratio=0.01) # numpy array, T, H, W, 3# ----------------------------------------------# end# ----------------------------------------------
app.py+59-36
inpainter/base_inpainter.py+10-10