xiezhe22 commited on
Commit
6acc3f3
Β·
0 Parent(s):

Initial commit

Browse files
Files changed (4) hide show
  1. .gitattributes +35 -0
  2. README.md +18 -0
  3. app.py +359 -0
  4. requirements.txt +7 -0
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: ChatTS
3
+ emoji: πŸ’¬
4
+ colorFrom: yellow
5
+ colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: 5.0.1
8
+ app_file: app.py
9
+ pinned: true
10
+ license: apache-2.0
11
+ short_description: Demo for ChatTS
12
+ models:
13
+ - bytedance-research/ChatTS-14B
14
+ datasets:
15
+ - ChatTSRepo/ChatTS-Training-Dataset
16
+ ---
17
+
18
+ A ChatBot space for ChatTS-14B.
app.py ADDED
@@ -0,0 +1,359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces # for ZeroGPU support
2
+ import gradio as gr
3
+ import pandas as pd
4
+ import numpy as np
5
+ import torch
6
+ import subprocess
7
+ from threading import Thread
8
+ from transformers import (
9
+ AutoModelForCausalLM,
10
+ AutoTokenizer,
11
+ AutoProcessor,
12
+ TextIteratorStreamer
13
+ )
14
+
15
+ # ─── MODEL SETUP ────────────────────────────────────────────────────────────────
16
+ MODEL_NAME = "bytedance-research/ChatTS-14B"
17
+
18
+ tokenizer = AutoTokenizer.from_pretrained(
19
+ MODEL_NAME, trust_remote_code=True
20
+ )
21
+ processor = AutoProcessor.from_pretrained(
22
+ MODEL_NAME, trust_remote_code=True, tokenizer=tokenizer
23
+ )
24
+ model = AutoModelForCausalLM.from_pretrained(
25
+ MODEL_NAME,
26
+ trust_remote_code=True,
27
+ device_map="auto",
28
+ torch_dtype=torch.float16
29
+ )
30
+ model.eval()
31
+
32
+ # ─── HELPER FUNCTIONS ──────────────────────────────────────────────────────────
33
+
34
+ def create_default_timeseries():
35
+ """Create default time series with sudden increase"""
36
+ x1 = np.arange(256)
37
+ x2 = np.arange(256)
38
+ ts1 = np.sin(x1 / 10) * 5.0
39
+ ts1[103:] -= 10.0
40
+ ts2 = x2 * 0.01
41
+ ts2[100] += 10.0
42
+
43
+ df = pd.DataFrame({
44
+ "TS1": ts1,
45
+ "TS2": ts2
46
+ })
47
+ return df
48
+
49
+ def process_csv_file(csv_file):
50
+ """Process CSV file and return DataFrame with validation"""
51
+ if csv_file is None:
52
+ return None, "No file uploaded"
53
+
54
+ try:
55
+ df = pd.read_csv(csv_file.name)
56
+
57
+ # drop columns with empty names or all-NaNs
58
+ df.columns = [str(c).strip() for c in df.columns]
59
+ df = df.loc[:, [c for c in df.columns if c]]
60
+ df = df.dropna(axis=1, how="all")
61
+ print(f"File {csv_file.name} loaded. {df.columns=}")
62
+
63
+ if df.shape[1] == 0:
64
+ return None, "No valid time-series columns found."
65
+ if df.shape[1] > 15:
66
+ return None, f"Too many series ({df.shape[1]}). Max allowed = 15."
67
+
68
+ # Validate ALL columns as time series
69
+ ts_names, ts_list = [], []
70
+ for name in df.columns:
71
+ series = df[name]
72
+ # ensure float dtype
73
+ if not pd.api.types.is_float_dtype(series):
74
+ try:
75
+ series = pd.to_numeric(series, errors='coerce')
76
+ except:
77
+ return None, f"Series '{name}' cannot be converted to float type."
78
+
79
+ # trim trailing NaNs only
80
+ last_valid = series.last_valid_index()
81
+ if last_valid is None:
82
+ continue
83
+ trimmed = series.loc[:last_valid].to_numpy(dtype=np.float32)
84
+ length = trimmed.shape[0]
85
+ if length < 64 or length > 1024:
86
+ return None, f"Series '{name}' length {length} invalid. Must be 64 to 1024."
87
+ ts_names.append(name)
88
+ ts_list.append(trimmed)
89
+
90
+ if not ts_list:
91
+ return None, "All time series are empty after trimming NaNs."
92
+ print(f"Successfully loaded {len(ts_names)} time series: {', '.join(ts_names)}")
93
+
94
+ return df, f"Successfully loaded {len(ts_names)} time series: {', '.join(ts_names)}"
95
+
96
+ except Exception as e:
97
+ return None, f"Error processing file: {str(e)}"
98
+
99
+ def preview_csv(csv_file, use_default):
100
+ """Preview uploaded CSV file immediately"""
101
+ if csv_file is None:
102
+ return gr.LinePlot(value=pd.DataFrame()), "Please upload a CSV file first", gr.Dropdown(), False
103
+
104
+ df, message = process_csv_file(csv_file)
105
+
106
+ if df is None:
107
+ return gr.LinePlot(value=pd.DataFrame()), message, gr.Dropdown(), False
108
+
109
+ # Create dropdown choices
110
+ column_choices = list(df.columns)
111
+
112
+ # Create plot with first column as default
113
+ first_column = column_choices[0]
114
+ df_with_index = df.copy()
115
+ df_with_index["_internal_idx"] = np.arange(len(df[first_column].values))
116
+ plot = gr.LinePlot(
117
+ df_with_index,
118
+ x="_internal_idx",
119
+ y=first_column,
120
+ title=f"Time Series: {first_column}"
121
+ )
122
+
123
+ # Update dropdown
124
+ dropdown = gr.Dropdown(
125
+ choices=column_choices,
126
+ value=first_column,
127
+ label="Select a Column to Visualize"
128
+ )
129
+
130
+ print("Successfully generated preview!")
131
+
132
+ return plot, message, dropdown, False # Set use_default to False when file is uploaded
133
+
134
+ def clear_csv():
135
+ """Clear uploaded CSV file immediately"""
136
+ df, message = process_csv_file(None)
137
+
138
+ return gr.LinePlot(value=pd.DataFrame()), message, gr.Dropdown()
139
+
140
+
141
+ def update_plot(csv_file, selected_column, use_default_state):
142
+ """Update plot based on selected column"""
143
+ if (csv_file is None and not use_default_state) or selected_column is None :
144
+ return gr.LinePlot(value=pd.DataFrame())
145
+
146
+ if csv_file is None and use_default_state:
147
+ df = create_default_timeseries()
148
+ else:
149
+ df, _ = process_csv_file(csv_file)
150
+ if df is None:
151
+ return gr.LinePlot(value=pd.DataFrame())
152
+
153
+ df_with_index = df.copy()
154
+ df_with_index["_internal_idx"] = np.arange(len(df[selected_column].values))
155
+
156
+ plot = gr.LinePlot(
157
+ df_with_index,
158
+ x="_internal_idx",
159
+ y=selected_column,
160
+ title=f"Time Series: {selected_column}"
161
+ )
162
+
163
+ return plot
164
+
165
+ def initialize_interface():
166
+ """Initialize interface with default time series"""
167
+ df = create_default_timeseries()
168
+ column_choices = list(df.columns)
169
+ first_column = column_choices[0]
170
+
171
+ df_with_index = df.copy()
172
+ df_with_index["_internal_idx"] = np.arange(len(df[first_column].values))
173
+
174
+ plot = gr.LinePlot(
175
+ df_with_index,
176
+ x="_internal_idx",
177
+ y=first_column,
178
+ title=f"Time Series: {first_column}"
179
+ )
180
+
181
+ dropdown = gr.Dropdown(
182
+ choices=column_choices,
183
+ value=first_column,
184
+ label="Select a Column to Visualize"
185
+ )
186
+
187
+ message = "Using default time series (TS1 and TS2). Please select a time series from the dropdown box above for visualization."
188
+
189
+ return plot, message, dropdown, True # Set use_default to True on initialization
190
+
191
+ # ─── INFERENCE + VALIDATION ────────────────────────────────────────────────────
192
+
193
+ @spaces.GPU # dynamically allocate & release a ZeroGPU device on each call
194
+ def infer_chatts_stream(prompt: str, csv_file, use_default):
195
+ """
196
+ Streaming version of ChatTS inference
197
+ """
198
+ print("Start inferring!!!")
199
+
200
+ if not prompt.strip():
201
+ yield "Please enter a prompt"
202
+ return
203
+
204
+ # Use default if no file uploaded and use_default is True
205
+ if csv_file is None and use_default:
206
+ df = create_default_timeseries()
207
+ error_msg = None
208
+ else:
209
+ df, error_msg = process_csv_file(csv_file)
210
+
211
+ if df is None:
212
+ yield "Please upload a CSV file first or the file contains errors"
213
+ return
214
+
215
+ try:
216
+ # Prepare time series data - use ALL columns
217
+ ts_names, ts_list = [], []
218
+ for name in df.columns:
219
+ series = df[name]
220
+ last_valid = series.last_valid_index()
221
+ if last_valid is not None:
222
+ trimmed = series.loc[:last_valid].to_numpy(dtype=np.float32)
223
+ ts_names.append(name)
224
+ ts_list.append(trimmed)
225
+
226
+ if not ts_list:
227
+ yield "No valid time series data found. Please upload time series first."
228
+ return
229
+
230
+ # Clean prompt
231
+ clean_prompt = prompt.replace("<ts>", "").replace("<ts/>", "")
232
+
233
+ # Build prompt prefix
234
+ prefix = f"I have {len(ts_list)} time series:\n"
235
+ for name, arr in zip(ts_names, ts_list):
236
+ prefix += f"The {name} is of length {len(arr)}: <ts><ts/>\n"
237
+
238
+ 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 at least one time series data before answering.<|im_end|><|im_start|>user\n{prefix}{clean_prompt} Please output a step-by-step analysis about the time series attributes that mentioned in the question first, and then give a detailed result about this question. Always remember to carefully double check the values before answer the results.<|im_end|><|im_start|>assistant\n"
239
+
240
+ print(f"[debug] {full_prompt}. {len(ts_list)=}, {[len(item) for item in ts_list]=}")
241
+
242
+ # Encode inputs
243
+ inputs = processor(
244
+ text=[full_prompt],
245
+ timeseries=ts_list,
246
+ padding=True,
247
+ return_tensors="pt"
248
+ )
249
+ inputs = {k: v.to(model.device) for k, v in inputs.items()}
250
+
251
+ if inputs['timeseries'] is not None:
252
+ print(f"[debug] {inputs['timeseries'].shape=}")
253
+
254
+ # Generate with streaming
255
+ streamer = TextIteratorStreamer(tokenizer, timeout=10., skip_prompt=True, skip_special_tokens=True)
256
+ inputs.update({
257
+ "max_new_tokens": 512,
258
+ "streamer": streamer,
259
+ "temperature": 0.3
260
+ })
261
+ thread = Thread(
262
+ target=model.generate,
263
+ kwargs=inputs
264
+ )
265
+ thread.start()
266
+
267
+ model_output = ""
268
+ for new_text in streamer:
269
+ model_output += new_text
270
+ yield model_output
271
+
272
+ except Exception as e:
273
+ yield f"Error during inference: {str(e)}"
274
+
275
+ # ─── GRADIO APP ────────────────────────────────────────────────────────────────
276
+
277
+ with gr.Blocks(title="ChatTS Demo") as demo:
278
+ gr.Markdown("## ChatTS: Time Series Understanding and Reasoning")
279
+ gr.HTML("""<div style="display:flex;justify-content: center">
280
+ <a href="https://github.com/NetmanAIOps/ChatTS"><img alt="github" src="https://img.shields.io/badge/Code-GitHub-blue"></a>
281
+ <a href="https://huggingface.co/bytedance-research/ChatTS-14B"><img alt="github" src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Model-FFD21E"></a>
282
+ <a href="https://arxiv.org/abs/2412.03104"><img alt="preprint" src="https://img.shields.io/static/v1?label=arXiv&amp;message=2412.03104&amp;color=B31B1B&amp;logo=arXiv"></a>
283
+ </div>""")
284
+ gr.Markdown("Try ChatTS with the default time series, or upload a CSV file (Example: [ts_example.csv](https://github.com/NetManAIOps/ChatTS/blob/main/demo/ts_example.csv)) containing UTS/MTS where each column is a dimension (no index column). All columns will be used as input of ChatTS automatically.")
285
+ gr.Markdown("Suggested time series length: 256. The length should be between 64 and 1024, with 15 time series at most.")
286
+ gr.Markdown("Since ChatTS only supports English, please use English to ask questions. If you like ChatTS, kindly star our [GitHub repo](https://github.com/NetmanAIOps/ChatTS). If you find any issues, feel free to open an issue in the [GitHub Issues](https://github.com/NetManAIOps/ChatTS/issues).")
287
+
288
+ # State to track whether to use default time series
289
+ use_default_state = gr.State(value=True)
290
+
291
+ with gr.Row():
292
+ with gr.Column(scale=1):
293
+ upload = gr.File(
294
+ label="Upload CSV File",
295
+ file_types=[".csv"],
296
+ type="filepath"
297
+ )
298
+
299
+ prompt_input = gr.Textbox(
300
+ lines=6,
301
+ placeholder="Enter your question here...",
302
+ label="Analysis Prompt",
303
+ value="Please analyze all the given time series and provide insights about the local fluctuations in the time series in detail."
304
+ )
305
+
306
+ run_btn = gr.Button("Run ChatTS", variant="primary")
307
+
308
+ with gr.Column(scale=2):
309
+ series_selector = gr.Dropdown(
310
+ label="Select a Column to Visualize",
311
+ choices=[],
312
+ value=None
313
+ )
314
+ plot_out = gr.LinePlot(value=pd.DataFrame(), label="Time Series Visualization")
315
+ file_status = gr.Textbox(
316
+ label="File Status",
317
+ interactive=False,
318
+ lines=2
319
+ )
320
+
321
+ text_out = gr.Textbox(
322
+ lines=10,
323
+ label="ChatTS Analysis Results",
324
+ interactive=False
325
+ )
326
+
327
+ # Initialize interface with default data
328
+ demo.load(
329
+ fn=initialize_interface,
330
+ outputs=[plot_out, file_status, series_selector, use_default_state]
331
+ )
332
+
333
+ # Event handlers
334
+ upload.upload(
335
+ fn=preview_csv,
336
+ inputs=[upload, use_default_state],
337
+ outputs=[plot_out, file_status, series_selector, use_default_state]
338
+ )
339
+
340
+ upload.clear(
341
+ fn=clear_csv,
342
+ inputs=[],
343
+ outputs=[plot_out, file_status, series_selector]
344
+ )
345
+
346
+ series_selector.change(
347
+ fn=update_plot,
348
+ inputs=[upload, series_selector, use_default_state],
349
+ outputs=[plot_out]
350
+ )
351
+
352
+ run_btn.click(
353
+ fn=infer_chatts_stream,
354
+ inputs=[prompt_input, upload, use_default_state],
355
+ outputs=[text_out]
356
+ )
357
+
358
+ if __name__ == '__main__':
359
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ huggingface_hub==0.25.2
2
+ transformers<=4.49.0
3
+ numpy
4
+ pandas
5
+ accelerate
6
+ torch>=2.2.0
7
+ pydantic==2.10.6