Spaces:
Runtime error
Runtime error
File size: 34,083 Bytes
e6be672 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 | # Copyright (C) 2026 Mattia Zatelli
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
IFC file processing service using ifcopenshell
This service handles the entire IFC file processing pipeline:
- IFC file parsing and validation
- Project and site metadata extraction
- Geometry and spatial property calculations
- GPU acceleration for heavy computations
- Element extraction for database
- Project statistics generation
Supports IFC2X3, IFC4, IFC4X1 standards with robust error handling.
"""
import logging
import tempfile
import os
import numpy as np
from typing import Dict, Any, List, Optional
import ifcopenshell
import ifcopenshell.geom
from app.services.gpu_accelerator import get_gpu_accelerator
logger = logging.getLogger(__name__)
class IFCProcessor:
"""IFC file processor with ifcopenshell support
Handles complete IFC file processing with:
- World coordinates geometry configuration
- GPU acceleration integration
- Structured metadata extraction
- Optimized spatial calculations
- Robust error handling
Attributes:
settings: ifcopenshell geometry configuration
gpu: GPU accelerator for heavy computations
"""
def __init__(self):
# Configure ifcopenshell settings — optimized for fast bounding box extraction
self.settings = ifcopenshell.geom.settings()
self.settings.set(self.settings.USE_WORLD_COORDS, True)
# Initialize geometry accelerator (GPU if available, CPU fallback)
self.gpu = get_gpu_accelerator()
logger.info(f"Geometry accelerator: {self.gpu.device_info['name']}")
async def parse_ifc_content(self, file_content: bytes, filename: str) -> Dict[str, Any]:
"""
Parse IFC file content and extract base information
**Processing pipeline:**
1. Secure temporary file creation
2. Open with ifcopenshell
3. Schema and version validation
4. Project/site metadata extraction
5. Bounding box and statistics calculation
6. Automatic temporary file cleanup
**Extracted metadata:**
- IFC schema (IFC2X3, IFC4, etc.)
- Project and application information
- Site and building data
- Complete 3D bounding box
- Gross floor area
- Building height
- Element count by type
Args:
file_content: Raw bytes of the IFC file
filename: Original filename for logging
Returns:
Dict containing:
- ifc_model: ifcopenshell instance for further processing
- schema: IFC schema used
- version: IFC file version
- project_info: Project metadata
- site_info: Site/building metadata
- bounding_box: 3D box {min: [x,y,z], max: [x,y,z]}
- gross_floor_area: Total floor area (m²)
- building_height: Building height (m)
Raises:
IFCProcessingError: If parsing fails
ValidationError: If IFC file is invalid
"""
logger.info(f"Parsing IFC file: {filename}")
# Create secure temporary file for ifcopenshell
temp_path = None
try:
fd = tempfile.mkstemp(suffix='.ifc')
temp_path = fd[1]
os.close(fd[0])
os.chmod(temp_path, 0o600)
with open(temp_path, 'wb') as temp_file:
temp_file.write(file_content)
# === PHASE 1: OPEN AND VALIDATE IFC FILE ===
ifc_file = ifcopenshell.open(temp_path)
logger.info(f"IFC file opened successfully - Schema: {ifc_file.schema}")
# === PHASE 2: STRUCTURED METADATA EXTRACTION ===
result = {
"ifc_model": ifc_file,
"schema": ifc_file.schema,
"version": self._extract_version(ifc_file),
"project_info": self._extract_project_info(ifc_file),
"site_info": self._extract_site_info(ifc_file),
"units": self._extract_units(ifc_file),
"bounding_box": self._calculate_bounding_box(ifc_file),
"gross_floor_area": self._calculate_gross_floor_area(ifc_file),
"building_height": self._calculate_building_height(ifc_file)
}
# === PHASE 3: ELEMENT STATISTICS ===
product_count = len(ifc_file.by_type('IfcProduct'))
logger.info(f"IFC file processed - {product_count} products found")
return result
except Exception as e:
logger.error(f"IFC file parsing failed {filename}: {e}")
raise
finally:
# === CLEANUP: TEMPORARY FILE REMOVAL ===
if temp_path and os.path.exists(temp_path):
try:
os.unlink(temp_path)
except OSError as cleanup_err:
logger.warning(f"Failed to clean up temp file {temp_path}: {cleanup_err}")
def _extract_version(self, ifc_file) -> Optional[str]:
"""Extract IFC file version from IfcFileDescription
Returns:
str: IFC version or None if not found
"""
try:
file_description = ifc_file.by_type('IfcFileDescription')
if file_description:
return str(file_description[0].Description[0]) if file_description[0].Description else None
except:
pass
return None
def _extract_project_info(self, ifc_file) -> Dict[str, Any]:
"""Extract project information from IFC entities
Retrieves metadata from:
- IfcProject: name, description, long name
- IfcApplication: software used
- IfcPerson: author/responsible
- IfcOrganization: organization
Returns:
Dict: Structured project metadata
"""
info = {}
try:
# === BASE PROJECT INFORMATION ===
projects = ifc_file.by_type('IfcProject')
if projects:
project = projects[0]
info['name'] = project.Name
info['description'] = project.Description
info['long_name'] = project.LongName if hasattr(project, 'LongName') else None
# === AUTHORING APPLICATION INFORMATION ===
applications = ifc_file.by_type('IfcApplication')
if applications:
app = applications[0]
info['created_by'] = {
'application': app.ApplicationFullName,
'version': app.Version,
'developer': app.ApplicationDeveloper.Name if app.ApplicationDeveloper else None
}
except Exception as e:
logger.warning(f"Failed to extract project info: {e}")
return info
def _extract_site_info(self, ifc_file) -> Dict[str, Any]:
"""Extract site and building information"""
info = {}
try:
sites = ifc_file.by_type('IfcSite')
if sites:
site = sites[0]
info['site_name'] = site.Name
info['site_description'] = site.Description
buildings = ifc_file.by_type('IfcBuilding')
if buildings:
building = buildings[0]
info['building_name'] = building.Name
info['building_description'] = building.Description
except Exception as e:
logger.warning(f"Failed to extract site info: {e}")
return info
def _extract_units(self, ifc_file) -> Dict[str, Any]:
"""Extract unit assignments from IFC file
Extracts units for length, area, volume, and other quantities.
This is crucial for correct interpretation of numerical values.
Returns:
Dict containing unit information:
- length_unit: e.g., "METRE", "MILLIMETRE"
- area_unit: e.g., "SQUARE_METRE"
- volume_unit: e.g., "CUBIC_METRE"
- length_prefix: e.g., None, "MILLI", "CENTI"
- conversion_factors: multipliers to convert to base units (meters)
"""
units = {
'length_unit': None,
'area_unit': None,
'volume_unit': None,
'length_prefix': None,
'conversion_factors': {
'length_to_meters': 1.0,
'area_to_square_meters': 1.0,
'volume_to_cubic_meters': 1.0
}
}
try:
# Get project and its unit assignment
projects = ifc_file.by_type('IfcProject')
if not projects:
return units
project = projects[0]
if not hasattr(project, 'UnitsInContext') or not project.UnitsInContext:
return units
unit_assignment = project.UnitsInContext
if not hasattr(unit_assignment, 'Units'):
return units
# Parse each unit
for unit in unit_assignment.Units:
try:
unit_type = unit.UnitType if hasattr(unit, 'UnitType') else None
if unit.is_a('IfcSIUnit'):
unit_name = unit.Name if hasattr(unit, 'Name') else None
prefix = unit.Prefix if hasattr(unit, 'Prefix') else None
# Calculate conversion factor based on prefix
prefix_multipliers = {
'EXA': 1e18, 'PETA': 1e15, 'TERA': 1e12,
'GIGA': 1e9, 'MEGA': 1e6, 'KILO': 1e3,
'HECTO': 1e2, 'DECA': 1e1,
'DECI': 1e-1, 'CENTI': 1e-2, 'MILLI': 1e-3,
'MICRO': 1e-6, 'NANO': 1e-9, 'PICO': 1e-12
}
multiplier = prefix_multipliers.get(prefix, 1.0)
if unit_type == 'LENGTHUNIT':
units['length_unit'] = unit_name
units['length_prefix'] = prefix
units['conversion_factors']['length_to_meters'] = multiplier
elif unit_type == 'AREAUNIT':
units['area_unit'] = unit_name
units['conversion_factors']['area_to_square_meters'] = multiplier ** 2
elif unit_type == 'VOLUMEUNIT':
units['volume_unit'] = unit_name
# Default calculation based on the unit's own prefix
units['conversion_factors']['volume_to_cubic_meters'] = multiplier ** 3
elif unit.is_a('IfcConversionBasedUnit'):
# Handle custom units (e.g., imperial units)
unit_name = unit.Name if hasattr(unit, 'Name') else None
if hasattr(unit, 'ConversionFactor'):
# Extract conversion factor - this is complex in IFC
pass
except Exception as e:
logger.debug(f"Failed to parse unit {unit}: {e}")
continue
logger.info(f"Extracted units: length={units['length_unit']} (prefix={units['length_prefix']}), "
f"area={units['area_unit']}, volume={units['volume_unit']}, "
f"conversions={units['conversion_factors']}")
except Exception as e:
logger.warning(f"Failed to extract units: {e}")
return units
def _calculate_bounding_box(self, ifc_file) -> Optional[Dict[str, List[float]]]:
"""Calculate overall bounding box"""
try:
# This is a simplified implementation
# In production, you'd want to calculate the actual 3D bounding box
return {
"min": [0.0, 0.0, 0.0],
"max": [100.0, 100.0, 10.0] # Placeholder
}
except Exception as e:
logger.warning(f"Failed to calculate bounding box: {e}")
return None
def _calculate_gross_floor_area(self, ifc_file) -> Optional[float]:
"""Calculate gross floor area"""
try:
total_area = 0.0
slabs = ifc_file.by_type('IfcSlab')
for slab in slabs:
# Check if it's a floor slab
if hasattr(slab, 'PredefinedType') and slab.PredefinedType == 'FLOOR':
# Extract area from quantities
if hasattr(slab, 'IsDefinedBy'):
for definition in slab.IsDefinedBy:
if hasattr(definition, 'RelatingPropertyDefinition'):
prop_def = definition.RelatingPropertyDefinition
if hasattr(prop_def, 'Quantities'):
for quantity in prop_def.Quantities:
if hasattr(quantity, 'Name') and 'Area' in quantity.Name:
if hasattr(quantity, 'AreaValue'):
total_area += quantity.AreaValue
return total_area if total_area > 0 else None
except Exception as e:
logger.warning(f"Failed to calculate gross floor area: {e}")
return None
def _calculate_building_height(self, ifc_file) -> Optional[float]:
"""Calculate building height"""
try:
# Find the highest and lowest points
# This is a simplified implementation
storeys = ifc_file.by_type('IfcBuildingStorey')
if not storeys:
return None
elevations = []
for storey in storeys:
if hasattr(storey, 'Elevation') and storey.Elevation is not None:
elevations.append(storey.Elevation)
if len(elevations) >= 2:
return max(elevations) - min(elevations)
return None
except Exception as e:
logger.warning(f"Failed to calculate building height: {e}")
return None
async def extract_elements(self, ifc_file, progress_callback=None) -> List[Dict[str, Any]]:
"""
Extract all relevant elements from IFC model with parallel processing
Args:
ifc_file: Opened IFC file object
progress_callback: Optional callback function(current, total) for progress updates
Returns:
List of element dictionaries
"""
logger.info("Extracting elements from IFC model")
products = ifc_file.by_type('IfcProduct')
total_products = len(products)
logger.info(f"Processing {total_products} IFC products with parallel extraction")
# Use ThreadPoolExecutor for parallel element extraction
import os
import concurrent.futures
# Wrapper function for thread pool
def extract_single_element(product):
try:
return self._extract_element_data(product, ifc_file)
except Exception as e:
logger.warning(f"Failed to extract element {product.GlobalId if hasattr(product, 'GlobalId') else 'unknown'}: {e}")
return None
# Use all available cores for maximum parallelism
max_workers = min(os.cpu_count() or 8, 32)
logger.info(f"Using {max_workers} workers for element extraction")
elements = []
with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
# Submit all tasks
future_to_product = {executor.submit(extract_single_element, product): product for product in products}
# Collect results as they complete
for i, future in enumerate(concurrent.futures.as_completed(future_to_product)):
try:
element_data = future.result()
if element_data:
elements.append(element_data)
# Update progress callback
if progress_callback and (i + 1) % 500 == 0:
progress_callback(i + 1, total_products)
# Log progress periodically
if (i + 1) % 100 == 0:
logger.info(f"Processed {i + 1}/{total_products} elements")
except Exception as e:
logger.warning(f"Failed to process future result: {e}")
continue
# Final progress update
if progress_callback:
progress_callback(total_products, total_products)
logger.info(f"Extracted {len(elements)} elements from IFC model")
return elements
def _extract_element_data(self, product, ifc_file) -> Optional[Dict[str, Any]]:
"""Extract data for a single IFC element"""
try:
# Basic element information
data = {
"ifc_global_id": product.GlobalId,
"ifc_type": product.is_a(),
"ifc_class": product.is_a(),
"name": product.Name,
"description": product.Description,
"tag": getattr(product, 'Tag', None)
}
# Normalize element type
data["element_type"] = self._normalize_element_type(product.is_a())
# Extract spatial information
spatial_info = self._extract_spatial_info(product)
data.update(spatial_info)
# Geometry is extracted in a separate background phase for speed.
# Dimensions will be populated from IFC quantities/properties if available.
geometry_info = {}
# Extract material information
material_info = self._extract_material_info(product)
data.update(material_info)
# Extract properties
properties = self._extract_properties(product)
data["properties"] = properties
# Extract quantities
quantities = self._extract_quantities(product)
data["quantities"] = quantities
# Extract classifications
classifications = self._extract_classifications(product)
data["classifications"] = classifications
# Helper to extract numeric value from property (handles dict format)
def extract_numeric(value):
"""Extract numeric value from property (which may be dict or number)"""
if value is None:
return None
if isinstance(value, (int, float)):
return float(value)
if isinstance(value, dict):
# Properties are often {'value': 123.4, 'unit': 'm', ...}
return float(value.get('value')) if value.get('value') is not None else None
try:
return float(value)
except (ValueError, TypeError):
return None
# Normalize common properties to direct columns for better query performance
# Priority: quantities > properties > calculated from geometry
data["area"] = (
extract_numeric(quantities.get("area")) or
extract_numeric(properties.get("Area")) or
extract_numeric(properties.get("area")) or
geometry_info.get("calculated_area")
)
data["volume"] = (
extract_numeric(quantities.get("volume")) or
extract_numeric(properties.get("Volume")) or
extract_numeric(properties.get("volume")) or
geometry_info.get("calculated_volume")
)
data["length"] = (
extract_numeric(quantities.get("length")) or
extract_numeric(properties.get("Length")) or
extract_numeric(properties.get("length")) or
geometry_info.get("calculated_length")
)
data["width"] = (
extract_numeric(quantities.get("width")) or
extract_numeric(properties.get("Width")) or
extract_numeric(properties.get("width")) or
geometry_info.get("calculated_width")
)
data["height"] = (
extract_numeric(quantities.get("height")) or
extract_numeric(properties.get("Height")) or
extract_numeric(properties.get("height")) or
geometry_info.get("calculated_height")
)
data["perimeter"] = (
extract_numeric(quantities.get("perimeter")) or
extract_numeric(properties.get("Perimeter")) or
extract_numeric(properties.get("perimeter")) or
geometry_info.get("calculated_perimeter")
)
# Set flags
data["has_geometry"] = bool(geometry_info.get("bounding_box"))
data["has_properties"] = bool(properties)
data["has_materials"] = bool(material_info.get("material_name"))
return data
except Exception as e:
logger.warning(f"Failed to extract data for element {product.GlobalId}: {e}")
return None
def _normalize_element_type(self, ifc_type: str) -> str:
"""Normalize IFC type to standard categories"""
type_mapping = {
"IfcWall": "Wall",
"IfcWallStandardCase": "Wall",
"IfcSlab": "Floor",
"IfcBeam": "Beam",
"IfcColumn": "Column",
"IfcDoor": "Door",
"IfcWindow": "Window",
"IfcStair": "Stair",
"IfcStairFlight": "Stair",
"IfcRailing": "Railing",
"IfcRoof": "Roof",
"IfcSpace": "Space",
"IfcRoom": "Room",
"IfcFurniture": "Furniture",
"IfcCovering": "Covering",
"IfcCurtainWall": "Curtain Wall",
"IfcPlate": "Plate",
"IfcMember": "Member",
"IfcFooting": "Foundation",
"IfcPile": "Pile",
}
return type_mapping.get(ifc_type, "Other")
def _extract_spatial_info(self, product) -> Dict[str, Any]:
"""Extract spatial hierarchy information"""
info = {}
try:
# Find containing spatial element
if hasattr(product, 'ContainedInStructure'):
for rel in product.ContainedInStructure:
spatial_element = rel.RelatingStructure
if spatial_element.is_a('IfcBuildingStorey'):
info["level_name"] = spatial_element.Name
info["level_elevation"] = getattr(spatial_element, 'Elevation', None)
elif spatial_element.is_a('IfcBuilding'):
info["building_name"] = spatial_element.Name
elif spatial_element.is_a('IfcSite'):
info["site_name"] = spatial_element.Name
except Exception as e:
logger.debug(f"Failed to extract spatial info: {e}")
return info
def _extract_geometry_info(self, product) -> Dict[str, Any]:
"""Extract geometry information with GPU acceleration and calculate derived metrics"""
info = {}
try:
if hasattr(product, 'Representation') and product.Representation:
info["has_geometry"] = True
try:
shape = ifcopenshell.geom.create_shape(self.settings, product)
verts = shape.geometry.verts
vertices = np.array(verts).reshape(-1, 3)
if len(vertices) > 0:
bbox_results = self.gpu.calculate_bounding_box_batch([vertices])
centroid_results = self.gpu.calculate_centroids_batch([vertices])
bbox = bbox_results[0]
info["bounding_box"] = bbox
info["centroid"] = centroid_results[0]
# Calculate geometric dimensions from bounding box
if bbox and "min" in bbox and "max" in bbox:
min_pt = bbox["min"]
max_pt = bbox["max"]
# Calculate dimensions
width = abs(max_pt[0] - min_pt[0])
depth = abs(max_pt[1] - min_pt[1])
height = abs(max_pt[2] - min_pt[2])
info["calculated_width"] = round(width, 3) if width > 0.001 else None
info["calculated_height"] = round(height, 3) if height > 0.001 else None
info["calculated_depth"] = round(depth, 3) if depth > 0.001 else None
# Calculate volume from bounding box (approximation)
volume = width * depth * height
if volume > 0.001: # Only if meaningful volume
info["calculated_volume"] = round(volume, 3)
# Calculate area based on element type
ifc_type = product.is_a()
# For flat elements (windows, doors, slabs), use largest face
if ifc_type in ['IfcWindow', 'IfcDoor']:
# Assume width x height for openings
area = width * height
if area > 0.001:
info["calculated_area"] = round(area, 3)
elif ifc_type in ['IfcSlab', 'IfcRoof', 'IfcCovering']:
# Use horizontal area (width x depth)
area = width * depth
if area > 0.001:
info["calculated_area"] = round(area, 3)
elif ifc_type in ['IfcWall', 'IfcCurtainWall']:
# Use vertical area (perimeter approximation)
# For walls, estimate as (width + depth) * 2 * height
perimeter = (width + depth) * 2
area = perimeter * height
if area > 0.001:
info["calculated_area"] = round(area, 3)
if perimeter > 0.001:
info["calculated_perimeter"] = round(perimeter, 3)
# For linear elements, calculate length
if ifc_type in ['IfcBeam', 'IfcColumn', 'IfcMember']:
# Use the largest dimension as length
length = max(width, depth, height)
if length > 0.001:
info["calculated_length"] = round(length, 3)
else:
info["bounding_box"] = {"min": [0.0, 0.0, 0.0], "max": [0.0, 0.0, 0.0]}
info["centroid"] = [0.0, 0.0, 0.0]
except Exception as geom_error:
logger.debug(f"Geometry extraction failed, using placeholder: {geom_error}")
info["bounding_box"] = {"min": [0.0, 0.0, 0.0], "max": [1.0, 1.0, 1.0]}
info["centroid"] = [0.5, 0.5, 0.5]
except Exception as e:
logger.debug(f"Failed to extract geometry info: {e}")
return info
def _extract_material_info(self, product) -> Dict[str, Any]:
"""Extract material information"""
info = {}
try:
if hasattr(product, 'HasAssociations'):
for association in product.HasAssociations:
if association.is_a('IfcRelAssociatesMaterial'):
material = association.RelatingMaterial
if material.is_a('IfcMaterial'):
info["material_name"] = material.Name
info["material_category"] = getattr(material, 'Category', None)
elif material.is_a('IfcMaterialLayerSetUsage'):
layer_set = material.ForLayerSet
if layer_set.MaterialLayers:
# Use the primary layer material
primary_material = layer_set.MaterialLayers[0].Material
info["material_name"] = primary_material.Name
except Exception as e:
logger.debug(f"Failed to extract material info: {e}")
return info
def _extract_properties(self, product) -> Dict[str, Any]:
"""Extract IFC properties"""
properties = {}
try:
if hasattr(product, 'IsDefinedBy'):
for definition in product.IsDefinedBy:
if hasattr(definition, 'RelatingPropertyDefinition'):
prop_def = definition.RelatingPropertyDefinition
if prop_def.is_a('IfcPropertySet'):
for prop in prop_def.HasProperties:
if prop.is_a('IfcPropertySingleValue'):
if prop.NominalValue:
properties[prop.Name] = {
"value": prop.NominalValue.wrappedValue,
"unit": prop.Unit.Name if prop.Unit else None,
"property_set": prop_def.Name
}
except Exception as e:
logger.debug(f"Failed to extract properties: {e}")
return properties
def _extract_quantities(self, product) -> Dict[str, Any]:
"""Extract IFC quantities"""
quantities = {}
try:
if hasattr(product, 'IsDefinedBy'):
for definition in product.IsDefinedBy:
if hasattr(definition, 'RelatingPropertyDefinition'):
prop_def = definition.RelatingPropertyDefinition
if prop_def.is_a('IfcElementQuantity'):
for quantity in prop_def.Quantities:
# Get quantity name for flexible mapping
quantity_name = getattr(quantity, 'Name', '').lower()
if quantity.is_a('IfcQuantityArea'):
quantities["area"] = quantity.AreaValue
elif quantity.is_a('IfcQuantityVolume'):
quantities["volume"] = quantity.VolumeValue
elif quantity.is_a('IfcQuantityLength'):
# Map based on name if available
if 'width' in quantity_name:
quantities["width"] = quantity.LengthValue
elif 'height' in quantity_name or 'depth' in quantity_name:
quantities["height"] = quantity.LengthValue
elif 'perimeter' in quantity_name:
quantities["perimeter"] = quantity.LengthValue
else:
quantities["length"] = quantity.LengthValue
except Exception as e:
logger.debug(f"Failed to extract quantities: {e}")
return quantities
def _extract_classifications(self, product) -> Dict[str, str]:
"""Extract external classifications"""
classifications = {}
try:
if hasattr(product, 'HasAssociations'):
for association in product.HasAssociations:
if association.is_a('IfcRelAssociatesClassification'):
classification = association.RelatingClassification
if hasattr(classification, 'ReferencedSource'):
source = classification.ReferencedSource
if hasattr(source, 'Name'):
classifications[source.Name] = classification.Identification
except Exception as e:
logger.debug(f"Failed to extract classifications: {e}")
return classifications
async def create_search_indexes(self, project_id: int, elements_data: List[Dict[str, Any]]):
"""Create search indexes and embeddings for semantic search"""
try:
logger.info(f"Creating search indexes for project {project_id}")
# This would create:
# 1. Full-text search indexes on element names and properties
# 2. Vector embeddings for semantic search
# 3. Spatial indexes for geometric queries
# Placeholder implementation
logger.info(f"Created search indexes for {len(elements_data)} elements")
except Exception as e:
logger.error(f"Failed to create search indexes: {e}")
# Don't fail the entire processing for search index issues
pass |