Spaces:
Runtime error
Runtime error
Update app.py
Browse files1234537 unmodified lines434445464748499 unmodified lines5960616263646566676818 unmodified lines878889909192939 unmodified lines1031041051061071081091101111121131141 unmodified line11611711811912012112272 unmodified lines1951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392403 unmodified lines244245246247248249208 unmodified lines45845946046146246346415 unmodified lines480481482483484485486487488import subprocessimport re# Define the command to be executedcommand = ["python", "setup.py", "build_ext", "--inplace"]37 unmodified linesreturn fpsdef preprocess_image(image):# we clean allreturn [image, # first_frame_path9 unmodified linesunique_id = datetime.now().strftime('%Y%m%d%H%M%S')# Set directory with this ID to store video framesoutput_dir = f'frames_{unique_id}'# Create the output directoryos.makedirs(output_dir, exist_ok=True)### Process video frames #### Open the video file18 unmodified linesbreak# Format the frame filename as '00000.jpg'frame_filename = os.path.join(output_dir, f'{frame_number:05d}.jpg')# Save the frame as a JPEG filecv2.imwrite(frame_filename, frame)9 unmodified lines# scan all the JPEG frame names in this directoryscanned_frames = [p for p in os.listdir(output_dir)if os.path.splitext(p)[-1] in [".jpg", ".jpeg", ".JPG", ".JPEG"]]scanned_frames.sort(key=lambda p: int(os.path.splitext(p)[0]))print(f"SCANNED_FRAMES: {scanned_frames}")return [first_frame, # first_frame_path1 unmodified linegr.State([]), # trackings_input_labelfirst_frame, # input_first_frame_imagefirst_frame, # points_mapoutput_dir, # video_frames_dirscanned_frames, # scanned_framesNone, # stored_inference_stateNone, # stored_frame_names72 unmodified linesif checkpoint == "tiny":sam2_checkpoint = "./checkpoints/sam2_hiera_tiny.pt"model_cfg = "sam2_hiera_t.yaml"return sam2_checkpoint, model_cfgelif checkpoint == "samll":sam2_checkpoint = "./checkpoints/sam2_hiera_small.pt"model_cfg = "sam2_hiera_s.yaml"return sam2_checkpoint, model_cfgelif checkpoint == "base-plus":sam2_checkpoint = "./checkpoints/sam2_hiera_base_plus.pt"model_cfg = "sam2_hiera_b+.yaml"return sam2_checkpoint, model_cfgelif checkpoint == "large":sam2_checkpoint = "./checkpoints/sam2_hiera_large.pt"model_cfg = "sam2_hiera_l.yaml"return sam2_checkpoint, model_cfgdef sam_process(input_first_frame_image, checkpoint, tracking_points, trackings_input_label, video_frames_dir, scanned_frames, working_frame, progress=gr.Progress(track_tqdm=True)):# 1. We need to preprocess the video and store frames in the right directory# — Penser à utiliser un ID unique pour le dossiersam2_checkpoint, model_cfg = load_model(checkpoint)predictor = build_sam2_video_predictor(model_cfg, sam2_checkpoint)# `video_dir` a directory of JPEG frames with filenames like `<frame_index>.jpg`print(f"STATE FRAME OUTPUT DIRECTORY: {video_frames_dir}")video_dir = video_frames_dir# scan all the JPEG frame names in this directoryframe_names = scanned_framesinference_state = predictor.init_state(video_path=video_dir)# segment and track one object# predictor.reset_state(inference_state) # if any previous tracking, resetnew_working_frame = None# Add new pointif working_frame == None:ann_frame_idx = 0 # the frame index we interact withnew_working_frame = "frames_output_images/frame_0.jpg"else:# Use a regular expression to find the integer3 unmodified linesframe_number = int(match.group(1))ann_frame_idx = frame_numbernew_working_frame = f"frames_output_images/frame_{ann_frame_idx}.jpg"ann_obj_id = 1 # give a unique id to each object we interact with (it can be any integers)208 unmodified lines# Clear every points clicked and added to the mapclear_points_btn.click(fn = preprocess_image,inputs = input_first_frame_image, # we get the untouched hidden imageoutputs = [first_frame_path,15 unmodified lines"""submit_btn.click(fn = sam_process,inputs = [input_first_frame_image, checkpoint, tracking_points, trackings_input_label, video_frames_dir, scanned_frames, working_frame],outputs = [output_result, stored_frame_names, stored_inference_state])propagate_btn.click(12345637 unmodified lines444546474849509 unmodified lines6061626364656667686918 unmodified lines888990919293949 unmodified lines1041051061071081091101111121131141 unmodified line11611711811912012112272 unmodified lines1951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542553 unmodified lines259260261262263264265208 unmodified lines47447547647747847948015 unmodified lines496497498499500501502503504505506507508509510511512513514515516import subprocessimport refrom typing import List, Tuple, Optional# Define the command to be executedcommand = ["python", "setup.py", "build_ext", "--inplace"]37 unmodified linesreturn fpsdef clear_points(image):# we clean allreturn [image, # first_frame_path9 unmodified linesunique_id = datetime.now().strftime('%Y%m%d%H%M%S')# Set directory with this ID to store video framesextracted_frames_output_dir = f'frames_{unique_id}'# Create the output directoryos.makedirs(extracted_frames_output_dir, exist_ok=True)### Process video frames #### Open the video file18 unmodified linesbreak# Format the frame filename as '00000.jpg'frame_filename = os.path.join(extracted_frames_output_dir, f'{frame_number:05d}.jpg')# Save the frame as a JPEG filecv2.imwrite(frame_filename, frame)9 unmodified lines# scan all the JPEG frame names in this directoryscanned_frames = [p for p in os.listdir(extracted_frames_output_dir)if os.path.splitext(p)[-1] in [".jpg", ".jpeg", ".JPG", ".JPEG"]]scanned_frames.sort(key=lambda p: int(os.path.splitext(p)[0]))print(f"SCANNED_FRAMES: {scanned_frames}")return [first_frame, # first_frame_path1 unmodified linegr.State([]), # trackings_input_labelfirst_frame, # input_first_frame_imagefirst_frame, # points_mapextracted_frames_output_dir, # video_frames_dirscanned_frames, # scanned_framesNone, # stored_inference_stateNone, # stored_frame_names72 unmodified linesif checkpoint == "tiny":sam2_checkpoint = "./checkpoints/sam2_hiera_tiny.pt"model_cfg = "sam2_hiera_t.yaml"return [sam2_checkpoint, model_cfg]elif checkpoint == "samll":sam2_checkpoint = "./checkpoints/sam2_hiera_small.pt"model_cfg = "sam2_hiera_s.yaml"return [sam2_checkpoint, model_cfg]elif checkpoint == "base-plus":sam2_checkpoint = "./checkpoints/sam2_hiera_base_plus.pt"model_cfg = "sam2_hiera_b+.yaml"return [sam2_checkpoint, model_cfg]elif checkpoint == "large":sam2_checkpoint = "./checkpoints/sam2_hiera_large.pt"model_cfg = "sam2_hiera_l.yaml"return [sam2_checkpoint, model_cfg]def get_mask_sam_process(input_first_frame_image,checkpoint,tracking_points,trackings_input_label,video_frames_dir, # extracted_frames_output_dir defined in 'preprocess_video_in' functionscanned_frames,working_frame: str = None, # current frame being added pointsprogress=gr.Progress(track_tqdm=True)):# get model and model config pathsprint(f"USER CHOSEN CHECKPOINT: {checkpoint}")sam2_checkpoint, model_cfg = load_model(checkpoint)print("MODEL LOADED")# set predictorpredictor = build_sam2_video_predictor(model_cfg, sam2_checkpoint)print("PREDICTOR READY")# `video_dir` a directory of JPEG frames with filenames like `<frame_index>.jpg`print(f"STATE FRAME OUTPUT DIRECTORY: {video_frames_dir}")video_dir = video_frames_dir# scan all the JPEG frame names in this directoryframe_names = scanned_frames# Init SAM2 inference_stateinference_state = predictor.init_state(video_path=video_dir)print("NEW INFERENCE_STATE INITIATED")# segment and track one object# predictor.reset_state(inference_state) # if any previous tracking, reset### HANDLING WORKING FRAMEnew_working_frame = None# Add new pointif working_frame is None:ann_frame_idx = 0 # the frame index we interact with, 0 if it is the first framenew_working_frame = "frames_output_images/frame_0.jpg"else:# Use a regular expression to find the integer3 unmodified linesframe_number = int(match.group(1))ann_frame_idx = frame_numbernew_working_frame = f"frames_output_images/frame_{ann_frame_idx}.jpg"print(f"NEW_WORKING_FRAME PATH: {new_working_frame}")ann_obj_id = 1 # give a unique id to each object we interact with (it can be any integers)208 unmodified lines# Clear every points clicked and added to the mapclear_points_btn.click(fn = clear_points,inputs = input_first_frame_image, # we get the untouched hidden imageoutputs = [first_frame_path,15 unmodified lines"""submit_btn.click(fn = get_mask_sam_process,inputs = [input_first_frame_image,checkpoint,tracking_points,trackings_input_label,video_frames_dir,scanned_frames,working_frame,],outputs = [output_result,stored_frame_names,stored_inference_state,])propagate_btn.click(
app.py+51-23