Create analysis_modules.py
Browse files- analysis_modules.py +56 -0
analysis_modules.py
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# analysis_modules.py
|
2 |
+
|
3 |
+
import pandas as pd
|
4 |
+
import plotly.express as px
|
5 |
+
from statsmodels.tsa.seasonal import seasonal_decompose
|
6 |
+
from statsmodels.tsa.stattools import adfuller
|
7 |
+
from sklearn.cluster import KMeans
|
8 |
+
from wordcloud import WordCloud
|
9 |
+
import matplotlib.pyplot as plt
|
10 |
+
import io
|
11 |
+
import base64
|
12 |
+
|
13 |
+
# --- Time-Series Module ---
|
14 |
+
def analyze_time_series(df: pd.DataFrame, date_col: str, value_col: str):
|
15 |
+
"""Performs time-series decomposition and stationarity testing."""
|
16 |
+
df[date_col] = pd.to_datetime(df[date_col])
|
17 |
+
ts_df = df.set_index(date_col)[value_col].dropna()
|
18 |
+
|
19 |
+
# Decomposition
|
20 |
+
decomposition = seasonal_decompose(ts_df, model='additive', period=12) # Assuming monthly data
|
21 |
+
fig_decomp = px.line(pd.DataFrame({'trend': decomposition.trend, 'seasonal': decomposition.seasonal, 'residual': decomposition.resid}),
|
22 |
+
title=f"Time-Series Decomposition of {value_col}")
|
23 |
+
|
24 |
+
# Stationarity Test (ADF)
|
25 |
+
adf_result = adfuller(ts_df)
|
26 |
+
adf_md = f"""
|
27 |
+
### Stationarity Analysis (ADF Test)
|
28 |
+
- **Test Statistic:** `{adf_result[0]:.4f}`
|
29 |
+
- **p-value:** `{adf_result[1]:.4f}`
|
30 |
+
- **Conclusion:** The series is likely **{'stationary' if adf_result[1] < 0.05 else 'non-stationary'}**.
|
31 |
+
"""
|
32 |
+
return fig_decomp, adf_md
|
33 |
+
|
34 |
+
# --- Text Analysis Module ---
|
35 |
+
def generate_word_cloud(df: pd.DataFrame, text_col: str):
|
36 |
+
"""Generates a word cloud from a text column."""
|
37 |
+
text = ' '.join(df[text_col].dropna().astype(str))
|
38 |
+
wordcloud = WordCloud(width=800, height=400, background_color='white').generate(text)
|
39 |
+
|
40 |
+
# Convert matplotlib plot to a data URI for Gradio
|
41 |
+
buf = io.BytesIO()
|
42 |
+
wordcloud.to_image().save(buf, format='png')
|
43 |
+
img_str = "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode('utf-8')
|
44 |
+
return img_str
|
45 |
+
|
46 |
+
# --- Clustering Module ---
|
47 |
+
def perform_clustering(df: pd.DataFrame, numeric_cols: list, n_clusters: int = 4):
|
48 |
+
"""Performs K-Means clustering and returns a scatter plot."""
|
49 |
+
cluster_data = df[numeric_cols].dropna()
|
50 |
+
kmeans = KMeans(n_clusters=n_clusters, random_state=42, n_init='auto').fit(cluster_data)
|
51 |
+
cluster_data['Cluster'] = kmeans.labels_.astype(str)
|
52 |
+
|
53 |
+
# For visualization, we'll use the first two numeric columns
|
54 |
+
fig_cluster = px.scatter(cluster_data, x=numeric_cols[0], y=numeric_cols[1], color='Cluster',
|
55 |
+
title=f"K-Means Clustering (k={n_clusters})")
|
56 |
+
return fig_cluster
|