SanthiSastra commited on
Commit
18555be
·
verified ·
1 Parent(s): dd04f84

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -68
app.py CHANGED
@@ -7,108 +7,122 @@ from sklearn.decomposition import PCA
7
  from sklearn.preprocessing import StandardScaler
8
  from docx import Document
9
  from docx.shared import Inches
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
  def perform_mining(file):
12
- if file is None:
13
- return [None] * 6
14
 
15
  df = pd.read_csv(file.name)
16
  num_cols = df.select_dtypes(include=[np.number]).columns.tolist()
17
 
18
- # 1. Dataset Description Summary
19
- rows, cols = df.shape
20
- mem_usage = df.memory_usage(deep=True).sum() / 1024
21
- desc_text = f"Dataset contains {rows} observations and {cols} attributes. Total memory footprint: {mem_usage:.3f} KB."
22
 
23
- # 2. Statistical Summary - Strict 3 Decimal Correction
24
- stats = df.describe().round(3).reset_index()
25
- stats.rename(columns={'index': 'Statistic'}, inplace=True)
26
 
27
- # 3. PCA & Nature of Data
28
- nature_insight = ""
29
- pca_text = "N/A"
30
- if len(num_cols) >= 2:
31
- scaler = StandardScaler()
32
- df_imputed = df[num_cols].fillna(df[num_cols].mean())
33
- df_norm = scaler.fit_transform(df_imputed)
34
- pca = PCA(n_components=2)
35
- pca.fit(df_norm)
36
- var_ratio = pca.explained_variance_ratio_
37
- pca_text = f"PC1: {var_ratio[0]:.3f} | PC2: {var_ratio[1]:.3f}"
38
-
39
- if var_ratio[0] > 0.5:
40
- nature_insight = "The data exhibits high multicollinearity; a few principal components capture most of the variance."
41
- else:
42
- nature_insight = "The data is complex and spherical; variance is spread across multiple dimensions."
43
 
44
- # 4. Generating 15-Plot Dashboard
 
 
 
45
  fig = plt.figure(figsize=(15, 20))
46
  for i in range(15):
47
  plt.subplot(5, 3, i+1)
48
  col = num_cols[i % len(num_cols)]
49
  if i < 5:
50
- sns.histplot(df[col].dropna(), kde=True, color='royalblue')
51
- plt.title(f"Histogram: {col}")
52
  elif i < 10:
53
  sns.boxplot(y=df[col].dropna(), color='cyan')
54
- plt.title(f"Boxplot: {col}")
 
 
 
55
  else:
56
- sns.scatterplot(x=df[num_cols[0]], y=df[col], alpha=0.6)
57
  plt.title(f"Scatter: {col}")
58
 
59
  plt.tight_layout()
60
- plot_path = "mining_dashboard.png"
61
  plt.savefig(plot_path)
62
  plt.close()
63
 
64
- # 5. Professional DOCX Report
65
  doc_path = "Sastra_Data_Mining_Report.docx"
66
  doc = Document()
67
- doc.add_heading('Amrita Manthan: Preprocessing Report', 0)
68
- doc.add_paragraph(f"Faculty: Prof. B. Santhi | SRC, SASTRA")
69
- doc.add_heading('Dataset Description', level=1)
70
- doc.add_paragraph(desc_text)
71
- doc.add_heading('Inference & Nature of Data', level=1)
72
- doc.add_paragraph(nature_insight)
73
- doc.add_picture(plot_path, width=Inches(6))
74
  doc.save(doc_path)
75
 
76
- return stats, desc_text, plot_path, nature_insight, pca_text, doc_path
77
 
78
- # --- UI Layout ---
79
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
80
- # Centered Header: Logo then Title
81
- with gr.Column(variant="panel"):
82
- with gr.Row():
83
- gr.Image("logo.jpg", width=120, show_label=False, container=False, scale=1)
84
- gr.Markdown("<h1 style='text-align: center; color: #0000FF;'><b>Amrita Manthan</b></h1>")
85
- gr.Markdown("<h2 style='text-align: center; color: #0000FF;'><b>Preprocessing & Data Mining Portal</b></h2>")
86
- gr.Markdown("<p style='text-align: center; color: #0000FF;'><b>Prof. B. Santhi, SRC, SASTRA</b></p>")
 
 
 
 
 
 
 
