razaali10 commited on
Commit
06b3467
·
verified ·
1 Parent(s): d6ad8ce

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -30
app.py CHANGED
@@ -5,8 +5,9 @@ import traceback
5
  from hardy_cross_solver import hardy_cross_solver
6
  from hardy_cross_plot import plot_hardy_cross_network
7
  import os
 
8
 
9
- def run_hardy_cross(file, loops_json, max_iterations, tolerance):
10
  try:
11
  df = pd.read_csv(file.name)
12
  pipes_data = df.to_dict(orient='records')
@@ -17,48 +18,78 @@ def run_hardy_cross(file, loops_json, max_iterations, tolerance):
17
  max_iterations=int(max_iterations),
18
  tolerance=float(tolerance)
19
  )
20
-
21
  plot_filename = "hardy_cross_network_result.png"
22
  plot_path = plot_hardy_cross_network(final_flows, save_path=plot_filename)
23
 
24
- # Debug print statements for clear diagnosis
25
- print(f"DEBUG: plot_path returned by plot_hardy_cross_network: {plot_path}")
26
- print(f"DEBUG: os.path.exists(plot_path): {os.path.exists(plot_path)}")
27
- print(f"DEBUG: os.listdir('.'): {os.listdir('.')}")
28
- print(f"DEBUG: Current working directory: {os.getcwd()}")
29
-
30
- # Validate plot_path before returning
31
  if not (os.path.isfile(plot_path) and plot_path.endswith(".png")):
32
- print("DEBUG: Invalid plot_path detected, returning empty string for Gradio image output.")
33
- plot_path = "" # Safe fallback to prevent directory error
34
 
35
  return (
36
- final_flows.to_markdown(),
37
- pd.DataFrame(results).to_markdown(),
38
  plot_path
39
  )
40
  except Exception as e:
41
  tb = traceback.format_exc()
42
  error_message = f"❌ **Error:** {str(e)}\n\n```\n{tb}\n```"
43
- print(error_message)
44
  return error_message, "", ""
45
 
46
- demo = gr.Interface(
47
- fn=run_hardy_cross,
48
- inputs=[
49
- gr.File(label="Upload Pipe Network CSV"),
50
- gr.Textbox(label="Loops JSON (e.g., {\"L1\": [\"P1\", \"P2\"], \"L2\": [\"P3\", \"P4\"]})"),
51
- gr.Number(label="Max Iterations", value=10),
52
- gr.Number(label="Tolerance", value=0.001)
53
- ],
54
- outputs=[
55
- gr.Markdown(label="Final Pipe Flows or Error Trace"),
56
- gr.Markdown(label="Iteration Details"),
57
- gr.Image(label="Flow Direction Plot")
58
- ],
59
- title="Hardy Cross Method Solver with Visualization",
60
- description="Upload your pipe network CSV and loops JSON to compute flows and visualize using the Hardy Cross Method."
61
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
  if __name__ == "__main__":
64
  demo.launch()
 
5
  from hardy_cross_solver import hardy_cross_solver
6
  from hardy_cross_plot import plot_hardy_cross_network
7
  import os
8
+ import numpy as np
9
 
10
+ def hardy_cross_tab(file, loops_json, max_iterations, tolerance):
11
  try:
12
  df = pd.read_csv(file.name)
13
  pipes_data = df.to_dict(orient='records')
 
18
  max_iterations=int(max_iterations),
19
  tolerance=float(tolerance)
20
  )
 
21
  plot_filename = "hardy_cross_network_result.png"
22
  plot_path = plot_hardy_cross_network(final_flows, save_path=plot_filename)
23
 
24
+ # Safety check
 
 
 
 
 
 
25
  if not (os.path.isfile(plot_path) and plot_path.endswith(".png")):
26
+ plot_path = ""
 
27
 
28
  return (
29
+ final_flows.to_markdown(index=False),
30
+ pd.DataFrame(results).to_markdown(index=False),
31
  plot_path
32
  )
33
  except Exception as e:
34
  tb = traceback.format_exc()
35
  error_message = f"❌ **Error:** {str(e)}\n\n```\n{tb}\n```"
 
36
  return error_message, "", ""
37
 
38
+ def head_loss_tab(file):
39
+ try:
40
+ df = pd.read_csv(file.name)
41
+ g = 9.81
42
+ df["area_m2"] = np.pi * (df["diameter_m"] / 2) ** 2
43
+ df["velocity_ms"] = np.abs(df["flow_m3s"]) / df["area_m2"]
44
+ df["head_loss_m"] = (
45
+ df["friction_factor"]
46
+ * df["length_m"]
47
+ / df["diameter_m"]
48
+ * df["velocity_ms"] ** 2
49
+ / (2 * g)
50
+ )
51
+ output_csv = "head_loss_results.csv"
52
+ df.to_csv(output_csv, index=False)
53
+ return (
54
+ df[["pipe_id", "velocity_ms", "head_loss_m"]].to_markdown(index=False),
55
+ output_csv
56
+ )
57
+ except Exception as e:
58
+ tb = traceback.format_exc()
59
+ error_message = f"❌ **Error:** {str(e)}\n\n```\n{tb}\n```"
60
+ return error_message, None
61
+
62
+ with gr.Blocks(title="Hardy Cross Method and Head Loss Calculator") as demo:
63
+ gr.Markdown("# Hardy Cross Method Solver and Head Loss Calculator")
64
+ with gr.Tab("Hardy Cross Solver"):
65
+ gr.Markdown("Upload your pipe network CSV and loops JSON to compute flows and visualize using the Hardy Cross Method.")
66
+ file_input = gr.File(label="Upload Pipe Network CSV")
67
+ loops_json_input = gr.Textbox(label="Loops JSON", placeholder='{"L1": ["AB", "BC", "CD"], "L2": ["DE", "EF", "BC"]}')
68
+ max_iter_input = gr.Number(label="Max Iterations", value=10)
69
+ tol_input = gr.Number(label="Tolerance", value=0.001)
70
+ run_button = gr.Button("Run Hardy Cross")
71
+ flows_output = gr.Markdown(label="Final Pipe Flows")
72
+ iterations_output = gr.Markdown(label="Iteration Details")
73
+ plot_output = gr.Image(label="Flow Direction Plot")
74
+
75
+ run_button.click(
76
+ hardy_cross_tab,
77
+ inputs=[file_input, loops_json_input, max_iter_input, tol_input],
78
+ outputs=[flows_output, iterations_output, plot_output]
79
+ )
80
+
81
+ with gr.Tab("Head Loss Calculator"):
82
+ gr.Markdown("Upload your final flows CSV with columns: `pipe_id`, `length_m`, `diameter_m`, `friction_factor`, `flow_m3s` to compute head losses.")
83
+ file_input_hl = gr.File(label="Upload Final Flows CSV")
84
+ run_button_hl = gr.Button("Compute Head Losses")
85
+ head_loss_output = gr.Markdown(label="Head Loss Results")
86
+ download_output = gr.File(label="Download Computed Head Loss CSV")
87
+
88
+ run_button_hl.click(
89
+ head_loss_tab,
90
+ inputs=[file_input_hl],
91
+ outputs=[head_loss_output, download_output]
92
+ )
93
 
94
  if __name__ == "__main__":
95
  demo.launch()