UsmanGoraya commited on
Commit
f624e78
·
verified ·
1 Parent(s): 4427c88

Delete app.py

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