Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
@@ -1,10 +1,41 @@
|
|
1 |
import cv2
|
2 |
import numpy as np
|
3 |
-
from PIL import Image
|
4 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
|
6 |
# Function to calculate materials based on blueprint dimensions
|
7 |
def calculate_materials_from_dimensions(wall_area, foundation_area):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
materials = {
|
9 |
"cement": 0,
|
10 |
"bricks": 0,
|
@@ -15,83 +46,182 @@ def calculate_materials_from_dimensions(wall_area, foundation_area):
|
|
15 |
if wall_area > 0:
|
16 |
materials['cement'] += wall_area * 10 # 10 kg cement per m² for walls
|
17 |
materials['bricks'] += wall_area * 500 # 500 bricks per m² for walls
|
18 |
-
materials['steel'] += wall_area * 2
|
|
|
|
|
19 |
|
20 |
# Foundation calculations (in m²)
|
21 |
if foundation_area > 0:
|
22 |
materials['cement'] += foundation_area * 20 # 20 kg cement per m² for foundation
|
23 |
materials['bricks'] += foundation_area * 750 # 750 bricks per m² for foundation
|
24 |
-
materials['steel'] += foundation_area * 5
|
|
|
|
|
25 |
|
|
|
26 |
return materials
|
27 |
|
28 |
-
# Function to process the blueprint
|
29 |
-
def process_blueprint(
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
if
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
85 |
|
86 |
# Set up Gradio interface
|
87 |
interface = gr.Interface(
|
88 |
fn=process_blueprint,
|
89 |
-
inputs=
|
|
|
|
|
|
|
|
|
|
|
90 |
outputs=gr.JSON(label="Material Estimates"),
|
91 |
title="Blueprint Material Estimator",
|
92 |
-
description=
|
|
|
|
|
|
|
93 |
)
|
94 |
|
95 |
# Launch the interface
|
96 |
if __name__ == "__main__":
|
|
|
97 |
interface.launch(share=False)
|
|
|
1 |
import cv2
|
2 |
import numpy as np
|
|
|
3 |
import gradio as gr
|
4 |
+
from pdf2image import convert_from_path
|
5 |
+
import os
|
6 |
+
import tempfile
|
7 |
+
import logging
|
8 |
+
|
9 |
+
# Set up logging to debug.log
|
10 |
+
logging.basicConfig(
|
11 |
+
filename='debug.log',
|
12 |
+
level=logging.DEBUG,
|
13 |
+
format='%(asctime)s - %(levelname)s - %(message)s'
|
14 |
+
)
|
15 |
+
logger = logging.getLogger(__name__)
|
16 |
|
17 |
# Function to calculate materials based on blueprint dimensions
|
18 |
def calculate_materials_from_dimensions(wall_area, foundation_area):
|
19 |
+
"""
|
20 |
+
Calculate required materials (cement, bricks, steel) based on wall and foundation areas.
|
21 |
+
Args:
|
22 |
+
wall_area (float): Wall area in square meters.
|
23 |
+
foundation_area (float): Foundation area in square meters.
|
24 |
+
Returns:
|
25 |
+
dict: Material quantities (cement in kg, bricks in units, steel in kg).
|
26 |
+
Raises:
|
27 |
+
ValueError: If areas are negative or invalid.
|
28 |
+
"""
|
29 |
+
logger.debug(f"Calculating materials for wall_area={wall_area}, foundation_area={foundation_area}")
|
30 |
+
|
31 |
+
# Validate inputs
|
32 |
+
if not isinstance(wall_area, (int, float)) or not isinstance(foundation_area, (int, float)):
|
33 |
+
logger.error("Invalid area type: wall_area and foundation_area must be numeric")
|
34 |
+
raise ValueError("Wall and foundation areas must be numeric")
|
35 |
+
if wall_area < 0 or foundation_area < 0:
|
36 |
+
logger.error("Negative areas provided: wall_area=%s, foundation_area=%s", wall_area, foundation_area)
|
37 |
+
raise ValueError("Wall and foundation areas must be non-negative")
|
38 |
+
|
39 |
materials = {
|
40 |
"cement": 0,
|
41 |
"bricks": 0,
|
|
|
46 |
if wall_area > 0:
|
47 |
materials['cement'] += wall_area * 10 # 10 kg cement per m² for walls
|
48 |
materials['bricks'] += wall_area * 500 # 500 bricks per m² for walls
|
49 |
+
materials['steel'] += wall_area * 2 # 2 kg steel per m² for walls
|
50 |
+
logger.debug("Wall materials: cement=%s kg, bricks=%s, steel=%s kg",
|
51 |
+
materials['cement'], materials['bricks'], materials['steel'])
|
52 |
|
53 |
# Foundation calculations (in m²)
|
54 |
if foundation_area > 0:
|
55 |
materials['cement'] += foundation_area * 20 # 20 kg cement per m² for foundation
|
56 |
materials['bricks'] += foundation_area * 750 # 750 bricks per m² for foundation
|
57 |
+
materials['steel'] += foundation_area * 5 # 5 kg steel per m² for foundation
|
58 |
+
logger.debug("Foundation materials added: cement=%s kg, bricks=%s, steel=%s kg",
|
59 |
+
materials['cement'], materials['bricks'], materials['steel'])
|
60 |
|
61 |
+
logger.info("Material calculation complete: %s", materials)
|
62 |
return materials
|
63 |
|
64 |
+
# Function to process the blueprint from a PDF
|
65 |
+
def process_blueprint(pdf_path, blueprint_width_m=27, blueprint_height_m=9.78, poppler_path=None):
|
66 |
+
"""
|
67 |
+
Process a PDF blueprint to estimate construction materials.
|
68 |
+
Args:
|
69 |
+
pdf_path (str): Path to the PDF file.
|
70 |
+
blueprint_width_m (float): Blueprint width in meters (default: 27).
|
71 |
+
blueprint_height_m (float): Blueprint height in meters (default: 9.78).
|
72 |
+
poppler_path (str, optional): Path to poppler binaries.
|
73 |
+
Returns:
|
74 |
+
dict: Formatted material estimates or error message.
|
75 |
+
"""
|
76 |
+
logger.info("Starting blueprint processing for PDF: %s", pdf_path)
|
77 |
+
|
78 |
+
# Validate inputs
|
79 |
+
if not os.path.exists(pdf_path):
|
80 |
+
logger.error("PDF file does not exist: %s", pdf_path)
|
81 |
+
return {"error": f"PDF file not found: {pdf_path}"}
|
82 |
+
if not isinstance(blueprint_width_m, (int, float)) or not isinstance(blueprint_height_m, (int, float)):
|
83 |
+
logger.error("Invalid blueprint dimensions: width=%s, height=%s", blueprint_width_m, blueprint_height_m)
|
84 |
+
return {"error": "Blueprint width and height must be numeric"}
|
85 |
+
if blueprint_width_m <= 0 or blueprint_height_m <= 0:
|
86 |
+
logger.error("Invalid blueprint dimensions: width=%s, height=%s", blueprint_width_m, blueprint_height_m)
|
87 |
+
return {"error": "Blueprint width and height must be positive"}
|
88 |
+
|
89 |
+
try:
|
90 |
+
# Convert PDF to images
|
91 |
+
logger.debug("Converting PDF to image with poppler_path=%s", poppler_path)
|
92 |
+
images = convert_from_path(
|
93 |
+
pdf_path,
|
94 |
+
first_page=1,
|
95 |
+
last_page=1,
|
96 |
+
poppler_path=poppler_path
|
97 |
+
)
|
98 |
+
if not images:
|
99 |
+
logger.error("No images extracted from PDF")
|
100 |
+
return {"error": "No images extracted from the PDF"}
|
101 |
+
|
102 |
+
logger.info("Successfully extracted %d image(s) from PDF", len(images))
|
103 |
+
|
104 |
+
# Save the first page as a temporary image
|
105 |
+
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as temp_file:
|
106 |
+
images[0].save(temp_file.name, 'PNG')
|
107 |
+
temp_image_path = temp_file.name
|
108 |
+
logger.debug("Saved temporary image to: %s", temp_image_path)
|
109 |
+
|
110 |
+
# Verify temporary file exists
|
111 |
+
if not os.path.exists(temp_image_path):
|
112 |
+
logger.error("Temporary image file not created: %s", temp_image_path)
|
113 |
+
return {"error": "Failed to create temporary image file"}
|
114 |
+
|
115 |
+
# Open the image with OpenCV
|
116 |
+
image = cv2.imread(temp_image_path)
|
117 |
+
if image is None:
|
118 |
+
logger.error("Failed to load image from: %s", temp_image_path)
|
119 |
+
return {"error": "Could not load the image from PDF"}
|
120 |
+
|
121 |
+
logger.info("Loaded image with dimensions: %s", image.shape)
|
122 |
+
|
123 |
+
# Clean up temporary file
|
124 |
+
os.unlink(temp_image_path)
|
125 |
+
logger.debug("Deleted temporary image file: %s", temp_image_path)
|
126 |
+
|
127 |
+
# Convert to grayscale for easier processing
|
128 |
+
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
129 |
+
logger.debug("Converted image to grayscale")
|
130 |
+
|
131 |
+
# Apply edge detection to find lines (walls)
|
132 |
+
edges = cv2.Canny(gray, 50, 150, apertureSize=3)
|
133 |
+
logger.debug("Applied Canny edge detection")
|
134 |
+
|
135 |
+
# Use Hough Transform to detect lines (walls)
|
136 |
+
lines = cv2.HoughLinesP(edges, 1, np.pi / 180, threshold=100, minLineLength=50, maxLineGap=10)
|
137 |
+
logger.debug("Detected %s lines with Hough Transform", len(lines) if lines is not None else 0)
|
138 |
+
|
139 |
+
# Calculate total wall length (in pixels)
|
140 |
+
total_wall_length_pixels = 0
|
141 |
+
if lines is not None:
|
142 |
+
for line in lines:
|
143 |
+
x1, y1, x2, y2 = line[0]
|
144 |
+
length = np.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
|
145 |
+
total_wall_length_pixels += length
|
146 |
+
logger.debug("Line from (%d,%d) to (%d,%d), length=%f pixels", x1, y1, x2, y2, length)
|
147 |
+
else:
|
148 |
+
logger.warning("No lines detected in the blueprint")
|
149 |
+
|
150 |
+
logger.info("Total wall length in pixels: %f", total_wall_length_pixels)
|
151 |
+
|
152 |
+
# Get image dimensions
|
153 |
+
image_height, image_width = image.shape[:2]
|
154 |
+
logger.debug("Image dimensions: width=%d, height=%d pixels", image_width, image_height)
|
155 |
+
|
156 |
+
# Calculate pixel-to-meter ratio
|
157 |
+
pixel_to_meter_width = blueprint_width_m / image_width
|
158 |
+
pixel_to_meter_height = blueprint_height_m / image_height
|
159 |
+
pixel_to_meter = (pixel_to_meter_width + pixel_to_meter_height) / 2
|
160 |
+
logger.debug("Pixel-to-meter ratios: width=%f, height=%f, average=%f",
|
161 |
+
pixel_to_meter_width, pixel_to_meter_height, pixel_to_meter)
|
162 |
+
|
163 |
+
# Convert wall length to meters
|
164 |
+
total_wall_length_m = total_wall_length_pixels * pixel_to_meter
|
165 |
+
logger.info("Total wall length in meters: %f", total_wall_length_m)
|
166 |
+
|
167 |
+
# Estimate wall area (assume wall height of 3 m)
|
168 |
+
wall_height_m = 3 # Hardcoded assumption; may need adjustment
|
169 |
+
wall_area = total_wall_length_m * wall_height_m
|
170 |
+
logger.info("Wall area: %f m² (wall length=%f m, height=%f m)",
|
171 |
+
wall_area, total_wall_length_m, wall_height_m)
|
172 |
+
|
173 |
+
# Estimate foundation area (10% of total blueprint area)
|
174 |
+
total_area = blueprint_width_m * blueprint_height_m
|
175 |
+
foundation_area = total_area * 0.1 # Hardcoded assumption
|
176 |
+
logger.info("Total area: %f m², Foundation area: %f m²", total_area, foundation_area)
|
177 |
+
|
178 |
+
# Calculate materials
|
179 |
+
materials = calculate_materials_from_dimensions(wall_area, foundation_area)
|
180 |
+
logger.info("Raw material estimates: %s", materials)
|
181 |
+
|
182 |
+
# Format the output
|
183 |
+
formatted_materials = {
|
184 |
+
"cement": f"{materials['cement']:.2f} kg",
|
185 |
+
"bricks": f"{materials['bricks']:.0f} units",
|
186 |
+
"steel": f"{materials['steel']:.2f} kg"
|
187 |
+
}
|
188 |
+
logger.info("Formatted material estimates: %s", formatted_materials)
|
189 |
+
|
190 |
+
return formatted_materials
|
191 |
+
|
192 |
+
except Exception as e:
|
193 |
+
# Customize error message for poppler-related issues
|
194 |
+
error_msg = str(e)
|
195 |
+
if "Unable to get page count" in error_msg:
|
196 |
+
error_msg = (
|
197 |
+
"Poppler is not installed or not in PATH. "
|
198 |
+
"Please install poppler-utils:\n"
|
199 |
+
"- Windows: Download from https://github.com/oschwartz10612/poppler-windows and add to PATH.\n"
|
200 |
+
"- Linux: Run 'sudo apt-get install poppler-utils'.\n"
|
201 |
+
"- Mac: Run 'brew install poppler'.\n"
|
202 |
+
"Alternatively, specify poppler_path in the input (e.g., C:/poppler/bin)."
|
203 |
+
)
|
204 |
+
logger.error("Processing failed: %s", error_msg)
|
205 |
+
return {"error": f"Failed to process PDF: {error_msg}"}
|
206 |
|
207 |
# Set up Gradio interface
|
208 |
interface = gr.Interface(
|
209 |
fn=process_blueprint,
|
210 |
+
inputs=[
|
211 |
+
gr.File(file_types=[".pdf"], label="Upload Blueprint PDF"),
|
212 |
+
gr.Number(label="Blueprint Width (meters)", value=27),
|
213 |
+
gr.Number(label="Blueprint Height (meters)", value=9.78),
|
214 |
+
gr.Textbox(label="Poppler Path (optional)", placeholder="e.g., C:/poppler/bin")
|
215 |
+
],
|
216 |
outputs=gr.JSON(label="Material Estimates"),
|
217 |
title="Blueprint Material Estimator",
|
218 |
+
description=(
|
219 |
+
"Upload a PDF containing a blueprint to estimate construction materials. "
|
220 |
+
"Specify blueprint dimensions and optionally provide the path to poppler binaries if not in PATH."
|
221 |
+
)
|
222 |
)
|
223 |
|
224 |
# Launch the interface
|
225 |
if __name__ == "__main__":
|
226 |
+
logger.info("Launching Gradio interface")
|
227 |
interface.launch(share=False)
|