87
 
88
  with gr.Tabs():
89
- with gr.TabItem("1. Input & Theory"):
90
- gr.Markdown("### **Preprocessing Formalisms**")
91
- gr.Markdown(r"**Standardization Formula:** $$z = \frac{x - \mu}{\sigma}$$")
92
- gr.Markdown(r"**PCA Projection:** $$\mathbf{T} = \mathbf{X} \mathbf{W}$$")
93
- input_file = gr.File(label="Upload Student Dataset (CSV)")
94
- run_btn = gr.Button("EXECUTE DATA MINING", variant="primary")
95
 
96
- with gr.TabItem("2. Statistics & Description"):
97
- out_desc = gr.Textbox(label="Dataset Description", placeholder="Summary of rows, columns, and memory...")
98
- out_stats = gr.DataFrame(label="Descriptive Statistics (3 Decimal Correction)")
 
 
99
 
100
- with gr.TabItem("3. Visual Mining & Nature"):
101
- out_plot = gr.Image(label="15-Plot Distribution Dashboard")
102
- out_nature = gr.Textbox(label="Nature of Data & Insights")
103
- out_pca = gr.Label(label="Principal Component Variance")
104
 
105
- with gr.TabItem("4. Export"):
106
- out_file = gr.File(label="Download Comprehensive Report")
107
 
108
- run_btn.click(
109
- fn=perform_mining,
110
- inputs=input_file,
111
- outputs=[out_stats, out_desc, out_plot, out_nature, out_pca, out_file]
112
- )
113
 
114
  demo.launch()
 
7
  from sklearn.preprocessing import StandardScaler
8
  from docx import Document
9
  from docx.shared import Inches
10
+ from scipy.stats import skew
11
+
12
+ def analyze_nature(df):
13
+ num_cols = df.select_dtypes(include=[np.number]).columns
14
+ insights = []
15
+
16
+ for col in num_cols:
17
+ # 1. Symmetry/Skewness check
18
+ s = skew(df[col].dropna())
19
+ if abs(s) < 0.5:
20
+ shape = "Symmetric (Approx. Normal)"
21
+ elif s > 0.5:
22
+ shape = "Right-Skewed (Positive)"
23
+ else:
24
+ shape = "Left-Skewed (Negative)"
25
+
26
+ # 2. Outlier check (IQR Method)
27
+ Q1 = df[col].quantile(0.25)
28
+ Q3 = df[col].quantile(0.75)
29
+ IQR = Q3 - Q1
30
+ outliers = df[(df[col] < (Q1 - 1.5 * IQR)) | (df[col] > (Q3 + 1.5 * IQR))]
31
+
32
+ insights.append(f"Attribute '{col}': {shape} | Outliers detected: {len(outliers)}")
33
+
34
+ return "\n".join(insights)
35
 
36
  def perform_mining(file):
37
+ if file is None: return [None]*6
 
38
 
39
  df = pd.read_csv(file.name)
40
  num_cols = df.select_dtypes(include=[np.number]).columns.tolist()
41
 
42
+ # Dataset Description
43
+ desc_text = f"Observations: {df.shape[0]} | Attributes: {df.shape[1]}"
 
 
44
 
45
+ # Data Nature & Statistical Inference
46
+ nature_report = analyze_nature(df)
 
47
 
48
+ # Correlation Inference
49
+ corr_matrix = df[num_cols].corr()
50
+ high_corr = corr_matrix.unstack().sort_values(ascending=False)
51
+ high_corr = high_corr[(high_corr < 1) & (high_corr > 0.7)].drop_duplicates()
52
+ corr_inference = f"Strong Correlations found: {len(high_corr)} pairs."
 
 
 
 
 
 
 
 
 
 
 
53
 
