Junyi42 commited on
Commit
02eef8d
·
1 Parent(s): 98d7910

use global data cache

Browse files
Files changed (2) hide show
  1. app.py +123 -4
  2. vis_st4rtrack.py +99 -87
app.py CHANGED
@@ -1,13 +1,128 @@
1
  import random
2
  import threading
3
- import psutil # Add this import for RAM monitoring
4
-
5
  import fastapi
6
  import gradio as gr
7
  import uvicorn
 
 
 
8
 
9
  from viser_proxy_manager import ViserProxyManager
10
- from vis_st4rtrack import visualize_st4rtrack
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
 
13
  def check_ram_usage(threshold_percent=90):
@@ -25,6 +140,9 @@ def check_ram_usage(threshold_percent=90):
25
 
26
 
27
  def main() -> None:
 
 
 
28
  app = fastapi.FastAPI()
29
  viser_manager = ViserProxyManager(app)
30
 
@@ -69,7 +187,8 @@ def main() -> None:
69
  target=visualize_st4rtrack,
70
  kwargs={
71
  "server": server,
72
- "use_float16": True, # Enable float16 precision
 
73
  },
74
  daemon=True
75
  ).start()
 
1
  import random
2
  import threading
3
+ import psutil
4
+ import numpy as onp
5
  import fastapi
6
  import gradio as gr
7
  import uvicorn
8
+ import os
9
+ from pathlib import Path
10
+ from glob import glob
11
 
12
  from viser_proxy_manager import ViserProxyManager
