Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import pandas as pd
|
3 |
+
import numpy as np
|
4 |
+
from statsmodels.tsa.seasonal import STL
|
5 |
+
from sklearn.ensemble import IsolationForest
|
6 |
+
import matplotlib.pyplot as plt
|
7 |
+
|
8 |
+
def detect_anomalies(series, seasonality_window=7, anomaly_threshold=0.05):
|
9 |
+
# Decompose series using Seasonal-Trend decomposition using LOESS (STL)
|
10 |
+
decomposition = STL(series, seasonal=seasonality_window).fit()
|
11 |
+
trend = decomposition.trend
|
12 |
+
seasonal = decomposition.seasonal
|
13 |
+
residual = decomposition.resid
|
14 |
+
|
15 |
+
# Combine trend and seasonal components to form detrended series
|
16 |
+
detrended_series = series - trend - seasonal
|
17 |
+
|
18 |
+
# Fit the Isolation Forest model to detect anomalies in the detrended series
|
19 |
+
model = IsolationForest(contamination=anomaly_threshold)
|
20 |
+
model.fit(detrended_series.values.reshape(-1, 1))
|
21 |
+
|
22 |
+
# Predict outliers in the detrended series
|
23 |
+
outlier_predictions = model.predict(detrended_series.values.reshape(-1, 1))
|
24 |
+
anomalies = detrended_series[outlier_predictions == -1]
|
25 |
+
|
26 |
+
return anomalies.index
|
27 |
+
|
28 |
+
def plot_anomalies(series, anomalies):
|
29 |
+
plt.figure(figsize=(12, 6))
|
30 |
+
plt.plot(series, label='Original Series')
|
31 |
+
plt.scatter(anomalies, series[anomalies], color='red', label='Anomalies')
|
32 |
+
plt.legend()
|
33 |
+
plt.title('Time Series with Anomalies')
|
34 |
+
plt.xlabel('Date')
|
35 |
+
plt.ylabel('Value')
|
36 |
+
plt.show()
|
37 |
+
|
38 |
+
# Função para o Gradio
|
39 |
+
def anomaly_detection_app(time_series_csv):
|
40 |
+
# Carregar a série temporal a partir do arquivo CSV
|
41 |
+
df = pd.read_csv(time_series_csv)
|
42 |
+
df['Date'] = pd.to_datetime(df['Date'])
|
43 |
+
df = df.set_index('Date')
|
44 |
+
|
45 |
+
# Detectar anomalias na série temporal
|
46 |
+
anomalies = detect_anomalies(df['Value'])
|
47 |
+
|
48 |
+
# Plotar a série temporal com as anomalias destacadas
|
49 |
+
plot_anomalies(df['Value'], anomalies)
|
50 |
+
|
51 |
+
return anomalies
|
52 |
+
|
53 |
+
# Interface do Gradio
|
54 |
+
iface = gr.Interface(
|
55 |
+
fn=anomaly_detection_app,
|
56 |
+
inputs=gr.inputs.File(label="Carregar série temporal (CSV)"),
|
57 |
+
outputs="text",
|
58 |
+
title="Análise de Anomalias em Séries Temporais",
|
59 |
+
description="Este aplicativo detecta anomalias em uma série temporal carregada através de um arquivo CSV.",
|
60 |
+
live=True
|
61 |
+
)
|
62 |
+
|
63 |
+
if __name__ == "__main__":
|
64 |
+
iface.launch()
|