# 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 . """ Export intent plugin — CSV, XLSX, JSON, BCF, IFC, and PDF export. Generates file exports in multiple formats for BIM element data, including tabular formats (CSV/XLSX), structured data (JSON), collaboration formats (BCF), native BIM formats (IFC), and reports (PDF). """ import logging import csv import io import json from typing import Dict, List, Any, Optional from datetime import datetime from sqlalchemy.ext.asyncio import AsyncSession from app.models import Project, Element from app.schemas.intent import SingleQueryPlan, SingleQueryResult, MainIntent from app.core.intent_system.base_plugin import BaseIntentPlugin from app.core.intent_system.decorators import sub_intent logger = logging.getLogger(__name__) class ExportIntentPlugin(BaseIntentPlugin): """Plugin for the EXPORT intent — CSV/XLSX/JSON/BCF/IFC/PDF export.""" def __init__(self): super().__init__() self.intent_type = MainIntent.EXPORT self.supported_sub_intents = [ "export.csv", "export.xlsx", "export.json", "export.bcf", "export.ifc", "export.pdf", ] # Default CSV columns for element export self.default_csv_columns = [ "id", "ifc_global_id", "ifc_type", "name", "level_name", "area", "volume", "height", "width", "length", "material_name", "is_load_bearing", "is_external", "fire_rating", "thermal_transmittance", ] # ------------------------------------------------------------------ # Sub-intent handlers # ------------------------------------------------------------------ @sub_intent("export.csv") async def handle_export_csv( self, query_plan: SingleQueryPlan, project: Project, session: AsyncSession, context: Optional[Dict] = None, ) -> SingleQueryResult: """Export elements to CSV format.""" logger.info(f"Exporting elements to CSV for project {project.id}") # Build query query = await self.build_base_query( session=session, project=project, filter_groups=query_plan.filter_groups, scope=query_plan.scope, ) # Execute query result = await session.execute(query) elements = result.scalars().all() if not elements: return self.create_result( query_plan=query_plan, result_text="No elements to export", explanation="No elements match the specified criteria", result_data={"total_elements": 0}, provenance=["database_query"], ) # Generate CSV csv_data = self._generate_csv(elements) # Calculate file size file_size_bytes = len(csv_data.encode("utf-8")) file_size_kb = round(file_size_bytes / 1024, 2) return self.create_result( query_plan=query_plan, result_text=f"CSV export ready: {len(elements)} elements ({file_size_kb} KB)", explanation=( f"Generated CSV file with {len(elements)} elements " f"and {len(self.default_csv_columns)} columns" ), result_data={ "format": "csv", "total_elements": len(elements), "columns": self.default_csv_columns, "file_size_bytes": file_size_bytes, "file_size_kb": file_size_kb, "csv_content": csv_data, "download_ready": True, }, provenance=["database_query", "csv_generation"], elements_processed=len(elements), ) @sub_intent("export.xlsx") async def handle_export_xlsx( self, query_plan: SingleQueryPlan, project: Project, session: AsyncSession, context: Optional[Dict] = None, ) -> SingleQueryResult: """Export elements to Excel (XLSX) format.""" logger.info(f"Exporting elements to XLSX for project {project.id}") # Build query query = await self.build_base_query( session=session, project=project, filter_groups=query_plan.filter_groups, scope=query_plan.scope, ) result = await session.execute(query) elements = result.scalars().all() if not elements: return self.create_result( query_plan=query_plan, result_text="No elements to export", explanation="No elements match the specified criteria", result_data={"total_elements": 0}, provenance=["database_query"], ) # Generate Excel metadata (actual file generation would require openpyxl) xlsx_metadata = self._prepare_xlsx_metadata(elements) return self.create_result( query_plan=query_plan, result_text=f"Excel export ready: {len(elements)} elements", explanation=( f"Prepared Excel workbook with {len(elements)} elements " f"across {xlsx_metadata['sheet_count']} sheets" ), result_data=xlsx_metadata, provenance=["database_query", "xlsx_preparation"], elements_processed=len(elements), limitations=[ "Full XLSX generation requires openpyxl library installation", ], ) @sub_intent("export.json") async def handle_export_json( self, query_plan: SingleQueryPlan, project: Project, session: AsyncSession, context: Optional[Dict] = None, ) -> SingleQueryResult: """Export elements to JSON format.""" logger.info(f"Exporting elements to JSON for project {project.id}") # Build query query = await self.build_base_query( session=session, project=project, filter_groups=query_plan.filter_groups, scope=query_plan.scope, ) result = await session.execute(query) elements = result.scalars().all() if not elements: return self.create_result( query_plan=query_plan, result_text="No elements to export", explanation="No elements match the specified criteria", result_data={"total_elements": 0}, provenance=["database_query"], ) # Generate JSON json_data = self._generate_json(elements) # Calculate file size file_size_bytes = len(json_data.encode("utf-8")) file_size_kb = round(file_size_bytes / 1024, 2) return self.create_result( query_plan=query_plan, result_text=f"JSON export ready: {len(elements)} elements ({file_size_kb} KB)", explanation=( f"Generated JSON with {len(elements)} elements " f"and full property data" ), result_data={ "format": "json", "total_elements": len(elements), "file_size_bytes": file_size_bytes, "file_size_kb": file_size_kb, "json_content": json_data, "download_ready": True, }, provenance=["database_query", "json_generation"], elements_processed=len(elements), ) @sub_intent("export.bcf") async def handle_export_bcf( self, query_plan: SingleQueryPlan, project: Project, session: AsyncSession, context: Optional[Dict] = None, ) -> SingleQueryResult: """Export to BCF (BIM Collaboration Format) for issues.""" logger.info(f"Exporting to BCF for project {project.id}") # Build query query = await self.build_base_query( session=session, project=project, filter_groups=query_plan.filter_groups, scope=query_plan.scope, ) result = await session.execute(query) elements = result.scalars().all() if not elements: return self.create_result( query_plan=query_plan, result_text="No elements to export as BCF issues", explanation="No elements match the specified criteria", result_data={"total_elements": 0}, provenance=["database_query"], ) # Prepare BCF structure bcf_structure = self._prepare_bcf_structure(elements, project) return self.create_result( query_plan=query_plan, result_text=( f"BCF export prepared: {bcf_structure['topic_count']} topics " f"from {len(elements)} elements" ), explanation=( f"BCF 2.1 format with {bcf_structure['topic_count']} topics " f"ready for download" ), result_data=bcf_structure, provenance=["database_query", "bcf_preparation"], elements_processed=len(elements), limitations=["Full BCF ZIP generation requires bcf-xml library"], ) @sub_intent("export.ifc") async def handle_export_ifc( self, query_plan: SingleQueryPlan, project: Project, session: AsyncSession, context: Optional[Dict] = None, ) -> SingleQueryResult: """Export filtered elements to IFC file.""" logger.info(f"Exporting filtered IFC for project {project.id}") # Build query query = await self.build_base_query( session=session, project=project, filter_groups=query_plan.filter_groups, scope=query_plan.scope, ) result = await session.execute(query) elements = result.scalars().all() if not elements: return self.create_result( query_plan=query_plan, result_text="No elements to export to IFC", explanation="No elements match the specified criteria", result_data={"total_elements": 0}, provenance=["database_query"], ) # Prepare IFC export metadata ifc_metadata = self._prepare_ifc_export(elements, project) return self.create_result( query_plan=query_plan, result_text=f"IFC export prepared: {len(elements)} elements", explanation=( f"Filtered IFC with {len(elements)} elements " f"from {ifc_metadata['total_types']} types" ), result_data=ifc_metadata, provenance=["database_query", "ifc_filter_preparation"], elements_processed=len(elements), limitations=[ "Full IFC file generation requires ifcopenshell library " "and source IFC access", ], ) @sub_intent("export.pdf") async def handle_export_pdf( self, query_plan: SingleQueryPlan, project: Project, session: AsyncSession, context: Optional[Dict] = None, ) -> SingleQueryResult: """Generate PDF report for elements.""" logger.info(f"Generating PDF report for project {project.id}") # Build query query = await self.build_base_query( session=session, project=project, filter_groups=query_plan.filter_groups, scope=query_plan.scope, ) result = await session.execute(query) elements = result.scalars().all() if not elements: return self.create_result( query_plan=query_plan, result_text="No elements for PDF report", explanation="No elements match the specified criteria", result_data={"total_elements": 0}, provenance=["database_query"], ) # Prepare PDF report structure pdf_structure = self._prepare_pdf_report(elements, project) return self.create_result( query_plan=query_plan, result_text=f"PDF report prepared: {len(elements)} elements", explanation=( f"PDF report with {pdf_structure['page_count']} pages " f"covering {len(elements)} elements" ), result_data=pdf_structure, provenance=["database_query", "pdf_preparation"], elements_processed=len(elements), limitations=["Full PDF generation requires reportlab library"], ) # ------------------------------------------------------------------ # Helper methods # ------------------------------------------------------------------ def _generate_csv(self, elements: List[Element]) -> str: """Generate CSV content from elements.""" output = io.StringIO() writer = csv.DictWriter(output, fieldnames=self.default_csv_columns) # Write header writer.writeheader() # Write rows for element in elements: row = {} for col in self.default_csv_columns: value = getattr(element, col, None) if value is None: row[col] = "" elif isinstance(value, (int, float, bool)): row[col] = str(value) else: row[col] = str(value) writer.writerow(row) csv_content = output.getvalue() output.close() return csv_content def _prepare_xlsx_metadata(self, elements: List[Element]) -> Dict[str, Any]: """Prepare Excel workbook metadata.""" # Group elements by type for multiple sheets by_type: Dict[str, list] = {} for element in elements: ifc_type = element.ifc_type if ifc_type not in by_type: by_type[ifc_type] = [] by_type[ifc_type].append(element) sheets = [] for ifc_type, type_elements in by_type.items(): sheets.append( { "name": ifc_type, "row_count": len(type_elements), "columns": self.default_csv_columns, } ) return { "format": "xlsx", "total_elements": len(elements), "sheet_count": len(sheets), "sheets": sheets, "workbook_name": ( f"elements_export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx" ), "download_ready": False, "requires_library": "openpyxl", } def _generate_json(self, elements: List[Element]) -> str: """Generate JSON content from elements.""" elements_data = [] for element in elements: elem_dict = { "id": element.id, "ifc_global_id": element.ifc_global_id, "ifc_type": element.ifc_type, "name": element.name, "level_name": element.level_name, "measurements": { "area": element.area, "volume": element.volume, "height": element.height, "width": element.width, "length": element.length, "perimeter": element.perimeter, }, "properties": element.properties if element.properties else {}, "quantities": element.quantities if element.quantities else {}, "material_name": element.material_name, "is_load_bearing": element.is_load_bearing, "is_external": element.is_external, "fire_rating": element.fire_rating, "thermal_transmittance": element.thermal_transmittance, "classifications": ( element.classifications if element.classifications else {} ), } elements_data.append(elem_dict) json_output = { "export_metadata": { "timestamp": datetime.now().isoformat(), "total_elements": len(elements), "format": "json", }, "elements": elements_data, } return json.dumps(json_output, indent=2, ensure_ascii=False) def _prepare_bcf_structure( self, elements: List[Element], project: Project ) -> Dict[str, Any]: """Prepare BCF (BIM Collaboration Format) structure.""" topics = [] for element in elements[:50]: # Limit to 50 topics for performance topic = { "guid": f"bcf-{element.ifc_global_id}", "title": f"Element: {element.name or element.ifc_type}", "description": ( f"Type: {element.ifc_type}, " f"Level: {element.level_name or 'Unknown'}" ), "topic_type": "Info", "topic_status": "Open", "priority": "Normal", "assigned_to": None, "creation_date": datetime.now().isoformat(), "creation_author": "BIM Query", "labels": [element.ifc_type], "related_topics": [], "reference_links": [], "viewpoint": { "guid": f"view-{element.ifc_global_id}", "components": { "selection": [element.ifc_global_id], }, }, } topics.append(topic) return { "format": "bcf", "version": "2.1", "topic_count": len(topics), "topics": topics, "project_info": { "project_id": str(project.id), "project_name": project.name, }, "markup_files": len(topics), "download_ready": False, "requires_library": "bcf-xml or custom BCF generation", } def _prepare_ifc_export( self, elements: List[Element], project: Project ) -> Dict[str, Any]: """Prepare IFC export metadata.""" type_counts: Dict[str, int] = {} for element in elements: ifc_type = element.ifc_type type_counts[ifc_type] = type_counts.get(ifc_type, 0) + 1 return { "format": "ifc", "schema": "IFC4", "total_elements": len(elements), "total_types": len(type_counts), "type_distribution": type_counts, "project_info": { "project_id": str(project.id), "project_name": project.name, }, "element_guids": [e.ifc_global_id for e in elements[:100]], # Sample "file_name": ( f"filtered_export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.ifc" ), "download_ready": False, "requires_library": "ifcopenshell and source IFC file access", } def _prepare_pdf_report( self, elements: List[Element], project: Project ) -> Dict[str, Any]: """Prepare PDF report structure.""" elements_per_page = 10 page_count = (len(elements) // elements_per_page) + ( 1 if len(elements) % elements_per_page > 0 else 0 ) page_count += 2 # Cover page + summary page # Group by type for summary by_type: Dict[str, int] = {} for element in elements: ifc_type = element.ifc_type by_type[ifc_type] = by_type.get(ifc_type, 0) + 1 return { "format": "pdf", "total_elements": len(elements), "page_count": page_count, "sections": [ {"name": "Cover Page", "page": 1}, { "name": "Summary", "page": 2, "content": { "total_elements": len(elements), "type_distribution": by_type, }, }, { "name": "Element Details", "page_start": 3, "page_end": page_count, "elements_per_page": elements_per_page, }, ], "project_info": { "project_id": str(project.id), "project_name": project.name, "export_date": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), }, "file_name": ( f"elements_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf" ), "download_ready": False, "requires_library": "reportlab", }