Ansaribinhyder commited on
Commit
702e044
·
1 Parent(s): 6a6c25d

Change to flask app

Browse files
Files changed (3) hide show
  1. app.py +72 -85
  2. requirements.txt +1 -1
  3. templates/index.html +55 -0
app.py CHANGED
@@ -1,98 +1,85 @@
1
- import gradio as gr
2
  import pandas as pd
3
  import matplotlib.pyplot as plt
4
  import numpy as np
5
  import io
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
- def plot_excel_data(golden_data_file, manipulated_data_file):
8
- """
9
- Reads two Excel files, plots the time-series data, and adds spec limits.
10
- """
11
- if golden_data_file is None:
12
- raise gr.Error("Please upload the 'Golden Data' Excel file.")
13
-
14
- try:
15
- # Read first 3 rows to extract limits from the golden data
16
- limits_df1 = pd.read_excel(golden_data_file.name, nrows=4)
17
- limits_df1 = limits_df1.drop(0)
18
-
19
- # Data (skip first 3 rows)
20
- df1 = pd.read_excel(golden_data_file.name)
21
- df1 = df1.drop([0, 1, 2, 3])
22
- df1 = df1.apply(pd.to_numeric, errors="coerce")
23
- except Exception as e:
24
- raise gr.Error(f"Error processing 'Golden Data' file: {e}")
25
-
26
- # Build limits dictionary per column
27
- ignore_cols = ["SITE_NUM", "PART_ID", "PASSFG", "SOFT_BIN", "T_TIME", "TEST_NUM"]
28
- cols_to_plot = [col for col in limits_df1.columns if "_" in col and col not in ignore_cols]
29
- limits_df1 = limits_df1.drop(columns=ignore_cols)
30
- limits = {
31
- col: {"LL": limits_df1.iloc[0][col], "UL": limits_df1.iloc[1][col]}
32
- for col in limits_df1.columns
33
- }
34
-
35
- # Initialize a second dataframe if a file is provided
36
- df2 = None
37
- if manipulated_data_file is not None:
38
  try:
39
- df2 = pd.read_excel(manipulated_data_file.name)
 
 
 
 
40
  df2 = df2.drop([0, 1, 2, 3])
 
 
41
  df2 = df2.apply(pd.to_numeric, errors="coerce")
42
- except Exception as e:
43
- raise gr.Error(f"Error processing 'Manipulated Data' file: {e}")
44
 
45
- # Plotting logic
46
- n_cols = 3
47
- n_rows = (len(df1.columns) + n_cols - 1) // n_cols
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
- fig, axes = plt.subplots(n_rows, n_cols, figsize=(n_cols * 5, n_rows * 3.5))
50
- if n_rows * n_cols > len(df1.columns):
51
- # Flatten axes array for easy iteration, then turn off unused subplots
52
- for i in range(len(df1.columns), n_rows * n_cols):
53
- axes.flatten()[i].axis('off')
54
 
55
- for i, col in enumerate(cols_to_plot):
56
- ax = axes.flatten()[i] if n_rows > 1 else axes[i]
57
-
58
- # Golden data (Old)
59
- x1 = np.arange(1, len(df1[col]) + 1)
60
- y1 = pd.to_numeric(df1[col], errors="coerce").values
61
- ax.plot(x1, y1, marker="o", linestyle="-", color="blue", label="Old")
62
-
63
- # New data (if provided)
64
- if df2 is not None and col in df2.columns:
65
- x2 = np.arange(1, len(df2[col]) + 1)
66
- y2 = pd.to_numeric(df2[col], errors="coerce").values
67
- ax.plot(x2, y2, marker="s", linestyle="--", color="red", label="New")
68
-
69
- # Spec limits
70
- if col in limits:
71
- ll, ul = limits[col]["LL"], limits[col]["UL"]
72
- ax.axhline(ll, color="green", linestyle="--", linewidth=2, label="LL")
73
- ax.axhline(ul, color="orange", linestyle="--", linewidth=2, label="UL")
74
-
75
- ax.set_title(f"{col}")
76
- ax.set_xlabel("Part # (sequence)")
77
- ax.set_ylabel("Value")
78
- ax.set_xticks(x1)
79
- ax.grid(True, linestyle="--", alpha=0.7)
80
- ax.legend()
81
-
82
- plt.tight_layout()
83
- return fig
84
-
85
- # Gradio Interface
86
- iface = gr.Interface(
87
- fn=plot_excel_data,
88
- inputs=[
89
- gr.File(label="Upload IPM_Golden_Data.xlsx (Required)"),
90
- gr.File(label="Upload IPM_Golden_Data_Manipulated.xlsx (Optional)"),
91
- ],
92
- outputs=gr.Plot(label="Comparison Plots"),
93
- title="Time-Series Data Comparison",
94
- description="Upload two Excel files to compare time-series data and visualize specification limits. The first file (Golden Data) is required and will be used to extract the limits."
95
- )
96
 
97
  if __name__ == "__main__":
98
- iface.launch()
 
1
+ from flask import Flask, render_template, request, send_file
2
  import pandas as pd
3
  import matplotlib.pyplot as plt
4
  import numpy as np
5
  import io
