from flask import Flask, render_template_string, request, send_file
import zipfile, os, io, base64
import pandas as pd
import plotly.express as px
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
app = Flask(__name__)
UPLOAD_FOLDER = 'uploads'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
HTML_PAGE = """
Advanced CSV Analyzer
Advanced CSV / ZIP Analyzer
{{ plot_html|safe }}
{{ ml_result }}
{% if csv_file %}
Download Combined CSV
{% endif %}
"""
@app.route('/', methods=['GET','POST'])
def index():
plot_html = ""
ml_result = ""
csv_file = None
if request.method=='POST':
file = request.files['file']
action = request.form.get('action')
csv_files = []
if file.filename.endswith('.zip'):
zip_path = os.path.join(UPLOAD_FOLDER, file.filename)
file.save(zip_path)
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall(UPLOAD_FOLDER)
csv_files = [os.path.join(UPLOAD_FOLDER,f) for f in zip_ref.namelist() if f.endswith('.csv')]
else:
path = os.path.join(UPLOAD_FOLDER, file.filename)
file.save(path)
csv_files = [path]
if action=='combine':
df = pd.concat([pd.read_csv(f) for f in csv_files], ignore_index=True)
else:
df = pd.read_csv(csv_files[0])
for f in csv_files[1:]:
df = df.append(pd.read_csv(f), ignore_index=True)
combined_csv = os.path.join(UPLOAD_FOLDER, 'combined.csv')
df.to_csv(combined_csv, index=False)
csv_file = 'combined.csv'
# Visualization with Plotly
num_df = df.select_dtypes(include='number')
if not num_df.empty:
fig = px.scatter_matrix(num_df)
plot_html = fig.to_html(full_html=False)
# ML Prediction
numeric_cols = num_df.columns
if len(numeric_cols)>1:
X = num_df[numeric_cols[:-1]].fillna(0)
y = num_df[numeric_cols[-1]].fillna(0)
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2, random_state=42)
model = LinearRegression()
model.fit(X_train,y_train)
pred = model.predict(X_test)
mse = mean_squared_error(y_test, pred)
ml_result = f"ML Prediction done! Mean Squared Error: {mse:.2f}"
return render_template_string(HTML_PAGE, plot_html=plot_html, ml_result=ml_result, csv_file=csv_file)
@app.route('/download/')
def download_file(filename):
return send_file(os.path.join(UPLOAD_FOLDER, filename), as_attachment=True)
if __name__=='__main__':
app.run(debug=True)