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()