Spaces:
Runtime error
Runtime error
BIM Query Deploy
Claude Opus 4.7 (1M context)
deploy: initial BIM Query API on Hugging Face Spaces
e6be672 Download app/main.py from 12mhsssss/bimquery-api: direct link, hf CLI and curl.
- Browser
- Download file 10.2 kB
-
https://huggingface.co/spaces/12mhsssss/bimquery-api/resolve/main/app/main.py
- Command line
-
hf download hf://spaces/12mhsssss/bimquery-api/app/main.py
-
curl -L -o main.py https://huggingface.co/spaces/12mhsssss/bimquery-api/resolve/main/app/main.py
10.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/>. | |
| """ | |
| BIM Query - Main FastAPI application | |
| This is the main application that handles all API requests for the BIM platform. | |
| It provides endpoints for IFC file upload, natural language queries, geometric calculations, | |
| and data export. | |
| """ | |
| import os | |
| import logging | |
| from contextlib import asynccontextmanager | |
| from datetime import datetime | |
| from fastapi import FastAPI, Request, Response | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.middleware.gzip import GZipMiddleware | |
| from fastapi.responses import JSONResponse | |
| # OpenTelemetry imports (optional for distributed telemetry) | |
| # Enables monitoring and tracing of requests across microservices | |
| try: | |
| from opentelemetry import trace, metrics | |
| from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor | |
| from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor | |
| from opentelemetry.instrumentation.redis import RedisInstrumentor | |
| OTEL_AVAILABLE = True | |
| except ImportError: | |
| # If OpenTelemetry is not available, the app still works without telemetry | |
| OTEL_AVAILABLE = False | |
| trace = None | |
| metrics = None | |
| from app.core.config import get_settings | |
| from app.core.database import init_db, close_db | |
| from app.core.redis import init_redis, close_redis | |
| from app.core.s3 import init_s3 | |
| from app.core.openai_pool import openai_warm_pool | |
| from app.api.v1.router import api_router | |
| from app.core.middleware import ( | |
| RequestIDMiddleware, | |
| AuthenticationMiddleware, | |
| RateLimitMiddleware, | |
| IdempotencyMiddleware, | |
| LoggingMiddleware | |
| ) | |
| from app.core.exceptions import BIMAPIException, bim_exception_handler | |
| # Logging system configuration | |
| # Uses both console and file for logs, with graceful fallback if the file is not accessible | |
| handlers = [logging.StreamHandler()] | |
| try: | |
| # Try to create a file log handler with UTF-8 encoding | |
| handlers.append(logging.FileHandler('logs/app.log', encoding='utf-8')) | |
| except Exception: | |
| # If the file handler is not available (e.g. logs directory does not exist), continue with console only | |
| pass | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', | |
| handlers=handlers | |
| ) | |
| logger = logging.getLogger(__name__) | |
| settings = get_settings() | |
| # OpenTelemetry setup (optional) | |
| if OTEL_AVAILABLE: | |
| tracer = trace.get_tracer(__name__) | |
| meter = metrics.get_meter(__name__) | |
| else: | |
| tracer = None | |
| meter = None | |
| async def lifespan(app: FastAPI): | |
| """Application lifecycle manager | |
| This function handles the initialization and cleanup of resources | |
| during startup and shutdown of the FastAPI application. | |
| """ | |
| logger.info("Starting BIM Query...") | |
| # Validate critical security configuration | |
| _INSECURE_DEFAULTS = {"bim_change_me_in_production", "dev-secret-key-change-in-production"} | |
| if settings.APP_ENV == "prod": | |
| missing = [] | |
| if not settings.API_KEY or settings.API_KEY in _INSECURE_DEFAULTS: | |
| missing.append("API_KEY") | |
| if not settings.SECRET_KEY or settings.SECRET_KEY in _INSECURE_DEFAULTS: | |
| missing.append("SECRET_KEY") | |
| if not settings.POSTGRES_PASSWORD: | |
| missing.append("POSTGRES_PASSWORD") | |
| if not settings.S3_ACCESS_KEY or not settings.S3_SECRET_KEY: | |
| missing.append("S3_ACCESS_KEY / S3_SECRET_KEY") | |
| if not settings.CORS_ORIGINS: | |
| missing.append("CORS_ORIGINS") | |
| if missing: | |
| raise RuntimeError( | |
| f"Refusing to start in production: missing or insecure settings: {', '.join(missing)}. " | |
| "Configure these in your .env file." | |
| ) | |
| elif not settings.API_KEY or settings.API_KEY in _INSECURE_DEFAULTS: | |
| logger.warning( | |
| "API_KEY is not configured or still set to default. " | |
| "Set a strong API_KEY in your .env file for production use." | |
| ) | |
| # Initialize core services in the correct order | |
| # 1. PostgreSQL database with pgvector for vector searches | |
| await init_db() | |
| # 2. Redis for cache, rate limiting, and message broker | |
| await init_redis() | |
| # 3. S3/MinIO for IFC file storage | |
| init_s3() | |
| # 4. OpenAI Warm Pool to eliminate cold-start latency | |
| await openai_warm_pool.start() | |
| # OpenTelemetry instrumentation for distributed telemetry (optional) | |
| if OTEL_AVAILABLE: | |
| # Instrument SQLAlchemy to trace SQL queries | |
| SQLAlchemyInstrumentor().instrument() | |
| # Instrument Redis to trace cache operations | |
| RedisInstrumentor().instrument() | |
| logger.info("BIM Query started successfully") | |
| yield # The application is now running | |
| # Resource cleanup during shutdown | |
| logger.info("Shutting down BIM Query...") | |
| # Stop the OpenAI warm pool | |
| await openai_warm_pool.stop() | |
| # Close database connections gracefully | |
| await close_db() | |
| # Close Redis connections | |
| await close_redis() | |
| logger.info("BIM Query shutdown completed") | |
| # Create the FastAPI instance with enterprise configuration | |
| app = FastAPI( | |
| title="BIM Query", | |
| description="Enterprise platform for BIM data processing and querying", | |
| version="1.0.0", | |
| # Swagger/OpenAPI docs available only in development for security | |
| docs_url="/docs" if settings.APP_ENV != "prod" else None, | |
| redoc_url="/redoc" if settings.APP_ENV != "prod" else None, | |
| lifespan=lifespan, | |
| servers=[ | |
| { | |
| "url": f"{settings.API_BASE_PATH}", | |
| "description": "BIM Query" | |
| } | |
| ], | |
| ) | |
| # FastAPI instrumentation with OpenTelemetry (optional) | |
| if OTEL_AVAILABLE: | |
| FastAPIInstrumentor.instrument_app(app) | |
| # Middleware Stack (order is CRITICAL for correct operation!) | |
| # 1. GZip compression to reduce response size (applied last) | |
| app.add_middleware(GZipMiddleware, minimum_size=1000) | |
| # 2. Request ID for distributed request tracking | |
| app.add_middleware(RequestIDMiddleware) | |
| # 3. Structured logging of all requests and responses | |
| app.add_middleware(LoggingMiddleware) | |
| # 4. Idempotency key handling to prevent duplicate operations | |
| app.add_middleware(IdempotencyMiddleware) | |
| # 5. Rate limiting to protect from abuse (API key-based) | |
| app.add_middleware(RateLimitMiddleware) | |
| # 6. API key authentication (applied first) | |
| app.add_middleware(AuthenticationMiddleware) | |
| # CORS (Cross-Origin Resource Sharing) configuration | |
| # Differentiated policies for development vs production environments | |
| if settings.APP_ENV == "dev": | |
| logger.warning("CORS: wildcard origins enabled (dev mode)") | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| else: | |
| # Production/staging: restrictive CORS - empty origins = deny all cross-origin | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=settings.CORS_ORIGINS, | |
| allow_credentials=True, | |
| allow_methods=["GET", "POST", "HEAD", "OPTIONS"], | |
| allow_headers=[ | |
| "X-Api-Key", | |
| "X-Request-Id", | |
| "X-Idempotency-Key", | |
| "Content-Type", | |
| "Authorization" | |
| ], | |
| ) | |
| # Exception handlers | |
| app.add_exception_handler(BIMAPIException, bim_exception_handler) | |
| # Health check endpoint (outside of versioned APIs) | |
| async def health_check(): | |
| """Application health check endpoint | |
| Used by load balancers and monitoring systems to verify | |
| that the application is operational and ready to receive traffic. | |
| """ | |
| return { | |
| "status": "ok", | |
| "service": "bim-query", | |
| "version": "1.0.0" | |
| } | |
| # Include API router | |
| app.include_router(api_router, prefix=settings.API_BASE_PATH) | |
| # Root endpoint | |
| async def root(): | |
| """Root endpoint with service information""" | |
| return { | |
| "service": "BIM Query", | |
| "version": "1.0.0", | |
| "docs": f"{settings.API_BASE_PATH}/docs" if settings.APP_ENV != "prod" else None, | |
| "health": "/health" | |
| } | |
| # Development-only debug endpoints (double-guarded against accidental prod exposure) | |
| if settings.APP_ENV == "dev": | |
| async def debug_config(): | |
| """Debug endpoint for configuration (dev only)""" | |
| if settings.APP_ENV not in ("dev", "test"): | |
| return JSONResponse(status_code=404, content={"error": "Not found"}) | |
| import re | |
| safe_redis = re.sub(r'://[^@]*@', '://***:***@', settings.REDIS_URL) | |
| return { | |
| "app_env": settings.APP_ENV, | |
| "api_base_path": settings.API_BASE_PATH, | |
| "postgres_host": settings.POSTGRES_HOST, | |
| "redis_url": safe_redis, | |
| "s3_endpoint": settings.S3_ENDPOINT, | |
| } | |
| async def debug_trace(request: Request): | |
| """Debug endpoint for tracing (dev only)""" | |
| if settings.APP_ENV not in ("dev", "test"): | |
| return JSONResponse(status_code=404, content={"error": "Not found"}) | |
| with tracer.start_as_current_span("debug_trace") as span: | |
| span.set_attribute("request.method", request.method) | |
| span.set_attribute("request.url", str(request.url)) | |
| return {"message": "Trace created", "trace_id": format(span.get_span_context().trace_id, 'x')} | |
| if __name__ == "__main__": | |
| import uvicorn | |
| uvicorn.run( | |
| "app.main:app", | |
| host=settings.API_HOST, | |
| port=settings.API_PORT, | |
| reload=settings.APP_ENV == "dev", | |
| log_level="info" if settings.APP_ENV == "dev" else "warning" | |
| ) |