54
+ # Stats rounded to 3 decimals
55
+ stats = df.describe().round(3).reset_index()
56
+
57
+ # Plotting 15-Plot Suite
58
  fig = plt.figure(figsize=(15, 20))
59
  for i in range(15):
60
  plt.subplot(5, 3, i+1)
61
  col = num_cols[i % len(num_cols)]
62
  if i < 5:
63
+ sns.histplot(df[col].dropna(), kde=True, color='blue')
64
+ plt.title(f"Dist: {col}")
65
  elif i < 10:
66
  sns.boxplot(y=df[col].dropna(), color='cyan')
67
+ plt.title(f"Outliers: {col}")
68
+ elif i == 10:
69
+ sns.heatmap(corr_matrix, annot=True, cmap='coolwarm', fmt=".2f")
70
+ plt.title("Correlogram")
71
  else:
72
+ sns.scatterplot(x=df[num_cols[0]], y=df[col], alpha=0.5)
73
  plt.title(f"Scatter: {col}")
74
 
75
  plt.tight_layout()
76
+ plot_path = "mining_results.png"
77
  plt.savefig(plot_path)
78
  plt.close()
79
 
80
+ # Doc Generation
81
  doc_path = "Sastra_Data_Mining_Report.docx"
82
  doc = Document()
83
+ doc.add_heading('Amrita Manthan: Data Mining Report', 0)
84
+ doc.add_paragraph(nature_report)
 
 
 
 
 
85
  doc.save(doc_path)
86
 
87
+ return stats, desc_text, plot_path, nature_report, corr_inference, doc_path
88
 
 
89
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
90
+ # Header: Logo Center, Text Left
91
+ with gr.Row():
92
+ with gr.Column(scale=1):
93
+ pass # Spacer
94
+ with gr.Column(scale=2):
95
+ gr.Image("logo.jpg", width=120, show_label=False, container=False)
96
+ with gr.Column(scale=1):
97
+ pass # Spacer
98
+
99
+ with gr.Row():
100
+ with gr.Column():
101
+ gr.Markdown("<h1 style='color: #0000FF; text-align: left;'><b>Amrita Manthan</b></h1>")
102
+ gr.Markdown("<h2 style='color: #0000FF; text-align: left;'><b>Preprocessing & Data Mining Portal</b></h2>")
103
+ gr.Markdown("<h3 style='color: #0000FF; text-align: left;'><b>Prof. B. Santhi, SRC, SASTRA</b></h3>")
104
 
105
  with gr.Tabs():
106
+ with gr.TabItem("1. Theory & Upload"):
107
+ gr.Markdown("### **Mathematical Clarity**")
108
+ gr.Markdown(r"**Skewness ($\gamma_1$):** $$\gamma_1 = E\left[\left(\frac{X-\mu}{\sigma}\right)^3\right]$$")
109
+ gr.Markdown(r"**Outlier Detection (IQR):** $$[Q1 - 1.5 \times IQR, Q3 + 1.5 \times IQR]$$")
110
+ u_file = gr.File(label="Upload CSV")
111
+ run_btn = gr.Button("ANALYZE", variant="primary")
112
 
113
+ with gr.TabItem("2. Statistics & Skewness"):
114
+ gr.Markdown("#### **Dataset Summary**")
115
+ out_desc = gr.Markdown()
116
+ out_stats = gr.DataFrame(label="3-Decimal Summary")
117
+ out_nature = gr.Textbox(label="Distribution & Outlier Analysis", lines=10)
118
 
119
+ with gr.TabItem("3. Visual Dashboard"):
120
+ out_corr = gr.Label(label="Correlation Inference")
121
+ out_img = gr.Image(label="EDA Dashboard (15 Plots)")
 
122
 
123
+ with gr.TabItem("4. Download"):
124
+ out_file = gr.File(label="Final Report")
125
 
126
+ run_btn.click(perform_mining, u_file, [out_stats, out_desc, out_img, out_nature, out_corr, out_file])
 
 
 
 
127
 
128
  demo.launch()