13
+ from vis_st4rtrack import visualize_st4rtrack, log_memory_usage
14
+
15
+ # Global cache for loaded data
16
+ global_data_cache = {
17
+ 'traj_3d_head1': None,
18
+ 'traj_3d_head2': None,
19
+ 'conf_mask_head1': None,
20
+ 'conf_mask_head2': None,
21
+ 'masks': None,
22
+ 'loaded': False
23
+ }
24
+
25
+ def load_data_once(traj_path="results", use_float16=True):
26
+ """Load data once and store in global cache."""
27
+ if global_data_cache['loaded']:
28
+ return
29
+
30
+ log_memory_usage("before loading data")
31
+
32
+ # Load masks
33
+ mask_folder = './train'
34
+ masks_paths = sorted(glob(mask_folder + '/*.jpg'))
35
+ masks = None
36
+
37
+ if masks_paths:
38
+ import cv2
39
+ import numpy as np
40
+ import imageio.v3 as iio
41
+
42
+ masks = [iio.imread(p) for p in masks_paths]
43
+ masks = np.stack(masks, axis=0)
44
+ # Convert masks to binary (0 or 1)
45
+ masks = (masks < 1).astype(np.float32)
46
+ masks = masks.sum(axis=-1) > 2 # Combine all channels, True where any channel was 1
47
+ print(f"Original masks shape: {masks.shape}")
48
+ else:
49
+ print("No masks found. Will create default masks when needed.")
50
+
51
+ global_data_cache['masks'] = masks
52
+
53
+ if Path(traj_path).is_dir():
54
+ # Load head1 data
55
+ traj_3d_paths_head1 = sorted(glob(traj_path + '/pts3d1_p*.npy'),
56
+ key=lambda x: int(x.split('_p')[-1].split('.')[0]))
57
+ conf_paths_head1 = sorted(glob(traj_path + '/conf1_p*.npy'),
58
+ key=lambda x: int(x.split('_p')[-1].split('.')[0]))
59
+
60
+ # Load head2 data
61
+ traj_3d_paths_head2 = sorted(glob(traj_path + '/pts3d2_p*.npy'),
62
+ key=lambda x: int(x.split('_p')[-1].split('.')[0]))
63
+ conf_paths_head2 = sorted(glob(traj_path + '/conf2_p*.npy'),
64
+ key=lambda x: int(x.split('_p')[-1].split('.')[0]))
65
+
66
+ # Process head1
67
+ if traj_3d_paths_head1:
68
+ if use_float16:
69
+ traj_3d_head1 = onp.stack([onp.load(p).astype(onp.float16) for p in traj_3d_paths_head1], axis=0)
70
+ else:
71
+ traj_3d_head1 = onp.stack([onp.load(p) for p in traj_3d_paths_head1], axis=0)
72
+
73
+ log_memory_usage("after loading head1 data")
74
+
75
+ h, w, _ = traj_3d_head1.shape[1:]
76
+
77
+ # If masks is None, create default masks (all ones)
78
+ if masks is None:
79
+ num_frames = traj_3d_head1.shape[0]
80
+ masks = np.ones((num_frames, h, w), dtype=bool)
81
+ print(f"Created default masks with shape: {masks.shape}")
82
+ global_data_cache['masks'] = masks
83
+ else:
84
+ # Resize masks to match trajectory dimensions using nearest neighbor interpolation
85
+ masks_resized = np.zeros((masks.shape[0], h, w), dtype=bool)
86
+ for i in range(masks.shape[0]):
87
+ masks_resized[i] = cv2.resize(
88
+ masks[i].astype(np.uint8),
89
+ (w, h),
90
+ interpolation=cv2.INTER_NEAREST
91
+ ).astype(bool)
92
+
93
+ print(f"Resized masks shape: {masks_resized.shape}")
94
+ global_data_cache['masks'] = masks_resized
95
+
96
+ # Reshape trajectory data
97
+ traj_3d_head1 = traj_3d_head1.reshape(traj_3d_head1.shape[0], -1, 6)
98
+ global_data_cache['traj_3d_head1'] = traj_3d_head1
99
+
100
+ if conf_paths_head1:
101
+ conf_head1 = onp.stack([onp.load(p).astype(onp.float16) for p in conf_paths_head1], axis=0)
102
+ conf_head1 = conf_head1.reshape(conf_head1.shape[0], -1)
103
+ conf_mask_head1 = conf_head1 > 1.0 # Default threshold
104
+ global_data_cache['conf_mask_head1'] = conf_mask_head1
105
+
106
+ # Process head2
107
+ if traj_3d_paths_head2:
108
+ if use_float16:
109
+ traj_3d_head2 = onp.stack([onp.load(p).astype(onp.float16) for p in traj_3d_paths_head2], axis=0)
110
+ else:
111
+ traj_3d_head2 = onp.stack([onp.load(p) for p in traj_3d_paths_head2], axis=0)
112
+
113
+ log_memory_usage("after loading head2 data")
114
+
115
+ traj_3d_head2 = traj_3d_head2.reshape(traj_3d_head2.shape[0], -1, 6)
116
+ global_data_cache['traj_3d_head2'] = traj_3d_head2
117
+
118
+ if conf_paths_head2:
119
+ conf_head2 = onp.stack([onp.load(p).astype(onp.float16) for p in conf_paths_head2], axis=0)
120
+ conf_head2 = conf_head2.reshape(conf_head2.shape[0], -1)
121
+ conf_mask_head2 = conf_head2 > 1.0 # Default threshold
122
+ global_data_cache['conf_mask_head2'] = conf_mask_head2
123
+
124
+ global_data_cache['loaded'] = True
125
+ log_memory_usage("after loading all data")
126
 
127
 
128
  def check_ram_usage(threshold_percent=90):
 
140
 
141
 
142
  def main() -> None:
143
+ # Load data once at startup
144
+ load_data_once(use_float16=True)
145
+
146
  app = fastapi.FastAPI()
147
  viser_manager = ViserProxyManager(app)
148
 
 
187
  target=visualize_st4rtrack,
188
  kwargs={
189
  "server": server,
190
+ "use_float16": True,
191
+ "preloaded_data": global_data_cache # Pass the preloaded data
192
  },
193
  daemon=True
194
  ).start()
