Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pandas as pd
|
| 3 |
+
from statsmodels.tsa.seasonal import seasonal_decompose
|
| 4 |
+
from statsmodels.tsa.arima.model import ARIMA
|
| 5 |
+
from sklearn.ensemble import IsolationForest
|
| 6 |
+
from sklearn.preprocessing import StandardScaler
|
| 7 |
+
import gradio as gr
|
| 8 |
+
import traceback
|
| 9 |
+
import logging
|
| 10 |
+
|
| 11 |
+
# Set up logging
|
| 12 |
+
logging.basicConfig(level=logging.ERROR)
|
| 13 |
+
|
| 14 |
+
class TrendAnalysisAgent:
|
| 15 |
+
def analyze(self, data):
|
| 16 |
+
result = seasonal_decompose(data, model='additive', period=1)
|
| 17 |
+
return result.trend
|
| 18 |
+
|
| 19 |
+
class SeasonalityDetectionAgent:
|
| 20 |
+
def detect(self, data):
|
| 21 |
+
result = seasonal_decompose(data, model='additive', period=12)
|
| 22 |
+
return result.seasonal
|
| 23 |
+
|
| 24 |
+
class AnomalyDetectionAgent:
|
| 25 |
+
def detect(self, data):
|
| 26 |
+
scaler = StandardScaler()
|
| 27 |
+
data_scaled = scaler.fit_transform(data.reshape(-1, 1))
|
| 28 |
+
iso_forest = IsolationForest(contamination=0.1, random_state=42)
|
| 29 |
+
anomalies = iso_forest.fit_predict(data_scaled)
|
| 30 |
+
return anomalies == -1
|
| 31 |
+
|
| 32 |
+
class FeatureExtractionAgent:
|
| 33 |
+
def extract(self, data):
|
| 34 |
+
features = pd.DataFrame({
|
| 35 |
+
'mean': [np.mean(data)],
|
| 36 |
+
'std': [np.std(data)],
|
| 37 |
+
'min': [np.min(data)],
|
| 38 |
+
'max': [np.max(data)]
|
| 39 |
+
})
|
| 40 |
+
return features
|
| 41 |
+
|
| 42 |
+
class ForecastingAgent:
|
| 43 |
+
def forecast(self, data, steps):
|
| 44 |
+
model = ARIMA(data, order=(1,1,1))
|
| 45 |
+
results = model.fit()
|
| 46 |
+
forecast = results.forecast(steps=steps)
|
| 47 |
+
return forecast
|
| 48 |
+
|
| 49 |
+
class RetrievalMechanism:
|
| 50 |
+
def __init__(self):
|
| 51 |
+
self.database = {}
|
| 52 |
+
|
| 53 |
+
def store(self, key, data):
|
| 54 |
+
self.database[key] = data
|
| 55 |
+
|
| 56 |
+
def retrieve(self, key):
|
| 57 |
+
return self.database.get(key, None)
|
| 58 |
+
|
| 59 |
+
class MockLanguageModel:
|
| 60 |
+
def generate_insight(self, data, trend, seasonality, anomalies, features, forecast):
|
| 61 |
+
insight = f"The time series has a mean of {features['mean'].values[0]:.2f} and standard deviation of {features['std'].values[0]:.2f}. "
|
| 62 |
+
insight += f"There {'are' if anomalies.sum() > 1 else 'is'} {anomalies.sum()} anomal{'ies' if anomalies.sum() > 1 else 'y'} detected. "
|
| 63 |
+
insight += f"The forecast suggests a {'upward' if forecast[-1] > data[-1] else 'downward'} trend in the near future."
|
| 64 |
+
return insight
|
| 65 |
+
|
| 66 |
+
class AgenticRAG:
|
| 67 |
+
def __init__(self):
|
| 68 |
+
self.trend_agent = TrendAnalysisAgent()
|
| 69 |
+
self.seasonality_agent = SeasonalityDetectionAgent()
|
| 70 |
+
self.anomaly_agent = AnomalyDetectionAgent()
|
| 71 |
+
self.feature_agent = FeatureExtractionAgent()
|
| 72 |
+
self.forecasting_agent = ForecastingAgent()
|
| 73 |
+
self.retrieval = RetrievalMechanism()
|
| 74 |
+
self.language_model = MockLanguageModel()
|
| 75 |
+
|
| 76 |
+
def process(self, data, forecast_steps):
|
| 77 |
+
trend = self.trend_agent.analyze(data)
|
| 78 |
+
seasonality = self.seasonality_agent.detect(data)
|
| 79 |
+
anomalies = self.anomaly_agent.detect(data)
|
| 80 |
+
features = self.feature_agent.extract(data)
|
| 81 |
+
forecast = self.forecasting_agent.forecast(data, forecast_steps)
|
| 82 |
+
|
| 83 |
+
insight = self.language_model.generate_insight(data, trend, seasonality, anomalies, features, forecast)
|
| 84 |
+
|
| 85 |
+
return trend, seasonality, anomalies, features, forecast, insight
|
| 86 |
+
|
| 87 |
+
def analyze_time_series(data, forecast_steps):
|
| 88 |
+
try:
|
| 89 |
+
data = np.array([float(x) for x in data.split(',')])
|
| 90 |
+
if len(data) < 2:
|
| 91 |
+
raise ValueError("Input data must contain at least two values.")
|
| 92 |
+
|
| 93 |
+
agentic_rag = AgenticRAG()
|
| 94 |
+
trend, seasonality, anomalies, features, forecast, insight = agentic_rag.process(data, forecast_steps)
|
| 95 |
+
|
| 96 |
+
return {
|
| 97 |
+
"Trend": trend,
|
| 98 |
+
"Seasonality": seasonality,
|
| 99 |
+
"Anomalies": anomalies,
|
| 100 |
+
"Features": features.to_dict(orient='records')[0],
|
| 101 |
+
"Forecast": forecast.tolist(),
|
| 102 |
+
"Insight": insight
|
| 103 |
+
}
|
| 104 |
+
except Exception as e:
|
| 105 |
+
error_msg = f"An error occurred: {str(e)}\n{traceback.format_exc()}"
|
| 106 |
+
logging.error(error_msg)
|
| 107 |
+
return {
|
| 108 |
+
"Error": error_msg
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
iface = gr.Interface(
|
| 112 |
+
fn=analyze_time_series,
|
| 113 |
+
inputs=[
|
| 114 |
+
gr.Textbox(label="Enter comma-separated time series data"),
|
| 115 |
+
gr.Number(label="Number of steps to forecast", value=5)
|
| 116 |
+
],
|
| 117 |
+
outputs=[
|
| 118 |
+
gr.Plot(label="Trend"),
|
| 119 |
+
gr.Plot(label="Seasonality"),
|
| 120 |
+
gr.Plot(label="Anomalies"),
|
| 121 |
+
gr.JSON(label="Features"),
|
| 122 |
+
gr.Plot(label="Forecast"),
|
| 123 |
+
gr.Textbox(label="Insight"),
|
| 124 |
+
gr.Textbox(label="Error", visible=False)
|
| 125 |
+
],
|
| 126 |
+
title="Agentic RAG Time Series Analysis",
|
| 127 |
+
description="Enter a comma-separated list of numbers representing your time series data, and specify the number of steps to forecast."
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
if __name__ == "__main__":
|
| 131 |
+
iface.launch()
|