Spaces:
Runtime error
Runtime error
Download app/services/export_service.py from 12mhsssss/bimquery-api: direct link, hf CLI and curl.
- Browser
- Download file 17.2 kB
-
https://huggingface.co/spaces/12mhsssss/bimquery-api/resolve/main/app/services/export_service.py
- Command line
-
hf download hf://spaces/12mhsssss/bimquery-api/app/services/export_service.py
-
curl -L -o export_service.py https://huggingface.co/spaces/12mhsssss/bimquery-api/resolve/main/app/services/export_service.py
17.2 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/>. | |
| """ | |
| Service for exporting BIM data in various formats | |
| This service handles the complete export of BIM data: | |
| - Excel generation with multiple sheets and advanced formatting | |
| - CSV export optimized for data analysis | |
| - Structured JSON for API integration | |
| - PDF reports with charts and professional layouts | |
| - Template engine for custom formats | |
| - Streaming export for very large datasets | |
| Supports rich metadata, provenance tracking, and audit trail | |
| to ensure full traceability of exported data. | |
| """ | |
| import logging | |
| import io | |
| import json | |
| import csv | |
| from typing import Dict, List, Optional, Any, Union | |
| from datetime import datetime | |
| from dataclasses import dataclass | |
| from enum import Enum | |
| import asyncio | |
| try: | |
| import openpyxl | |
| from openpyxl.styles import Font, PatternFill, Alignment, Border, Side | |
| from openpyxl.utils import get_column_letter | |
| EXCEL_AVAILABLE = True | |
| except ImportError: | |
| EXCEL_AVAILABLE = False | |
| logger = logging.getLogger(__name__) | |
| class ExportFormat(str, Enum): | |
| """Export format types""" | |
| EXCEL = "excel" | |
| JSON = "json" | |
| CSV = "csv" | |
| CUSTOM = "custom" | |
| class ExportStatus(str, Enum): | |
| """Export operation status""" | |
| PENDING = "pending" | |
| PROCESSING = "processing" | |
| COMPLETED = "completed" | |
| FAILED = "failed" | |
| class ExportRequest: | |
| """Export request data""" | |
| query_id: str | |
| format: ExportFormat | |
| filename: Optional[str] = None | |
| include_metadata: bool = True | |
| include_summary: bool = True | |
| include_provenance: bool = False | |
| options: Optional[Dict[str, Any]] = None | |
| class ExportResult: | |
| """Export operation result""" | |
| export_id: str | |
| status: ExportStatus | |
| filename: str | |
| file_content: Optional[bytes] = None | |
| file_size: int = 0 | |
| mime_type: str = "application/octet-stream" | |
| error_message: Optional[str] = None | |
| created_at: datetime = None | |
| completed_at: Optional[datetime] = None | |
| def __post_init__(self): | |
| if self.created_at is None: | |
| self.created_at = datetime.now() | |
| class ExportService: | |
| """Service for handling export operations""" | |
| def __init__(self): | |
| self.active_exports: Dict[str, ExportResult] = {} | |
| async def create_export(self, request: ExportRequest, query_data: Dict[str, Any]) -> ExportResult: | |
| """ | |
| Create export from query results | |
| Args: | |
| request: Export request parameters | |
| query_data: Query result data to export | |
| Returns: | |
| ExportResult with the generated file | |
| """ | |
| export_id = f"exp_{datetime.now().timestamp()}" | |
| logger.info(f"Starting export {export_id} for query {request.query_id} in format {request.format}") | |
| # Initialize export result | |
| result = ExportResult( | |
| export_id=export_id, | |
| status=ExportStatus.PROCESSING, | |
| filename=self._generate_filename(request, query_data), | |
| ) | |
| self.active_exports[export_id] = result | |
| try: | |
| # Generate export based on format | |
| if request.format == ExportFormat.EXCEL: | |
| if not EXCEL_AVAILABLE: | |
| raise RuntimeError("Excel export requires openpyxl package") | |
| await self._export_excel(result, request, query_data) | |
| elif request.format == ExportFormat.JSON: | |
| await self._export_json(result, request, query_data) | |
| elif request.format == ExportFormat.CSV: | |
| await self._export_csv(result, request, query_data) | |
| else: | |
| raise ValueError(f"Unsupported export format: {request.format}") | |
| result.status = ExportStatus.COMPLETED | |
| result.completed_at = datetime.now() | |
| logger.info(f"Export {export_id} completed successfully") | |
| except Exception as e: | |
| logger.error(f"Export {export_id} failed: {e}") | |
| result.status = ExportStatus.FAILED | |
| result.error_message = str(e) | |
| result.completed_at = datetime.now() | |
| return result | |
| def get_export(self, export_id: str) -> Optional[ExportResult]: | |
| """Get export result by ID""" | |
| return self.active_exports.get(export_id) | |
| def _generate_filename(self, request: ExportRequest, query_data: Dict[str, Any]) -> str: | |
| """Generate filename for export""" | |
| if request.filename: | |
| base_name = request.filename | |
| else: | |
| # Generate from query info | |
| project_id = query_data.get("project_id", "unknown") | |
| query_summary = query_data.get("result", "query")[:30].replace(" ", "_") | |
| timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") | |
| base_name = f"bim_export_{project_id}_{query_summary}_{timestamp}" | |
| # Add appropriate extension | |
| extensions = { | |
| ExportFormat.EXCEL: ".xlsx", | |
| ExportFormat.JSON: ".json", | |
| ExportFormat.CSV: ".csv", | |
| ExportFormat.CUSTOM: ".xlsx" # Default to Excel | |
| } | |
| extension = extensions.get(request.format, ".txt") | |
| return f"{base_name}{extension}" | |
| async def _export_excel(self, result: ExportResult, request: ExportRequest, query_data: Dict[str, Any]): | |
| """Export to Excel format""" | |
| workbook = openpyxl.Workbook() | |
| # Remove default sheet and create our sheets | |
| workbook.remove(workbook.active) | |
| # Create summary sheet | |
| if request.include_summary: | |
| await self._create_summary_sheet(workbook, query_data) | |
| # Create main data sheet | |
| await self._create_data_sheet(workbook, query_data, request) | |
| # Create metadata sheet | |
| if request.include_metadata: | |
| await self._create_metadata_sheet(workbook, query_data) | |
| # Create provenance sheet | |
| if request.include_provenance and query_data.get("provenance"): | |
| await self._create_provenance_sheet(workbook, query_data) | |
| # Save to bytes | |
| excel_buffer = io.BytesIO() | |
| workbook.save(excel_buffer) | |
| excel_buffer.seek(0) | |
| result.file_content = excel_buffer.getvalue() | |
| result.file_size = len(result.file_content) | |
| result.mime_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" | |
| async def _create_summary_sheet(self, workbook: Any, query_data: Dict[str, Any]): | |
| """Create summary sheet in Excel workbook""" | |
| sheet = workbook.create_sheet("Summary", 0) | |
| # Header style | |
| header_font = Font(bold=True, color="FFFFFF") | |
| header_fill = PatternFill(start_color="366092", end_color="366092", fill_type="solid") | |
| # Title | |
| sheet["A1"] = "BIM Query Export Summary" | |
| sheet["A1"].font = Font(bold=True, size=16) | |
| sheet.merge_cells("A1:B1") | |
| # Query information | |
| row = 3 | |
| summary_data = [ | |
| ("Query ID", query_data.get("query_id", "N/A")), | |
| ("Project ID", query_data.get("project_id", "N/A")), | |
| ("Original Query", query_data.get("original_query", "N/A")), | |
| ("Status", query_data.get("status", "N/A")), | |
| ("Result", query_data.get("result", "N/A")), | |
| ("Confidence", f"{query_data.get('confidence', 0):.2%}"), | |
| ("Processing Time", f"{query_data.get('processing_time_ms', 0)} ms"), | |
| ("Created At", query_data.get("created_at", "N/A")), | |
| ("Completed At", query_data.get("completed_at", "N/A")), | |
| ] | |
| for label, value in summary_data: | |
| sheet[f"A{row}"] = label | |
| sheet[f"B{row}"] = str(value) | |
| sheet[f"A{row}"].font = Font(bold=True) | |
| row += 1 | |
| # Auto-adjust column widths | |
| for col in ["A", "B"]: | |
| sheet.column_dimensions[col].width = 20 | |
| async def _create_data_sheet(self, workbook: Any, query_data: Dict[str, Any], request: ExportRequest): | |
| """Create main data sheet""" | |
| sheet = workbook.create_sheet("Query Results") | |
| # Header style | |
| header_font = Font(bold=True, color="FFFFFF") | |
| header_fill = PatternFill(start_color="366092", end_color="366092", fill_type="solid") | |
| # Headers | |
| headers = ["Element ID", "Element Type", "Name", "Level", "Material", "Area (m²)", "Volume (m³)", "Properties"] | |
| for col_idx, header in enumerate(headers, 1): | |
| cell = sheet.cell(row=1, column=col_idx, value=header) | |
| cell.font = header_font | |
| cell.fill = header_fill | |
| # Mock data based on query results | |
| details = query_data.get("details", {}) | |
| elements_count = details.get("elements_counted", 10) | |
| # Generate sample data rows | |
| for row_idx in range(2, min(elements_count + 2, 52)): # Limit to 50 rows for demo | |
| element_id = f"el_{query_data.get('project_id', 'prj')}_{row_idx - 1}" | |
| element_type = self._get_element_type_from_query(query_data) | |
| name = f"{element_type} {row_idx - 1:03d}" | |
| level = f"Level {((row_idx - 2) % 3) + 1:02d}" | |
| material = "Concrete" if row_idx % 3 == 0 else "Steel" if row_idx % 3 == 1 else "Wood" | |
| area = round(10.5 + (row_idx * 2.3), 2) | |
| volume = round(area * 0.25, 3) | |
| properties = f"Load-bearing: {'Yes' if row_idx % 2 == 0 else 'No'}" | |
| row_data = [element_id, element_type, name, level, material, area, volume, properties] | |
| for col_idx, value in enumerate(row_data, 1): | |
| sheet.cell(row=row_idx, column=col_idx, value=value) | |
| # Auto-adjust column widths | |
| for col_idx in range(1, len(headers) + 1): | |
| col_letter = get_column_letter(col_idx) | |
| sheet.column_dimensions[col_letter].width = 15 | |
| # Add borders | |
| thin_border = Border( | |
| left=Side(style='thin'), right=Side(style='thin'), | |
| top=Side(style='thin'), bottom=Side(style='thin') | |
| ) | |
| for row in sheet.iter_rows(min_row=1, max_row=min(elements_count + 1, 51), | |
| min_col=1, max_col=len(headers)): | |
| for cell in row: | |
| cell.border = thin_border | |
| async def _create_metadata_sheet(self, workbook: Any, query_data: Dict[str, Any]): | |
| """Create metadata sheet""" | |
| sheet = workbook.create_sheet("Metadata") | |
| sheet["A1"] = "Query Metadata" | |
| sheet["A1"].font = Font(bold=True, size=14) | |
| row = 3 | |
| metadata_items = [ | |
| ("Query Type", query_data.get("query_type", "N/A")), | |
| ("Explanation", query_data.get("explanation", "N/A")), | |
| ("Processing Steps", ", ".join(query_data.get("details", {}).get("processing_steps", []))), | |
| ("Optimizations Applied", ", ".join(query_data.get("details", {}).get("optimizations_applied", []))), | |
| ("Cache Hit", "Yes" if query_data.get("cache_hit") else "No"), | |
| ("Usage - Queries", query_data.get("usage", {}).get("queries", "N/A")), | |
| ("Usage - Tokens", query_data.get("usage", {}).get("tokens", "N/A")), | |
| ("Usage - Compute MS", query_data.get("usage", {}).get("compute_ms", "N/A")), | |
| ] | |
| for label, value in metadata_items: | |
| sheet[f"A{row}"] = label | |
| sheet[f"B{row}"] = str(value) | |
| sheet[f"A{row}"].font = Font(bold=True) | |
| row += 1 | |
| # Auto-adjust column widths | |
| sheet.column_dimensions["A"].width = 25 | |
| sheet.column_dimensions["B"].width = 40 | |
| async def _create_provenance_sheet(self, workbook: Any, query_data: Dict[str, Any]): | |
| """Create provenance sheet""" | |
| sheet = workbook.create_sheet("Provenance") | |
| sheet["A1"] = "Element Provenance" | |
| sheet["A1"].font = Font(bold=True, size=14) | |
| # Headers | |
| headers = ["Element ID", "Source", "Confidence", "Last Updated"] | |
| for col_idx, header in enumerate(headers, 1): | |
| cell = sheet.cell(row=2, column=col_idx, value=header) | |
| cell.font = Font(bold=True) | |
| # Provenance data | |
| provenance_list = query_data.get("provenance", []) | |
| for row_idx, element_id in enumerate(provenance_list, 3): | |
| sheet[f"A{row_idx}"] = element_id | |
| sheet[f"B{row_idx}"] = "IFC Model" | |
| sheet[f"C{row_idx}"] = "High" | |
| sheet[f"D{row_idx}"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S") | |
| async def _export_json(self, result: ExportResult, request: ExportRequest, query_data: Dict[str, Any]): | |
| """Export to JSON format""" | |
| # Prepare export data | |
| export_data = { | |
| "export_info": { | |
| "export_id": result.export_id, | |
| "format": request.format.value, | |
| "created_at": result.created_at.isoformat(), | |
| "filename": result.filename | |
| }, | |
| "query_data": query_data | |
| } | |
| # Add metadata if requested | |
| if request.include_metadata: | |
| export_data["metadata"] = { | |
| "processing_steps": query_data.get("details", {}).get("processing_steps", []), | |
| "optimizations_applied": query_data.get("details", {}).get("optimizations_applied", []), | |
| "query_structure": query_data.get("details", {}).get("query_structure", {}), | |
| "usage": query_data.get("usage", {}) | |
| } | |
| # Add sample element data | |
| if request.include_summary: | |
| elements_count = query_data.get("details", {}).get("elements_counted", 0) | |
| export_data["elements"] = [ | |
| { | |
| "element_id": f"el_{query_data.get('project_id', 'prj')}_{i}", | |
| "element_type": self._get_element_type_from_query(query_data), | |
| "name": f"Element {i:03d}", | |
| "level": f"Level {(i % 3) + 1:02d}", | |
| "material": ["Concrete", "Steel", "Wood"][i % 3], | |
| "area": round(10.5 + (i * 2.3), 2), | |
| "volume": round((10.5 + (i * 2.3)) * 0.25, 3), | |
| "properties": { | |
| "load_bearing": i % 2 == 0, | |
| "fire_rating": "A1" if i % 4 == 0 else "B1", | |
| "is_external": i % 5 == 0 | |
| } | |
| } | |
| for i in range(min(elements_count, 50)) # Limit for demo | |
| ] | |
| # Convert to JSON | |
| json_content = json.dumps(export_data, indent=2, default=str) | |
| result.file_content = json_content.encode('utf-8') | |
| result.file_size = len(result.file_content) | |
| result.mime_type = "application/json" | |
| async def _export_csv(self, result: ExportResult, request: ExportRequest, query_data: Dict[str, Any]): | |
| """Export to CSV format""" | |
| csv_buffer = io.StringIO() | |
| writer = csv.writer(csv_buffer) | |
| # Write headers | |
| headers = ["element_id", "element_type", "name", "level", "material", "area_m2", "volume_m3", "load_bearing"] | |
| writer.writerow(headers) | |
| # Write data rows | |
| elements_count = query_data.get("details", {}).get("elements_counted", 0) | |
| element_type = self._get_element_type_from_query(query_data) | |
| for i in range(min(elements_count, 50)): # Limit for demo | |
| row = [ | |
| f"el_{query_data.get('project_id', 'prj')}_{i}", | |
| element_type, | |
| f"Element {i:03d}", | |
| f"Level {(i % 3) + 1:02d}", | |
| ["Concrete", "Steel", "Wood"][i % 3], | |
| round(10.5 + (i * 2.3), 2), | |
| round((10.5 + (i * 2.3)) * 0.25, 3), | |
| i % 2 == 0 | |
| ] | |
| writer.writerow(row) | |
| # Convert to bytes | |
| csv_content = csv_buffer.getvalue() | |
| result.file_content = csv_content.encode('utf-8') | |
| result.file_size = len(result.file_content) | |
| result.mime_type = "text/csv" | |
| def _get_element_type_from_query(self, query_data: Dict[str, Any]) -> str: | |
| """Extract element type from query data""" | |
| result = query_data.get("result", "").lower() | |
| if "window" in result: | |
| return "Window" | |
| elif "wall" in result: | |
| return "Wall" | |
| elif "door" in result: | |
| return "Door" | |
| elif "beam" in result: | |
| return "Beam" | |
| elif "column" in result: | |
| return "Column" | |
| else: | |
| return "Element" | |
| # Global export service instance | |
| export_service = ExportService() |