Spaces:
Sleeping

clementBE commited on
Commit
8b22417
Β·
verified Β·
1 Parent(s): 36ca2d6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -145
app.py CHANGED
@@ -3,22 +3,18 @@ import pandas as pd
3
  import numpy as np
4
  from sklearn.model_selection import train_test_split
5
  from sklearn.ensemble import RandomForestClassifier
6
- from sklearn.preprocessing import LabelEncoder
7
  from sklearn.metrics import classification_report
8
 
9
- # ----------- Helper Functions -----------
10
-
11
  def load_data(file):
12
  try:
 
13
  if file.name.endswith(".csv"):
14
- df = pd.read_csv(file.name)
15
  else:
16
- df = pd.read_excel(file.name)
17
 
18
- # Show first 5 rows of the uploaded file
19
  preview = df.head(5)
20
-
21
- # Create a short summary with column types and missing values
22
  summary = pd.DataFrame({
23
  "Column": df.columns,
24
  "Data Type": [df[col].dtype for col in df.columns],
@@ -29,151 +25,99 @@ def load_data(file):
29
  except Exception as e:
30
  return None, [], pd.DataFrame(), "", f"❌ Error loading file: {e}"
31
 
 
32
  def preprocess_dataframe(df, quantile_binning=False, count_words=False):
33
- # Copy the original DataFrame to avoid overwriting
34
  df = df.copy()
35
 
36
- # If user selects quantile binning
37
  if quantile_binning:
38
- numeric_cols = df.select_dtypes(include=["int64", "float64"]).columns
39
  for col in numeric_cols:
40
  try:
41
- df[col + "_qbin"] = pd.qcut(df[col], q=4, labels=["Q1", "Q2", "Q3", "Q4"])
42
- except Exception as e:
43
- print(f"Warning (qbin failed for {col}):", e)
44
 
45
- # If user selects count_words for text columns
46
  if count_words:
47
- text_cols = df.select_dtypes(include=["object"]).columns
48
  for col in text_cols:
49
- try:
50
- df[col + "_wordcount"] = df[col].astype(str).apply(lambda x: len(x.split()))
51
- except Exception as e:
52
- print(f"Warning (wordcount failed for {col}):", e)
53
 
54
  return df
55
 
56
- def train_model(df, target_column, feature_columns):
57
- # Remove rows with missing target values
58
- df = df.dropna(subset=[target_column])
59
-
60
- # Fill missing values in feature columns
61
- for col in feature_columns:
62
- if df[col].dtype == "O":
63
- df[col] = df[col].fillna("missing")
64
- else:
65
- df[col] = df[col].fillna(df[col].median())
66
-
67
- X = df[feature_columns]
68
- y = df[target_column]
69
-
70
- # Encode categorical features
71
- for col in X.select_dtypes(include=["object"]).columns:
72
- X[col] = LabelEncoder().fit_transform(X[col])
73
-
74
- # Encode target if it's categorical
75
- if y.dtype == "O":
76
- y = LabelEncoder().fit_transform(y)
77
 
78
- # Split into train and test sets
79
- X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
 
 
80
 
81
- # Train a simple Random Forest model
82
- model = RandomForestClassifier()
83
- model.fit(X_train, y_train)
84
 
85
- # Predict and show classification report
86
- y_pred = model.predict(X_test)
87
- report = classification_report(y_test, y_pred)
88
 
89
- return report
 
 
 
90
 
91
- # ----------- Gradio Interface Setup -----------
 
 
92
 
93
- with gr.Blocks() as demo:
94
- gr.Markdown("# 🧠 CSV/XLSX Classifier with Auto Summary and Visualization")
95
 
96
- # Store the DataFrame in memory
97
- df_state = gr.State(None)
 
98
 
99
- # Upload section
100
  with gr.Row():
101
- file_input = gr.File(label="πŸ“ Upload CSV or Excel File", file_types=[".csv", ".xlsx", ".xls"])
 
 
102
 
103
  with gr.Row():
104
- quantile_option = gr.Checkbox(label="πŸ“Š Discretize Numeric Columns into Quartiles")
105
- wordcount_option = gr.Checkbox(label="πŸ“ Count Words in Text Columns")
106
 
107
  with gr.Row():
108
- target_col = gr.Dropdown(label="🎯 Target Column (What you want to predict)", choices=[])
109
- feature_cols = gr.CheckboxGroup(label="🧾 Feature Columns (Used to predict target)", choices=[])
110
 
111
- # Buttons
112
  with gr.Row():
113
- train_button = gr.Button("πŸš€ Train Model")
114
- clear_button = gr.Button("πŸ”„ Clear All")
115
 
116
- # Outputs
117
- with gr.Row():
118
- output = gr.Textbox(label="πŸ“‹ Model Output (Classification Report)", lines=10)
119
 
120
  with gr.Row():
121
- data_summary = gr.Textbox(label="πŸ“Š Data Summary", lines=10)
122
- help_box = gr.Textbox(label="πŸ’‘ Help", lines=5, value="βœ”οΈ Upload a dataset, choose preprocessing options, then train.")
123
-
124
- # Data Previews
125
- with gr.Row():
126
- table_preview = gr.DataFrame(label="πŸ” Original Data Preview")
127
- processed_preview = gr.DataFrame(label="πŸ§ͺ Processed Data Preview (with new columns)")
128
-
129
- # ----------- Define App Logic -----------
130
-
131
- # Handle file upload and update column options
132
- def on_file_change(file, quantile_binning, count_words):
133
- df, _, preview, summary_md, error = load_data(file)
134
- if df is None:
135
- return None, gr.update(choices=[], value=None), gr.update(choices=[], value=[]), pd.DataFrame(), "", "", "", error
136
-
137
- # Apply preprocessing
138
- df_processed = preprocess_dataframe(df, quantile_binning, count_words)
139
-
140
- # Update selectors with new columns from the processed DataFrame
141
- columns = list(df_processed.columns)
142
-
143
- return (
144
- df_processed, # Store processed df in state
145
- gr.update(choices=columns, value=None),
146
- gr.update(choices=columns, value=[]),
147
- preview,
148
- summary_md,
149
- df_processed.head(100), # Show processed preview
150
- "", # Clear model output
151
- "" # Clear help
152
- )
153
-
154
- # Handle training the model
155
- def on_train(df, target, features):
156
- if df is None:
157
- return "⚠️ Please upload a file first."
158
- if target is None or not features:
159
- return "⚠️ Please select target and feature columns."
160
- return train_model(df, target, features)
161
-
162
- # Clear all interface elements
163
- def on_clear():
164
- return (
165
- None, # df_state
166
- None, # target_col
167
- [], # feature_cols
168
- pd.DataFrame(),
169
- "",
170
- pd.DataFrame(),
171
- "",
172
- "βœ”οΈ Upload a dataset, choose preprocessing options, then train."
173
- )
174
-
175
- # ----------- Connect Actions to Widgets -----------
176
 
 
177
  file_input.change(
178
  fn=on_file_change,
179
  inputs=[file_input, quantile_option, wordcount_option],
@@ -185,32 +129,15 @@ with gr.Blocks() as demo:
185
  data_summary,
186
  processed_preview,
187
  output,
188
- help_box
189
- ]
190
  )
191
 
192
  train_button.click(
193
- fn=on_train,
194
  inputs=[df_state, target_col, feature_cols],
195
- outputs=output
196
  )
197
 
198
- clear_button.click(
199
- fn=on_clear,
200
- inputs=[],
201
- outputs=[
202
- df_state,
203
- target_col,
204
- feature_cols,
205
- table_preview,
206
- data_summary,
207
- processed_preview,
208
- output,
209
- help_box
210
- ]
211
- )
212
-
213
- # ----------- Launch the App -----------
214
-
215
- if __name__ == "__main__":
216
- demo.launch(share=True)
 
3
  import numpy as np
4
  from sklearn.model_selection import train_test_split
5
  from sklearn.ensemble import RandomForestClassifier
 
6
  from sklearn.metrics import classification_report
7
 
8
+ # βœ… Load data from CSV or Excel
 
9
  def load_data(file):
10
  try:
11
+ # πŸ”„ Use file object directly to avoid FileNotFoundError
12
  if file.name.endswith(".csv"):
13
+ df = pd.read_csv(file)
14
  else:
15
+ df = pd.read_excel(file)
16
 
 
17
  preview = df.head(5)
 
 
18
  summary = pd.DataFrame({
19
  "Column": df.columns,
20
  "Data Type": [df[col].dtype for col in df.columns],
 
25
  except Exception as e:
26
  return None, [], pd.DataFrame(), "", f"❌ Error loading file: {e}"
27
 
28
+ # βœ… Preprocess DataFrame
29
  def preprocess_dataframe(df, quantile_binning=False, count_words=False):
 
30
  df = df.copy()
31
 
32
+ # βž• Add _qbin columns for numeric columns
33
  if quantile_binning:
34
+ numeric_cols = df.select_dtypes(include=np.number).columns
35
  for col in numeric_cols:
36
  try:
37
+ df[col + "_qbin"] = pd.qcut(df[col], q=4, labels=False, duplicates='drop')
38
+ except:
39
+ pass # Some columns can't be binned (e.g., constant values)
40
 
41
+ # βž• Add _wordcount columns for text columns
42
  if count_words:
43
+ text_cols = df.select_dtypes(include="object").columns
44
  for col in text_cols:
45
+ df[col + "_wordcount"] = df[col].astype(str).apply(lambda x: len(x.split()))
 
 
 
46
 
47
  return df
48
 
49
+ # βœ… Handle file input and update UI
50
+ def on_file_change(file, quantile_binning, count_words):
51
+ df, _, preview, summary_md, error = load_data(file)
52
+ if df is None:
53
+ return None, gr.update(choices=[], value=None), gr.update(choices=[], value=[]), pd.DataFrame(), "", "", "", error
54
+
55
+ # πŸ”„ Preprocess data and get new columns
56
+ df_processed = preprocess_dataframe(df, quantile_binning, count_words)
57
+ columns = list(df_processed.columns)
58
+
59
+ return (
60
+ df_processed, # Save in state
61
+ gr.update(choices=columns, value=None), # Update target dropdown
62
+ gr.update(choices=columns, value=[]), # Update feature selector
63
+ preview, # Show original preview
64
+ summary_md, # Show summary table
65
+ df_processed.head(100), # Show processed data
66
+ "", "", # Clear output and help box
67
+ )
 
 
68
 
69
+ # βœ… Train model
70
+ def train_model(df, target, features):
71
+ if df is None or target is None or not features:
72
+ return "⚠️ Please upload data, select a target column and features.", ""
73
 
74
+ try:
75
+ X = df[features]
76
+ y = df[target]
77
 
78
+ # Handle categorical features
79
+ X = pd.get_dummies(X)
 
80
 
81
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
82
+ clf = RandomForestClassifier()
83
+ clf.fit(X_train, y_train)
84
+ y_pred = clf.predict(X_test)
85
 
86
+ report = classification_report(y_test, y_pred)
87
+ help_text = "βœ… Model trained successfully. You can review the metrics below."
88
+ return report, help_text
89
 
90
+ except Exception as e:
91
+ return f"❌ Error training model: {e}", ""
92
 
93
+ # βœ… Gradio App Interface
94
+ with gr.Blocks(title="πŸ“Š ML Model Trainer with Quartiles and Word Counts") as app:
95
+ gr.Markdown("## 🧠 Train a Machine Learning Model on Your Dataset")
96
 
 
97
  with gr.Row():
98
+ file_input = gr.File(label="πŸ“ Upload CSV or Excel", file_types=[".csv", ".xls", ".xlsx"])
99
+ quantile_option = gr.Checkbox(label="Discretize into Quartiles", value=True)
100
+ wordcount_option = gr.Checkbox(label="Count Words in Text Columns", value=True)
101
 
102
  with gr.Row():
103
+ target_col = gr.Dropdown(label="🎯 Select Target Column")
104
+ feature_cols = gr.CheckboxGroup(label="🧠 Select Feature Columns")
105
 
106
  with gr.Row():
107
+ df_state = gr.State()
 
108
 
 
109
  with gr.Row():
110
+ table_preview = gr.DataFrame(label="πŸ“‹ Data Preview")
111
+ processed_preview = gr.DataFrame(label="πŸ” Processed Data (100 rows)")
112
 
113
+ data_summary = gr.Markdown()
 
 
114
 
115
  with gr.Row():
116
+ train_button = gr.Button("πŸš€ Train Model")
117
+ output = gr.Textbox(label="πŸ“Š Classification Report", lines=10)
118
+ help_box = gr.Textbox(label="ℹ️ Status", interactive=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
 
120
+ # πŸ”„ Events
121
  file_input.change(
122
  fn=on_file_change,
123
  inputs=[file_input, quantile_option, wordcount_option],
 
129
  data_summary,
130
  processed_preview,
131
  output,
132
+ help_box,
133
+ ],
134
  )
135
 
136
  train_button.click(
137
+ fn=train_model,
138
  inputs=[df_state, target_col, feature_cols],
139
+ outputs=[output, help_box],
140
  )
141
 
142
+ # πŸ” Launch the app
143
+ app.launch()