Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -11,49 +11,34 @@ import json
|
|
| 11 |
import re
|
| 12 |
from io import BytesIO
|
| 13 |
import math
|
|
|
|
| 14 |
import fitz # PyMuPDF
|
| 15 |
from PIL import Image
|
| 16 |
import google.generativeai as genai
|
| 17 |
-
|
| 18 |
-
#
|
| 19 |
logging.basicConfig(
|
| 20 |
level=logging.INFO,
|
| 21 |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
| 22 |
handlers=[
|
| 23 |
-
logging.StreamHandler(),
|
| 24 |
-
logging.FileHandler("floor_plan_api.log")
|
| 25 |
]
|
| 26 |
)
|
| 27 |
logger = logging.getLogger(__name__)
|
| 28 |
|
| 29 |
-
# Initialize API Key
|
| 30 |
GOOGLE_API_KEY = os.environ.get('GOOGLE_API_KEY')
|
| 31 |
if not GOOGLE_API_KEY:
|
| 32 |
logger.warning("GOOGLE_API_KEY environment variable not set!")
|
| 33 |
else:
|
| 34 |
genai.configure(api_key=GOOGLE_API_KEY)
|
| 35 |
|
| 36 |
-
# Create uploads directory
|
| 37 |
os.makedirs("uploads", exist_ok=True)
|
| 38 |
|
| 39 |
-
# Data models
|
| 40 |
class FloorPlanQuery(BaseModel):
|
| 41 |
-
"""
|
| 42 |
-
Query parameters for floor plan analysis
|
| 43 |
-
|
| 44 |
-
Attributes:
|
| 45 |
-
description (str, optional): Additional description of the floor plan
|
| 46 |
-
"""
|
| 47 |
description: Optional[str] = None
|
| 48 |
|
| 49 |
class RoomQuery(BaseModel):
|
| 50 |
-
"""
|
| 51 |
-
Query parameters for room search
|
| 52 |
-
|
| 53 |
-
Attributes:
|
| 54 |
-
room_name (str): Name or partial name of the room to find
|
| 55 |
-
exact_match (bool): Whether to match the name exactly or do partial matching
|
| 56 |
-
"""
|
| 57 |
room_name: str
|
| 58 |
exact_match: bool = False
|
| 59 |
|
|
@@ -66,20 +51,20 @@ class PDF:
|
|
| 66 |
self.error = None
|
| 67 |
self.images = []
|
| 68 |
self.page_count = 0
|
| 69 |
-
self.file_type = "pdf" if content_type == "application/pdf" else "image"
|
| 70 |
self.measurement_info = {
|
| 71 |
-
"scale": 100,
|
| 72 |
-
"ceiling_height": 2.4,
|
| 73 |
"room_dimensions": {}
|
| 74 |
}
|
| 75 |
-
self.analysis_result = None
|
| 76 |
|
| 77 |
def to_dict(self):
|
| 78 |
return {
|
| 79 |
"id": self.id,
|
| 80 |
"filename": self.filename,
|
| 81 |
"content_type": self.content_type,
|
| 82 |
-
"file_type": self.file_type,
|
| 83 |
"processed": self.processed,
|
| 84 |
"error": self.error,
|
| 85 |
"page_count": self.page_count if self.file_type == "pdf" else None,
|
|
@@ -89,12 +74,10 @@ class PDF:
|
|
| 89 |
"room_count": len(self.analysis_result) if self.analysis_result else 0
|
| 90 |
}
|
| 91 |
|
| 92 |
-
# Floor Plan Processor Class
|
| 93 |
class FloorPlanProcessor:
|
| 94 |
def __init__(self):
|
| 95 |
self.model = genai.GenerativeModel('gemini-2.5-pro')
|
| 96 |
-
self.pdfs = {}
|
| 97 |
-
# Define supported image formats
|
| 98 |
self.supported_image_formats = {
|
| 99 |
"image/jpeg": ".jpg",
|
| 100 |
"image/png": ".png",
|
|
@@ -105,23 +88,19 @@ class FloorPlanProcessor:
|
|
| 105 |
}
|
| 106 |
|
| 107 |
async def process_upload(self, file_content, filename, content_type):
|
| 108 |
-
"""Process uploaded content based on file type"""
|
| 109 |
pdf_id = re.sub(r'[^a-zA-Z0-9]', '_', filename)
|
| 110 |
logger.info(f"Processing file {filename} (ID: {pdf_id}, Type: {content_type})")
|
| 111 |
|
| 112 |
-
# Create PDF object (handles both PDFs and images)
|
| 113 |
pdf = PDF(filename, content_type)
|
| 114 |
self.pdfs[pdf_id] = pdf
|
| 115 |
|
| 116 |
try:
|
| 117 |
-
# Save file to disk for persistence
|
| 118 |
extension = ".pdf" if content_type == "application/pdf" else self.supported_image_formats.get(content_type, ".unknown")
|
| 119 |
file_path = f"uploads/{pdf_id}{extension}"
|
| 120 |
with open(file_path, "wb") as f:
|
| 121 |
f.write(file_content)
|
| 122 |
logger.info(f"Saved file to {file_path}")
|
| 123 |
|
| 124 |
-
# Process based on file type
|
| 125 |
if content_type == "application/pdf":
|
| 126 |
await self.extract_images_from_pdf(pdf, file_content)
|
| 127 |
elif content_type in self.supported_image_formats:
|
|
@@ -139,34 +118,23 @@ class FloorPlanProcessor:
|
|
| 139 |
return pdf_id
|
| 140 |
|
| 141 |
async def process_image(self, pdf, file_content):
|
| 142 |
-
"""Process an image file for floor plan analysis"""
|
| 143 |
try:
|
| 144 |
-
# Open image using PIL
|
| 145 |
img = Image.open(BytesIO(file_content))
|
| 146 |
logger.info(f"Processed image: {pdf.filename}, size: {img.width}x{img.height}")
|
| 147 |
-
|
| 148 |
-
# Add to images list
|
| 149 |
pdf.images.append(img)
|
| 150 |
-
|
| 151 |
-
# Extract measurement information (for now, use defaults)
|
| 152 |
-
# In a real implementation, you might want to try to extract this from image metadata
|
| 153 |
-
# or use AI to detect scale information from the image
|
| 154 |
pdf.measurement_info = {
|
| 155 |
-
"scale": 100,
|
| 156 |
-
"ceiling_height": 2.4,
|
| 157 |
"room_dimensions": {}
|
| 158 |
}
|
| 159 |
-
|
| 160 |
logger.info(f"Image {pdf.filename} processing completed")
|
| 161 |
return True
|
| 162 |
-
|
| 163 |
except Exception as e:
|
| 164 |
logger.error(f"Error processing image {pdf.filename}: {str(e)}", exc_info=True)
|
| 165 |
pdf.error = str(e)
|
| 166 |
return False
|
| 167 |
|
| 168 |
async def extract_images_from_pdf(self, pdf, file_content):
|
| 169 |
-
"""Extract images from PDF for floor plan analysis"""
|
| 170 |
try:
|
| 171 |
pdf_document = fitz.open(stream=file_content, filetype="pdf")
|
| 172 |
pdf.page_count = len(pdf_document)
|
|
@@ -178,39 +146,26 @@ class FloorPlanProcessor:
|
|
| 178 |
|
| 179 |
for page_num in range(len(pdf_document)):
|
| 180 |
page = pdf_document[page_num]
|
| 181 |
-
logger.debug(f"Processing page {page_num+1}")
|
| 182 |
-
|
| 183 |
-
# First try to get embedded images
|
| 184 |
image_list = page.get_images(full=True)
|
| 185 |
-
logger.debug(f"Found {len(image_list)} embedded images on page {page_num+1}")
|
| 186 |
|
| 187 |
-
# If no embedded images, render the page as an image
|
| 188 |
if not image_list:
|
| 189 |
-
logger.debug(f"No embedded images on page {page_num+1}, rendering as image")
|
| 190 |
pix = page.get_pixmap(matrix=fitz.Matrix(2, 2))
|
| 191 |
img_bytes = pix.tobytes("png")
|
| 192 |
img = Image.open(BytesIO(img_bytes))
|
| 193 |
images.append(img)
|
| 194 |
rendered_page_count += 1
|
| 195 |
else:
|
| 196 |
-
# Extract embedded images
|
| 197 |
for img_index, img_info in enumerate(image_list):
|
| 198 |
xref = img_info[0]
|
| 199 |
base_image = pdf_document.extract_image(xref)
|
| 200 |
image_bytes = base_image["image"]
|
| 201 |
img = Image.open(BytesIO(image_bytes))
|
| 202 |
|
| 203 |
-
# Filter out very small images (likely icons or decorations)
|
| 204 |
if img.width > 100 and img.height > 100:
|
| 205 |
-
logger.debug(f"Extracted image from page {page_num+1}, size: {img.width}x{img.height}")
|
| 206 |
images.append(img)
|
| 207 |
embedded_image_count += 1
|
| 208 |
-
else:
|
| 209 |
-
logger.debug(f"Skipping small image ({img.width}x{img.height}) on page {page_num+1}")
|
| 210 |
|
| 211 |
-
# If no images were found, render all pages as images
|
| 212 |
if not images:
|
| 213 |
-
logger.info(f"No usable images found in PDF, rendering all pages as images")
|
| 214 |
for page_num in range(len(pdf_document)):
|
| 215 |
page = pdf_document[page_num]
|
| 216 |
pix = page.get_pixmap(matrix=fitz.Matrix(2, 2))
|
|
@@ -222,15 +177,7 @@ class FloorPlanProcessor:
|
|
| 222 |
pdf.images = images
|
| 223 |
logger.info(f"Extracted {len(images)} images from PDF (embedded: {embedded_image_count}, rendered: {rendered_page_count})")
|
| 224 |
|
| 225 |
-
# Extract measurement information
|
| 226 |
-
logger.info(f"Extracting measurement information from PDF")
|
| 227 |
pdf.measurement_info = await self.extract_measurement_info(pdf_document)
|
| 228 |
-
logger.info(f"Extracted measurement info: scale 1:{pdf.measurement_info['scale']}, ceiling height: {pdf.measurement_info['ceiling_height']}m")
|
| 229 |
-
if pdf.measurement_info["room_dimensions"]:
|
| 230 |
-
logger.info(f"Found dimensions for {len(pdf.measurement_info['room_dimensions'])} rooms")
|
| 231 |
-
for room, dims in pdf.measurement_info["room_dimensions"].items():
|
| 232 |
-
logger.debug(f"Room '{room}': {dims['width']}m × {dims['length']}m")
|
| 233 |
-
|
| 234 |
return True
|
| 235 |
|
| 236 |
except Exception as e:
|
|
@@ -239,7 +186,6 @@ class FloorPlanProcessor:
|
|
| 239 |
return False
|
| 240 |
|
| 241 |
async def extract_measurement_info(self, pdf_document):
|
| 242 |
-
"""Extract measurement information like scale and dimensions from PDF"""
|
| 243 |
try:
|
| 244 |
measurement_info = {
|
| 245 |
"scale": None,
|
|
@@ -258,8 +204,6 @@ class FloorPlanProcessor:
|
|
| 258 |
r'(?i)ceiling\s*height\s*[=:]?\s*(\d+[\.,]?\d*)\s*m',
|
| 259 |
r'(?i)takhøyde\s*[=:]?\s*(\d+[\.,]?\d*)\s*m',
|
| 260 |
r'(?i)høyde\s*[=:]?\s*(\d+[\.,]?\d*)\s*m',
|
| 261 |
-
r'(?i)romhøyde\s*[=:]?\s*(\d+[\.,]?\d*)\s*m',
|
| 262 |
-
r'(?i)h\s*[=:]?\s*(\d+[\.,]?\d*)\s*m'
|
| 263 |
]
|
| 264 |
|
| 265 |
room_dim_patterns = [
|
|
@@ -271,7 +215,6 @@ class FloorPlanProcessor:
|
|
| 271 |
page = pdf_document[page_num]
|
| 272 |
text = page.get_text()
|
| 273 |
|
| 274 |
-
# Look for scale information
|
| 275 |
if not measurement_info["scale"]:
|
| 276 |
for pattern in scale_patterns:
|
| 277 |
matches = re.findall(pattern, text)
|
|
@@ -279,7 +222,6 @@ class FloorPlanProcessor:
|
|
| 279 |
measurement_info["scale"] = int(matches[0])
|
| 280 |
break
|
| 281 |
|
| 282 |
-
# Look for ceiling height
|
| 283 |
if not measurement_info["ceiling_height"]:
|
| 284 |
for pattern in height_patterns:
|
| 285 |
matches = re.findall(pattern, text)
|
|
@@ -288,7 +230,6 @@ class FloorPlanProcessor:
|
|
| 288 |
measurement_info["ceiling_height"] = float(height)
|
| 289 |
break
|
| 290 |
|
| 291 |
-
# Look for room dimensions
|
| 292 |
for pattern in room_dim_patterns:
|
| 293 |
matches = re.findall(pattern, text)
|
| 294 |
for match in matches:
|
|
@@ -300,25 +241,17 @@ class FloorPlanProcessor:
|
|
| 300 |
"length": length
|
| 301 |
}
|
| 302 |
|
| 303 |
-
# Default values if not found
|
| 304 |
if not measurement_info["scale"]:
|
| 305 |
-
measurement_info["scale"] = 100
|
| 306 |
-
|
| 307 |
if not measurement_info["ceiling_height"]:
|
| 308 |
-
measurement_info["ceiling_height"] = 2.4
|
| 309 |
|
| 310 |
return measurement_info
|
| 311 |
-
|
| 312 |
except Exception as e:
|
| 313 |
logger.error(f"Error extracting measurement info: {e}")
|
| 314 |
-
return {
|
| 315 |
-
"scale": 100,
|
| 316 |
-
"ceiling_height": 2.4,
|
| 317 |
-
"room_dimensions": {}
|
| 318 |
-
}
|
| 319 |
|
| 320 |
async def analyze_floor_plan(self, pdf_id, description=None):
|
| 321 |
-
"""Analyze floor plan PDF and generate structured room data"""
|
| 322 |
pdf = self.pdfs.get(pdf_id)
|
| 323 |
if not pdf:
|
| 324 |
raise ValueError(f"PDF with ID {pdf_id} not found")
|
|
@@ -326,184 +259,291 @@ class FloorPlanProcessor:
|
|
| 326 |
if not pdf.images:
|
| 327 |
raise ValueError(f"No images found in PDF {pdf_id}")
|
| 328 |
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
|
|
|
| 343 |
try:
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
|
|
|
| 357 |
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
fixed_text = response_text.replace("'", '"')
|
| 368 |
-
# Fix missing quotes around property names
|
| 369 |
-
fixed_text = re.sub(r'(\s*)(\w+)(\s*):', r'\1"\2"\3:', fixed_text)
|
| 370 |
-
# Try to extract JSON again
|
| 371 |
-
match = re.search(r'\[.*\]', fixed_text, re.DOTALL)
|
| 372 |
-
if match:
|
| 373 |
-
json_str = match.group(0)
|
| 374 |
-
parsed_json = json.loads(json_str)
|
| 375 |
-
return self.validate_and_fix_measurements(parsed_json, pdf.measurement_info)
|
| 376 |
-
except (json.JSONDecodeError, AttributeError):
|
| 377 |
-
pass
|
| 378 |
-
|
| 379 |
-
# If we've reached here, no valid JSON was found
|
| 380 |
-
# As a last resort, try to generate a basic room structure
|
| 381 |
-
logger.warning(f"Could not extract valid JSON from model response for PDF {pdf_id}. Attempting to generate fallback data.")
|
| 382 |
-
|
| 383 |
-
# Create a default room structure if we have measurement info
|
| 384 |
-
if pdf.measurement_info:
|
| 385 |
-
fallback_room = {
|
| 386 |
-
"name": "Main Room",
|
| 387 |
-
"name_no": "Hovedrom",
|
| 388 |
-
"area_m2": 25.0,
|
| 389 |
-
"position": "center",
|
| 390 |
-
"dimensions_m": {
|
| 391 |
-
"width": 5.0,
|
| 392 |
-
"length": 5.0
|
| 393 |
-
},
|
| 394 |
-
"windows": 2,
|
| 395 |
-
"window_positions": ["south wall", "east wall"],
|
| 396 |
-
"doors": 1,
|
| 397 |
-
"door_positions": ["north wall"],
|
| 398 |
-
"connected_rooms": [],
|
| 399 |
-
"has_external_access": True,
|
| 400 |
-
"ceiling_height_m": pdf.measurement_info.get("ceiling_height", 2.4),
|
| 401 |
-
"furniture": [],
|
| 402 |
-
"estimated": True
|
| 403 |
-
}
|
| 404 |
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 408 |
|
| 409 |
-
|
| 410 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 411 |
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 419 |
|
| 420 |
def create_prompt(self, floor_plan_description=None, measurement_info=None, file_type="pdf"):
|
| 421 |
-
"""Create the prompt for Gemini - with Norwegian context and measurement instructions"""
|
| 422 |
-
# Add measurement information to the prompt if available
|
| 423 |
measurement_context = ""
|
| 424 |
if measurement_info:
|
| 425 |
measurement_context = f"""
|
| 426 |
-
**
|
| 427 |
-
*
|
| 428 |
-
*
|
| 429 |
"""
|
| 430 |
if measurement_info["room_dimensions"]:
|
| 431 |
-
measurement_context += "* Known
|
| 432 |
for room, dims in measurement_info["room_dimensions"].items():
|
| 433 |
-
measurement_context += f" - {room}: {dims['width']} × {dims['length']}
|
| 434 |
-
|
| 435 |
-
# Add file type specific context
|
| 436 |
-
file_type_context = ""
|
| 437 |
-
if file_type == "image":
|
| 438 |
-
file_type_context = """
|
| 439 |
-
**Note:** This floor plan was provided as an image file, not a PDF. The system may not have been able to extract text-based measurement information. Please pay extra attention to visual cues like scale bars, dimensions, and room labels that might be present in the image.
|
| 440 |
-
"""
|
| 441 |
|
| 442 |
-
prompt = f"""You are an expert architectural assistant
|
| 443 |
{measurement_context}
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
Please return the following **JSON structure**, including estimates and spatial relationships:
|
| 447 |
[
|
| 448 |
{{
|
| 449 |
"name": "Room name",
|
| 450 |
-
"name_no": "Norwegian
|
| 451 |
"area_m2": 0.0,
|
| 452 |
-
"position": "
|
| 453 |
-
"dimensions_m": {{
|
| 454 |
-
"width": 0.0,
|
| 455 |
-
"length": 0.0
|
| 456 |
-
}},
|
| 457 |
"windows": 0,
|
| 458 |
-
"window_positions": ["
|
| 459 |
"doors": 0,
|
| 460 |
-
"door_positions": ["
|
| 461 |
-
"connected_rooms": ["Room
|
| 462 |
-
"has_external_access":
|
| 463 |
"ceiling_height_m": 2.4,
|
| 464 |
-
"furniture": [
|
| 465 |
"estimated": false
|
| 466 |
}}
|
| 467 |
]
|
| 468 |
|
| 469 |
-
|
| 470 |
-
* Include
|
| 471 |
-
*
|
| 472 |
-
*
|
| 473 |
-
*
|
| 474 |
-
* Try to determine the **direction/position** of each room (e.g., "northwest corner", "center").
|
| 475 |
-
* Count and identify **doors and windows**, and specify on which **wall** they are located.
|
| 476 |
-
* Include `"has_external_access": true` if a room connects directly outside (e.g., terrace, garage, entrance).
|
| 477 |
-
* Optionally include `"furniture"` if visible or labeled in the plan.
|
| 478 |
-
* Use the ceiling height of {measurement_info["ceiling_height"] if measurement_info else 2.4}m if not otherwise specified.
|
| 479 |
-
* **VERY IMPORTANT: Only return the JSON array. Do not add explanations, preambles, or any text before or after the JSON array. Do not include markdown code blocks.**
|
| 480 |
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
* Kjøkken = Kitchen
|
| 484 |
-
* Soverom = Bedroom
|
| 485 |
-
* Bad = Bathroom
|
| 486 |
-
* Toalett = Toilet
|
| 487 |
-
* Gang = Hallway
|
| 488 |
-
* Entré = Entrance
|
| 489 |
-
* Garderobe = Wardrobe
|
| 490 |
-
* Balkong = Balcony
|
| 491 |
-
* Terrasse = Terrace
|
| 492 |
-
* Kontor = Office
|
| 493 |
-
* Vaskerom = Laundry room
|
| 494 |
-
* Bod = Storage room
|
| 495 |
-
* Garasje = Garage
|
| 496 |
-
* Trapp = Stairs
|
| 497 |
-
* Spisestue = Dining room
|
| 498 |
-
"""
|
| 499 |
|
| 500 |
if floor_plan_description:
|
| 501 |
-
prompt += f"\n\
|
| 502 |
|
| 503 |
return prompt
|
| 504 |
|
| 505 |
def validate_and_fix_measurements(self, json_data, measurement_info=None):
|
| 506 |
-
"""Validate and fix measurement values in the JSON results"""
|
| 507 |
try:
|
| 508 |
if isinstance(json_data, str):
|
| 509 |
data = json.loads(json_data)
|
|
@@ -513,46 +553,36 @@ Please return the following **JSON structure**, including estimates and spatial
|
|
| 513 |
if not isinstance(data, list):
|
| 514 |
return json_data
|
| 515 |
|
| 516 |
-
|
| 517 |
|
| 518 |
for room in data:
|
| 519 |
-
# Fix ceiling height
|
| 520 |
if room.get("ceiling_height_m") is None or room.get("ceiling_height_m") <= 0:
|
| 521 |
-
room["ceiling_height_m"] =
|
| 522 |
room["estimated"] = True
|
| 523 |
|
| 524 |
-
# Check dimensions and area
|
| 525 |
if "dimensions_m" in room:
|
| 526 |
width = room["dimensions_m"].get("width", 0)
|
| 527 |
length = room["dimensions_m"].get("length", 0)
|
| 528 |
|
| 529 |
-
# If we have dimensions but they're invalid, try to fix them
|
| 530 |
if width <= 0 or length <= 0:
|
| 531 |
-
# Check if we have area to calculate dimensions
|
| 532 |
if room.get("area_m2", 0) > 0:
|
| 533 |
-
# Approximate dimensions using a square root (assuming square-ish room)
|
| 534 |
side = math.sqrt(room["area_m2"])
|
| 535 |
room["dimensions_m"]["width"] = round(side, 1)
|
| 536 |
room["dimensions_m"]["length"] = round(side, 1)
|
| 537 |
room["estimated"] = True
|
| 538 |
else:
|
| 539 |
-
# Set reasonable defaults
|
| 540 |
room["dimensions_m"]["width"] = 3.0
|
| 541 |
room["dimensions_m"]["length"] = 3.0
|
| 542 |
room["area_m2"] = 9.0
|
| 543 |
room["estimated"] = True
|
| 544 |
else:
|
| 545 |
-
# Recalculate area based on dimensions
|
| 546 |
calculated_area = width * length
|
| 547 |
current_area = room.get("area_m2", 0)
|
| 548 |
|
| 549 |
-
# If area is missing or significantly different, update it
|
| 550 |
if current_area <= 0 or abs(current_area - calculated_area) > 0.5:
|
| 551 |
room["area_m2"] = round(calculated_area, 1)
|
| 552 |
|
| 553 |
-
# If we have area but no dimensions, calculate them
|
| 554 |
elif "area_m2" in room and room["area_m2"] > 0:
|
| 555 |
-
# Approximate dimensions using a square root (assuming square-ish room)
|
| 556 |
side = math.sqrt(room["area_m2"])
|
| 557 |
room["dimensions_m"] = {
|
| 558 |
"width": round(side, 1),
|
|
@@ -560,12 +590,10 @@ Please return the following **JSON structure**, including estimates and spatial
|
|
| 560 |
}
|
| 561 |
room["estimated"] = True
|
| 562 |
|
| 563 |
-
# Check if we have room dimensions in our measurement info
|
| 564 |
if measurement_info and "room_dimensions" in measurement_info:
|
| 565 |
room_name_lower = room.get("name", "").lower()
|
| 566 |
room_name_no_lower = room.get("name_no", "").lower()
|
| 567 |
|
| 568 |
-
# Check both English and Norwegian names
|
| 569 |
for name in [room_name_lower, room_name_no_lower]:
|
| 570 |
if name in measurement_info["room_dimensions"]:
|
| 571 |
known_dims = measurement_info["room_dimensions"][name]
|
|
@@ -580,26 +608,17 @@ Please return the following **JSON structure**, including estimates and spatial
|
|
| 580 |
return data
|
| 581 |
|
| 582 |
except Exception as e:
|
| 583 |
-
logger.error(f"Error validating
|
| 584 |
return json_data
|
| 585 |
|
| 586 |
-
# Initialize FastAPI
|
| 587 |
-
# Initialize FastAPI with Swagger UI configuration
|
| 588 |
app = FastAPI(
|
| 589 |
-
title="Floor Plan
|
| 590 |
-
description="
|
| 591 |
-
version="1.0.
|
| 592 |
docs_url="/",
|
| 593 |
-
redoc_url="/redoc"
|
| 594 |
-
openapi_url="/openapi.json",
|
| 595 |
-
openapi_tags=[
|
| 596 |
-
{"name": "status", "description": "API status endpoints"},
|
| 597 |
-
{"name": "pdfs", "description": "PDF management endpoints"}, # Keep original tags
|
| 598 |
-
{"name": "analysis", "description": "Floor plan analysis endpoints"},
|
| 599 |
-
]
|
| 600 |
)
|
| 601 |
|
| 602 |
-
# Add CORS middleware
|
| 603 |
app.add_middleware(
|
| 604 |
CORSMiddleware,
|
| 605 |
allow_origins=["*"],
|
|
@@ -608,239 +627,137 @@ app.add_middleware(
|
|
| 608 |
allow_headers=["*"]
|
| 609 |
)
|
| 610 |
|
| 611 |
-
# Initialize processor
|
| 612 |
processor = FloorPlanProcessor()
|
| 613 |
|
| 614 |
-
|
| 615 |
-
@app.get("/status", tags=["status"])
|
| 616 |
async def get_status():
|
| 617 |
-
"""
|
| 618 |
-
Get the current status of the API and count of processed PDFs
|
| 619 |
-
|
| 620 |
-
Returns:
|
| 621 |
-
dict: Status information including running state and PDF count
|
| 622 |
-
"""
|
| 623 |
return {
|
| 624 |
"status": "running",
|
| 625 |
-
"pdfs_count": len(processor.pdfs)
|
|
|
|
|
|
|
| 626 |
}
|
| 627 |
|
| 628 |
-
@app.get("/pdfs"
|
| 629 |
async def get_pdfs():
|
| 630 |
-
""
|
| 631 |
-
List all uploaded PDFs and their metadata
|
| 632 |
-
|
| 633 |
-
Returns:
|
| 634 |
-
dict: List of all PDFs with their metadata
|
| 635 |
-
"""
|
| 636 |
-
return {
|
| 637 |
-
"pdfs": [pdf.to_dict() for pdf in processor.pdfs.values()]
|
| 638 |
-
}
|
| 639 |
|
| 640 |
-
@app.get("/pdf/{pdf_id}"
|
| 641 |
async def get_pdf(pdf_id: str):
|
| 642 |
-
"""
|
| 643 |
-
Get information about a specific PDF by ID
|
| 644 |
-
|
| 645 |
-
Args:
|
| 646 |
-
pdf_id (str): The ID of the PDF to retrieve
|
| 647 |
-
|
| 648 |
-
Returns:
|
| 649 |
-
dict: PDF metadata including processing status and measurement information
|
| 650 |
-
|
| 651 |
-
Raises:
|
| 652 |
-
HTTPException: 404 if PDF not found
|
| 653 |
-
"""
|
| 654 |
if pdf_id not in processor.pdfs:
|
| 655 |
raise HTTPException(status_code=404, detail="PDF not found")
|
| 656 |
-
|
| 657 |
return processor.pdfs[pdf_id].to_dict()
|
| 658 |
|
| 659 |
-
@app.post("/upload"
|
| 660 |
async def upload_pdf(file: UploadFile = File(...)):
|
| 661 |
-
"""
|
| 662 |
-
Upload a floor plan (PDF or image) for processing
|
| 663 |
-
|
| 664 |
-
The file will be processed to extract images and measurement information.
|
| 665 |
-
The system will detect scales, dimensions, and prepare the floor plan for analysis.
|
| 666 |
-
Supports PDF files and common image formats (JPG, PNG, GIF, BMP, TIFF, WebP).
|
| 667 |
-
|
| 668 |
-
Args:
|
| 669 |
-
file (UploadFile): The file to upload (PDF, JPG, PNG, etc.)
|
| 670 |
-
|
| 671 |
-
Returns:
|
| 672 |
-
dict: Upload confirmation with PDF ID and basic information
|
| 673 |
-
|
| 674 |
-
Raises:
|
| 675 |
-
HTTPException: 400 if file type is not supported
|
| 676 |
-
"""
|
| 677 |
-
# Validate file content type
|
| 678 |
content_type = file.content_type.lower()
|
| 679 |
-
|
| 680 |
|
| 681 |
-
if content_type not in
|
| 682 |
-
logger.warning(f"Rejected unsupported file type: {content_type} for file {file.filename}")
|
| 683 |
return JSONResponse(
|
| 684 |
status_code=400,
|
| 685 |
-
content={
|
| 686 |
-
"error": "Unsupported file type",
|
| 687 |
-
"supported_types": ", ".join(supported_types)
|
| 688 |
-
}
|
| 689 |
)
|
| 690 |
|
| 691 |
-
logger.info(f"
|
| 692 |
|
| 693 |
try:
|
| 694 |
-
# Read file content
|
| 695 |
file_content = await file.read()
|
| 696 |
-
file_size = len(file_content)
|
| 697 |
-
logger.info(f"Read file content, size: {file_size} bytes")
|
| 698 |
-
|
| 699 |
-
# Process file
|
| 700 |
pdf_id = await processor.process_upload(file_content, file.filename, content_type)
|
| 701 |
pdf_info = processor.pdfs[pdf_id].to_dict()
|
| 702 |
|
| 703 |
-
logger.info(f"File processed successfully, assigned ID: {pdf_id}")
|
| 704 |
-
logger.info(f"PDF info: {json.dumps(pdf_info)}")
|
| 705 |
-
|
| 706 |
return {
|
| 707 |
-
"message": "
|
| 708 |
"pdf_id": pdf_id,
|
| 709 |
"pdf_info": pdf_info
|
| 710 |
}
|
| 711 |
except Exception as e:
|
| 712 |
-
logger.error(f"
|
| 713 |
-
return JSONResponse(
|
| 714 |
-
status_code=500,
|
| 715 |
-
content={"error": f"Error processing upload: {str(e)}"}
|
| 716 |
-
)
|
| 717 |
|
| 718 |
-
@app.post("/analyze/{pdf_id}"
|
| 719 |
async def analyze_pdf(pdf_id: str, query: FloorPlanQuery = None):
|
| 720 |
-
"""
|
| 721 |
-
Analyze a floor plan PDF and extract room information
|
| 722 |
-
|
| 723 |
-
This endpoint analyzes a previously uploaded floor plan PDF and extracts
|
| 724 |
-
detailed room-level information using AI. The analysis includes room dimensions,
|
| 725 |
-
positions, doors, windows, and connections between rooms.
|
| 726 |
-
|
| 727 |
-
Args:
|
| 728 |
-
pdf_id (str): The ID of the PDF to analyze
|
| 729 |
-
query (FloorPlanQuery, optional): Additional information about the floor plan
|
| 730 |
-
|
| 731 |
-
Returns:
|
| 732 |
-
dict: Analysis results including measurement information and room data
|
| 733 |
-
|
| 734 |
-
Raises:
|
| 735 |
-
HTTPException: 404 if PDF not found
|
| 736 |
-
HTTPException: 400 if PDF is still processing or doesn't contain images
|
| 737 |
-
HTTPException: 500 if analysis fails
|
| 738 |
-
"""
|
| 739 |
if pdf_id not in processor.pdfs:
|
| 740 |
raise HTTPException(status_code=404, detail="PDF not found")
|
| 741 |
|
| 742 |
pdf = processor.pdfs[pdf_id]
|
| 743 |
|
| 744 |
-
# Check if PDF is processed
|
| 745 |
if not pdf.processed:
|
| 746 |
-
return JSONResponse(
|
| 747 |
-
status_code=400,
|
| 748 |
-
content={"error": "PDF is still being processed"}
|
| 749 |
-
)
|
| 750 |
|
| 751 |
-
# Check if PDF has images for floor plan analysis
|
| 752 |
if not pdf.images:
|
| 753 |
-
return JSONResponse(
|
| 754 |
-
status_code=400,
|
| 755 |
-
content={"error": "This PDF doesn't contain images suitable for floor plan analysis"}
|
| 756 |
-
)
|
| 757 |
|
| 758 |
try:
|
| 759 |
description = query.description if query else None
|
| 760 |
-
|
| 761 |
|
| 762 |
-
# If the API call takes too long, it might time out for the client
|
| 763 |
-
# Use a shorter timeout for model response
|
| 764 |
result = await asyncio.wait_for(
|
| 765 |
processor.analyze_floor_plan(pdf_id, description),
|
| 766 |
-
timeout=
|
| 767 |
)
|
| 768 |
|
| 769 |
-
|
| 770 |
pdf.analysis_result = result
|
| 771 |
|
| 772 |
-
|
|
|
|
|
|
|
|
|
|
| 773 |
|
| 774 |
return {
|
| 775 |
-
"message": "
|
| 776 |
"pdf_id": pdf_id,
|
| 777 |
"measurement_info": pdf.measurement_info,
|
| 778 |
-
"rooms": result
|
|
|
|
|
|
|
|
|
|
| 779 |
}
|
|
|
|
| 780 |
except asyncio.TimeoutError:
|
| 781 |
-
|
| 782 |
-
|
| 783 |
-
status_code=504, # Gateway Timeout
|
| 784 |
-
content={"error": "Analysis timed out. The process took too long to complete."}
|
| 785 |
-
)
|
| 786 |
-
except Exception as e:
|
| 787 |
-
logger.error(f"Error analyzing floor plan {pdf_id}: {str(e)}")
|
| 788 |
|
| 789 |
-
|
| 790 |
-
|
| 791 |
-
"
|
| 792 |
-
"
|
| 793 |
-
"
|
|
|
|
| 794 |
}
|
| 795 |
|
| 796 |
-
|
| 797 |
-
|
| 798 |
-
for key, value in e.__dict__.items():
|
| 799 |
-
if isinstance(value, (str, int, float, bool, type(None))):
|
| 800 |
-
error_details[f"error_{key}"] = value
|
| 801 |
|
| 802 |
-
|
| 803 |
-
|
| 804 |
-
|
| 805 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 806 |
|
| 807 |
-
@app.post("/room/{pdf_id}"
|
| 808 |
async def find_room(pdf_id: str, query: RoomQuery):
|
| 809 |
-
"""
|
| 810 |
-
Find a specific room in a floor plan by name
|
| 811 |
-
|
| 812 |
-
This endpoint searches for a room by name in a previously analyzed floor plan.
|
| 813 |
-
It can perform exact matching or partial matching based on the query parameters.
|
| 814 |
-
|
| 815 |
-
Args:
|
| 816 |
-
pdf_id (str): The ID of the analyzed PDF to search
|
| 817 |
-
query (RoomQuery): Room search parameters
|
| 818 |
-
room_name (str): Name or partial name of the room to find
|
| 819 |
-
exact_match (bool): Whether to match the name exactly or do partial matching
|
| 820 |
-
|
| 821 |
-
Returns:
|
| 822 |
-
dict: Room information if found, or error message
|
| 823 |
-
|
| 824 |
-
Raises:
|
| 825 |
-
HTTPException: 404 if PDF not found or room not found
|
| 826 |
-
"""
|
| 827 |
if pdf_id not in processor.pdfs:
|
| 828 |
-
logger.error(f"PDF not found: {pdf_id}")
|
| 829 |
raise HTTPException(status_code=404, detail="PDF not found")
|
| 830 |
|
| 831 |
pdf = processor.pdfs[pdf_id]
|
| 832 |
|
| 833 |
-
# Check if the PDF has been analyzed
|
| 834 |
if not hasattr(pdf, "analysis_result") or not pdf.analysis_result:
|
| 835 |
-
logger.error(f"PDF {pdf_id} has not been analyzed yet")
|
| 836 |
raise HTTPException(
|
| 837 |
status_code=400,
|
| 838 |
-
content={"error": "PDF
|
| 839 |
)
|
| 840 |
|
| 841 |
-
logger.info(f"Searching for room '{query.room_name}' in PDF {pdf_id} (exact_match={query.exact_match})")
|
| 842 |
-
|
| 843 |
-
# Search for room by name (case insensitive)
|
| 844 |
found_rooms = []
|
| 845 |
room_name_lower = query.room_name.lower()
|
| 846 |
|
|
@@ -849,32 +766,25 @@ async def find_room(pdf_id: str, query: RoomQuery):
|
|
| 849 |
norwegian_name = room.get("name_no", "").lower()
|
| 850 |
|
| 851 |
if query.exact_match:
|
| 852 |
-
# Exact match (case insensitive)
|
| 853 |
if english_name == room_name_lower or norwegian_name == room_name_lower:
|
| 854 |
found_rooms.append(room)
|
| 855 |
else:
|
| 856 |
-
# Partial match (case insensitive)
|
| 857 |
if room_name_lower in english_name or room_name_lower in norwegian_name:
|
| 858 |
found_rooms.append(room)
|
| 859 |
|
| 860 |
if not found_rooms:
|
| 861 |
-
logger.warning(f"No rooms found matching '{query.room_name}' in PDF {pdf_id}")
|
| 862 |
raise HTTPException(
|
| 863 |
status_code=404,
|
| 864 |
content={"error": f"No rooms found matching '{query.room_name}'"}
|
| 865 |
)
|
| 866 |
|
| 867 |
-
# If only one room found, return it directly
|
| 868 |
if len(found_rooms) == 1:
|
| 869 |
-
logger.info(f"Found exactly one room matching '{query.room_name}': {found_rooms[0].get('name')}")
|
| 870 |
return {
|
| 871 |
"message": f"Room found: {found_rooms[0].get('name')}",
|
| 872 |
"pdf_id": pdf_id,
|
| 873 |
"room": found_rooms[0]
|
| 874 |
}
|
| 875 |
|
| 876 |
-
# Multiple rooms found
|
| 877 |
-
logger.info(f"Found {len(found_rooms)} rooms matching '{query.room_name}'")
|
| 878 |
room_names = [f"{room.get('name')} ({room.get('name_no', '')})" for room in found_rooms]
|
| 879 |
|
| 880 |
return {
|
|
@@ -884,11 +794,8 @@ async def find_room(pdf_id: str, query: RoomQuery):
|
|
| 884 |
"room_names": room_names
|
| 885 |
}
|
| 886 |
|
| 887 |
-
# Create necessary directories and startup logic
|
| 888 |
@app.on_event("startup")
|
| 889 |
async def startup_event():
|
| 890 |
-
"""Initialize necessary directories and settings on startup"""
|
| 891 |
-
# Create necessary directories
|
| 892 |
for directory in ["uploads", "logs"]:
|
| 893 |
try:
|
| 894 |
os.makedirs(directory, exist_ok=True)
|
|
@@ -896,26 +803,25 @@ async def startup_event():
|
|
| 896 |
except Exception as e:
|
| 897 |
logger.error(f"Failed to create directory {directory}: {str(e)}")
|
| 898 |
|
| 899 |
-
# Check API key configuration
|
| 900 |
if GOOGLE_API_KEY:
|
| 901 |
-
logger.info("GOOGLE_API_KEY
|
| 902 |
else:
|
| 903 |
-
logger.warning("GOOGLE_API_KEY
|
| 904 |
-
|
| 905 |
-
|
| 906 |
-
logger.info("
|
| 907 |
-
logger.info(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 908 |
logger.info(f"Documentation: http://localhost:7860/")
|
| 909 |
-
logger.info(
|
| 910 |
-
logger.info(f"Upload: http://localhost:7860/upload")
|
| 911 |
-
logger.info("==============================\n")
|
| 912 |
|
| 913 |
@app.on_event("shutdown")
|
| 914 |
async def shutdown_event():
|
| 915 |
-
"""Log when the application is shutting down"""
|
| 916 |
logger.info("Application shutting down")
|
| 917 |
|
| 918 |
-
# Start the application if this file is run directly
|
| 919 |
if __name__ == "__main__":
|
| 920 |
-
logger.info("Starting Floor Plan Analysis API
|
| 921 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 11 |
import re
|
| 12 |
from io import BytesIO
|
| 13 |
import math
|
| 14 |
+
import time
|
| 15 |
import fitz # PyMuPDF
|
| 16 |
from PIL import Image
|
| 17 |
import google.generativeai as genai
|
| 18 |
+
|
| 19 |
+
# version = 0.0.5 - High Accuracy Mode for Paid Plans
|
| 20 |
logging.basicConfig(
|
| 21 |
level=logging.INFO,
|
| 22 |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
| 23 |
handlers=[
|
| 24 |
+
logging.StreamHandler(),
|
| 25 |
+
logging.FileHandler("floor_plan_api.log")
|
| 26 |
]
|
| 27 |
)
|
| 28 |
logger = logging.getLogger(__name__)
|
| 29 |
|
|
|
|
| 30 |
GOOGLE_API_KEY = os.environ.get('GOOGLE_API_KEY')
|
| 31 |
if not GOOGLE_API_KEY:
|
| 32 |
logger.warning("GOOGLE_API_KEY environment variable not set!")
|
| 33 |
else:
|
| 34 |
genai.configure(api_key=GOOGLE_API_KEY)
|
| 35 |
|
|
|
|
| 36 |
os.makedirs("uploads", exist_ok=True)
|
| 37 |
|
|
|
|
| 38 |
class FloorPlanQuery(BaseModel):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
description: Optional[str] = None
|
| 40 |
|
| 41 |
class RoomQuery(BaseModel):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
room_name: str
|
| 43 |
exact_match: bool = False
|
| 44 |
|
|
|
|
| 51 |
self.error = None
|
| 52 |
self.images = []
|
| 53 |
self.page_count = 0
|
| 54 |
+
self.file_type = "pdf" if content_type == "application/pdf" else "image"
|
| 55 |
self.measurement_info = {
|
| 56 |
+
"scale": 100,
|
| 57 |
+
"ceiling_height": 2.4,
|
| 58 |
"room_dimensions": {}
|
| 59 |
}
|
| 60 |
+
self.analysis_result = None
|
| 61 |
|
| 62 |
def to_dict(self):
|
| 63 |
return {
|
| 64 |
"id": self.id,
|
| 65 |
"filename": self.filename,
|
| 66 |
"content_type": self.content_type,
|
| 67 |
+
"file_type": self.file_type,
|
| 68 |
"processed": self.processed,
|
| 69 |
"error": self.error,
|
| 70 |
"page_count": self.page_count if self.file_type == "pdf" else None,
|
|
|
|
| 74 |
"room_count": len(self.analysis_result) if self.analysis_result else 0
|
| 75 |
}
|
| 76 |
|
|
|
|
| 77 |
class FloorPlanProcessor:
|
| 78 |
def __init__(self):
|
| 79 |
self.model = genai.GenerativeModel('gemini-2.5-pro')
|
| 80 |
+
self.pdfs = {}
|
|
|
|
| 81 |
self.supported_image_formats = {
|
| 82 |
"image/jpeg": ".jpg",
|
| 83 |
"image/png": ".png",
|
|
|
|
| 88 |
}
|
| 89 |
|
| 90 |
async def process_upload(self, file_content, filename, content_type):
|
|
|
|
| 91 |
pdf_id = re.sub(r'[^a-zA-Z0-9]', '_', filename)
|
| 92 |
logger.info(f"Processing file {filename} (ID: {pdf_id}, Type: {content_type})")
|
| 93 |
|
|
|
|
| 94 |
pdf = PDF(filename, content_type)
|
| 95 |
self.pdfs[pdf_id] = pdf
|
| 96 |
|
| 97 |
try:
|
|
|
|
| 98 |
extension = ".pdf" if content_type == "application/pdf" else self.supported_image_formats.get(content_type, ".unknown")
|
| 99 |
file_path = f"uploads/{pdf_id}{extension}"
|
| 100 |
with open(file_path, "wb") as f:
|
| 101 |
f.write(file_content)
|
| 102 |
logger.info(f"Saved file to {file_path}")
|
| 103 |
|
|
|
|
| 104 |
if content_type == "application/pdf":
|
| 105 |
await self.extract_images_from_pdf(pdf, file_content)
|
| 106 |
elif content_type in self.supported_image_formats:
|
|
|
|
| 118 |
return pdf_id
|
| 119 |
|
| 120 |
async def process_image(self, pdf, file_content):
|
|
|
|
| 121 |
try:
|
|
|
|
| 122 |
img = Image.open(BytesIO(file_content))
|
| 123 |
logger.info(f"Processed image: {pdf.filename}, size: {img.width}x{img.height}")
|
|
|
|
|
|
|
| 124 |
pdf.images.append(img)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
pdf.measurement_info = {
|
| 126 |
+
"scale": 100,
|
| 127 |
+
"ceiling_height": 2.4,
|
| 128 |
"room_dimensions": {}
|
| 129 |
}
|
|
|
|
| 130 |
logger.info(f"Image {pdf.filename} processing completed")
|
| 131 |
return True
|
|
|
|
| 132 |
except Exception as e:
|
| 133 |
logger.error(f"Error processing image {pdf.filename}: {str(e)}", exc_info=True)
|
| 134 |
pdf.error = str(e)
|
| 135 |
return False
|
| 136 |
|
| 137 |
async def extract_images_from_pdf(self, pdf, file_content):
|
|
|
|
| 138 |
try:
|
| 139 |
pdf_document = fitz.open(stream=file_content, filetype="pdf")
|
| 140 |
pdf.page_count = len(pdf_document)
|
|
|
|
| 146 |
|
| 147 |
for page_num in range(len(pdf_document)):
|
| 148 |
page = pdf_document[page_num]
|
|
|
|
|
|
|
|
|
|
| 149 |
image_list = page.get_images(full=True)
|
|
|
|
| 150 |
|
|
|
|
| 151 |
if not image_list:
|
|
|
|
| 152 |
pix = page.get_pixmap(matrix=fitz.Matrix(2, 2))
|
| 153 |
img_bytes = pix.tobytes("png")
|
| 154 |
img = Image.open(BytesIO(img_bytes))
|
| 155 |
images.append(img)
|
| 156 |
rendered_page_count += 1
|
| 157 |
else:
|
|
|
|
| 158 |
for img_index, img_info in enumerate(image_list):
|
| 159 |
xref = img_info[0]
|
| 160 |
base_image = pdf_document.extract_image(xref)
|
| 161 |
image_bytes = base_image["image"]
|
| 162 |
img = Image.open(BytesIO(image_bytes))
|
| 163 |
|
|
|
|
| 164 |
if img.width > 100 and img.height > 100:
|
|
|
|
| 165 |
images.append(img)
|
| 166 |
embedded_image_count += 1
|
|
|
|
|
|
|
| 167 |
|
|
|
|
| 168 |
if not images:
|
|
|
|
| 169 |
for page_num in range(len(pdf_document)):
|
| 170 |
page = pdf_document[page_num]
|
| 171 |
pix = page.get_pixmap(matrix=fitz.Matrix(2, 2))
|
|
|
|
| 177 |
pdf.images = images
|
| 178 |
logger.info(f"Extracted {len(images)} images from PDF (embedded: {embedded_image_count}, rendered: {rendered_page_count})")
|
| 179 |
|
|
|
|
|
|
|
| 180 |
pdf.measurement_info = await self.extract_measurement_info(pdf_document)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
return True
|
| 182 |
|
| 183 |
except Exception as e:
|
|
|
|
| 186 |
return False
|
| 187 |
|
| 188 |
async def extract_measurement_info(self, pdf_document):
|
|
|
|
| 189 |
try:
|
| 190 |
measurement_info = {
|
| 191 |
"scale": None,
|
|
|
|
| 204 |
r'(?i)ceiling\s*height\s*[=:]?\s*(\d+[\.,]?\d*)\s*m',
|
| 205 |
r'(?i)takhøyde\s*[=:]?\s*(\d+[\.,]?\d*)\s*m',
|
| 206 |
r'(?i)høyde\s*[=:]?\s*(\d+[\.,]?\d*)\s*m',
|
|
|
|
|
|
|
| 207 |
]
|
| 208 |
|
| 209 |
room_dim_patterns = [
|
|
|
|
| 215 |
page = pdf_document[page_num]
|
| 216 |
text = page.get_text()
|
| 217 |
|
|
|
|
| 218 |
if not measurement_info["scale"]:
|
| 219 |
for pattern in scale_patterns:
|
| 220 |
matches = re.findall(pattern, text)
|
|
|
|
| 222 |
measurement_info["scale"] = int(matches[0])
|
| 223 |
break
|
| 224 |
|
|
|
|
| 225 |
if not measurement_info["ceiling_height"]:
|
| 226 |
for pattern in height_patterns:
|
| 227 |
matches = re.findall(pattern, text)
|
|
|
|
| 230 |
measurement_info["ceiling_height"] = float(height)
|
| 231 |
break
|
| 232 |
|
|
|
|
| 233 |
for pattern in room_dim_patterns:
|
| 234 |
matches = re.findall(pattern, text)
|
| 235 |
for match in matches:
|
|
|
|
| 241 |
"length": length
|
| 242 |
}
|
| 243 |
|
|
|
|
| 244 |
if not measurement_info["scale"]:
|
| 245 |
+
measurement_info["scale"] = 100
|
|
|
|
| 246 |
if not measurement_info["ceiling_height"]:
|
| 247 |
+
measurement_info["ceiling_height"] = 2.4
|
| 248 |
|
| 249 |
return measurement_info
|
|
|
|
| 250 |
except Exception as e:
|
| 251 |
logger.error(f"Error extracting measurement info: {e}")
|
| 252 |
+
return {"scale": 100, "ceiling_height": 2.4, "room_dimensions": {}}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
|
| 254 |
async def analyze_floor_plan(self, pdf_id, description=None):
|
|
|
|
| 255 |
pdf = self.pdfs.get(pdf_id)
|
| 256 |
if not pdf:
|
| 257 |
raise ValueError(f"PDF with ID {pdf_id} not found")
|
|
|
|
| 259 |
if not pdf.images:
|
| 260 |
raise ValueError(f"No images found in PDF {pdf_id}")
|
| 261 |
|
| 262 |
+
logger.info(f"\n{'='*70}")
|
| 263 |
+
logger.info(f"HIGH ACCURACY Analysis: {pdf_id}")
|
| 264 |
+
logger.info(f"Total images: {len(pdf.images)}")
|
| 265 |
+
logger.info(f"Using: gemini-2.5-pro (Maximum Quality)")
|
| 266 |
+
logger.info(f"{'='*70}\n")
|
| 267 |
+
|
| 268 |
+
best_images = self._select_best_images(pdf.images, max_images=3)
|
| 269 |
+
high_quality_images = [self._prepare_high_quality_image(img) for img in best_images]
|
| 270 |
+
|
| 271 |
+
logger.info(f"Using {len(high_quality_images)} high-quality images")
|
| 272 |
+
for idx, img in enumerate(high_quality_images):
|
| 273 |
+
logger.info(f" Image {idx+1}: {img.size[0]}x{img.size[1]} pixels")
|
| 274 |
+
|
| 275 |
+
max_retries = 3
|
| 276 |
+
for attempt in range(max_retries):
|
| 277 |
try:
|
| 278 |
+
logger.info(f"\nAttempt {attempt + 1}/{max_retries}")
|
| 279 |
+
|
| 280 |
+
result = await self._analyze_with_max_quality(
|
| 281 |
+
high_quality_images,
|
| 282 |
+
pdf.measurement_info,
|
| 283 |
+
description,
|
| 284 |
+
pdf.file_type,
|
| 285 |
+
timeout=600,
|
| 286 |
+
attempt=attempt
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
if result and len(result) > 0:
|
| 290 |
+
logger.info(f"✓ SUCCESS: Found {len(result)} rooms")
|
| 291 |
+
return result
|
| 292 |
|
| 293 |
+
except asyncio.TimeoutError:
|
| 294 |
+
logger.warning(f"Attempt {attempt + 1} timed out")
|
| 295 |
+
if attempt < max_retries - 1:
|
| 296 |
+
await asyncio.sleep(5)
|
| 297 |
+
continue
|
| 298 |
+
|
| 299 |
+
except Exception as e:
|
| 300 |
+
error_str = str(e)
|
| 301 |
+
logger.warning(f"Attempt {attempt + 1} failed: {error_str[:200]}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 302 |
|
| 303 |
+
retryable = ['504', '503', '429', 'timeout', 'deadline', 'overloaded']
|
| 304 |
+
if any(k in error_str.lower() for k in retryable):
|
| 305 |
+
if attempt < max_retries - 1:
|
| 306 |
+
wait_time = 10 * (attempt + 1)
|
| 307 |
+
logger.info(f"Waiting {wait_time}s before retry...")
|
| 308 |
+
await asyncio.sleep(wait_time)
|
| 309 |
+
continue
|
| 310 |
|
| 311 |
+
raise
|
| 312 |
+
|
| 313 |
+
logger.warning("All attempts exhausted, generating fallback")
|
| 314 |
+
return self._generate_fallback(pdf.measurement_info)
|
| 315 |
+
|
| 316 |
+
def _select_best_images(self, images, max_images=3):
|
| 317 |
+
if len(images) <= max_images:
|
| 318 |
+
return images
|
| 319 |
+
|
| 320 |
+
scored = []
|
| 321 |
+
for img in images:
|
| 322 |
+
width, height = img.size
|
| 323 |
+
area = width * height
|
| 324 |
+
aspect_ratio = max(width, height) / min(width, height)
|
| 325 |
|
| 326 |
+
score = area
|
| 327 |
+
if 0.5 <= aspect_ratio <= 2.5:
|
| 328 |
+
score *= 1.5
|
| 329 |
+
|
| 330 |
+
scored.append((score, img))
|
| 331 |
+
|
| 332 |
+
scored.sort(reverse=True, key=lambda x: x[0])
|
| 333 |
+
return [img for _, img in scored[:max_images]]
|
| 334 |
+
|
| 335 |
+
def _prepare_high_quality_image(self, image, max_size=2048):
|
| 336 |
+
if image.mode not in ('RGB', 'L'):
|
| 337 |
+
image = image.convert('RGB')
|
| 338 |
+
|
| 339 |
+
width, height = image.size
|
| 340 |
+
|
| 341 |
+
if width > max_size or height > max_size:
|
| 342 |
+
ratio = max_size / max(width, height)
|
| 343 |
+
new_width = int(width * ratio)
|
| 344 |
+
new_height = int(height * ratio)
|
| 345 |
+
image = image.resize((new_width, new_height), Image.Resampling.LANCZOS)
|
| 346 |
+
logger.info(f"Resized: {width}x{height} → {new_width}x{new_height}")
|
| 347 |
+
|
| 348 |
+
return image
|
| 349 |
+
|
| 350 |
+
async def _analyze_with_max_quality(self, images, measurement_info, description,
|
| 351 |
+
file_type, timeout, attempt=0):
|
| 352 |
+
prompt = self.create_prompt(description, measurement_info, file_type)
|
| 353 |
+
|
| 354 |
+
temperature = 0.2 if attempt == 0 else 0.3
|
| 355 |
+
max_tokens = 16384 if attempt == 0 else 12288
|
| 356 |
+
|
| 357 |
+
start_time = time.time()
|
| 358 |
+
loop = asyncio.get_event_loop()
|
| 359 |
+
|
| 360 |
+
def make_request():
|
| 361 |
+
return self.model.generate_content(
|
| 362 |
+
[prompt] + images,
|
| 363 |
+
generation_config={
|
| 364 |
+
"temperature": temperature,
|
| 365 |
+
"max_output_tokens": max_tokens,
|
| 366 |
+
"top_p": 0.95,
|
| 367 |
+
"top_k": 40,
|
| 368 |
+
},
|
| 369 |
+
safety_settings={
|
| 370 |
+
'HARASSMENT': 'BLOCK_NONE',
|
| 371 |
+
'HATE_SPEECH': 'BLOCK_NONE',
|
| 372 |
+
'SEXUALLY_EXPLICIT': 'BLOCK_NONE',
|
| 373 |
+
'DANGEROUS_CONTENT': 'BLOCK_NONE'
|
| 374 |
+
},
|
| 375 |
+
request_options={'timeout': timeout}
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
response = await asyncio.wait_for(
|
| 379 |
+
loop.run_in_executor(None, make_request),
|
| 380 |
+
timeout=timeout + 30
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
elapsed = time.time() - start_time
|
| 384 |
+
logger.info(f"Response in {elapsed:.1f}s ({len(response.text)} chars)")
|
| 385 |
+
|
| 386 |
+
parsed = self._extract_json_comprehensive(response.text)
|
| 387 |
+
|
| 388 |
+
if parsed and len(parsed) > 0:
|
| 389 |
+
validated = self.validate_and_fix_measurements(parsed, measurement_info)
|
| 390 |
+
logger.info(f"Validated {len(validated)} rooms")
|
| 391 |
+
return validated
|
| 392 |
+
|
| 393 |
+
return None
|
| 394 |
+
|
| 395 |
+
def _extract_json_comprehensive(self, text):
|
| 396 |
+
if not text:
|
| 397 |
+
return None
|
| 398 |
+
|
| 399 |
+
text = text.strip()
|
| 400 |
+
text = re.sub(r'```(?:json|javascript)?\s*\n?', '', text)
|
| 401 |
+
text = text.strip('`').strip()
|
| 402 |
+
|
| 403 |
+
try:
|
| 404 |
+
data = json.loads(text)
|
| 405 |
+
if isinstance(data, list) and len(data) > 0:
|
| 406 |
+
return data
|
| 407 |
+
except json.JSONDecodeError:
|
| 408 |
+
pass
|
| 409 |
+
|
| 410 |
+
patterns = [
|
| 411 |
+
r'\[\s*\{[\s\S]*?\}\s*\]',
|
| 412 |
+
r'\[[\s\S]*?\]',
|
| 413 |
+
]
|
| 414 |
+
|
| 415 |
+
for pattern in patterns:
|
| 416 |
+
matches = list(re.finditer(pattern, text))
|
| 417 |
+
for match in sorted(matches, key=lambda m: len(m.group(0)), reverse=True):
|
| 418 |
+
try:
|
| 419 |
+
data = json.loads(match.group(0))
|
| 420 |
+
if isinstance(data, list) and len(data) > 0:
|
| 421 |
+
return data
|
| 422 |
+
except json.JSONDecodeError:
|
| 423 |
+
continue
|
| 424 |
+
|
| 425 |
+
try:
|
| 426 |
+
fixed = re.sub(r',\s*}', '}', text)
|
| 427 |
+
fixed = re.sub(r',\s*]', ']', fixed)
|
| 428 |
+
match = re.search(r'\[[\s\S]*\]', fixed)
|
| 429 |
+
if match:
|
| 430 |
+
data = json.loads(match.group(0))
|
| 431 |
+
if isinstance(data, list):
|
| 432 |
+
return data
|
| 433 |
+
except:
|
| 434 |
+
pass
|
| 435 |
+
|
| 436 |
+
return None
|
| 437 |
+
|
| 438 |
+
def _generate_fallback(self, measurement_info):
|
| 439 |
+
ceiling = measurement_info.get('ceiling_height', 2.4)
|
| 440 |
+
|
| 441 |
+
return [
|
| 442 |
+
{
|
| 443 |
+
"name": "Living Room", "name_no": "Stue",
|
| 444 |
+
"area_m2": 28.0, "position": "main",
|
| 445 |
+
"dimensions_m": {"width": 5.6, "length": 5.0},
|
| 446 |
+
"windows": 2, "window_positions": ["south", "east"],
|
| 447 |
+
"doors": 2, "door_positions": ["to kitchen", "to hallway"],
|
| 448 |
+
"connected_rooms": ["Kitchen", "Hallway"],
|
| 449 |
+
"has_external_access": False,
|
| 450 |
+
"ceiling_height_m": ceiling,
|
| 451 |
+
"furniture": [],
|
| 452 |
+
"estimated": True,
|
| 453 |
+
"note": "Fallback data"
|
| 454 |
+
},
|
| 455 |
+
{
|
| 456 |
+
"name": "Kitchen", "name_no": "Kjøkken",
|
| 457 |
+
"area_m2": 12.0, "position": "adjacent",
|
| 458 |
+
"dimensions_m": {"width": 3.0, "length": 4.0},
|
| 459 |
+
"windows": 1, "window_positions": ["north"],
|
| 460 |
+
"doors": 1, "door_positions": ["to living room"],
|
| 461 |
+
"connected_rooms": ["Living Room"],
|
| 462 |
+
"has_external_access": False,
|
| 463 |
+
"ceiling_height_m": ceiling,
|
| 464 |
+
"furniture": [],
|
| 465 |
+
"estimated": True,
|
| 466 |
+
"note": "Fallback data"
|
| 467 |
+
},
|
| 468 |
+
{
|
| 469 |
+
"name": "Bedroom", "name_no": "Soverom",
|
| 470 |
+
"area_m2": 15.0, "position": "private",
|
| 471 |
+
"dimensions_m": {"width": 3.75, "length": 4.0},
|
| 472 |
+
"windows": 1, "window_positions": ["west"],
|
| 473 |
+
"doors": 1, "door_positions": ["to hallway"],
|
| 474 |
+
"connected_rooms": ["Hallway"],
|
| 475 |
+
"has_external_access": False,
|
| 476 |
+
"ceiling_height_m": ceiling,
|
| 477 |
+
"furniture": [],
|
| 478 |
+
"estimated": True,
|
| 479 |
+
"note": "Fallback data"
|
| 480 |
+
},
|
| 481 |
+
{
|
| 482 |
+
"name": "Bathroom", "name_no": "Bad",
|
| 483 |
+
"area_m2": 6.0, "position": "private",
|
| 484 |
+
"dimensions_m": {"width": 2.0, "length": 3.0},
|
| 485 |
+
"windows": 0, "window_positions": [],
|
| 486 |
+
"doors": 1, "door_positions": ["to hallway"],
|
| 487 |
+
"connected_rooms": ["Hallway"],
|
| 488 |
+
"has_external_access": False,
|
| 489 |
+
"ceiling_height_m": ceiling,
|
| 490 |
+
"furniture": [],
|
| 491 |
+
"estimated": True,
|
| 492 |
+
"note": "Fallback data"
|
| 493 |
+
}
|
| 494 |
+
]
|
| 495 |
|
| 496 |
def create_prompt(self, floor_plan_description=None, measurement_info=None, file_type="pdf"):
|
|
|
|
|
|
|
| 497 |
measurement_context = ""
|
| 498 |
if measurement_info:
|
| 499 |
measurement_context = f"""
|
| 500 |
+
**Measurement Information:**
|
| 501 |
+
* Scale: 1:{measurement_info['scale']}
|
| 502 |
+
* Ceiling height: {measurement_info['ceiling_height']}m
|
| 503 |
"""
|
| 504 |
if measurement_info["room_dimensions"]:
|
| 505 |
+
measurement_context += "* Known dimensions:\n"
|
| 506 |
for room, dims in measurement_info["room_dimensions"].items():
|
| 507 |
+
measurement_context += f" - {room}: {dims['width']} × {dims['length']}m\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 508 |
|
| 509 |
+
prompt = f"""You are an expert architectural assistant analyzing a Norwegian floor plan. Extract complete room information as JSON.
|
| 510 |
{measurement_context}
|
| 511 |
+
|
| 512 |
+
Return this JSON structure:
|
|
|
|
| 513 |
[
|
| 514 |
{{
|
| 515 |
"name": "Room name",
|
| 516 |
+
"name_no": "Norwegian name",
|
| 517 |
"area_m2": 0.0,
|
| 518 |
+
"position": "location",
|
| 519 |
+
"dimensions_m": {{"width": 0.0, "length": 0.0}},
|
|
|
|
|
|
|
|
|
|
| 520 |
"windows": 0,
|
| 521 |
+
"window_positions": ["wall"],
|
| 522 |
"doors": 0,
|
| 523 |
+
"door_positions": ["location"],
|
| 524 |
+
"connected_rooms": ["Room"],
|
| 525 |
+
"has_external_access": false,
|
| 526 |
"ceiling_height_m": 2.4,
|
| 527 |
+
"furniture": [],
|
| 528 |
"estimated": false
|
| 529 |
}}
|
| 530 |
]
|
| 531 |
|
| 532 |
+
Instructions:
|
| 533 |
+
* Include ALL rooms (Stue, Kjøkken, Soverom, Bad, Gang, Entré, Terrasse, etc.)
|
| 534 |
+
* Calculate area_m2 = width × length
|
| 535 |
+
* Set estimated=true if values are approximated
|
| 536 |
+
* Return ONLY the JSON array, no other text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 537 |
|
| 538 |
+
Norwegian terms: Stue=Living room, Kjøkken=Kitchen, Soverom=Bedroom, Bad=Bathroom, Gang=Hallway
|
| 539 |
+
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 540 |
|
| 541 |
if floor_plan_description:
|
| 542 |
+
prompt += f"\n\nContext: {floor_plan_description}"
|
| 543 |
|
| 544 |
return prompt
|
| 545 |
|
| 546 |
def validate_and_fix_measurements(self, json_data, measurement_info=None):
|
|
|
|
| 547 |
try:
|
| 548 |
if isinstance(json_data, str):
|
| 549 |
data = json.loads(json_data)
|
|
|
|
| 553 |
if not isinstance(data, list):
|
| 554 |
return json_data
|
| 555 |
|
| 556 |
+
default_ceiling = measurement_info.get("ceiling_height", 2.4) if measurement_info else 2.4
|
| 557 |
|
| 558 |
for room in data:
|
|
|
|
| 559 |
if room.get("ceiling_height_m") is None or room.get("ceiling_height_m") <= 0:
|
| 560 |
+
room["ceiling_height_m"] = default_ceiling
|
| 561 |
room["estimated"] = True
|
| 562 |
|
|
|
|
| 563 |
if "dimensions_m" in room:
|
| 564 |
width = room["dimensions_m"].get("width", 0)
|
| 565 |
length = room["dimensions_m"].get("length", 0)
|
| 566 |
|
|
|
|
| 567 |
if width <= 0 or length <= 0:
|
|
|
|
| 568 |
if room.get("area_m2", 0) > 0:
|
|
|
|
| 569 |
side = math.sqrt(room["area_m2"])
|
| 570 |
room["dimensions_m"]["width"] = round(side, 1)
|
| 571 |
room["dimensions_m"]["length"] = round(side, 1)
|
| 572 |
room["estimated"] = True
|
| 573 |
else:
|
|
|
|
| 574 |
room["dimensions_m"]["width"] = 3.0
|
| 575 |
room["dimensions_m"]["length"] = 3.0
|
| 576 |
room["area_m2"] = 9.0
|
| 577 |
room["estimated"] = True
|
| 578 |
else:
|
|
|
|
| 579 |
calculated_area = width * length
|
| 580 |
current_area = room.get("area_m2", 0)
|
| 581 |
|
|
|
|
| 582 |
if current_area <= 0 or abs(current_area - calculated_area) > 0.5:
|
| 583 |
room["area_m2"] = round(calculated_area, 1)
|
| 584 |
|
|
|
|
| 585 |
elif "area_m2" in room and room["area_m2"] > 0:
|
|
|
|
| 586 |
side = math.sqrt(room["area_m2"])
|
| 587 |
room["dimensions_m"] = {
|
| 588 |
"width": round(side, 1),
|
|
|
|
| 590 |
}
|
| 591 |
room["estimated"] = True
|
| 592 |
|
|
|
|
| 593 |
if measurement_info and "room_dimensions" in measurement_info:
|
| 594 |
room_name_lower = room.get("name", "").lower()
|
| 595 |
room_name_no_lower = room.get("name_no", "").lower()
|
| 596 |
|
|
|
|
| 597 |
for name in [room_name_lower, room_name_no_lower]:
|
| 598 |
if name in measurement_info["room_dimensions"]:
|
| 599 |
known_dims = measurement_info["room_dimensions"][name]
|
|
|
|
| 608 |
return data
|
| 609 |
|
| 610 |
except Exception as e:
|
| 611 |
+
logger.error(f"Error validating: {e}")
|
| 612 |
return json_data
|
| 613 |
|
|
|
|
|
|
|
| 614 |
app = FastAPI(
|
| 615 |
+
title="Floor Plan API - High Accuracy",
|
| 616 |
+
description="Maximum accuracy floor plan analysis with gemini-2.5-pro",
|
| 617 |
+
version="1.0.5",
|
| 618 |
docs_url="/",
|
| 619 |
+
redoc_url="/redoc"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 620 |
)
|
| 621 |
|
|
|
|
| 622 |
app.add_middleware(
|
| 623 |
CORSMiddleware,
|
| 624 |
allow_origins=["*"],
|
|
|
|
| 627 |
allow_headers=["*"]
|
| 628 |
)
|
| 629 |
|
|
|
|
| 630 |
processor = FloorPlanProcessor()
|
| 631 |
|
| 632 |
+
@app.get("/status")
|
|
|
|
| 633 |
async def get_status():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 634 |
return {
|
| 635 |
"status": "running",
|
| 636 |
+
"pdfs_count": len(processor.pdfs),
|
| 637 |
+
"model": "gemini-2.5-pro",
|
| 638 |
+
"mode": "high_accuracy"
|
| 639 |
}
|
| 640 |
|
| 641 |
+
@app.get("/pdfs")
|
| 642 |
async def get_pdfs():
|
| 643 |
+
return {"pdfs": [pdf.to_dict() for pdf in processor.pdfs.values()]}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 644 |
|
| 645 |
+
@app.get("/pdf/{pdf_id}")
|
| 646 |
async def get_pdf(pdf_id: str):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 647 |
if pdf_id not in processor.pdfs:
|
| 648 |
raise HTTPException(status_code=404, detail="PDF not found")
|
|
|
|
| 649 |
return processor.pdfs[pdf_id].to_dict()
|
| 650 |
|
| 651 |
+
@app.post("/upload")
|
| 652 |
async def upload_pdf(file: UploadFile = File(...)):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 653 |
content_type = file.content_type.lower()
|
| 654 |
+
supported = ["application/pdf"] + list(processor.supported_image_formats.keys())
|
| 655 |
|
| 656 |
+
if content_type not in supported:
|
|
|
|
| 657 |
return JSONResponse(
|
| 658 |
status_code=400,
|
| 659 |
+
content={"error": "Unsupported file type", "supported_types": ", ".join(supported)}
|
|
|
|
|
|
|
|
|
|
| 660 |
)
|
| 661 |
|
| 662 |
+
logger.info(f"Upload: {file.filename} ({content_type})")
|
| 663 |
|
| 664 |
try:
|
|
|
|
| 665 |
file_content = await file.read()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 666 |
pdf_id = await processor.process_upload(file_content, file.filename, content_type)
|
| 667 |
pdf_info = processor.pdfs[pdf_id].to_dict()
|
| 668 |
|
|
|
|
|
|
|
|
|
|
| 669 |
return {
|
| 670 |
+
"message": "File uploaded successfully",
|
| 671 |
"pdf_id": pdf_id,
|
| 672 |
"pdf_info": pdf_info
|
| 673 |
}
|
| 674 |
except Exception as e:
|
| 675 |
+
logger.error(f"Upload error: {str(e)}", exc_info=True)
|
| 676 |
+
return JSONResponse(status_code=500, content={"error": str(e)})
|
|
|
|
|
|
|
|
|
|
| 677 |
|
| 678 |
+
@app.post("/analyze/{pdf_id}")
|
| 679 |
async def analyze_pdf(pdf_id: str, query: FloorPlanQuery = None):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 680 |
if pdf_id not in processor.pdfs:
|
| 681 |
raise HTTPException(status_code=404, detail="PDF not found")
|
| 682 |
|
| 683 |
pdf = processor.pdfs[pdf_id]
|
| 684 |
|
|
|
|
| 685 |
if not pdf.processed:
|
| 686 |
+
return JSONResponse(status_code=400, content={"error": "PDF still processing"})
|
|
|
|
|
|
|
|
|
|
| 687 |
|
|
|
|
| 688 |
if not pdf.images:
|
| 689 |
+
return JSONResponse(status_code=400, content={"error": "No images found"})
|
|
|
|
|
|
|
|
|
|
| 690 |
|
| 691 |
try:
|
| 692 |
description = query.description if query else None
|
| 693 |
+
start_time = time.time()
|
| 694 |
|
|
|
|
|
|
|
| 695 |
result = await asyncio.wait_for(
|
| 696 |
processor.analyze_floor_plan(pdf_id, description),
|
| 697 |
+
timeout=1200
|
| 698 |
)
|
| 699 |
|
| 700 |
+
elapsed = time.time() - start_time
|
| 701 |
pdf.analysis_result = result
|
| 702 |
|
| 703 |
+
is_fallback = any(
|
| 704 |
+
room.get("estimated") and "fallback" in room.get("note", "").lower()
|
| 705 |
+
for room in result
|
| 706 |
+
)
|
| 707 |
|
| 708 |
return {
|
| 709 |
+
"message": "Analysis complete" + (" - fallback" if is_fallback else " - high accuracy"),
|
| 710 |
"pdf_id": pdf_id,
|
| 711 |
"measurement_info": pdf.measurement_info,
|
| 712 |
+
"rooms": result,
|
| 713 |
+
"analysis_time_seconds": round(elapsed, 1),
|
| 714 |
+
"is_estimated": is_fallback,
|
| 715 |
+
"quality": "fallback" if is_fallback else "high_accuracy"
|
| 716 |
}
|
| 717 |
+
|
| 718 |
except asyncio.TimeoutError:
|
| 719 |
+
fallback = processor._generate_fallback(pdf.measurement_info)
|
| 720 |
+
pdf.analysis_result = fallback
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 721 |
|
| 722 |
+
return {
|
| 723 |
+
"message": "Timeout - using fallback",
|
| 724 |
+
"pdf_id": pdf_id,
|
| 725 |
+
"rooms": fallback,
|
| 726 |
+
"is_estimated": True,
|
| 727 |
+
"quality": "fallback"
|
| 728 |
}
|
| 729 |
|
| 730 |
+
except Exception as e:
|
| 731 |
+
logger.error(f"Analysis error: {str(e)}", exc_info=True)
|
|
|
|
|
|
|
|
|
|
| 732 |
|
| 733 |
+
try:
|
| 734 |
+
fallback = processor._generate_fallback(pdf.measurement_info)
|
| 735 |
+
return {
|
| 736 |
+
"message": "Error - using fallback",
|
| 737 |
+
"pdf_id": pdf_id,
|
| 738 |
+
"rooms": fallback,
|
| 739 |
+
"is_estimated": True,
|
| 740 |
+
"error": str(e)
|
| 741 |
+
}
|
| 742 |
+
except:
|
| 743 |
+
return JSONResponse(
|
| 744 |
+
status_code=500,
|
| 745 |
+
content={"error": str(e), "pdf_id": pdf_id}
|
| 746 |
+
)
|
| 747 |
|
| 748 |
+
@app.post("/room/{pdf_id}")
|
| 749 |
async def find_room(pdf_id: str, query: RoomQuery):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 750 |
if pdf_id not in processor.pdfs:
|
|
|
|
| 751 |
raise HTTPException(status_code=404, detail="PDF not found")
|
| 752 |
|
| 753 |
pdf = processor.pdfs[pdf_id]
|
| 754 |
|
|
|
|
| 755 |
if not hasattr(pdf, "analysis_result") or not pdf.analysis_result:
|
|
|
|
| 756 |
raise HTTPException(
|
| 757 |
status_code=400,
|
| 758 |
+
content={"error": "PDF not analyzed yet. Call /analyze/{pdf_id} first"}
|
| 759 |
)
|
| 760 |
|
|
|
|
|
|
|
|
|
|
| 761 |
found_rooms = []
|
| 762 |
room_name_lower = query.room_name.lower()
|
| 763 |
|
|
|
|
| 766 |
norwegian_name = room.get("name_no", "").lower()
|
| 767 |
|
| 768 |
if query.exact_match:
|
|
|
|
| 769 |
if english_name == room_name_lower or norwegian_name == room_name_lower:
|
| 770 |
found_rooms.append(room)
|
| 771 |
else:
|
|
|
|
| 772 |
if room_name_lower in english_name or room_name_lower in norwegian_name:
|
| 773 |
found_rooms.append(room)
|
| 774 |
|
| 775 |
if not found_rooms:
|
|
|
|
| 776 |
raise HTTPException(
|
| 777 |
status_code=404,
|
| 778 |
content={"error": f"No rooms found matching '{query.room_name}'"}
|
| 779 |
)
|
| 780 |
|
|
|
|
| 781 |
if len(found_rooms) == 1:
|
|
|
|
| 782 |
return {
|
| 783 |
"message": f"Room found: {found_rooms[0].get('name')}",
|
| 784 |
"pdf_id": pdf_id,
|
| 785 |
"room": found_rooms[0]
|
| 786 |
}
|
| 787 |
|
|
|
|
|
|
|
| 788 |
room_names = [f"{room.get('name')} ({room.get('name_no', '')})" for room in found_rooms]
|
| 789 |
|
| 790 |
return {
|
|
|
|
| 794 |
"room_names": room_names
|
| 795 |
}
|
| 796 |
|
|
|
|
| 797 |
@app.on_event("startup")
|
| 798 |
async def startup_event():
|
|
|
|
|
|
|
| 799 |
for directory in ["uploads", "logs"]:
|
| 800 |
try:
|
| 801 |
os.makedirs(directory, exist_ok=True)
|
|
|
|
| 803 |
except Exception as e:
|
| 804 |
logger.error(f"Failed to create directory {directory}: {str(e)}")
|
| 805 |
|
|
|
|
| 806 |
if GOOGLE_API_KEY:
|
| 807 |
+
logger.info("GOOGLE_API_KEY is set")
|
| 808 |
else:
|
| 809 |
+
logger.warning("GOOGLE_API_KEY not set!")
|
| 810 |
+
|
| 811 |
+
logger.info("\n" + "="*60)
|
| 812 |
+
logger.info("Floor Plan Analysis API - HIGH ACCURACY MODE")
|
| 813 |
+
logger.info("="*60)
|
| 814 |
+
logger.info(f"Model: gemini-2.5-pro")
|
| 815 |
+
logger.info(f"Max Analysis Time: 20 minutes")
|
| 816 |
+
logger.info(f"Image Quality: 2048px")
|
| 817 |
+
logger.info(f"Retries: 3 per analysis")
|
| 818 |
logger.info(f"Documentation: http://localhost:7860/")
|
| 819 |
+
logger.info("="*60 + "\n")
|
|
|
|
|
|
|
| 820 |
|
| 821 |
@app.on_event("shutdown")
|
| 822 |
async def shutdown_event():
|
|
|
|
| 823 |
logger.info("Application shutting down")
|
| 824 |
|
|
|
|
| 825 |
if __name__ == "__main__":
|
| 826 |
+
logger.info("Starting Floor Plan Analysis API (High Accuracy Mode)")
|
| 827 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|