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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
"""
Data2Model - Flask Web Application
Updated to handle all 8 system improvements.
"""

from flask import Flask, render_template, request, redirect, url_for, send_file, flash
import os, json, time, atexit, shutil
import pandas as pd
from werkzeug.utils import secure_filename
from model_pipeline import AutoMLPipeline
from datetime import datetime

app = Flask(__name__)
app.secret_key = 'data2model-secret-key-2025'

UPLOAD_FOLDER  = 'uploads'
MODEL_FOLDER   = 'saved_models'
ALLOWED_EXTENSIONS = {'csv', 'xlsx', 'xls', 'json'}

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MODEL_FOLDER']  = MODEL_FOLDER

os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(MODEL_FOLDER,  exist_ok=True)

current_pipeline = None
current_results  = None

# ── Workflow state ────────────────────────────────────────────────────────────
# Predict is unlocked when a model is trained successfully (with either split)
model_state = {
    'trained':      False,
    'split_type':   None,    # 'train_test' or 'train_test_val'
    'split_info':   None,    # human-readable e.g. "60% / 20% / 20%"
    'model_name':   None,
    'problem_type': None,
    'scaler_path':  None,    # path to saved scaler pkl (None if not applied)
    'encoder_path': None,    # path to saved encoder pkl (None if not applied)
    'scaling_applied':  False,
    'encoding_applied': False,
}

def predict_unlocked():
    return model_state['trained']


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


# ── Context processor: inject predict_unlocked into every template ───────────
@app.context_processor
def inject_state():
    return {
        'predict_unlocked': predict_unlocked(),
        'model_state': model_state,
    }


# ─────────────────────────────────────────────────────────────────────────────
def cleanup_old_files():
    """Delete files in uploads older than 1 hour to prevent permanent storage."""
    now = time.time()
    for filename in os.listdir(app.config['UPLOAD_FOLDER']):
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        if os.path.isfile(file_path):
            if os.stat(file_path).st_mtime < now - 3600:
                try:
                    os.remove(file_path)
                except Exception as e:
                    print(f"Error cleaning up file {file_path}: {e}")


def cleanup_file(filepath):
    """Safely delete a single file if it exists."""
    try:
        if filepath and os.path.isfile(filepath):
            os.remove(filepath)
            print(f"πŸ—‘ Cleaned up: {os.path.basename(filepath)}")
    except Exception as e:
        print(f"Warning: Could not delete {filepath}: {e}")


def cleanup_all_session_files():
    """Delete ALL session artifacts (uploads + saved models/zips) on shutdown."""
    # 1. Clean uploads
    upload_dir = app.config['UPLOAD_FOLDER']
    if os.path.isdir(upload_dir):
        for filename in os.listdir(upload_dir):
            file_path = os.path.join(upload_dir, filename)
            try:
                if os.path.isfile(file_path):
                    os.remove(file_path)
            except Exception:
                pass
        print("πŸ—‘ All uploaded files cleaned up on shutdown.")

    # 2. Clean saved_models (model .pkl, scaler .pkl, encoder .pkl, deployable_app .zip)
    model_dir = app.config['MODEL_FOLDER']
    if os.path.isdir(model_dir):
        for filename in os.listdir(model_dir):
            # Preserve .gitkeep so the directory stays tracked in git
            if filename == '.gitkeep':
                continue
            file_path = os.path.join(model_dir, filename)
            try:
                if os.path.isfile(file_path):
                    os.remove(file_path)
            except Exception:
                pass
        print("πŸ—‘ All saved models and deployable app zips cleaned up on shutdown.")


# Register shutdown hook β€” wipes uploads + saved models when server stops
atexit.register(cleanup_all_session_files)

# ─────────────────────────────────────────────────────────────────────────────
@app.route('/')
def index():
    return render_template('index.html')


# ─────────────────────────────────────────────────────────────────────────────
@app.route('/upload', methods=['POST'])
def upload_file():
    global current_pipeline, current_results

    try:
        cleanup_old_files()

        if 'file' not in request.files:
            flash('No file uploaded', 'error')
            return redirect(url_for('index'))

        file = request.files['file']
        if file.filename == '':
            flash('No file selected', 'error')
            return redirect(url_for('index'))

        if not allowed_file(file.filename):
            flash('Invalid file type. Please upload CSV, Excel, or JSON.', 'error')
            return redirect(url_for('index'))

        filename  = secure_filename(file.filename)
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        filename  = f"{timestamp}_{filename}"
        filepath  = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        file.save(filepath)

        ext = filename.rsplit('.', 1)[1].lower()
        file_type = 'excel' if ext in ('xlsx', 'xls') else ext

        current_pipeline = AutoMLPipeline()
        data     = current_pipeline.load_data(filepath, file_type)
        analysis = current_pipeline.analyze_data(data)
        viz_plots = current_pipeline.generate_visualizations(data, analysis['numeric_columns'], analysis['categorical_columns'])

        session_data = {
            'filepath':  filepath,
            'file_type': file_type,
            'filename':  file.filename,
            'viz_plots': viz_plots,
            'analysis': {
                'shape':               analysis['shape'],
                'columns':             analysis['columns'],
                'numeric_columns':     analysis['numeric_columns'],
                'categorical_columns': analysis['categorical_columns'],
                # missing_values: only cols that actually have gaps
                'missing_values':      {k: int(v) for k, v in analysis['missing_values'].items() if v > 0},
                'duplicates':          int(analysis['duplicates']),
                'col_stats':           analysis['col_stats'],
            }
        }

        return render_template('configure.html', data=session_data)

    except Exception as e:
        flash(f'Error processing file: {str(e)}', 'error')
        return redirect(url_for('index'))