vis_st4rtrack.py CHANGED
@@ -42,9 +42,10 @@ def visualize_st4rtrack(
42
  traj_line_width: float = 3.,
43
  fixed_length_traj: int = 10,
44
  server: viser.ViserServer = None,
45
- use_float16: bool = True, # Add this parameter to control precision
 
46
  ) -> None:
47
- log_memory_usage("at start")
48
 
49
  if server is None:
50
  server = viser.ViserServer()
@@ -58,101 +59,112 @@ def visualize_st4rtrack(
58
 
59
  # Configure the GUI panel size and layout
60
  server.gui.configure_theme(
61
- control_layout="collapsible", # Options: "floating", "collapsible", "fixed"
62
- control_width="small", # Options: "small", "medium", "large"
63
- dark_mode=False, # Set to True for dark mode, False for light mode
64
  show_logo=False,
65
  show_share_button=True
66
  )
67
 
68
  server.scene.set_up_direction(up_dir)
69
- print("Loading frames!")
70
-
71
- # Load both head1 and head2 data
72
- traj_3d_head1 = None
73
- traj_3d_head2 = None
74
- conf_mask_head1 = None
75
- conf_mask_head2 = None
76
- mask_folder = './train'
77
- masks_paths = sorted(glob(mask_folder + '/*.jpg'))
78
-
79
- # Check if masks exist
80
- if masks_paths:
81
- masks = [iio.imread(p) for p in masks_paths]
82
- masks = np.stack(masks, axis=0)
83
- # Convert masks to binary (0 or 1)
84
- masks = (masks < 1).astype(np.float32)
85
- masks = masks.sum(axis=-1) > 2 # Combine all channels, True where any channel was 1
86
- print(f"Original masks shape: {masks.shape}")
87
  else:
88
- # If no masks found, create default masks (all ones)
89
- print("No masks found. Creating default masks (all ones).")
90
- masks = None # Will be initialized with proper dimensions later
91
-
92
- if Path(traj_path).is_dir():
93
- # Load head1 data
94
- traj_3d_paths_head1 = sorted(glob(traj_path + '/pts3d1_p*.npy'),
95
- key=lambda x: int(x.split('_p')[-1].split('.')[0]))
96
- conf_paths_head1 = sorted(glob(traj_path + '/conf1_p*.npy'),
97
- key=lambda x: int(x.split('_p')[-1].split('.')[0]))
98
 
99
- # Load head2 data
100
- traj_3d_paths_head2 = sorted(glob(traj_path + '/pts3d2_p*.npy'),
101
- key=lambda x: int(x.split('_p')[-1].split('.')[0]))
102
- conf_paths_head2 = sorted(glob(traj_path + '/conf2_p*.npy'),
103
- key=lambda x: int(x.split('_p')[-1].split('.')[0]))
104
-
105
- # Process head1
106
- if traj_3d_paths_head1:
107
- if use_float16:
108
- traj_3d_head1 = onp.stack([onp.load(p).astype(onp.float16) for p in traj_3d_paths_head1], axis=0)
109
- else:
110
- traj_3d_head1 = onp.stack([onp.load(p) for p in traj_3d_paths_head1], axis=0)
111
-
112
- log_memory_usage("after loading head1 data")
113
-
114
- h, w, _ = traj_3d_head1.shape[1:]
 
 
 
115
 
116
- # If masks is None, create default masks (all ones)
117
- if masks is None:
118
- num_frames = traj_3d_head1.shape[0]
119
- masks = np.ones((num_frames, h, w), dtype=bool)
120
- print(f"Created default masks with shape: {masks.shape}")
121
- else:
122
- # Resize masks to match trajectory dimensions using nearest neighbor interpolation
123
- masks_resized = np.zeros((masks.shape[0], h, w), dtype=bool)
124
- for i in range(masks.shape[0]):
125
- masks_resized[i] = cv2.resize(
126
- masks[i].astype(np.uint8),
127
- (w, h),
128
- interpolation=cv2.INTER_NEAREST
129
- ).astype(bool)
130
 
131
- print(f"Resized masks shape: {masks_resized.shape}")
132
- masks = masks_resized
133
-
134
- # Reshape trajectory data
135
- traj_3d_head1 = traj_3d_head1.reshape(traj_3d_head1.shape[0], -1, 6)
136
-
137
- if conf_paths_head1:
138
- conf_head1 = onp.stack([onp.load(p).astype(onp.float16) for p in conf_paths_head1], axis=0)
139
- conf_head1 = conf_head1.reshape(conf_head1.shape[0], -1)
140
- conf_mask_head1 = conf_head1 > conf_thre
141
-
142
- # Process head2
143
- if traj_3d_paths_head2:
144
- if use_float16:
145
- traj_3d_head2 = onp.stack([onp.load(p).astype(onp.float16) for p in traj_3d_paths_head2], axis=0)
146
- else:
147
- traj_3d_head2 = onp.stack([onp.load(p) for p in traj_3d_paths_head2], axis=0)
148
 
149
- log_memory_usage("after loading head2 data")
150
-
151
- traj_3d_head2 = traj_3d_head2.reshape(traj_3d_head2.shape[0], -1, 6)
152
- if conf_paths_head2:
153
- conf_head2 = onp.stack([onp.load(p).astype(onp.float16) for p in conf_paths_head2], axis=0)
154
- conf_head2 = conf_head2.reshape(conf_head2.shape[0], -1)
155
- conf_mask_head2 = conf_head2 > conf_thre
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
 
157
  # Add visualization controls
158
  with server.gui.add_folder("Visualization"):
 
42
  traj_line_width: float = 3.,
43
  fixed_length_traj: int = 10,
44
  server: viser.ViserServer = None,
45
+ use_float16: bool = True,
46
+ preloaded_data: dict = None, # Add this parameter to accept preloaded data
47
  ) -> None:
