Spaces:
Runtime error

bimquery-api / app /intents /select /handler.py
BIM Query Deploy
Claude Opus 4.7 (1M context)
deploy: initial BIM Query API on Hugging Face Spaces
e6be672
Raw History Blame Contribute Delete
28.3 kB
# 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/>.
"""
Select intent plugin — selects and highlights BIM elements for 3D visualization.
Returns element IDs and GUIDs that the viewer can use to highlight matching
elements by type, property, condition, spatial location, material, size range,
or compliance status.
"""
import logging
from typing import Dict, List, Any, Optional
from datetime import datetime
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, and_, or_, func
from app.models import Project, Element
from app.schemas.intent import (
SingleQueryPlan, SingleQueryResult, MainIntent,
PresentationFormat,
)
from app.core.intent_system.base_plugin import BaseIntentPlugin
from app.core.intent_system.decorators import sub_intent
from app.services.element_cache_service import element_cache_service
logger = logging.getLogger(__name__)
class SelectIntentPlugin(BaseIntentPlugin):
"""Plugin for the SELECT intent — returns element IDs for visualization."""
def __init__(self):
super().__init__()
self.intent_type = MainIntent.SELECT
self.supported_sub_intents = [
"by_type",
"by_property",
"by_condition",
"by_spatial_location",
"by_material",
"by_size_range",
"by_compliance_status",
"by_completeness",
"by_assembly",
"outliers",
]
# ------------------------------------------------------------------
# Sub-intent handlers
# ------------------------------------------------------------------
@sub_intent("select.by_type")
async def handle_by_type(
self,
query_plan: SingleQueryPlan,
project: Project,
session: AsyncSession,
context: Optional[Dict] = None,
) -> SingleQueryResult:
"""Select elements by IFC type for visualization — optimized with caching."""
# Use optimized cached element selection service
element_tuples = await element_cache_service.get_or_compute_element_ids(
session=session,
project_id=project.id,
filter_groups=query_plan.filter_groups,
use_cache=True,
limit=1000, # Reasonable limit for visualization
)
# Extract IDs and GUIDs
element_ids = [str(elem_tuple[0]) for elem_tuple in element_tuples]
element_guids = [
elem_tuple[1] for elem_tuple in element_tuples if elem_tuple[1]
]
count = len(element_tuples)
# Get IFC type from filters
ifc_type = query_plan.filter_groups.get("ifc_type", "elements")
element_type_name = self._get_element_type_name(ifc_type)
return self.create_result(
query_plan=query_plan,
result_text=f"Selected {count} {element_type_name} for visualization",
explanation=(
f"Found {count} elements of type {element_type_name} to highlight "
f"in the 3D viewer using optimized cache-aware query"
),
provenance=element_ids[:20], # Limit provenance for performance
result_data={
"element_ids": element_ids,
"element_guids": element_guids,
"count": count,
"selection_type": "by_type",
"ifc_type": ifc_type,
"element_type_name": element_type_name,
"cache_optimized": True,
},
processing_steps=[
"optimized_id_query",
"cache_lookup",
"element_selection",
],
elements_processed=count,
)
@sub_intent("select.by_property")
async def handle_by_property(
self,
query_plan: SingleQueryPlan,
project: Project,
session: AsyncSession,
context: Optional[Dict] = None,
) -> SingleQueryResult:
"""Select elements by specific properties."""
query = await self.build_base_query(
session=session,
project=project,
filter_groups=query_plan.filter_groups,
scope=query_plan.scope,
)
# Get elements with common properties for better response synthesis
result = await session.execute(query)
elements = result.scalars().all()
# Extract IDs and build detailed result with properties
element_ids = [str(elem.id) for elem in elements]
element_guids = [
elem.ifc_global_id for elem in elements if elem.ifc_global_id
]
count = len(elements)
# Build detailed element data with properties
elements_data = []
for elem in elements[:100]: # Limit to 100 for performance
elem_data = {
"id": elem.ifc_global_id or str(elem.id),
"name": elem.name,
"type": elem.ifc_type,
}
# Add geometric properties if available
if elem.height:
elem_data["height_m"] = round(elem.height, 2)
if elem.width:
elem_data["width_m"] = round(elem.width, 2)
if elem.length:
elem_data["length_m"] = round(elem.length, 2)
if elem.area:
elem_data["area_m2"] = round(elem.area, 2)
if elem.volume:
elem_data["volume_m3"] = round(elem.volume, 3)
if elem.level_name:
elem_data["level"] = elem.level_name
elements_data.append(elem_data)
# Generate descriptive text based on filters
filter_desc = self._describe_filters(query_plan.filter_groups)
return self.create_result(
query_plan=query_plan,
result_text=f"Selected {count} elements with properties: {filter_desc}",
explanation=f"Found {count} elements matching the specified property criteria",
provenance=element_ids[:20],
result_data={
"elements": elements_data,
"element_ids": element_ids,
"element_guids": element_guids,
"count": count,
"selection_type": "by_property",
"filters": query_plan.filter_groups,
"showing": len(elements_data),
},
elements_processed=count,
)
@sub_intent("select.by_condition")
async def handle_by_condition(
self,
query_plan: SingleQueryPlan,
project: Project,
session: AsyncSession,
context: Optional[Dict] = None,
) -> SingleQueryResult:
"""Select elements meeting specific conditions (e.g., area < 1m2)."""
query = await self.build_base_query(
session=session,
project=project,
filter_groups=query_plan.filter_groups,
scope=query_plan.scope,
)
# Get element IDs with relevant data for condition description
query = query.with_only_columns(
Element.id, Element.ifc_global_id, Element.ifc_type, Element.area
)
result = await session.execute(query)
elements = result.all()
# Extract IDs
element_ids = [str(elem.id) for elem in elements]
element_guids = [
elem.ifc_global_id for elem in elements if elem.ifc_global_id
]
count = len(elements)
# Build condition description
condition_desc = self._describe_conditions(query_plan.filter_groups)
ifc_type = query_plan.filter_groups.get("ifc_type", "elements")
return self.create_result(
query_plan=query_plan,
result_text=f"Selected {count} {ifc_type} meeting condition: {condition_desc}",
explanation=f"Found {count} elements that satisfy the specified conditions",
provenance=element_ids,
result_data={
"element_ids": element_ids,
"element_guids": element_guids,
"count": count,
"selection_type": "by_condition",
"condition": condition_desc,
"filters": query_plan.filter_groups,
},
elements_processed=count,
)
@sub_intent("select.by_spatial_location")
async def handle_by_spatial_location(
self,
query_plan: SingleQueryPlan,
project: Project,
session: AsyncSession,
context: Optional[Dict] = None,
) -> SingleQueryResult:
"""Select elements in specific spatial locations."""
query = await self.build_base_query(
session=session,
project=project,
filter_groups=query_plan.filter_groups,
scope=query_plan.scope,
)
# Get element IDs
query = query.with_only_columns(
Element.id, Element.ifc_global_id, Element.level_name
)
result = await session.execute(query)
elements = result.all()
element_ids = [str(elem.id) for elem in elements]
element_guids = [
elem.ifc_global_id for elem in elements if elem.ifc_global_id
]
count = len(elements)
# Get spatial context
spatial_desc = query_plan.filter_groups.get(
"building_story", "specified location"
)
return self.create_result(
query_plan=query_plan,
result_text=f"Selected {count} elements in {spatial_desc}",
explanation=f"Found {count} elements in the specified spatial location",
provenance=element_ids,
result_data={
"element_ids": element_ids,
"element_guids": element_guids,
"count": count,
"selection_type": "by_spatial_location",
"location": spatial_desc,
},
elements_processed=count,
)
@sub_intent("select.by_material")
async def handle_by_material(
self,
query_plan: SingleQueryPlan,
project: Project,
session: AsyncSession,
context: Optional[Dict] = None,
) -> SingleQueryResult:
"""Select elements by material type."""
query = await self.build_base_query(
session=session,
project=project,
filter_groups=query_plan.filter_groups,
scope=query_plan.scope,
)
# Get element IDs
query = query.with_only_columns(
Element.id, Element.ifc_global_id, Element.material_name
)
result = await session.execute(query)
elements = result.all()
element_ids = [str(elem.id) for elem in elements]
element_guids = [
elem.ifc_global_id for elem in elements if elem.ifc_global_id
]
count = len(elements)
# Get material info
material = query_plan.filter_groups.get("material", "specified material")
return self.create_result(
query_plan=query_plan,
result_text=f"Selected {count} elements with material: {material}",
explanation=f"Found {count} elements made of {material}",
provenance=element_ids,
result_data={
"element_ids": element_ids,
"element_guids": element_guids,
"count": count,
"selection_type": "by_material",
"material": material,
},
elements_processed=count,
)
@sub_intent("select.by_size_range")
async def handle_by_size_range(
self,
query_plan: SingleQueryPlan,
project: Project,
session: AsyncSession,
context: Optional[Dict] = None,
) -> SingleQueryResult:
"""Select elements within specific size ranges."""
query = await self.build_base_query(
session=session,
project=project,
filter_groups=query_plan.filter_groups,
scope=query_plan.scope,
)
# Get element IDs
query = query.with_only_columns(
Element.id, Element.ifc_global_id, Element.area, Element.volume
)
result = await session.execute(query)
elements = result.all()
element_ids = [str(elem.id) for elem in elements]
element_guids = [
elem.ifc_global_id for elem in elements if elem.ifc_global_id
]
count = len(elements)
# Describe size range
size_desc = self._describe_size_range(query_plan.filter_groups)
return self.create_result(
query_plan=query_plan,
result_text=f"Selected {count} elements within size range: {size_desc}",
explanation=f"Found {count} elements matching the specified size criteria",
provenance=element_ids,
result_data={
"element_ids": element_ids,
"element_guids": element_guids,
"count": count,
"selection_type": "by_size_range",
"size_criteria": size_desc,
},
elements_processed=count,
)
@sub_intent("select.by_compliance_status")
async def handle_by_compliance_status(
self,
query_plan: SingleQueryPlan,
project: Project,
session: AsyncSession,
context: Optional[Dict] = None,
) -> SingleQueryResult:
"""Select elements based on compliance status."""
query = await self.build_base_query(
session=session,
project=project,
filter_groups=query_plan.filter_groups,
scope=query_plan.scope,
)
# Get element IDs
query = query.with_only_columns(
Element.id, Element.ifc_global_id, Element.fire_rating
)
result = await session.execute(query)
elements = result.all()
element_ids = [str(elem.id) for elem in elements]
element_guids = [
elem.ifc_global_id for elem in elements if elem.ifc_global_id
]
count = len(elements)
# Describe compliance status
compliance_desc = query_plan.filter_groups.get(
"compliance_status", "specified compliance criteria"
)
return self.create_result(
query_plan=query_plan,
result_text=f"Selected {count} elements based on compliance: {compliance_desc}",
explanation=f"Found {count} elements matching compliance criteria",
provenance=element_ids,
result_data={
"element_ids": element_ids,
"element_guids": element_guids,
"count": count,
"selection_type": "by_compliance_status",
"compliance_criteria": compliance_desc,
},
elements_processed=count,
)
# ------------------------------------------------------------------
# Private helper methods
# ------------------------------------------------------------------
def _describe_filters(self, filters: Dict[str, Any]) -> str:
"""Generate human-readable description of filters."""
descriptions = []
if "ifc_type" in filters:
descriptions.append(f"type={filters['ifc_type']}")
if "building_story" in filters:
descriptions.append(f"floor={filters['building_story']}")
if "material" in filters:
descriptions.append(f"material={filters['material']}")
if "is_external" in filters:
descriptions.append(f"external={filters['is_external']}")
if "is_load_bearing" in filters:
descriptions.append(f"load-bearing={filters['is_load_bearing']}")
return ", ".join(descriptions) if descriptions else "specified criteria"
def _describe_conditions(self, filters: Dict[str, Any]) -> str:
"""Generate human-readable description of conditions."""
conditions = []
for field in ["area", "volume", "height", "width", "length"]:
if field in filters:
field_filter = filters[field]
if isinstance(field_filter, dict):
if "$lt" in field_filter:
conditions.append(f"{field} < {field_filter['$lt']}")
elif "$lte" in field_filter:
conditions.append(f"{field} \u2264 {field_filter['$lte']}")
elif "$gt" in field_filter:
conditions.append(f"{field} > {field_filter['$gt']}")
elif "$gte" in field_filter:
conditions.append(f"{field} \u2265 {field_filter['$gte']}")
return " and ".join(conditions) if conditions else "specified conditions"
def _describe_size_range(self, filters: Dict[str, Any]) -> str:
"""Generate human-readable description of size range."""
descriptions = []
if "area" in filters:
area_filter = filters["area"]
if isinstance(area_filter, dict):
if "$lt" in area_filter:
descriptions.append(f"area < {area_filter['$lt']}m\u00b2")
elif "$gt" in area_filter:
descriptions.append(f"area > {area_filter['$gt']}m\u00b2")
if "volume" in filters:
vol_filter = filters["volume"]
if isinstance(vol_filter, dict):
if "$lt" in vol_filter:
descriptions.append(f"volume < {vol_filter['$lt']}m\u00b3")
elif "$gt" in vol_filter:
descriptions.append(f"volume > {vol_filter['$gt']}m\u00b3")
return ", ".join(descriptions) if descriptions else "specified size range"
# ------------------------------------------------------------------
# New sub-intents: completeness, assembly, outliers
# ------------------------------------------------------------------
@sub_intent("select.by_completeness")
async def handle_by_completeness(
self,
query_plan: SingleQueryPlan,
project: Project,
session: AsyncSession,
context: Optional[Dict] = None,
) -> SingleQueryResult:
"""Select elements by data completeness status for viewer highlighting."""
logger.info(f"Selecting elements by completeness for project {project.id}")
fragment = (query_plan.query_fragment or "").lower()
# Determine completeness filter
if any(w in fragment for w in ["complet", "tutti i dati", "all data"]):
condition = and_(
Element.has_geometry == True,
Element.has_properties == True,
Element.has_materials == True,
)
desc = "complete elements (geometry + properties + materials)"
elif any(w in fragment for w in ["geometr", "geometry"]):
if any(w in fragment for w in ["senza", "without", "missing", "no "]):
condition = Element.has_geometry == False
desc = "elements without geometry"
else:
condition = Element.has_geometry == True
desc = "elements with geometry"
elif any(w in fragment for w in ["material", "materiali"]):
if any(w in fragment for w in ["senza", "without", "missing", "no "]):
condition = Element.has_materials == False
desc = "elements without materials"
else:
condition = Element.has_materials == True
desc = "elements with materials"
elif any(w in fragment for w in ["propriet", "propert"]):
if any(w in fragment for w in ["senza", "without", "missing", "no "]):
condition = Element.has_properties == False
desc = "elements without properties"
else:
condition = Element.has_properties == True
desc = "elements with properties"
else:
# Default: select incomplete elements
condition = or_(
Element.has_geometry == False,
Element.has_properties == False,
Element.has_materials == False,
)
desc = "incomplete elements"
query = (
select(Element.id, Element.ifc_global_id, Element.name, Element.ifc_type)
.where(and_(Element.project_id == project.id, condition))
.order_by(Element.ifc_type, Element.name)
.limit(500)
)
result = await session.execute(query)
rows = result.all()
element_ids = [r.ifc_global_id for r in rows]
return self.create_result(
query_plan=query_plan,
result_text=f"Selected {len(rows)} {desc}",
confidence=0.95,
explanation=f"Filtered by completeness flags: {desc}",
provenance=element_ids[:20],
result_data={
"selected_ids": element_ids,
"count": len(rows),
"description": desc,
},
processing_steps=["completeness_filter", "id_extraction"],
elements_processed=len(rows),
)
@sub_intent("select.by_assembly")
async def handle_by_assembly(
self,
query_plan: SingleQueryPlan,
project: Project,
session: AsyncSession,
context: Optional[Dict] = None,
) -> SingleQueryResult:
"""Select elements belonging to an assembly or parent for viewer highlighting."""
logger.info(f"Selecting elements by assembly for project {project.id}")
# Check for assembly_id or parent_element_id in filters
assembly_id = self._get_filter_value(query_plan.filter_groups, "assembly_id")
parent_id = self._get_filter_value(query_plan.filter_groups, "parent_element_id")
if assembly_id:
condition = Element.assembly_id == assembly_id
desc = f"assembly {assembly_id}"
elif parent_id:
condition = Element.parent_element_id == parent_id
desc = f"children of element {parent_id}"
else:
# Select all elements that belong to any assembly
condition = Element.assembly_id.is_not(None)
desc = "all assembled elements"
query = (
select(Element.id, Element.ifc_global_id, Element.name, Element.ifc_type)
.where(and_(Element.project_id == project.id, condition))
.order_by(Element.ifc_type, Element.name)
.limit(500)
)
result = await session.execute(query)
rows = result.all()
element_ids = [r.ifc_global_id for r in rows]
return self.create_result(
query_plan=query_plan,
result_text=f"Selected {len(rows)} elements ({desc})",
confidence=0.95,
explanation=f"Assembly-based selection: {desc}",
provenance=element_ids[:20],
result_data={
"selected_ids": element_ids,
"count": len(rows),
"description": desc,
},
processing_steps=["assembly_filter", "id_extraction"],
elements_processed=len(rows),
)
@sub_intent("select.outliers")
async def handle_outliers(
self,
query_plan: SingleQueryPlan,
project: Project,
session: AsyncSession,
context: Optional[Dict] = None,
) -> SingleQueryResult:
"""Select elements with anomalous dimensions (beyond 2 standard deviations)."""
logger.info(f"Selecting outlier elements for project {project.id}")
# Detect which field to check — default to area
fragment = (query_plan.query_fragment or "").lower()
if any(w in fragment for w in ["volume", "volum"]):
col = Element.volume
field_name = "volume"
elif any(w in fragment for w in ["height", "altezza", "alto", "alt"]):
col = Element.height
field_name = "height"
elif any(w in fragment for w in ["length", "lunghezza", "lung"]):
col = Element.length
field_name = "length"
elif any(w in fragment for w in ["width", "larghezza", "larg"]):
col = Element.width
field_name = "width"
else:
col = Element.area
field_name = "area"
unit = self.get_unit_for_field(field_name, project)
# Calculate stats per ifc_type
stats_query = (
select(
Element.ifc_type,
func.avg(col).label("avg_val"),
func.stddev(col).label("stddev_val"),
)
.where(and_(Element.project_id == project.id, col.is_not(None)))
.group_by(Element.ifc_type)
.having(func.stddev(col) > 0)
)
stats_result = await session.execute(stats_query)
type_stats = {r.ifc_type: (float(r.avg_val), float(r.stddev_val)) for r in stats_result.all()}
if not type_stats:
return self.create_result(
query_plan=query_plan,
result_text=f"No outliers found — insufficient data for {field_name} analysis",
confidence=0.9,
explanation="Not enough data to compute standard deviation",
result_data={"outliers": [], "field": field_name},
provenance=[],
processing_steps=["stats_calculation"],
)
# Find outliers: elements beyond ±2 stddev from their type's mean
outlier_conditions = []
for ifc_type, (avg, stddev) in type_stats.items():
lower = avg - 2 * stddev
upper = avg + 2 * stddev
outlier_conditions.append(
and_(
Element.ifc_type == ifc_type,
or_(col < lower, col > upper),
)
)
query = (
select(Element.id, Element.ifc_global_id, Element.name, Element.ifc_type, col.label("value"))
.where(
and_(
Element.project_id == project.id,
col.is_not(None),
or_(*outlier_conditions),
)
)
.order_by(col.desc())
.limit(500)
)
result = await session.execute(query)
rows = result.all()
element_ids = [r.ifc_global_id for r in rows]
outlier_data = [
{
"id": r.ifc_global_id,
"name": r.name,
"type": r.ifc_type,
"value": round(float(r.value), 2) if r.value else None,
"unit": unit,
}
for r in rows[:50]
]
return self.create_result(
query_plan=query_plan,
result_text=f"Found {len(rows)} outlier elements by {field_name} (±2σ from type mean)",
confidence=0.90,
explanation=f"Elements with {field_name} beyond 2 standard deviations from their type average",
provenance=element_ids[:20],
result_data={
"selected_ids": element_ids,
"count": len(rows),
"field": field_name,
"unit": unit,
"outliers": outlier_data,
"type_stats": {k: {"mean": round(v[0], 2), "stddev": round(v[1], 2)} for k, v in type_stats.items()},
},
processing_steps=["stats_per_type", "outlier_detection", "id_extraction"],
elements_processed=len(rows),
)