# ─────────────────────────────────────────────────────────────────────────────
@app.route('/train', methods=['POST'])
def train_model():
    global current_pipeline, current_results

    try:
        filepath      = request.form.get('filepath')
        file_type     = request.form.get('file_type')
        target_column = request.form.get('target_column') or None
        problem_type  = request.form.get('problem_type', 'auto')
        split_type    = request.form.get('split_type', 'train_test')
        test_size     = float(request.form.get('test_size', 0.2))
        val_size      = float(request.form.get('val_size', 0.2))
        drop_columns  = request.form.getlist('drop_columns')

        # ── FIX 1 & 2: per-column null strategies ────────────────────────────
        null_strategies = {}
        for key, value in request.form.items():
            if key.startswith('null_') and not key.startswith('null_custom_'):
                col = key[5:]          # strip "null_"
                if value == 'custom':
                    custom_val = request.form.get(f'null_custom_{col}', '')
                    null_strategies[col] = f"custom_{custom_val}"
                else:
                    null_strategies[col] = value

        # ── FIX 6: per-column scaling config ─────────────────────────────────
        scaling_config = {}
        for key, value in request.form.items():
            if key.startswith('scale_'):
                col = key[6:]          # strip "scale_"
                scaling_config[col] = value
        # If no per-column choices collected, fall back to standard
        if not scaling_config:
            scaling_config = 'standard'

        # ── FIX 7: per-column encoding config ────────────────────────────────
        encoding_config = {}
        for key, value in request.form.items():
            if key.startswith('encode_'):
                col = key[7:]          # strip "encode_"
                encoding_config[col] = value
        if not encoding_config:
            encoding_config = 'auto'

        # ── FIX 8: categorical overrides ─────────────────────────────────────
        categorical_overrides = request.form.getlist('cat_override')

        # Validate target column for supervised
        UNSUPERVISED = ('clustering', 'dimensionality_reduction', 'association')
        if problem_type not in UNSUPERVISED and not target_column:
            flash('Please select a target column for supervised learning.', 'error')
            return redirect(url_for('index'))

        if current_pipeline is None:
            current_pipeline = AutoMLPipeline()

        results = current_pipeline.run_complete_pipeline(
            file_path=filepath,
            target_column=target_column,
            file_type=file_type,
            problem_type=problem_type,
            split_type=split_type,
            test_size=test_size,
            val_size=val_size,
            null_strategies=null_strategies or None,
            scaling_config=scaling_config,
            encoding_config=encoding_config,
            categorical_overrides=categorical_overrides or None,
            drop_columns=drop_columns or None,
        )

        current_results = results

        # ── Clean up: delete the uploaded dataset (no longer needed) ──────────
        cleanup_file(filepath)

        # ── FIX 9: update model_state β€” unlock predict only for 3-way split ──
        model_state['trained']           = True
        model_state['split_type']        = split_type
        model_state['split_info']        = results.get('split_info')
        model_state['model_name']        = results.get('model_name')
        model_state['problem_type']      = results.get('problem_type')
        model_state['scaler_path']       = results.get('scaler_path')
        model_state['encoder_path']      = results.get('encoder_path')
        model_state['deployable_app_path'] = results.get('deployable_app_path')
        model_state['scaling_applied']   = results.get('scaling_applied', False)
        model_state['encoding_applied']  = results.get('encoding_applied', False)

        return render_template('result.html',
                               results=results,
                               pipeline=current_pipeline,
                               predict_unlocked=predict_unlocked())

    except Exception as e:
        import traceback
        traceback.print_exc()
        flash(f'Error during training: {str(e)}', 'error')
        return redirect(url_for('index'))


# ─────────────────────────────────────────────────────────────────────────────
@app.route('/download_model')
def download_model():
    try:
        if current_results and 'model_path' in current_results:
            return send_file(current_results['model_path'], as_attachment=True)
        flash('No model available for download.', 'error')
        return redirect(url_for('index'))
    except Exception as e:
        flash(f'Download error: {str(e)}', 'error')
        return redirect(url_for('index'))


