UsmanGoraya commited on
Commit
9838276
·
verified ·
1 Parent(s): 6b500f4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +199 -1
app.py CHANGED
@@ -1 +1,199 @@
1
- <REPLACE_WITH_FINAL_APP_CODE_FROM_CANVAS>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import ezdxf
3
+ import io
4
+ import pandas as pd
5
+ import matplotlib.pyplot as plt
6
+ from fpdf import FPDF
7
+ from tempfile import NamedTemporaryFile
8
+ import matplotlib.patches as patches
9
+ import tempfile
10
+
11
+ # Constants
12
+ BRICK_VOLUME_CFT = (9/12) * (4.5/12) * (3/12)
13
+ CEMENT_SAND_RATIO = 1 / 6
14
+ SAND_RATIO = 5 / 6
15
+ CEMENT_DENSITY_KG_PER_CFT = 1440 / 35.3147
16
+ CEMENT_BAG_WEIGHT_KG = 50
17
+ DEFAULT_WALL_THICKNESS = 0.75
18
+
19
+ st.set_page_config(page_title="Building Estimator from CAD", layout="wide")
20
+ st.title("🏗️ Auto Estimation from AutoCAD (.dxf) Drawing")
21
+
22
+ uploaded_file = st.file_uploader("Upload your DXF file", type=["dxf"])
23
+
24
+ @st.cache_data
25
+ def extract_geometry(file_bytes):
26
+ try:
27
+ text_buffer = io.TextIOWrapper(file_bytes, encoding='utf-8', errors='ignore')
28
+ doc = ezdxf.read(text_buffer)
29
+ except Exception as e:
30
+ st.error(f"Error reading DXF file: {e}")
31
+ return [], 0.75, [], 1, []
32
+
33
+ msp = doc.modelspace()
34
+ rooms = []
35
+ room_shapes = []
36
+ openings = []
37
+ floors = 1
38
+ wall_thickness = DEFAULT_WALL_THICKNESS
39
+
40
+ for entity in msp:
41
+ if entity.dxftype() == "TEXT":
42
+ content = entity.dxf.text.lower()
43
+ if "wall thickness" in content:
44
+ try:
45
+ wall_thickness = float(content.split(":")[1].strip())
46
+ except:
47
+ continue
48
+ elif "floor" in content:
49
+ try:
50
+ floors = int(content.split(":")[1].strip())
51
+ except:
52
+ continue
53
+
54
+ elif entity.dxftype() == "LWPOLYLINE":
55
+ if entity.closed and len(entity) == 4:
56
+ points = entity.get_points()
57
+ x_vals = [p[0] for p in points]
58
+ y_vals = [p[1] for p in points]
59
+ length = abs(max(x_vals) - min(x_vals)) / 12
60
+ width = abs(max(y_vals) - min(y_vals)) / 12
61
+ height = 10
62
+ if length > 2 and width > 2:
63
+ rooms.append((length, width, height))
64
+ room_shapes.append((min(x_vals), min(y_vals), max(x_vals), max(y_vals)))
65
+ else:
66
+ openings.append(("opening", length, height))
67
+
68
+ return rooms, wall_thickness, openings, floors, room_shapes
69
+
70
+ def estimate(rooms, wall_thickness, openings, floors):
71
+ wall_volume = sum(2 * (l + w) * h * wall_thickness for l, w, h in rooms)
72
+ opening_volume = sum(l * h * wall_thickness for _, l, h in openings)
73
+ beam_volume = sum((l + 1) * 0.75 * 0.75 for _, l, _ in openings)
74
+ net_volume = (wall_volume - opening_volume - beam_volume) * floors
75
+
76
+ number_of_bricks = round((net_volume / BRICK_VOLUME_CFT) * 1.05)
77
+ mortar_volume = net_volume * 0.25
78
+ cement_volume = mortar_volume * CEMENT_SAND_RATIO
79
+ sand_volume = mortar_volume * SAND_RATIO
80
+ cement_bag_volume_cft = CEMENT_BAG_WEIGHT_KG / CEMENT_DENSITY_KG_PER_CFT
81
+ cement_bags = round(cement_volume / cement_bag_volume_cft)
82
+
83
+ return number_of_bricks, sand_volume, cement_bags, {
84
+ "Wall Volume (cft)": wall_volume,
85
+ "Opening Volume (cft)": opening_volume,
86
+ "Beam Volume (cft)": beam_volume,
87
+ "Net Volume (cft)": net_volume,
88
+ "Mortar Volume (cft)": mortar_volume,
89
+ "Cement Volume (cft)": cement_volume,
90
+ "Sand Volume (cft)": sand_volume,
91
+ "Cement Bag Volume (cft)": cement_bag_volume_cft,
92
+ "Brick Volume (cft)": BRICK_VOLUME_CFT
93
+ }
94
+
95
+ def draw_plan_image(room_shapes):
96
+ fig, ax = plt.subplots()
97
+ for x0, y0, x1, y1 in room_shapes:
98
+ width = x1 - x0
99
+ height = y1 - y0
100
+ rect = patches.Rectangle((x0, y0), width, height, linewidth=1, edgecolor='black', facecolor='none')
101
+ ax.add_patch(rect)
102
+ ax.text(x0 + width / 2, y0 - 2, f"{round(width / 12, 1)} ft", ha='center', fontsize=8)
103
+ ax.text(x1 + 2, y0 + height / 2, f"{round(height / 12, 1)} ft", va='center', fontsize=8, rotation=90)
104
+ ax.set_aspect('equal')
105
+ ax.axis('off')
106
+ temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
107
+ fig.savefig(temp_file.name, bbox_inches='tight')
108
+ plt.close(fig)
109
+ return temp_file.name
110
+
111
+ def generate_pdf(data_dict, calc_details, room_shapes):
112
+ image_path = draw_plan_image(room_shapes)
113
+
114
+ pdf = FPDF()
115
+ pdf.add_page()
116
+ pdf.set_font("Arial", 'B', size=14)
117
+ pdf.cell(200, 10, "Estimation Report", ln=True, align='C')
118
+ pdf.ln(5)
119
+
120
+ pdf.set_font("Arial", 'B', size=12)
121
+ pdf.cell(200, 10, "Summary of Quantities", ln=True)
122
+ pdf.set_font("Arial", '', size=11)
123
+ for key, value in data_dict.items():
124
+ pdf.cell(200, 10, f"{key}: {value}", ln=True)
125
+
126
+ pdf.ln(8)
127
+ pdf.set_font("Arial", 'B', size=12)
128
+ pdf.cell(200, 10, "Step-by-Step Calculations with Formulas", ln=True)
129
+
130
+ pdf.set_font("Arial", '', size=10)
131
+ pdf.multi_cell(0, 8, f"""
132
+ 1. Wall Volume = 2 × (L + W) × H × t = {round(calc_details['Wall Volume (cft)'], 2)} cft
133
+ 2. Opening Volume = L × H × t = {round(calc_details['Opening Volume (cft)'], 2)} cft
134
+ 3. Beam Volume = (L+1) × 0.75 × 0.75 = {round(calc_details['Beam Volume (cft)'], 2)} cft
135
+ 4. Net Volume = (Wall - Opening - Beam) × Floors = {round(calc_details['Net Volume (cft)'], 2)} cft
136
+ 5. Brick Volume = 9\" × 4.5\" × 3\" = {round(calc_details['Brick Volume (cft)'], 4)} cft
137
+ 6. Bricks = Net Volume / Brick Vol × 1.05 = {data_dict['Bricks Required']}
138
+ 7. Mortar = Net Volume × 0.25 = {round(calc_details['Mortar Volume (cft)'], 2)} cft
139
+ 8. Cement = Mortar × 1/6 = {round(calc_details['Cement Volume (cft)'], 2)} cft
140
+ 9. Sand = Mortar × 5/6 = {round(calc_details['Sand Volume (cft)'], 2)} cft
141
+ 10. Cement Bags = Cement / Bag Volume = {data_dict['Cement Bags']}
142
+ """)
143
+
144
+ pdf.ln(5)
145
+ pdf.set_font("Arial", 'B', size=12)
146
+ pdf.cell(200, 10, "2D Plan with Dimensions (in ft)", ln=True)
147
+ pdf.image(image_path, x=10, y=None, w=180)
148
+
149
+ tmp = NamedTemporaryFile(delete=False, suffix=".pdf")
150
+ pdf.output(tmp.name)
151
+ return tmp.name
152
+
153
+ def plot_rooms(shapes):
154
+ fig, ax = plt.subplots()
155
+ for x0, y0, x1, y1 in shapes:
156
+ width = (x1 - x0)
157
+ height = (y1 - y0)
158
+ rect = plt.Rectangle((x0, y0), width, height, fill=False, edgecolor='blue', linewidth=2)
159
+ ax.add_patch(rect)
160
+ ax.set_title("🗏️ 2D Floor Plan")
161
+ ax.set_aspect("equal")
162
+ ax.axis("off")
163
+ st.pyplot(fig)
164
+
165
+ if uploaded_file:
166
+ file_bytes = io.BytesIO(uploaded_file.read())
167
+ rooms, wall_thickness, openings, floors, room_shapes = extract_geometry(file_bytes)
168
+
169
+ st.success(f"✔️ Parsed {len(rooms)} rooms and {len(openings)} openings across {floors} floor(s).")
170
+ st.write(f"📏 Wall Thickness: {wall_thickness} ft")
171
+
172
+ bricks, sand, cement, calc_details = estimate(rooms, wall_thickness, openings, floors)
173
+
174
+ st.subheader("📊 Room Dimensions")
175
+ df_rooms = pd.DataFrame(rooms, columns=["Length (ft)", "Width (ft)", "Height (ft)"])
176
+ st.dataframe(df_rooms)
177
+
178
+ st.subheader("🧱 Estimation Result")
179
+ df_result = pd.DataFrame({
180
+ "Item": ["Bricks", "Sand (cft)", "Cement (bags)"],
181
+ "Quantity": [bricks, round(sand, 2), cement]
182
+ })
183
+ st.dataframe(df_result)
184
+
185
+ st.subheader("🖼️ 2D Floor Plan")
186
+ plot_rooms(room_shapes)
187
+
188
+ st.subheader("📄 Export")
189
+ col1, col2 = st.columns(2)
190
+ with col1:
191
+ st.download_button("⬇️ Download Excel", df_result.to_csv(index=False).encode(), "estimates.csv", "text/csv")
192
+ with col2:
193
+ pdf_file = generate_pdf({
194
+ "Bricks Required": f"{bricks:,}",
195
+ "Sand Volume": f"{sand:.2f} cft",
196
+ "Cement Bags": f"{cement} bags"
197
+ }, calc_details, room_shapes)
198
+ with open(pdf_file, "rb") as f:
199
+ st.download_button("⬇️ Download PDF", f.read(), "estimates.pdf", "application/pdf")