48
+ log_memory_usage("at start of visualization")
49
 
50
  if server is None:
51
  server = viser.ViserServer()
 
59
 
60
  # Configure the GUI panel size and layout
61
  server.gui.configure_theme(
62
+ control_layout="collapsible",
63
+ control_width="small",
64
+ dark_mode=False,
65
  show_logo=False,
66
  show_share_button=True
67
  )
68
 
69
  server.scene.set_up_direction(up_dir)
70
+ print("Setting up visualization!")
71
+
72
+ # Use preloaded data if available
73
+ if preloaded_data and preloaded_data['loaded']:
74
+ traj_3d_head1 = preloaded_data['traj_3d_head1']
75
+ traj_3d_head2 = preloaded_data['traj_3d_head2']
76
+ conf_mask_head1 = preloaded_data['conf_mask_head1']
77
+ conf_mask_head2 = preloaded_data['conf_mask_head2']
78
+ masks = preloaded_data['masks']
79
+ print("Using preloaded data!")
 
 
 
 
 
 
 
 
80
  else:
81
+ # Original data loading code (as a fallback)
82
+ print("No preloaded data available, loading from files...")
83
+ # Load both head1 and head2 data
84
+ traj_3d_head1 = None
85
+ traj_3d_head2 = None
86
+ conf_mask_head1 = None
87
+ conf_mask_head2 = None
88
+ mask_folder = './train'
89
+ masks_paths = sorted(glob(mask_folder + '/*.jpg'))
 
90
 
