xiezhe22 commited on
Commit
20602ee
Β·
1 Parent(s): 3848804
Files changed (1) hide show
  1. app.py +36 -16
app.py CHANGED
@@ -89,15 +89,15 @@ def process_csv_file(csv_file):
89
  except Exception as e:
90
  return None, f"Error processing file: {str(e)}"
91
 
92
- def preview_csv(csv_file):
93
  """Preview uploaded CSV file immediately"""
94
  if csv_file is None:
95
- return gr.LinePlot(value=pd.DataFrame()), "Please upload a CSV file first", gr.Dropdown()
96
 
97
  df, message = process_csv_file(csv_file)
98
 
99
  if df is None:
100
- return gr.LinePlot(value=pd.DataFrame()), message, gr.Dropdown()
101
 
102
  # Create dropdown choices
103
  column_choices = list(df.columns)
@@ -122,7 +122,14 @@ def preview_csv(csv_file):
122
 
123
  print("Successfully generated preview!")
124
 
125
- return plot, message, dropdown
 
 
 
 
 
 
 
126
 
127
  def update_plot(csv_file, selected_column):
128
  """Update plot based on selected column"""
@@ -169,12 +176,12 @@ def initialize_interface():
169
 
170
  message = "Using default time series with sudden increase at step 100"
171
 
172
- return plot, message, dropdown
173
 
174
  # ─── INFERENCE + VALIDATION ────────────────────────────────────────────────────
175
 
176
  @spaces.GPU # dynamically allocate & release a ZeroGPU device on each call
177
- def infer_chatts_stream(prompt: str, csv_file):
178
  """
179
  Streaming version of ChatTS inference
180
  """
@@ -184,15 +191,15 @@ def infer_chatts_stream(prompt: str, csv_file):
184
  yield "Please enter a prompt"
185
  return
186
 
187
- # Use default if no file uploaded, otherwise process CSV
188
- if csv_file is None:
189
  df = create_default_timeseries()
190
  error_msg = None
191
  else:
192
  df, error_msg = process_csv_file(csv_file)
193
 
194
  if df is None:
195
- yield f"Error: {error_msg}"
196
  return
197
 
198
  try:
@@ -206,17 +213,21 @@ def infer_chatts_stream(prompt: str, csv_file):
206
  ts_names.append(name)
207
  ts_list.append(trimmed)
208
 
209
- # Add chat_template
 
 
 
 
210
  clean_prompt = prompt.replace("<ts>", "").replace("<ts/>", "")
211
- formatted_prompt = f"<|im_start|>system\nYou are a helpful assistant. Your name is ChatTS. You can analyze time series data and provide insights. If user asks who you are, you should give your name and capabilities in the language of the prompt. If no time series are provided, you should say 'I cannot answer this question as you haven't provide the timeseries I need' in the language of the prompt. Always check if the user has provided time series data before answering.<|im_end|><|im_start|>user\n{clean_prompt}<|im_end|><|im_start|>assistant\n"
212
 
213
  # Build prompt prefix
214
  prefix = f"I have {len(ts_list)} time series:\n"
215
  for name, arr in zip(ts_names, ts_list):
216
  prefix += f"The {name} is of length {len(arr)}: <ts><ts/>\n"
217
- full_prompt = prefix + formatted_prompt
 
218
 
219
- print(f"[debug] {full_prompt=}, {len(ts_list)=}, {[len(item) for item in ts_list]=}")
220
 
221
  # Encode inputs
