Lefei commited on
Commit
2ac4402
·
verified ·
1 Parent(s): 2091b13

update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -9
app.py CHANGED
@@ -1,11 +1,14 @@
1
  # app.py
2
  import os
 
 
3
  import gradio as gr
4
  import torch
5
  import numpy as np
6
  import pandas as pd
7
  import matplotlib.pyplot as plt
8
  import einops
 
9
 
10
  from huggingface_hub import snapshot_download
11
  from visionts import VisionTSpp, freq_to_seasonality_list
@@ -31,6 +34,7 @@ model = VisionTSpp(
31
  ARCH,
32
  ckpt_path=CKPT_PATH,
33
  # quantiles=QUANTILES,
 
34
  clip_input=True,
35
  complete_no_clip=False,
36
  color=True
@@ -48,8 +52,8 @@ imagenet_std = np.array([0.229, 0.224, 0.225])
48
  # This dictionary maps user-friendly names to local file paths
49
  # ASSUMPTION: These files exist in a 'datasets' subfolder
50
 
51
- # data_dir = "./datasets/"
52
- data_dir = "./"
53
  PRESET_DATASETS = {
54
  "ETTm1": data_dir + "ETTm1.csv",
55
  "ETTm2": data_dir + "ETTm2.csv",
@@ -71,27 +75,40 @@ def load_preset_data(name):
71
  # 3. Visualization Functions (No changes needed)
72
  # ========================
73
  def show_image_tensor(image_tensor, title='', cur_nvars=1, cur_color_list=None):
74
- if image_tensor is None: return None
75
- image = image_tensor.permute(1, 2, 0).cpu()
 
 
 
 
 
76
  cur_image = torch.zeros_like(image)
 
77
  height_per_var = image.shape[0] // cur_nvars
78
  for i in range(cur_nvars):
79
  cur_color_idx = cur_color_list[i]
80
  var_slice = image[i*height_per_var:(i+1)*height_per_var, :, :]
81
  unnormalized_channel = var_slice[:, :, cur_color_idx] * imagenet_std[cur_color_idx] + imagenet_mean[cur_color_idx]
82
  cur_image[i*height_per_var:(i+1)*height_per_var, :, cur_color_idx] = unnormalized_channel * 255
 
83
  cur_image = torch.clamp(cur_image, 0, 255).int().numpy()
 
84
  fig, ax = plt.subplots(figsize=(6, 6))
85
  ax.imshow(cur_image)
86
  ax.set_title(title, fontsize=14)
87
  ax.axis('off')
 
88
  plt.tight_layout()
89
  plt.close(fig)
 
90
  return fig
91
 
92
  def visual_ts_with_quantiles(true_data, pred_median, pred_quantiles_list, model_quantiles, context_len, pred_len):
93
- if isinstance(true_data, torch.Tensor): true_data = true_data.cpu().numpy()
94
- if isinstance(pred_median, torch.Tensor): pred_median = pred_median.cpu().numpy()
 
 
 
95
  for i, q in enumerate(pred_quantiles_list):
96
  if isinstance(q, torch.Tensor):
97
  pred_quantiles_list[i] = q.cpu().numpy()
@@ -99,11 +116,17 @@ def visual_ts_with_quantiles(true_data, pred_median, pred_quantiles_list, model_
99
  nvars = true_data.shape[1]
100
  FIG_WIDTH, FIG_HEIGHT_PER_VAR = 15, 2.0
101
  fig, axes = plt.subplots(nvars, 1, figsize=(FIG_WIDTH, nvars * FIG_HEIGHT_PER_VAR), sharex=True)
102
- if nvars == 1: axes = [axes]
 
 
 
 
 
103
 
104
  sorted_quantiles = sorted(zip(model_quantiles, pred_quantiles_list + [pred_median]), key=lambda x: x[0])
105
  quantile_preds = [item[1] for item in sorted_quantiles if item[0] != 0.5]
106
  quantile_vals = [item[0] for item in sorted_quantiles if item[0] != 0.5]
 
107
  num_bands = len(quantile_preds) // 2
108
  quantile_colors = plt.cm.Blues(np.linspace(0.3, 0.8, num_bands))[::-1]
109
 
@@ -128,6 +151,7 @@ def visual_ts_with_quantiles(true_data, pred_median, pred_quantiles_list, model_
128
  fig.legend(unique_labels.values(), unique_labels.keys(), loc='upper center', bbox_to_anchor=(0.5, 1.05), ncol=num_bands + 2)
129
  plt.tight_layout(rect=[0, 0, 1, 0.95])
130
  plt.close(fig)
 
131
  return fig
132
 
133
 
@@ -159,6 +183,7 @@ def predict_at_index(df, index, context_len, pred_len):
159
  inferred_freq = pd.tseries.frequencies.to_offset(time_diff).freqstr
160
  gr.Warning(f"Could not reliably infer frequency. Using fallback based on first two timestamps: {inferred_freq}")
161
  print(f"Inferred frequency: {inferred_freq}")
 
162
  except Exception as e:
163
  raise gr.Error(f"❌ Date processing failed: {e}. Please check the date format (e.g., YYYY-MM-DD HH:MM:SS).")
164
 
@@ -167,7 +192,7 @@ def predict_at_index(df, index, context_len, pred_len):
167
 
168
  total_samples = len(data) - context_len - pred_len + 1
169
  if total_samples <= 0:
170
- raise gr.Error(f"Data is too short. It needs at least {context_len + pred_len} rows, but has {len(data)}.")
171
 
172
  index = max(0, min(index, total_samples - 1))
173
 
@@ -184,6 +209,7 @@ def predict_at_index(df, index, context_len, pred_len):
184
  # *** Use inferred frequency ***
185
  periodicity_list = freq_to_seasonality_list(inferred_freq)
186
  periodicity = periodicity_list[0] if periodicity_list else 1
 
187
  color_list = [i % 3 for i in range(nvars)]
188
  model.update_config(context_len=context_len, pred_len=pred_len, periodicity=periodicity)
189
 
@@ -191,10 +217,39 @@ def predict_at_index(df, index, context_len, pred_len):
191
  y_pred, input_image, reconstructed_image, _, _ = model.forward(
192
  x_tensor, export_image=True, color_list=color_list
193
  )
194
- all_preds = dict(zip(model.quantiles, y_pred))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
  pred_median_norm = all_preds.pop(0.5)[0]
196
  pred_quantiles_norm = [q[0] for q in list(all_preds.values())]
197
 
 
 
 
198
  y_true = y_true_norm * x_std + x_mean
199
  pred_median = pred_median_norm.cpu().numpy() * x_std + x_mean
200
  pred_quantiles = [q.cpu().numpy() * x_std + x_mean for q in pred_quantiles_norm]
@@ -251,6 +306,7 @@ def run_forecast(data_source, upload_file, index, context_len, pred_len):
251
  gr.update(maximum=result.total_samples - 1, value=final_index),
252
  gr.update(value=result.inferred_freq) # *** Update frequency textbox ***
253
  )
 
254
  except Exception as e:
255
  error_fig = plt.figure(figsize=(10, 5))
256
  plt.text(0.5, 0.5, f"An error occurred:\n{str(e)}", ha='center', va='center', wrap=True, color='red', fontsize=12)
 
1
  # app.py
2
  import os
3
+ os.environ["GRADIO_TEMP_DIR"] = "/home/mouxiangchen/VisionTSpp/gradio_tmp"
4
+
5
  import gradio as gr
6
  import torch
7
  import numpy as np
8
  import pandas as pd
9
  import matplotlib.pyplot as plt
10
  import einops
11
+ import copy
12
 
13
  from huggingface_hub import snapshot_download
14
  from visionts import VisionTSpp, freq_to_seasonality_list
 
34
  ARCH,
35
  ckpt_path=CKPT_PATH,
36
  # quantiles=QUANTILES,
37
+ quantile=True,
38
  clip_input=True,
39
  complete_no_clip=False,
40
  color=True
 
52
  # This dictionary maps user-friendly names to local file paths
53
  # ASSUMPTION: These files exist in a 'datasets' subfolder
54
 
55
+ data_dir = "./datasets/"
56
+ # data_dir = "./"
57
  PRESET_DATASETS = {
58
  "ETTm1": data_dir + "ETTm1.csv",
59
  "ETTm2": data_dir + "ETTm2.csv",
 
75
  # 3. Visualization Functions (No changes needed)
76
  # ========================
77
  def show_image_tensor(image_tensor, title='', cur_nvars=1, cur_color_list=None):
78
+ if image_tensor is None:
79
+ return None
80
+
81
+ # no need for permute?
82
+ # image = image_tensor.permute(1, 2, 0).cpu()
83
+ image = image_tensor.cpu()
84
+
85
  cur_image = torch.zeros_like(image)
86
+
87
  height_per_var = image.shape[0] // cur_nvars
88
  for i in range(cur_nvars):
89
  cur_color_idx = cur_color_list[i]
90
  var_slice = image[i*height_per_var:(i+1)*height_per_var, :, :]
91
  unnormalized_channel = var_slice[:, :, cur_color_idx] * imagenet_std[cur_color_idx] + imagenet_mean[cur_color_idx]
92
  cur_image[i*height_per_var:(i+1)*height_per_var, :, cur_color_idx] = unnormalized_channel * 255
93
+
94
  cur_image = torch.clamp(cur_image, 0, 255).int().numpy()
95
+
96
  fig, ax = plt.subplots(figsize=(6, 6))
97
  ax.imshow(cur_image)
98
  ax.set_title(title, fontsize=14)
99
  ax.axis('off')
100
+
101
  plt.tight_layout()
102
  plt.close(fig)
103
+
104
  return fig
105
 
106
  def visual_ts_with_quantiles(true_data, pred_median, pred_quantiles_list, model_quantiles, context_len, pred_len):
107
+ if isinstance(true_data, torch.Tensor):
108
+ true_data = true_data.cpu().numpy()
109
+ if isinstance(pred_median, torch.Tensor):
110
+ pred_median = pred_median.cpu().numpy()
111
+
112
  for i, q in enumerate(pred_quantiles_list):
113
  if isinstance(q, torch.Tensor):
114
  pred_quantiles_list[i] = q.cpu().numpy()
 
116
  nvars = true_data.shape[1]
117
  FIG_WIDTH, FIG_HEIGHT_PER_VAR = 15, 2.0
118
  fig, axes = plt.subplots(nvars, 1, figsize=(FIG_WIDTH, nvars * FIG_HEIGHT_PER_VAR), sharex=True)
119
+ if nvars == 1:
120
+ axes = [axes]
121
+
122
+ print(f"{len(pred_quantiles_list) = }")
123
+ print(f"{len(model_quantiles) = }")
124
+ print(f"{pred_quantiles_list[0].shape = }")
125
 
126
  sorted_quantiles = sorted(zip(model_quantiles, pred_quantiles_list + [pred_median]), key=lambda x: x[0])
127
  quantile_preds = [item[1] for item in sorted_quantiles if item[0] != 0.5]
128
  quantile_vals = [item[0] for item in sorted_quantiles if item[0] != 0.5]
129
+
130
  num_bands = len(quantile_preds) // 2
131
  quantile_colors = plt.cm.Blues(np.linspace(0.3, 0.8, num_bands))[::-1]
132
 
 
151
  fig.legend(unique_labels.values(), unique_labels.keys(), loc='upper center', bbox_to_anchor=(0.5, 1.05), ncol=num_bands + 2)
152
  plt.tight_layout(rect=[0, 0, 1, 0.95])
153
  plt.close(fig)
154
+
155
  return fig
156
 
157
 
 
183
  inferred_freq = pd.tseries.frequencies.to_offset(time_diff).freqstr
184
  gr.Warning(f"Could not reliably infer frequency. Using fallback based on first two timestamps: {inferred_freq}")
185
  print(f"Inferred frequency: {inferred_freq}")
186
+
187
  except Exception as e:
188
  raise gr.Error(f"❌ Date processing failed: {e}. Please check the date format (e.g., YYYY-MM-DD HH:MM:SS).")
189
 
 
192
 
193
  total_samples = len(data) - context_len - pred_len + 1
194
  if total_samples <= 0:
195
+ raise gr.Error(f"Data is too short. It needs at least context_len + pred_len = {context_len + pred_len} rows, but has {len(data)}.")
196
 
197
  index = max(0, min(index, total_samples - 1))
198
 
 
209
  # *** Use inferred frequency ***
210
  periodicity_list = freq_to_seasonality_list(inferred_freq)
211
  periodicity = periodicity_list[0] if periodicity_list else 1
212
+
213
  color_list = [i % 3 for i in range(nvars)]
214
  model.update_config(context_len=context_len, pred_len=pred_len, periodicity=periodicity)
215
 
 
217
  y_pred, input_image, reconstructed_image, _, _ = model.forward(
218
  x_tensor, export_image=True, color_list=color_list
219
  )
220
+ y_pred, y_pred_quantile_list = y_pred
221
+
222
+ print(f"{x_tensor.shape = }")
223
+ print(f"{y_pred.shape = }")
224
+ print(f"{input_image.shape = }")
225
+ print(f"{reconstructed_image.shape = }")
226
+ print(f"{len(y_pred_quantile_list) = }")
227
+
228
+ print(f"{input_image = }")
229
+ print(f"{input_image[0,0,0, :, 0] = }")
230
+ print(f"{input_image[0,0,0, 50:70, 0] = }")
231
+ print(f"{input_image[0,0,0, 100:120, 0] = }")
232
+ # print(f"{input_image[0] = }")
233
+ # print(f"{reconstructed_image = }")
234
+
235
+ all_y_pred_list = copy.deepcopy(y_pred_quantile_list)
236
+
237
+ # insert in the place of 0.5 quantile, ie:len(QUANTILES)//2
238
+ all_y_pred_list.insert(len(QUANTILES)//2, y_pred)
239
+
240
+ print(f"{len(all_y_pred_list) = }")
241
+ print(f"{all_y_pred_list[0].shape = }")
242
+
243
+ all_preds = dict(zip(QUANTILES, all_y_pred_list))
244
+
245
+ print(f"{all_preds.keys() = }")
246
+
247
  pred_median_norm = all_preds.pop(0.5)[0]
248
  pred_quantiles_norm = [q[0] for q in list(all_preds.values())]
249
 
250
+ print(f"{pred_median_norm.shape = }")
251
+ print(f"{len(pred_quantiles_norm) = }")
252
+
253
  y_true = y_true_norm * x_std + x_mean
254
  pred_median = pred_median_norm.cpu().numpy() * x_std + x_mean
255
  pred_quantiles = [q.cpu().numpy() * x_std + x_mean for q in pred_quantiles_norm]
 
306
  gr.update(maximum=result.total_samples - 1, value=final_index),
307
  gr.update(value=result.inferred_freq) # *** Update frequency textbox ***
308
  )
309
+
310
  except Exception as e:
311
  error_fig = plt.figure(figsize=(10, 5))
312
  plt.text(0.5, 0.5, f"An error occurred:\n{str(e)}", ha='center', va='center', wrap=True, color='red', fontsize=12)