91
+ # Check if masks exist
92
+ if masks_paths:
93
+ masks = [iio.imread(p) for p in masks_paths]
94
+ masks = np.stack(masks, axis=0)
95
+ # Convert masks to binary (0 or 1)
96
+ masks = (masks < 1).astype(np.float32)
97
+ masks = masks.sum(axis=-1) > 2 # Combine all channels, True where any channel was 1
98
+ print(f"Original masks shape: {masks.shape}")
99
+ else:
100
+ # If no masks found, create default masks (all ones)
101
+ print("No masks found. Creating default masks (all ones).")
102
+ masks = None # Will be initialized with proper dimensions later
103
+
104
+ if Path(traj_path).is_dir():
105
+ # Load head1 data
106
+ traj_3d_paths_head1 = sorted(glob(traj_path + '/pts3d1_p*.npy'),
107
+ key=lambda x: int(x.split('_p')[-1].split('.')[0]))
108
+ conf_paths_head1 = sorted(glob(traj_path + '/conf1_p*.npy'),
109
+ key=lambda x: int(x.split('_p')[-1].split('.')[0]))
110
 
111
+ # Load head2 data
112
+ traj_3d_paths_head2 = sorted(glob(traj_path + '/pts3d2_p*.npy'),
113
+ key=lambda x: int(x.split('_p')[-1].split('.')[0]))
114
+ conf_paths_head2 = sorted(glob(traj_path + '/conf2_p*.npy'),
115
+ key=lambda x: int(x.split('_p')[-1].split('.')[0]))
116
+
117
+ # Process head1
118
+ if traj_3d_paths_head1:
119
+ if use_float16:
120
+ traj_3d_head1 = onp.stack([onp.load(p).astype(onp.float16) for p in traj_3d_paths_head1], axis=0)
121
+ else:
122
+ traj_3d_head1 = onp.stack([onp.load(p) for p in traj_3d_paths_head1], axis=0)
123
+
124
+ log_memory_usage("after loading head1 data")
125
 
126
+ h, w, _ = traj_3d_head1.shape[1:]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
 
128
+ # If masks is None, create default masks (all ones)
129
+ if masks is None:
130
+ num_frames = traj_3d_head1.shape[0]
131
+ masks = np.ones((num_frames, h, w), dtype=bool)
132
+ print(f"Created default masks with shape: {masks.shape}")
133
+ else:
134
+ # Resize masks to match trajectory dimensions using nearest neighbor interpolation
135
+ masks_resized = np.zeros((masks.shape[0], h, w), dtype=bool)
136
+ for i in range(masks.shape[0]):
137
+ masks_resized[i] = cv2.resize(
138
+ masks[i].astype(np.uint8),
139
+ (w, h),
140
+ interpolation=cv2.INTER_NEAREST
141
+ ).astype(bool)
142
+
143
+ print(f"Resized masks shape: {masks_resized.shape}")
144
+ masks = masks_resized
145
+
146
+ # Reshape trajectory data
147
+ traj_3d_head1 = traj_3d_head1.reshape(traj_3d_head1.shape[0], -1, 6)
148
+
149
+ if conf_paths_head1:
150
+ conf_head1 = onp.stack([onp.load(p).astype(onp.float16) for p in conf_paths_head1], axis=0)
151
+ conf_head1 = conf_head1.reshape(conf_head1.shape[0], -1)
152
+ conf_mask_head1 = conf_head1 > conf_thre
153
+
154
+ # Process head2
155
+ if traj_3d_paths_head2:
156
+ if use_float16:
157
+ traj_3d_head2 = onp.stack([onp.load(p).astype(onp.float16) for p in traj_3d_paths_head2], axis=0)
158
+ else:
159
+ traj_3d_head2 = onp.stack([onp.load(p) for p in traj_3d_paths_head2], axis=0)
160
+
161
+ log_memory_usage("after loading head2 data")
162
+
163
+ traj_3d_head2 = traj_3d_head2.reshape(traj_3d_head2.shape[0], -1, 6)
164
+ if conf_paths_head2:
165
+ conf_head2 = onp.stack([onp.load(p).astype(onp.float16) for p in conf_paths_head2], axis=0)
166
+ conf_head2 = conf_head2.reshape(conf_head2.shape[0], -1)
167
+ conf_mask_head2 = conf_head2 > conf_thre
168
 
169
  # Add visualization controls
170
  with server.gui.add_folder("Visualization"):