DHEIVER's picture
Update app.py
af54ee7
raw
history blame
2.65 kB
import gradio as gr
import pandas as pd
import numpy as np
from statsmodels.tsa.seasonal import STL
from pmdarima import auto_arima
import matplotlib.pyplot as plt
def detect_periodicity(series):
# Use o método auto_arima para determinar a periodicidade da série
stepwise_model = auto_arima(series, start_p=1, start_q=1, max_p=3, max_q=3, m=12, seasonal=True, trace=True)
return stepwise_model.seasonal_order[0]
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 automaticamente
periodicity = detect_periodicity(df['Value'])
# 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
# 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()