File size: 2,152 Bytes
8be4b91
 
 
 
 
a82a069
 
 
 
af54ee7
a82a069
 
8be4b91
a82a069
 
8be4b91
 
 
 
 
 
 
 
 
 
 
 
 
 
a7011d8
 
 
8be4b91
 
 
a82a069
 
8be4b91
 
 
 
 
 
 
 
 
a82a069
a7011d8
a82a069
 
 
8be4b91
 
a7011d8
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
import gradio as gr
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

def detect_anomalies(series, window_size=7, threshold=2.5):
    # Calculate the rolling mean and standard deviation using the specified window size
    rolling_mean = series.rolling(window=window_size, center=True).mean()
    rolling_std = series.rolling(window=window_size, center=True).std()

    # Calculate the z-score for each data point
    z_scores = np.abs((series - rolling_mean) / rolling_std)

    # Detect anomalies based on the threshold
    anomalies = series[z_scores > threshold]

    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, window_size=7, threshold=2.5):
    # 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')

    # Detectar anomalias na série temporal usando a média móvel
    anomalies = detect_anomalies(df['Value'], window_size=window_size, threshold=threshold)

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

    return anomalies

# Interface do Gradio
iface = gr.Interface(
    fn=anomaly_detection_app,
    inputs=[
        gr.inputs.File(label="Carregar série temporal (TXT)"),
        gr.inputs.Number(default=7, label="Tamanho da janela da média móvel"),
        gr.inputs.Number(default=2.5, label="Threshold para anomalias (em desvios-padrão)")
    ],
    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) usando a média móvel.",
    live=True
)

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