File size: 2,497 Bytes
8be4b91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa4a0b3
 
 
8be4b91
 
 
e2d4bf8
 
 
 
8be4b91
e2d4bf8
8be4b91
 
 
 
 
 
e2d4bf8
 
 
8be4b91
 
 
aa4a0b3
8be4b91
 
aa4a0b3
8be4b91
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import gradio as gr
import pandas as pd
import numpy as np
from statsmodels.tsa.seasonal import STL
from sklearn.ensemble import IsolationForest
import matplotlib.pyplot as plt

def detect_anomalies(series, seasonality_window=7, anomaly_threshold=0.05):
    # Decompose series using Seasonal-Trend decomposition using LOESS (STL)
    decomposition = STL(series, seasonal=seasonality_window).fit()
    trend = decomposition.trend
    seasonal = decomposition.seasonal
    residual = decomposition.resid

    # Combine trend and seasonal components to form detrended series
    detrended_series = series - trend - seasonal

    # Fit the Isolation Forest model to detect anomalies in the detrended series
    model = IsolationForest(contamination=anomaly_threshold)
    model.fit(detrended_series.values.reshape(-1, 1))

    # Predict outliers in the detrended series
    outlier_predictions = model.predict(detrended_series.values.reshape(-1, 1))
    anomalies = detrended_series[outlier_predictions == -1]

    return anomalies.index

def plot_anomalies(series, anomalies):
    plt.figure(figsize=(12, 6))
    plt.plot(series, label='Original Series')
    plt.scatter(anomalies, series[anomalies], color='red', label='Anomalies')
    plt.legend()
    plt.title('Time Series with Anomalies')
    plt.xlabel('Date')
    plt.ylabel('Value')
    plt.show()

# Função para o Gradio
def anomaly_detection_app(time_series_txt):
    # Carregar a série temporal a partir do arquivo de texto
    df = pd.read_csv(time_series_txt, header=None, names=["Date", "Value"])
    df['Date'] = pd.to_datetime(df['Date'])
    df = df.set_index('Date')

    # Determinar a periodicidade da série (assumindo que é diária)
    # Se os dados forem de outra periodicidade, ajuste o valor apropriado aqui
    periodicity = 1

    # Detectar anomalias na série temporal
    anomalies = detect_anomalies(df['Value'], seasonality_window=periodicity)

    # Plotar a série temporal com as anomalias destacadas
    plot_anomalies(df['Value'], anomalies)

    return anomalies

# Resto do código continua o mesmo


# Interface do Gradio
iface = gr.Interface(
    fn=anomaly_detection_app,
    inputs=gr.inputs.File(label="Carregar série temporal (TXT)"),
    outputs="text",
    title="Análise de Anomalias em Séries Temporais",
    description="Este aplicativo detecta anomalias em uma série temporal carregada através de um arquivo de texto (TXT).",
    live=True
)

if __name__ == "__main__":
    iface.launch()