6
+ import os
7
+
8
+ app = Flask(__name__)
9
+
10
+ @app.route("/", methods=["GET", "POST"])
11
+ def index():
12
+ if request.method == "POST":
13
+ golden_file = request.files.get("golden_file")
14
+ test_file = request.files.get("test_file")
15
+
16
+ if not golden_file or not test_file:
17
+ return render_template("index.html", error="Please upload both files.")
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  try:
20
+ # --- Read Data ---
21
+ limits_df1 = pd.read_excel(golden_file, nrows=4)
22
+ df1 = pd.read_excel(golden_file)
23
+ df1 = df1.drop([0, 1, 2, 3])
24
+ df2 = pd.read_excel(test_file)
25
  df2 = df2.drop([0, 1, 2, 3])
26
+
27
+ df1 = df1.apply(pd.to_numeric, errors="coerce")
28
  df2 = df2.apply(pd.to_numeric, errors="coerce")
 
 
29
 
30
+ # --- Build Limits ---
31
+ limits_df1 = limits_df1.drop([0])
32
+ ignore_cols = ["SITE_NUM", "PART_ID", "PASSFG", "SOFT_BIN", "T_TIME", "TEST_NUM"]
33
+ cols_to_plot = [col for col in limits_df1.columns if "_" in col and col not in ignore_cols]
34
+ limits_df1 = limits_df1.drop(columns=ignore_cols)
35
+
36
+ limits = {
37
+ col: {"LL": limits_df1.iloc[0][col], "UL": limits_df1.iloc[1][col]}
38
+ for col in limits_df1.columns
39
+ }
40
+
41
+ # --- Plot ---
42
+ n_cols = 3
43
+ n_rows = (len(cols_to_plot) + n_cols - 1) // n_cols
44
+
45
+ plt.figure(figsize=(n_cols * 5, n_rows * 3.5))
46
+ for i, col in enumerate(cols_to_plot, 1):
47
+ plt.subplot(n_rows, n_cols, i)
48
+ x1 = np.arange(1, len(df1[col]) + 1)
49
+ y1 = pd.to_numeric(df1[col], errors="coerce").values
50
+ plt.plot(x1, y1, marker="o", linestyle="-", color="blue", label="Golden")
51
+
52
+ if col in df2.columns:
53
+ x2 = np.arange(1, len(df2[col]) + 1)
54
+ y2 = pd.to_numeric(df2[col], errors="coerce").values
55
+ plt.plot(x2, y2, marker="s", linestyle="--", color="red", label="Test")
56
+
57
+ if col in limits:
58
+ ll, ul = limits[col]["LL"], limits[col]["UL"]
59
+ plt.axhline(ll, color="green", linestyle="--", linewidth=2, label="LL")
60
+ plt.axhline(ul, color="orange", linestyle="--", linewidth=2, label="UL")
61
+
62
+ plt.title(f"{col}")
63
+ plt.xlabel("Part # (sequence)")
64
+ plt.ylabel("Value")
65
+ plt.grid(True, linestyle="--", alpha=0.7)
66
+ plt.legend(fontsize="small")
67
+
68
+ plt.tight_layout()
69
+
70
+ # Save plot to in-memory buffer
71
+ buf = io.BytesIO()
72
+ plt.savefig(buf, format="png", bbox_inches="tight")
73
+ buf.seek(0)
74
+ plt.close()
75
+
76
+ return send_file(buf, mimetype="image/png")
77
+
78
+ except Exception as e:
79
+ return render_template("index.html", error=f"Error: {str(e)}")
80
 
81
+ return render_template("index.html")
 
 
 
 
82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
  if __name__ == "__main__":
85
+ app.run(host="0.0.0.0", port=7860, debug=True)
requirements.txt CHANGED
@@ -1,4 +1,4 @@
1
- gradio
2
  pandas
3
  matplotlib
4
  numpy
 
1
+ flask
2
  pandas
3
  matplotlib
4
  numpy
templates/index.html ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <title>IPM Golden vs Test Data Visualizer</title>
5
+ <style>
6
+ body {
7
+ font-family: Arial, sans-serif;
8
+ background: #f2f2f2;
9
+ text-align: center;
10
+ padding: 40px;
11
+ }
12
+ form {
13
+ background: white;
14
+ padding: 20px;
15
+ border-radius: 10px;
16
+ display: inline-block;
17
+ }
18
+ input[type=file] {
19
+ margin: 10px;
20
+ }
21
+ button {
22
+ background-color: #0078d7;
23
+ color: white;
24
+ border: none;
25
+ padding: 10px 20px;
26
+ border-radius: 5px;
27
+ cursor: pointer;
28
+ }
29
+ button:hover {
30
+ background-color: #005fa3;
31
+ }
32
+ .error {
33
+ color: red;
34
+ }
35
+ </style>
36
+ </head>
37
+ <body>
38
+ <h2>📊 IPM Golden vs Test Data Visualizer</h2>
39
+ <p>Upload your Golden and Test Excel files to compare results visually.</p>
40
+
41
+ {% if error %}
42
+ <p class="error">{{ error }}</p>
43
+ {% endif %}
44
+
45
+ <form method="POST" enctype="multipart/form-data">
46
+ <label>Golden Data (.xlsx):</label><br>
47
+ <input type="file" name="golden_file" accept=".xlsx" required><br><br>
48
+
49
+ <label>Test Data (.xlsx):</label><br>
50
+ <input type="file" name="test_file" accept=".xlsx" required><br><br>
51
+
52
+ <button type="submit">Generate Plot</button>
53
+ </form>
54
+ </body>
55
+ </html>