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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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):
|
142 |
+
"""Update plot based on selected column"""
|
143 |
+
if csv_file is None or selected_column is None:
|
144 |
+
return gr.LinePlot(value=pd.DataFrame())
|
145 |
+
|
146 |
+
df, _ = process_csv_file(csv_file)
|
147 |
+
if df is None:
|
148 |
+
return gr.LinePlot(value=pd.DataFrame())
|
149 |
+
|
150 |
+
df_with_index = df.copy()
|
151 |
+
df_with_index["_internal_idx"] = np.arange(len(df[selected_column].values))
|
152 |
+
|
153 |
+
plot = gr.LinePlot(
|
154 |
+
df_with_index,
|
155 |
+
x="_internal_idx",
|
156 |
+
y=selected_column,
|
157 |
+
title=f"Time Series: {selected_column}"
|
158 |
+
)
|
159 |
+
|
160 |
+
return plot
|
161 |
+
|
162 |
+
def initialize_interface():
|
163 |
+
"""Initialize interface with default time series"""
|
164 |
+
df = create_default_timeseries()
|
165 |
+
column_choices = list(df.columns)
|
166 |
+
first_column = column_choices[0]
|
167 |
+
|
168 |
+
df_with_index = df.copy()
|
169 |
+
df_with_index["_internal_idx"] = np.arange(len(df[first_column].values))
|
170 |
+
|
171 |
+
plot = gr.LinePlot(
|
172 |
+
df_with_index,
|
173 |
+
x="_internal_idx",
|
174 |
+
y=first_column,
|
175 |
+
title=f"Time Series: {first_column}"
|
176 |
+
)
|
177 |
+
|
178 |
+
dropdown = gr.Dropdown(
|
179 |
+
choices=column_choices,
|
180 |
+
value=first_column,
|
181 |
+
label="Select a Column to Visualize"
|
182 |
+
)
|
183 |
+
|
184 |
+
message = "Using default time series with sudden increase at step 100"
|
185 |
+
|
186 |
+
return plot, message, dropdown, True # Set use_default to True on initialization
|
187 |
+
|
188 |
+
# βββ INFERENCE + VALIDATION ββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
189 |
+
|
190 |
+
@spaces.GPU # dynamically allocate & release a ZeroGPU device on each call
|
191 |
+
def infer_chatts_stream(prompt: str, csv_file, use_default):
|
192 |
+
"""
|
193 |
+
Streaming version of ChatTS inference
|
194 |
+
"""
|
195 |
+
print("Start inferring!!!")
|
196 |
+
|
197 |
+
if not prompt.strip():
|
198 |
+
yield "Please enter a prompt"
|
199 |
+
return
|
200 |
+
|
201 |
+
# Use default if no file uploaded and use_default is True
|
202 |
+
if csv_file is None and use_default:
|
203 |
+
df = create_default_timeseries()
|
204 |
+
error_msg = None
|
205 |
+
else:
|
206 |
+
df, error_msg = process_csv_file(csv_file)
|
207 |
+
|
208 |
+
if df is None:
|
209 |
+
yield "Please upload a CSV file first or the file contains errors"
|
210 |
+
return
|
211 |
+
|
212 |
+
try:
|
213 |
+
# Prepare time series data - use ALL columns
|
214 |
+
ts_names, ts_list = [], []
|
215 |
+
for name in df.columns:
|
216 |
+
series = df[name]
|
217 |
+
last_valid = series.last_valid_index()
|
218 |
+
if last_valid is not None:
|
219 |
+
trimmed = series.loc[:last_valid].to_numpy(dtype=np.float32)
|
220 |
+
ts_names.append(name)
|
221 |
+
ts_list.append(trimmed)
|
222 |
+
|
223 |
+
if not ts_list:
|
224 |
+
yield "No valid time series data found. Please upload time series first."
|
225 |
+
return
|
226 |
+
|
227 |
+
# Clean prompt
|
228 |
+
clean_prompt = prompt.replace("<ts>", "").replace("<ts/>", "")
|
229 |
+
|
230 |
+
# Build prompt prefix
|
231 |
+
prefix = f"I have {len(ts_list)} time series:\n"
|
232 |
+
for name, arr in zip(ts_names, ts_list):
|
233 |
+
prefix += f"The {name} is of length {len(arr)}: <ts><ts/>\n"
|
234 |
+
|
235 |
+
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}<|im_end|><|im_start|>assistant\n"
|
236 |
+
|
237 |
+
print(f"[debug] {full_prompt}. {len(ts_list)=}, {[len(item) for item in ts_list]=}")
|
238 |
+
|
239 |
+
# Encode inputs
|
240 |
+
inputs = processor(
|
241 |
+
text=[full_prompt],
|
242 |
+
timeseries=ts_list,
|
243 |
+
padding=True,
|
244 |
+
return_tensors="pt"
|
245 |
+
)
|
246 |
+
inputs = {k: v.to(model.device) for k, v in inputs.items()}
|
247 |
+
|
248 |
+
if inputs['timeseries'] is not None:
|
249 |
+
print(f"[debug] {inputs['timeseries'].shape=}")
|
250 |
+
|
251 |
+
# Generate with streaming
|
252 |
+
streamer = TextIteratorStreamer(tokenizer, timeout=10., skip_prompt=True, skip_special_tokens=True)
|
253 |
+
inputs.update({
|
254 |
+
"max_new_tokens": 512,
|
255 |
+
"streamer": streamer,
|
256 |
+
"temperature": 0.3
|
257 |
+
})
|
258 |
+
thread = Thread(
|
259 |
+
target=model.generate,
|
260 |
+
kwargs=inputs
|
261 |
+
)
|
262 |
+
thread.start()
|
263 |
+
|
264 |
+
model_output = ""
|
265 |
+
for new_text in streamer:
|
266 |
+
model_output += new_text
|
267 |
+
yield model_output
|
268 |
+
|
269 |
+
except Exception as e:
|
270 |
+
yield f"Error during inference: {str(e)}"
|
271 |
+
|
272 |
+
# βββ GRADIO APP ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
273 |
+
|
274 |
+
with gr.Blocks(title="ChatTS Demo") as demo:
|
275 |
+
gr.Markdown("## ChatTS: Time Series Understanding and Reasoning")
|
276 |
+
gr.HTML("""<div style="display:flex;justify-content: center">
|
277 |
+
<a href="https://github.com/NetmanAIOps/ChatTS"><img alt="github" src="https://img.shields.io/badge/Code-GitHub-blue"></a>
|
278 |
+
<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>
|
279 |
+
<a href="https://arxiv.org/abs/2412.03104"><img alt="preprint" src="https://img.shields.io/static/v1?label=arXiv&message=2412.03104&color=B31B1B&logo=arXiv"></a>
|
280 |
+
</div>""")
|
281 |
+
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.")
|
282 |
+
|
283 |
+
# State to track whether to use default time series
|
284 |
+
use_default_state = gr.State(value=True)
|
285 |
+
|
286 |
+
with gr.Row():
|
287 |
+
with gr.Column(scale=1):
|
288 |
+
upload = gr.File(
|
289 |
+
label="Upload CSV File",
|
290 |
+
file_types=[".csv"],
|
291 |
+
type="filepath"
|
292 |
+
)
|
293 |
+
|
294 |
+
prompt_input = gr.Textbox(
|
295 |
+
lines=6,
|
296 |
+
placeholder="Enter your question here...",
|
297 |
+
label="Analysis Prompt",
|
298 |
+
value="Please analyze all the given time series and provide insights about the local fluctuations in the time series in detail."
|
299 |
+
)
|
300 |
+
|
301 |
+
run_btn = gr.Button("Run ChatTS", variant="primary")
|
302 |
+
|
303 |
+
with gr.Column(scale=2):
|
304 |
+
series_selector = gr.Dropdown(
|
305 |
+
label="Select a Column to Visualize",
|
306 |
+
choices=[],
|
307 |
+
value=None
|
308 |
+
)
|
309 |
+
plot_out = gr.LinePlot(value=pd.DataFrame(), label="Time Series Visualization")
|
310 |
+
file_status = gr.Textbox(
|
311 |
+
label="File Status",
|
312 |
+
interactive=False,
|
313 |
+
lines=2
|
314 |
+
)
|
315 |
+
|
316 |
+
text_out = gr.Textbox(
|
317 |
+
lines=10,
|
318 |
+
label="ChatTS Analysis Results",
|
319 |
+
interactive=False
|
320 |
+
)
|
321 |
+
|
322 |
+
# Initialize interface with default data
|
323 |
+
demo.load(
|
324 |
+
fn=initialize_interface,
|
325 |
+
outputs=[plot_out, file_status, series_selector, use_default_state]
|
326 |
+
)
|
327 |
+
|
328 |
+
# Event handlers
|
329 |
+
upload.upload(
|
330 |
+
fn=preview_csv,
|
331 |
+
inputs=[upload, use_default_state],
|
332 |
+
outputs=[plot_out, file_status, series_selector, use_default_state]
|
333 |
+
)
|
334 |
+
|
335 |
+
upload.clear(
|
336 |
+
fn=clear_csv,
|
337 |
+
inputs=[],
|
338 |
+
outputs=[plot_out, file_status, series_selector]
|
339 |
+
)
|
340 |
+
|
341 |
+
series_selector.change(
|
342 |
+
fn=update_plot,
|
343 |
+
inputs=[upload, series_selector],
|
344 |
+
outputs=[plot_out]
|
345 |
+
)
|
346 |
+
|
347 |
+
run_btn.click(
|
348 |
+
fn=infer_chatts_stream,
|
349 |
+
inputs=[prompt_input, upload, use_default_state],
|
350 |
+
outputs=[text_out]
|
351 |
+
)
|
352 |
+
|
353 |
+
if __name__ == '__main__':
|
354 |
+
demo.launch()
|