# ─────────────────────────────────────────────────────────────────────────────
@app.route('/download_scaler')
def download_scaler():
    try:
        path = model_state.get('scaler_path')
        if path and os.path.exists(path):
            return send_file(path, as_attachment=True)
        flash('No scaler artifact available for download.', 'error')
        return redirect(url_for('index'))
    except Exception as e:
        flash(f'Download error: {str(e)}', 'error')
        return redirect(url_for('index'))


# ─────────────────────────────────────────────────────────────────────────────
@app.route('/download_encoder')
def download_encoder():
    try:
        path = model_state.get('encoder_path')
        if path and os.path.exists(path):
            return send_file(path, as_attachment=True)
        flash('No encoder artifact available for download.', 'error')
        return redirect(url_for('index'))
    except Exception as e:
        flash(f'Download error: {str(e)}', 'error')
        return redirect(url_for('index'))


# ─────────────────────────────────────────────────────────────────────────────
@app.route('/download_app')
def download_app():
    try:
        path = model_state.get('deployable_app_path')
        if path and os.path.exists(path):
            return send_file(path, as_attachment=True,
                             download_name='prediction_app.zip',
                             mimetype='application/zip')
        flash('No deployable app available for download. Please train a model first.', 'error')
        return redirect(url_for('index'))
    except Exception as e:
        flash(f'Error generating deployable app: {str(e)}', 'error')
        return redirect(url_for('index'))


# ─────────────────────────────────────────────────────────────────────────────
@app.route('/predict', methods=['GET', 'POST'])
def predict():
    # Gate β€” predict only when a model is trained
    if request.method == 'GET':
        if not predict_unlocked():
            return render_template('predict_locked.html',
                                   model_trained=model_state['trained'],
                                   split_type=model_state['split_type'])
        return render_template('predict.html', model_state=model_state)

    try:
        # Also block POST if not trained
        if not predict_unlocked():
            flash('Predictions are only available after training a model.', 'warning')
            return redirect(url_for('predict'))

        if current_pipeline is None or current_pipeline.model is None:
            flash('No trained model found. Please train a model first.', 'error')
            return redirect(url_for('index'))

        if 'file' not in request.files:
            flash('No file uploaded', 'error')
            return redirect(url_for('predict'))

        file = request.files['file']
        if file.filename == '':
            flash('No file selected', 'error')
            return redirect(url_for('predict'))

        filename = secure_filename(file.filename)
        filepath = os.path.join(app.config['UPLOAD_FOLDER'], f"pred_{filename}")
        file.save(filepath)

        ext = filename.rsplit('.', 1)[1].lower()
        if ext == 'csv':
            pred_data = pd.read_csv(filepath)
        elif ext in ('xlsx', 'xls'):
            pred_data = pd.read_excel(filepath)
        else:
            pred_data = pd.read_json(filepath)

        predictions = current_pipeline.predict(pred_data)
        pred_data['Predictions'] = predictions

        out_path = os.path.join(app.config['UPLOAD_FOLDER'], f"predictions_{filename.rsplit('.',1)[0]}.csv")
        pred_data.to_csv(out_path, index=False)

        # Clean up the prediction input file (output CSV kept for download)
        cleanup_file(filepath)

        return render_template('predict.html',
                               predictions=predictions.tolist()[:100],
                               total=len(predictions),
                               download_path=out_path)

    except Exception as e:
        flash(f'Prediction error: {str(e)}', 'error')
        return redirect(url_for('predict'))


# ─────────────────────────────────────────────────────────────────────────────
@app.route('/feedback', methods=['GET', 'POST'])
def feedback():
    if request.method == 'GET':
        return render_template('feedback.html')

    try:
        fb = {
            'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'name':    request.form.get('name'),
            'email':   request.form.get('email'),
            'rating':  request.form.get('rating'),
            'message': request.form.get('message'),
        }
        fb_file = 'feedback.json'
        existing = []
        if os.path.exists(fb_file):
            with open(fb_file) as f:
                existing = json.load(f)
        existing.append(fb)
        with open(fb_file, 'w') as f:
            json.dump(existing, f, indent=2)
        flash('Thank you for your feedback!', 'success')
        return redirect(url_for('feedback'))
    except Exception as e:
        flash(f'Error submitting feedback: {str(e)}', 'error')
        return redirect(url_for('feedback'))


# ─────────────────────────────────────────────────────────────────────────────
@app.route('/about')
def about():
    return render_template('about.html')


@app.route('/documentation')
def documentation():
    return render_template('documentation.html')


@app.errorhandler(404)
def not_found(e):
    return render_template('404.html'), 404


@app.errorhandler(500)
def server_error(e):
    return render_template('500.html'), 500


if __name__ == '__main__':
    # use_reloader=False prevents the server from restarting mid-training
    # when the pipeline saves .pkl files or the deployable app zip.
    port = int(os.environ.get('PORT', 5000))
    app.run(debug=True, use_reloader=False, host='0.0.0.0', port=port)