iplotnor commited on
Commit
5e0ac15
·
verified ·
1 Parent(s): 806a704

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +921 -0
app.py ADDED
@@ -0,0 +1,921 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import asyncio
3
+ from typing import List, Dict, Any, Optional, Union
4
+ from fastapi import FastAPI, UploadFile, File, HTTPException
5
+ from fastapi.middleware.cors import CORSMiddleware
6
+ from fastapi.responses import JSONResponse
7
+ from pydantic import BaseModel
8
+ import uvicorn
9
+ import logging
10
+ 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
+ # version = 0.0.2
18
+ # Configure logging
19
+ logging.basicConfig(
20
+ level=logging.INFO,
21
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
22
+ handlers=[
23
+ logging.StreamHandler(), # Log to console
24
+ logging.FileHandler("floor_plan_api.log") # Log to file
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
+
60
+ class PDF:
61
+ def __init__(self, filename, content_type):
62
+ self.filename = filename
63
+ self.content_type = content_type
64
+ self.id = re.sub(r'[^a-zA-Z0-9]', '_', filename)
65
+ self.processed = False
66
+ self.error = None
67
+ self.images = []
68
+ self.page_count = 0
69
+ self.file_type = "pdf" if content_type == "application/pdf" else "image" # Added to support images
70
+ self.measurement_info = {
71
+ "scale": 100, # Default scale 1:100
72
+ "ceiling_height": 2.4, # Default ceiling height in meters
73
+ "room_dimensions": {}
74
+ }
75
+ self.analysis_result = None # Will store the room analysis result
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, # Added to response
83
+ "processed": self.processed,
84
+ "error": self.error,
85
+ "page_count": self.page_count if self.file_type == "pdf" else None,
86
+ "image_count": len(self.images) if self.images else 0,
87
+ "measurement_info": self.measurement_info,
88
+ "has_analysis": self.analysis_result is not None,
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-1.5-pro-latest')
96
+ self.pdfs = {} # Keep the original name for backward compatibility
97
+ # Define supported image formats
98
+ self.supported_image_formats = {
99
+ "image/jpeg": ".jpg",
100
+ "image/png": ".png",
101
+ "image/gif": ".gif",
102
+ "image/bmp": ".bmp",
103
+ "image/tiff": ".tiff",
104
+ "image/webp": ".webp"
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:
128
+ await self.process_image(pdf, file_content)
129
+ else:
130
+ raise ValueError(f"Unsupported content type: {content_type}")
131
+
132
+ pdf.processed = True
133
+ logger.info(f"File {filename} (ID: {pdf_id}) processing completed successfully")
134
+ return pdf_id
135
+
136
+ except Exception as e:
137
+ logger.error(f"Error processing file {filename}: {str(e)}", exc_info=True)
138
+ pdf.error = str(e)
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, # Default scale 1:100
156
+ "ceiling_height": 2.4, # Default ceiling height in meters
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)
173
+ logger.info(f"PDF has {pdf.page_count} pages")
174
+
175
+ images = []
176
+ embedded_image_count = 0
177
+ rendered_page_count = 0
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))
217
+ img_bytes = pix.tobytes("png")
218
+ img = Image.open(BytesIO(img_bytes))
219
+ images.append(img)
220
+ rendered_page_count += 1
221
+
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:
237
+ logger.error(f"Error processing PDF {pdf.filename}: {str(e)}", exc_info=True)
238
+ pdf.error = str(e)
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,
246
+ "ceiling_height": None,
247
+ "room_dimensions": {}
248
+ }
249
+
250
+ scale_patterns = [
251
+ r'(?i)scale\s*1\s*:\s*(\d+)',
252
+ r'(?i)målestokk\s*1\s*:\s*(\d+)',
253
+ r'(?i)skala\s*1\s*:\s*(\d+)',
254
+ r'1\s*:\s*(\d+)'
255
+ ]
256
+
257
+ height_patterns = [
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 = [
266
+ r'(?i)(stue|kjøkken|soverom|bad|gang|entré|kontor|bod).*?(\d+[\.,]?\d*)\s*[xX×]\s*(\d+[\.,]?\d*)',
267
+ r'(?i)(living|kitchen|bedroom|bathroom|hallway|entrance|office|storage).*?(\d+[\.,]?\d*)\s*[xX×]\s*(\d+[\.,]?\d*)'
268
+ ]
269
+
270
+ for page_num in range(len(pdf_document)):
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)
278
+ if matches:
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)
286
+ if matches:
287
+ height = matches[0].replace(',', '.')
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:
295
+ room_name = match[0].lower().strip()
296
+ width = float(match[1].replace(',', '.'))
297
+ length = float(match[2].replace(',', '.'))
298
+ measurement_info["room_dimensions"][room_name] = {
299
+ "width": width,
300
+ "length": length
301
+ }
302
+
303
+ # Default values if not found
304
+ if not measurement_info["scale"]:
305
+ measurement_info["scale"] = 100 # Common scale for residential floor plans
306
+
307
+ if not measurement_info["ceiling_height"]:
308
+ measurement_info["ceiling_height"] = 2.4 # Standard ceiling height in Norway
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")
325
+
326
+ if not pdf.images:
327
+ raise ValueError(f"No images found in PDF {pdf_id}")
328
+
329
+ try:
330
+ # Create prompt for floor plan analysis with measurement info
331
+ prompt = self.create_prompt(description, pdf.measurement_info, pdf.file_type)
332
+
333
+ # Call Gemini with the images and prompt
334
+ response = self.model.generate_content([prompt, *pdf.images])
335
+
336
+ # Extract JSON from the response
337
+ response_text = response.text
338
+
339
+ # Enhanced JSON extraction - try multiple approaches
340
+ parsed_json = None
341
+
342
+ # Attempt 1: Try to parse the entire response
343
+ try:
344
+ parsed_json = json.loads(response_text.strip())
345
+ return self.validate_and_fix_measurements(parsed_json, pdf.measurement_info)
346
+ except json.JSONDecodeError:
347
+ pass # Continue to next attempt
348
+
349
+ # Attempt 2: Look for JSON between triple backticks
350
+ if "```" in response_text:
351
+ parts = response_text.split("```")
352
+ for i, part in enumerate(parts):
353
+ part = part.strip()
354
+ # Skip empty parts and parts that are just language identifiers
355
+ if not part or part.lower() in ["json", "javascript"]:
356
+ continue
357
+
358
+ try:
359
+ parsed_json = json.loads(part)
360
+ return self.validate_and_fix_measurements(parsed_json, pdf.measurement_info)
361
+ except json.JSONDecodeError:
362
+ continue
363
+
364
+ # Attempt 3: Try to repair common JSON issues
365
+ try:
366
+ # Replace single quotes with double quotes
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
+ # Add a fallback explanation in the logs
406
+ logger.error(f"Generated fallback room data for PDF {pdf_id} due to JSON parsing issues.")
407
+ logger.error(f"Original model response: {response_text[:500]}...")
408
+
409
+ # Return the fallback data
410
+ return [fallback_room]
411
+
412
+ # If all else fails, raise an error
413
+ logger.error(f"Failed to extract room data from model response: {response_text[:500]}...")
414
+ raise ValueError("Could not extract valid JSON from model response")
415
+
416
+ except Exception as e:
417
+ logger.error(f"Error analyzing floor plan {pdf_id}: {str(e)}")
418
+ raise e
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
+ **Important Measurement Information:**
427
+ * The floor plan uses a scale of 1:{measurement_info['scale']}
428
+ * The standard ceiling height is {measurement_info['ceiling_height']} meters
429
+ """
430
+ if measurement_info["room_dimensions"]:
431
+ measurement_context += "* Known room dimensions (width × length in meters):\n"
432
+ for room, dims in measurement_info["room_dimensions"].items():
433
+ measurement_context += f" - {room}: {dims['width']} × {dims['length']} meters\n"
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. I am providing a {file_type} floor plan of a house from Norway. The floor plan is likely to contain Norwegian text and terminology. Your job is to analyze the layout and extract **complete room-level information** in **structured JSON format** that I can directly use to build a 3D model.
443
+ {measurement_context}
444
+ {file_type_context}
445
+
446
+ Please return the following **JSON structure**, including estimates and spatial relationships:
447
+ [
448
+ {{
449
+ "name": "Room name",
450
+ "name_no": "Norwegian room name (if present)",
451
+ "area_m2": 0.0,
452
+ "position": "approximate location (e.g., north, south-east corner)",
453
+ "dimensions_m": {{
454
+ "width": 0.0,
455
+ "length": 0.0
456
+ }},
457
+ "windows": 0,
458
+ "window_positions": ["north wall", "east wall"],
459
+ "doors": 0,
460
+ "door_positions": ["interior", "to terrace"],
461
+ "connected_rooms": ["Room A", "Room B"],
462
+ "has_external_access": true,
463
+ "ceiling_height_m": 2.4,
464
+ "furniture": ["sofa", "kitchen island"],
465
+ "estimated": false
466
+ }}
467
+ ]
468
+
469
+ **Instructions:**
470
+ * Include **all rooms**, including utility spaces (garage, hallway, terrace, storage, laundry, etc.).
471
+ * Recognize Norwegian room names and provide both Norwegian (name_no) and English (name) versions.
472
+ * Calculate area_m2 accurately as width × length. Double-check this calculation for all rooms.
473
+ * If any values are not labeled, **estimate them** based on layout scale and set `"estimated": true`.
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
+ **Common Norwegian architectural terms:**
482
+ * Stue = Living room
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\nAdditional information about the floor plan: {floor_plan_description}"
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)
510
+ else:
511
+ data = json_data
512
+
513
+ if not isinstance(data, list):
514
+ return json_data
515
+
516
+ default_ceiling_height = measurement_info.get("ceiling_height", 2.4) if measurement_info else 2.4
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"] = default_ceiling_height
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),
559
+ "length": round(side, 1)
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]
572
+ room["dimensions_m"] = {
573
+ "width": known_dims["width"],
574
+ "length": known_dims["length"]
575
+ }
576
+ room["area_m2"] = round(known_dims["width"] * known_dims["length"], 1)
577
+ room["estimated"] = False
578
+ break
579
+
580
+ return data
581
+
582
+ except Exception as e:
583
+ logger.error(f"Error validating measurements: {e}")
584
+ return json_data
585
+
586
+ # Initialize FastAPI
587
+ # Initialize FastAPI with Swagger UI configuration
588
+ app = FastAPI(
589
+ title="Floor Plan Analysis API",
590
+ description="API for analyzing floor plans in PDF or image format and extracting structured room data",
591
+ version="1.0.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=["*"],
606
+ allow_credentials=True,
607
+ allow_methods=["*"],
608
+ allow_headers=["*"]
609
+ )
610
+
611
+ # Initialize processor
612
+ processor = FloorPlanProcessor()
613
+
614
+ # API endpoints
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", tags=["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}", tags=["pdfs"])
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", tags=["pdfs"])
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
+ supported_types = ["application/pdf"] + list(processor.supported_image_formats.keys())
680
+
681
+ if content_type not in supported_types:
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"Received upload request for file: {file.filename} ({content_type})")
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": "PDF uploaded successfully",
708
+ "pdf_id": pdf_id,
709
+ "pdf_info": pdf_info
710
+ }
711
+ except Exception as e:
712
+ logger.error(f"Error processing upload for {file.filename}: {str(e)}", exc_info=True)
713
+ return JSONResponse(
714
+ status_code=500,
715
+ content={"error": f"Error processing upload: {str(e)}"}
716
+ )
717
+
718
+ @app.post("/analyze/{pdf_id}", tags=["analysis"])
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
+ logger.info(f"Analyzing floor plan {pdf_id} with description: {description}")
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=120 # 2 minute timeout
767
+ )
768
+
769
+ # Store the analysis result in the PDF object for later retrieval
770
+ pdf.analysis_result = result
771
+
772
+ logger.info(f"Successfully analyzed floor plan {pdf_id}, found {len(result)} rooms")
773
+
774
+ return {
775
+ "message": "Floor plan analyzed successfully",
776
+ "pdf_id": pdf_id,
777
+ "measurement_info": pdf.measurement_info,
778
+ "rooms": result
779
+ }
780
+ except asyncio.TimeoutError:
781
+ logger.error(f"Timeout while analyzing floor plan {pdf_id}")
782
+ return JSONResponse(
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
+ # Return more detailed error information
790
+ error_details = {
791
+ "error": f"Error analyzing floor plan: {str(e)}",
792
+ "error_type": type(e).__name__,
793
+ "pdf_id": pdf_id
794
+ }
795
+
796
+ if hasattr(e, '__dict__'):
797
+ # Include additional error attributes if available
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
+ return JSONResponse(
803
+ status_code=500,
804
+ content=error_details
805
+ )
806
+
807
+ @app.post("/room/{pdf_id}", tags=["analysis"])
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 has not been analyzed yet. Please call /analyze/{pdf_id} first."}
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
+
847
+ for room in pdf.analysis_result:
848
+ english_name = room.get("name", "").lower()
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 {
881
+ "message": f"Found {len(found_rooms)} rooms matching '{query.room_name}'",
882
+ "pdf_id": pdf_id,
883
+ "rooms": found_rooms,
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)
895
+ logger.info(f"Created directory: {directory}")
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 environment variable is set")
902
+ else:
903
+ logger.warning("GOOGLE_API_KEY environment variable is not set! The API will not function correctly.")
904
+
905
+ # Print API information
906
+ logger.info("\n===== Floor Plan Analysis API =====")
907
+ logger.info(f"Starting server with Gemini API: {'CONFIGURED' if GOOGLE_API_KEY else 'NOT CONFIGURED'}")
908
+ logger.info(f"Documentation: http://localhost:7860/")
909
+ logger.info(f"Status: http://localhost:7860/status")
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 server")
921
+ uvicorn.run(app, host="0.0.0.0", port=7860)