dataanalysis / app.py
Ansaribinhyder's picture
Enhancement in the UI
815a086
raw
history blame
3.42 kB
from flask import Flask, render_template, request, redirect, url_for, send_file
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import io
import os
app = Flask(__name__)
app.config["UPLOAD_FOLDER"] = "uploads"
os.makedirs(app.config["UPLOAD_FOLDER"], exist_ok=True)
# Global variables to hold data between requests
df1, df2, limits, cols_to_plot = None, None, {}, []
def process_files(golden_file, test_file):
global df1, df2, limits, cols_to_plot
limits_df1 = pd.read_excel(golden_file, nrows=4)
df1 = pd.read_excel(golden_file)
df1 = df1.drop([0, 1, 2, 3])
df2 = pd.read_excel(test_file)
df2 = df2.drop([0, 1, 2, 3])
df1 = df1.apply(pd.to_numeric, errors="coerce")
df2 = df2.apply(pd.to_numeric, errors="coerce")
limits_df1 = limits_df1.drop([0])
ignore_cols = ["SITE_NUM", "PART_ID", "PASSFG", "SOFT_BIN", "T_TIME", "TEST_NUM"]
cols_to_plot = [col for col in limits_df1.columns if "_" in col and col not in ignore_cols]
limits_df1 = limits_df1.drop(columns=ignore_cols)
limits = {
col: {"LL": limits_df1.iloc[0][col], "UL": limits_df1.iloc[1][col]}
for col in limits_df1.columns
}
return df1, df2, limits, cols_to_plot
def generate_plot(col):
"""Generate a matplotlib plot for a single column."""
plt.figure(figsize=(6, 4))
x1 = np.arange(1, len(df1[col]) + 1)
y1 = pd.to_numeric(df1[col], errors="coerce").values
plt.plot(x1, y1, marker="o", linestyle="-", color="blue", label="Golden")
if col in df2.columns:
x2 = np.arange(1, len(df2[col]) + 1)
y2 = pd.to_numeric(df2[col], errors="coerce").values
plt.plot(x2, y2, marker="s", linestyle="--", color="red", label="Test")
if col in limits:
ll, ul = limits[col]["LL"], limits[col]["UL"]
plt.axhline(ll, color="green", linestyle="--", linewidth=2, label="LL")
plt.axhline(ul, color="orange", linestyle="--", linewidth=2, label="UL")
plt.title(f"{col}")
plt.xlabel("Part # (sequence)")
plt.ylabel("Value")
plt.grid(True, linestyle="--", alpha=0.7)
plt.legend(fontsize="small")
plt.tight_layout()
buf = io.BytesIO()
plt.savefig(buf, format="png", bbox_inches="tight")
buf.seek(0)
plt.close()
return buf
@app.route("/", methods=["GET", "POST"])
def index():
global df1, df2, limits, cols_to_plot
if request.method == "POST":
golden_file = request.files.get("golden_file")
test_file = request.files.get("test_file")
if not golden_file or not test_file:
return render_template("index.html", error="Please upload both files.")
try:
df1, df2, limits, cols_to_plot = process_files(golden_file, test_file)
# Show the first 3 plots initially
preview_cols = cols_to_plot[:3]
return render_template(
"plot.html",
cols=cols_to_plot,
preview_cols=preview_cols,
)
except Exception as e:
return render_template("index.html", error=f"Error: {str(e)}")
return render_template("index.html")
@app.route("/plot_image/<col>")
def plot_image(col):
"""Return plot as PNG stream for the selected column."""
buf = generate_plot(col)
return send_file(buf, mimetype="image/png")
if __name__ == "__main__":
app.run(host="0.0.0.0", port=7860, debug=True)