Data2Model / app.py
Nausad's picture
Upload 25 files
facf506 verified
Raw History Blame Contribute Delete
19.6 kB
"""
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)