222
  inputs = processor(
@@ -254,6 +265,9 @@ with gr.Blocks(title="ChatTS Demo") as demo:
254
  gr.Markdown("## ChatTS Demo: Time Series Understanding and Reasoning")
255
  gr.Markdown("Upload a CSV file where each column is a time series, or use the default time series with sudden increase. All columns will be treated as time series data.")
256
 
 
 
 
257
  with gr.Row():
258
  with gr.Column(scale=1):
259
  upload = gr.File(
@@ -293,13 +307,19 @@ with gr.Blocks(title="ChatTS Demo") as demo:
293
  # Initialize interface with default data
294
  demo.load(
295
  fn=initialize_interface,
296
- outputs=[plot_out, file_status, series_selector]
297
  )
298
 
299
  # Event handlers
300
  upload.upload(
301
  fn=preview_csv,
302
- inputs=[upload],
 
 
 
 
 
 
303
  outputs=[plot_out, file_status, series_selector]
304
  )
305
 
@@ -311,7 +331,7 @@ with gr.Blocks(title="ChatTS Demo") as demo:
311
 
312
  run_btn.click(
313
  fn=infer_chatts_stream,
314
- inputs=[prompt_input, upload],
315
  outputs=[text_out]
316
  )
317
 
 
89
  except Exception as e:
90
  return None, f"Error processing file: {str(e)}"
91
 
92
+ def preview_csv(csv_file, use_default):
93
  """Preview uploaded CSV file immediately"""
94
  if csv_file is None:
95
+ return gr.LinePlot(value=pd.DataFrame()), "Please upload a CSV file first", gr.Dropdown(), False
96
 
97
  df, message = process_csv_file(csv_file)
98
 
99
  if df is None:
100
+ return gr.LinePlot(value=pd.DataFrame()), message, gr.Dropdown(), False
101
 
102
  # Create dropdown choices
103
  column_choices = list(df.columns)
 
122
 
123
  print("Successfully generated preview!")
124
 
125
+ return plot, message, dropdown, False # Set use_default to False when file is uploaded
126
+
127
+ def clear_csv():
128
+ """Clear uploaded CSV file immediately"""
129
+ df, message = process_csv_file(None)
130
+
131
+ return gr.LinePlot(value=pd.DataFrame()), message, gr.Dropdown()
132
+
133
 
134
  def update_plot(csv_file, selected_column):
135
  """Update plot based on selected column"""
 
176
 
177
  message = "Using default time series with sudden increase at step 100"
178
 
179
+ return plot, message, dropdown, True # Set use_default to True on initialization
180
 
181
  # ─── INFERENCE + VALIDATION ────────────────────────────────────────────────────
182
 
183
  @spaces.GPU # dynamically allocate & release a ZeroGPU device on each call
184
+ def infer_chatts_stream(prompt: str, csv_file, use_default):
185
  """
186
  Streaming version of ChatTS inference
187
  """
 
191
  yield "Please enter a prompt"
192
  return
193
 
194
+ # Use default if no file uploaded and use_default is True
195
+ if csv_file is None and use_default:
196
  df = create_default_timeseries()
197
  error_msg = None
198
  else:
199
  df, error_msg = process_csv_file(csv_file)
200
 
201
  if df is None:
202
+ yield "Please upload a CSV file first or the file contains errors"
203
  return
204
 
205
  try:
 
213
  ts_names.append(name)
214
  ts_list.append(trimmed)
215
 
216
+ if not ts_list:
217
+ yield "No valid time series data found. Please upload time series first."
218
+ return
219
+
220
+ # Clean prompt
221
  clean_prompt = prompt.replace("<ts>", "").replace("<ts/>", "")
 
222
 
223
  # Build prompt prefix
224
  prefix = f"I have {len(ts_list)} time series:\n"
225
  for name, arr in zip(ts_names, ts_list):
226
  prefix += f"The {name} is of length {len(arr)}: <ts><ts/>\n"
227
+
228
+ full_prompt = f"<|im_start|>system\nYou are a helpful assistant. Your name is ChatTS. You can analyze time series data and provide insights. If user asks who you are, you should give your name and capabilities in the language of the prompt. If no time series are provided, you should say 'I cannot answer this question as you haven't provide the timeseries I need' in the language of the prompt. Always check if the user has provided time series data before answering.<|im_end|><|im_start|>user\n{prefix}{clean_prompt}<|im_end|><|im_start|>assistant\n"
229
 
230
+ print(f"[debug] {len(ts_list)=}, {[len(item) for item in ts_list]=}")
231
 
232
  # Encode inputs
233
  inputs = processor(
 
265
  gr.Markdown("## ChatTS Demo: Time Series Understanding and Reasoning")
266
  gr.Markdown("Upload a CSV file where each column is a time series, or use the default time series with sudden increase. All columns will be treated as time series data.")
267
 
268
+ # State to track whether to use default time series
269
+ use_default_state = gr.State(value=True)
270
+
271
  with gr.Row():
272
  with gr.Column(scale=1):
273
  upload = gr.File(
 
307
  # Initialize interface with default data
308
  demo.load(
309
  fn=initialize_interface,
310
+ outputs=[plot_out, file_status, series_selector, use_default_state]
311
  )
312
 
313
  # Event handlers
314
  upload.upload(
315
  fn=preview_csv,
316
+ inputs=[upload, use_default_state],
317
+ outputs=[plot_out, file_status, series_selector, use_default_state]
318
+ )
319
+
320
+ upload.clear(
321
+ fn=clear_csv,
322
+ inputs=[],
323
  outputs=[plot_out, file_status, series_selector]
324
  )
325
 
 
331
 
332
  run_btn.click(
333
  fn=infer_chatts_stream,
334
+ inputs=[prompt_input, upload, use_default_state],
335
  outputs=[text_out]
336
  )
337