Update app.py
Browse files
app.py
CHANGED
@@ -3,73 +3,40 @@ import pandas as pd
|
|
3 |
import numpy as np
|
4 |
import matplotlib.pyplot as plt
|
5 |
from io import StringIO
|
6 |
-
import logging
|
7 |
from momentfm import MOMENTPipeline
|
|
|
8 |
|
9 |
-
#
|
10 |
-
|
11 |
-
|
|
|
|
|
|
|
12 |
|
13 |
-
|
14 |
-
try:
|
15 |
-
model = MOMENTPipeline.from_pretrained(
|
16 |
-
"AutonLab/MOMENT-1-large",
|
17 |
-
model_kwargs={"task_name": "reconstruction"},
|
18 |
-
)
|
19 |
-
model.init()
|
20 |
-
logger.info("Model loaded successfully")
|
21 |
-
except Exception as e:
|
22 |
-
logger.error(f"Model loading failed: {str(e)}")
|
23 |
-
raise
|
24 |
-
|
25 |
-
def validate_and_process_data(data_input):
|
26 |
-
"""Handle all data validation and processing"""
|
27 |
try:
|
28 |
-
#
|
29 |
-
|
30 |
-
df = pd.read_csv(StringIO(data_input))
|
31 |
-
else:
|
32 |
-
raise ValueError("Input must be CSV text")
|
33 |
-
|
34 |
-
# Check required columns
|
35 |
-
required = ['timestamp', 'value']
|
36 |
-
if not all(col in df.columns for col in required):
|
37 |
-
missing = [col for col in required if col not in df.columns]
|
38 |
-
raise ValueError(f"Missing columns: {missing}")
|
39 |
-
|
40 |
-
# Convert and validate timestamp
|
41 |
-
df['timestamp'] = pd.to_datetime(df['timestamp'], errors='coerce')
|
42 |
-
if df['timestamp'].isnull().any():
|
43 |
-
raise ValueError("Invalid timestamp format")
|
44 |
|
45 |
-
# Validate
|
46 |
-
|
47 |
-
|
48 |
-
except:
|
49 |
-
raise ValueError("Non-numeric values found")
|
50 |
|
51 |
-
|
52 |
-
df = df.sort_values('timestamp')
|
53 |
|
54 |
-
|
55 |
-
|
56 |
-
except Exception as e:
|
57 |
-
logger.error(f"Data processing error: {str(e)}")
|
58 |
-
raise
|
59 |
-
|
60 |
-
def detect_anomalies(data_input, threshold=0.1):
|
61 |
-
"""Main anomaly detection function"""
|
62 |
-
try:
|
63 |
-
# Process input data
|
64 |
-
df = validate_and_process_data(data_input)
|
65 |
values = df['value'].values.astype(np.float32)
|
|
|
|
|
|
|
|
|
66 |
|
67 |
-
#
|
68 |
-
|
69 |
-
errors = np.abs(values - reconstruction)
|
70 |
|
71 |
-
# Dynamic threshold (
|
72 |
-
threshold_value = np.mean(errors) +
|
73 |
df['anomaly_score'] = errors
|
74 |
df['is_anomaly'] = errors > threshold_value
|
75 |
|
@@ -83,30 +50,28 @@ def detect_anomalies(data_input, threshold=0.1):
|
|
83 |
)
|
84 |
ax.set_title(f'Anomaly Detection (Threshold: {threshold_value:.2f})')
|
85 |
ax.legend()
|
86 |
-
plt.close(fig) # Prevents duplicate plots
|
87 |
|
88 |
# Prepare outputs
|
89 |
stats = {
|
90 |
"data_points": len(df),
|
91 |
"anomalies": int(df['is_anomaly'].sum()),
|
92 |
-
"
|
93 |
"max_score": float(np.max(errors))
|
94 |
}
|
95 |
|
96 |
return fig, stats, df.to_dict('records')
|
97 |
|
98 |
except Exception as e:
|
99 |
-
logger.error(f"Detection error: {str(e)}")
|
100 |
return None, {"error": str(e)}, None
|
101 |
|
102 |
-
# Gradio
|
103 |
-
with gr.Blocks(
|
104 |
gr.Markdown("# 🚨 Time-Series Anomaly Detection")
|
105 |
|
106 |
with gr.Row():
|
107 |
with gr.Column():
|
108 |
data_input = gr.Textbox(
|
109 |
-
label="Paste CSV Data",
|
110 |
value="""timestamp,value
|
111 |
2025-04-01 00:00:00,100
|
112 |
2025-04-01 01:00:00,102
|
@@ -123,13 +88,13 @@ with gr.Blocks(title="Anomaly Detector") as demo:
|
|
123 |
2025-04-01 12:00:00,101""",
|
124 |
lines=15
|
125 |
)
|
126 |
-
threshold = gr.Slider(0
|
127 |
submit_btn = gr.Button("Analyze", variant="primary")
|
128 |
|
129 |
with gr.Column():
|
130 |
-
plot_output = gr.Plot(
|
131 |
-
stats_output = gr.JSON(
|
132 |
-
data_output = gr.JSON(
|
133 |
|
134 |
submit_btn.click(
|
135 |
detect_anomalies,
|
@@ -138,4 +103,4 @@ with gr.Blocks(title="Anomaly Detector") as demo:
|
|
138 |
)
|
139 |
|
140 |
if __name__ == "__main__":
|
141 |
-
demo.launch(
|
|
|
3 |
import numpy as np
|
4 |
import matplotlib.pyplot as plt
|
5 |
from io import StringIO
|
|
|
6 |
from momentfm import MOMENTPipeline
|
7 |
+
from datetime import datetime
|
8 |
|
9 |
+
# Initialize model correctly
|
10 |
+
model = MOMENTPipeline.from_pretrained(
|
11 |
+
"AutonLab/MOMENT-1-large",
|
12 |
+
model_kwargs={"task_name": "anomaly_detection"}, # Changed task name
|
13 |
+
)
|
14 |
+
model.init()
|
15 |
|
16 |
+
def detect_anomalies(data_input, threshold=3.0): # Changed default threshold
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
try:
|
18 |
+
# Process input data
|
19 |
+
df = pd.read_csv(StringIO(data_input))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
|
21 |
+
# Validate data
|
22 |
+
if 'timestamp' not in df.columns or 'value' not in df.columns:
|
23 |
+
return None, {"error": "CSV must contain 'timestamp' and 'value' columns"}, None
|
|
|
|
|
24 |
|
25 |
+
df['timestamp'] = pd.to_datetime(df['timestamp'])
|
26 |
+
df = df.sort_values('timestamp')
|
27 |
|
28 |
+
# Prepare input for MOMENT (must be 3D array: [samples, timesteps, features])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
values = df['value'].values.astype(np.float32)
|
30 |
+
values_3d = values.reshape(1, -1, 1) # Reshape to 3D
|
31 |
+
|
32 |
+
# Correct reconstruction call
|
33 |
+
reconstruction = model.reconstruct(X=values_3d) # Using named parameter
|
34 |
|
35 |
+
# Calculate errors (flatten back to 1D)
|
36 |
+
errors = np.abs(values - reconstruction[0,:,0])
|
|
|
37 |
|
38 |
+
# Dynamic threshold (using z-score)
|
39 |
+
threshold_value = np.mean(errors) + threshold * np.std(errors)
|
40 |
df['anomaly_score'] = errors
|
41 |
df['is_anomaly'] = errors > threshold_value
|
42 |
|
|
|
50 |
)
|
51 |
ax.set_title(f'Anomaly Detection (Threshold: {threshold_value:.2f})')
|
52 |
ax.legend()
|
|
|
53 |
|
54 |
# Prepare outputs
|
55 |
stats = {
|
56 |
"data_points": len(df),
|
57 |
"anomalies": int(df['is_anomaly'].sum()),
|
58 |
+
"threshold": float(threshold_value),
|
59 |
"max_score": float(np.max(errors))
|
60 |
}
|
61 |
|
62 |
return fig, stats, df.to_dict('records')
|
63 |
|
64 |
except Exception as e:
|
|
|
65 |
return None, {"error": str(e)}, None
|
66 |
|
67 |
+
# Gradio interface
|
68 |
+
with gr.Blocks() as demo:
|
69 |
gr.Markdown("# 🚨 Time-Series Anomaly Detection")
|
70 |
|
71 |
with gr.Row():
|
72 |
with gr.Column():
|
73 |
data_input = gr.Textbox(
|
74 |
+
label="Paste CSV Data",
|
75 |
value="""timestamp,value
|
76 |
2025-04-01 00:00:00,100
|
77 |
2025-04-01 01:00:00,102
|
|
|
88 |
2025-04-01 12:00:00,101""",
|
89 |
lines=15
|
90 |
)
|
91 |
+
threshold = gr.Slider(1.0, 5.0, value=3.0, step=0.1, label="Z-Score Threshold")
|
92 |
submit_btn = gr.Button("Analyze", variant="primary")
|
93 |
|
94 |
with gr.Column():
|
95 |
+
plot_output = gr.Plot()
|
96 |
+
stats_output = gr.JSON()
|
97 |
+
data_output = gr.JSON()
|
98 |
|
99 |
submit_btn.click(
|
100 |
detect_anomalies,
|
|
|
103 |
)
|
104 |
|
105 |
if __name__ == "__main__":
|
106 |
+
demo.launch()
|