samannot 0.6.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,118 @@
1
+ # @package _global_
2
+
3
+ # Model
4
+ model:
5
+ _target_: sam2.modeling.sam2_base.SAM2Base
6
+ image_encoder:
7
+ _target_: sam2.modeling.backbones.image_encoder.ImageEncoder
8
+ scalp: 1
9
+ trunk:
10
+ _target_: sam2.modeling.backbones.hieradet.Hiera
11
+ embed_dim: 96
12
+ num_heads: 1
13
+ stages: [1, 2, 7, 2]
14
+ global_att_blocks: [5, 7, 9]
15
+ window_pos_embed_bkg_spatial_size: [7, 7]
16
+ neck:
17
+ _target_: sam2.modeling.backbones.image_encoder.FpnNeck
18
+ position_encoding:
19
+ _target_: sam2.modeling.position_encoding.PositionEmbeddingSine
20
+ num_pos_feats: 256
21
+ normalize: true
22
+ scale: null
23
+ temperature: 10000
24
+ d_model: 256
25
+ backbone_channel_list: [768, 384, 192, 96]
26
+ fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features
27
+ fpn_interp_model: nearest
28
+
29
+ memory_attention:
30
+ _target_: sam2.modeling.memory_attention.MemoryAttention
31
+ d_model: 256
32
+ pos_enc_at_input: true
33
+ layer:
34
+ _target_: sam2.modeling.memory_attention.MemoryAttentionLayer
35
+ activation: relu
36
+ dim_feedforward: 2048
37
+ dropout: 0.1
38
+ pos_enc_at_attn: false
39
+ self_attention:
40
+ _target_: sam2.modeling.sam.transformer.RoPEAttention
41
+ rope_theta: 10000.0
42
+ feat_sizes: [32, 32]
43
+ embedding_dim: 256
44
+ num_heads: 1
45
+ downsample_rate: 1
46
+ dropout: 0.1
47
+ d_model: 256
48
+ pos_enc_at_cross_attn_keys: true
49
+ pos_enc_at_cross_attn_queries: false
50
+ cross_attention:
51
+ _target_: sam2.modeling.sam.transformer.RoPEAttention
52
+ rope_theta: 10000.0
53
+ feat_sizes: [32, 32]
54
+ rope_k_repeat: True
55
+ embedding_dim: 256
56
+ num_heads: 1
57
+ downsample_rate: 1
58
+ dropout: 0.1
59
+ kv_in_dim: 64
60
+ num_layers: 4
61
+
62
+ memory_encoder:
63
+ _target_: sam2.modeling.memory_encoder.MemoryEncoder
64
+ out_dim: 64
65
+ position_encoding:
66
+ _target_: sam2.modeling.position_encoding.PositionEmbeddingSine
67
+ num_pos_feats: 64
68
+ normalize: true
69
+ scale: null
70
+ temperature: 10000
71
+ mask_downsampler:
72
+ _target_: sam2.modeling.memory_encoder.MaskDownSampler
73
+ kernel_size: 3
74
+ stride: 2
75
+ padding: 1
76
+ fuser:
77
+ _target_: sam2.modeling.memory_encoder.Fuser
78
+ layer:
79
+ _target_: sam2.modeling.memory_encoder.CXBlock
80
+ dim: 256
81
+ kernel_size: 7
82
+ padding: 3
83
+ layer_scale_init_value: 1e-6
84
+ use_dwconv: True # depth-wise convs
85
+ num_layers: 2
86
+
87
+ num_maskmem: 7
88
+ image_size: 1024
89
+ # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask
90
+ # SAM decoder
91
+ sigmoid_scale_for_mem_enc: 20.0
92
+ sigmoid_bias_for_mem_enc: -10.0
93
+ use_mask_input_as_output_without_sam: true
94
+ # Memory
95
+ directly_add_no_mem_embed: true
96
+ # use high-resolution feature map in the SAM mask decoder
97
+ use_high_res_features_in_sam: true
98
+ # output 3 masks on the first click on initial conditioning frames
99
+ multimask_output_in_sam: true
100
+ # SAM heads
101
+ iou_prediction_use_sigmoid: True
102
+ # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder
103
+ use_obj_ptrs_in_encoder: true
104
+ add_tpos_enc_to_obj_ptrs: false
105
+ only_obj_ptrs_in_the_past_for_eval: true
106
+ # object occlusion prediction
107
+ pred_obj_scores: true
108
+ pred_obj_scores_mlp: true
109
+ fixed_no_obj_ptr: true
110
+ # multimask tracking settings
111
+ multimask_output_for_tracking: true
112
+ use_multimask_token_for_obj_ptr: true
113
+ multimask_min_pt_num: 0
114
+ multimask_max_pt_num: 1
115
+ use_mlp_for_obj_ptr_proj: true
116
+ # Compilation flag
117
+ # HieraT does not currently support compilation, should always be set to False
118
+ compile_image_encoder: False
@@ -0,0 +1,246 @@
1
+ import cv2
2
+ import torch
3
+ import time
4
+ import numpy as np
5
+ import os
6
+ from .label import Label
7
+ from sam2.build_sam import build_sam2_video_predictor
8
+ import re
9
+ import shutil
10
+ class SAM_Annotator:
11
+ def __init__(self, model_type="vit_b", model_cfg_path = None, ckpt_path=None):
12
+ self.model_loaded = False
13
+ self.model_loading = False
14
+ self.model_type = model_type
15
+ self.ckpt_path = ckpt_path
16
+ self.model_cfg_path = model_cfg_path
17
+ self.labels = []
18
+ self.object_id_to_label_name = {}
19
+ self.blocking_frames = []
20
+ self.current_block = 0
21
+ self.media_files = []
22
+ self.propagation_blocks = {}
23
+ self.loading_stages = [
24
+ "Loading model weights",
25
+ "Setup complete"
26
+ ]
27
+ self.current_stage = 0
28
+ if torch.cuda.is_available():
29
+ self.device = torch.device('cuda')
30
+ torch.autocast(device_type="cuda", dtype=torch.float16).__enter__()
31
+ if torch.cuda.get_device_properties(0).major >= 8: # 8 ~ Ampere
32
+ torch.backends.cuda.matmul.allow_tf32 = True
33
+ torch.backends.cudnn.allow_tf32 = True
34
+ else:
35
+ self.device = torch.device('cpu')
36
+ print('Warning: only cpu available, SAM2 will not work properly')
37
+ self.curr_img_idx = -1
38
+ self.inference_state = None
39
+ self.tracking_init = False
40
+ self.object_ids = {}
41
+ self.frame_names = None
42
+ def load_model(self, status_callback):
43
+ if self.model_loaded or self.model_loading:
44
+ return True
45
+ self.model_loading = True
46
+ try:
47
+ start_time = time.time()
48
+ self._update_loading_stage(status_callback)
49
+ self.predictor = build_sam2_video_predictor(self.model_cfg_path, self.ckpt_path).to(device=self.device)
50
+ self._update_loading_stage(status_callback)
51
+ self.model_loaded = True
52
+ self.model_loading = False
53
+ load_time = time.time() - start_time
54
+ if status_callback:
55
+ status_callback(f"SAM2 loaded successfully in {load_time:.1f}s (using {self.device})")
56
+ return True
57
+ except Exception as e:
58
+ if status_callback:
59
+ status_callback(f"Error loading SAM2: {str(e)}")
60
+ self.model_loading = False
61
+ return False
62
+ def _update_loading_stage(self, status_callback):
63
+ if self.current_stage < len(self.loading_stages):
64
+ stage_text = self.loading_stages[self.current_stage]
65
+ if status_callback:
66
+ progress = f"[{self.current_stage+1}/{len(self.loading_stages)}]"
67
+ status_callback(f"Loading SAM2 model {progress} {stage_text}")
68
+ self.current_stage += 1
69
+ def is_model_loaded(self):
70
+ return self.model_loaded
71
+ def _find_most_recent_prompt(self,label,idx):
72
+ most_recent_prompt = -1
73
+ for pt in label.pts[self.current_block]:
74
+ if pt.idx <= idx:
75
+ most_recent_prompt = np.amax([most_recent_prompt,pt.idx])
76
+ return most_recent_prompt
77
+ def _find_most_recent_prompt_box(self,label,idx):
78
+ most_recent_prompt = -1
79
+ for box in label.boxes[self.current_block]:
80
+ if box.idx <= idx:
81
+ most_recent_prompt = np.amax([most_recent_prompt,box.idx])
82
+ return most_recent_prompt
83
+ def _preprocess_label(self,label,idx,flag=0):
84
+ pt_coords = []
85
+ pt_labels = []
86
+ boxes = []
87
+ most_recent_prompt = -1
88
+ most_recent_prompt_box = -1
89
+ if flag == 1:
90
+ most_recent_prompt = self._find_most_recent_prompt(label,idx)
91
+ for pt in label.pts[self.current_block]:
92
+ if flag == 0 and pt.idx == self.curr_img_idx:
93
+ pt_coords.append([pt.x, pt.y])
94
+ pt_labels.append(pt.pt_type)
95
+ if flag == 1 and pt.idx == most_recent_prompt:
96
+ pt_coords.append([pt.x, pt.y])
97
+ pt_labels.append(pt.pt_type)
98
+ if flag == 1:
99
+ most_recent_prompt_box = self._find_most_recent_prompt_box(label,idx)
100
+ for box in label.boxes[self.current_block]:
101
+ if flag == 0 and box.idx == self.curr_img_idx:
102
+ boxes.append([box.fx,box.fy,box.x,box.y])
103
+ if flag == 1 and box.idx== most_recent_prompt_box:
104
+ boxes.append([box.fx,box.fy,box.x,box.y])
105
+ if len(boxes) > 0:
106
+ boxes = [boxes[0]]
107
+ pt_coords = np.array(pt_coords)
108
+ pt_labels = np.array(pt_labels)
109
+ boxes = np.array(boxes)
110
+ return pt_coords, pt_labels, boxes, most_recent_prompt, most_recent_prompt_box
111
+ def _get_object_id_for_label(self, label_name):
112
+ if (label_name + str(self.current_block)) not in self.object_ids:
113
+ self.object_ids[(label_name + str(self.current_block))] = len(self.object_ids) + 1
114
+ self.object_id_to_label_name[self.object_ids[(label_name + str(self.current_block))]] = label_name
115
+ return self.object_ids[(label_name + str(self.current_block))]
116
+ def init_inference_state(self, path, status_callback=None):
117
+ if not self.model_loaded:
118
+ return False
119
+ try:
120
+ self.inference_state = self.predictor.init_state(video_path=path)
121
+ self.tracking_init = True
122
+ if status_callback:
123
+ status_callback(f"SAM2 tracking initialized successfully!")
124
+ return True
125
+ except Exception as e:
126
+ if status_callback:
127
+ status_callback(f"Error initializing SAM2 tracking: {str(e)}")
128
+ return False
129
+ def generate_mask_for_frame(self,idx,flag=0):
130
+ if not self.model_loaded:
131
+ return {}
132
+ try:
133
+ print(f"### {self.media_files}")
134
+ current_path = self.media_files[idx]
135
+ img_dir = os.path.dirname(current_path)
136
+ os.makedirs("./singular_temp_dir/",exist_ok=True)
137
+ shutil.copy(current_path,os.path.join("./singular_temp_dir/",os.path.basename(current_path)))
138
+ if not self.tracking_init or self.inference_state is None:
139
+ temp_inference_state = self.predictor.init_state(video_path=img_dir)
140
+ else:
141
+ temp_inference_state = self.inference_state
142
+ results = {}
143
+ for label in self.labels:
144
+ pt_coords, pt_labels, boxes, _, _ = self._preprocess_label(label,idx,flag)
145
+ if pt_coords.shape[0] != 0:
146
+ with torch.autocast('cuda' if torch.cuda.is_available() else 'cpu', dtype=torch.float16):
147
+ _, obj_ids, mask_logits = self.predictor.add_new_points_or_box(
148
+ inference_state=temp_inference_state,
149
+ frame_idx=self.curr_img_idx,
150
+ obj_id=self._get_object_id_for_label(label.name),
151
+ points=pt_coords,
152
+ labels=pt_labels
153
+ )
154
+ if boxes.shape[0] != 0:
155
+ with torch.autocast('cuda' if torch.cuda.is_available() else 'cpu', dtype=torch.float16):
156
+ _, obj_ids, mask_logits = self.predictor.add_new_points_or_box(
157
+ inference_state=temp_inference_state,
158
+ frame_idx=self.curr_img_idx,
159
+ obj_id=self._get_object_id_for_label(label.name),
160
+ box = boxes
161
+ )
162
+ mask = (mask_logits > 0.0).cpu().numpy()
163
+ frame_results = {}
164
+ for j, obj_id in enumerate(obj_ids):
165
+ frame_results[self.object_id_to_label_name[obj_id]] = mask[j]
166
+ results[idx] = frame_results
167
+ if not self.tracking_init or self.inference_state is None:
168
+ self.predictor.reset_state(temp_inference_state)
169
+ return results
170
+ except Exception as e:
171
+ print(f"Error generating mask: {str(e)}")
172
+ return {}
173
+ def propagate(self, direction, start_frame_idx, end_frame_idx = None, progress_callback = None, flag = 1):
174
+ if not self.tracking_init:
175
+ print("Tracking not initialized!")
176
+ return {}
177
+ try:
178
+ self.predictor.reset_state(self.inference_state)
179
+ for label in self.labels:
180
+ pt_coords, pt_labels, boxes, most_recent_prompt, most_recent_prompt_box = self._preprocess_label(label,start_frame_idx,flag)
181
+ if pt_coords.shape[0] != 0:
182
+ with torch.autocast('cuda' if torch.cuda.is_available() else 'cpu', dtype=torch.float16):
183
+ self.predictor.add_new_points_or_box(
184
+ inference_state=self.inference_state,
185
+ frame_idx=most_recent_prompt,
186
+ obj_id=self._get_object_id_for_label(label.name),
187
+ points=pt_coords,
188
+ labels=pt_labels
189
+ )
190
+ if boxes.shape[0] != 0:
191
+ with torch.autocast('cuda' if torch.cuda.is_available() else 'cpu', dtype=torch.float16):
192
+ self.predictor.add_new_points_or_box(
193
+ inference_state=self.inference_state,
194
+ frame_idx=most_recent_prompt_box,
195
+ obj_id=self._get_object_id_for_label(label.name),
196
+ box = boxes
197
+ )
198
+ results = {}
199
+ prop_extra_frame = True
200
+ if direction == 1:
201
+ if end_frame_idx is None:
202
+ end_frame_idx = len(self.media_files)
203
+ max_efi = 1000000
204
+ for k,v in self.propagation_blocks[self.current_block].items():
205
+ if k > start_frame_idx and k < max_efi:
206
+ max_efi = k
207
+ prop_extra_frame = False
208
+ end_frame_idx = np.amin([end_frame_idx,max_efi])
209
+ if prop_extra_frame:
210
+ end_frame_idx += 1
211
+ total_prop_frames = end_frame_idx - start_frame_idx - 1
212
+ else:
213
+ if end_frame_idx is None:
214
+ end_frame_idx = 0
215
+ max_efi = -1000000
216
+ for k,v in self.propagation_blocks[self.current_block].items():
217
+ if k < start_frame_idx and k > max_efi:
218
+ max_efi = k
219
+ end_frame_idx = np.amax([end_frame_idx,max_efi+1])
220
+ if end_frame_idx is not None:
221
+ total_prop_frames = start_frame_idx - end_frame_idx
222
+ else:
223
+ total_prop_frames = start_frame_idx
224
+ with torch.autocast('cuda' if torch.cuda.is_available() else 'cpu', dtype=torch.float16):
225
+ for i, (out_frame_idx, out_obj_ids, out_mask_logits) in enumerate(
226
+ self.predictor.propagate_in_video(self.inference_state,start_frame_idx=start_frame_idx,max_frame_num_to_track=total_prop_frames,reverse=(direction != 1))):
227
+ masks = (out_mask_logits > 0.0).cpu().numpy()
228
+ frame_results = {}
229
+ for j, obj_id in enumerate(out_obj_ids):
230
+ frame_results[self.object_id_to_label_name[obj_id]] = masks[j]
231
+ results[out_frame_idx] = frame_results
232
+ if progress_callback:
233
+ progress = (i / total_prop_frames) * 100
234
+ progress_callback(f"Processing data...", progress)
235
+ torch.cuda.empty_cache()
236
+ self.predictor.reset_state(self.inference_state)
237
+ return results
238
+ except Exception as e:
239
+ print(f"Error propagating masks: {str(e)}")
240
+ if progress_callback:
241
+ progress_callback(f"Error propagating masks: {str(e)}", 0)
242
+ return {}
243
+ def propagate_to_all(self, current_frame_idx, start_frame_idx = None, end_frame_idx = None, progress_callback = None, flag = 1):
244
+ forward_prop_results = self.propagate(1,current_frame_idx,end_frame_idx,progress_callback,flag)
245
+ backward_prop_results = self.propagate(-1,current_frame_idx,start_frame_idx,progress_callback,flag)
246
+ return forward_prop_results | backward_prop_results
@@ -0,0 +1,71 @@
1
+ import psutil
2
+ from pynvml import nvmlInit, nvmlShutdown, nvmlDeviceGetCount, nvmlDeviceGetHandleByIndex,nvmlDeviceGetMemoryInfo, nvmlDeviceGetUtilizationRates, nvmlDeviceGetName
3
+ import tkinter as tk
4
+ from .visual_widget_utils import *
5
+ class SystemMonitor:
6
+ def __init__(self):
7
+ nvmlInit()
8
+ self.device_count = nvmlDeviceGetCount()
9
+ self.device_handles = []
10
+ self.device_names = []
11
+ self.used_ram = 0
12
+ self.total_ram = 0
13
+ self.gpu_util = []
14
+ self.gpu_memory = []
15
+ for idx in range(self.device_count):
16
+ handle = nvmlDeviceGetHandleByIndex(idx)
17
+ self.device_handles.append(handle)
18
+ self.device_names.append(nvmlDeviceGetName(handle))
19
+ self.gpu_memory.append(0)
20
+ self.gpu_util.append(0)
21
+ self.update_system_info()
22
+ def update_system_info(self):
23
+ virtual_memory = psutil.virtual_memory()
24
+ self.used_ram = virtual_memory.used
25
+ self.total_ram = virtual_memory.total
26
+ for idx in range(self.device_count):
27
+ self.gpu_util[idx] = nvmlDeviceGetUtilizationRates(self.device_handles[idx]).gpu
28
+ gpu_mem = nvmlDeviceGetMemoryInfo(self.device_handles[idx])
29
+ self.gpu_memory[idx] = (gpu_mem.used,gpu_mem.total)
30
+ def __del__(self):
31
+ nvmlShutdown()
32
+ class SystemMonitorWindow(tk.Toplevel):
33
+ def __init__(self, parent):
34
+ super().__init__(parent)
35
+ self.configure(bg="#f5f6f7")
36
+ self.title("System Resources")
37
+ self.info_frame = tk.Frame(self, bg="#f5f5f5")
38
+ self.info_frame.pack(fill=tk.BOTH, padx=10, pady=10)
39
+ self.is_open = True
40
+ # RAM
41
+ ram_frame = tk.Frame(self.info_frame, bg="#f5f5f5")
42
+ ram_frame.grid(row=0, column=0, padx=15)
43
+ ram_label = tk.Label(ram_frame, text="RAM", bg="#f5f5f5", fg="#222222", font=("Segoe UI", 14, "bold"))
44
+ ram_label.pack(pady=(0, 5))
45
+ self.circular_progress_bar_ram = CircularProgress(self.info_frame, size=200)
46
+ self.circular_progress_bar_ram.grid(row=1,column=0, sticky="ew")
47
+ # GPU Util
48
+ gpu_frame = tk.Frame(self.info_frame, bg="#f5f5f5")
49
+ gpu_frame.grid(row=0, column=1, padx=15)
50
+ gpu_label = tk.Label(gpu_frame, text="GPU", bg="#f5f5f5", fg="#222222", font=("Segoe UI", 14, "bold"))
51
+ gpu_label.pack(pady=(0, 5))
52
+ self.circular_progress_bar_gpu = CircularProgress(self.info_frame, size=200)
53
+ self.circular_progress_bar_gpu.grid(row=1,column=1, sticky="ew")
54
+ # VRAM
55
+ vram_frame = tk.Frame(self.info_frame, bg="#f5f5f5")
56
+ vram_frame.grid(row=0, column=2, padx=15)
57
+ vram_label = tk.Label(vram_frame, text="VRAM", bg="#f5f5f5", fg="#222222", font=("Segoe UI", 14, "bold"))
58
+ vram_label.pack(pady=(0, 5))
59
+ self.circular_progress_bar_vram = CircularProgress(self.info_frame, size=200)
60
+ self.circular_progress_bar_vram.grid(row=1,column=2, sticky="ew")
61
+ self.protocol("WM_DELETE_WINDOW", self.on_close)
62
+ def hide(self):
63
+ self.withdraw()
64
+ self.is_open = False
65
+ def show(self):
66
+ self.deiconify()
67
+ self.lift()
68
+ self.focus_force()
69
+ self.is_open = True
70
+ def on_close(self):
71
+ self.hide()
samannot/user_guide.py ADDED
@@ -0,0 +1,216 @@
1
+ import tkinter as tk
2
+ from tkinter import ttk
3
+ class UserGuideWindow(tk.Toplevel):
4
+ def __init__(self, parent):
5
+ super().__init__(parent)
6
+
7
+ self.title("User Guide")
8
+ self.geometry("900x600")
9
+ self.minsize(600, 400)
10
+ self.configure(bg="#202331")
11
+
12
+ self.protocol("WM_DELETE_WINDOW", self.on_close)
13
+
14
+ style = ttk.Style(self)
15
+ style.configure(
16
+ "Guide.TFrame",
17
+ background="#202331",
18
+ )
19
+ style.configure(
20
+ "GuideHeader.TLabel",
21
+ background="#202331",
22
+ foreground="#FFFFFF",
23
+ font=("Segoe UI", 16, "bold"),
24
+ )
25
+ style.configure(
26
+ "GuideSubHeader.TLabel",
27
+ background="#202331",
28
+ foreground="#A0A4C0",
29
+ font=("Segoe UI", 10),
30
+ )
31
+ style.configure(
32
+ "GuideText.TLabel",
33
+ background="#202331",
34
+ foreground="#E0E3FF",
35
+ font=("Segoe UI", 10),
36
+ wraplength=600,
37
+ justify="left",
38
+ )
39
+ style.configure(
40
+ "GuideNav.TButton",
41
+ anchor="w",
42
+ padding=6,
43
+ )
44
+
45
+ main = ttk.Frame(self, style="Guide.TFrame")
46
+ main.pack(fill="both", expand=True, padx=16, pady=16)
47
+
48
+ main.columnconfigure(0, weight=0)
49
+ main.columnconfigure(1, weight=1)
50
+ main.rowconfigure(1, weight=1)
51
+
52
+ header_frame = ttk.Frame(main, style="Guide.TFrame")
53
+ header_frame.grid(row=0, column=0, columnspan=2, sticky="ew", pady=(0, 12))
54
+
55
+ title_label = ttk.Label(header_frame,text="User Guide",style="GuideHeader.TLabel",)
56
+ title_label.pack(anchor="w")
57
+
58
+ subtitle_label = ttk.Label(header_frame,text=" ",style="GuideSubHeader.TLabel",)
59
+ subtitle_label.pack(anchor="w")
60
+
61
+ nav_frame = ttk.Frame(main, style="Guide.TFrame")
62
+ nav_frame.grid(row=1, column=0, sticky="nsw", padx=(0, 16))
63
+ nav_label = ttk.Label(nav_frame,text="Sections",style="GuideSubHeader.TLabel",)
64
+ nav_label.pack(anchor="w", pady=(0, 6))
65
+
66
+ self.nav_buttons = {}
67
+ sections = [
68
+ ("getting_started", "Getting Started", True),
69
+ ("workspace", "Workspace Overview", False),
70
+ ("shortcuts", "Keyboard Shortcuts", True),
71
+ ("faq", "FAQ", False),
72
+ ]
73
+
74
+ for key, text, access in sections:
75
+ btn = ttk.Button(nav_frame,text=text,style="GuideNav.TButton",command=lambda k=key: self.show_section(k),state=tk.NORMAL if access else tk.DISABLED)
76
+ btn.pack(fill="x", pady=2)
77
+ self.nav_buttons[key] = btn
78
+
79
+ content_outer = ttk.Frame(main, style="Guide.TFrame")
80
+ content_outer.grid(row=1, column=1, sticky="nsew")
81
+ content_outer.rowconfigure(0, weight=1)
82
+ content_outer.columnconfigure(0, weight=1)
83
+
84
+ self.content_canvas = tk.Canvas(content_outer,bg="#202331",highlightthickness=0,borderwidth=0,)
85
+ self.content_canvas.grid(row=0, column=0, sticky="nsew")
86
+ self.content_canvas.configure()
87
+ self.content_canvas.bind("<Configure>", self.on_canvas_configure)
88
+
89
+ self.content_frame = ttk.Frame(self.content_canvas, style="Guide.TFrame")
90
+ self.content_window = self.content_canvas.create_window((0, 0),window=self.content_frame,anchor="nw",)
91
+ self.content_frame.bind("<Configure>", self.on_content_configure)
92
+
93
+ self.current_section_key = None
94
+ self.show_section("getting_started")
95
+
96
+ def show(self):
97
+ if not self.winfo_exists():
98
+ return
99
+ self.deiconify()
100
+ self.lift()
101
+ self.focus_force()
102
+ def hide(self):
103
+ if self.winfo_exists():
104
+ self.withdraw()
105
+ def on_close(self):
106
+ self.hide()
107
+ def on_content_configure(self, event):
108
+ self.content_canvas.configure(scrollregion=self.content_canvas.bbox("all"))
109
+ def on_canvas_configure(self, event):
110
+ canvas_width = event.width
111
+ self.content_canvas.itemconfig(self.content_window, width=canvas_width)
112
+ def clear_content(self):
113
+ for child in self.content_frame.winfo_children():
114
+ child.destroy()
115
+ def show_section(self, key: str):
116
+ if key == self.current_section_key:
117
+ return
118
+ self.current_section_key = key
119
+ self.clear_content()
120
+ if key == "getting_started":
121
+ self.section_getting_started()
122
+ elif key == "workspace":
123
+ self.section_workspace()
124
+ elif key == "shortcuts":
125
+ self.section_shortcuts()
126
+ else:
127
+ self.section_faq()
128
+ def add_heading(self, text: str):
129
+ lbl = ttk.Label(self.content_frame,text=text,style="GuideHeader.TLabel",)
130
+ lbl.pack(anchor="w", pady=(0, 4))
131
+ def add_subheading(self, text: str):
132
+ lbl = ttk.Label(self.content_frame,text=text,style="GuideSubHeader.TLabel",)
133
+ lbl.pack(anchor="w", pady=(12, 2))
134
+ def add_paragraph(self, text: str):
135
+ lbl = ttk.Label(self.content_frame,text=text,style="GuideText.TLabel",)
136
+ lbl.pack(anchor="w", pady=2)
137
+ def section_getting_started(self):
138
+ self.add_heading("Getting Started")
139
+ self.add_paragraph(
140
+ "This section will give a quick overview of the annotator"
141
+ )
142
+
143
+ self.add_subheading("1. Load media")
144
+ self.add_paragraph(
145
+ "* Load a video, folder images\n"
146
+ "* Select the number of frames in a block (the frames handled in one propagation)"
147
+ )
148
+
149
+ self.add_subheading("2. Create labels")
150
+ self.add_paragraph(
151
+ "* Create as many labels as you need (each with a unique name)\n"
152
+ "* You can assign permanentfeatures to them"
153
+ )
154
+ self.add_subheading("3. Add promts")
155
+ self.add_paragraph(
156
+ "* You can add prompts, by clicking on the canvas\n"
157
+ "* Positive prompts: this is A\n"
158
+ "* Negative prompt: this is not A\n"
159
+ "* You can add many points and a single box style prompt"
160
+ )
161
+ self.add_subheading("4. Propagation")
162
+ self.add_paragraph(
163
+ "* Once you have added all prompts you can propagate the data across frames\n"
164
+ "* Adding checkpoints will create a block across which the program doesn't propagate\n"
165
+ " Use this, to mark areas that are good, and any further correction shouldn't affect\n"
166
+ "* If the propagation is successful you will see an overlay view of the generated masks"
167
+ )
168
+ self.add_subheading("5. Export")
169
+ self.add_paragraph(
170
+ "* You can export two things:"
171
+ "* Session data (under export/<Session name>.pkl), so you can continue working from where you left off\n"
172
+ "* And annotation output saved under export/<Session name>/..."
173
+ )
174
+ def section_workspace(self):
175
+ self.add_heading("Workspace Overview")
176
+ self.add_paragraph(
177
+ "Describe the main layout: toolbar, canvas, sidebar panels, status bar, etc."
178
+ )
179
+ self.add_subheading("Main Canvas")
180
+ self.add_paragraph("Explain navigation, zoom, pan, and overlays.")
181
+ self.add_subheading("Panels")
182
+ self.add_paragraph("Describe list of images, layers, properties, etc.")
183
+
184
+ def section_shortcuts(self):
185
+ self.add_heading("Keyboard Shortcuts")
186
+ self.add_paragraph(
187
+ "Below is a list of the most important shortcuts to speed up your workflow."
188
+ )
189
+ header_frame = ttk.Frame(self.content_frame, style="Guide.TFrame")
190
+ header_frame.pack(anchor="w", pady=(12, 4), fill="x")
191
+ table = ttk.Frame(self.content_frame, style="Guide.TFrame")
192
+ table.pack(anchor="w", fill="x")
193
+ ttk.Label(table,text="Action",style="GuideSubHeader.TLabel",).grid(row=0, column=0, sticky="w", padx=(0, 20))
194
+ ttk.Label(table,text="Shortcut",style="GuideSubHeader.TLabel",).grid(row=0, column=1, sticky="w")
195
+
196
+ shortcuts = [
197
+ ("Fullscreen", "Shift + F"),
198
+ ("Next frame", "D"),
199
+ ("Previous frame", "A"),
200
+ ("Next label", "W"),
201
+ ("Previous label", "S"),
202
+ ("Switch to next viewmode", "Shift + M"),
203
+ ("Switch to specific viewmode", "Shift + 1/2/3/4"),
204
+ ("Select prompt (point or box)", "Ctrl + Click"),
205
+ ("Delete selected prompt (point or box)", "Delete"),
206
+ ]
207
+
208
+ for r, (action, key) in enumerate(shortcuts):
209
+ ttk.Label(table,text=action,style="GuideText.TLabel",).grid(row=r+1, column=0, sticky="w", padx=(0, 20), pady=2)
210
+ ttk.Label(table,text=key,style="GuideText.TLabel",).grid(row=r+1, column=1, sticky="w", pady=2)
211
+
212
+ def section_faq(self):
213
+ self.add_heading("Frequently Asked Questions")
214
+ self.add_paragraph(
215
+ " - "
216
+ )